corteq-onepassword 0.1.5

Secure 1Password SDK wrapper with FFI bindings for Rust applications
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
//! 1Password client implementation.
//!
//! This module provides the main `OnePassword` client and its builder.

use crate::error::{Error, Result};
use crate::ffi::{load_library, SdkClient};
use crate::secret::{SecretMap, SecretReference};
use base64::Engine;
use secrecy::SecretString;
use std::sync::Arc;
use tokio::sync::Mutex;

/// Prefix for 1Password service account tokens.
const TOKEN_PREFIX: &str = "ops_";

/// Validate a 1Password service account token format.
///
/// Tokens must:
/// - Start with "ops_" prefix
/// - Contain valid base64 after the prefix
/// - Decode to JSON with required fields (signInAddress, email, deviceUuid)
///
/// This validation ensures early error detection with clear error messages,
/// rather than cryptic SDK errors at connect time.
fn validate_token(token: &str) -> Result<()> {
    // Check prefix
    if !token.starts_with(TOKEN_PREFIX) {
        return Err(Error::InvalidToken);
    }

    let payload = &token[TOKEN_PREFIX.len()..];

    // Decode base64 (1Password uses URL-safe base64 without padding)
    let decoded = base64::engine::general_purpose::URL_SAFE_NO_PAD
        .decode(payload)
        .map_err(|_| Error::InvalidToken)?;

    // Parse JSON and check required fields
    let json: serde_json::Value =
        serde_json::from_slice(&decoded).map_err(|_| Error::InvalidToken)?;

    // Validate required fields exist
    const REQUIRED_FIELDS: &[&str] = &["signInAddress", "email", "deviceUuid"];
    for field in REQUIRED_FIELDS {
        if json.get(*field).is_none() {
            return Err(Error::InvalidToken);
        }
    }

    Ok(())
}

/// Builder for configuring and creating a `OnePassword` client.
///
/// Use [`OnePassword::from_env()`] or [`OnePassword::from_token()`] to create a builder,
/// then configure it and call [`connect()`](OnePasswordBuilder::connect) to establish
/// the connection.
///
/// # Examples
///
/// ```no_run
/// use corteq_onepassword::OnePassword;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     // From environment variable
///     let client = OnePassword::from_env()?
///         .integration("my-app", "1.0.0")
///         .connect()
///         .await?;
///
///     // From explicit token (use env var in production)
///     let token = std::env::var("MY_TOKEN")?;
///     let client = OnePassword::from_token(&token)?
///         .integration("my-app", "1.0.0")
///         .connect()
///         .await?;
///     Ok(())
/// }
/// ```
pub struct OnePasswordBuilder {
    /// The service account token (wrapped for security).
    token: SecretString,

    /// Integration name for 1Password audit logs.
    integration_name: Option<String>,

    /// Integration version for 1Password audit logs.
    integration_version: Option<String>,
}

impl OnePasswordBuilder {
    /// Create a new builder with the given token.
    fn new(token: impl Into<String>) -> Self {
        Self {
            token: SecretString::from(token.into()),
            integration_name: None,
            integration_version: None,
        }
    }

    /// Set the integration name and version for 1Password audit logs.
    ///
    /// This metadata appears in 1Password's audit logs, helping identify
    /// which application is accessing secrets.
    ///
    /// If not set, defaults to `corteq-onepassword` and the crate version.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use corteq_onepassword::OnePassword;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = OnePassword::from_env()?
    ///         .integration("contact-guard", "2.1.0")
    ///         .connect()
    ///         .await?;
    ///     Ok(())
    /// }
    /// ```
    pub fn integration(mut self, name: &str, version: &str) -> Self {
        self.integration_name = Some(name.to_string());
        self.integration_version = Some(version.to_string());
        self
    }

    /// Connect to 1Password and create the client.
    ///
    /// This establishes a session with 1Password using the configured
    /// service account token.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The native library cannot be loaded
    /// - Authentication fails (invalid or expired token)
    /// - Network issues prevent connection
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use corteq_onepassword::OnePassword;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = OnePassword::from_env()?
    ///         .connect()
    ///         .await?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn connect(self) -> Result<OnePassword> {
        let integration_name = self
            .integration_name
            .unwrap_or_else(|| "corteq-onepassword".to_string());
        let integration_version = self
            .integration_version
            .unwrap_or_else(|| env!("CARGO_PKG_VERSION").to_string());

        #[cfg(feature = "tracing")]
        tracing::debug!(
            integration_name = %integration_name,
            integration_version = %integration_version,
            "connecting to 1Password"
        );

        // Load the native library
        let library = load_library()?;

        // Initialize the SDK client
        let client = SdkClient::init(
            library,
            &self.token,
            &integration_name,
            &integration_version,
        )?;

        #[cfg(feature = "tracing")]
        tracing::info!("connected to 1Password");

        Ok(OnePassword {
            client: Arc::new(Mutex::new(client)),
        })
    }

    /// Connect to 1Password synchronously (blocking).
    ///
    /// This is equivalent to `connect()` but blocks the current thread
    /// instead of returning a future.
    ///
    /// # Feature Flag
    ///
    /// This method requires the `blocking` feature to be enabled.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use corteq_onepassword::OnePassword;
    ///
    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = OnePassword::from_env()?
    ///         .connect_blocking()?;
    ///     Ok(())
    /// }
    /// ```
    #[cfg(feature = "blocking")]
    pub fn connect_blocking(self) -> Result<OnePassword> {
        tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .map_err(|e| Error::SdkError {
                message: format!("failed to create runtime: {e}"),
            })?
            .block_on(self.connect())
    }
}

/// 1Password client for retrieving secrets.
///
/// The client is thread-safe and can be shared across tasks via `Arc<OnePassword>`.
/// It does NOT implement `Clone` to prevent accidental session duplication.
///
/// # Thread Safety
///
/// `OnePassword` is `Send + Sync`, allowing it to be used in async contexts
/// and shared between threads.
///
/// # Examples
///
/// ```no_run
/// use std::sync::Arc;
/// use corteq_onepassword::OnePassword;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     // Create and share the client
///     let client = Arc::new(OnePassword::from_env()?.connect().await?);
///
///     // Use in multiple tasks
///     let client1 = Arc::clone(&client);
///     let client2 = Arc::clone(&client);
///
///     let (secret1, secret2) = tokio::join!(
///         client1.secret("op://vault/item/field1"),
///         client2.secret("op://vault/item/field2"),
///     );
///
///     Ok(())
/// }
/// ```
pub struct OnePassword {
    /// The underlying SDK client, protected by a mutex for thread safety.
    client: Arc<Mutex<SdkClient>>,
}

// Explicitly implement Send + Sync
// SAFETY: Access to SdkClient is synchronized via Mutex
unsafe impl Send for OnePassword {}
unsafe impl Sync for OnePassword {}

impl OnePassword {
    /// Create a builder using the `OP_SERVICE_ACCOUNT_TOKEN` environment variable.
    ///
    /// This is the recommended way to create a client in production, as it
    /// avoids hardcoding tokens in source code.
    ///
    /// # Errors
    ///
    /// Returns [`Error::MissingAuthToken`] if the environment variable is not set
    /// or is empty.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use corteq_onepassword::OnePassword;
    ///
    /// // Set OP_SERVICE_ACCOUNT_TOKEN in your environment
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = OnePassword::from_env()?
    ///         .connect()
    ///         .await?;
    ///     Ok(())
    /// }
    /// ```
    #[must_use = "builder must be used to connect"]
    pub fn from_env() -> Result<OnePasswordBuilder> {
        let token =
            std::env::var("OP_SERVICE_ACCOUNT_TOKEN").map_err(|_| Error::MissingAuthToken)?;

        if token.is_empty() {
            return Err(Error::MissingAuthToken);
        }

        // Validate token format before accepting
        validate_token(&token)?;

        Ok(OnePasswordBuilder::new(token))
    }

    /// Create a builder with an explicit service account token.
    ///
    /// Use this method for testing or when the token is provided through
    /// a mechanism other than environment variables.
    ///
    /// # Security Note
    ///
    /// Avoid hardcoding tokens in source code. Prefer [`from_env()`](Self::from_env)
    /// for production use.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidToken`] if the token format is invalid.
    /// Valid tokens start with "ops_" and contain a base64-encoded JSON payload.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use corteq_onepassword::OnePassword;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let token = std::env::var("CUSTOM_TOKEN_VAR")?;
    ///     let client = OnePassword::from_token(&token)?
    ///         .connect()
    ///         .await?;
    ///     Ok(())
    /// }
    /// ```
    #[must_use = "builder must be used to connect"]
    pub fn from_token(token: impl Into<String>) -> Result<OnePasswordBuilder> {
        let token = token.into();

        // Validate token format before accepting
        validate_token(&token)?;

        Ok(OnePasswordBuilder::new(token))
    }

    /// Resolve a single secret by reference.
    ///
    /// # Arguments
    ///
    /// * `reference` - Secret reference in format `op://vault/item/field`
    ///   or `op://vault/item/section/field`
    ///
    /// # Returns
    ///
    /// The secret value wrapped in [`SecretString`] for secure memory handling.
    /// Use [`.expose_secret()`](ExposeSecret::expose_secret) to access the value.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidReference`] - The reference format is invalid
    /// - [`Error::SecretNotFound`] - The secret doesn't exist
    /// - [`Error::AccessDenied`] - No permission to access the vault
    /// - [`Error::NetworkError`] - Connection issues
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use corteq_onepassword::{OnePassword, ExposeSecret};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = OnePassword::from_env()?.connect().await?;
    ///
    ///     let api_key = client.secret("op://prod/stripe/api-key").await?;
    ///     println!("API key length: {}", api_key.expose_secret().len());
    ///     Ok(())
    /// }
    /// ```
    pub async fn secret(&self, reference: &str) -> Result<SecretString> {
        // Validate reference format first
        SecretReference::parse(reference)?;

        #[cfg(feature = "tracing")]
        tracing::debug!(reference = %reference, "resolving secret");

        let client = self.client.lock().await;
        let result = client.resolve_secret(reference);

        #[cfg(feature = "tracing")]
        if result.is_ok() {
            tracing::debug!(reference = %reference, "secret resolved successfully");
        }

        result
    }

    /// Resolve multiple secrets in a batch.
    ///
    /// Secrets are returned in the same order as the input references.
    /// The operation fails atomically - if any reference fails, none are returned.
    ///
    /// # Arguments
    ///
    /// * `references` - Slice of secret references to resolve
    ///
    /// # Returns
    ///
    /// A vector of [`SecretString`] values in the same order as input.
    ///
    /// # Errors
    ///
    /// Returns an error if any reference is invalid or cannot be resolved.
    /// The error will indicate which reference failed.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use corteq_onepassword::{OnePassword, ExposeSecret};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = OnePassword::from_env()?.connect().await?;
    ///
    ///     let secrets = client.secrets(&[
    ///         "op://prod/database/host",
    ///         "op://prod/database/username",
    ///         "op://prod/database/password",
    ///     ]).await?;
    ///
    ///     let host = secrets[0].expose_secret();
    ///     let user = secrets[1].expose_secret();
    ///     let pass = secrets[2].expose_secret();
    ///     Ok(())
    /// }
    /// ```
    pub async fn secrets(&self, references: &[&str]) -> Result<Vec<SecretString>> {
        // Validate all references first
        for reference in references {
            SecretReference::parse(reference)?;
        }

        if references.is_empty() {
            return Ok(Vec::new());
        }

        #[cfg(feature = "tracing")]
        tracing::debug!(count = references.len(), "resolving batch of secrets");

        let client = self.client.lock().await;
        client.resolve_secrets_batch(references)
    }

    /// Resolve secrets with user-defined names.
    ///
    /// This method allows you to assign memorable names to secrets,
    /// making your code more readable and decoupling it from specific
    /// vault/item/field paths.
    ///
    /// # Arguments
    ///
    /// * `mappings` - Slice of (name, reference) tuples
    ///
    /// # Returns
    ///
    /// A [`SecretMap`] that can be accessed by name.
    ///
    /// # Errors
    ///
    /// Returns an error if any reference is invalid or cannot be resolved.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use corteq_onepassword::{OnePassword, ExposeSecret};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = OnePassword::from_env()?.connect().await?;
    ///
    ///     let secrets = client.secrets_named(&[
    ///         ("db_host", "op://prod/database/host"),
    ///         ("db_user", "op://prod/database/username"),
    ///         ("db_pass", "op://prod/database/password"),
    ///     ]).await?;
    ///
    ///     let host = secrets.get("db_host").expect("db_host not found").expose_secret();
    ///     let user = secrets.get("db_user").expect("db_user not found").expose_secret();
    ///     let pass = secrets.get("db_pass").expect("db_pass not found").expose_secret();
    ///     Ok(())
    /// }
    /// ```
    pub async fn secrets_named(&self, mappings: &[(&str, &str)]) -> Result<SecretMap> {
        let references: Vec<&str> = mappings.iter().map(|(_, r)| *r).collect();
        let names: Vec<&str> = mappings.iter().map(|(n, _)| *n).collect();

        let secrets = self.secrets(&references).await?;

        Ok(SecretMap::from_pairs(names.into_iter().zip(secrets)))
    }
}

impl std::fmt::Debug for OnePassword {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OnePassword")
            .field("connected", &true)
            .finish_non_exhaustive()
    }
}

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

    #[test]
    fn test_onepassword_is_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<OnePassword>();
    }

    #[test]
    fn test_builder_is_send() {
        fn assert_send<T: Send>() {}
        assert_send::<OnePasswordBuilder>();
    }

    #[test]
    #[serial]
    fn test_from_env_missing_var() {
        // Temporarily unset the variable
        let original = std::env::var("OP_SERVICE_ACCOUNT_TOKEN").ok();
        // SAFETY: Test is serialized to prevent concurrent env var access
        unsafe {
            std::env::remove_var("OP_SERVICE_ACCOUNT_TOKEN");
        }

        let result = OnePassword::from_env();
        assert!(matches!(result, Err(Error::MissingAuthToken)));

        // Restore if it was set
        // SAFETY: Test is serialized to prevent concurrent env var access
        if let Some(val) = original {
            unsafe {
                std::env::set_var("OP_SERVICE_ACCOUNT_TOKEN", val);
            }
        }
    }

    #[test]
    #[serial]
    fn test_from_env_empty_var() {
        let original = std::env::var("OP_SERVICE_ACCOUNT_TOKEN").ok();
        // SAFETY: Test is serialized to prevent concurrent env var access
        unsafe {
            std::env::set_var("OP_SERVICE_ACCOUNT_TOKEN", "");
        }

        let result = OnePassword::from_env();
        assert!(matches!(result, Err(Error::MissingAuthToken)));

        // Restore
        // SAFETY: Test is serialized to prevent concurrent env var access
        unsafe {
            match original {
                Some(val) => std::env::set_var("OP_SERVICE_ACCOUNT_TOKEN", val),
                None => std::env::remove_var("OP_SERVICE_ACCOUNT_TOKEN"),
            }
        }
    }

    #[test]
    fn test_from_token_rejects_invalid_token() {
        // Missing ops_ prefix
        let result = OnePassword::from_token("test-token");
        assert!(matches!(result, Err(Error::InvalidToken)));
    }

    #[test]
    fn test_from_token_rejects_invalid_prefix() {
        // Wrong prefix
        let result = OnePassword::from_token("opp_test");
        assert!(matches!(result, Err(Error::InvalidToken)));
    }

    #[test]
    fn test_from_token_rejects_invalid_base64() {
        // Valid prefix but invalid base64
        let result = OnePassword::from_token("ops_not-valid-base64!!!");
        assert!(matches!(result, Err(Error::InvalidToken)));
    }

    #[test]
    fn test_from_token_rejects_invalid_json() {
        // Valid prefix and base64, but not JSON
        // "hello world" in URL-safe base64 without padding
        let result = OnePassword::from_token("ops_aGVsbG8gd29ybGQ");
        assert!(matches!(result, Err(Error::InvalidToken)));
    }

    #[test]
    fn test_from_token_rejects_missing_fields() {
        // Valid JSON but missing required fields
        // {"foo": "bar"} in URL-safe base64 without padding
        let result = OnePassword::from_token("ops_eyJmb28iOiAiYmFyIn0");
        assert!(matches!(result, Err(Error::InvalidToken)));
    }

    #[test]
    fn test_from_token_accepts_valid_format() {
        // Valid format with all required fields
        // {"signInAddress":"example.com","email":"test@test.com","deviceUuid":"123"}
        let valid_payload = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(
            r#"{"signInAddress":"example.com","email":"test@test.com","deviceUuid":"123"}"#,
        );
        let token = format!("ops_{valid_payload}");
        let result = OnePassword::from_token(&token);
        assert!(result.is_ok());
    }

    #[test]
    fn test_builder_integration_chaining() {
        // Use a valid token format for testing builder functionality
        let valid_payload = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(
            r#"{"signInAddress":"example.com","email":"test@test.com","deviceUuid":"123"}"#,
        );
        let token = format!("ops_{valid_payload}");

        let builder = OnePassword::from_token(&token)
            .expect("valid token should be accepted")
            .integration("my-app", "2.0.0");

        // Verify chaining works
        assert!(builder.integration_name.is_some());
        assert!(builder.integration_version.is_some());
    }
}