socket-patch-core 3.3.0

Core library for socket-patch: manifest, hash, crawlers, patch engine, API client
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
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
use std::collections::HashSet;

use reqwest::header::{self, HeaderMap, HeaderValue};
use reqwest::StatusCode;
use serde::Serialize;

use crate::api::types::*;
use crate::constants::{
    DEFAULT_PATCH_API_PROXY_URL, DEFAULT_SOCKET_API_URL, USER_AGENT as USER_AGENT_VALUE,
};
use crate::utils::env_compat::read_env_with_legacy;

/// Check if debug mode is enabled via SOCKET_DEBUG env (falling back to the
/// legacy SOCKET_PATCH_DEBUG name with a one-shot deprecation warning).
fn is_debug_enabled() -> bool {
    match read_env_with_legacy("SOCKET_DEBUG", "SOCKET_PATCH_DEBUG") {
        Some(val) => val == "1" || val == "true",
        None => false,
    }
}

/// Log debug messages when debug mode is enabled.
fn debug_log(message: &str) {
    if is_debug_enabled() {
        eprintln!("[socket-patch debug] {}", message);
    }
}

/// Severity order for sorting (most severe = lowest number).
fn get_severity_order(severity: Option<&str>) -> u8 {
    match severity.map(|s| s.to_lowercase()).as_deref() {
        Some("critical") => 0,
        Some("high") => 1,
        Some("medium") => 2,
        Some("low") => 3,
        _ => 4,
    }
}

/// Options for constructing an [`ApiClient`].
#[derive(Debug, Clone)]
pub struct ApiClientOptions {
    pub api_url: String,
    pub api_token: Option<String>,
    /// When true, the client will use the public patch API proxy
    /// which only provides access to free patches without authentication.
    pub use_public_proxy: bool,
    /// Organization slug for authenticated API access.
    /// Required when using authenticated API (not public proxy).
    pub org_slug: Option<String>,
}

/// HTTP client for the Socket Patch API.
///
/// Supports both the authenticated Socket API (`api.socket.dev`) and the
/// public proxy (`patches-api.socket.dev`) which serves free patches
/// without authentication.
#[derive(Debug, Clone)]
pub struct ApiClient {
    client: reqwest::Client,
    api_url: String,
    api_token: Option<String>,
    use_public_proxy: bool,
    org_slug: Option<String>,
}

/// Body payload for the batch search POST endpoint.
#[derive(Serialize)]
struct BatchSearchBody {
    components: Vec<BatchComponent>,
}

#[derive(Serialize)]
struct BatchComponent {
    purl: String,
}

impl ApiClient {
    /// Create a new API client from the given options.
    ///
    /// Constructs a `reqwest::Client` with proper default headers
    /// (User-Agent, Accept, and optionally Authorization).
    pub fn new(options: ApiClientOptions) -> Self {
        let api_url = options.api_url.trim_end_matches('/').to_string();

        let mut default_headers = HeaderMap::new();
        default_headers.insert(
            header::USER_AGENT,
            HeaderValue::from_static(USER_AGENT_VALUE),
        );
        default_headers.insert(header::ACCEPT, HeaderValue::from_static("application/json"));

        if let Some(ref token) = options.api_token {
            if let Ok(hv) = HeaderValue::from_str(&format!("Bearer {}", token)) {
                default_headers.insert(header::AUTHORIZATION, hv);
            }
        }

        let client = reqwest::Client::builder()
            .default_headers(default_headers)
            .build()
            .expect("failed to build reqwest client");

        Self {
            client,
            api_url,
            api_token: options.api_token,
            use_public_proxy: options.use_public_proxy,
            org_slug: options.org_slug,
        }
    }

    /// Returns the API token, if set.
    pub fn api_token(&self) -> Option<&String> {
        self.api_token.as_ref()
    }

    /// Returns the org slug, if set.
    pub fn org_slug(&self) -> Option<&String> {
        self.org_slug.as_ref()
    }

    // ── Internal helpers ──────────────────────────────────────────────

    /// Internal GET that deserialises JSON. Returns `Ok(None)` on 404.
    async fn get_json<T: serde::de::DeserializeOwned>(
        &self,
        path: &str,
    ) -> Result<Option<T>, ApiError> {
        let url = format!("{}{}", self.api_url, path);
        debug_log(&format!("GET {}", url));

        let resp = self
            .client
            .get(&url)
            .send()
            .await
            .map_err(|e| ApiError::Network(format!("Network error: {}", e)))?;

        Self::handle_json_response(resp, self.use_public_proxy).await
    }

    /// Internal POST that deserialises JSON. Returns `Ok(None)` on 404.
    async fn post_json<T: serde::de::DeserializeOwned, B: Serialize>(
        &self,
        path: &str,
        body: &B,
    ) -> Result<Option<T>, ApiError> {
        let url = format!("{}{}", self.api_url, path);
        debug_log(&format!("POST {}", url));

        let resp = self
            .client
            .post(&url)
            .header(header::CONTENT_TYPE, "application/json")
            .json(body)
            .send()
            .await
            .map_err(|e| ApiError::Network(format!("Network error: {}", e)))?;

        Self::handle_json_response(resp, self.use_public_proxy).await
    }

    /// Map an HTTP response to `Ok(Some(T))`, `Ok(None)` (404), or `Err`.
    async fn handle_json_response<T: serde::de::DeserializeOwned>(
        resp: reqwest::Response,
        use_public_proxy: bool,
    ) -> Result<Option<T>, ApiError> {
        let status = resp.status();

        match status {
            StatusCode::OK => {
                let body = resp
                    .json::<T>()
                    .await
                    .map_err(|e| ApiError::Parse(format!("Failed to parse response: {}", e)))?;
                Ok(Some(body))
            }
            StatusCode::NOT_FOUND => Ok(None),
            StatusCode::UNAUTHORIZED => Err(ApiError::Unauthorized(
                "Unauthorized: Invalid API token".into(),
            )),
            StatusCode::FORBIDDEN => {
                let msg = if use_public_proxy {
                    "Forbidden: This patch is only available to paid subscribers. \
                     Sign up at https://socket.dev to access paid patches."
                } else {
                    "Forbidden: Access denied. This may be a paid patch or \
                     you may not have access to this organization."
                };
                Err(ApiError::Forbidden(msg.into()))
            }
            StatusCode::TOO_MANY_REQUESTS => Err(ApiError::RateLimited(
                "Rate limit exceeded. Please try again later.".into(),
            )),
            _ => {
                let text = resp.text().await.unwrap_or_default();
                Err(ApiError::Other(format!(
                    "API request failed with status {}: {}",
                    status.as_u16(),
                    text
                )))
            }
        }
    }

    // ── Public API methods ────────────────────────────────────────────

    /// Fetch a patch by UUID (full details with blob content).
    ///
    /// Returns `Ok(None)` when the patch is not found (404).
    pub async fn fetch_patch(
        &self,
        org_slug: Option<&str>,
        uuid: &str,
    ) -> Result<Option<PatchResponse>, ApiError> {
        let path = if self.use_public_proxy {
            format!("/patch/view/{}", uuid)
        } else {
            let slug = org_slug.or(self.org_slug.as_deref()).unwrap_or("default");
            format!("/v0/orgs/{}/patches/view/{}", slug, uuid)
        };
        self.get_json(&path).await
    }

    /// Shared implementation for `search_patches_by_{cve,ghsa,package}`.
    /// `route` is the `by-<x>` URL segment — the rest of the path layout
    /// is identical across the three endpoints.
    async fn search_patches_by_route(
        &self,
        org_slug: Option<&str>,
        route: &str,
        identifier: &str,
    ) -> Result<SearchResponse, ApiError> {
        let encoded = urlencoding_encode(identifier);
        let path = if self.use_public_proxy {
            format!("/patch/{route}/{encoded}")
        } else {
            let slug = org_slug.or(self.org_slug.as_deref()).unwrap_or("default");
            format!("/v0/orgs/{slug}/patches/{route}/{encoded}")
        };
        let result = self.get_json::<SearchResponse>(&path).await?;
        Ok(result.unwrap_or_else(|| SearchResponse {
            patches: Vec::new(),
            can_access_paid_patches: false,
        }))
    }

    /// Search patches by CVE ID.
    pub async fn search_patches_by_cve(
        &self,
        org_slug: Option<&str>,
        cve_id: &str,
    ) -> Result<SearchResponse, ApiError> {
        self.search_patches_by_route(org_slug, "by-cve", cve_id)
            .await
    }

    /// Search patches by GHSA ID.
    pub async fn search_patches_by_ghsa(
        &self,
        org_slug: Option<&str>,
        ghsa_id: &str,
    ) -> Result<SearchResponse, ApiError> {
        self.search_patches_by_route(org_slug, "by-ghsa", ghsa_id)
            .await
    }

    /// Search patches by package PURL.
    ///
    /// The PURL must be a valid Package URL starting with `pkg:`.
    /// Examples: `pkg:npm/lodash@4.17.21`, `pkg:pypi/django@3.2.0`
    pub async fn search_patches_by_package(
        &self,
        org_slug: Option<&str>,
        purl: &str,
    ) -> Result<SearchResponse, ApiError> {
        self.search_patches_by_route(org_slug, "by-package", purl)
            .await
    }

    /// Search patches for multiple packages (batch).
    ///
    /// For authenticated API, uses the POST `/patches/batch` endpoint.
    /// For the public proxy (which cannot cache POST bodies on CDN), falls
    /// back to individual GET requests per PURL with a concurrency limit of
    /// 10.
    ///
    /// Maximum 500 PURLs per request.
    pub async fn search_patches_batch(
        &self,
        org_slug: Option<&str>,
        purls: &[String],
    ) -> Result<BatchSearchResponse, ApiError> {
        if !self.use_public_proxy {
            let slug = org_slug.or(self.org_slug.as_deref()).unwrap_or("default");
            let path = format!("/v0/orgs/{}/patches/batch", slug);
            let body = BatchSearchBody {
                components: purls
                    .iter()
                    .map(|p| BatchComponent { purl: p.clone() })
                    .collect(),
            };
            let result = self
                .post_json::<BatchSearchResponse, _>(&path, &body)
                .await?;
            return Ok(result.unwrap_or_else(|| BatchSearchResponse {
                packages: Vec::new(),
                can_access_paid_patches: false,
            }));
        }

        // Public proxy: fall back to individual per-package GET requests
        self.search_patches_batch_via_individual_queries(purls)
            .await
    }

    /// Internal: fall back to individual GET requests per PURL when the
    /// batch endpoint is not available (public proxy mode).
    ///
    /// Processes PURLs in batches of `CONCURRENCY_LIMIT` to avoid
    /// overwhelming the server while remaining efficient.
    async fn search_patches_batch_via_individual_queries(
        &self,
        purls: &[String],
    ) -> Result<BatchSearchResponse, ApiError> {
        const CONCURRENCY_LIMIT: usize = 10;

        // Collect all (purl, response) pairs
        let mut all_results: Vec<(String, Option<SearchResponse>)> = Vec::new();

        for chunk in purls.chunks(CONCURRENCY_LIMIT) {
            // Use tokio::JoinSet for concurrent execution within each chunk
            let mut join_set = tokio::task::JoinSet::new();

            for purl in chunk {
                let purl = purl.clone();
                let client = self.clone();
                join_set.spawn(async move {
                    let resp = client.search_patches_by_package(None, &purl).await;
                    match resp {
                        Ok(r) => (purl, Some(r)),
                        Err(e) => {
                            debug_log(&format!("Error fetching patches for {}: {}", purl, e));
                            (purl, None)
                        }
                    }
                });
            }

            while let Some(result) = join_set.join_next().await {
                match result {
                    Ok(pair) => all_results.push(pair),
                    Err(e) => {
                        debug_log(&format!("Task join error: {}", e));
                    }
                }
            }
        }

        // Convert the individual SearchResponse results into the batch shape.
        Ok(assemble_batch_from_individual(all_results))
    }

    /// Fetch organizations accessible to the current API token.
    pub async fn fetch_organizations(
        &self,
    ) -> Result<Vec<crate::api::types::OrganizationInfo>, ApiError> {
        let path = "/v0/organizations";
        match self
            .get_json::<crate::api::types::OrganizationsResponse>(path)
            .await?
        {
            Some(resp) => Ok(resp.organizations.into_values().collect()),
            None => Ok(Vec::new()),
        }
    }

    /// Resolve the org slug from the API token by querying `/v0/organizations`.
    ///
    /// If there is exactly one org, returns its slug.
    /// If there are multiple, picks the first and prints a warning.
    /// If there are none, returns an error.
    pub async fn resolve_org_slug(&self) -> Result<String, ApiError> {
        let orgs = self.fetch_organizations().await?;
        select_org_slug(orgs)
    }

    /// Fetch a blob by its SHA-256 hash.
    ///
    /// Returns the raw binary content, or `Ok(None)` if not found.
    /// Uses the authenticated endpoint when token and org slug are
    /// available, otherwise falls back to the public proxy.
    pub async fn fetch_blob(&self, hash: &str) -> Result<Option<Vec<u8>>, ApiError> {
        // Validate hash format: SHA-256 = 64 hex characters
        if !is_valid_sha256_hex(hash) {
            return Err(ApiError::InvalidHash(format!(
                "Invalid hash format: {}. Expected SHA256 hash (64 hex characters).",
                hash
            )));
        }
        self.fetch_binary("blob", "blob", hash).await
    }

    /// Fetch a per-file diff archive (tar.gz of bsdiff deltas) by patch UUID.
    ///
    /// Returns the raw archive bytes, or `Ok(None)` if not found (404). The
    /// public proxy serves these under `/patch/diff/<uuid>`; the
    /// authenticated API serves them under `/v0/orgs/<slug>/patches/diff/<uuid>`.
    pub async fn fetch_diff(&self, uuid: &str) -> Result<Option<Vec<u8>>, ApiError> {
        if !is_valid_uuid(uuid) {
            return Err(ApiError::InvalidHash(format!(
                "Invalid patch UUID: {}",
                uuid
            )));
        }
        self.fetch_binary("diff", "diff", uuid).await
    }

    /// Fetch a per-package patch archive (tar.gz of patched files) by patch UUID.
    ///
    /// Returns the raw archive bytes, or `Ok(None)` if not found (404).
    pub async fn fetch_package(&self, uuid: &str) -> Result<Option<Vec<u8>>, ApiError> {
        if !is_valid_uuid(uuid) {
            return Err(ApiError::InvalidHash(format!(
                "Invalid patch UUID: {}",
                uuid
            )));
        }
        self.fetch_binary("package", "package", uuid).await
    }

    /// Build the URL (and an `is_authenticated` flag) for a binary fetch of
    /// `kind` (`blob` / `diff` / `package`) identified by `identifier`.
    ///
    /// Uses the authenticated `/v0/orgs/<slug>/patches/...` endpoint when a
    /// token and org slug are configured (and we're not pinned to the public
    /// proxy). Otherwise it targets the public proxy.
    ///
    /// In public-proxy mode the base is the client's own configured `api_url`
    /// — the same value the JSON endpoints (`get_json`/`post_json`) use — so an
    /// explicit `--proxy-url` / `SOCKET_PROXY_URL` override is honored for
    /// binary downloads too. Only when falling back from an *authenticated*
    /// client that lacks an org slug (so `api_url` is the auth host, not a
    /// proxy) do we re-derive the proxy base from the environment.
    fn binary_url(&self, kind: &str, identifier: &str) -> (String, bool) {
        if self.api_token.is_some() && self.org_slug.is_some() && !self.use_public_proxy {
            let slug = self.org_slug.as_deref().unwrap();
            let u = format!(
                "{}/v0/orgs/{}/patches/{}/{}",
                self.api_url, slug, kind, identifier
            );
            (u, true)
        } else {
            let base = if self.use_public_proxy {
                self.api_url.clone()
            } else {
                read_env_with_legacy("SOCKET_PROXY_URL", "SOCKET_PATCH_PROXY_URL")
                    .unwrap_or_else(|| DEFAULT_PATCH_API_PROXY_URL.to_string())
            };
            let u = format!(
                "{}/patch/{}/{}",
                base.trim_end_matches('/'),
                kind,
                identifier
            );
            (u, false)
        }
    }

    /// Shared implementation for `fetch_blob` / `fetch_diff` / `fetch_package`.
    ///
    /// `kind` is the URL segment (`blob` / `diff` / `package`). `label` is the
    /// human-readable noun used in log + error messages. `identifier` is the
    /// hash or UUID interpolated into the URL.
    async fn fetch_binary(
        &self,
        kind: &str,
        label: &str,
        identifier: &str,
    ) -> Result<Option<Vec<u8>>, ApiError> {
        let (url, use_auth) = self.binary_url(kind, identifier);

        debug_log(&format!("GET {} {}", label, url));

        // Build the request. When fetching from the public proxy (different
        // base URL than self.api_url), we use a plain client without auth
        // headers to avoid leaking credentials to the proxy.
        let resp = if use_auth {
            self.client
                .get(&url)
                .header(header::ACCEPT, "application/octet-stream")
                .send()
                .await
        } else {
            let mut headers = HeaderMap::new();
            headers.insert(
                header::USER_AGENT,
                HeaderValue::from_static(USER_AGENT_VALUE),
            );
            headers.insert(
                header::ACCEPT,
                HeaderValue::from_static("application/octet-stream"),
            );

            let plain_client = reqwest::Client::builder()
                .default_headers(headers)
                .build()
                .expect("failed to build plain reqwest client");

            plain_client.get(&url).send().await
        };

        let resp = resp.map_err(|e| {
            ApiError::Network(format!(
                "Network error fetching {} {}: {}",
                label, identifier, e
            ))
        })?;

        let status = resp.status();

        match status {
            StatusCode::OK => {
                let bytes = resp.bytes().await.map_err(|e| {
                    ApiError::Network(format!(
                        "Error reading {} body for {}: {}",
                        label, identifier, e
                    ))
                })?;
                Ok(Some(bytes.to_vec()))
            }
            StatusCode::NOT_FOUND => Ok(None),
            _ => {
                let text = resp.text().await.unwrap_or_default();
                Err(ApiError::Other(format!(
                    "Failed to fetch {} {}: status {} - {}",
                    label,
                    identifier,
                    status.as_u16(),
                    text,
                )))
            }
        }
    }
}

// ── Free functions ────────────────────────────────────────────────────

/// Explicit overrides for environment-based API client construction.
///
/// Each `Some(value)` wins over the corresponding env var; `None` falls
/// back to env-var lookup (with the legacy `SOCKET_PATCH_*` shim where
/// applicable).
#[derive(Debug, Clone, Default)]
pub struct ApiClientEnvOverrides {
    pub api_url: Option<String>,
    pub api_token: Option<String>,
    pub org_slug: Option<String>,
    pub proxy_url: Option<String>,
}

/// Get an API client configured from environment variables.
///
/// If `SOCKET_API_TOKEN` is not set, the client will use the public patch
/// API proxy which provides free access to free-tier patches without
/// authentication.
///
/// When `SOCKET_API_TOKEN` is set but no org slug is provided (neither via
/// argument nor `SOCKET_ORG_SLUG` env var), the function will attempt to
/// auto-resolve the org slug by querying `GET /v0/organizations`.
///
/// # Environment variables
///
/// | Variable | Purpose |
/// |---|---|
/// | `SOCKET_API_URL` | Override the API URL (default `https://api.socket.dev`) |
/// | `SOCKET_API_TOKEN` | API token for authenticated access |
/// | `SOCKET_PROXY_URL` | Override the public proxy URL (default `https://patches-api.socket.dev`). Legacy: `SOCKET_PATCH_PROXY_URL`. |
/// | `SOCKET_ORG_SLUG` | Organization slug |
///
/// Returns `(client, use_public_proxy)`.
pub async fn get_api_client_from_env(org_slug: Option<&str>) -> (ApiClient, bool) {
    get_api_client_with_overrides(ApiClientEnvOverrides {
        org_slug: org_slug.map(String::from),
        ..ApiClientEnvOverrides::default()
    })
    .await
}

/// Like [`get_api_client_from_env`] but with explicit overrides for every
/// env-driven knob. Each `Some(value)` in `overrides` wins over the
/// corresponding env var. Used by CLI commands that expose `--api-url`,
/// `--api-token`, `--org`, `--proxy-url` flags via [`crate::utils`] in the
/// CLI crate.
pub async fn get_api_client_with_overrides(overrides: ApiClientEnvOverrides) -> (ApiClient, bool) {
    let api_token = overrides
        .api_token
        .or_else(|| std::env::var("SOCKET_API_TOKEN").ok())
        .filter(|t| !t.is_empty());
    let resolved_org_slug = overrides
        .org_slug
        .or_else(|| std::env::var("SOCKET_ORG_SLUG").ok());

    if api_token.is_none() {
        let proxy_url = overrides.proxy_url.unwrap_or_else(|| {
            read_env_with_legacy("SOCKET_PROXY_URL", "SOCKET_PATCH_PROXY_URL")
                .unwrap_or_else(|| DEFAULT_PATCH_API_PROXY_URL.to_string())
        });
        eprintln!("No SOCKET_API_TOKEN set. Using public patch API proxy (free patches only).");
        let client = ApiClient::new(ApiClientOptions {
            api_url: proxy_url,
            api_token: None,
            use_public_proxy: true,
            org_slug: None,
        });
        return (client, true);
    }

    // Shape check the configured token before the network round-trip so
    // a "you set the hash, not the token" mistake is loud and immediate.
    if let Some(ref t) = api_token {
        if let Some(msg) = validate_token_shape(t) {
            eprintln!("{msg}");
        }
    }

    let api_url = overrides
        .api_url
        .or_else(|| std::env::var("SOCKET_API_URL").ok())
        .unwrap_or_else(|| DEFAULT_SOCKET_API_URL.to_string());

    // Auto-resolve org slug if not provided
    let final_org_slug = if resolved_org_slug.is_some() {
        resolved_org_slug
    } else {
        let temp_client = ApiClient::new(ApiClientOptions {
            api_url: api_url.clone(),
            api_token: api_token.clone(),
            use_public_proxy: false,
            org_slug: None,
        });
        match temp_client.resolve_org_slug().await {
            Ok(slug) => Some(slug),
            Err(e) => {
                eprintln!("Warning: Could not auto-detect organization: {e}");
                if matches!(e, ApiError::Unauthorized(_)) {
                    if let Some(ref t) = api_token {
                        if looks_like_token_hash(t) {
                            eprintln!(
                                "  Hint: SOCKET_API_TOKEN starts with `{}-` \
                                 which is the stored hash format. Set it to \
                                 the raw `sktsec_..._api` value instead.",
                                t.split('-').next().unwrap_or("sha512")
                            );
                        }
                    }
                }
                None
            }
        }
    };

    let client = ApiClient::new(ApiClientOptions {
        api_url,
        api_token,
        use_public_proxy: false,
        org_slug: final_org_slug,
    });
    (client, false)
}

/// Build a public-proxy `ApiClient` from the same overrides used by
/// [`get_api_client_with_overrides`], ignoring any API token.
///
/// Used by `scan` and `get` to retry against the public proxy after
/// the authenticated endpoint returns 401/403 — a stale/revoked token
/// shouldn't block access to free patches. The auth header is
/// deliberately dropped (`api_token: None`).
pub fn build_proxy_fallback_client(overrides: &ApiClientEnvOverrides) -> ApiClient {
    let proxy_url = overrides.proxy_url.clone().unwrap_or_else(|| {
        read_env_with_legacy("SOCKET_PROXY_URL", "SOCKET_PATCH_PROXY_URL")
            .unwrap_or_else(|| DEFAULT_PATCH_API_PROXY_URL.to_string())
    });
    ApiClient::new(ApiClientOptions {
        api_url: proxy_url,
        api_token: None,
        use_public_proxy: true,
        org_slug: None,
    })
}

/// Return `true` when the configured token value looks like an
/// SRI-format hash (`sha512-<base64>` etc.) rather than a raw API
/// token. The server stores tokens *as* this hash; the CLI sometimes
/// gets configured with the storage representation by mistake (users
/// copy what they see in the dashboard). Surfacing this as a hint
/// short-circuits a confusing 401 round-trip.
pub fn looks_like_token_hash(token: &str) -> bool {
    matches!(
        token.split_once('-'),
        Some(("sha256" | "sha384" | "sha512", _))
    )
}

/// Inspect a configured `SOCKET_API_TOKEN` value and return a
/// human-readable warning when the value doesn't match the canonical
/// Socket API token shape (`sktsec_<44 chars>_api`). Returns `None`
/// when the token looks valid, so the caller can ignore the result
/// without checking length.
///
/// The validation is intentionally a non-authoritative shape check —
/// the server's regex is the source of truth. We only flag values
/// that are *obviously* wrong (e.g. the storage hash, an empty
/// prefix/suffix) so a benign typo at the server's regex boundary
/// doesn't generate noise.
///
/// The returned message redacts the middle of the token (first 8 +
/// last 4 chars) so a real token doesn't leak into stderr if a user
/// pastes one with a wrong suffix.
pub fn validate_token_shape(token: &str) -> Option<String> {
    let has_prefix = token.starts_with("sktsec_");
    let has_suffix = token.ends_with("_api") || token.ends_with("_agent");
    let plausible_len = token.len() >= 55;
    if has_prefix && has_suffix && plausible_len {
        return None;
    }
    let len = token.len();
    let head: String = token.chars().take(8).collect();
    let tail_start = len.saturating_sub(4);
    let tail: String = token.chars().skip(tail_start).collect();
    let preview = if len <= 12 {
        token.to_string()
    } else {
        format!("{head}...{tail}")
    };
    let hash_hint = if looks_like_token_hash(token) {
        "\n  That value looks like an SRI-format hash (sha###-<base64>) — \
         the server stores the *hash* of your token, not what you should \
         set here. Use the raw `sktsec_..._api` value shown when the token \
         was generated."
    } else {
        ""
    };
    Some(format!(
        "Warning: SOCKET_API_TOKEN does not look like a Socket API token \
         (expected `sktsec_<44 chars>_api`).{hash_hint}\n  \
         Got: {preview} ({len} chars). Continuing anyway; the server may \
         reject this with 401."
    ))
}

/// Classify an [`ApiError`] as a candidate for the auth → proxy
/// fallback. We only re-route on 401/403 (the stale-credentials
/// signals). Network errors, rate limits, 404s, and 5xx surface as-is
/// so they remain visible to the operator.
pub fn is_fallback_candidate(err: &ApiError) -> bool {
    matches!(err, ApiError::Unauthorized(_) | ApiError::Forbidden(_))
}

/// Choose an org slug from the list returned by `/v0/organizations`.
///
/// Returns an error when the list is empty, the sole slug when there is
/// exactly one, and the first slug (with a warning) when there are several.
///
/// `fetch_organizations` collects from a `HashMap`, so the upstream order is
/// not stable across runs. We sort by slug first so the chosen org *and* the
/// warning text are deterministic — otherwise a token with multiple orgs
/// could silently operate against a different org on each invocation.
fn select_org_slug(mut orgs: Vec<crate::api::types::OrganizationInfo>) -> Result<String, ApiError> {
    orgs.sort_by(|a, b| a.slug.cmp(&b.slug));
    match orgs.len() {
        0 => Err(ApiError::Other(
            "No organizations found for this API token.".into(),
        )),
        1 => Ok(orgs.into_iter().next().unwrap().slug),
        _ => {
            let slugs: Vec<_> = orgs.iter().map(|o| o.slug.as_str()).collect();
            let first = orgs[0].slug.clone();
            eprintln!(
                "Multiple organizations found: {}. Using \"{}\". \
                 Pass --org to select a different one.",
                slugs.join(", "),
                first
            );
            Ok(first)
        }
    }
}

// ── Helpers ───────────────────────────────────────────────────────────

/// Percent-encode a string for use in URL path segments.
fn urlencoding_encode(input: &str) -> String {
    // Encode everything that is not unreserved per RFC 3986.
    let mut out = String::with_capacity(input.len());
    for byte in input.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(byte as char)
            }
            _ => {
                out.push('%');
                out.push_str(&format!("{:02X}", byte));
            }
        }
    }
    out
}

/// Truncate a string to at most `max_chars` characters, appending "..." if truncated.
/// Unlike byte slicing (`&s[..n]`), this is safe for multi-byte UTF-8 characters.
fn truncate_to_chars(s: &str, max_chars: usize) -> String {
    if s.chars().count() <= max_chars {
        return s.to_string();
    }
    let truncated: String = s.chars().take(max_chars).collect();
    format!("{}...", truncated)
}

/// Validate that a string is a 64-character hex string (SHA-256).
fn is_valid_sha256_hex(s: &str) -> bool {
    s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit())
}

/// Validate the standard 8-4-4-4-12 UUID hex grouping.
fn is_valid_uuid(s: &str) -> bool {
    let parts: Vec<&str> = s.split('-').collect();
    if parts.len() != 5 {
        return false;
    }
    let lengths = [8, 4, 4, 4, 12];
    parts
        .iter()
        .zip(lengths.iter())
        .all(|(part, &want)| part.len() == want && part.bytes().all(|b| b.is_ascii_hexdigit()))
}

/// Convert a `PatchSearchResult` into a `BatchPatchInfo`, extracting
/// CVE/GHSA IDs and computing the highest severity.
fn convert_search_result_to_batch_info(patch: PatchSearchResult) -> BatchPatchInfo {
    let mut cve_ids: Vec<String> = Vec::new();
    let mut ghsa_ids: Vec<String> = Vec::new();
    let mut highest_severity: Option<String> = None;
    let mut title = String::new();

    let mut seen_cves: HashSet<String> = HashSet::new();

    // `vulnerabilities` is a HashMap, so iterate in a stable (GHSA-id) order.
    // Otherwise the chosen `title` (first non-empty summary) — and the
    // first-seen tie-break for equal severities — would vary across runs.
    let mut entries: Vec<(&String, &VulnerabilityResponse)> =
        patch.vulnerabilities.iter().collect();
    entries.sort_by(|a, b| a.0.cmp(b.0));

    for (ghsa_id, vuln) in entries {
        ghsa_ids.push(ghsa_id.clone());

        for cve in &vuln.cves {
            if seen_cves.insert(cve.clone()) {
                cve_ids.push(cve.clone());
            }
        }

        // Track highest severity (lower order number = higher severity)
        let current_order = get_severity_order(highest_severity.as_deref());
        let vuln_order = get_severity_order(Some(&vuln.severity));
        if vuln_order < current_order {
            highest_severity = Some(vuln.severity.clone());
        }

        // Use first non-empty summary as title
        if title.is_empty() && !vuln.summary.is_empty() {
            title = truncate_to_chars(&vuln.summary, 97);
        }
    }

    // Use description as fallback title
    if title.is_empty() && !patch.description.is_empty() {
        title = truncate_to_chars(&patch.description, 97);
    }

    cve_ids.sort();
    ghsa_ids.sort();

    BatchPatchInfo {
        uuid: patch.uuid,
        purl: patch.purl,
        tier: patch.tier,
        cve_ids,
        ghsa_ids,
        severity: highest_severity,
        title,
    }
}

/// Assemble a [`BatchSearchResponse`] from the per-PURL [`SearchResponse`]s
/// gathered by the public-proxy fallback (one GET per package).
///
/// A `None` entry is a query that errored and is skipped. The
/// `can_access_paid_patches` capability is OR-aggregated across **every**
/// successful response — independent of whether that response carried any
/// patches — because it is a global capability signal, not a per-package
/// one. The empty-patches check only governs whether a package is added to
/// the `packages` list (an empty package would be noise), so it must run
/// *after* the flag is observed; folding it into the same skip would drop a
/// `canAccessPaidPatches: true` that arrived alongside an empty patch list.
fn assemble_batch_from_individual(
    results: Vec<(String, Option<SearchResponse>)>,
) -> BatchSearchResponse {
    let mut packages: Vec<BatchPackagePatches> = Vec::new();
    let mut can_access_paid_patches = false;

    for (purl, response) in results {
        let Some(response) = response else { continue };

        if response.can_access_paid_patches {
            can_access_paid_patches = true;
        }

        if response.patches.is_empty() {
            continue;
        }

        let batch_patches: Vec<BatchPatchInfo> = response
            .patches
            .into_iter()
            .map(convert_search_result_to_batch_info)
            .collect();

        packages.push(BatchPackagePatches {
            purl,
            patches: batch_patches,
        });
    }

    BatchSearchResponse {
        packages,
        can_access_paid_patches,
    }
}

// ── Error type ────────────────────────────────────────────────────────

/// Errors returned by [`ApiClient`] methods.
#[derive(Debug, thiserror::Error)]
pub enum ApiError {
    #[error("{0}")]
    Network(String),

    #[error("{0}")]
    Parse(String),

    #[error("{0}")]
    Unauthorized(String),

    #[error("{0}")]
    Forbidden(String),

    #[error("{0}")]
    RateLimited(String),

    #[error("{0}")]
    InvalidHash(String),

    #[error("{0}")]
    Other(String),
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    #[test]
    fn test_urlencoding_basic() {
        assert_eq!(urlencoding_encode("hello"), "hello");
        assert_eq!(urlencoding_encode("a b"), "a%20b");
        assert_eq!(
            urlencoding_encode("pkg:npm/lodash@4.17.21"),
            "pkg%3Anpm%2Flodash%404.17.21"
        );
    }

    #[test]
    fn test_is_valid_sha256_hex() {
        let valid = "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789";
        assert!(is_valid_sha256_hex(valid));

        // Too short
        assert!(!is_valid_sha256_hex("abcdef"));
        // Non-hex
        assert!(!is_valid_sha256_hex(
            "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
        ));
    }

    #[test]
    fn test_severity_order() {
        assert!(get_severity_order(Some("critical")) < get_severity_order(Some("high")));
        assert!(get_severity_order(Some("high")) < get_severity_order(Some("medium")));
        assert!(get_severity_order(Some("medium")) < get_severity_order(Some("low")));
        assert!(get_severity_order(Some("low")) < get_severity_order(None));
        assert_eq!(
            get_severity_order(Some("unknown")),
            get_severity_order(None)
        );
    }

    #[test]
    fn test_convert_search_result_to_batch_info() {
        let mut vulns = HashMap::new();
        vulns.insert(
            "GHSA-1234-5678-9abc".to_string(),
            VulnerabilityResponse {
                cves: vec!["CVE-2024-0001".into()],
                summary: "Test vulnerability".into(),
                severity: "high".into(),
                description: "A test vuln".into(),
            },
        );

        let patch = PatchSearchResult {
            uuid: "uuid-1".into(),
            purl: "pkg:npm/test@1.0.0".into(),
            published_at: "2024-01-01".into(),
            description: "A patch".into(),
            license: "MIT".into(),
            tier: "free".into(),
            vulnerabilities: vulns,
        };

        let info = convert_search_result_to_batch_info(patch);
        assert_eq!(info.uuid, "uuid-1");
        assert_eq!(info.cve_ids, vec!["CVE-2024-0001"]);
        assert_eq!(info.ghsa_ids, vec!["GHSA-1234-5678-9abc"]);
        assert_eq!(info.severity, Some("high".into()));
        assert_eq!(info.title, "Test vulnerability");
    }

    #[tokio::test]
    async fn test_get_api_client_from_env_no_token() {
        // Clear token to ensure public proxy mode
        std::env::remove_var("SOCKET_API_TOKEN");
        let (client, is_public) = get_api_client_from_env(None).await;
        assert!(is_public);
        assert!(client.use_public_proxy);
    }

    // ── Group 6: convert_search_result_to_batch_info edge cases ──────

    fn make_vuln(summary: &str, severity: &str, cves: Vec<&str>) -> VulnerabilityResponse {
        VulnerabilityResponse {
            cves: cves.into_iter().map(String::from).collect(),
            summary: summary.into(),
            severity: severity.into(),
            description: "desc".into(),
        }
    }

    fn make_patch(
        vulns: HashMap<String, VulnerabilityResponse>,
        description: &str,
    ) -> PatchSearchResult {
        PatchSearchResult {
            uuid: "uuid-1".into(),
            purl: "pkg:npm/test@1.0.0".into(),
            published_at: "2024-01-01".into(),
            description: description.into(),
            license: "MIT".into(),
            tier: "free".into(),
            vulnerabilities: vulns,
        }
    }

    #[test]
    fn test_convert_no_vulnerabilities() {
        let patch = make_patch(HashMap::new(), "A patch description");
        let info = convert_search_result_to_batch_info(patch);
        assert!(info.cve_ids.is_empty());
        assert!(info.ghsa_ids.is_empty());
        assert_eq!(info.title, "A patch description");
        assert!(info.severity.is_none());
    }

    #[test]
    fn test_convert_multiple_vulns_picks_highest_severity() {
        let mut vulns = HashMap::new();
        vulns.insert(
            "GHSA-1111".into(),
            make_vuln("Medium vuln", "medium", vec!["CVE-2024-0001"]),
        );
        vulns.insert(
            "GHSA-2222".into(),
            make_vuln("Critical vuln", "critical", vec!["CVE-2024-0002"]),
        );
        let patch = make_patch(vulns, "desc");
        let info = convert_search_result_to_batch_info(patch);
        assert_eq!(info.severity, Some("critical".into()));
    }

    #[test]
    fn test_convert_duplicate_cves_deduplicated() {
        let mut vulns = HashMap::new();
        vulns.insert(
            "GHSA-1111".into(),
            make_vuln("Vuln A", "high", vec!["CVE-2024-0001"]),
        );
        vulns.insert(
            "GHSA-2222".into(),
            make_vuln("Vuln B", "high", vec!["CVE-2024-0001"]),
        );
        let patch = make_patch(vulns, "desc");
        let info = convert_search_result_to_batch_info(patch);
        // Same CVE in both vulns should only appear once
        let cve_count = info
            .cve_ids
            .iter()
            .filter(|c| *c == "CVE-2024-0001")
            .count();
        assert_eq!(cve_count, 1);
    }

    #[test]
    fn test_convert_title_truncated_at_100() {
        let long_summary = "x".repeat(150);
        let mut vulns = HashMap::new();
        vulns.insert("GHSA-1111".into(), make_vuln(&long_summary, "high", vec![]));
        let patch = make_patch(vulns, "desc");
        let info = convert_search_result_to_batch_info(patch);
        // Should be 97 chars + "..." = 100 chars
        assert_eq!(info.title.len(), 100);
        assert!(info.title.ends_with("..."));
    }

    #[test]
    fn test_convert_title_unicode_truncation() {
        // Create a summary with multi-byte chars that would panic with byte slicing
        // Each emoji is 4 bytes, so 30 emojis = 120 bytes but only 30 chars
        let emoji_summary = "\u{1F600}".repeat(30);
        let mut vulns = HashMap::new();
        vulns.insert(
            "GHSA-1111".into(),
            make_vuln(&emoji_summary, "high", vec![]),
        );
        let patch = make_patch(vulns, "desc");
        // This should NOT panic (validates the UTF-8 truncation fix)
        let info = convert_search_result_to_batch_info(patch);
        assert!(!info.title.is_empty());

        // Also test with description fallback
        let patch2 = make_patch(HashMap::new(), &"\u{1F600}".repeat(120));
        let info2 = convert_search_result_to_batch_info(patch2);
        assert!(info2.title.ends_with("..."));
    }

    #[test]
    fn test_convert_title_falls_back_to_description() {
        let mut vulns = HashMap::new();
        vulns.insert("GHSA-1111".into(), make_vuln("", "high", vec![]));
        let patch = make_patch(vulns, "Fallback desc");
        let info = convert_search_result_to_batch_info(patch);
        assert_eq!(info.title, "Fallback desc");
    }

    #[test]
    fn test_convert_empty_summary_and_description() {
        let mut vulns = HashMap::new();
        vulns.insert("GHSA-1111".into(), make_vuln("", "high", vec![]));
        let patch = make_patch(vulns, "");
        let info = convert_search_result_to_batch_info(patch);
        assert!(info.title.is_empty());
    }

    #[test]
    fn test_convert_cves_and_ghsas_sorted() {
        let mut vulns = HashMap::new();
        vulns.insert(
            "GHSA-cccc".into(),
            make_vuln("V1", "high", vec!["CVE-2024-0003"]),
        );
        vulns.insert(
            "GHSA-aaaa".into(),
            make_vuln("V2", "high", vec!["CVE-2024-0001"]),
        );
        vulns.insert(
            "GHSA-bbbb".into(),
            make_vuln("V3", "high", vec!["CVE-2024-0002"]),
        );
        let patch = make_patch(vulns, "desc");
        let info = convert_search_result_to_batch_info(patch);
        // Both should be sorted alphabetically
        let mut sorted_cves = info.cve_ids.clone();
        sorted_cves.sort();
        assert_eq!(info.cve_ids, sorted_cves);
        let mut sorted_ghsas = info.ghsa_ids.clone();
        sorted_ghsas.sort();
        assert_eq!(info.ghsa_ids, sorted_ghsas);
    }

    // ── Group 7: urlencoding + SHA256 edge cases ─────────────────────

    #[test]
    fn test_urlencoding_unicode() {
        // Multi-byte UTF-8: 'é' = 0xC3 0xA9
        let encoded = urlencoding_encode("café");
        assert_eq!(encoded, "caf%C3%A9");
    }

    #[test]
    fn test_urlencoding_empty() {
        assert_eq!(urlencoding_encode(""), "");
    }

    #[test]
    fn test_urlencoding_all_safe_chars() {
        // Unreserved chars should pass through
        let safe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~";
        assert_eq!(urlencoding_encode(safe), safe);
    }

    #[test]
    fn test_urlencoding_slash_and_at() {
        assert_eq!(urlencoding_encode("/"), "%2F");
        assert_eq!(urlencoding_encode("@"), "%40");
    }

    #[test]
    fn test_sha256_uppercase_valid() {
        let upper = "ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789";
        assert!(is_valid_sha256_hex(upper));
    }

    #[test]
    fn test_sha256_65_chars_invalid() {
        let too_long = "a".repeat(65);
        assert!(!is_valid_sha256_hex(&too_long));
    }

    #[test]
    fn test_sha256_63_chars_invalid() {
        let too_short = "a".repeat(63);
        assert!(!is_valid_sha256_hex(&too_short));
    }

    #[test]
    fn test_sha256_empty_invalid() {
        assert!(!is_valid_sha256_hex(""));
    }

    #[test]
    fn test_sha256_mixed_case_valid() {
        let mixed = "aAbBcCdDeEfF0123456789aAbBcCdDeEfF0123456789aAbBcCdDeEfF01234567";
        assert_eq!(mixed.len(), 64);
        assert!(is_valid_sha256_hex(mixed));
    }

    // ── UUID validation tests ───────────────────────────────────────

    #[test]
    fn test_is_valid_uuid_accepts_standard_form() {
        assert!(is_valid_uuid("80630680-4da6-45f9-bba8-b888e0ffd58c"));
        assert!(is_valid_uuid("00000000-0000-0000-0000-000000000000"));
        // Uppercase hex is acceptable.
        assert!(is_valid_uuid("ABCDEF01-2345-6789-ABCD-EF0123456789"));
    }

    #[test]
    fn test_is_valid_uuid_rejects_malformed() {
        assert!(!is_valid_uuid(""));
        assert!(!is_valid_uuid("not-a-uuid"));
        // Wrong segment count.
        assert!(!is_valid_uuid("80630680-4da6-45f9-bba8"));
        // Wrong length on first segment.
        assert!(!is_valid_uuid("8063068-4da6-45f9-bba8-b888e0ffd58c"));
        // Non-hex character.
        assert!(!is_valid_uuid("80630680-4da6-45f9-bba8-b888e0ffd58z"));
        // No dashes.
        assert!(!is_valid_uuid("80630680xxxxx"));
    }

    // ── fetch_diff / fetch_package validation tests ─────────────────
    //
    // These tests cover input validation only — they intentionally do
    // NOT hit the network. The shared `fetch_binary` helper handles the
    // transport, and `fetch_blob` already has integration coverage via
    // the e2e_npm test.

    #[tokio::test]
    async fn test_fetch_diff_rejects_invalid_uuid() {
        std::env::remove_var("SOCKET_API_TOKEN");
        let (client, _) = get_api_client_from_env(None).await;
        let result = client.fetch_diff("not-a-uuid").await;
        assert!(matches!(result, Err(ApiError::InvalidHash(_))));
    }

    #[tokio::test]
    async fn test_fetch_package_rejects_invalid_uuid() {
        std::env::remove_var("SOCKET_API_TOKEN");
        let (client, _) = get_api_client_from_env(None).await;
        let result = client.fetch_package("xxx").await;
        assert!(matches!(result, Err(ApiError::InvalidHash(_))));
    }

    // ── Token shape validation ─────────────────────────────────────────

    #[test]
    fn validate_token_shape_accepts_canonical_api_token() {
        // 7-char prefix + 44 random chars + 4-char `_api` suffix = 55 chars,
        // matching the server's SOCKET_TOKEN_REGEXP.
        let raw = format!("sktsec_{}_api", "x".repeat(44));
        assert_eq!(raw.len(), 55);
        assert!(validate_token_shape(&raw).is_none());
    }

    #[test]
    fn validate_token_shape_accepts_agent_token() {
        let raw = format!("sktsec_{}_agent", "x".repeat(44));
        assert!(validate_token_shape(&raw).is_none());
    }

    #[test]
    fn validate_token_shape_flags_sha512_hash() {
        let hash = "sha512-7aegAloeNsCqF1mpNL2J9MJ2dpIxQEwgKvXPml8XY2rrV2Za+\
                    bfj0yhG7RcqvqqLZ4iAH/drJjHjOqFkTGhddg==";
        let msg = validate_token_shape(hash).expect("hash must be flagged");
        assert!(
            msg.contains("does not look like a Socket API token"),
            "missing core warning; got: {msg}"
        );
        assert!(
            msg.contains("SRI-format hash"),
            "missing sha-hash hint; got: {msg}"
        );
        assert!(
            msg.contains("sktsec_"),
            "warning must point users at the correct prefix; got: {msg}"
        );
        // Token preview must not leak the whole value.
        assert!(
            !msg.contains("7RcqvqqLZ4iAH"),
            "middle of the value must be redacted; got: {msg}"
        );
    }

    #[test]
    fn validate_token_shape_flags_too_short() {
        let msg = validate_token_shape("sktsec_abc_api").expect("short token must be flagged");
        assert!(msg.contains("does not look like a Socket API token"));
        assert!(!msg.contains("SRI-format hash"));
    }

    #[test]
    fn validate_token_shape_flags_missing_suffix() {
        let raw = format!("sktsec_{}", "x".repeat(50));
        assert!(validate_token_shape(&raw).is_some());
    }

    #[test]
    fn looks_like_token_hash_recognizes_sri_prefixes() {
        assert!(looks_like_token_hash("sha256-abc"));
        assert!(looks_like_token_hash("sha384-abc"));
        assert!(looks_like_token_hash("sha512-abc"));
        assert!(!looks_like_token_hash("sktsec_xxx_api"));
        assert!(!looks_like_token_hash("hello"));
        assert!(!looks_like_token_hash(""));
    }

    // ── binary_url: proxy override must reach blob/diff/package fetches ──
    //
    // Regression: `fetch_binary` used to re-derive the proxy base from
    // `SOCKET_PROXY_URL`/default instead of the client's configured
    // `api_url`, so a `--proxy-url` override (which sets `api_url` but no env
    // var) was honored for searches yet silently ignored for downloads.

    fn proxy_client(api_url: &str) -> ApiClient {
        ApiClient::new(ApiClientOptions {
            api_url: api_url.into(),
            api_token: None,
            use_public_proxy: true,
            org_slug: None,
        })
    }

    #[test]
    fn binary_url_proxy_uses_configured_api_url() {
        let client = proxy_client("https://custom.proxy.example");
        let (url, use_auth) = client.binary_url("blob", "deadbeef");
        assert!(!use_auth);
        assert_eq!(url, "https://custom.proxy.example/patch/blob/deadbeef");
    }

    #[test]
    fn binary_url_proxy_covers_diff_and_package() {
        let client = proxy_client("https://custom.proxy.example");
        assert_eq!(
            client.binary_url("diff", "uuid-1").0,
            "https://custom.proxy.example/patch/diff/uuid-1"
        );
        assert_eq!(
            client.binary_url("package", "uuid-1").0,
            "https://custom.proxy.example/patch/package/uuid-1"
        );
    }

    #[test]
    fn binary_url_proxy_trims_trailing_slash() {
        // `new()` trims the trailing slash on api_url; binary_url also trims
        // defensively so the path never ends up with a doubled separator.
        let client = proxy_client("https://custom.proxy.example/");
        assert_eq!(
            client.binary_url("blob", "x").0,
            "https://custom.proxy.example/patch/blob/x"
        );
    }

    #[test]
    fn binary_url_authenticated_uses_org_path() {
        let client = ApiClient::new(ApiClientOptions {
            api_url: "https://api.socket.dev".into(),
            api_token: Some("sktsec_x_api".into()),
            use_public_proxy: false,
            org_slug: Some("my-org".into()),
        });
        let (url, use_auth) = client.binary_url("diff", "uuid-123");
        assert!(use_auth);
        assert_eq!(
            url,
            "https://api.socket.dev/v0/orgs/my-org/patches/diff/uuid-123"
        );
    }

    // ── select_org_slug: deterministic org selection ────────────────────

    fn org(slug: &str) -> crate::api::types::OrganizationInfo {
        crate::api::types::OrganizationInfo {
            id: format!("id-{slug}"),
            name: Some(slug.to_string()),
            image: None,
            plan: "free".into(),
            slug: slug.into(),
        }
    }

    #[test]
    fn select_org_slug_errors_when_empty() {
        assert!(matches!(select_org_slug(vec![]), Err(ApiError::Other(_))));
    }

    #[test]
    fn select_org_slug_returns_sole_org() {
        assert_eq!(select_org_slug(vec![org("acme")]).unwrap(), "acme");
    }

    #[test]
    fn select_org_slug_is_deterministic_for_multiple() {
        // Regardless of the (HashMap-derived) input order, the
        // lexicographically-first slug is chosen so repeated runs agree.
        let a = select_org_slug(vec![org("zeta"), org("alpha"), org("mid")]).unwrap();
        let b = select_org_slug(vec![org("mid"), org("zeta"), org("alpha")]).unwrap();
        assert_eq!(a, "alpha");
        assert_eq!(b, "alpha");
    }

    // ── assemble_batch_from_individual: proxy-fallback aggregation ──────

    fn search_response(
        purl: &str,
        can_access_paid_patches: bool,
        patch_uuids: &[&str],
    ) -> SearchResponse {
        SearchResponse {
            patches: patch_uuids
                .iter()
                .map(|uuid| PatchSearchResult {
                    uuid: (*uuid).into(),
                    purl: purl.into(),
                    published_at: "2024-01-01".into(),
                    description: "desc".into(),
                    license: "MIT".into(),
                    tier: "free".into(),
                    vulnerabilities: HashMap::new(),
                })
                .collect(),
            can_access_paid_patches,
        }
    }

    #[test]
    fn assemble_batch_collects_patches_per_purl() {
        let results = vec![
            (
                "pkg:npm/a@1".to_string(),
                Some(search_response("pkg:npm/a@1", false, &["uuid-a"])),
            ),
            (
                "pkg:npm/b@1".to_string(),
                Some(search_response(
                    "pkg:npm/b@1",
                    false,
                    &["uuid-b1", "uuid-b2"],
                )),
            ),
        ];
        let batch = assemble_batch_from_individual(results);
        assert_eq!(batch.packages.len(), 2);
        assert!(!batch.can_access_paid_patches);
        let a = batch
            .packages
            .iter()
            .find(|p| p.purl == "pkg:npm/a@1")
            .unwrap();
        assert_eq!(a.patches.len(), 1);
        let b = batch
            .packages
            .iter()
            .find(|p| p.purl == "pkg:npm/b@1")
            .unwrap();
        assert_eq!(b.patches.len(), 2);
    }

    #[test]
    fn assemble_batch_skips_errored_and_empty_responses() {
        // None = query errored; an empty patch list contributes no package.
        let results = vec![
            ("pkg:npm/err@1".to_string(), None),
            (
                "pkg:npm/empty@1".to_string(),
                Some(search_response("pkg:npm/empty@1", false, &[])),
            ),
            (
                "pkg:npm/ok@1".to_string(),
                Some(search_response("pkg:npm/ok@1", false, &["uuid-ok"])),
            ),
        ];
        let batch = assemble_batch_from_individual(results);
        // Only the package with at least one patch is listed.
        assert_eq!(batch.packages.len(), 1);
        assert_eq!(batch.packages[0].purl, "pkg:npm/ok@1");
    }

    #[test]
    fn assemble_batch_aggregates_paid_flag_across_all_responses() {
        // OR-aggregation: any response with the flag set flips the aggregate.
        let results = vec![
            (
                "pkg:npm/a@1".to_string(),
                Some(search_response("pkg:npm/a@1", false, &["uuid-a"])),
            ),
            (
                "pkg:npm/b@1".to_string(),
                Some(search_response("pkg:npm/b@1", true, &["uuid-b"])),
            ),
        ];
        let batch = assemble_batch_from_individual(results);
        assert!(batch.can_access_paid_patches);
    }

    #[test]
    fn assemble_batch_keeps_paid_flag_from_empty_patch_response() {
        // Regression: the capability flag must survive even when the response
        // that carries it has *no* patches. The empty-patch response must not
        // be listed as a package, but its `canAccessPaidPatches: true` must
        // still flip the aggregate flag — a fused skip would have dropped it.
        let results = vec![
            (
                "pkg:npm/free@1".to_string(),
                Some(search_response("pkg:npm/free@1", false, &["uuid-free"])),
            ),
            (
                "pkg:npm/paid-only@1".to_string(),
                Some(search_response("pkg:npm/paid-only@1", true, &[])),
            ),
        ];
        let batch = assemble_batch_from_individual(results);
        assert!(
            batch.can_access_paid_patches,
            "paid-access flag from an empty-patch response was dropped"
        );
        // The empty-patch package must not appear in the listing.
        assert_eq!(batch.packages.len(), 1);
        assert_eq!(batch.packages[0].purl, "pkg:npm/free@1");
    }

    // ── convert: title selection is deterministic ───────────────────────

    #[test]
    fn test_convert_title_deterministic_across_iteration_order() {
        // Two vulns, each with a non-empty summary. The title must always be
        // drawn from the lexicographically-first GHSA id so the value is
        // stable across runs (HashMap iteration order is not).
        let mut vulns = HashMap::new();
        vulns.insert("GHSA-zzzz".into(), make_vuln("Z summary", "high", vec![]));
        vulns.insert("GHSA-aaaa".into(), make_vuln("A summary", "high", vec![]));
        let patch = make_patch(vulns, "desc");
        let info = convert_search_result_to_batch_info(patch);
        assert_eq!(info.title, "A summary");
    }
}