shopify-sdk 1.0.0

A Rust SDK for the Shopify API
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
//! OAuth-specific error types for the Shopify API SDK.
//!
//! This module contains error types for OAuth operations including HMAC validation,
//! state verification, token exchange failures, client credentials failures,
//! token refresh failures, and JWT validation for embedded apps.
//!
//! # Error Types
//!
//! - [`OAuthError::InvalidHmac`]: HMAC signature validation failed
//! - [`OAuthError::StateMismatch`]: OAuth state parameter doesn't match expected
//! - [`OAuthError::TokenExchangeFailed`]: Token exchange request failed
//! - [`OAuthError::ClientCredentialsFailed`]: Client credentials exchange request failed
//! - [`OAuthError::TokenRefreshFailed`]: Token refresh or migration request failed
//! - [`OAuthError::InvalidCallback`]: Callback parameters are malformed
//! - [`OAuthError::MissingHostConfig`]: Host URL not configured for redirect URI
//! - [`OAuthError::InvalidJwt`]: JWT validation failed (for token exchange)
//! - [`OAuthError::NotEmbeddedApp`]: Token exchange requires embedded app configuration
//! - [`OAuthError::NotPrivateApp`]: Client credentials requires non-embedded app configuration
//! - [`OAuthError::HttpError`]: Wrapped HTTP client error
//!
//! # Example
//!
//! ```rust
//! use shopify_sdk::auth::oauth::OAuthError;
//!
//! let error = OAuthError::InvalidHmac;
//! assert_eq!(error.to_string(), "HMAC signature validation failed");
//!
//! let error = OAuthError::StateMismatch {
//!     expected: "abc123".to_string(),
//!     received: "xyz789".to_string(),
//! };
//! assert!(error.to_string().contains("abc123"));
//!
//! let error = OAuthError::InvalidJwt {
//!     reason: "Token expired".to_string(),
//! };
//! assert!(error.to_string().contains("Token expired"));
//!
//! let error = OAuthError::ClientCredentialsFailed {
//!     status: 401,
//!     message: "Invalid credentials".to_string(),
//! };
//! assert!(error.to_string().contains("401"));
//!
//! let error = OAuthError::TokenRefreshFailed {
//!     status: 400,
//!     message: "Invalid refresh token".to_string(),
//! };
//! assert!(error.to_string().contains("400"));
//! ```

use crate::clients::HttpError;
use thiserror::Error;

/// Errors that can occur during OAuth operations.
///
/// This enum covers all failure modes in OAuth flows, including the authorization
/// code flow, token exchange, client credentials, token refresh, and JWT validation
/// for embedded apps.
///
/// # Thread Safety
///
/// `OAuthError` is `Send + Sync`, making it safe to use across async boundaries.
///
/// # Example
///
/// ```rust
/// use shopify_sdk::auth::oauth::OAuthError;
///
/// fn handle_oauth_error(err: OAuthError) {
///     match err {
///         OAuthError::InvalidHmac => {
///             eprintln!("Security: HMAC validation failed");
///         }
///         OAuthError::StateMismatch { expected, received } => {
///             eprintln!("CSRF: State mismatch - expected {}, got {}", expected, received);
///         }
///         OAuthError::TokenExchangeFailed { status, message } => {
///             eprintln!("Token exchange failed ({}): {}", status, message);
///         }
///         OAuthError::ClientCredentialsFailed { status, message } => {
///             eprintln!("Client credentials failed ({}): {}", status, message);
///         }
///         OAuthError::TokenRefreshFailed { status, message } => {
///             eprintln!("Token refresh failed ({}): {}", status, message);
///         }
///         OAuthError::InvalidCallback { reason } => {
///             eprintln!("Invalid callback: {}", reason);
///         }
///         OAuthError::MissingHostConfig => {
///             eprintln!("Configuration error: Host URL not configured");
///         }
///         OAuthError::InvalidJwt { reason } => {
///             eprintln!("JWT validation failed: {}", reason);
///         }
///         OAuthError::NotEmbeddedApp => {
///             eprintln!("Token exchange only works for embedded apps");
///         }
///         OAuthError::NotPrivateApp => {
///             eprintln!("Client credentials only works for private apps");
///         }
///         OAuthError::HttpError(e) => {
///             eprintln!("HTTP error: {}", e);
///         }
///     }
/// }
/// ```
#[derive(Debug, Error)]
pub enum OAuthError {
    /// HMAC signature validation failed.
    ///
    /// This indicates the callback request's HMAC signature does not match
    /// the expected value computed with the API secret key. This could indicate
    /// a tampered request or misconfigured secret key.
    #[error("HMAC signature validation failed")]
    InvalidHmac,

    /// OAuth state parameter mismatch.
    ///
    /// The state parameter in the callback does not match the expected state
    /// that was generated during `begin_auth()`. This is a security measure
    /// against CSRF attacks.
    #[error("State parameter mismatch: expected '{expected}', received '{received}'")]
    StateMismatch {
        /// The expected state value that was generated.
        expected: String,
        /// The state value received in the callback.
        received: String,
    },

    /// Token exchange request failed.
    ///
    /// The POST request to exchange the authorization code for an access token
    /// returned a non-success HTTP status.
    #[error("Token exchange failed with status {status}: {message}")]
    TokenExchangeFailed {
        /// The HTTP status code returned.
        status: u16,
        /// The error message from the response.
        message: String,
    },

    /// Client credentials exchange request failed.
    ///
    /// The POST request to obtain an access token using client credentials
    /// returned a non-success HTTP status. This error is specific to the
    /// Client Credentials Grant flow used by private/organization apps.
    ///
    /// # Example
    ///
    /// ```rust
    /// use shopify_sdk::auth::oauth::OAuthError;
    ///
    /// let error = OAuthError::ClientCredentialsFailed {
    ///     status: 401,
    ///     message: "Invalid client credentials".to_string(),
    /// };
    /// assert!(error.to_string().contains("Client credentials"));
    /// assert!(error.to_string().contains("401"));
    /// ```
    #[error("Client credentials exchange failed with status {status}: {message}")]
    ClientCredentialsFailed {
        /// The HTTP status code returned (0 for network errors).
        status: u16,
        /// The error message from the response or network error description.
        message: String,
    },

    /// Token refresh or migration request failed.
    ///
    /// The POST request to refresh an access token or migrate to expiring tokens
    /// returned a non-success HTTP status. This error is used for both the
    /// `refresh_access_token` and `migrate_to_expiring_token` functions.
    ///
    /// # Example
    ///
    /// ```rust
    /// use shopify_sdk::auth::oauth::OAuthError;
    ///
    /// let error = OAuthError::TokenRefreshFailed {
    ///     status: 400,
    ///     message: "Invalid refresh token".to_string(),
    /// };
    /// assert!(error.to_string().contains("Token refresh"));
    /// assert!(error.to_string().contains("400"));
    /// ```
    #[error("Token refresh failed with status {status}: {message}")]
    TokenRefreshFailed {
        /// The HTTP status code returned (0 for network errors).
        status: u16,
        /// The error message from the response or network error description.
        message: String,
    },

    /// Callback parameters are invalid or malformed.
    ///
    /// One or more parameters in the OAuth callback are missing, empty,
    /// or have invalid formats.
    #[error("Invalid callback: {reason}")]
    InvalidCallback {
        /// Description of what's invalid about the callback.
        reason: String,
    },

    /// Host URL is not configured in `ShopifyConfig`.
    ///
    /// The `begin_auth()` function requires a host URL to construct the
    /// redirect URI. Configure this via `ShopifyConfigBuilder::host()`.
    #[error("Host URL must be configured in ShopifyConfig for OAuth")]
    MissingHostConfig,

    /// JWT validation failed.
    ///
    /// This error occurs during token exchange when the session token (JWT)
    /// provided by App Bridge cannot be validated. Common causes include:
    ///
    /// - Token is expired or not yet valid
    /// - Token was signed with a different secret key
    /// - Token's audience (`aud`) claim doesn't match the app's API key
    /// - Token structure is malformed
    /// - Shopify rejected the token during token exchange
    ///
    /// # Example
    ///
    /// ```rust
    /// use shopify_sdk::auth::oauth::OAuthError;
    ///
    /// let error = OAuthError::InvalidJwt {
    ///     reason: "Session token had invalid API key".to_string(),
    /// };
    /// assert!(error.to_string().contains("Invalid JWT"));
    /// ```
    #[error("Invalid JWT: {reason}")]
    InvalidJwt {
        /// Description of why the JWT validation failed.
        reason: String,
    },

    /// Token exchange requires an embedded app configuration.
    ///
    /// Token exchange OAuth flow is only available for embedded apps that
    /// receive session tokens from Shopify App Bridge. Ensure that
    /// `ShopifyConfigBuilder::is_embedded(true)` is set.
    ///
    /// # Example
    ///
    /// ```rust
    /// use shopify_sdk::auth::oauth::OAuthError;
    ///
    /// let error = OAuthError::NotEmbeddedApp;
    /// assert!(error.to_string().contains("embedded app"));
    /// ```
    #[error("Token exchange requires an embedded app configuration")]
    NotEmbeddedApp,

    /// Client credentials requires a non-embedded app configuration.
    ///
    /// Client Credentials Grant OAuth flow is only available for private or
    /// organization apps that are NOT embedded in the Shopify admin. Ensure
    /// that `ShopifyConfigBuilder::is_embedded(false)` is set (or not set,
    /// as `false` is the default).
    ///
    /// This error is the inverse of [`NotEmbeddedApp`](OAuthError::NotEmbeddedApp),
    /// which is used for token exchange flows that require embedded apps.
    ///
    /// # Example
    ///
    /// ```rust
    /// use shopify_sdk::auth::oauth::OAuthError;
    ///
    /// let error = OAuthError::NotPrivateApp;
    /// assert!(error.to_string().contains("non-embedded"));
    /// ```
    #[error("Client credentials requires a non-embedded app configuration")]
    NotPrivateApp,

    /// Wrapped HTTP client error.
    ///
    /// An error occurred during HTTP communication, such as a network failure
    /// or request validation error.
    #[error(transparent)]
    HttpError(#[from] HttpError),
}

// Verify OAuthError is Send + Sync at compile time
const _: fn() = || {
    const fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<OAuthError>();
};

#[cfg(test)]
mod tests {
    use super::*;
    use crate::clients::{HttpResponseError, InvalidHttpRequestError};

    #[test]
    fn test_invalid_hmac_formats_correctly() {
        let error = OAuthError::InvalidHmac;
        assert_eq!(error.to_string(), "HMAC signature validation failed");
    }

    #[test]
    fn test_state_mismatch_includes_expected_and_received() {
        let error = OAuthError::StateMismatch {
            expected: "abc123".to_string(),
            received: "xyz789".to_string(),
        };
        let message = error.to_string();
        assert!(message.contains("abc123"));
        assert!(message.contains("xyz789"));
        assert!(message.contains("expected"));
        assert!(message.contains("received"));
    }

    #[test]
    fn test_token_exchange_failed_includes_status_and_message() {
        let error = OAuthError::TokenExchangeFailed {
            status: 401,
            message: "Invalid client credentials".to_string(),
        };
        let message = error.to_string();
        assert!(message.contains("401"));
        assert!(message.contains("Invalid client credentials"));
    }

    #[test]
    fn test_from_http_error_conversion() {
        let http_error = HttpError::Response(HttpResponseError {
            code: 500,
            message: "Internal server error".to_string(),
            error_reference: None,
        });
        let oauth_error: OAuthError = http_error.into();
        match oauth_error {
            OAuthError::HttpError(_) => {}
            _ => panic!("Expected HttpError variant"),
        }
    }

    #[test]
    fn test_oauth_error_implements_std_error() {
        let error: &dyn std::error::Error = &OAuthError::InvalidHmac;
        let _ = error;

        let error: &dyn std::error::Error = &OAuthError::StateMismatch {
            expected: "a".to_string(),
            received: "b".to_string(),
        };
        let _ = error;

        let error: &dyn std::error::Error = &OAuthError::TokenExchangeFailed {
            status: 400,
            message: "test".to_string(),
        };
        let _ = error;

        let error: &dyn std::error::Error = &OAuthError::InvalidCallback {
            reason: "test".to_string(),
        };
        let _ = error;

        let error: &dyn std::error::Error = &OAuthError::MissingHostConfig;
        let _ = error;

        let error: &dyn std::error::Error = &OAuthError::InvalidJwt {
            reason: "test".to_string(),
        };
        let _ = error;

        let error: &dyn std::error::Error = &OAuthError::NotEmbeddedApp;
        let _ = error;

        let error: &dyn std::error::Error = &OAuthError::ClientCredentialsFailed {
            status: 401,
            message: "test".to_string(),
        };
        let _ = error;

        let error: &dyn std::error::Error = &OAuthError::NotPrivateApp;
        let _ = error;

        let error: &dyn std::error::Error = &OAuthError::TokenRefreshFailed {
            status: 400,
            message: "test".to_string(),
        };
        let _ = error;
    }

    #[test]
    fn test_invalid_callback_includes_reason() {
        let error = OAuthError::InvalidCallback {
            reason: "Shop domain is invalid".to_string(),
        };
        assert!(error.to_string().contains("Shop domain is invalid"));
    }

    #[test]
    fn test_missing_host_config_message() {
        let error = OAuthError::MissingHostConfig;
        assert!(error.to_string().contains("Host URL"));
        assert!(error.to_string().contains("configured"));
    }

    #[test]
    fn test_http_error_from_invalid_request() {
        let invalid = InvalidHttpRequestError::MissingBodyType;
        let http_error = HttpError::InvalidRequest(invalid);
        let oauth_error: OAuthError = http_error.into();

        match oauth_error {
            OAuthError::HttpError(HttpError::InvalidRequest(_)) => {}
            _ => panic!("Expected HttpError::InvalidRequest variant"),
        }
    }

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

    // === New tests for InvalidJwt and NotEmbeddedApp variants ===

    #[test]
    fn test_invalid_jwt_formats_error_message_with_reason() {
        let error = OAuthError::InvalidJwt {
            reason: "Token expired".to_string(),
        };
        let message = error.to_string();
        assert!(message.contains("Invalid JWT"));
        assert!(message.contains("Token expired"));
    }

    #[test]
    fn test_not_embedded_app_has_correct_error_message() {
        let error = OAuthError::NotEmbeddedApp;
        let message = error.to_string();
        assert!(message.contains("embedded app"));
        assert!(message.contains("Token exchange"));
    }

    #[test]
    fn test_new_variants_implement_std_error() {
        // InvalidJwt implements std::error::Error
        let invalid_jwt_error: &dyn std::error::Error = &OAuthError::InvalidJwt {
            reason: "test reason".to_string(),
        };
        assert!(invalid_jwt_error.to_string().contains("Invalid JWT"));

        // NotEmbeddedApp implements std::error::Error
        let not_embedded_error: &dyn std::error::Error = &OAuthError::NotEmbeddedApp;
        assert!(not_embedded_error.to_string().contains("embedded app"));
    }

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

        // These compile-time assertions verify Send + Sync
        assert_send_sync::<OAuthError>();

        // Also verify the specific variants at runtime
        let invalid_jwt = OAuthError::InvalidJwt {
            reason: "test".to_string(),
        };
        let not_embedded = OAuthError::NotEmbeddedApp;

        // Can be sent across threads
        std::thread::spawn(move || {
            let _ = invalid_jwt;
        })
        .join()
        .unwrap();

        std::thread::spawn(move || {
            let _ = not_embedded;
        })
        .join()
        .unwrap();
    }

    // === Tests for ClientCredentialsFailed and NotPrivateApp variants ===

    #[test]
    fn test_client_credentials_failed_formats_error_message_with_status_and_message() {
        let error = OAuthError::ClientCredentialsFailed {
            status: 401,
            message: "Invalid client credentials".to_string(),
        };
        let message = error.to_string();
        assert!(message.contains("Client credentials"));
        assert!(message.contains("401"));
        assert!(message.contains("Invalid client credentials"));
    }

    #[test]
    fn test_not_private_app_has_correct_error_message() {
        let error = OAuthError::NotPrivateApp;
        let message = error.to_string();
        assert!(message.contains("non-embedded"));
        assert!(message.contains("Client credentials"));
    }

    #[test]
    fn test_client_credentials_variants_implement_std_error() {
        // ClientCredentialsFailed implements std::error::Error
        let client_creds_error: &dyn std::error::Error = &OAuthError::ClientCredentialsFailed {
            status: 500,
            message: "Server error".to_string(),
        };
        assert!(client_creds_error
            .to_string()
            .contains("Client credentials"));

        // NotPrivateApp implements std::error::Error
        let not_private_error: &dyn std::error::Error = &OAuthError::NotPrivateApp;
        assert!(not_private_error.to_string().contains("non-embedded"));
    }

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

        // These compile-time assertions verify Send + Sync
        assert_send_sync::<OAuthError>();

        // Also verify the specific variants at runtime
        let client_creds_failed = OAuthError::ClientCredentialsFailed {
            status: 401,
            message: "test".to_string(),
        };
        let not_private = OAuthError::NotPrivateApp;

        // Can be sent across threads
        std::thread::spawn(move || {
            let _ = client_creds_failed;
        })
        .join()
        .unwrap();

        std::thread::spawn(move || {
            let _ = not_private;
        })
        .join()
        .unwrap();
    }

    // === Tests for TokenRefreshFailed variant ===

    #[test]
    fn test_token_refresh_failed_formats_error_message_with_status_and_message() {
        let error = OAuthError::TokenRefreshFailed {
            status: 400,
            message: "Invalid refresh token".to_string(),
        };
        let message = error.to_string();
        assert!(message.contains("Token refresh"));
        assert!(message.contains("400"));
        assert!(message.contains("Invalid refresh token"));
    }

    #[test]
    fn test_token_refresh_failed_with_network_error_status_zero() {
        let error = OAuthError::TokenRefreshFailed {
            status: 0,
            message: "Network error: connection refused".to_string(),
        };
        let message = error.to_string();
        assert!(message.contains("Token refresh"));
        assert!(message.contains("0"));
        assert!(message.contains("Network error"));
    }

    #[test]
    fn test_token_refresh_failed_implements_std_error() {
        let error: &dyn std::error::Error = &OAuthError::TokenRefreshFailed {
            status: 401,
            message: "Unauthorized".to_string(),
        };
        assert!(error.to_string().contains("Token refresh"));
    }

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

        let token_refresh_failed = OAuthError::TokenRefreshFailed {
            status: 400,
            message: "test".to_string(),
        };

        std::thread::spawn(move || {
            let _ = token_refresh_failed;
        })
        .join()
        .unwrap();
    }
}