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
//! Token refresh and migration for Shopify expiring offline access tokens.
//!
//! This module provides functions for refreshing expiring access tokens and
//! migrating non-expiring offline tokens to expiring tokens.
//!
//! # Overview
//!
//! Shopify supports expiring offline access tokens with refresh tokens, which
//! provide enhanced security by requiring periodic token rotation. This module
//! provides:
//!
//! - [`refresh_access_token`]: Refresh an expiring access token using a refresh token
//! - [`migrate_to_expiring_token`]: One-time migration from non-expiring to expiring tokens
//!
//! # Token Refresh Flow
//!
//! When an app uses expiring offline tokens:
//! 1. The initial OAuth flow returns both an access token and a refresh token
//! 2. The access token expires after a period (e.g., 24 hours)
//! 3. Before expiration, use `refresh_access_token` to get a new access token
//! 4. The refresh token itself may also expire and need renewal
//!
//! Use [`Session::expired`] and [`Session::refresh_token_expired`] to check
//! when tokens need refreshing.
//!
//! # Token Migration
//!
//! Apps with existing non-expiring offline tokens can migrate to expiring tokens
//! using [`migrate_to_expiring_token`]. This is a one-time, irreversible operation
//! per shop.
//!
//! # Example: Refreshing an Access Token
//!
//! ```rust,ignore
//! use shopify_sdk::{ShopifyConfig, ShopDomain, Session};
//! use shopify_sdk::auth::oauth::refresh_access_token;
//!
//! // Check if the token needs refreshing
//! if session.expired() || session.refresh_token_expired() {
//!     // Refresh token is available from the session
//!     if let Some(refresh_token) = &session.refresh_token {
//!         let new_session = refresh_access_token(&config, &shop, refresh_token).await?;
//!         println!("New access token: {}", new_session.access_token);
//!     }
//! }
//! ```
//!
//! # Example: Migrating to Expiring Tokens
//!
//! ```rust,ignore
//! use shopify_sdk::{ShopifyConfig, ShopDomain};
//! use shopify_sdk::auth::oauth::migrate_to_expiring_token;
//!
//! // IMPORTANT: This is a one-time, irreversible migration
//! let new_session = migrate_to_expiring_token(&config, &shop, &old_access_token).await?;
//!
//! // The new session has an expiring access token and a refresh token
//! println!("New access token: {}", new_session.access_token);
//! println!("Refresh token: {:?}", new_session.refresh_token);
//! ```
//!
//! # Reference
//!
//! This implementation matches the Ruby SDK's behavior:
//! - `ShopifyAPI::Auth::RefreshToken.refresh_access_token`
//! - `ShopifyAPI::Auth::TokenExchange.migrate_to_expiring_token`

use super::token_exchange::RequestedTokenType;
use crate::auth::oauth::OAuthError;
use crate::auth::session::AccessTokenResponse;
use crate::auth::Session;
use crate::config::{ShopDomain, ShopifyConfig};
use serde::Serialize;

/// Grant type for token exchange (RFC 8693).
/// Reused from `token_exchange` for migration.
const TOKEN_EXCHANGE_GRANT_TYPE: &str = "urn:ietf:params:oauth:grant-type:token-exchange";

/// Grant type for refresh token requests.
const REFRESH_TOKEN_GRANT_TYPE: &str = "refresh_token";

/// Request body for token refresh.
#[derive(Debug, Serialize)]
struct TokenRefreshRequest<'a> {
    client_id: &'a str,
    client_secret: &'a str,
    grant_type: &'a str,
    refresh_token: &'a str,
}

/// Request body for migrating to expiring tokens.
#[derive(Debug, Serialize)]
struct MigrateTokenRequest<'a> {
    client_id: &'a str,
    client_secret: &'a str,
    grant_type: &'a str,
    subject_token: &'a str,
    subject_token_type: &'a str,
    requested_token_type: &'a str,
    expiring: &'a str,
}

/// Refreshes an expiring access token using a refresh token.
///
/// This function exchanges a refresh token for a new access token. Use this
/// when the current access token has expired or is about to expire.
///
/// # Arguments
///
/// * `config` - Shopify SDK configuration
/// * `shop` - The shop domain
/// * `refresh_token` - The refresh token from the current session
///
/// # Returns
///
/// A new [`Session`] with:
/// - A new access token
/// - Updated expiration time
/// - A new refresh token (if issued by Shopify)
///
/// # Errors
///
/// - [`OAuthError::TokenRefreshFailed`] if the refresh request fails
///
/// # Example
///
/// ```rust,ignore
/// use shopify_sdk::auth::oauth::refresh_access_token;
///
/// // Get the refresh token from your stored session
/// let refresh_token = session.refresh_token.as_ref().expect("No refresh token");
///
/// let new_session = refresh_access_token(&config, &shop, refresh_token).await?;
/// println!("New access token obtained");
/// ```
pub async fn refresh_access_token(
    config: &ShopifyConfig,
    shop: &ShopDomain,
    refresh_token: &str,
) -> Result<Session, OAuthError> {
    // Build the token URL
    let token_url = format!("https://{}/admin/oauth/access_token", shop.as_ref());

    // Create the request body
    let request_body = TokenRefreshRequest {
        client_id: config.api_key().as_ref(),
        client_secret: config.api_secret_key().as_ref(),
        grant_type: REFRESH_TOKEN_GRANT_TYPE,
        refresh_token,
    };

    // Send the POST request
    let client = reqwest::Client::new();
    let response = client
        .post(&token_url)
        .json(&request_body)
        .send()
        .await
        .map_err(|e| OAuthError::TokenRefreshFailed {
            status: 0,
            message: format!("Network error: {e}"),
        })?;

    let status = response.status().as_u16();

    // Handle error responses
    if !response.status().is_success() {
        let error_body = response.text().await.unwrap_or_default();
        return Err(OAuthError::TokenRefreshFailed {
            status,
            message: error_body,
        });
    }

    // Parse the successful response
    let token_response: AccessTokenResponse =
        response
            .json()
            .await
            .map_err(|e| OAuthError::TokenRefreshFailed {
                status,
                message: format!("Failed to parse token response: {e}"),
            })?;

    // Create and return the session
    let session = Session::from_access_token_response(shop.clone(), &token_response);

    Ok(session)
}

/// Migrates a non-expiring offline access token to an expiring token.
///
/// This function performs a one-time, irreversible migration from a non-expiring
/// offline access token to an expiring offline access token with a refresh token.
///
/// # Important
///
/// - This migration is **one-time and irreversible** per shop
/// - After migration, the old non-expiring token will no longer work
/// - You must store and manage the new refresh token for future token refreshes
///
/// # Arguments
///
/// * `config` - Shopify SDK configuration
/// * `shop` - The shop domain
/// * `access_token` - The current non-expiring offline access token
///
/// # Returns
///
/// A new [`Session`] with:
/// - A new expiring access token
/// - A refresh token for obtaining new access tokens
/// - Expiration times for both tokens
///
/// # Errors
///
/// - [`OAuthError::TokenRefreshFailed`] if the migration request fails
///
/// # Example
///
/// ```rust,ignore
/// use shopify_sdk::auth::oauth::migrate_to_expiring_token;
///
/// // IMPORTANT: This is irreversible!
/// let new_session = migrate_to_expiring_token(&config, &shop, &old_token).await?;
///
/// // Save the new session with refresh token
/// println!("Migration successful!");
/// println!("New access token expires at: {:?}", new_session.expires);
/// println!("Refresh token: {:?}", new_session.refresh_token);
/// ```
pub async fn migrate_to_expiring_token(
    config: &ShopifyConfig,
    shop: &ShopDomain,
    access_token: &str,
) -> Result<Session, OAuthError> {
    // Build the token URL
    let token_url = format!("https://{}/admin/oauth/access_token", shop.as_ref());

    // Use offline access token URN for both subject and requested token types
    // This matches the Ruby SDK behavior for migration
    let offline_token_urn = RequestedTokenType::OfflineAccessToken.as_urn();

    // Create the request body
    let request_body = MigrateTokenRequest {
        client_id: config.api_key().as_ref(),
        client_secret: config.api_secret_key().as_ref(),
        grant_type: TOKEN_EXCHANGE_GRANT_TYPE,
        subject_token: access_token,
        subject_token_type: offline_token_urn,
        requested_token_type: offline_token_urn,
        expiring: "1",
    };

    // Send the POST request
    let client = reqwest::Client::new();
    let response = client
        .post(&token_url)
        .json(&request_body)
        .send()
        .await
        .map_err(|e| OAuthError::TokenRefreshFailed {
            status: 0,
            message: format!("Network error: {e}"),
        })?;

    let status = response.status().as_u16();

    // Handle error responses
    if !response.status().is_success() {
        let error_body = response.text().await.unwrap_or_default();
        return Err(OAuthError::TokenRefreshFailed {
            status,
            message: error_body,
        });
    }

    // Parse the successful response
    let token_response: AccessTokenResponse =
        response
            .json()
            .await
            .map_err(|e| OAuthError::TokenRefreshFailed {
                status,
                message: format!("Failed to parse token response: {e}"),
            })?;

    // Create and return the session
    let session = Session::from_access_token_response(shop.clone(), &token_response);

    Ok(session)
}

// Verify types are Send + Sync at compile time
const _: fn() = || {
    const fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<TokenRefreshRequest<'_>>();
    assert_send_sync::<MigrateTokenRequest<'_>>();
};

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{ApiKey, ApiSecretKey};

    fn create_config() -> ShopifyConfig {
        ShopifyConfig::builder()
            .api_key(ApiKey::new("test-api-key").unwrap())
            .api_secret_key(ApiSecretKey::new("test-secret").unwrap())
            .build()
            .unwrap()
    }

    // === TokenRefreshRequest tests ===

    #[test]
    fn test_token_refresh_request_serializes_with_correct_grant_type() {
        let request = TokenRefreshRequest {
            client_id: "test-client-id",
            client_secret: "test-client-secret",
            grant_type: REFRESH_TOKEN_GRANT_TYPE,
            refresh_token: "test-refresh-token",
        };

        let json = serde_json::to_string(&request).unwrap();
        assert!(json.contains("\"grant_type\":\"refresh_token\""));
        assert!(json.contains("\"client_id\":\"test-client-id\""));
        assert!(json.contains("\"client_secret\":\"test-client-secret\""));
        assert!(json.contains("\"refresh_token\":\"test-refresh-token\""));
    }

    #[test]
    fn test_refresh_token_grant_type_constant_is_correct() {
        assert_eq!(REFRESH_TOKEN_GRANT_TYPE, "refresh_token");
    }

    // === MigrateTokenRequest tests ===

    #[test]
    fn test_migrate_token_request_serializes_with_correct_fields() {
        let request = MigrateTokenRequest {
            client_id: "test-client-id",
            client_secret: "test-client-secret",
            grant_type: TOKEN_EXCHANGE_GRANT_TYPE,
            subject_token: "old-access-token",
            subject_token_type: RequestedTokenType::OfflineAccessToken.as_urn(),
            requested_token_type: RequestedTokenType::OfflineAccessToken.as_urn(),
            expiring: "1",
        };

        let json = serde_json::to_string(&request).unwrap();
        assert!(json.contains("\"grant_type\":\"urn:ietf:params:oauth:grant-type:token-exchange\""));
        assert!(json.contains("\"expiring\":\"1\""));
        assert!(json.contains("\"subject_token\":\"old-access-token\""));
        assert!(json.contains(
            "\"subject_token_type\":\"urn:shopify:params:oauth:token-type:offline-access-token\""
        ));
        assert!(json.contains(
            "\"requested_token_type\":\"urn:shopify:params:oauth:token-type:offline-access-token\""
        ));
    }

    #[test]
    fn test_token_exchange_grant_type_constant_is_correct() {
        assert_eq!(
            TOKEN_EXCHANGE_GRANT_TYPE,
            "urn:ietf:params:oauth:grant-type:token-exchange"
        );
    }

    // === refresh_access_token tests ===

    #[tokio::test]
    async fn test_refresh_access_token_returns_token_refresh_failed_error_on_failure() {
        let config = create_config();
        let shop = ShopDomain::new("test-shop").unwrap();

        let result = refresh_access_token(&config, &shop, "test-refresh-token").await;

        // Should fail with TokenRefreshFailed error (network or HTTP error)
        match result {
            Err(OAuthError::TokenRefreshFailed { status, message }) => {
                // Network errors have status 0, HTTP errors have status >= 400
                assert!(status == 0 || status >= 400);
                assert!(!message.is_empty());
            }
            _ => panic!("Expected TokenRefreshFailed error"),
        }
    }

    #[tokio::test]
    async fn test_refresh_access_token_constructs_correct_url() {
        // We can verify URL construction by checking that the request fails
        // at the network layer (not a code error)
        let config = create_config();
        let shop = ShopDomain::new("my-test-shop").unwrap();

        let result = refresh_access_token(&config, &shop, "test-refresh-token").await;

        // The request will fail, but we've verified URL construction works
        assert!(matches!(result, Err(OAuthError::TokenRefreshFailed { .. })));
    }

    // === migrate_to_expiring_token tests ===

    #[tokio::test]
    async fn test_migrate_to_expiring_token_returns_token_refresh_failed_error_on_failure() {
        let config = create_config();
        let shop = ShopDomain::new("test-shop").unwrap();

        let result = migrate_to_expiring_token(&config, &shop, "old-access-token").await;

        // Should fail with TokenRefreshFailed error (network or HTTP error)
        match result {
            Err(OAuthError::TokenRefreshFailed { status, message }) => {
                // Network errors have status 0, HTTP errors have status >= 400
                assert!(status == 0 || status >= 400);
                assert!(!message.is_empty());
            }
            _ => panic!("Expected TokenRefreshFailed error"),
        }
    }

    #[tokio::test]
    async fn test_migrate_to_expiring_token_constructs_correct_url() {
        let config = create_config();
        let shop = ShopDomain::new("my-test-shop").unwrap();

        let result = migrate_to_expiring_token(&config, &shop, "old-token").await;

        // The request will fail, but we've verified URL construction works
        assert!(matches!(result, Err(OAuthError::TokenRefreshFailed { .. })));
    }

    // === Send + Sync tests ===

    #[test]
    fn test_token_refresh_request_is_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<TokenRefreshRequest<'_>>();
    }

    #[test]
    fn test_migrate_token_request_is_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<MigrateTokenRequest<'_>>();
    }

    // === Session creation tests ===

    #[test]
    fn test_session_from_refresh_response_populates_all_fields() {
        let shop = ShopDomain::new("test-shop").unwrap();
        let response = AccessTokenResponse {
            access_token: "new-access-token".to_string(),
            scope: "read_products,write_orders".to_string(),
            expires_in: Some(86400),
            associated_user_scope: None,
            associated_user: None,
            session: Some("shopify-session-id".to_string()),
            refresh_token: Some("new-refresh-token".to_string()),
            refresh_token_expires_in: Some(2592000),
        };

        let session = Session::from_access_token_response(shop, &response);

        assert_eq!(session.access_token, "new-access-token");
        assert_eq!(session.refresh_token, Some("new-refresh-token".to_string()));
        assert!(session.expires.is_some());
        assert!(session.refresh_token_expires_at.is_some());
        assert!(!session.is_online);
        assert_eq!(session.id, "offline_test-shop.myshopify.com");
    }
}