Skip to main content

provenant/parsers/
cargo.rs

1// SPDX-FileCopyrightText: Provenant contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Parser for Cargo.toml manifest files.
5//!
6//! Extracts package metadata, dependencies, and license information from
7//! Rust Cargo.toml files.
8//!
9//! # Supported Formats
10//! - Cargo.toml (manifest)
11//!
12//! # Key Features
13//! - Dependency extraction with feature flags and optional dependencies
14//! - `is_pinned` analysis (exact version vs range specifiers)
15//! - Package URL (purl) generation
16//! - Workspace inheritance detection (stores `"workspace"` markers in extra_data)
17//!
18//! # Implementation Notes
19//! - Uses toml crate for parsing
20//! - Version pinning: `"1.0.0"` is pinned, `"^1.0.0"` is not
21//! - Graceful error handling with `warn!()` logs
22//! - Direct dependencies: all in manifest are direct (no lockfile)
23
24use crate::models::{DatasourceId, Dependency, FileReference, PackageData, PackageType, Party};
25use crate::parser_warn as warn;
26use crate::parsers::utils::{
27    MAX_ITERATION_COUNT, RecursionGuard, read_file_to_string, split_name_email, truncate_field,
28};
29use packageurl::PackageUrl;
30use std::path::Path;
31use toml::Value;
32
33use super::PackageParser;
34use super::license_normalization::{
35    DeclaredLicenseMatchMetadata, build_declared_license_data, empty_declared_license_data,
36    normalize_spdx_expression,
37};
38
39const FIELD_PACKAGE: &str = "package";
40const FIELD_NAME: &str = "name";
41const FIELD_VERSION: &str = "version";
42const FIELD_LICENSE: &str = "license";
43const FIELD_LICENSE_FILE: &str = "license-file";
44const FIELD_AUTHORS: &str = "authors";
45const FIELD_REPOSITORY: &str = "repository";
46const FIELD_HOMEPAGE: &str = "homepage";
47const FIELD_DEPENDENCIES: &str = "dependencies";
48const FIELD_DEV_DEPENDENCIES: &str = "dev-dependencies";
49const FIELD_DEV_DEPENDENCIES_LEGACY: &str = "dev_dependencies";
50const FIELD_BUILD_DEPENDENCIES: &str = "build-dependencies";
51const FIELD_BUILD_DEPENDENCIES_LEGACY: &str = "build_dependencies";
52const FIELD_DESCRIPTION: &str = "description";
53const FIELD_KEYWORDS: &str = "keywords";
54const FIELD_CATEGORIES: &str = "categories";
55const FIELD_RUST_VERSION: &str = "rust-version";
56const FIELD_EDITION: &str = "edition";
57const FIELD_README: &str = "readme";
58const FIELD_PUBLISH: &str = "publish";
59
60/// Rust Cargo.toml manifest parser.
61///
62/// Extracts package metadata including dependencies (regular, dev, build),
63/// license information, and crate-specific fields.
64pub struct CargoParser;
65
66impl PackageParser for CargoParser {
67    const PACKAGE_TYPE: PackageType = PackageType::Cargo;
68
69    fn extract_packages(path: &Path) -> Vec<PackageData> {
70        let toml_content = match read_cargo_toml(path) {
71            Ok(content) => content,
72            Err(_) => return Vec::new(),
73        };
74
75        let package = toml_content.get(FIELD_PACKAGE).and_then(|v| v.as_table());
76
77        let name = package
78            .and_then(|p| p.get(FIELD_NAME))
79            .and_then(|v| v.as_str())
80            .map(|s| truncate_field(s.to_string()));
81
82        let version = package
83            .and_then(|p| p.get(FIELD_VERSION))
84            .and_then(|v| v.as_str())
85            .map(|s| truncate_field(s.to_string()));
86
87        let raw_license = package
88            .and_then(|p| p.get(FIELD_LICENSE))
89            .and_then(|v| v.as_str())
90            .map(|s| truncate_field(s.to_string()));
91        let file_references = extract_file_references(&toml_content);
92        let (declared_license_expression, declared_license_expression_spdx, license_detections) =
93            raw_license
94                .as_deref()
95                .and_then(normalize_spdx_expression)
96                .map(|normalized| {
97                    build_declared_license_data(
98                        normalized,
99                        DeclaredLicenseMatchMetadata::single_line(
100                            raw_license.as_deref().unwrap_or_default(),
101                        ),
102                    )
103                })
104                .unwrap_or_else(empty_declared_license_data);
105
106        let extracted_license_statement = raw_license.clone();
107
108        let dependencies = extract_dependencies_for_scopes(&toml_content, &[FIELD_DEPENDENCIES]);
109        let dev_dependencies = extract_dependencies_for_scopes(
110            &toml_content,
111            &[FIELD_DEV_DEPENDENCIES, FIELD_DEV_DEPENDENCIES_LEGACY],
112        );
113        let build_dependencies = extract_dependencies_for_scopes(
114            &toml_content,
115            &[FIELD_BUILD_DEPENDENCIES, FIELD_BUILD_DEPENDENCIES_LEGACY],
116        );
117
118        let purl = create_package_url(&name, &version);
119
120        let homepage_url = package
121            .and_then(|p| p.get(FIELD_HOMEPAGE))
122            .and_then(|v| v.as_str())
123            .map(|s| truncate_field(s.to_string()))
124            .or_else(|| {
125                name.as_ref()
126                    .map(|n| format!("https://crates.io/crates/{}", n))
127            });
128
129        let repository_url = package
130            .and_then(|p| p.get(FIELD_REPOSITORY))
131            .and_then(|v| v.as_str())
132            .map(|s| truncate_field(s.to_string()));
133        let download_url = None;
134
135        let api_data_url = generate_cargo_api_url(&name, &version);
136
137        let repository_homepage_url = name
138            .as_ref()
139            .map(|n| format!("https://crates.io/crates/{}", n));
140
141        let repository_download_url = match (&name, &version) {
142            (Some(n), Some(v)) => Some(format!(
143                "https://crates.io/api/v1/crates/{}/{}/download",
144                n, v
145            )),
146            _ => None,
147        };
148
149        let description = package
150            .and_then(|p| p.get(FIELD_DESCRIPTION))
151            .and_then(|v| v.as_str())
152            .map(|s| truncate_field(s.trim().to_string()));
153
154        let keywords = extract_keywords_and_categories(&toml_content);
155
156        let extra_data = extract_extra_data(&toml_content);
157        let is_private = package
158            .and_then(|p| p.get(FIELD_PUBLISH))
159            .is_some_and(|value| matches!(value, Value::Boolean(false)));
160        vec![PackageData {
161            package_type: Some(Self::PACKAGE_TYPE),
162            namespace: None,
163            name,
164            version,
165            qualifiers: None,
166            subpath: None,
167            primary_language: Some("Rust".to_string()),
168            description,
169            release_date: None,
170            parties: extract_parties(&toml_content),
171            keywords,
172            homepage_url,
173            download_url,
174            size: None,
175            sha1: None,
176            md5: None,
177            sha256: None,
178            sha512: None,
179            bug_tracking_url: None,
180            code_view_url: None,
181            vcs_url: repository_url,
182            copyright: None,
183            holder: None,
184            declared_license_expression,
185            declared_license_expression_spdx,
186            license_detections,
187            other_license_expression: None,
188            other_license_expression_spdx: None,
189            other_license_detections: Vec::new(),
190            extracted_license_statement,
191            notice_text: None,
192            source_packages: Vec::new(),
193            file_references,
194            is_private,
195            is_virtual: false,
196            extra_data,
197            dependencies: [dependencies, dev_dependencies, build_dependencies].concat(),
198            repository_homepage_url,
199            repository_download_url,
200            api_data_url,
201            datasource_id: Some(DatasourceId::CargoToml),
202            purl,
203        }]
204    }
205
206    fn is_match(path: &Path) -> bool {
207        path.file_name()
208            .and_then(|name| name.to_str())
209            .is_some_and(|name| name.eq_ignore_ascii_case("cargo.toml"))
210    }
211}
212
213/// Reads and parses a TOML file
214fn read_cargo_toml(path: &Path) -> Result<Value, String> {
215    let content =
216        read_file_to_string(path, None).map_err(|e| format!("Failed to read file: {}", e))?;
217
218    toml::from_str(&content).map_err(|e| format!("Failed to parse TOML: {}", e))
219}
220
221fn generate_cargo_api_url(name: &Option<String>, _version: &Option<String>) -> Option<String> {
222    const REGISTRY: &str = "https://crates.io/api/v1/crates";
223    name.as_ref().map(|name| format!("{}/{}", REGISTRY, name))
224}
225
226fn create_package_url(name: &Option<String>, version: &Option<String>) -> Option<String> {
227    name.as_ref().and_then(|name| {
228        let mut package_url = match PackageUrl::new(CargoParser::PACKAGE_TYPE.as_str(), name) {
229            Ok(p) => p,
230            Err(e) => {
231                warn!(
232                    "Failed to create PackageUrl for cargo package '{}': {}",
233                    name, e
234                );
235                return None;
236            }
237        };
238
239        if let Some(v) = version
240            && let Err(e) = package_url.with_version(v)
241        {
242            warn!(
243                "Failed to set version '{}' for cargo package '{}': {}",
244                v, name, e
245            );
246            return None;
247        }
248
249        Some(package_url.to_string())
250    })
251}
252
253/// Extracts party information from the `authors` field
254fn extract_parties(toml_content: &Value) -> Vec<Party> {
255    let mut parties = Vec::new();
256
257    if let Some(package) = toml_content.get(FIELD_PACKAGE).and_then(|v| v.as_table())
258        && let Some(authors) = package.get(FIELD_AUTHORS).and_then(|v| v.as_array())
259    {
260        for author in authors.iter().take(MAX_ITERATION_COUNT) {
261            if let Some(author_str) = author.as_str() {
262                let (name, email) = split_name_email(author_str);
263                parties.push(Party {
264                    r#type: None,
265                    role: Some("author".to_string()),
266                    name,
267                    email,
268                    url: None,
269                    organization: None,
270                    organization_url: None,
271                    timezone: None,
272                });
273            }
274        }
275        if authors.len() > MAX_ITERATION_COUNT {
276            warn!(
277                "Authors array has {} entries, capping at MAX_ITERATION_COUNT ({})",
278                authors.len(),
279                MAX_ITERATION_COUNT
280            );
281        }
282    }
283
284    parties
285}
286
287/// Determines if a Cargo version specifier is pinned to an exact version.
288///
289/// A version is considered pinned if it specifies an exact version (full semver)
290/// without range operators. Examples:
291/// - Pinned: "1.0.0", "0.8.1"
292/// - NOT pinned: "0.8" (allows patch), "^1.0.0", "~1.0.0", ">=1.0.0", "*"
293fn is_cargo_version_pinned(version_str: &str) -> bool {
294    let trimmed = version_str.trim();
295
296    // Empty version is not pinned
297    if trimmed.is_empty() {
298        return false;
299    }
300
301    // Check for range operators that indicate unpinned versions
302    if trimmed.contains('^')
303        || trimmed.contains('~')
304        || trimmed.contains('>')
305        || trimmed.contains('<')
306        || trimmed.contains('*')
307        || trimmed.contains('=')
308    {
309        return false;
310    }
311
312    // Count dots to check if it's a full semver (major.minor.patch)
313    // Pinned versions must have at least 2 dots (e.g., "1.0.0")
314    // Partial versions like "0.8" or "1" are not pinned
315    trimmed.matches('.').count() >= 2
316}
317
318fn extract_dependencies(toml_content: &Value, scope: &str) -> Vec<Dependency> {
319    use serde_json::json;
320
321    let mut dependencies = Vec::new();
322
323    // Determine is_runtime based on scope
324    let is_runtime = !scope.ends_with("dev-dependencies") && !scope.ends_with("build-dependencies");
325
326    if let Some(deps_table) = toml_content.get(scope).and_then(|v| v.as_table()) {
327        if deps_table.len() > MAX_ITERATION_COUNT {
328            warn!(
329                "Dependency table '{}' has {} entries, capping at MAX_ITERATION_COUNT ({})",
330                scope,
331                deps_table.len(),
332                MAX_ITERATION_COUNT
333            );
334        }
335        for (name, value) in deps_table.iter().take(MAX_ITERATION_COUNT) {
336            let (extracted_requirement, is_optional, extra_data_map, is_pinned) = match value {
337                Value::String(version_str) => {
338                    // Simple string version: "1.0"
339                    let pinned = is_cargo_version_pinned(version_str);
340                    (
341                        Some(version_str.to_string()),
342                        false,
343                        std::collections::HashMap::new(),
344                        pinned,
345                    )
346                }
347                Value::Table(table) => {
348                    // Complex table format: { version = "1.0", optional = true, features = [...] }
349                    let version = table
350                        .get("version")
351                        .and_then(|v| v.as_str())
352                        .map(String::from);
353
354                    let pinned = version.as_ref().is_some_and(|v| is_cargo_version_pinned(v));
355
356                    let is_optional = table
357                        .get("optional")
358                        .and_then(|v| v.as_bool())
359                        .unwrap_or(false);
360
361                    let mut extra_data = std::collections::HashMap::new();
362
363                    // Extract all table fields into extra_data
364                    for (key, val) in table {
365                        match key.as_str() {
366                            "version" => {
367                                // Store version in extra_data
368                                if let Some(v) = val.as_str() {
369                                    extra_data.insert("version".to_string(), json!(v));
370                                }
371                            }
372                            "features" => {
373                                // Extract features array
374                                if let Some(features_array) = val.as_array() {
375                                    let features: Vec<String> = features_array
376                                        .iter()
377                                        .filter_map(|f| f.as_str().map(String::from))
378                                        .collect();
379                                    extra_data.insert("features".to_string(), json!(features));
380                                }
381                            }
382                            "optional" => {
383                                // Skip optional flag, it's handled separately
384                            }
385                            _ => {
386                                // Store other fields (workspace, path, git, branch, tag, rev, etc.)
387                                if let Some(s) = val.as_str() {
388                                    extra_data.insert(key.clone(), json!(s));
389                                } else if let Some(b) = val.as_bool() {
390                                    extra_data.insert(key.clone(), json!(b));
391                                } else if let Some(i) = val.as_integer() {
392                                    extra_data.insert(key.clone(), json!(i));
393                                }
394                            }
395                        }
396                    }
397
398                    (version, is_optional, extra_data, pinned)
399                }
400                _ => {
401                    // Unknown format, skip
402                    continue;
403                }
404            };
405
406            // Only create dependency if we have a version or it's a table with other data
407            if extracted_requirement.is_some() || !extra_data_map.is_empty() {
408                let purl = match PackageUrl::new(CargoParser::PACKAGE_TYPE.as_str(), name) {
409                    Ok(p) => p.to_string(),
410                    Err(e) => {
411                        warn!(
412                            "Failed to create PackageUrl for cargo dependency '{}': {}",
413                            name, e
414                        );
415                        continue; // Skip this dependency
416                    }
417                };
418
419                dependencies.push(Dependency {
420                    purl: Some(purl),
421                    extracted_requirement,
422                    scope: Some(scope.to_string()),
423                    is_runtime: Some(is_runtime),
424                    is_optional: Some(is_optional),
425                    is_pinned: Some(is_pinned),
426                    is_direct: Some(true),
427                    resolved_package: None,
428                    extra_data: if extra_data_map.is_empty() {
429                        None
430                    } else {
431                        Some(extra_data_map)
432                    },
433                });
434            }
435        }
436    }
437
438    dependencies
439}
440
441fn extract_dependencies_for_scopes(toml_content: &Value, scopes: &[&str]) -> Vec<Dependency> {
442    scopes
443        .iter()
444        .flat_map(|scope| extract_dependencies(toml_content, scope))
445        .collect()
446}
447
448/// Extracts keywords and categories, merging them into a single keywords array
449fn extract_keywords_and_categories(toml_content: &Value) -> Vec<String> {
450    let mut keywords = Vec::new();
451
452    if let Some(package) = toml_content.get(FIELD_PACKAGE).and_then(|v| v.as_table()) {
453        if let Some(kw_array) = package.get(FIELD_KEYWORDS).and_then(|v| v.as_array()) {
454            if kw_array.len() > MAX_ITERATION_COUNT {
455                warn!(
456                    "Keywords array has {} entries, capping at MAX_ITERATION_COUNT ({})",
457                    kw_array.len(),
458                    MAX_ITERATION_COUNT
459                );
460            }
461            for kw in kw_array.iter().take(MAX_ITERATION_COUNT) {
462                if let Some(kw_str) = kw.as_str() {
463                    keywords.push(truncate_field(kw_str.to_string()));
464                }
465            }
466        }
467
468        if let Some(cat_array) = package.get(FIELD_CATEGORIES).and_then(|v| v.as_array()) {
469            if cat_array.len() > MAX_ITERATION_COUNT {
470                warn!(
471                    "Categories array has {} entries, capping at MAX_ITERATION_COUNT ({})",
472                    cat_array.len(),
473                    MAX_ITERATION_COUNT
474                );
475            }
476            for cat in cat_array.iter().take(MAX_ITERATION_COUNT) {
477                if let Some(cat_str) = cat.as_str() {
478                    keywords.push(truncate_field(cat_str.to_string()));
479                }
480            }
481        }
482    }
483
484    keywords
485}
486
487fn extract_file_references(toml_content: &Value) -> Vec<FileReference> {
488    let mut file_references = Vec::new();
489
490    if let Some(package) = toml_content
491        .get(FIELD_PACKAGE)
492        .and_then(|value| value.as_table())
493    {
494        for path in [
495            package
496                .get(FIELD_LICENSE_FILE)
497                .and_then(|value| value.as_str()),
498            package.get(FIELD_README).and_then(|value| value.as_str()),
499        ]
500        .into_iter()
501        .flatten()
502        {
503            if file_references
504                .iter()
505                .any(|reference: &FileReference| reference.path == path)
506            {
507                continue;
508            }
509
510            file_references.push(FileReference {
511                path: path.to_string(),
512                size: None,
513                sha1: None,
514                md5: None,
515                sha256: None,
516                sha512: None,
517                extra_data: None,
518            });
519        }
520    }
521
522    file_references
523}
524
525fn toml_to_json(value: &toml::Value, guard: &mut RecursionGuard<()>) -> serde_json::Value {
526    if guard.descend() {
527        warn!("TOML nesting depth exceeded, returning Null");
528        return serde_json::Value::Null;
529    }
530    let result = match value {
531        toml::Value::String(s) => serde_json::json!(s),
532        toml::Value::Integer(i) => serde_json::json!(i),
533        toml::Value::Float(f) => serde_json::json!(f),
534        toml::Value::Boolean(b) => serde_json::json!(b),
535        toml::Value::Array(a) => {
536            serde_json::Value::Array(a.iter().map(|v| toml_to_json(v, guard)).collect())
537        }
538        toml::Value::Table(t) => {
539            let map: serde_json::Map<String, serde_json::Value> = t
540                .iter()
541                .map(|(k, v)| (k.clone(), toml_to_json(v, guard)))
542                .collect();
543            serde_json::Value::Object(map)
544        }
545        toml::Value::Datetime(d) => serde_json::json!(d.to_string()),
546    };
547    guard.ascend();
548    result
549}
550
551/// Extracts extra_data fields (rust-version, edition, documentation, license-file, workspace)
552fn extract_extra_data(
553    toml_content: &Value,
554) -> Option<std::collections::HashMap<String, serde_json::Value>> {
555    use serde_json::json;
556    let mut extra_data = std::collections::HashMap::new();
557
558    if let Some(package) = toml_content.get(FIELD_PACKAGE).and_then(|v| v.as_table()) {
559        if package.len() > MAX_ITERATION_COUNT {
560            warn!(
561                "Package table has {} entries, exceeding MAX_ITERATION_COUNT ({})",
562                package.len(),
563                MAX_ITERATION_COUNT
564            );
565        }
566        if let Some(rust_version_value) = package.get(FIELD_RUST_VERSION) {
567            if let Some(rust_version_str) = rust_version_value.as_str() {
568                extra_data.insert("rust_version".to_string(), json!(rust_version_str));
569            } else if rust_version_value
570                .as_table()
571                .is_some_and(|t| t.get("workspace") == Some(&toml::Value::Boolean(true)))
572            {
573                extra_data.insert("rust-version".to_string(), json!("workspace"));
574            }
575        }
576
577        // Extract edition (or detect workspace inheritance)
578        if let Some(edition_value) = package.get(FIELD_EDITION) {
579            if let Some(edition_str) = edition_value.as_str() {
580                extra_data.insert("rust_edition".to_string(), json!(edition_str));
581            } else if edition_value
582                .as_table()
583                .is_some_and(|t| t.get("workspace") == Some(&toml::Value::Boolean(true)))
584            {
585                extra_data.insert("edition".to_string(), json!("workspace"));
586            }
587        }
588
589        // Extract documentation URL
590        if let Some(documentation) = package.get("documentation").and_then(|v| v.as_str()) {
591            extra_data.insert("documentation_url".to_string(), json!(documentation));
592        }
593
594        // Extract license-file path
595        if let Some(license_file) = package.get(FIELD_LICENSE_FILE).and_then(|v| v.as_str()) {
596            extra_data.insert("license_file".to_string(), json!(license_file));
597        }
598
599        if let Some(readme_value) = package.get(FIELD_README) {
600            if let Some(readme_file) = readme_value.as_str() {
601                extra_data.insert("readme_file".to_string(), json!(readme_file));
602            } else if let Some(readme_enabled) = readme_value.as_bool() {
603                extra_data.insert("readme".to_string(), json!(readme_enabled));
604            } else if readme_value
605                .as_table()
606                .is_some_and(|t| t.get("workspace") == Some(&toml::Value::Boolean(true)))
607            {
608                extra_data.insert("readme".to_string(), json!("workspace"));
609            }
610        }
611
612        if let Some(publish_value) = package.get(FIELD_PUBLISH) {
613            extra_data.insert(
614                "publish".to_string(),
615                toml_to_json(publish_value, &mut RecursionGuard::depth_only()),
616            );
617        }
618
619        // Check for workspace inheritance markers for other fields
620        // version
621        if let Some(version_value) = package.get(FIELD_VERSION)
622            && version_value
623                .as_table()
624                .is_some_and(|t| t.get("workspace") == Some(&toml::Value::Boolean(true)))
625        {
626            extra_data.insert("version".to_string(), json!("workspace"));
627        }
628
629        // license
630        if let Some(license_value) = package.get(FIELD_LICENSE)
631            && license_value
632                .as_table()
633                .is_some_and(|t| t.get("workspace") == Some(&toml::Value::Boolean(true)))
634        {
635            extra_data.insert("license".to_string(), json!("workspace"));
636        }
637
638        // homepage
639        if let Some(homepage_value) = package.get(FIELD_HOMEPAGE)
640            && homepage_value
641                .as_table()
642                .is_some_and(|t| t.get("workspace") == Some(&toml::Value::Boolean(true)))
643        {
644            extra_data.insert("homepage".to_string(), json!("workspace"));
645        }
646
647        // repository
648        if let Some(repository_value) = package.get(FIELD_REPOSITORY)
649            && repository_value
650                .as_table()
651                .is_some_and(|t| t.get("workspace") == Some(&toml::Value::Boolean(true)))
652        {
653            extra_data.insert("repository".to_string(), json!("workspace"));
654        }
655
656        // categories
657        if let Some(categories_value) = package.get(FIELD_CATEGORIES)
658            && categories_value
659                .as_table()
660                .is_some_and(|t| t.get("workspace") == Some(&toml::Value::Boolean(true)))
661        {
662            extra_data.insert("categories".to_string(), json!("workspace"));
663        }
664
665        // authors
666        if let Some(authors_value) = package.get(FIELD_AUTHORS)
667            && authors_value
668                .as_table()
669                .is_some_and(|t| t.get("workspace") == Some(&toml::Value::Boolean(true)))
670        {
671            extra_data.insert("authors".to_string(), json!("workspace"));
672        }
673    }
674
675    // Extract workspace table if it exists
676    if let Some(workspace_value) = toml_content.get("workspace") {
677        extra_data.insert(
678            "workspace".to_string(),
679            toml_to_json(workspace_value, &mut RecursionGuard::depth_only()),
680        );
681    }
682
683    if extra_data.is_empty() {
684        None
685    } else {
686        Some(extra_data)
687    }
688}
689
690crate::register_parser!(
691    "Rust Cargo.toml manifest",
692    &["**/Cargo.toml", "**/cargo.toml"],
693    "cargo",
694    "Rust",
695    Some("https://doc.rust-lang.org/cargo/reference/manifest.html"),
696);