cuenv-1password 0.40.6

1Password integration for the cuenv ecosystem
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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
//! 1Password secret resolver with auto-negotiating dual-mode (HTTP via WASM SDK + CLI)

// Complex WASM+CLI dual-mode resolver with mutex-based shared core management
#![allow(
    clippy::cognitive_complexity,
    clippy::too_many_lines,
    clippy::significant_drop_tightening
)]

use super::core::SharedCore;
use super::wasm;
use async_trait::async_trait;
use cuenv_secrets::{SecretError, SecretResolver, SecretSpec, SecureSecret};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tokio::{process::Command, sync::Mutex};

/// Configuration for 1Password secret resolution
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct OnePasswordConfig {
    /// Secret reference (e.g., `op://vault/item/field`)
    #[serde(rename = "ref")]
    pub reference: String,
}

impl OnePasswordConfig {
    /// Create a new 1Password secret config
    #[must_use]
    pub fn new(reference: impl Into<String>) -> Self {
        Self {
            reference: reference.into(),
        }
    }
}

/// Resolves secrets from 1Password
///
/// Mode is auto-negotiated based on environment:
/// - If `OP_SERVICE_ACCOUNT_TOKEN` is set AND WASM SDK is installed → HTTP mode
/// - Otherwise → CLI mode (uses `op` CLI)
///
/// To enable HTTP mode, run: `cuenv secrets setup onepassword`
///
/// The `source` field in [`SecretSpec`] can be:
/// - A JSON-encoded [`OnePasswordConfig`]
/// - A simple reference string (e.g., `op://vault/item/field`)
pub struct OnePasswordResolver {
    /// Client ID for WASM SDK (when using HTTP mode)
    client_id: Option<u64>,
    /// One-time CLI auth preflight state for `op whoami` in CLI mode.
    cli_auth_state: Mutex<CliAuthState>,
}

#[derive(Debug, Clone)]
enum CliAuthState {
    Unknown,
    Authenticated,
    Failed(String),
}

impl std::fmt::Debug for OnePasswordResolver {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OnePasswordResolver")
            .field("mode", &if self.can_use_http() { "http" } else { "cli" })
            .finish()
    }
}

impl OnePasswordResolver {
    /// Create a new 1Password resolver with auto-detected mode
    ///
    /// If 1Password service account token is available AND the WASM SDK is installed,
    /// uses HTTP mode. Otherwise, CLI mode will be used.
    ///
    /// # Errors
    ///
    /// Returns an error if HTTP mode is detected (WASM + token) but WASM initialization fails.
    /// This prevents silent fallback to CLI mode which masks configuration errors.
    pub fn new() -> Result<Self, SecretError> {
        let client_id = if Self::http_mode_available() {
            // HTTP mode is available (WASM + token), WASM MUST initialize successfully
            // Do NOT silently fall back to CLI - that masks the real error
            let id = Self::init_wasm_client().map_err(|e| SecretError::ResolutionFailed {
                name: "onepassword".to_string(),
                message: format!(
                    "1Password HTTP mode detected (WASM + token) but initialization failed: {e}\n\
                    \n\
                    This indicates a platform/runtime compatibility issue.\n\
                    To use CLI mode instead, unset OP_SERVICE_ACCOUNT_TOKEN or remove the WASM file."
                ),
            })?;
            tracing::debug!("1Password WASM client initialized successfully");
            Some(id)
        } else {
            tracing::debug!("1Password HTTP mode not available, using CLI");
            None
        };

        Ok(Self {
            client_id,
            cli_auth_state: Mutex::new(CliAuthState::Unknown),
        })
    }

    /// Check if HTTP mode is available (token set + WASM installed)
    fn http_mode_available() -> bool {
        let token_set = std::env::var("OP_SERVICE_ACCOUNT_TOKEN").is_ok();
        let wasm_available = wasm::onepassword_wasm_available();
        tracing::trace!(
            token_set,
            wasm_available,
            "1Password HTTP mode availability check"
        );
        token_set && wasm_available
    }

    /// Initialize the WASM client and return the client ID
    fn init_wasm_client() -> Result<u64, SecretError> {
        let token = std::env::var("OP_SERVICE_ACCOUNT_TOKEN").map_err(|_| {
            SecretError::ResolutionFailed {
                name: "onepassword".to_string(),
                message: "OP_SERVICE_ACCOUNT_TOKEN not set".to_string(),
            }
        })?;

        let core_mutex = SharedCore::get_or_init()?;
        let mut guard = core_mutex
            .lock()
            .map_err(|_| SecretError::ResolutionFailed {
                name: "onepassword".to_string(),
                message: "Failed to acquire shared core lock".to_string(),
            })?;

        let core = guard
            .as_mut()
            .ok_or_else(|| SecretError::ResolutionFailed {
                name: "onepassword".to_string(),
                message: "SharedCore not initialized".to_string(),
            })?;

        core.init_client(&token)
    }

    /// Check if this resolver can use HTTP mode
    const fn can_use_http(&self) -> bool {
        self.client_id.is_some()
    }

    /// Resolve using the 1Password WASM SDK (HTTP mode)
    fn resolve_http(&self, name: &str, config: &OnePasswordConfig) -> Result<String, SecretError> {
        let client_id = self
            .client_id
            .ok_or_else(|| SecretError::ResolutionFailed {
                name: name.to_string(),
                message: "HTTP client not initialized".to_string(),
            })?;

        let core_mutex = SharedCore::get_or_init()?;
        let mut guard = core_mutex
            .lock()
            .map_err(|_| SecretError::ResolutionFailed {
                name: name.to_string(),
                message: "Failed to acquire shared core lock".to_string(),
            })?;

        let core = guard
            .as_mut()
            .ok_or_else(|| SecretError::ResolutionFailed {
                name: name.to_string(),
                message: "SharedCore not initialized".to_string(),
            })?;

        // Invoke the SecretsResolve method (Go SDK uses this name, not "Secrets.Resolve")
        let mut params = serde_json::Map::new();
        params.insert(
            "secret_reference".to_string(),
            serde_json::Value::String(config.reference.clone()),
        );

        let result = core.invoke(client_id, "SecretsResolve", &params, &config.reference)?;

        // Parse the response - the Go SDK returns a JSON-encoded string
        // The invoke response is the raw string from WASM, which is a JSON-quoted secret value
        let secret: String =
            serde_json::from_str(&result).map_err(|e| SecretError::ResolutionFailed {
                name: name.to_string(),
                message: format!("Failed to parse resolve response: {e}"),
            })?;

        Ok(secret)
    }

    /// Resolve using the op CLI
    async fn resolve_cli(
        &self,
        name: &str,
        config: &OnePasswordConfig,
    ) -> Result<String, SecretError> {
        tracing::debug!(
            name = name,
            reference = config.reference,
            "1Password resolve_cli"
        );
        let output = Command::new("op")
            .args(["read", &config.reference])
            .output()
            .await
            .map_err(|e| SecretError::ResolutionFailed {
                name: name.to_string(),
                message: format!("Failed to execute op CLI: {e}"),
            })?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(SecretError::ResolutionFailed {
                name: name.to_string(),
                message: format!("op CLI failed: {stderr}"),
            });
        }

        Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
    }

    /// Ensure CLI auth is valid once per resolver instance.
    ///
    /// Returns `Some(secret_value)` when auth bootstrap consumed the current
    /// secret read, allowing caller to skip a second `op read` call.
    async fn ensure_cli_authenticated(
        &self,
        name: &str,
        config: &OnePasswordConfig,
    ) -> Result<Option<String>, SecretError> {
        let mut state = self.cli_auth_state.lock().await;
        match &*state {
            CliAuthState::Authenticated => return Ok(None),
            CliAuthState::Failed(message) => {
                return Err(SecretError::ResolutionFailed {
                    name: name.to_string(),
                    message: message.clone(),
                });
            }
            CliAuthState::Unknown => {}
        }

        let preflight_result = Command::new("op").arg("whoami").output().await;

        match preflight_result {
            Ok(output) if output.status.success() => {
                *state = CliAuthState::Authenticated;
                Ok(None)
            }
            Ok(output) => {
                let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
                let details = if stderr.is_empty() {
                    "no error output from 1Password CLI".to_string()
                } else {
                    stderr
                };

                // Interactive local workflows may be signed out before the first read.
                // In this case, allow one bootstrap read to trigger signin once,
                // then keep all remaining reads parallel.
                if details.to_lowercase().contains("not signed in") {
                    let read_result = Command::new("op")
                        .args(["read", &config.reference])
                        .output()
                        .await;

                    match read_result {
                        Ok(read_output) if read_output.status.success() => {
                            *state = CliAuthState::Authenticated;
                            let secret = String::from_utf8_lossy(&read_output.stdout)
                                .trim()
                                .to_string();
                            return Ok(Some(secret));
                        }
                        Ok(read_output) => {
                            let read_stderr = String::from_utf8_lossy(&read_output.stderr)
                                .trim()
                                .to_string();
                            let read_details = if read_stderr.is_empty() {
                                "no error output from 1Password CLI".to_string()
                            } else {
                                read_stderr
                            };
                            let message = format!(
                                "1Password CLI authentication check failed (`op whoami`) and \
                                bootstrap secret read failed. Run `op signin` and retry. \
                                Details: {read_details}"
                            );
                            *state = CliAuthState::Failed(message.clone());
                            return Err(SecretError::ResolutionFailed {
                                name: name.to_string(),
                                message,
                            });
                        }
                        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                            let message = "1Password CLI not found (`op` command unavailable). \
                                Install the 1Password CLI and retry."
                                .to_string();
                            *state = CliAuthState::Failed(message.clone());
                            return Err(SecretError::ResolutionFailed {
                                name: name.to_string(),
                                message,
                            });
                        }
                        Err(e) => {
                            let message = format!(
                                "Failed to execute 1Password bootstrap secret read (`op read`): {e}. \
                                Run `op signin` and retry."
                            );
                            *state = CliAuthState::Failed(message.clone());
                            return Err(SecretError::ResolutionFailed {
                                name: name.to_string(),
                                message,
                            });
                        }
                    }
                }

                let message = format!(
                    "1Password CLI authentication check failed (`op whoami`). \
                    Run `op signin` and retry. Details: {details}"
                );
                *state = CliAuthState::Failed(message.clone());
                Err(SecretError::ResolutionFailed {
                    name: name.to_string(),
                    message,
                })
            }
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                let message = "1Password CLI not found (`op` command unavailable). \
                    Install the 1Password CLI and retry."
                    .to_string();
                *state = CliAuthState::Failed(message.clone());
                Err(SecretError::ResolutionFailed {
                    name: name.to_string(),
                    message,
                })
            }
            Err(e) => {
                let message = format!(
                    "Failed to execute 1Password CLI authentication check (`op whoami`): {e}. \
                    Run `op signin` and retry."
                );
                *state = CliAuthState::Failed(message.clone());
                Err(SecretError::ResolutionFailed {
                    name: name.to_string(),
                    message,
                })
            }
        }
    }

    /// Resolve a secret - tries HTTP first if available, falls back to CLI
    async fn resolve_with_config(
        &self,
        name: &str,
        config: &OnePasswordConfig,
    ) -> Result<String, SecretError> {
        // Try HTTP mode if available
        if self.client_id.is_some() {
            return self.resolve_http(name, config);
        }

        // Fallback to CLI
        if let Some(secret) = self.ensure_cli_authenticated(name, config).await? {
            return Ok(secret);
        }
        self.resolve_cli(name, config).await
    }

    /// Resolve multiple secrets using Secrets.ResolveAll (HTTP mode)
    fn resolve_batch_http(
        &self,
        secrets: &HashMap<String, SecretSpec>,
    ) -> Result<HashMap<String, SecureSecret>, SecretError> {
        let client_id = self
            .client_id
            .ok_or_else(|| SecretError::ResolutionFailed {
                name: "batch".to_string(),
                message: "HTTP client not initialized".to_string(),
            })?;

        let core_mutex = SharedCore::get_or_init()?;
        let mut guard = core_mutex
            .lock()
            .map_err(|_| SecretError::ResolutionFailed {
                name: "batch".to_string(),
                message: "Failed to acquire shared core lock".to_string(),
            })?;

        let core = guard
            .as_mut()
            .ok_or_else(|| SecretError::ResolutionFailed {
                name: "batch".to_string(),
                message: "SharedCore not initialized".to_string(),
            })?;

        // Build list of references and track mapping back to names
        let mut ref_to_names: HashMap<String, Vec<String>> = HashMap::new();
        let mut references: Vec<String> = Vec::new();

        for (name, spec) in secrets {
            let config = serde_json::from_str::<OnePasswordConfig>(&spec.source)
                .unwrap_or_else(|_| OnePasswordConfig::new(spec.source.clone()));

            ref_to_names
                .entry(config.reference.clone())
                .or_default()
                .push(name.clone());

            if !references.contains(&config.reference) {
                references.push(config.reference);
            }
        }

        // Invoke SecretsResolveAll with array of references
        let mut params = serde_json::Map::new();
        params.insert(
            "secret_references".to_string(),
            serde_json::Value::Array(
                references
                    .iter()
                    .map(|r| serde_json::Value::String(r.clone()))
                    .collect(),
            ),
        );

        // Use first reference as context for top-level errors
        let context = references.first().map_or("batch", String::as_str);
        let result = core.invoke(client_id, "SecretsResolveAll", &params, context)?;

        // Parse the response
        let response: serde_json::Value =
            serde_json::from_str(&result).map_err(|e| SecretError::ResolutionFailed {
                name: "batch".to_string(),
                message: format!("Failed to parse ResolveAll response: {e}"),
            })?;

        // Extract individual responses
        let individual_responses = response["individualResponses"].as_array().ok_or_else(|| {
            SecretError::ResolutionFailed {
                name: "batch".to_string(),
                message: "No individualResponses in response".to_string(),
            }
        })?;

        // Map responses back to original names
        let mut resolved: HashMap<String, SecureSecret> = HashMap::new();

        for (i, resp) in individual_responses.iter().enumerate() {
            let reference = references
                .get(i)
                .ok_or_else(|| SecretError::ResolutionFailed {
                    name: "batch".to_string(),
                    message: "Response index out of bounds".to_string(),
                })?;

            // Check for errors - fail immediately with the specific secret reference
            if let Some(error) = resp.get("error")
                && !error.is_null()
            {
                let error_type = error["type"].as_str().unwrap_or("Unknown");
                let error_msg = error["message"].as_str().unwrap_or("Unknown error");
                return Err(SecretError::ResolutionFailed {
                    name: reference.clone(),
                    message: format!("1Password error ({error_type}): {error_msg}"),
                });
            }

            // Extract secret value
            let secret = resp["content"]["secret"]
                .as_str()
                .or_else(|| resp["result"].as_str())
                .ok_or_else(|| SecretError::ResolutionFailed {
                    name: reference.clone(),
                    message: "No secret value in response".to_string(),
                })?;

            // Map to all names that use this reference
            if let Some(names) = ref_to_names.get(reference) {
                for name in names {
                    resolved.insert(name.clone(), SecureSecret::new(secret.to_string()));
                }
            }
        }

        Ok(resolved)
    }

    /// Resolve multiple secrets using CLI (fallback, concurrent)
    async fn resolve_batch_cli(
        &self,
        secrets: &HashMap<String, SecretSpec>,
    ) -> Result<HashMap<String, SecureSecret>, SecretError> {
        use futures::future::try_join_all;

        let futures: Vec<_> = secrets
            .iter()
            .map(|(name, spec)| {
                let name = name.clone();
                let spec = spec.clone();
                async move {
                    let value = self.resolve(&name, &spec).await?;
                    Ok::<_, SecretError>((name, SecureSecret::new(value)))
                }
            })
            .collect();

        try_join_all(futures).await.map(|v| v.into_iter().collect())
    }
}

impl Drop for OnePasswordResolver {
    fn drop(&mut self) {
        if let Some(client_id) = self.client_id
            && let Ok(core_mutex) = SharedCore::get_or_init()
            && let Ok(mut guard) = core_mutex.lock()
            && let Some(core) = guard.as_mut()
        {
            core.release_client(client_id);
        }
    }
}

#[async_trait]
impl SecretResolver for OnePasswordResolver {
    fn provider_name(&self) -> &'static str {
        "onepassword"
    }

    fn supports_native_batch(&self) -> bool {
        // 1Password SDK supports Secrets.ResolveAll
        true
    }

    async fn resolve(&self, name: &str, spec: &SecretSpec) -> Result<String, SecretError> {
        // Try to parse source as JSON OnePasswordConfig
        if let Ok(config) = serde_json::from_str::<OnePasswordConfig>(&spec.source) {
            return self.resolve_with_config(name, &config).await;
        }

        // Fallback: treat source as a simple reference string
        let config = OnePasswordConfig::new(spec.source.clone());
        self.resolve_with_config(name, &config).await
    }

    async fn resolve_batch(
        &self,
        secrets: &HashMap<String, SecretSpec>,
    ) -> Result<HashMap<String, SecureSecret>, SecretError> {
        if secrets.is_empty() {
            return Ok(HashMap::new());
        }

        // Use Secrets.ResolveAll if HTTP mode is available
        if self.client_id.is_some() {
            return self.resolve_batch_http(secrets);
        }

        // Fallback to concurrent CLI calls
        self.resolve_batch_cli(secrets).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(unix)]
    use std::os::unix::fs::PermissionsExt;
    #[cfg(unix)]
    use std::{fs, path::Path};

    #[cfg(unix)]
    fn write_fake_op_shim(dir: &Path) -> std::path::PathBuf {
        let op_path = dir.join("op");
        let script = r#"#!/bin/sh
cmd="$1"
shift

case "$cmd" in
  whoami)
    printf "whoami\n" >> "$OP_TEST_LOG"
    if [ "x$OP_TEST_FAIL_WHOAMI" = "x1" ]; then
      printf "not signed in\n" >&2
      exit 1
    fi
    printf "test-user@example.com\n"
    exit 0
    ;;
  read)
    printf "read:%s\n" "$1" >> "$OP_TEST_LOG"
    if [ "x$OP_TEST_FAIL_READ" = "x1" ]; then
      printf "read failed\n" >&2
      exit 1
    fi
    printf "secret-for-%s\n" "$1"
    exit 0
    ;;
  *)
    printf "unsupported op command: %s\n" "$cmd" >&2
    exit 2
    ;;
esac
"#;

        fs::write(&op_path, script).unwrap();
        let mut perms = fs::metadata(&op_path).unwrap().permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&op_path, perms).unwrap();
        op_path
    }

    #[cfg(unix)]
    fn prepend_path(dir: &Path) -> String {
        let mut parts = vec![dir.to_path_buf()];
        if let Some(current) = std::env::var_os("PATH") {
            parts.extend(std::env::split_paths(&current));
        }
        std::env::join_paths(parts)
            .unwrap()
            .to_string_lossy()
            .into_owned()
    }

    #[cfg(unix)]
    fn read_log_lines(path: &Path) -> Vec<String> {
        let content = fs::read_to_string(path).unwrap_or_default();
        content
            .lines()
            .map(str::trim)
            .filter(|line| !line.is_empty())
            .map(str::to_string)
            .collect()
    }

    #[test]
    fn test_onepassword_config_serialization() {
        let config = OnePasswordConfig {
            reference: "op://vault/item/password".to_string(),
        };

        let json = serde_json::to_string(&config).unwrap();
        assert!(json.contains("\"ref\""));

        let parsed: OnePasswordConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(config, parsed);
    }

    #[test]
    fn test_simple_config() {
        let config = OnePasswordConfig::new("op://Personal/GitHub/token");
        assert_eq!(config.reference, "op://Personal/GitHub/token");
    }

    #[test]
    fn test_config_new_from_string() {
        let config = OnePasswordConfig::new(String::from("op://vault/item/field"));
        assert_eq!(config.reference, "op://vault/item/field");
    }

    #[test]
    fn test_config_new_from_str_slice() {
        let ref_str = "op://vault/item/field";
        let config = OnePasswordConfig::new(ref_str);
        assert_eq!(config.reference, ref_str);
    }

    #[test]
    fn test_config_equality() {
        let config1 = OnePasswordConfig::new("op://vault/item/field");
        let config2 = OnePasswordConfig::new("op://vault/item/field");
        let config3 = OnePasswordConfig::new("op://other/item/field");

        assert_eq!(config1, config2);
        assert_ne!(config1, config3);
    }

    #[test]
    fn test_config_clone() {
        let config = OnePasswordConfig::new("op://vault/item/field");
        let cloned = config.clone();
        assert_eq!(config, cloned);
    }

    #[test]
    fn test_config_debug() {
        let config = OnePasswordConfig::new("op://vault/item/field");
        let debug = format!("{config:?}");
        assert!(debug.contains("OnePasswordConfig"));
        assert!(debug.contains("op://vault/item/field"));
    }

    #[test]
    fn test_config_deserialization_with_ref_key() {
        let json = r#"{"ref": "op://vault/item/field"}"#;
        let config: OnePasswordConfig = serde_json::from_str(json).unwrap();
        assert_eq!(config.reference, "op://vault/item/field");
    }

    #[test]
    fn test_config_deserialization_camel_case() {
        // Since serde uses camelCase, the field is "ref"
        let json = r#"{"ref": "op://example/test/password"}"#;
        let config: OnePasswordConfig = serde_json::from_str(json).unwrap();
        assert_eq!(config.reference, "op://example/test/password");
    }

    #[test]
    fn test_config_deserialization_missing_ref() {
        let json = r"{}";
        let result = serde_json::from_str::<OnePasswordConfig>(json);
        assert!(result.is_err());
    }

    #[test]
    fn test_config_with_special_characters() {
        let config = OnePasswordConfig::new("op://My Vault/My Item 2024/api-key_v1");
        assert!(config.reference.contains("My Vault"));
        assert!(config.reference.contains("api-key_v1"));
    }

    #[test]
    fn test_http_mode_available_without_env() {
        // Without OP_SERVICE_ACCOUNT_TOKEN, HTTP mode should not be available
        // (unless already set in environment)
        let result = OnePasswordResolver::http_mode_available();
        // Just verify it returns a boolean without panicking
        let _ = result;
    }

    #[test]
    fn test_resolver_provider_name() {
        // Create a resolver in CLI mode (without WASM)
        // If WASM is not available and token is not set, this should work
        if (!wasm::onepassword_wasm_available()
            || std::env::var("OP_SERVICE_ACCOUNT_TOKEN").is_err())
            && let Ok(resolver) = OnePasswordResolver::new()
        {
            assert_eq!(resolver.provider_name(), "onepassword");
        }
    }

    #[test]
    fn test_resolver_supports_native_batch() {
        if (!wasm::onepassword_wasm_available()
            || std::env::var("OP_SERVICE_ACCOUNT_TOKEN").is_err())
            && let Ok(resolver) = OnePasswordResolver::new()
        {
            assert!(resolver.supports_native_batch());
        }
    }

    #[test]
    fn test_resolver_can_use_http_false_without_client() {
        // A resolver without client_id should return false for can_use_http
        if (!wasm::onepassword_wasm_available()
            || std::env::var("OP_SERVICE_ACCOUNT_TOKEN").is_err())
            && let Ok(resolver) = OnePasswordResolver::new()
        {
            assert!(!resolver.can_use_http());
        }
    }

    #[test]
    fn test_resolver_debug_output() {
        if (!wasm::onepassword_wasm_available()
            || std::env::var("OP_SERVICE_ACCOUNT_TOKEN").is_err())
            && let Ok(resolver) = OnePasswordResolver::new()
        {
            let debug = format!("{resolver:?}");
            assert!(debug.contains("OnePasswordResolver"));
            // Should show mode as cli when no WASM client
            assert!(debug.contains("cli") || debug.contains("http"));
        }
    }

    #[tokio::test]
    async fn test_resolve_batch_empty() {
        if (!wasm::onepassword_wasm_available()
            || std::env::var("OP_SERVICE_ACCOUNT_TOKEN").is_err())
            && let Ok(resolver) = OnePasswordResolver::new()
        {
            let empty: HashMap<String, SecretSpec> = HashMap::new();
            let result = resolver.resolve_batch(&empty).await;
            assert!(result.is_ok());
            assert!(result.unwrap().is_empty());
        }
    }

    #[test]
    fn test_config_roundtrip_serialization() {
        let original = OnePasswordConfig::new("op://vault/item/field");
        let json = serde_json::to_string(&original).unwrap();
        let parsed: OnePasswordConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(original, parsed);
    }

    #[test]
    fn test_config_empty_reference() {
        // Empty reference should be allowed at config level
        let config = OnePasswordConfig::new("");
        assert_eq!(config.reference, "");
    }

    #[test]
    fn test_config_unicode_reference() {
        let config = OnePasswordConfig::new("op://vault/项目/密码");
        assert_eq!(config.reference, "op://vault/项目/密码");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn test_cli_preflight_runs_once_for_parallel_batch_reads() {
        let temp = tempfile::tempdir().unwrap();
        write_fake_op_shim(temp.path());
        let log_path = temp.path().join("op.log");
        let path = prepend_path(temp.path());
        let log_path_str = log_path.to_string_lossy().into_owned();

        temp_env::async_with_vars(
            [
                ("PATH", Some(path.as_str())),
                ("OP_TEST_LOG", Some(log_path_str.as_str())),
                ("OP_SERVICE_ACCOUNT_TOKEN", None),
            ],
            async {
                let resolver = OnePasswordResolver::new().unwrap();
                let secrets = HashMap::from([
                    (
                        "API_KEY".to_string(),
                        SecretSpec::new("op://vault/service/api_key"),
                    ),
                    (
                        "DB_PASSWORD".to_string(),
                        SecretSpec::new("op://vault/service/db_password"),
                    ),
                    (
                        "JWT_SECRET".to_string(),
                        SecretSpec::new("op://vault/service/jwt_secret"),
                    ),
                ]);

                let secret_values = resolver.resolve_batch(&secrets).await.unwrap();
                assert_eq!(secret_values.len(), 3);
            },
        )
        .await;

        let lines = read_log_lines(&log_path);
        assert_eq!(
            lines.iter().filter(|line| *line == "whoami").count(),
            1,
            "expected exactly one auth preflight, got log lines: {lines:?}"
        );
        assert_eq!(
            lines
                .iter()
                .filter(|line| line.starts_with("read:"))
                .count(),
            3,
            "expected one read per secret, got log lines: {lines:?}"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn test_cli_preflight_signed_out_bootstraps_then_runs_parallel_reads() {
        let temp = tempfile::tempdir().unwrap();
        write_fake_op_shim(temp.path());
        let log_path = temp.path().join("op.log");
        let path = prepend_path(temp.path());
        let log_path_str = log_path.to_string_lossy().into_owned();

        temp_env::async_with_vars(
            [
                ("PATH", Some(path.as_str())),
                ("OP_TEST_LOG", Some(log_path_str.as_str())),
                ("OP_TEST_FAIL_WHOAMI", Some("1")),
                ("OP_SERVICE_ACCOUNT_TOKEN", None),
            ],
            async {
                let resolver = OnePasswordResolver::new().unwrap();
                let secrets = HashMap::from([
                    ("A".to_string(), SecretSpec::new("op://vault/item/a")),
                    ("B".to_string(), SecretSpec::new("op://vault/item/b")),
                ]);

                let result = resolver.resolve_batch(&secrets).await;
                assert!(result.is_ok(), "expected bootstrap read to recover auth");
                assert_eq!(result.unwrap().len(), 2);
            },
        )
        .await;

        let lines = read_log_lines(&log_path);
        assert_eq!(
            lines.iter().filter(|line| *line == "whoami").count(),
            1,
            "expected single preflight attempt, got log lines: {lines:?}"
        );
        assert_eq!(
            lines
                .iter()
                .filter(|line| line.starts_with("read:"))
                .count(),
            2,
            "expected one read per secret after bootstrap auth, got log lines: {lines:?}"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn test_cli_preflight_bootstrap_read_failure_fails_fast() {
        let temp = tempfile::tempdir().unwrap();
        write_fake_op_shim(temp.path());
        let log_path = temp.path().join("op.log");
        let path = prepend_path(temp.path());
        let log_path_str = log_path.to_string_lossy().into_owned();

        temp_env::async_with_vars(
            [
                ("PATH", Some(path.as_str())),
                ("OP_TEST_LOG", Some(log_path_str.as_str())),
                ("OP_TEST_FAIL_WHOAMI", Some("1")),
                ("OP_TEST_FAIL_READ", Some("1")),
                ("OP_SERVICE_ACCOUNT_TOKEN", None),
            ],
            async {
                let resolver = OnePasswordResolver::new().unwrap();
                let secrets = HashMap::from([
                    ("A".to_string(), SecretSpec::new("op://vault/item/a")),
                    ("B".to_string(), SecretSpec::new("op://vault/item/b")),
                ]);

                let result = resolver.resolve_batch(&secrets).await;
                assert!(result.is_err());
                let err = result.unwrap_err().to_string();
                assert!(
                    err.contains("bootstrap secret read"),
                    "unexpected error: {err}"
                );
                assert!(err.contains("op signin"), "unexpected error: {err}");
            },
        )
        .await;

        let lines = read_log_lines(&log_path);
        assert_eq!(
            lines.iter().filter(|line| *line == "whoami").count(),
            1,
            "expected single preflight attempt, got log lines: {lines:?}"
        );
        assert_eq!(
            lines
                .iter()
                .filter(|line| line.starts_with("read:"))
                .count(),
            1,
            "expected a single bootstrap read attempt before fail-fast, got log lines: {lines:?}"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn test_cli_preflight_missing_op_reports_clear_error() {
        let empty_dir = tempfile::tempdir().unwrap();
        let path = empty_dir.path().to_string_lossy().into_owned();

        temp_env::async_with_vars(
            [
                ("PATH", Some(path.as_str())),
                ("OP_SERVICE_ACCOUNT_TOKEN", None),
            ],
            async {
                let resolver = OnePasswordResolver::new().unwrap();
                let spec = SecretSpec::new("op://vault/item/password");

                let result = resolver.resolve("missing-op", &spec).await;
                assert!(result.is_err());
                let err = result.unwrap_err().to_string();
                assert!(err.contains("1Password CLI"), "unexpected error: {err}");
                assert!(err.contains("not found"), "unexpected error: {err}");
            },
        )
        .await;
    }
}