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
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
//! Salesforce API Client
//!
//! This crate provides a client with several authentication types for the Salesforce APIs.
//!
use super::responses::login_error_response::LoginErrorResponse;
use crate::client::responses::access_token::AccessToken;
use crate::client::responses::token_response::TokenResponse;
use crate::client::xml::{create_login_envelope, extract_xml_tag};
use crate::errors::Error;
use log::debug;
use regex::Regex;
use reqwest::header::{AUTHORIZATION, HeaderMap, HeaderName, HeaderValue};
use reqwest::{Response, Url};
use serde::Serialize;
use std::collections::HashMap;
use std::fmt::Debug;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
/// Represents a client used for interacting with a remote API.
/// This struct encapsulates all the necessary data required to authenticate
/// and send HTTP requests to the API.
///
/// # Fields
///
/// * `http_client` - The underlying HTTP client (`reqwest::Client`) used to execute requests.
/// * `client_id` - An optional client ID used for authentication.
/// * `client_secret` - An optional client secret used for authentication.
/// * `login_endpoint` - The URL of the login endpoint used for authenticating requests.
/// * `instance_url` - An optional URL of the API instance to which the client is connected.
/// * `access_token` - An optional access token representing the user session for authenticated requests.
/// * `refresh_token` - An optional refresh token used to obtain a new access token when it expires.
/// * `version` - The version of the API being used.
/// * `secret_required` - A boolean value indicating whether the client secret is mandatory for authentication.
///
/// # Derive Attributes
///
/// * `Clone` - Enables creating a deep copy of the `Client`.
/// * `Debug` - Enables formatting a debugging representation of the `Client`.
///
/// # Usage
///
/// This struct is designed to facilitate authenticated communication with an API.
/// Use it to configure connection settings, store authentication tokens,
/// and manage HTTP request creation.
///
/// Example usage may include setting up the client with credentials, defining the
/// API endpoint, and invoking authenticated API calls with the underlying HTTP client.
///
/// # Example
/// ```rust
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
///
/// // Configure authentication credentials, e.g.:
/// client.set_client_id("client_Id");
/// client.set_client_secret("client_secret");
/// match client.login_with_credential("username", "password").await {
/// Ok(_) => println!("Login successful!"),
/// Err(e) => println!("Login failed: {}", e),
/// }
/// // ... other logic ...
/// Ok(())
/// }
/// ```
///
/// # Note
///
/// Ensure that sensitive fields like `client_secret` and `access_token` are handled securely
/// to avoid unintended exposure of confidential data.
#[derive(Clone, Debug)]
pub struct Client {
pub(crate) http_client: reqwest::Client,
pub(crate) client_id: Option<String>,
pub(crate) client_secret: Option<String>,
pub(crate) login_endpoint: String,
pub(crate) instance_url: Option<String>,
pub(crate) access_token: Option<AccessToken>,
pub(crate) refresh_token: Option<String>,
pub(crate) version: String,
pub(crate) secret_required: bool,
pub(crate) organisation_id: Option<String>,
pub(crate) user_id: Option<String>,
}
impl Default for Client {
fn default() -> Self {
Client::new()
}
}
impl Client {
/// Creates a new `Client` instance with default configuration.
///
/// This function initializes a `Client` with the following default properties:
/// - A new `reqwest::Client` instance for making HTTP requests.
/// - `client_id`: `None`
/// - `client_secret`: `None`
/// - `login_endpoint`: Set to `"https://login.salesforce.com"`.
/// - `access_token`: `None`
/// - `instance_url`: `None`
/// - `refresh_token`: `None`
/// - `secret_required`: Set to `true`.
/// - `version`: Set to `"v60.0"`.
///
/// # Returns
/// A configured `Client` instance ready for use.
///
/// # Examples
/// ```
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// // Authentication logic...
/// Ok(())
/// }
/// ```
pub fn new() -> Client {
let http_client = reqwest::Client::new();
Client {
http_client,
client_id: None,
client_secret: None,
login_endpoint: "https://login.salesforce.com".to_string(),
access_token: None,
instance_url: None,
refresh_token: None,
secret_required: true,
version: "v60.0".to_string(),
organisation_id: None,
user_id: None,
}
}
// --- Read-only getters ---
/// Retrieves the client ID associated with the current object, if it exists.
///
/// # Returns
/// - `Option<&str>`:
/// - `Some(&str)` containing the reference to the client ID if it is present.
/// - `None` if the client ID is not set.
///
/// # Example
/// ```rust
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// // ... set client ID and other fields ...
/// let client_id = client.client_id();
/// Ok(())
/// }
/// ```
///
/// This method allows for safely accessing the client ID without taking ownership of the value.
pub fn client_id(&self) -> Option<&str> {
self.client_id.as_deref()
}
/// Retrieves the client secret as an optional reference to a string slice.
///
/// # Returns
/// - `Some(&str)` if the `client_secret` field is set in the struct.
/// - `None` if the `client_secret` field is `None`.
///
/// This method allows safe access to the client secret without consuming the value.
///
/// # Example
/// ```rust
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// // Authentication logic...
/// let client_id = client.client_secret();
/// Ok(())
/// }
/// ```
pub fn client_secret(&self) -> Option<&str> {
self.client_secret.as_deref()
}
/// Returns the login endpoint URL as a string slice.
///
/// # Example
/// ```rust
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// // Authentication logic...
/// let endpoint = client.login_endpoint();
/// assert_eq!(endpoint, "https://login.salesforce.com");
/// Ok(())
/// }
/// ```
///
/// # Returns
/// * `&str` - A reference to the login endpoint URL.
pub fn login_endpoint(&self) -> &str {
&self.login_endpoint
}
/// Retrieves the instance URL as an optional string slice.
///
/// This function returns the value of `instance_url` if it is present,
/// or `None` if the value is absent.
///
/// # Returns
///
/// - `Some(&str)` if `instance_url` contains a value.
/// - `None` if `instance_url` is `None`.
///
/// # Examples
///
/// ```
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// // Authentication logic...
/// let endpoint = client.instance_url();
/// Ok(())
/// }
/// ```
pub fn instance_url(&self) -> Option<&str> {
self.instance_url.as_deref()
}
pub fn validated_base_url(&self) -> Result<String, Error> {
let instance_url = self.instance_url.as_ref().ok_or(Error::NotLoggedIn)?;
Ok(format!("{}/services/data/", instance_url))
}
/// Retrieves a reference to the `AccessToken` if it exists.
///
/// # Returns
///
/// - `Some(&AccessToken)` - A reference to the `AccessToken` if it is available.
/// - `None` - If the `access_token` is not set.
///
/// This method provides a way to access the `AccessToken` field of the
/// struct without taking ownership of it. It is useful when you want
/// to inspect or work with the token without modifying the struct.
///
/// # Examples
///
/// ```rust
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// // Authentication logic...
/// let token = client.access_token();
/// Ok(())
/// }
/// ```
pub fn access_token(&self) -> Option<&AccessToken> {
self.access_token.as_ref()
}
/// Retrieves the value of the access token, if it exists.
///
/// This method accesses the `access_token` field of the struct and extracts its
/// `value` as a string slice. If the `access_token` is `None`, this method will
/// return `None`.
///
/// # Returns
/// * `Option<&str>` - `Some(&str)` containing the value of the access token if it exists,
/// or `None` if the `access_token` is not present.
///
/// # Example
/// ```rust
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// // Authentication logic...
/// let token_value = client.access_token_value();
/// Ok(())
/// }
/// ```
pub fn access_token_value(&self) -> Option<&str> {
self.access_token.as_ref().map(|t| t.value.as_str())
}
/// Returns the version of the current instance.
///
/// # Returns
/// A string slice that holds the version information.
///
/// # Examples
/// ```
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// // Authentication logic...
/// assert_eq!(client.version(), "v60.0");
/// Ok(())
/// }
/// ```
pub fn version(&self) -> &str {
&self.version
}
/// Returns an optional reference to the refresh token.
///
/// This method provides a way to retrieve the refresh token, returning it as an
/// `Option<&str>`. If a refresh token exists within the structure, it is returned
/// as a `Some(&str)`; otherwise, `None` is returned.
///
/// # Returns
/// - `Some(&str)` if the refresh token is present.
/// - `None` if the refresh token is absent.
///
/// # Example
/// ```rust
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// // Authentication logic...
/// let token = client.refresh_token();
/// Ok(())
/// }
/// ```
pub fn refresh_token(&self) -> Option<&str> {
self.refresh_token.as_deref()
}
/// Constructs the base path URL for the API, incorporating the instance URL and version.
///
/// # Returns
///
/// - `Ok(String)` containing the formatted base path URL if the `instance_url` is available.
/// - `Err(Error::NotLoggedIn)` if the `instance_url` is not set.
///
/// # Errors
///
/// Returns an error of type `Error::NotLoggedIn` if the user is not logged in and the `instance_url`
/// is unavailable.
///
/// # Example
///
/// ```rust
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// // Authentication logic...
/// match client.base_version_path() {
/// Ok(base_path) => println!("Base path: {}", base_path),
/// Err(e) => println!("Error: {}", e),
/// }
/// Ok(())
/// }
/// ```
///
/// # Note
///
/// This method assumes that `version` is a valid string and does not perform validation on it.
pub fn base_version_path(&self) -> Result<String, Error> {
let instance_url = self.instance_url.as_ref().ok_or(Error::NotLoggedIn)?;
Ok(format!("{}/services/data/{}", instance_url, self.version))
}
pub fn base_path(&self) -> Result<String, Error> {
let instance_url = self.instance_url.as_ref().ok_or(Error::NotLoggedIn)?;
Ok(format!("{}/services/data/", instance_url))
}
// --- Setters ---
/// Sets the login endpoint for the current instance.
///
/// This method allows you to specify a custom login endpoint URL
/// for the object. It internally converts the provided string slice (`&str`)
/// into a `String` and assigns it to the `login_endpoint` field.
///
/// # Arguments
///
/// * `endpoint` - A string slice that specifies the login endpoint URL to be set.
///
/// # Returns
///
/// A mutable reference to the current instance, allowing method chaining.
///
/// # Example
///
/// ```rust
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// client.set_login_endpoint("https://test.salesforce.com/login");
/// // rest of authentication logic...
/// Ok(())
/// }
/// ```
pub fn set_login_endpoint(&mut self, endpoint: &str) -> &mut Self {
self.login_endpoint = endpoint.to_string();
self
}
/// Sets the version for the current instance.
///
/// This method updates the `version` field of the struct to the provided string.
/// It consumes a string slice, converts it to a `String`, and assigns it to the
/// instance's `version` field.
///
/// # Parameters
/// - `version`: A string slice representing the new version to be set.
///
/// # Returns
/// A mutable reference to the current instance, allowing for method chaining.
///
/// # Example
/// ```rust
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// // Authentication logic...
/// client.set_version("v65.0");
/// Ok(())
/// }
/// ```
pub fn set_version(&mut self, version: &str) -> &mut Self {
self.version = version.to_string();
self
}
/// Sets the instance URL for the current object.
///
/// This method allows you to set the `instance_url` field of the object to the specified
/// URL string. The provided URL is converted into an owned `String` and stored inside
/// the object. The method then returns a mutable reference to the current object,
/// allowing for method chaining.
///
/// # Arguments
///
/// * `instance_url` - A string slice that represents the URL to be set.
///
/// # Returns
///
/// A mutable reference to the current object (`&mut Self`) to enable method chaining.
///
/// # Example
///
/// ```rust
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// client.set_instance_url("https://develop.sandbox.mu.salesforce.com");
/// // Authentication logic...
/// Ok(())
/// }
/// ```
pub fn set_instance_url(&mut self, instance_url: &str) -> &mut Self {
self.instance_url = Some(instance_url.to_string());
self
}
/// Sets the refresh token for the current instance.
///
/// This method takes a string slice representing a refresh token,
/// converts it to a `String`, and assigns it to the `refresh_token` field
/// of the struct. After setting the value, it returns a mutable reference
/// to `self`, allowing method chaining.
///
/// # Arguments
///
/// * `refresh_token` - A string slice representing the refresh token to be set.
///
/// # Returns
///
/// * `&mut Self` - A mutable reference to the current instance, enabling method chaining.
///
/// # Example
///
/// ```rust
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// client.set_refresh_token("new_refresh_token");
/// Ok(())
/// }
/// ```
pub fn set_refresh_token(&mut self, refresh_token: &str) -> &mut Self {
self.refresh_token = Some(refresh_token.to_string());
self
}
/// Sets whether a secret is required for the entity and returns a mutable reference to the instance.
///
/// # Parameters
/// - `secret_required`: A boolean value indicating whether the entity requires a secret.
/// - `true`: A secret is required.
/// - `false`: A secret is not required.
///
/// # Returns
/// A mutable reference to the current instance of the object, enabling method chaining.
///
/// # Example
/// ```rust
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// // Authentication logic...
/// client.set_secret_required(true);
/// Ok(())
/// }
/// ```
pub fn set_secret_required(&mut self, secret_required: bool) -> &mut Self {
self.secret_required = secret_required;
self
}
/// Sets the client ID for the instance.
///
/// This method allows you to assign a client ID to the current instance.
/// The provided string reference is converted into an owned `String` and
/// stored internally. It returns a mutable reference to the instance,
/// allowing for method chaining.
///
/// # Arguments
///
/// * `client_id` - A string slice that holds the client ID to be set.
///
/// # Returns
///
/// * A mutable reference to the current instance (`Self`), enabling method chaining.
///
/// # Example
///
/// ```rust
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// client.set_client_id("client_id");
/// Ok(())
/// }
/// // Rest of authentication logic...
/// ```
pub fn set_client_id(&mut self, client_id: &str) -> &mut Self {
self.client_id = Some(client_id.to_string());
self
}
/// Sets the client secret for the current instance.
///
/// This method allows you to set the client secret, which is typically
/// used for authentication purposes or identifying the client in API requests.
///
/// # Arguments
///
/// * `client_secret` - A string slice containing the client secret to be set.
///
/// # Returns
///
/// Returns a mutable reference to the current instance, allowing method
/// chaining.
///
/// # Example
///
/// ```rust
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// client.set_client_secret("client_secret");
/// Ok(())
/// }
/// ```
pub fn set_client_secret(&mut self, client_secret: &str) -> &mut Self {
self.client_secret = Some(client_secret.to_string());
self
}
/// Sets the access token for the current instance.
///
/// This function updates the access token along with its type and issuance time.
/// It allows method chaining by returning a mutable reference to the instance.
///
/// # Arguments
///
/// * `access_token` - A `String` containing the access token value.
/// * `issued_at` - A `String` representing the time at which the token was issued.
/// * `token_type` - A `String` denoting the type of the token, e.g., "Bearer".
///
/// # Returns
///
/// A mutable reference to the current instance (`&mut Self`), enabling method chaining.
///
/// # Example
///
/// ```rust
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// client.set_access_token("abc123".to_string(), "2023-01-01T00:00:00Z".to_string(), "Bearer".to_string());
/// Ok(())
/// }
/// ```
///
/// This sets the access token, token type, and issuance time for the client.
pub fn set_access_token(
&mut self,
access_token: String,
issued_at: String,
token_type: String,
) -> &mut Self {
self.access_token = Some(AccessToken {
token_type,
value: access_token,
issued_at,
});
self
}
/// Asynchronously retrieves the identity from the provided URL.
///
/// This function sends a GET request to the specified `identity_url`
/// without any additional headers. If the response has a successful
/// status code, the response body is returned as a `String`. Otherwise,
/// an error is returned, containing a detailed description of the
/// failure.
///
/// # Arguments
///
/// * `identity_url` - A `String` containing the URL to fetch the identity from.
///
/// # Returns
///
/// * `Result<String, Error>` - Returns `Ok(String)` containing the response body if the
/// request was successful, or `Err(Error)` if an error occurred.
///
/// # Errors
///
/// This function returns an error in these cases:
/// - If the HTTP GET request fails.
/// - If the response status is not successful.
/// - If there is an issue reading or parsing the response body.
///
/// # Example
///
/// ```rust
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// // Authentication logic...
/// let identity_url = client.get_identity("identity_url".to_string()).await;
/// Ok(())
/// }
/// ```
///
/// # Dependencies
///
/// This function depends on the `get` method of the client object and assumes that:
/// * The `get` method takes a URL and headers as parameters.
/// * The `res` object has `status`, `text`, and `json` methods, where:
/// - `status()` returns the status of the response.
/// - `text().await` retrieves the response body as a `String`.
/// - `json().await` deserializes the response body into an error description.
pub async fn get_identity(&mut self, identity_url: String) -> Result<String, Error> {
let res = self.get(identity_url, vec![], vec![]).await?;
if res.status().is_success() {
Ok(res.text().await?)
} else {
Err(Error::DescribeError(res.json().await?))
}
}
pub fn get_user_id(&self) -> Option<&str> {
self.user_id.as_deref()
}
/// Asynchronously ensures that the access token is refreshed if it has expired or
/// if it cannot be parsed for comparison.
///
/// # Behavior
/// - If `self.access_token` is `None`, this function does nothing and returns `Ok(self)`.
/// - If the `issued_at` timestamp of the `access_token` cannot be parsed as a Unix
/// timestamp (milliseconds since epoch), the function will attempt to refresh
/// the access token immediately.
/// - If the `issued_at` timestamp is successfully parsed and the corresponding access token
/// is still valid (within 2 hours of being issued), no action is taken.
/// - If the access token has expired (2 hours past the `issued_at` time), the function
/// will attempt to refresh the token.
///
/// # Returns
/// - `Ok(&mut Self)` if the access token is valid or successfully refreshed.
/// - `Err(Error)` if there is an error during the refresh process.
///
/// # Logs
/// - Logs an informational message if the `issued_at` timestamp cannot be parsed.
/// - Logs an informational message if the access token has expired and a refresh is attempted.
///
/// # Errors
/// Returns an `Error` if the refresh operation fails.
///
/// # Examples
/// ```rust
/// use rustsf::{Client, Error};
///
/// async fn example() -> Result<(), Error> {
/// let mut client = Client::new();
/// client.ensure_refresh().await?;
/// Ok(())
/// }
/// ```
pub async fn ensure_refresh(&mut self) -> Result<&mut Self, Error> {
if self.access_token.is_none() {
return Ok(self);
}
let issued_at = &self.access_token.as_ref().unwrap().issued_at;
let timestamp_ms = match issued_at.parse::<u64>() {
Ok(ts) => ts,
Err(_) => {
// SOAP login returns ISO timestamp; can't compare, attempt refresh
log::info!("Could not parse issued_at as timestamp, attempting refresh.");
return self.refresh().await;
}
};
let seconds = timestamp_ms / 1000;
let nanos = (timestamp_ms % 1000) * 1_000_000;
let given_time = UNIX_EPOCH + Duration::new(seconds, nanos as u32);
let two_hours = Duration::from_secs(2 * 60 * 60); // 2 hours in seconds
let modified_time = given_time + two_hours;
let current_time = SystemTime::now();
if current_time > modified_time {
log::info!("Access Token Expired, Refreshing.");
Ok(self.refresh().await?)
} else {
Ok(self)
}
}
/// Generates a vector of key-value pairs representing parameters
/// required for a token refresh request.
///
/// # Returns
///
/// A `Vec` of tuples where each tuple contains:
/// - A `String` representing the parameter name.
/// - A `String` representing the parameter value.
///
/// The parameters include:
/// - `"grant_type"`: Always set to `"refresh_token"`.
/// - `"refresh_token"`: The `refresh_token` value (empty if not provided).
/// - `"client_id"`: The `client_id` value (empty if not provided).
///
/// If the `secret_required` field is `true`, the following parameter is also included:
/// - `"client_secret"`: The `client_secret` value (empty if not provided).
///
/// # Example
///
/// ```rust, ignore
/// let params = client.get_refresh_params();
/// for (key, value) in params {
/// println!("{}: {}", key, value);
/// }
/// ```
///
/// This function ensures that default values are used if any of the required
/// fields (`refresh_token`, `client_id`, `client_secret`) are not set.
fn get_refresh_params(&self) -> Vec<(String, String)> {
let refresh_token = self.refresh_token.clone().unwrap_or_default();
let client_id = self.client_id.clone().unwrap_or_default();
let mut params = vec![
("grant_type".to_string(), "refresh_token".to_string()),
("refresh_token".to_string(), refresh_token),
("client_id".to_string(), client_id),
];
if self.secret_required {
params.push((
"client_secret".to_string(),
self.client_secret.clone().unwrap_or_default(),
));
}
params
}
/// Refreshes the authentication token using the refresh token flow.
///
/// This asynchronous function performs the following steps:
/// 1. Constructs a token endpoint URL using the `login_endpoint`.
/// 2. Retrieves the required parameters for token refresh using `get_refresh_params()`.
/// 3. Sends an HTTP POST request with the parameters to the token endpoint.
/// 4. Processes the response:
/// - If the HTTP request fails, an error is returned.
/// - If the response status is not successful, it attempts to parse
/// and return a token-specific error.
/// - If the response is successful, it parses the token response,
/// updates the current access token, sets the token issuance time,
/// token type, and updates the instance URL.
///
/// # Returns
/// - `Ok(&mut Self)` if the token has been successfully refreshed.
/// - `Err(Error)` if the token refresh fails due to an HTTP error,
/// a server-side error, or an unexpected response structure.
///
/// # Errors
/// Returns an `Error` in the following cases:
/// - HTTP transmission error during the token refresh request.
/// - Unsuccessful HTTP response due to invalid credentials or other
/// server-side errors.
/// - Failure to parse the error or token response JSON into the
/// appropriate data structures.
///
/// # Example
/// ```rust
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// // Authentication logic...
/// match client.refresh().await {
/// Ok(updated_client) => {
/// println!("Token refreshed successfully!");
/// },
/// Err(e) => {
/// eprintln!("Failed to refresh token: {:?}", e);
/// }
/// }
/// Ok(())
/// }
/// ```
///
/// # Dependencies
/// - This function expects that the struct has an `http_client` field
/// capable of making asynchronous HTTP requests (e.g., an instance of `reqwest::Client`).
/// - The function assumes the existence of `get_refresh_params`, `set_access_token`,
/// and other utility methods within the struct to handle token management.
pub async fn refresh(&mut self) -> Result<&mut Self, Error> {
/// Extracts the Salesforce organization id and user idL.
///
/// Example: `https://login.salesforce.com/id/00D50000000IZ3ZEAW/00550000001fg5OAAQ`
fn extract_organisation_and_user_id(url: &str) -> Option<(String, String)> {
let path = url.split_once("/id/")?.1;
let mut parts = path.split('/');
let organisation_id = parts.next()?.trim();
let user_id = parts.next()?.trim();
if organisation_id.is_empty() || user_id.is_empty() {
return None;
}
Some((organisation_id.to_string(), user_id.to_string()))
}
let token_url = format!("{}/services/oauth2/token", self.login_endpoint);
let params = self.get_refresh_params();
let res = self
.http_client
.post(token_url.as_str())
.form(¶ms)
.send()
.await;
let res = match res {
Ok(res) => res,
Err(e) => return Err(e.into()),
};
if !res.status().is_success() {
let error_response = res.json().await?;
return Err(Error::TokenError(error_response));
}
let response: TokenResponse = res.json().await?;
let token_type = response.token_type.unwrap_or_default();
self.set_access_token(response.access_token, response.issued_at, token_type);
self.instance_url = Some(response.instance_url);
match extract_organisation_and_user_id(response.id.as_str()) {
Some((org_id, user_id)) => {
self.organisation_id = Some(org_id);
self.user_id = Some(user_id);
}
None => {
log::warn!("Could not extract organisation and user ID from token response.");
}
}
Ok(self)
}
/// Logs in using the provided username and password credentials,
/// retrieves an access token from the OAuth2 token endpoint,
/// and updates the internal client state.
///
/// # Arguments
///
/// - `username`: A string slice containing the user's username.
/// - `password`: A string slice containing the user's password.
///
/// # Returns
///
/// Returns:
/// - `Ok(&mut Self)` if the login and token retrieval are successful, allowing method chaining.
/// - `Err(Error)` if there are any configuration issues, HTTP request errors, or unsuccessful responses.
///
/// # Errors
///
/// The function can return the following errors:
/// - `ConfigError`: If `client_id` or `client_secret` is not configured.
/// - `HttpError`: If there is an issue with the HTTP request, such as network failure.
/// - `TokenError`: If the server returns an unsuccessful response, e.g., invalid credentials.
///
/// # Example
///
/// ```rust
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// client.set_client_id("example_client_id");
/// client.set_client_secret("example_client_secret");
///
/// let result = client.login_with_credential("username", "password").await;
/// match result {
/// Ok(client) => println!("Login successful!"),
/// Err(e) => eprintln!("Login failed: {:?}", e),
/// }
/// Ok(())
/// }
/// ```
///
/// # Behavior
///
/// - Constructs a token request URL based on the configured `login_endpoint`.
/// - Validates the presence of `client_id` and `client_secret` configurations.
/// - Sends an HTTP POST request with the required parameters to fetch an access token.
/// - Upon a successful response:
/// - Updates the internal client state with the access token, token type, issue timestamp, and instance URL.
/// - On error, the function returns a descriptive `Error` for troubleshooting.
///
/// # Notes
///
/// - Ensure that the `client_id` and `client_secret` are set before calling this method.
/// - The function uses the `reqwest` library for HTTP requests and assumes the `http_client` is properly initialized.
pub async fn login_with_credential(
&mut self,
username: &str,
password: &str,
) -> Result<&mut Self, Error> {
let token_url = format!("{}/services/oauth2/token", self.login_endpoint);
let client_id = self
.client_id
.as_ref()
.ok_or_else(|| Error::ConfigError("client_id is required".to_string()))?;
let client_secret = self
.client_secret
.as_ref()
.ok_or_else(|| Error::ConfigError("client_secret is required".to_string()))?;
let params = [
("grant_type", "password"),
("client_id", client_id.as_str()),
("client_secret", client_secret.as_str()),
("username", username),
("password", password),
];
let res = self
.http_client
.post(token_url.as_str())
.form(¶ms)
.send()
.await?;
if !(res.status().is_success()) {
let error_response = res.json().await?;
return Err(Error::TokenError(error_response));
}
let response: TokenResponse = res.json().await?;
let token_type = response.token_type.unwrap_or_default();
self.set_access_token(response.access_token, response.issued_at, token_type);
self.instance_url = Some(response.instance_url);
Ok(self)
}
/// Asynchronously log in to Salesforce using an SFDX Auth URL.
///
/// This method allows the user to authenticate with Salesforce by parsing an SFDX authentication URL,
/// extracting the necessary credentials, and exchanging the refresh token for an access token.
///
/// # Parameters
/// - `sfdx_auth_url`: A `&str` containing the SFDX authentication URL. The format of the auth URL must
/// match the pattern:
/// `force://<client_id>:<client_secret>:<refresh_token>@<login_endpoint>`.
///
/// # Returns
/// - On success, this function returns a mutable reference to the `Self` instance wrapped in a
/// `Result::Ok`. The `Self` instance will have the `access_token` and `instance_url` fields updated
/// with the authentication response.
/// - On failure, an `Error` is returned, which can indicate issues like errors during the token fetch
/// process or invalid credentials.
///
/// # Errors
/// - Returns `Error::NotLoggedIn` if the response from Salesforce does not include a valid `token_type`.
/// - Returns `Error::TokenError` if the Salesforce token service responds with an error payload.
/// - Returns other `Error` variants if the HTTP request fails or is invalid.
///
/// # Example
/// ```rust
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let sfdx_auth_url = "force://your_client_id:your_secret_token:your_refresh_token@your.login.endpoint";
/// let mut client = Client::new();
///
/// match client.login_with_sfdx_auth_url(sfdx_auth_url).await {
/// Ok(_) => {
/// println!("Successfully logged in!");
/// },
/// Err(e) => {
/// eprintln!("Failed to log in: {:?}", e);
/// }
/// }
/// Ok(())
/// }
/// ```
///
/// # Details
/// - The function utilizes a regular expression to extract credentials from the `sfdx_auth_url`.
/// - It uses an HTTP POST request to exchange the refresh token for an access token via Salesforce's
/// OAuth2 token endpoint.
/// - The response, if successful, updates the following fields of the `Self` instance:
/// - `access_token`: Contains the access token and associated metadata.
/// - `instance_url`: Contains the base URL of the Salesforce instance.
///
/// # Dependencies
/// - This function uses the `regex` crate for regular expression handling.
/// - The `reqwest` crate is used for making the HTTP POST request.
///
/// # Notes
/// - Ensure that the `sfdx_auth_url` provided is valid and has the expected format.
/// - This function relies on async/await for non-blocking execution. It must be used within an
/// async runtime.
pub async fn login_with_sfdx_auth_url(
&mut self,
sfdx_auth_url: &str,
) -> Result<&mut Self, Error> {
let re = Regex::new(r"force://([a-zA-Z0-9._-]+):([a-zA-Z0-9._-]*):([a-zA-Z0-9._-]+={0,2})@([a-zA-Z0-9._-]+)").unwrap();
let caps = re.captures(&sfdx_auth_url).unwrap();
self.set_client_id(&caps[1]);
self.set_client_secret(&caps[2]);
self.set_refresh_token(&caps[3]);
self.set_login_endpoint(&caps[4]);
let token_url = format!("https://{}/services/oauth2/token", self.login_endpoint);
println!("token_url: {}", token_url);
let params = [
("grant_type", "refresh_token"),
("client_id", self.client_id.as_ref().unwrap()),
("refresh_token", self.refresh_token.as_ref().unwrap()),
];
let res = self
.http_client
.post(token_url.as_str())
.form(¶ms)
.send()
.await?;
if res.status().is_success() {
let r: TokenResponse = res.json().await?;
self.access_token = Some(AccessToken {
value: r.access_token,
issued_at: r.issued_at,
token_type: r.token_type.ok_or(Error::NotLoggedIn)?,
});
self.instance_url = Some(r.instance_url);
match self.extract_organisation_and_user_id(r.id.as_str()) {
Some((org_id, user_id)) => {
self.organisation_id = Some(org_id);
self.user_id = Some(user_id);
}
None => {
log::warn!("Could not extract organisation and user ID from token response.");
}
}
Ok(self)
} else {
let error_response = res.json().await?;
Err(Error::TokenError(error_response))
}
}
fn extract_organisation_and_user_id(&self, url: &str) -> Option<(String, String)> {
let path = url.split_once("/id/")?.1;
let mut parts = path.split('/');
let organisation_id = parts.next()?.trim();
let user_id = parts.next()?.trim();
if organisation_id.is_empty() || user_id.is_empty() {
return None;
}
Some((organisation_id.to_string(), user_id.to_string()))
}
/// Asynchronously performs a login process using a SOAP API and updates the client instance
/// with the retrieved access token and instance URL.
///
/// # Arguments
///
/// - `username`: A reference to a string slice representing the username
/// to authenticate with.
/// - `password`: A reference to a string slice representing the password
/// associated with the username.
///
/// # Returns
///
/// Returns a `Result`:
/// - On success, it returns `Ok(&mut Self)`, where the instance is updated with
/// the `access_token` and `instance_url` obtained from the SOAP response.
/// - On failure, it returns `Err(Error)`, where `Error` contains information about
/// the login error, such as the error message and error code.
///
/// # Errors
///
/// This function will return an error if:
/// - The HTTP request fails.
/// - The SOAP API responds with an unsuccessful status code.
/// - The expected XML tags (`sessionId`, `serverTimestamp`, `serverUrl`, etc.)
/// are not present in the response.
///
/// # SOAP API Details
///
/// - The SOAP endpoint URL is constructed using the `self.login_endpoint`
/// and `self.version`, formatted as `{login_endpoint}/services/Soap/u/{version}`.
/// - The SOAP envelope containing the login request is generated by the
/// `create_login_envelope` function.
/// - Relevant details such as the session token (`sessionId`) and instance URL
/// (`serverUrl`) are extracted from the SOAP response using the `extract_xml_tag`
/// utility.
///
/// # Example
///
/// ```rust,ignore
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// let result = client.login_with_soap("username", "password").await;
/// match result {
/// Ok(updated_client) => {
/// println!("Login successful.");
/// println!("Access Token: {:?}", updated_client.access_token);
/// println!("Instance URL: {:?}", updated_client.instance_url);
/// }
/// Err(e) => {
/// eprintln!("Login failed: {:?}", e);
/// }
/// }
/// Ok(())
/// }
/// ```
///
/// # Notes
///
/// - Ensure that the input SOAP envelope and the response XML structure
/// conform to the expected SOAP API specification.
/// - If the `access_token` cannot be extracted from the response,
/// the `access_token` field will remain `None` in the updated client instance.
///
/// # Dependencies
///
/// - An HTTP client that supports asynchronous operations is required, e.g.,
/// `reqwest`.
/// - XML parsing utilities (e.g., `extract_xml_tag`) must be able to handle
/// the relevant tags properly in the SOAP response.
///
/// # Associated Types
///
/// - This function leverages an `AccessToken` struct, which contains
/// fields like `value` (session token), `issued_at` (server timestamp),
/// and `token_type` ("Bearer" by default).
///
/// # See Also
///
/// - `create_login_envelope` for generating the required SOAP envelope.
///
/// - `extract_xml_tag` for parsing specific XML tags from the response.
///
/// - `Error::LoginError` for understanding the structure of login errors.
///
/// # Deprecated
/// The use of login by SOAP is deprecated by Salesforce and should be avoided
#[deprecated(
since = "0.0.1",
note = "The use of login by SOAP is deprecated by Salesforce and should be avoided"
)]
pub async fn login_with_soap(
&mut self,
username: &str,
password: &str,
) -> Result<&mut Self, Error> {
let token_url = format!("{}/services/Soap/u/{}", self.login_endpoint, self.version);
let body = create_login_envelope(username, password);
let res = self
.http_client
.post(token_url.as_str())
.body(body)
.header("Content-Type", "text/xml")
.header("SOAPAction", "\"\"")
.send()
.await?;
if res.status().is_success() {
let body_response = res.text().await?;
self.access_token = match extract_xml_tag("sessionId", body_response.as_str()) {
Some(t) => {
let issued_at = extract_xml_tag("serverTimestamp", body_response.as_str())
.unwrap_or_default();
Some(AccessToken {
value: t,
issued_at,
token_type: "Bearer".to_string(),
})
}
None => None,
};
self.instance_url = extract_xml_tag("serverUrl", body_response.as_str());
Ok(self)
} else {
let body_response = res.text().await?;
let error_message =
extract_xml_tag("faultstring", body_response.as_str()).unwrap_or_default();
let error_code =
extract_xml_tag("faultcode", body_response.as_str()).unwrap_or_default();
Err(Error::LoginError(LoginErrorResponse {
message: error_message,
error_code,
}))
}
}
/// Asynchronously performs an HTTP GET request to a specified Apex REST endpoint using a full URI.
///
/// # Parameters
/// - `uri`: A string slice representing the relative path or endpoint of the resource to be accessed.
///
/// # Returns
/// - `Result<Response, Error>`:
/// - On success, returns a `Response` containing the result of the GET request.
/// - On failure, returns an `Error` indicating the reason for failure:
/// - `Error::NotLoggedIn`: If the `instance_url` field is not available (user is not logged in).
/// - `Error::ConfigError`: If the generated URL for the request is invalid.
///
/// # Description
/// This function constructs the full URL for the requested resource by combining the base
/// `instance_url` (from the current state) with the provided `uri` parameter. It validates
/// the resulting URL and extracts query parameters for the request. The function then delegates
/// the constructed path and parameters to the `rest_get` method, which executes the actual GET request.
///
/// The following steps are performed:
/// 1. Combine the base `instance_url` and `uri` to generate the full resource URL.
/// 2. Parse the URL to verify its validity and extract query parameters.
/// 3. Convert query parameters into suitable format for internal processing.
/// 4. Extract the URL path and invoke `rest_get` with the path and query parameters.
///
/// # Errors
/// - Returns `Error::NotLoggedIn` if no `instance_url` is available in the current context.
/// - Returns `Error::ConfigError` if URL parsing fails due to an invalid format.
///
/// # Example
/// ```rust
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// // Authentication logic...
/// match client.rest_get_fulluri("my/resource/endpoint").await {
/// Ok(response) => println!("Response: {:?}", response),
/// Err(e) => println!("Error: {:?}", e),
/// }
/// Ok(())
/// }
/// ```
///
/// # Notes
/// The function assumes that the `self.rest_get` method is implemented to handle the GET request
/// based on the extracted path and parameters.
pub async fn rest_get_fulluri(&mut self, uri: &str) -> Result<Response, Error> {
let resource_url = format!(
"{}/services/apexrest/{}",
self.instance_url.as_ref().ok_or(Error::NotLoggedIn)?,
uri
);
let parsed = Url::parse(&resource_url)
.map_err(|e| Error::ConfigError(format!("Invalid URL: {}", e)))?;
// Some ownership absurdity for string refs accessed through iterators with collect
let hash_query: HashMap<_, _> = parsed.query_pairs().into_owned().collect();
let params_string: Vec<(String, String)> = hash_query
.keys()
.map(|k| (String::from(k), String::from(&hash_query[k])))
.collect();
let params: Vec<(&str, &str)> = params_string
.iter()
.map(|(x, y)| (&x[..], &y[..]))
.collect();
let path: String = parsed.path().to_string();
self.rest_get(path, params).await
}
/// Asynchronously performs an HTTP GET request to a specified REST API endpoint.
///
/// # Arguments
///
/// * `path` - A `String` representing the relative path of the endpoint to be queried on the server.
/// * `params` - A `Vec` of key-value tuples (`&str`, `&str`) representing query parameters to be appended to the URL.
///
/// # Returns
///
/// * `Result<Response, Error>` -
/// - On success: Returns an `Ok(Response)` containing the HTTP response.
/// - On failure: Returns an `Err(Error)` indicating the reason for failure.
///
/// # Errors
///
/// This function may return errors in the following scenarios:
/// * `Error::NotLoggedIn` - If the `instance_url` is not set, indicating the user is not logged in.
/// * Errors originating from HTTP client operations, such as issues while creating headers, sending the request, or ensuring token refresh.
///
/// # Example
///
/// ```rust
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// // Authentication logic...
/// let path = String::from("/api/v1/data");
/// let params = vec![("key", "value"), ("filter", "recent")];
/// let response = client.rest_get(path, params).await;
///
/// match response {
/// Ok(res) => {
/// println!("Response received: {:?}", res);
/// }
/// Err(e) => {
/// eprintln!("Error occurred: {:?}", e);
/// }
/// }
/// Ok(())
/// }
/// ```
///
/// # Notes
///
/// This function ensures that the client's authentication tokens are refreshed before sending the request.
/// It constructs the full URL by concatenating the `instance_url` and the provided `path`. Query parameters are appended to the URL as needed.
///
/// This function assumes you have an internal configuration for `http_client` and a means to handle HTTP headers through `create_header`.
pub async fn rest_get(
&mut self,
path: String,
params: Vec<(&str, &str)>,
) -> Result<Response, Error> {
self.ensure_refresh().await?;
let url = format!(
"{}{}",
self.instance_url.as_ref().ok_or(Error::NotLoggedIn)?,
path
);
let res = self
.http_client
.get(url.as_str())
.headers(self.create_header(vec![])?)
.query(¶ms)
.send()
.await?;
Ok(res)
}
/// Sends a POST request to the specified REST API endpoint with the provided parameters.
///
/// # Type Parameters
/// * `T`: The type of the request parameters. Must implement the `Serialize` trait.
///
/// # Parameters
/// * `path`: A `String` specifying the API endpoint relative to the base instance URL.
/// * `params`: An object of type `T` containing the data to be serialized as JSON and sent
/// in the POST request body.
///
/// # Returns
/// Returns a `Result<Response, Error>` that represents either:
/// * `Ok(Response)` - The successful HTTP response.
/// * `Err(Error)` - An error encountered during the process (e.g., not logged in,
/// serialization issues, network errors, etc.).
///
/// # Errors
/// This function can return the following errors:
/// * `Error::NotLoggedIn` - If the client is not logged in or the instance URL is missing.
/// * Other errors may be returned due to HTTP request failures or issues during request setup.
///
/// # Behavior
/// 1. Ensures the client session is refreshed by calling `ensure_refresh()` asynchronously.
/// 2. Constructs the full URL by appending the given `path` to the instance URL.
/// 3. Sets the appropriate headers using `create_header`.
/// 4. Serializes the `params` into JSON.
/// 5. Sends an asynchronous POST request to the constructed URL.
/// 6. Returns the received HTTP response upon success.
///
/// # Examples
/// ```rust
/// use serde::Serialize;
/// use rustsf::{Client, Error};
///
/// #[derive(Serialize)]
/// struct Params {
/// key: String,
/// value: i32,
/// }
///
/// async fn example() -> Result<(), Error> {
/// let mut client = Client::new();
/// // Authentication...
/// let params = Params {
/// key: "example".into(),
/// value: 42,
/// };
/// let response = client
/// .rest_post("/api/endpoint".to_string(), params)
/// .await?;
///
/// println!("Response: {:?}", response);
/// Ok(())
/// }
/// ```
pub async fn rest_post<T: Serialize>(
&mut self,
path: String,
params: T,
) -> Result<Response, Error> {
self.ensure_refresh().await?;
let url = format!(
"{}{}",
self.instance_url.as_ref().ok_or(Error::NotLoggedIn)?,
path
);
let res = self
.http_client
.post(url)
.headers(self.create_header(vec![])?)
.json(¶ms)
.send()
.await?;
Ok(res)
}
/// Sends a PATCH request to the specified REST API endpoint with the given parameters.
///
/// # Type Parameters
/// - `T`: The type of the parameters to be serialized into the request body. It must implement the `Serialize` trait.
///
/// # Arguments
/// - `path`: A `String` representing the relative path of the API endpoint to send the request to.
/// - `params`: An object of type `T` containing the parameters to be serialized into the JSON body of the request.
///
/// # Returns
/// - `Ok(Response)`: On a successful request, returns the HTTP response of type `Response`.
/// - `Err(Error)`: Returns an error if:
/// - The instance is not properly set up or the user is not logged in (`Error::NotLoggedIn`).
/// - There is an issue with refreshing the instance or creating the request headers.
/// - The HTTP request fails for some other reason (e.g., a network error).
///
/// # Errors
/// This method may return an error in the following cases:
/// - The user is not logged in (`Error::NotLoggedIn`) and the `instance_url` is unavailable.
/// - If the `ensure_refresh` internal function fails (e.g., unable to refresh authentication tokens).
/// - If there is an error serializing the parameters or constructing the HTTP headers.
/// - If the HTTP request fails during transmission or response handling.
///
/// # Examples
/// ```rust
/// use serde::Serialize;
/// use rustsf::{Client, Error};
///
/// #[derive(Serialize)]
/// struct UpdateParams {
/// field: String,
/// value: String,
/// }
///
/// async fn example() -> Result<(), Error> {
/// let mut client = Client::new();
/// // Authentication...
/// let params = UpdateParams {
/// field: "example_field".to_string(),
/// value: "new_value".to_string(),
/// };
///
/// let response = client
/// .rest_patch("/api/endpoint".to_string(), params)
/// .await?;
///
/// println!("Response: {:?}", response);
/// Ok(())
/// }
/// ```
pub async fn rest_patch<T: Serialize>(
&mut self,
path: String,
params: T,
) -> Result<Response, Error> {
self.ensure_refresh().await?;
let url = format!(
"{}{}",
self.instance_url.as_ref().ok_or(Error::NotLoggedIn)?,
path
);
let res = self
.http_client
.patch(url.as_str())
.headers(self.create_header(vec![])?)
.json(¶ms)
.send()
.await?;
Ok(res)
}
/// Sends an HTTP PUT request to the specified REST API endpoint with the given parameters in JSON format.
///
/// This asynchronous function constructs the full URL by appending the provided `path` to the
/// instance URL, ensures the client is authenticated (by refreshing the session if necessary),
/// and makes the PUT request using the provided parameters. The function expects the parameters
/// to be serializable as JSON and attaches custom headers to the request.
///
/// # Type Parameters
/// * `T`: A type that implements the [`Serialize`](https://docs.rs/serde/latest/serde/trait.Serialize.html) trait, representing
/// the data to be serialized into JSON and included in the request body.
///
/// # Parameters
/// * `path`: A [`String`](https://doc.rust-lang.org/std/string/struct.String.html) specifying the REST API endpoint's relative path.
/// * `params`: A serializable object of type `T` that represents the payload to be included in the PUT request.
///
/// # Returns
/// * `Result<Response, Error>`: On success, this function returns a successful [`Response`](https://docs.rs/reqwest/latest/reqwest/struct.Response.html) from the PUT request.
/// On failure, it returns an [`Error`](https://docs.rs/reqwest/latest/reqwest/enum.Error.html) or custom `Error` defined by the client.
///
/// # Errors
/// * Returns `Error::NotLoggedIn` if the client is not logged in and the `instance_url` is not available.
/// * Propagates errors encountered while refreshing the session via `self.ensure_refresh()`.
/// * Propagates errors from invalid header creation, serializing the payload, sending the HTTP request, or other
/// networking issues encountered by the HTTP client.
///
/// # Examples
/// ```rust
/// use serde::Serialize;
/// use rustsf::{Client, Error};
///
/// #[derive(Serialize)]
/// struct UpdateData {
/// key: String,
/// value: String,
/// }
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
///
/// let data = UpdateData {
/// key: "example_key".to_string(),
/// value: "example_value".to_string(),
/// };
///
/// match client.rest_put("/api/resource".to_string(), data).await {
/// Ok(response) => {
/// println!("Request succeeded with status: {}", response.status());
/// }
/// Err(e) => {
/// eprintln!("Request failed: {}", e);
/// }
/// }
/// Ok(())
/// }
/// ```
pub async fn rest_put<T: Serialize>(
&mut self,
path: String,
params: T,
) -> Result<Response, Error> {
self.ensure_refresh().await?;
let url = format!(
"{}{}",
self.instance_url.as_ref().ok_or(Error::NotLoggedIn)?,
path
);
let res = self
.http_client
.put(url.as_str())
.headers(self.create_header(vec![])?)
.json(¶ms)
.send()
.await?;
Ok(res)
}
/// Sends an asynchronous HTTP DELETE request to a specified path.
///
/// # Parameters
/// - `path` (`String`): The path to which the DELETE request will be sent. This path will be appended to the instance URL.
///
/// # Returns
/// - `Result<Response, Error>`:
/// - On success, returns an `Ok(Response)` representing the HTTP response from the server.
/// - On failure, returns an `Err(Error)` detailing the error encountered.
///
/// # Errors
/// - This function will return an error in the following scenarios:
/// - If the client is not logged in (`Error::NotLoggedIn`).
/// - If refreshing the authentication token fails.
/// - If there is an issue creating the HTTP headers.
/// - If the HTTP request fails during execution.
///
/// # Async Behavior
/// - This function is asynchronous and should be awaited.
/// - Before sending the DELETE request, it ensures that the authentication state is up-to-date by calling `self.ensure_refresh()`.
///
/// # Example
/// ```rust
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// // Authentication logic...
/// let response = client.rest_delete("/resource/123".to_string()).await;
///
/// match response {
/// Ok(res) => {
/// println!("DELETE request successful: {}", res.status());
/// }
/// Err(err) => {
/// eprintln!("Error occurred: {}", err);
/// }
/// }
/// Ok(())
/// }
/// ```
pub async fn rest_delete(&mut self, path: String) -> Result<Response, Error> {
self.ensure_refresh().await?;
let url = format!(
"{}{}",
self.instance_url.as_ref().ok_or(Error::NotLoggedIn)?,
path
);
let res = self
.http_client
.delete(url.as_str())
.headers(self.create_header(vec![])?)
.send()
.await?;
Ok(res)
}
/// Sends an asynchronous HTTP GET request to the specified URL with the provided query parameters.
///
/// This function ensures that any necessary pre-request setup (such as refreshing tokens or credentials)
/// is performed before sending the request. It then constructs the request with appropriate headers and
/// query parameters, uses the underlying HTTP client to send the request, and returns the response or an error.
///
/// # Arguments
///
/// * `url` - A `String` representing the target URL for the GET request.
/// * `params` - A `Vec` of tuples where each tuple contains a key-value pair (`String`, `String`) representing
/// query parameters to append to the URL.
///
/// # Returns
///
/// Returns a `Result` containing:
/// - `Response`: The HTTP response object if the request is successful.
/// - `Error`: An error if an issue occurs during the process of refreshing credentials,
/// constructing the request, or sending it.
///
/// # Errors
///
/// This function can return an `Error` due to:
/// - Failure during the token/credential refresh process in `self.ensure_refresh()`.
/// - Issues with building headers in `self.create_header`.
/// - Errors originating from the underlying HTTP client's `send` function (e.g., connectivity issues).
///
/// # Example
/// ```rust
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// // Authentication logic...
/// let response = client.get(
/// "https://api.example.com/items".into(),
/// vec![("key".into(), "value".into())],
/// vec![]
/// ).await;
/// match response {
/// Ok(res) => {
/// println!("Response: {:?}", res);
/// },
/// Err(err) => {
/// eprintln!("Error: {:?}", err);
/// }
/// }
/// Ok(())
/// }
/// ```
pub async fn get(
&mut self,
url: String,
params: Vec<(String, String)>,
headers: Vec<(String, String)>,
) -> Result<Response, Error> {
self.ensure_refresh().await?;
debug!("GET: {} params: {:?} headers: {:?}", url, params, headers);
let res = self
.http_client
.get(url.as_str())
.headers(self.create_header(headers)?)
.query(¶ms)
.send()
.await?;
Ok(res)
}
/// Sends a GET request to the specified URL with optional additional headers,
/// ensuring that necessary token or session refresh procedures are completed before the request.
///
/// # Arguments
///
/// * `url` - A string slice that holds the URL to which the GET request will be sent.
/// * `additional_headers` - A vector of key-value pairs (`String`, `String`) representing
/// additional headers to include in the request. Note that the "Accept" header is removed
/// from the headers before the request is sent.
///
/// # Returns
///
/// * `Result<Response, Error>` - On success, returns a `Response` object representing the
/// HTTP response. On failure, returns an `Error` indicating what went wrong.
///
/// # Errors
///
/// This function returns an error in the following scenarios:
///
/// * If `self.ensure_refresh()` fails during the session or token refresh process.
/// * If `self.create_header()` fails to create the HTTP headers from `additional_headers`.
/// * If the HTTP client encounters an issue while sending the GET request.
///
/// # Example
///
/// ```rust
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// // Authentication logic...
/// let url = "https://example.com/api/resource";
/// let headers = vec![("Authorization".to_string(), "Bearer token".to_string())];
/// match client.get_raw(url, headers).await {
/// Ok(response) => println!("Response status: {}", response.status()),
/// Err(err) => println!("Error: {}", err),
/// }
/// Ok(())
/// }
/// ```
///
/// # Notes
///
/// This method removes the "Accept" header (if any) from the list of headers before
/// sending the request.
pub async fn get_raw(
&mut self,
url: &str,
additional_headers: Vec<(String, String)>,
) -> Result<Response, Error> {
self.ensure_refresh().await?;
debug!("GET: {} headers: {:?}", url, additional_headers);
let mut headers = self.create_header(additional_headers)?;
headers.remove("Accept");
let res = self.http_client.get(url).headers(headers).send().await?;
Ok(res)
}
/// Asynchronously sends an HTTP POST request to the specified URL with the given parameters and headers.
///
/// This function ensures the client is refreshed before making the request.
/// It constructs the POST request by combining the given URL, serialization of parameters, and custom headers,
/// and uses the `reqwest` HTTP client to send the request.
///
/// # Type Parameters
///
/// * `T`: A type that implements the `Serialize` trait, representing the body of the POST request.
///
/// # Parameters
///
/// * `url` - A `String` representing the URL endpoint for the POST request.
/// * `params` - A serializable type (`T`) used as the JSON body of the POST request.
/// * `headers` - A vector of tuples where each tuple contains a header name and its corresponding value (`Vec<(String, String)>`).
///
/// # Returns
///
/// Returns a `Result`:
/// - `Ok(Response)` on success, where `Response` is the HTTP response returned by the request.
/// - `Err(Error)` if an error occurs during the request, such as serialization issues, header creation errors, or HTTP client errors.
///
/// # Errors
///
/// This function may return an error in the following circumstances:
/// * If `self.ensure_refresh()` fails.
/// * If `self.create_header(headers)` fails to construct the headers.
/// * If the HTTP client encounters an issue while sending the request.
///
/// # Examples
///
/// ```rust
/// use rustsf::{Client, BulkApiV2, Error, DefSObject};
/// use serde::{Deserialize, Serialize};
///
/// #[DefSObject(sobject_type = "Account", fields="system,type,name")]
/// struct Account {}
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// use rustsf::primary_types::SObject;
/// let mut client = Client::new();
/// // Authentication logic...
///
/// let headers = vec![("Authorization".to_string(), "Bearer token".to_string())];
/// let url = "https://www.salesforce.com/api/v60.0".to_string();
/// let mut acc = Account::new();
/// acc.set_id(Some("001xx000003DGbX"));
/// acc.name = Some("Test".to_string());
///
/// let response = client.post(url, acc, headers).await;
/// match response {
/// Ok(res) => println!("Response: {:?}", res),
/// Err(err) => eprintln!("Error: {:?}", err),
/// }
/// Ok(())
/// }
/// ```
///
/// Note: Ensure that the given `url` is valid and accessible and that proper error handling is implemented
/// for production use.
pub async fn post<T: Serialize + Debug>(
&mut self,
url: String,
params: T,
headers: Vec<(String, String)>,
) -> Result<Response, Error> {
self.ensure_refresh().await?;
debug!("POST: {} params: {:?} headers: {:?}", url, params, headers);
let res = self
.http_client
.post(url)
.headers(self.create_header(headers)?)
.json(¶ms)
.send()
.await?;
Ok(res)
}
/// Asynchronously sends an HTTP POST request to the specified URL with the given parameters and headers.
///
/// This function ensures the client is refreshed before making the request.
/// It constructs the POST request by combining the given URL, serialization of parameters, and custom headers,
/// and uses the `reqwest` HTTP client to send the request.
///
/// # Type Parameters
///
/// * `T`: A type that implements the `Serialize` trait, representing the body of the POST request.
///
/// # Parameters
///
/// * `url` - A `String` representing the URL endpoint for the POST request.
/// * `params` - A serializable type (`T`) used as the JSON body of the POST request.
/// * `headers` - A vector of tuples where each tuple contains a header name and its corresponding value (`Vec<(String, String)>`).
///
/// # Returns
///
/// Returns a `Result`:
/// - `Ok(Response)` on success, where `Response` is the HTTP response returned by the request.
/// - `Err(Error)` if an error occurs during the request, such as serialization issues, header creation errors, or HTTP client errors.
///
/// # Errors
///
/// This function may return an error in the following circumstances:
/// * If `self.ensure_refresh()` fails.
/// * If `self.create_header(headers)` fails to construct the headers.
/// * If the HTTP client encounters an issue while sending the request.
///
/// # Examples
///
/// ```rust
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// // Authentication logic...
/// let headers = vec![("Authorization".to_string(), "Bearer token".to_string())];
/// let url = "https://example.com/api/accounts".to_string();
/// match client.post_raw_buffer(url, vec![], headers).await {
/// Ok(res) => println!("Response: {:?}", res),
/// Err(err) => println!("Error: {:?}", err),
/// }
/// Ok(())
/// }
/// ```
pub async fn post_raw_buffer(
&mut self,
url: String,
body: Vec<u8>,
headers: Vec<(String, String)>,
) -> Result<Response, Error> {
self.ensure_refresh().await?;
debug!("POST: {} body: {:?} headers: {:?}", url, body, headers);
let res = self
.http_client
.post(url)
.headers(self.create_header(headers)?)
.body(body)
.send()
.await?;
Ok(res)
}
/// Sends an HTTP PUT request to the specified URL with the provided content.
///
/// This method ensures that necessary pre-request refresh actions are performed,
/// sets the proper headers (`Content-Type` as `text/csv` and `Accept` as `application/json`),
/// and sends the supplied data as the request body.
///
/// # Arguments
///
/// * `url` - A `String` containing the target URL for the PUT request.
/// * `buffer` - A `Vec<u8>` containing the binary data to be sent as the request body.
///
/// # Returns
///
/// This method returns a `Result`:
/// * `Ok(Response)` - The HTTP response returned by the server.
/// * `Err(Error)` - An error if the refresh action, header creation,
/// or the HTTP request itself fails.
///
/// # Errors
///
/// This function can return an error in the following cases:
/// * If the `ensure_refresh` method fails to complete successfully.
/// * If header creation fails to generate a valid set of headers.
/// * If the `http_client.put` request encounters an issue during sending or receiving.
///
/// # Examples
///
/// ```rust
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// // Authentication logic...
/// let url = "https://example.com/resource".to_string();
/// let data = b"column1,column2\nvalue1,value2".to_vec();
///
/// match client.put(url, data).await {
/// Ok(response) => println!("PUT request succeeded with status: {}", response.status()),
/// Err(err) => eprintln!("PUT request failed: {}", err),
/// }
/// Ok(())
/// }
/// ```
pub async fn put(&mut self, url: String, buffer: Vec<u8>) -> Result<Response, Error> {
self.ensure_refresh().await?;
debug!("PUT: {} body: {:?}", url, buffer);
let mut headers = self.create_header(vec![])?;
headers.insert("Content-Type", HeaderValue::from_static("text/csv"));
headers.insert("Accept", HeaderValue::from_static("application/json"));
let res = self
.http_client
.put(url.as_str())
.headers(headers)
.body(buffer)
.send()
.await?;
Ok(res)
}
/// Sends an asynchronous HTTP PATCH request to the specified URL with the provided parameters.
///
/// # Type Parameters
/// - `T`: A type that implements the `Serialize` trait, representing the body of the request.
///
/// # Parameters
/// - `url`: A `String` containing the target URL for the PATCH request.
/// - `params`: A value of type `T`, used as the serialized JSON body of the PATCH request.
///
/// # Returns
/// - `Result<Response, Error>`:
/// - `Ok(Response)`: If the request is successful, returns the response from the server.
/// - `Err(Error)`: If an error occurs during the request (e.g., problems in refreshing state,
/// creating headers, JSON serialization, or network issues), returns the corresponding error.
///
/// # Errors
/// This function returns an error if:
/// - `ensure_refresh` fails to refresh the client state.
/// - An error occurs while creating the headers.
/// - An error occurs in serializing the `params`.
/// - The HTTP client fails to send the request or receives an error response.
///
/// # Example
/// ```rust
/// use rustsf::{Client, Error, DefSObject};
/// use serde::Serialize;
///
/// #[DefSObject(sobject_type = "Account", fields="name")]
/// struct Account { }
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// // Authentication logic...
/// let url = String::from("https://example.com/resource");
/// let mut acc = Account::new();
/// acc.id = Some(String::from("001D000000IqhSLIAZ"));
/// acc.name = Some(String::from("Sample Account"));
///
/// match client.patch::<Account>(url, acc).await {
/// Ok(response) => println!("Request succeeded: {:?}", response),
/// Err(err) => eprintln!("Request failed: {}", err),
/// }
/// Ok(())
/// }
/// ```
pub async fn patch<T: Serialize + Debug>(
&mut self,
url: String,
params: T,
) -> Result<Response, Error> {
self.ensure_refresh().await?;
debug!("PATCH: {} params: {:?}", url, params);
let res = self
.http_client
.patch(url.as_str())
.headers(self.create_header(vec![])?)
.json(¶ms)
.send()
.await?;
Ok(res)
}
///
/// Sends an HTTP DELETE request to the specified URL and returns the response.
///
/// This function performs the following operations:
/// 1. Ensures that any necessary refresh operations are completed by calling `ensure_refresh`.
/// 2. Constructs a DELETE request to the given URL using the internal HTTP client.
/// 3. Adds the necessary headers to the request (created via `create_header`).
/// 4. Sends the request asynchronously and waits for the response.
///
/// # Parameters
/// - `url`: A `String` representing the URL to which the DELETE request will be sent.
///
/// # Returns
/// - `Ok(Response)`: An HTTP response if the request is successful.
/// - `Err(Error)`: An error if any part of the process fails, such as constructing headers,
/// sending the request, or encountering issues during the refresh process.
///
/// # Errors
/// This function will return an `Error` in the following cases:
/// - If `ensure_refresh` fails.
/// - If there is an issue with creating the headers.
/// - If sending the DELETE request fails (e.g., network issues or server errors).
///
/// # Examples
/// ```
/// use rustsf::{Client, Error};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Error> {
/// let mut client = Client::new();
/// // Authentication logic...
///
/// let url = "https://api.example.com/resource".to_string();
/// match client.delete(url).await {
/// Ok(response) => println!("DELETE request succeeded with status: {}", response.status()),
/// Err(err) => eprintln!("DELETE request failed: {}", err),
/// }
/// Ok(())
/// }
/// ```
///
/// # Note
/// Ensure that the client is properly initialized and authenticated before calling this method.
///
pub async fn delete(&mut self, url: String) -> Result<Response, Error> {
self.ensure_refresh().await?;
debug!("DELETE: {}", url);
let res = self
.http_client
.delete(url.as_str())
.headers(self.create_header(vec![])?)
.send()
.await?;
Ok(res)
}
/// Generates a `HeaderMap` containing default headers, authorization, and additional custom headers.
///
/// # Arguments
///
/// * `additional_headers` - A list of key-value pairs representing additional headers
/// to be added to the request. Each key is the header name and each value is the corresponding header value.
///
/// # Returns
///
/// * `Ok(HeaderMap)` - Returns the constructed `HeaderMap` with all headers included.
/// * `Err(Error)` - Returns an error in the following scenarios:
/// - If the access token is not found (`Error::NotLoggedIn`).
/// - If a provided header name is invalid (`Error::ConfigError`).
/// - If a provided header value cannot be parsed.
///
/// # Behavior
///
/// - Authenticates the request by including an `Authorization` header with a Bearer token.
/// The token is retrieved from the `access_token` field of the struct, and an error is
/// returned if it is not available.
/// - Sets a default `Accept: application/json` header.
/// - Iterates through the `additional_headers` list and adds the headers
/// to the `HeaderMap`. If a header name already exists, the existing value is replaced.
/// - All header names are validated for correctness, and invalid header names or values will result in an error.
///
/// # Errors
///
/// - `Error::NotLoggedIn` occurs when there is no access token available.
/// - `Error::ConfigError` occurs if the custom header name is invalid or unparseable.
/// - Errors are propagated if the header value conversion fails.
///
fn create_header(&self, additional_headers: Vec<(String, String)>) -> Result<HeaderMap, Error> {
let mut headers = HeaderMap::new();
let auth_value = format!(
"Bearer {}",
self.access_token.as_ref().ok_or(Error::NotLoggedIn)?.value
);
headers.insert(AUTHORIZATION, HeaderValue::from_str(&auth_value)?);
//Default header
headers.insert("Accept", HeaderValue::from_static("application/json"));
for (key, value) in additional_headers {
let header_name: HeaderName = key
.parse()
.map_err(|_| Error::ConfigError(format!("Invalid header name: {}", key)))?;
let header_value = HeaderValue::from_str(&value)?;
//delete duplicates
headers.remove(&header_name);
headers.insert(header_name, header_value);
}
Ok(headers)
}
}
#[cfg(test)]
mod tests {
use super::*;
use mockito::Server;
use serde_json::json;
fn create_test_client(server_url: &str) -> Client {
let mut client = Client::new();
client.set_instance_url(server_url);
client.set_access_token(
"test_token".to_string(),
// Use a timestamp far in the future so ensure_refresh doesn't trigger
"9999999999000".to_string(),
"Bearer".to_string(),
);
client
}
// --- Constructor and defaults ---
#[test]
fn test_new_defaults() {
let client = Client::new();
assert_eq!(client.login_endpoint, "https://login.salesforce.com");
assert_eq!(client.version, "v60.0");
assert!(client.client_id.is_none());
assert!(client.client_secret.is_none());
assert!(client.access_token.is_none());
assert!(client.instance_url.is_none());
assert!(client.refresh_token.is_none());
assert!(client.secret_required);
}
#[test]
fn test_default_calls_new() {
let client = Client::default();
assert_eq!(client.version, "v60.0");
}
// --- Setters and getters ---
#[test]
fn test_set_login_endpoint() {
let mut client = Client::new();
let result = client.set_login_endpoint("https://test.salesforce.com");
assert_eq!(result.login_endpoint, "https://test.salesforce.com");
}
#[test]
fn test_set_version() {
let mut client = Client::new();
client.set_version("v55.0");
assert_eq!(client.version, "v55.0");
}
#[test]
fn test_set_instance_url() {
let mut client = Client::new();
client.set_instance_url("https://example.com");
assert_eq!(Some("https://example.com".to_string()), client.instance_url);
}
#[test]
fn test_instance_url_getter() {
let mut client = Client::new();
assert_eq!(None, client.instance_url());
client.set_instance_url("https://example.com");
assert_eq!(Some("https://example.com"), client.instance_url());
}
#[test]
fn test_set_refresh_token() {
let mut client = Client::new();
client.set_refresh_token("my_refresh_token");
assert_eq!(Some("my_refresh_token".to_string()), client.refresh_token);
}
#[test]
fn test_set_secret_required() {
let mut client = Client::new();
assert!(client.secret_required);
client.set_secret_required(false);
assert!(!client.secret_required);
}
#[test]
fn test_set_client_id() {
let mut client = Client::new();
client.set_client_id("my_client_id");
assert_eq!(Some("my_client_id".to_string()), client.client_id);
}
#[test]
fn test_set_client_secret() {
let mut client = Client::new();
client.set_client_secret("my_secret");
assert_eq!(Some("my_secret".to_string()), client.client_secret);
}
#[test]
fn test_set_access_token() {
let mut client = Client::new();
client.set_access_token(
"token_val".to_string(),
"issued".to_string(),
"Bearer".to_string(),
);
let token = client.access_token.as_ref().unwrap();
assert_eq!("token_val", token.value);
assert_eq!("issued", token.issued_at);
assert_eq!("Bearer", token.token_type);
}
#[test]
fn test_access_token_value() {
let mut client = Client::new();
assert_eq!(None, client.access_token_value());
client.set_access_token("abc".to_string(), "".to_string(), "".to_string());
assert_eq!(Some("abc"), client.access_token_value());
}
#[test]
fn test_read_only_getters() {
let mut client = Client::new();
client.set_client_id("cid");
client.set_client_secret("csecret");
client.set_refresh_token("rtoken");
assert_eq!(client.client_id(), Some("cid"));
assert_eq!(client.client_secret(), Some("csecret"));
assert_eq!(client.login_endpoint(), "https://login.salesforce.com");
assert_eq!(client.version(), "v60.0");
assert_eq!(client.refresh_token(), Some("rtoken"));
}
// --- Chaining setters ---
#[test]
fn test_setter_chaining() {
let mut client = Client::new();
client
.set_login_endpoint("https://test.salesforce.com")
.set_version("v55.0")
.set_instance_url("https://inst.salesforce.com")
.set_client_id("cid")
.set_client_secret("csecret")
.set_refresh_token("rtoken")
.set_secret_required(false);
assert_eq!(client.login_endpoint, "https://test.salesforce.com");
assert_eq!(client.version, "v55.0");
assert_eq!(
client.instance_url,
Some("https://inst.salesforce.com".to_string())
);
assert_eq!(client.client_id, Some("cid".to_string()));
assert_eq!(client.client_secret, Some("csecret".to_string()));
assert_eq!(client.refresh_token, Some("rtoken".to_string()));
assert!(!client.secret_required);
}
// --- Refresh params ---
#[test]
fn test_get_refresh_params_with_secret() {
let mut client = Client::new();
client.set_client_id("cid");
client.set_client_secret("csecret");
client.set_refresh_token("rtoken");
let params = client.get_refresh_params();
assert_eq!(params.len(), 4);
assert!(params.contains(&("grant_type".to_string(), "refresh_token".to_string())));
assert!(params.contains(&("refresh_token".to_string(), "rtoken".to_string())));
assert!(params.contains(&("client_id".to_string(), "cid".to_string())));
assert!(params.contains(&("client_secret".to_string(), "csecret".to_string())));
}
#[test]
fn test_get_refresh_params_without_secret() {
let mut client = Client::new();
client.set_secret_required(false);
client.set_client_id("cid");
client.set_refresh_token("rtoken");
let params = client.get_refresh_params();
assert_eq!(params.len(), 3);
assert!(!params.iter().any(|(k, _)| k == "client_secret"));
}
#[test]
fn test_get_refresh_params_defaults_when_none() {
let client = Client::new();
let params = client.get_refresh_params();
// Should use empty strings for missing values
assert!(params.contains(&("refresh_token".to_string(), "".to_string())));
assert!(params.contains(&("client_id".to_string(), "".to_string())));
}
// --- create_header ---
#[test]
fn test_create_header_not_logged_in() {
let client = Client::new();
let result = client.create_header(vec![]);
assert!(result.is_err());
match result.unwrap_err() {
Error::NotLoggedIn => {}
e => panic!("Expected NotLoggedIn, got {:?}", e),
}
}
#[test]
fn test_create_header_with_token() {
let mut client = Client::new();
client.set_access_token("mytoken".to_string(), "".to_string(), "Bearer".to_string());
let headers = client.create_header(vec![]).unwrap();
assert_eq!(headers.get("Authorization").unwrap(), "Bearer mytoken");
assert_eq!(headers.get("Accept").unwrap(), "application/json");
}
#[test]
fn test_create_header_with_additional_headers() {
let mut client = Client::new();
client.set_access_token("mytoken".to_string(), "".to_string(), "Bearer".to_string());
let headers = client
.create_header(vec![
("X-Custom".to_string(), "custom_value".to_string()),
("Accept".to_string(), "text/xml".to_string()),
])
.unwrap();
assert_eq!(headers.get("X-Custom").unwrap(), "custom_value");
// Accept should be overridden
assert_eq!(headers.get("Accept").unwrap(), "text/xml");
}
// --- ensure_refresh ---
#[tokio::test]
async fn test_ensure_refresh_no_token() {
let mut client = Client::new();
// Should return Ok without doing anything
let result = client.ensure_refresh().await;
assert!(result.is_ok());
}
#[tokio::test]
async fn test_ensure_refresh_token_not_expired() {
let mut client = Client::new();
// Set a token with issued_at far in the future
client.set_access_token(
"token".to_string(),
"9999999999000".to_string(),
"Bearer".to_string(),
);
let result = client.ensure_refresh().await;
assert!(result.is_ok());
assert_eq!(client.access_token_value(), Some("token"));
}
// --- login_with_credential ---
#[tokio::test]
async fn test_login_with_credential_success() {
let mut server = Server::new_async().await;
let mock = server
.mock("POST", "/services/oauth2/token")
.with_status(200)
.with_header("content-type", "application/json")
.with_body(
json!({
"access_token": "PowerLevel9000",
"issued_at": "1234567890000",
"id": "https://login.salesforce.com/id/00Dxx/005xx",
"instance_url": server.url(),
"signature": "sig",
"token_type": "Bearer",
})
.to_string(),
)
.create_async()
.await;
let mut client = Client::new();
client.set_client_id("cid");
client.set_client_secret("csecret");
client.set_login_endpoint(&server.url());
let result = client.login_with_credential("user", "pass").await;
assert!(result.is_ok());
assert_eq!(client.access_token_value(), Some("PowerLevel9000"));
assert_eq!(client.instance_url.unwrap(), server.url());
mock.assert_async().await;
}
#[tokio::test]
async fn test_login_with_credential_failure() {
let mut server = Server::new_async().await;
let mock = server
.mock("POST", "/services/oauth2/token")
.with_status(400)
.with_header("content-type", "application/json")
.with_body(
json!({
"error": "invalid_grant",
"error_description": "authentication failure"
})
.to_string(),
)
.create_async()
.await;
let mut client = Client::new();
client.set_client_id("cid");
client.set_client_secret("csecret");
client.set_login_endpoint(&server.url());
let result = client.login_with_credential("user", "pass").await;
assert!(result.is_err());
match result.unwrap_err() {
Error::TokenError(_) => {}
e => panic!("Expected TokenError, got {:?}", e),
}
mock.assert_async().await;
}
#[tokio::test]
async fn test_login_with_credential_missing_client_id() {
let mut client = Client::new();
let result = client.login_with_credential("user", "pass").await;
assert!(result.is_err());
match result.unwrap_err() {
Error::ConfigError(msg) => assert!(msg.contains("client_id")),
e => panic!("Expected ConfigError, got {:?}", e),
}
}
// --- refresh ---
#[tokio::test]
async fn test_refresh_success() {
let mut server = Server::new_async().await;
let mock = server
.mock("POST", "/services/oauth2/token")
.with_status(200)
.with_header("content-type", "application/json")
.with_body(
json!({
"access_token": "new_token",
"issued_at": "1234567890000",
"id": "https://login.salesforce.com/id/00Dxx/005xx",
"instance_url": server.url(),
"signature": "sig",
"token_type": "Bearer",
})
.to_string(),
)
.create_async()
.await;
let mut client = Client::new();
client.set_client_id("cid");
client.set_client_secret("csecret");
client.set_refresh_token("rtoken");
client.set_login_endpoint(&server.url());
let result = client.refresh().await;
assert!(result.is_ok());
assert_eq!(client.access_token_value(), Some("new_token"));
mock.assert_async().await;
}
#[tokio::test]
async fn test_refresh_failure() {
let mut server = Server::new_async().await;
let mock = server
.mock("POST", "/services/oauth2/token")
.with_status(400)
.with_header("content-type", "application/json")
.with_body(
json!({
"error": "invalid_grant",
"error_description": "expired refresh token"
})
.to_string(),
)
.create_async()
.await;
let mut client = Client::new();
client.set_login_endpoint(&server.url());
let result = client.refresh().await;
assert!(result.is_err());
mock.assert_async().await;
}
// --- login_by_soap ---
#[tokio::test]
async fn test_login_by_soap_success() {
let mut server = Server::new_async().await;
let soap_response = r#"<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<loginResponse>
<result>
<sessionId>soap_token_123</sessionId>
<serverUrl>https://na1.salesforce.com/services/Soap/u/60.0/00Dxx</serverUrl>
<serverTimestamp>2024-01-01T00:00:00.000Z</serverTimestamp>
</result>
</loginResponse>
</soapenv:Body>
</soapenv:Envelope>"#;
let mock = server
.mock("POST", "/services/Soap/u/v60.0")
.with_status(200)
.with_header("content-type", "text/xml")
.with_body(soap_response)
.create_async()
.await;
let mut client = Client::new();
client.set_login_endpoint(&server.url());
#[allow(deprecated)]
let result = client.login_with_soap("user", "pass").await;
assert!(result.is_ok());
let token = client.access_token.unwrap();
assert_eq!(token.value, "soap_token_123");
assert_eq!(token.token_type, "Bearer");
mock.assert_async().await;
}
#[tokio::test]
async fn test_login_by_soap_failure() {
let mut server = Server::new_async().await;
let soap_error = r#"<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<soapenv:Fault>
<faultcode>INVALID_LOGIN</faultcode>
<faultstring>Invalid username or password</faultstring>
</soapenv:Fault>
</soapenv:Body>
</soapenv:Envelope>"#;
let mock = server
.mock("POST", "/services/Soap/u/v60.0")
.with_status(500)
.with_header("content-type", "text/xml")
.with_body(soap_error)
.create_async()
.await;
let mut client = Client::new();
client.set_login_endpoint(&server.url());
#[allow(deprecated)]
let result = client.login_with_soap("user", "pass").await;
assert!(result.is_err());
match result.unwrap_err() {
Error::LoginError(e) => {
assert_eq!(e.error_code, "INVALID_LOGIN");
assert_eq!(e.message, "Invalid username or password");
}
e => panic!("Expected LoginError, got {:?}", e),
}
mock.assert_async().await;
}
// --- HTTP methods with mock server ---
#[tokio::test]
async fn test_get() {
let mut server = Server::new_async().await;
let mock = server
.mock("GET", "/test")
.match_query(mockito::Matcher::AllOf(vec![]))
.with_status(200)
.with_body("ok")
.create_async()
.await;
let mut client = create_test_client(&server.url());
let res = client
.get(format!("{}/test", server.url()), vec![], vec![])
.await;
assert!(res.is_ok());
assert_eq!(res.unwrap().status(), 200);
mock.assert_async().await;
}
#[tokio::test]
async fn test_post() {
let mut server = Server::new_async().await;
let mock = server
.mock("POST", "/test")
.with_status(201)
.with_body(r#"{"id":"123","success":true}"#)
.create_async()
.await;
let mut client = create_test_client(&server.url());
let mut params = std::collections::HashMap::new();
params.insert("Name", "Test");
let res = client
.post(format!("{}/test", server.url()), params, vec![])
.await;
assert!(res.is_ok());
assert_eq!(res.unwrap().status(), 201);
mock.assert_async().await;
}
#[tokio::test]
async fn test_patch() {
let mut server = Server::new_async().await;
let mock = server
.mock("PATCH", "/test")
.with_status(204)
.create_async()
.await;
let mut client = create_test_client(&server.url());
let mut params = std::collections::HashMap::new();
params.insert("Name", "Updated");
let res = client.patch(format!("{}/test", server.url()), params).await;
assert!(res.is_ok());
assert_eq!(res.unwrap().status(), 204);
mock.assert_async().await;
}
#[tokio::test]
async fn test_delete() {
let mut server = Server::new_async().await;
let mock = server
.mock("DELETE", "/test")
.with_status(204)
.create_async()
.await;
let mut client = create_test_client(&server.url());
let res = client.delete(format!("{}/test", server.url())).await;
assert!(res.is_ok());
assert_eq!(res.unwrap().status(), 204);
mock.assert_async().await;
}
#[tokio::test]
async fn test_put() {
let mut server = Server::new_async().await;
let mock = server
.mock("PUT", "/test")
.with_status(201)
.create_async()
.await;
let mut client = create_test_client(&server.url());
let res = client
.put(format!("{}/test", server.url()), b"csv,data".to_vec())
.await;
assert!(res.is_ok());
assert_eq!(res.unwrap().status(), 201);
mock.assert_async().await;
}
#[tokio::test]
async fn test_post_raw_buffer() {
let mut server = Server::new_async().await;
let mock = server
.mock("POST", "/test")
.with_status(200)
.create_async()
.await;
let mut client = create_test_client(&server.url());
let res = client
.post_raw_buffer(
format!("{}/test", server.url()),
b"raw data".to_vec(),
vec![("Content-Type".to_string(), "text/csv".to_string())],
)
.await;
assert!(res.is_ok());
mock.assert_async().await;
}
#[tokio::test]
async fn test_get_raw() {
let mut server = Server::new_async().await;
let mock = server
.mock("GET", "/test")
.with_status(200)
.with_body("raw response")
.create_async()
.await;
let mut client = create_test_client(&server.url());
let res = client
.get_raw(&format!("{}/test", server.url()), vec![])
.await;
assert!(res.is_ok());
mock.assert_async().await;
}
// --- REST methods ---
#[tokio::test]
async fn test_rest_get() {
let mut server = Server::new_async().await;
let mock = server
.mock("GET", "/some/path")
.with_status(200)
.with_body("ok")
.create_async()
.await;
let mut client = create_test_client(&server.url());
let res = client.rest_get("/some/path".to_string(), vec![]).await;
assert!(res.is_ok());
mock.assert_async().await;
}
#[tokio::test]
async fn test_rest_post() {
let mut server = Server::new_async().await;
let mock = server
.mock("POST", "/some/path")
.with_status(201)
.create_async()
.await;
let mut client = create_test_client(&server.url());
let mut params = std::collections::HashMap::new();
params.insert("key", "value");
let res = client.rest_post("/some/path".to_string(), params).await;
assert!(res.is_ok());
mock.assert_async().await;
}
#[tokio::test]
async fn test_rest_patch() {
let mut server = Server::new_async().await;
let mock = server
.mock("PATCH", "/some/path")
.with_status(204)
.create_async()
.await;
let mut client = create_test_client(&server.url());
let mut params = std::collections::HashMap::new();
params.insert("key", "value");
let res = client.rest_patch("/some/path".to_string(), params).await;
assert!(res.is_ok());
mock.assert_async().await;
}
#[tokio::test]
async fn test_rest_put() {
let mut server = Server::new_async().await;
let mock = server
.mock("PUT", "/some/path")
.with_status(200)
.create_async()
.await;
let mut client = create_test_client(&server.url());
let mut params = std::collections::HashMap::new();
params.insert("key", "value");
let res = client.rest_put("/some/path".to_string(), params).await;
assert!(res.is_ok());
mock.assert_async().await;
}
#[tokio::test]
async fn test_rest_delete() {
let mut server = Server::new_async().await;
let mock = server
.mock("DELETE", "/some/path")
.with_status(204)
.create_async()
.await;
let mut client = create_test_client(&server.url());
let res = client.rest_delete("/some/path".to_string()).await;
assert!(res.is_ok());
mock.assert_async().await;
}
// --- get_identity ---
#[tokio::test]
async fn test_get_identity_success() {
let mut server = Server::new_async().await;
let mock = server
.mock("GET", "/id/info")
.with_status(200)
.with_body(r#"{"user_id":"005xx","username":"test@test.com"}"#)
.create_async()
.await;
let mut client = create_test_client(&server.url());
let result = client
.get_identity(format!("{}/id/info", server.url()))
.await;
assert!(result.is_ok());
assert!(result.unwrap().contains("test@test.com"));
mock.assert_async().await;
}
#[tokio::test]
async fn test_get_identity_failure() {
let mut server = Server::new_async().await;
let mock = server
.mock("GET", "/id/info")
.with_status(400)
.with_header("content-type", "application/json")
.with_body(
json!({
"message": "Session expired",
"errorCode": "INVALID_SESSION_ID"
})
.to_string(),
)
.create_async()
.await;
let mut client = create_test_client(&server.url());
let result = client
.get_identity(format!("{}/id/info", server.url()))
.await;
assert!(result.is_err());
mock.assert_async().await;
}
// --- rest_get_fulluri ---
#[tokio::test]
async fn test_rest_get_fulluri() {
let mut server = Server::new_async().await;
let mock = server
.mock("GET", "/services/apexrest/MyEndpoint")
.match_query(mockito::Matcher::UrlEncoded("param".into(), "value".into()))
.with_status(200)
.with_body("ok")
.create_async()
.await;
let mut client = create_test_client(&server.url());
let res = client.rest_get_fulluri("MyEndpoint?param=value").await;
assert!(res.is_ok());
mock.assert_async().await;
}
// --- ensure_refresh with expired token ---
#[tokio::test]
async fn test_ensure_refresh_expired_token_triggers_refresh() {
let mut server = Server::new_async().await;
let mock = server
.mock("POST", "/services/oauth2/token")
.with_status(200)
.with_header("content-type", "application/json")
.with_body(
json!({
"access_token": "refreshed_token",
"issued_at": "9999999999000",
"id": "https://login.salesforce.com/id/00Dxx/005xx",
"instance_url": server.url(),
"signature": "sig",
"token_type": "Bearer",
})
.to_string(),
)
.create_async()
.await;
let mut client = Client::new();
client.set_login_endpoint(&server.url());
client.set_client_id("cid");
client.set_client_secret("csecret");
client.set_refresh_token("rtoken");
// Set a token with issued_at far in the past (expired > 2 hours ago)
client.set_access_token(
"old_token".to_string(),
"1000000000000".to_string(), // ~2001, well past 2 hours
"Bearer".to_string(),
);
let result = client.ensure_refresh().await;
assert!(result.is_ok());
assert_eq!(client.access_token_value(), Some("refreshed_token"));
mock.assert_async().await;
}
}