Skip to main content

socket_patch_core/api/
client.rs

1use std::collections::HashSet;
2
3use reqwest::header::{self, HeaderMap, HeaderValue};
4use reqwest::StatusCode;
5use serde::Serialize;
6
7use crate::api::types::*;
8use crate::constants::{
9    DEFAULT_PATCH_API_PROXY_URL, DEFAULT_SOCKET_API_URL, USER_AGENT as USER_AGENT_VALUE,
10};
11
12/// Check if debug mode is enabled via SOCKET_PATCH_DEBUG env.
13fn is_debug_enabled() -> bool {
14    match std::env::var("SOCKET_PATCH_DEBUG") {
15        Ok(val) => val == "1" || val == "true",
16        Err(_) => false,
17    }
18}
19
20/// Log debug messages when debug mode is enabled.
21fn debug_log(message: &str) {
22    if is_debug_enabled() {
23        eprintln!("[socket-patch debug] {}", message);
24    }
25}
26
27/// Severity order for sorting (most severe = lowest number).
28fn get_severity_order(severity: Option<&str>) -> u8 {
29    match severity.map(|s| s.to_lowercase()).as_deref() {
30        Some("critical") => 0,
31        Some("high") => 1,
32        Some("medium") => 2,
33        Some("low") => 3,
34        _ => 4,
35    }
36}
37
38/// Options for constructing an [`ApiClient`].
39#[derive(Debug, Clone)]
40pub struct ApiClientOptions {
41    pub api_url: String,
42    pub api_token: Option<String>,
43    /// When true, the client will use the public patch API proxy
44    /// which only provides access to free patches without authentication.
45    pub use_public_proxy: bool,
46    /// Organization slug for authenticated API access.
47    /// Required when using authenticated API (not public proxy).
48    pub org_slug: Option<String>,
49}
50
51/// HTTP client for the Socket Patch API.
52///
53/// Supports both the authenticated Socket API (`api.socket.dev`) and the
54/// public proxy (`patches-api.socket.dev`) which serves free patches
55/// without authentication.
56#[derive(Debug, Clone)]
57pub struct ApiClient {
58    client: reqwest::Client,
59    api_url: String,
60    api_token: Option<String>,
61    use_public_proxy: bool,
62    org_slug: Option<String>,
63}
64
65/// Body payload for the batch search POST endpoint.
66#[derive(Serialize)]
67struct BatchSearchBody {
68    components: Vec<BatchComponent>,
69}
70
71#[derive(Serialize)]
72struct BatchComponent {
73    purl: String,
74}
75
76impl ApiClient {
77    /// Create a new API client from the given options.
78    ///
79    /// Constructs a `reqwest::Client` with proper default headers
80    /// (User-Agent, Accept, and optionally Authorization).
81    pub fn new(options: ApiClientOptions) -> Self {
82        let api_url = options.api_url.trim_end_matches('/').to_string();
83
84        let mut default_headers = HeaderMap::new();
85        default_headers.insert(
86            header::USER_AGENT,
87            HeaderValue::from_static(USER_AGENT_VALUE),
88        );
89        default_headers.insert(
90            header::ACCEPT,
91            HeaderValue::from_static("application/json"),
92        );
93
94        if let Some(ref token) = options.api_token {
95            if let Ok(hv) = HeaderValue::from_str(&format!("Bearer {}", token)) {
96                default_headers.insert(header::AUTHORIZATION, hv);
97            }
98        }
99
100        let client = reqwest::Client::builder()
101            .default_headers(default_headers)
102            .build()
103            .expect("failed to build reqwest client");
104
105        Self {
106            client,
107            api_url,
108            api_token: options.api_token,
109            use_public_proxy: options.use_public_proxy,
110            org_slug: options.org_slug,
111        }
112    }
113
114    /// Returns the API token, if set.
115    pub fn api_token(&self) -> Option<&String> {
116        self.api_token.as_ref()
117    }
118
119    /// Returns the org slug, if set.
120    pub fn org_slug(&self) -> Option<&String> {
121        self.org_slug.as_ref()
122    }
123
124    // ── Internal helpers ──────────────────────────────────────────────
125
126    /// Internal GET that deserialises JSON. Returns `Ok(None)` on 404.
127    async fn get_json<T: serde::de::DeserializeOwned>(
128        &self,
129        path: &str,
130    ) -> Result<Option<T>, ApiError> {
131        let url = format!("{}{}", self.api_url, path);
132        debug_log(&format!("GET {}", url));
133
134        let resp = self
135            .client
136            .get(&url)
137            .send()
138            .await
139            .map_err(|e| ApiError::Network(format!("Network error: {}", e)))?;
140
141        Self::handle_json_response(resp, self.use_public_proxy).await
142    }
143
144    /// Internal POST that deserialises JSON. Returns `Ok(None)` on 404.
145    async fn post_json<T: serde::de::DeserializeOwned, B: Serialize>(
146        &self,
147        path: &str,
148        body: &B,
149    ) -> Result<Option<T>, ApiError> {
150        let url = format!("{}{}", self.api_url, path);
151        debug_log(&format!("POST {}", url));
152
153        let resp = self
154            .client
155            .post(&url)
156            .header(header::CONTENT_TYPE, "application/json")
157            .json(body)
158            .send()
159            .await
160            .map_err(|e| ApiError::Network(format!("Network error: {}", e)))?;
161
162        Self::handle_json_response(resp, self.use_public_proxy).await
163    }
164
165    /// Map an HTTP response to `Ok(Some(T))`, `Ok(None)` (404), or `Err`.
166    async fn handle_json_response<T: serde::de::DeserializeOwned>(
167        resp: reqwest::Response,
168        use_public_proxy: bool,
169    ) -> Result<Option<T>, ApiError> {
170        let status = resp.status();
171
172        match status {
173            StatusCode::OK => {
174                let body = resp
175                    .json::<T>()
176                    .await
177                    .map_err(|e| ApiError::Parse(format!("Failed to parse response: {}", e)))?;
178                Ok(Some(body))
179            }
180            StatusCode::NOT_FOUND => Ok(None),
181            StatusCode::UNAUTHORIZED => {
182                Err(ApiError::Unauthorized("Unauthorized: Invalid API token".into()))
183            }
184            StatusCode::FORBIDDEN => {
185                let msg = if use_public_proxy {
186                    "Forbidden: This patch is only available to paid subscribers. \
187                     Sign up at https://socket.dev to access paid patches."
188                } else {
189                    "Forbidden: Access denied. This may be a paid patch or \
190                     you may not have access to this organization."
191                };
192                Err(ApiError::Forbidden(msg.into()))
193            }
194            StatusCode::TOO_MANY_REQUESTS => {
195                Err(ApiError::RateLimited(
196                    "Rate limit exceeded. Please try again later.".into(),
197                ))
198            }
199            _ => {
200                let text = resp.text().await.unwrap_or_default();
201                Err(ApiError::Other(format!(
202                    "API request failed with status {}: {}",
203                    status.as_u16(),
204                    text
205                )))
206            }
207        }
208    }
209
210    // ── Public API methods ────────────────────────────────────────────
211
212    /// Fetch a patch by UUID (full details with blob content).
213    ///
214    /// Returns `Ok(None)` when the patch is not found (404).
215    pub async fn fetch_patch(
216        &self,
217        org_slug: Option<&str>,
218        uuid: &str,
219    ) -> Result<Option<PatchResponse>, ApiError> {
220        let path = if self.use_public_proxy {
221            format!("/patch/view/{}", uuid)
222        } else {
223            let slug = org_slug
224                .or(self.org_slug.as_deref())
225                .unwrap_or("default");
226            format!("/v0/orgs/{}/patches/view/{}", slug, uuid)
227        };
228        self.get_json(&path).await
229    }
230
231    /// Search patches by CVE ID.
232    pub async fn search_patches_by_cve(
233        &self,
234        org_slug: Option<&str>,
235        cve_id: &str,
236    ) -> Result<SearchResponse, ApiError> {
237        let encoded = urlencoding_encode(cve_id);
238        let path = if self.use_public_proxy {
239            format!("/patch/by-cve/{}", encoded)
240        } else {
241            let slug = org_slug
242                .or(self.org_slug.as_deref())
243                .unwrap_or("default");
244            format!("/v0/orgs/{}/patches/by-cve/{}", slug, encoded)
245        };
246        let result = self.get_json::<SearchResponse>(&path).await?;
247        Ok(result.unwrap_or_else(|| SearchResponse {
248            patches: Vec::new(),
249            can_access_paid_patches: false,
250        }))
251    }
252
253    /// Search patches by GHSA ID.
254    pub async fn search_patches_by_ghsa(
255        &self,
256        org_slug: Option<&str>,
257        ghsa_id: &str,
258    ) -> Result<SearchResponse, ApiError> {
259        let encoded = urlencoding_encode(ghsa_id);
260        let path = if self.use_public_proxy {
261            format!("/patch/by-ghsa/{}", encoded)
262        } else {
263            let slug = org_slug
264                .or(self.org_slug.as_deref())
265                .unwrap_or("default");
266            format!("/v0/orgs/{}/patches/by-ghsa/{}", slug, encoded)
267        };
268        let result = self.get_json::<SearchResponse>(&path).await?;
269        Ok(result.unwrap_or_else(|| SearchResponse {
270            patches: Vec::new(),
271            can_access_paid_patches: false,
272        }))
273    }
274
275    /// Search patches by package PURL.
276    ///
277    /// The PURL must be a valid Package URL starting with `pkg:`.
278    /// Examples: `pkg:npm/lodash@4.17.21`, `pkg:pypi/django@3.2.0`
279    pub async fn search_patches_by_package(
280        &self,
281        org_slug: Option<&str>,
282        purl: &str,
283    ) -> Result<SearchResponse, ApiError> {
284        let encoded = urlencoding_encode(purl);
285        let path = if self.use_public_proxy {
286            format!("/patch/by-package/{}", encoded)
287        } else {
288            let slug = org_slug
289                .or(self.org_slug.as_deref())
290                .unwrap_or("default");
291            format!("/v0/orgs/{}/patches/by-package/{}", slug, encoded)
292        };
293        let result = self.get_json::<SearchResponse>(&path).await?;
294        Ok(result.unwrap_or_else(|| SearchResponse {
295            patches: Vec::new(),
296            can_access_paid_patches: false,
297        }))
298    }
299
300    /// Search patches for multiple packages (batch).
301    ///
302    /// For authenticated API, uses the POST `/patches/batch` endpoint.
303    /// For the public proxy (which cannot cache POST bodies on CDN), falls
304    /// back to individual GET requests per PURL with a concurrency limit of
305    /// 10.
306    ///
307    /// Maximum 500 PURLs per request.
308    pub async fn search_patches_batch(
309        &self,
310        org_slug: Option<&str>,
311        purls: &[String],
312    ) -> Result<BatchSearchResponse, ApiError> {
313        if !self.use_public_proxy {
314            let slug = org_slug
315                .or(self.org_slug.as_deref())
316                .unwrap_or("default");
317            let path = format!("/v0/orgs/{}/patches/batch", slug);
318            let body = BatchSearchBody {
319                components: purls
320                    .iter()
321                    .map(|p| BatchComponent { purl: p.clone() })
322                    .collect(),
323            };
324            let result = self.post_json::<BatchSearchResponse, _>(&path, &body).await?;
325            return Ok(result.unwrap_or_else(|| BatchSearchResponse {
326                packages: Vec::new(),
327                can_access_paid_patches: false,
328            }));
329        }
330
331        // Public proxy: fall back to individual per-package GET requests
332        self.search_patches_batch_via_individual_queries(purls).await
333    }
334
335    /// Internal: fall back to individual GET requests per PURL when the
336    /// batch endpoint is not available (public proxy mode).
337    ///
338    /// Processes PURLs in batches of `CONCURRENCY_LIMIT` to avoid
339    /// overwhelming the server while remaining efficient.
340    async fn search_patches_batch_via_individual_queries(
341        &self,
342        purls: &[String],
343    ) -> Result<BatchSearchResponse, ApiError> {
344        const CONCURRENCY_LIMIT: usize = 10;
345
346        let mut packages: Vec<BatchPackagePatches> = Vec::new();
347        let mut can_access_paid_patches = false;
348
349        // Collect all (purl, response) pairs
350        let mut all_results: Vec<(String, Option<SearchResponse>)> = Vec::new();
351
352        for chunk in purls.chunks(CONCURRENCY_LIMIT) {
353            // Use tokio::JoinSet for concurrent execution within each chunk
354            let mut join_set = tokio::task::JoinSet::new();
355
356            for purl in chunk {
357                let purl = purl.clone();
358                let client = self.clone();
359                join_set.spawn(async move {
360                    let resp = client.search_patches_by_package(None, &purl).await;
361                    match resp {
362                        Ok(r) => (purl, Some(r)),
363                        Err(e) => {
364                            debug_log(&format!("Error fetching patches for {}: {}", purl, e));
365                            (purl, None)
366                        }
367                    }
368                });
369            }
370
371            while let Some(result) = join_set.join_next().await {
372                match result {
373                    Ok(pair) => all_results.push(pair),
374                    Err(e) => {
375                        debug_log(&format!("Task join error: {}", e));
376                    }
377                }
378            }
379        }
380
381        // Convert individual SearchResponse results to BatchSearchResponse format
382        for (purl, response) in all_results {
383            let response = match response {
384                Some(r) if !r.patches.is_empty() => r,
385                _ => continue,
386            };
387
388            if response.can_access_paid_patches {
389                can_access_paid_patches = true;
390            }
391
392            let batch_patches: Vec<BatchPatchInfo> = response
393                .patches
394                .into_iter()
395                .map(convert_search_result_to_batch_info)
396                .collect();
397
398            packages.push(BatchPackagePatches {
399                purl,
400                patches: batch_patches,
401            });
402        }
403
404        Ok(BatchSearchResponse {
405            packages,
406            can_access_paid_patches,
407        })
408    }
409
410    /// Fetch organizations accessible to the current API token.
411    pub async fn fetch_organizations(
412        &self,
413    ) -> Result<Vec<crate::api::types::OrganizationInfo>, ApiError> {
414        let path = "/v0/organizations";
415        match self
416            .get_json::<crate::api::types::OrganizationsResponse>(path)
417            .await?
418        {
419            Some(resp) => Ok(resp.organizations.into_values().collect()),
420            None => Ok(Vec::new()),
421        }
422    }
423
424    /// Resolve the org slug from the API token by querying `/v0/organizations`.
425    ///
426    /// If there is exactly one org, returns its slug.
427    /// If there are multiple, picks the first and prints a warning.
428    /// If there are none, returns an error.
429    pub async fn resolve_org_slug(&self) -> Result<String, ApiError> {
430        let orgs = self.fetch_organizations().await?;
431        match orgs.len() {
432            0 => Err(ApiError::Other(
433                "No organizations found for this API token.".into(),
434            )),
435            1 => Ok(orgs.into_iter().next().unwrap().slug),
436            _ => {
437                let slugs: Vec<_> = orgs.iter().map(|o| o.slug.as_str()).collect();
438                let first = orgs[0].slug.clone();
439                eprintln!(
440                    "Multiple organizations found: {}. Using \"{}\". \
441                     Pass --org to select a different one.",
442                    slugs.join(", "),
443                    first
444                );
445                Ok(first)
446            }
447        }
448    }
449
450    /// Fetch a blob by its SHA-256 hash.
451    ///
452    /// Returns the raw binary content, or `Ok(None)` if not found.
453    /// Uses the authenticated endpoint when token and org slug are
454    /// available, otherwise falls back to the public proxy.
455    pub async fn fetch_blob(&self, hash: &str) -> Result<Option<Vec<u8>>, ApiError> {
456        // Validate hash format: SHA-256 = 64 hex characters
457        if !is_valid_sha256_hex(hash) {
458            return Err(ApiError::InvalidHash(format!(
459                "Invalid hash format: {}. Expected SHA256 hash (64 hex characters).",
460                hash
461            )));
462        }
463
464        let (url, use_auth) =
465            if self.api_token.is_some() && self.org_slug.is_some() && !self.use_public_proxy {
466                // Authenticated endpoint
467                let slug = self.org_slug.as_deref().unwrap();
468                let u = format!("{}/v0/orgs/{}/patches/blob/{}", self.api_url, slug, hash);
469                (u, true)
470            } else {
471                // Public proxy
472                let proxy_url = std::env::var("SOCKET_PATCH_PROXY_URL")
473                    .unwrap_or_else(|_| DEFAULT_PATCH_API_PROXY_URL.to_string());
474                let u = format!("{}/patch/blob/{}", proxy_url.trim_end_matches('/'), hash);
475                (u, false)
476            };
477
478        debug_log(&format!("GET blob {}", url));
479
480        // Build the request. When fetching from the public proxy (different
481        // base URL than self.api_url), we use a plain client without auth
482        // headers to avoid leaking credentials to the proxy.
483        let resp = if use_auth {
484            self.client
485                .get(&url)
486                .header(header::ACCEPT, "application/octet-stream")
487                .send()
488                .await
489        } else {
490            let mut headers = HeaderMap::new();
491            headers.insert(
492                header::USER_AGENT,
493                HeaderValue::from_static(USER_AGENT_VALUE),
494            );
495            headers.insert(
496                header::ACCEPT,
497                HeaderValue::from_static("application/octet-stream"),
498            );
499
500            let plain_client = reqwest::Client::builder()
501                .default_headers(headers)
502                .build()
503                .expect("failed to build plain reqwest client");
504
505            plain_client.get(&url).send().await
506        };
507
508        let resp = resp.map_err(|e| {
509            ApiError::Network(format!("Network error fetching blob {}: {}", hash, e))
510        })?;
511
512        let status = resp.status();
513
514        match status {
515            StatusCode::OK => {
516                let bytes = resp.bytes().await.map_err(|e| {
517                    ApiError::Network(format!("Error reading blob body for {}: {}", hash, e))
518                })?;
519                Ok(Some(bytes.to_vec()))
520            }
521            StatusCode::NOT_FOUND => Ok(None),
522            _ => {
523                let text = resp.text().await.unwrap_or_default();
524                Err(ApiError::Other(format!(
525                    "Failed to fetch blob {}: status {} - {}",
526                    hash,
527                    status.as_u16(),
528                    text,
529                )))
530            }
531        }
532    }
533}
534
535// ── Free functions ────────────────────────────────────────────────────
536
537/// Get an API client configured from environment variables.
538///
539/// If `SOCKET_API_TOKEN` is not set, the client will use the public patch
540/// API proxy which provides free access to free-tier patches without
541/// authentication.
542///
543/// When `SOCKET_API_TOKEN` is set but no org slug is provided (neither via
544/// argument nor `SOCKET_ORG_SLUG` env var), the function will attempt to
545/// auto-resolve the org slug by querying `GET /v0/organizations`.
546///
547/// # Environment variables
548///
549/// | Variable | Purpose |
550/// |---|---|
551/// | `SOCKET_API_URL` | Override the API URL (default `https://api.socket.dev`) |
552/// | `SOCKET_API_TOKEN` | API token for authenticated access |
553/// | `SOCKET_PATCH_PROXY_URL` | Override the public proxy URL (default `https://patches-api.socket.dev`) |
554/// | `SOCKET_ORG_SLUG` | Organization slug |
555///
556/// Returns `(client, use_public_proxy)`.
557pub async fn get_api_client_from_env(org_slug: Option<&str>) -> (ApiClient, bool) {
558    let api_token = std::env::var("SOCKET_API_TOKEN").ok();
559    let resolved_org_slug = org_slug
560        .map(String::from)
561        .or_else(|| std::env::var("SOCKET_ORG_SLUG").ok());
562
563    if api_token.is_none() {
564        let proxy_url = std::env::var("SOCKET_PATCH_PROXY_URL")
565            .unwrap_or_else(|_| DEFAULT_PATCH_API_PROXY_URL.to_string());
566        eprintln!(
567            "No SOCKET_API_TOKEN set. Using public patch API proxy (free patches only)."
568        );
569        let client = ApiClient::new(ApiClientOptions {
570            api_url: proxy_url,
571            api_token: None,
572            use_public_proxy: true,
573            org_slug: None,
574        });
575        return (client, true);
576    }
577
578    let api_url =
579        std::env::var("SOCKET_API_URL").unwrap_or_else(|_| DEFAULT_SOCKET_API_URL.to_string());
580
581    // Auto-resolve org slug if not provided
582    let final_org_slug = if resolved_org_slug.is_some() {
583        resolved_org_slug
584    } else {
585        let temp_client = ApiClient::new(ApiClientOptions {
586            api_url: api_url.clone(),
587            api_token: api_token.clone(),
588            use_public_proxy: false,
589            org_slug: None,
590        });
591        match temp_client.resolve_org_slug().await {
592            Ok(slug) => Some(slug),
593            Err(e) => {
594                eprintln!("Warning: Could not auto-detect organization: {e}");
595                None
596            }
597        }
598    };
599
600    let client = ApiClient::new(ApiClientOptions {
601        api_url,
602        api_token,
603        use_public_proxy: false,
604        org_slug: final_org_slug,
605    });
606    (client, false)
607}
608
609// ── Helpers ───────────────────────────────────────────────────────────
610
611/// Percent-encode a string for use in URL path segments.
612fn urlencoding_encode(input: &str) -> String {
613    // Encode everything that is not unreserved per RFC 3986.
614    let mut out = String::with_capacity(input.len());
615    for byte in input.bytes() {
616        match byte {
617            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
618                out.push(byte as char)
619            }
620            _ => {
621                out.push('%');
622                out.push_str(&format!("{:02X}", byte));
623            }
624        }
625    }
626    out
627}
628
629/// Truncate a string to at most `max_chars` characters, appending "..." if truncated.
630/// Unlike byte slicing (`&s[..n]`), this is safe for multi-byte UTF-8 characters.
631fn truncate_to_chars(s: &str, max_chars: usize) -> String {
632    if s.chars().count() <= max_chars {
633        return s.to_string();
634    }
635    let truncated: String = s.chars().take(max_chars).collect();
636    format!("{}...", truncated)
637}
638
639/// Validate that a string is a 64-character hex string (SHA-256).
640fn is_valid_sha256_hex(s: &str) -> bool {
641    s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit())
642}
643
644/// Convert a `PatchSearchResult` into a `BatchPatchInfo`, extracting
645/// CVE/GHSA IDs and computing the highest severity.
646fn convert_search_result_to_batch_info(patch: PatchSearchResult) -> BatchPatchInfo {
647    let mut cve_ids: Vec<String> = Vec::new();
648    let mut ghsa_ids: Vec<String> = Vec::new();
649    let mut highest_severity: Option<String> = None;
650    let mut title = String::new();
651
652    let mut seen_cves: HashSet<String> = HashSet::new();
653
654    for (ghsa_id, vuln) in &patch.vulnerabilities {
655        ghsa_ids.push(ghsa_id.clone());
656
657        for cve in &vuln.cves {
658            if seen_cves.insert(cve.clone()) {
659                cve_ids.push(cve.clone());
660            }
661        }
662
663        // Track highest severity (lower order number = higher severity)
664        let current_order = get_severity_order(highest_severity.as_deref());
665        let vuln_order = get_severity_order(Some(&vuln.severity));
666        if vuln_order < current_order {
667            highest_severity = Some(vuln.severity.clone());
668        }
669
670        // Use first non-empty summary as title
671        if title.is_empty() && !vuln.summary.is_empty() {
672            title = truncate_to_chars(&vuln.summary, 97);
673        }
674    }
675
676    // Use description as fallback title
677    if title.is_empty() && !patch.description.is_empty() {
678        title = truncate_to_chars(&patch.description, 97);
679    }
680
681    cve_ids.sort();
682    ghsa_ids.sort();
683
684    BatchPatchInfo {
685        uuid: patch.uuid,
686        purl: patch.purl,
687        tier: patch.tier,
688        cve_ids,
689        ghsa_ids,
690        severity: highest_severity,
691        title,
692    }
693}
694
695// ── Error type ────────────────────────────────────────────────────────
696
697/// Errors returned by [`ApiClient`] methods.
698#[derive(Debug, thiserror::Error)]
699pub enum ApiError {
700    #[error("{0}")]
701    Network(String),
702
703    #[error("{0}")]
704    Parse(String),
705
706    #[error("{0}")]
707    Unauthorized(String),
708
709    #[error("{0}")]
710    Forbidden(String),
711
712    #[error("{0}")]
713    RateLimited(String),
714
715    #[error("{0}")]
716    InvalidHash(String),
717
718    #[error("{0}")]
719    Other(String),
720}
721
722#[cfg(test)]
723mod tests {
724    use super::*;
725    use std::collections::HashMap;
726
727    #[test]
728    fn test_urlencoding_basic() {
729        assert_eq!(urlencoding_encode("hello"), "hello");
730        assert_eq!(urlencoding_encode("a b"), "a%20b");
731        assert_eq!(
732            urlencoding_encode("pkg:npm/lodash@4.17.21"),
733            "pkg%3Anpm%2Flodash%404.17.21"
734        );
735    }
736
737    #[test]
738    fn test_is_valid_sha256_hex() {
739        let valid = "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789";
740        assert!(is_valid_sha256_hex(valid));
741
742        // Too short
743        assert!(!is_valid_sha256_hex("abcdef"));
744        // Non-hex
745        assert!(!is_valid_sha256_hex(
746            "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
747        ));
748    }
749
750    #[test]
751    fn test_severity_order() {
752        assert!(get_severity_order(Some("critical")) < get_severity_order(Some("high")));
753        assert!(get_severity_order(Some("high")) < get_severity_order(Some("medium")));
754        assert!(get_severity_order(Some("medium")) < get_severity_order(Some("low")));
755        assert!(get_severity_order(Some("low")) < get_severity_order(None));
756        assert_eq!(get_severity_order(Some("unknown")), get_severity_order(None));
757    }
758
759    #[test]
760    fn test_convert_search_result_to_batch_info() {
761        let mut vulns = HashMap::new();
762        vulns.insert(
763            "GHSA-1234-5678-9abc".to_string(),
764            VulnerabilityResponse {
765                cves: vec!["CVE-2024-0001".into()],
766                summary: "Test vulnerability".into(),
767                severity: "high".into(),
768                description: "A test vuln".into(),
769            },
770        );
771
772        let patch = PatchSearchResult {
773            uuid: "uuid-1".into(),
774            purl: "pkg:npm/test@1.0.0".into(),
775            published_at: "2024-01-01".into(),
776            description: "A patch".into(),
777            license: "MIT".into(),
778            tier: "free".into(),
779            vulnerabilities: vulns,
780        };
781
782        let info = convert_search_result_to_batch_info(patch);
783        assert_eq!(info.uuid, "uuid-1");
784        assert_eq!(info.cve_ids, vec!["CVE-2024-0001"]);
785        assert_eq!(info.ghsa_ids, vec!["GHSA-1234-5678-9abc"]);
786        assert_eq!(info.severity, Some("high".into()));
787        assert_eq!(info.title, "Test vulnerability");
788    }
789
790    #[tokio::test]
791    async fn test_get_api_client_from_env_no_token() {
792        // Clear token to ensure public proxy mode
793        std::env::remove_var("SOCKET_API_TOKEN");
794        let (client, is_public) = get_api_client_from_env(None).await;
795        assert!(is_public);
796        assert!(client.use_public_proxy);
797    }
798
799    // ── Group 6: convert_search_result_to_batch_info edge cases ──────
800
801    fn make_vuln(summary: &str, severity: &str, cves: Vec<&str>) -> VulnerabilityResponse {
802        VulnerabilityResponse {
803            cves: cves.into_iter().map(String::from).collect(),
804            summary: summary.into(),
805            severity: severity.into(),
806            description: "desc".into(),
807        }
808    }
809
810    fn make_patch(
811        vulns: HashMap<String, VulnerabilityResponse>,
812        description: &str,
813    ) -> PatchSearchResult {
814        PatchSearchResult {
815            uuid: "uuid-1".into(),
816            purl: "pkg:npm/test@1.0.0".into(),
817            published_at: "2024-01-01".into(),
818            description: description.into(),
819            license: "MIT".into(),
820            tier: "free".into(),
821            vulnerabilities: vulns,
822        }
823    }
824
825    #[test]
826    fn test_convert_no_vulnerabilities() {
827        let patch = make_patch(HashMap::new(), "A patch description");
828        let info = convert_search_result_to_batch_info(patch);
829        assert!(info.cve_ids.is_empty());
830        assert!(info.ghsa_ids.is_empty());
831        assert_eq!(info.title, "A patch description");
832        assert!(info.severity.is_none());
833    }
834
835    #[test]
836    fn test_convert_multiple_vulns_picks_highest_severity() {
837        let mut vulns = HashMap::new();
838        vulns.insert(
839            "GHSA-1111".into(),
840            make_vuln("Medium vuln", "medium", vec!["CVE-2024-0001"]),
841        );
842        vulns.insert(
843            "GHSA-2222".into(),
844            make_vuln("Critical vuln", "critical", vec!["CVE-2024-0002"]),
845        );
846        let patch = make_patch(vulns, "desc");
847        let info = convert_search_result_to_batch_info(patch);
848        assert_eq!(info.severity, Some("critical".into()));
849    }
850
851    #[test]
852    fn test_convert_duplicate_cves_deduplicated() {
853        let mut vulns = HashMap::new();
854        vulns.insert(
855            "GHSA-1111".into(),
856            make_vuln("Vuln A", "high", vec!["CVE-2024-0001"]),
857        );
858        vulns.insert(
859            "GHSA-2222".into(),
860            make_vuln("Vuln B", "high", vec!["CVE-2024-0001"]),
861        );
862        let patch = make_patch(vulns, "desc");
863        let info = convert_search_result_to_batch_info(patch);
864        // Same CVE in both vulns should only appear once
865        let cve_count = info.cve_ids.iter().filter(|c| *c == "CVE-2024-0001").count();
866        assert_eq!(cve_count, 1);
867    }
868
869    #[test]
870    fn test_convert_title_truncated_at_100() {
871        let long_summary = "x".repeat(150);
872        let mut vulns = HashMap::new();
873        vulns.insert(
874            "GHSA-1111".into(),
875            make_vuln(&long_summary, "high", vec![]),
876        );
877        let patch = make_patch(vulns, "desc");
878        let info = convert_search_result_to_batch_info(patch);
879        // Should be 97 chars + "..." = 100 chars
880        assert_eq!(info.title.len(), 100);
881        assert!(info.title.ends_with("..."));
882    }
883
884    #[test]
885    fn test_convert_title_unicode_truncation() {
886        // Create a summary with multi-byte chars that would panic with byte slicing
887        // Each emoji is 4 bytes, so 30 emojis = 120 bytes but only 30 chars
888        let emoji_summary = "\u{1F600}".repeat(30);
889        let mut vulns = HashMap::new();
890        vulns.insert(
891            "GHSA-1111".into(),
892            make_vuln(&emoji_summary, "high", vec![]),
893        );
894        let patch = make_patch(vulns, "desc");
895        // This should NOT panic (validates the UTF-8 truncation fix)
896        let info = convert_search_result_to_batch_info(patch);
897        assert!(!info.title.is_empty());
898
899        // Also test with description fallback
900        let patch2 = make_patch(HashMap::new(), &"\u{1F600}".repeat(120));
901        let info2 = convert_search_result_to_batch_info(patch2);
902        assert!(info2.title.ends_with("..."));
903    }
904
905    #[test]
906    fn test_convert_title_falls_back_to_description() {
907        let mut vulns = HashMap::new();
908        vulns.insert(
909            "GHSA-1111".into(),
910            make_vuln("", "high", vec![]),
911        );
912        let patch = make_patch(vulns, "Fallback desc");
913        let info = convert_search_result_to_batch_info(patch);
914        assert_eq!(info.title, "Fallback desc");
915    }
916
917    #[test]
918    fn test_convert_empty_summary_and_description() {
919        let mut vulns = HashMap::new();
920        vulns.insert(
921            "GHSA-1111".into(),
922            make_vuln("", "high", vec![]),
923        );
924        let patch = make_patch(vulns, "");
925        let info = convert_search_result_to_batch_info(patch);
926        assert!(info.title.is_empty());
927    }
928
929    #[test]
930    fn test_convert_cves_and_ghsas_sorted() {
931        let mut vulns = HashMap::new();
932        vulns.insert(
933            "GHSA-cccc".into(),
934            make_vuln("V1", "high", vec!["CVE-2024-0003"]),
935        );
936        vulns.insert(
937            "GHSA-aaaa".into(),
938            make_vuln("V2", "high", vec!["CVE-2024-0001"]),
939        );
940        vulns.insert(
941            "GHSA-bbbb".into(),
942            make_vuln("V3", "high", vec!["CVE-2024-0002"]),
943        );
944        let patch = make_patch(vulns, "desc");
945        let info = convert_search_result_to_batch_info(patch);
946        // Both should be sorted alphabetically
947        let mut sorted_cves = info.cve_ids.clone();
948        sorted_cves.sort();
949        assert_eq!(info.cve_ids, sorted_cves);
950        let mut sorted_ghsas = info.ghsa_ids.clone();
951        sorted_ghsas.sort();
952        assert_eq!(info.ghsa_ids, sorted_ghsas);
953    }
954
955    // ── Group 7: urlencoding + SHA256 edge cases ─────────────────────
956
957    #[test]
958    fn test_urlencoding_unicode() {
959        // Multi-byte UTF-8: 'é' = 0xC3 0xA9
960        let encoded = urlencoding_encode("café");
961        assert_eq!(encoded, "caf%C3%A9");
962    }
963
964    #[test]
965    fn test_urlencoding_empty() {
966        assert_eq!(urlencoding_encode(""), "");
967    }
968
969    #[test]
970    fn test_urlencoding_all_safe_chars() {
971        // Unreserved chars should pass through
972        let safe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~";
973        assert_eq!(urlencoding_encode(safe), safe);
974    }
975
976    #[test]
977    fn test_urlencoding_slash_and_at() {
978        assert_eq!(urlencoding_encode("/"), "%2F");
979        assert_eq!(urlencoding_encode("@"), "%40");
980    }
981
982    #[test]
983    fn test_sha256_uppercase_valid() {
984        let upper = "ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789";
985        assert!(is_valid_sha256_hex(upper));
986    }
987
988    #[test]
989    fn test_sha256_65_chars_invalid() {
990        let too_long = "a".repeat(65);
991        assert!(!is_valid_sha256_hex(&too_long));
992    }
993
994    #[test]
995    fn test_sha256_63_chars_invalid() {
996        let too_short = "a".repeat(63);
997        assert!(!is_valid_sha256_hex(&too_short));
998    }
999
1000    #[test]
1001    fn test_sha256_empty_invalid() {
1002        assert!(!is_valid_sha256_hex(""));
1003    }
1004
1005    #[test]
1006    fn test_sha256_mixed_case_valid() {
1007        let mixed = "aAbBcCdDeEfF0123456789aAbBcCdDeEfF0123456789aAbBcCdDeEfF01234567";
1008        assert_eq!(mixed.len(), 64);
1009        assert!(is_valid_sha256_hex(mixed));
1010    }
1011}