force 0.2.0

Production-ready Salesforce Platform API client with REST and Bulk API 2.0 support
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
//! SOQL query execution.
//!
//! Query and query_more operations are provided by the
//! [`RestOperation`](crate::api::rest_operation::RestOperation) trait, which
//! `RestHandler` implements. This module retains the integration tests that
//! exercise those operations through the handler.

#[cfg(test)]
mod tests {
    use crate::api::rest_operation::RestOperation;
    use crate::client::builder;
    use crate::error::ForceError;
    use crate::test_support::{MockAuthenticator, Must};
    use crate::types::{DynamicSObject, QueryResult};
    use serde::{Deserialize, Serialize};
    use serde_json::json;
    use wiremock::matchers::{header, method, path, query_param};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    // Test SObject for typed queries
    #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
    struct TestAccount {
        #[serde(rename = "Id")]
        id: String,
        #[serde(rename = "Name")]
        name: String,
    }

    // RED PHASE - Write failing tests first
    // Note: These are compilation tests to ensure types are correct.
    // Integration tests will be added once the client builder is stabilized.

    #[test]
    fn test_query_result_deserialization_typed() {
        // Test that QueryResult can deserialize typed records
        let json = serde_json::json!({
            "totalSize": 2,
            "done": true,
            "records": [
                {"Id": "001", "Name": "Acme"},
                {"Id": "002", "Name": "Globex"}
            ]
        });

        let result: QueryResult<TestAccount> = serde_json::from_value(json).must();

        assert_eq!(result.total_size, 2);
        assert!(result.is_done());
        assert_eq!(result.len(), 2);
        assert_eq!(result.records[0].name, "Acme");
        assert_eq!(result.records[1].name, "Globex");
    }

    #[test]
    fn test_query_result_deserialization_dynamic() {
        // Test that QueryResult can deserialize DynamicSObject
        let json = serde_json::json!({
            "totalSize": 1,
            "done": true,
            "records": [{
                "attributes": {
                    "type": "Account",
                    "url": "/services/data/v60.0/sobjects/Account/001"
                },
                "Id": "001",
                "Name": "Acme"
            }]
        });

        let result: QueryResult<DynamicSObject> = serde_json::from_value(json).must();

        assert_eq!(result.total_size, 1);
        assert_eq!(result.records[0].object_type(), "Account");
        assert_eq!(
            result.records[0]
                .get_field("Name")
                .and_then(|v: &serde_json::Value| v.as_str()),
            Some("Acme")
        );
    }

    #[test]
    fn test_query_result_with_pagination() {
        // Test pagination metadata
        let json = serde_json::json!({
            "totalSize": 4,
            "done": false,
            "nextRecordsUrl": "/services/data/v60.0/query/01g-2000",
            "records": [
                {"Id": "001", "Name": "Acme"},
                {"Id": "002", "Name": "Globex"}
            ]
        });

        let result: QueryResult<TestAccount> = serde_json::from_value(json).must();

        assert_eq!(result.total_size, 4);
        assert!(!result.is_done());
        assert!(result.has_more());
        assert_eq!(
            result.next_records_url,
            Some("/services/data/v60.0/query/01g-2000".to_string())
        );
    }

    #[test]
    fn test_query_result_empty() {
        // Test empty result set
        let json = serde_json::json!({
            "totalSize": 0,
            "done": true,
            "records": []
        });

        let result: QueryResult<TestAccount> = serde_json::from_value(json).must();

        assert_eq!(result.total_size, 0);
        assert!(result.is_done());
        assert!(result.is_empty());
    }

    #[test]
    fn test_query_result_with_nested_query() {
        // Test complex SOQL with subqueries
        let json = serde_json::json!({
            "totalSize": 1,
            "done": true,
            "records": [{
                "Id": "001",
                "Name": "Tech Corp",
                "Contacts": {
                    "totalSize": 0,
                    "done": true,
                    "records": []
                }
            }]
        });

        let result: QueryResult<serde_json::Value> = serde_json::from_value(json).must();
        assert_eq!(result.total_size, 1);
    }

    #[test]
    fn test_query_result_pagination_workflow() {
        // Test that pagination metadata is correctly available
        let json = serde_json::json!({
            "totalSize": 100,
            "done": false,
            "nextRecordsUrl": "/services/data/v60.0/query/01g-batch2",
            "records": [
                {"Id": "001", "Name": "First"},
                {"Id": "002", "Name": "Second"}
            ]
        });

        let result: QueryResult<TestAccount> = serde_json::from_value(json).must();

        // Verify pagination state
        assert!(!result.is_done());
        assert!(result.has_more());
        assert!(result.next_records_url.is_some());

        // The next_records_url can be used with query_more()
        let next_url = result.next_records_url.must();
        assert!(next_url.starts_with("/services/data"));
    }

    // Integration tests with wiremock

    #[tokio::test]
    async fn test_query_success() {
        let mock_server = MockServer::start().await;
        let auth = MockAuthenticator::new("test_token", &mock_server.uri());

        // Mock the query endpoint
        Mock::given(method("GET"))
            .and(path("/services/data/v60.0/query"))
            .and(query_param("q", "SELECT Id, Name FROM Account LIMIT 2"))
            .and(header("authorization", "Bearer test_token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "totalSize": 2,
                "done": true,
                "records": [
                    {"Id": "001xx0000000001", "Name": "Acme Corp"},
                    {"Id": "001xx0000000002", "Name": "Globex Inc"}
                ]
            })))
            .mount(&mock_server)
            .await;

        let client = builder().authenticate(auth).build().await.must();

        let result: QueryResult<TestAccount> = client
            .rest()
            .query("SELECT Id, Name FROM Account LIMIT 2")
            .await
            .must();

        assert_eq!(result.total_size, 2);
        assert!(result.is_done());
        assert_eq!(result.len(), 2);
        assert_eq!(result.records[0].name, "Acme Corp");
        assert_eq!(result.records[1].name, "Globex Inc");
    }

    #[tokio::test]
    async fn test_query_pagination_missing_url() {
        let mock_server = MockServer::start().await;
        let auth = MockAuthenticator::new("test_token", &mock_server.uri());

        // Mock response with done: false but no nextRecordsUrl
        Mock::given(method("GET"))
            .and(path("/services/data/v60.0/query"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "totalSize": 10,
                "done": false,
                // nextRecordsUrl is missing!
                "records": [
                    {"Id": "001", "Name": "Record1"}
                ]
            })))
            .mount(&mock_server)
            .await;

        let client = builder().authenticate(auth).build().await.must();

        let result: QueryResult<TestAccount> = client
            .rest()
            .query("SELECT Id, Name FROM Account")
            .await
            .must();

        // Verify that the client deserializes it as is
        assert!(!result.is_done());
        assert!(!result.has_more()); // Fixed: has_more() now safely returns false
        assert!(result.next_records_url.is_none());
    }

    #[tokio::test]
    async fn test_query_with_pagination() {
        let mock_server = MockServer::start().await;
        let auth = MockAuthenticator::new("test_token", &mock_server.uri());

        // Mock first page
        Mock::given(method("GET"))
            .and(path("/services/data/v60.0/query"))
            .and(query_param("q", "SELECT Id, Name FROM Account"))
            .and(header("authorization", "Bearer test_token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "totalSize": 4,
                "done": false,
                "nextRecordsUrl": "/services/data/v60.0/query/01gxx-batch2",
                "records": [
                    {"Id": "001xx0000000001", "Name": "Page1 Record1"},
                    {"Id": "001xx0000000002", "Name": "Page1 Record2"}
                ]
            })))
            .mount(&mock_server)
            .await;

        let client = builder().authenticate(auth).build().await.must();

        let result: QueryResult<TestAccount> = client
            .rest()
            .query("SELECT Id, Name FROM Account")
            .await
            .must();

        assert_eq!(result.total_size, 4);
        assert!(!result.is_done());
        assert!(result.has_more());
        assert_eq!(result.len(), 2);
        assert_eq!(
            result.next_records_url,
            Some("/services/data/v60.0/query/01gxx-batch2".to_string())
        );
    }

    #[tokio::test]
    async fn test_query_more_success() {
        let mock_server = MockServer::start().await;
        let auth = MockAuthenticator::new("test_token", &mock_server.uri());

        // Mock first page
        Mock::given(method("GET"))
            .and(path("/services/data/v60.0/query"))
            .and(query_param("q", "SELECT Id, Name FROM Account"))
            .and(header("authorization", "Bearer test_token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "totalSize": 4,
                "done": false,
                "nextRecordsUrl": "/services/data/v60.0/query/01gxx-batch2",
                "records": [
                    {"Id": "001xx0000000001", "Name": "Batch1 Rec1"},
                    {"Id": "001xx0000000002", "Name": "Batch1 Rec2"}
                ]
            })))
            .mount(&mock_server)
            .await;

        // Mock second page (query_more)
        Mock::given(method("GET"))
            .and(path("/services/data/v60.0/query/01gxx-batch2"))
            .and(header("authorization", "Bearer test_token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "totalSize": 4,
                "done": true,
                "records": [
                    {"Id": "001xx0000000003", "Name": "Batch2 Rec1"},
                    {"Id": "001xx0000000004", "Name": "Batch2 Rec2"}
                ]
            })))
            .mount(&mock_server)
            .await;

        let client = builder().authenticate(auth).build().await.must();

        // First page
        let page1: QueryResult<TestAccount> = client
            .rest()
            .query("SELECT Id, Name FROM Account")
            .await
            .must();

        assert!(!page1.is_done());
        assert_eq!(page1.len(), 2);
        assert_eq!(page1.records[0].name, "Batch1 Rec1");

        // Second page using query_more
        let page2: QueryResult<TestAccount> = client
            .rest()
            .query_more(page1.next_records_url.as_ref().must())
            .await
            .must();

        assert!(page2.is_done());
        assert_eq!(page2.len(), 2);
        assert_eq!(page2.records[0].name, "Batch2 Rec1");
        assert_eq!(page2.records[1].name, "Batch2 Rec2");
    }

    #[tokio::test]
    async fn test_query_more_full_pagination_loop() {
        let mock_server = MockServer::start().await;
        let auth = MockAuthenticator::new("test_token", &mock_server.uri());

        // Mock first page
        Mock::given(method("GET"))
            .and(path("/services/data/v60.0/query"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "totalSize": 6,
                "done": false,
                "nextRecordsUrl": "/services/data/v60.0/query/batch2",
                "records": [
                    {"Id": "001xx0000000001", "Name": "Record1"},
                    {"Id": "001xx0000000002", "Name": "Record2"}
                ]
            })))
            .mount(&mock_server)
            .await;

        // Mock second page
        Mock::given(method("GET"))
            .and(path("/services/data/v60.0/query/batch2"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "totalSize": 6,
                "done": false,
                "nextRecordsUrl": "/services/data/v60.0/query/batch3",
                "records": [
                    {"Id": "001xx0000000003", "Name": "Record3"},
                    {"Id": "001xx0000000004", "Name": "Record4"}
                ]
            })))
            .mount(&mock_server)
            .await;

        // Mock third (final) page
        Mock::given(method("GET"))
            .and(path("/services/data/v60.0/query/batch3"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "totalSize": 6,
                "done": true,
                "records": [
                    {"Id": "001xx0000000005", "Name": "Record5"},
                    {"Id": "001xx0000000006", "Name": "Record6"}
                ]
            })))
            .mount(&mock_server)
            .await;

        let client = builder().authenticate(auth).build().await.must();

        // Collect all records by manually paginating
        let mut all_records = Vec::new();
        let result: QueryResult<TestAccount> = client
            .rest()
            .query("SELECT Id, Name FROM Account")
            .await
            .must();

        let mut next_url = result.next_records_url.clone();
        all_records.extend(result.records);

        while let Some(url) = next_url {
            let result = client.rest().query_more::<TestAccount>(&url).await.must();
            next_url = result.next_records_url.clone();
            all_records.extend(result.records);
        }

        // Verify we got all 6 records
        assert_eq!(all_records.len(), 6);
        assert_eq!(all_records[0].name, "Record1");
        assert_eq!(all_records[5].name, "Record6");
    }

    #[tokio::test]
    async fn test_query_more_http_error() {
        let mock_server = MockServer::start().await;
        let auth = MockAuthenticator::new("test_token", &mock_server.uri());

        // Mock query_more with 404 error (invalid locator)
        Mock::given(method("GET"))
            .and(path("/services/data/v60.0/query/invalid-locator"))
            .respond_with(ResponseTemplate::new(404).set_body_json(json!([{
                "errorCode": "INVALID_QUERY_LOCATOR",
                "message": "Unable to find query cursor"
            }])))
            .mount(&mock_server)
            .await;

        let client = builder().authenticate(auth).build().await.must();

        let result: Result<QueryResult<TestAccount>, _> = client
            .rest()
            .query_more("/services/data/v60.0/query/invalid-locator")
            .await;

        let Err(err) = result else {
            panic!("expected query_more to fail for invalid locator");
        };
        assert!(
            err.to_string().contains("404") || err.to_string().contains("Query pagination failed")
        );
    }

    #[tokio::test]
    async fn test_query_empty_result() {
        let mock_server = MockServer::start().await;
        let auth = MockAuthenticator::new("test_token", &mock_server.uri());

        Mock::given(method("GET"))
            .and(path("/services/data/v60.0/query"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "totalSize": 0,
                "done": true,
                "records": []
            })))
            .mount(&mock_server)
            .await;

        let client = builder().authenticate(auth).build().await.must();

        let result: QueryResult<TestAccount> = client
            .rest()
            .query("SELECT Id, Name FROM Account WHERE Name = 'NonExistent'")
            .await
            .must();

        assert_eq!(result.total_size, 0);
        assert!(result.is_done());
        assert!(result.is_empty());
        assert_eq!(result.len(), 0);
    }

    #[tokio::test]
    async fn test_query_more_absolute_url() {
        let mock_server = MockServer::start().await;
        let auth = MockAuthenticator::new("test_token", &mock_server.uri());

        // Mock first page
        Mock::given(method("GET"))
            .and(path("/services/data/v60.0/query"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "totalSize": 4,
                "done": false,
                // Absolute URL pointing back to the mock server
                "nextRecordsUrl": format!("{}/services/data/v60.0/query/batch2", mock_server.uri()),
                "records": [
                    {"Id": "001xx0000000001", "Name": "Record1"}
                ]
            })))
            .mount(&mock_server)
            .await;

        // Mock second page
        Mock::given(method("GET"))
            .and(path("/services/data/v60.0/query/batch2"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "totalSize": 4,
                "done": true,
                "records": [
                    {"Id": "001xx0000000002", "Name": "Record2"}
                ]
            })))
            .mount(&mock_server)
            .await;

        let client = builder().authenticate(auth).build().await.must();

        let page1: QueryResult<TestAccount> = client
            .rest()
            .query("SELECT Id, Name FROM Account")
            .await
            .must();

        let next_url = page1.next_records_url.as_ref().must();
        assert!(next_url.starts_with("http")); // Verify it is absolute

        let page2: QueryResult<TestAccount> = client.rest().query_more(next_url).await.must();

        assert_eq!(page2.len(), 1);
        assert_eq!(page2.records[0].name, "Record2");
    }

    #[tokio::test]
    async fn test_query_more_security_check() {
        let mock_server = MockServer::start().await;
        // Instance URL is the mock server
        let auth = MockAuthenticator::new("test_token", &mock_server.uri());
        let client = builder().authenticate(auth).build().await.must();

        // Attempt to query_more with a malicious URL (different host)
        let malicious_url = "https://attacker.com/services/data/v60.0/query/leak_token";

        let result: Result<QueryResult<TestAccount>, _> =
            client.rest().query_more(malicious_url).await;

        let Err(ForceError::InvalidInput(msg)) = result else {
            panic!(
                "Expected ForceError::InvalidInput with security warning, got {:?}",
                result
            );
        };
        assert!(msg.contains("Security Error"));
        assert!(msg.contains("does not match instance origin"));
    }

    #[tokio::test]
    async fn test_query_more_security_check_scheme_mismatch() {
        let mock_server = MockServer::start().await;
        // Instance URL is the mock server (http)
        let auth = MockAuthenticator::new("test_token", &mock_server.uri());
        let client = builder().authenticate(auth).build().await.must();

        let base_url = mock_server.uri();
        let parsed_base = url::Url::parse(&base_url).must();

        // Attempt to query_more with a malicious URL containing a different scheme (https instead of http)
        let malicious_url = format!(
            "https://{}:{}/services/data/v60.0/query/leak_token",
            parsed_base.host_str().must(),
            parsed_base.port_or_known_default().must()
        );

        let result: Result<QueryResult<TestAccount>, _> =
            client.rest().query_more(&malicious_url).await;

        let Err(ForceError::InvalidInput(msg)) = result else {
            panic!(
                "Expected ForceError::InvalidInput with security warning, got {:?}",
                result
            );
        };
        assert!(msg.contains("Security Error"));
        assert!(msg.contains("does not match instance origin"));
    }

    #[tokio::test]
    async fn test_query_more_security_check_username_mismatch() {
        let mock_server = MockServer::start().await;
        // Instance URL is the mock server
        let auth = MockAuthenticator::new("test_token", &mock_server.uri());
        let client = builder().authenticate(auth).build().await.must();

        let base_url = mock_server.uri();
        let parsed_base = url::Url::parse(&base_url).must();

        // Attempt to query_more with a malicious URL containing a username
        let malicious_url = format!(
            "{}://attacker@{}:{}/services/data/v60.0/query/leak_token",
            parsed_base.scheme(),
            parsed_base.host_str().must(),
            parsed_base.port_or_known_default().must()
        );

        let result: Result<QueryResult<TestAccount>, _> =
            client.rest().query_more(&malicious_url).await;

        let Err(ForceError::InvalidInput(msg)) = result else {
            panic!(
                "Expected ForceError::InvalidInput with security warning, got {:?}",
                result
            );
        };
        assert!(msg.contains("Security Error"));
        assert!(msg.contains("does not match instance origin"));
    }

    #[tokio::test]
    async fn test_query_more_security_check_port_mismatch() {
        let mock_server = MockServer::start().await;
        // Instance URL is the mock server
        let auth = MockAuthenticator::new("test_token", &mock_server.uri());
        let client = builder().authenticate(auth).build().await.must();

        let base_url = mock_server.uri();
        let parsed_base = url::Url::parse(&base_url).must();

        // Attempt to query_more with a malicious URL containing a different port
        let malicious_url = format!(
            "{}://{}:9999/services/data/v60.0/query/leak_token",
            parsed_base.scheme(),
            parsed_base.host_str().must()
        );

        let result: Result<QueryResult<TestAccount>, _> =
            client.rest().query_more(&malicious_url).await;

        let Err(ForceError::InvalidInput(msg)) = result else {
            panic!(
                "Expected ForceError::InvalidInput with security warning, got {:?}",
                result
            );
        };
        assert!(msg.contains("Security Error"));
        assert!(msg.contains("does not match instance origin"));
    }

    #[tokio::test]
    async fn test_query_more_security_check_credentials() {
        let mock_server = MockServer::start().await;
        // Instance URL is the mock server
        let auth = MockAuthenticator::new("test_token", &mock_server.uri());
        let client = builder().authenticate(auth).build().await.must();

        let base_url = mock_server.uri();
        let parsed_base = url::Url::parse(&base_url).must();

        // Attempt to query_more with a malicious URL containing credentials
        let malicious_url = format!(
            "{}://attacker:password@{}:{}/services/data/v60.0/query/leak_token",
            parsed_base.scheme(),
            parsed_base.host_str().must(),
            parsed_base.port_or_known_default().must()
        );

        let result: Result<QueryResult<TestAccount>, _> =
            client.rest().query_more(&malicious_url).await;

        let Err(ForceError::InvalidInput(msg)) = result else {
            panic!(
                "Expected ForceError::InvalidInput with security warning, got {:?}",
                result
            );
        };
        assert!(msg.contains("Security Error"));
        assert!(msg.contains("does not match instance origin"));
    }
}