sbom-tools 0.1.22

Semantic SBOM diff and analysis tool
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
//! C-compatible ABI for Go and Swift wrappers.

#![deny(unsafe_op_in_unsafe_fn)]

use crate::diff::DiffEngine;
use crate::model::{
    CanonicalId, Component, DependencyEdge, DocumentMetadata, FormatExtensions, NormalizedSbom,
};
use crate::parsers::{ParseError, detect_format, parse_sbom, parse_sbom_str};
use crate::quality::{QualityScorer, ScoringProfile};
use indexmap::IndexMap;
use serde::Serialize;
use std::ffi::{CStr, CString, c_char};
use std::path::Path;

const ABI_VERSION: &str = env!("CARGO_PKG_VERSION");

/// Stable error codes for the C ABI.
#[repr(u32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SbomToolsErrorCode {
    /// Successful operation.
    Ok = 0,
    /// Parsing of raw SBOM input failed.
    Parse = 1,
    /// Semantic diffing failed.
    Diff = 2,
    /// Validation of normalized JSON input failed.
    Validation = 3,
    /// IO failed while reading from disk.
    Io = 4,
    /// Requested functionality is unsupported.
    Unsupported = 5,
    /// Unexpected internal failure.
    Internal = 6,
}

/// Stable scoring profile identifiers for the C ABI.
#[repr(u32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SbomToolsScoringProfile {
    Minimal = 0,
    Standard = 1,
    Security = 2,
    LicenseCompliance = 3,
    Cra = 4,
    Comprehensive = 5,
    AiReadiness = 6,
}

impl SbomToolsScoringProfile {
    const fn into_rust(self) -> ScoringProfile {
        match self {
            Self::Minimal => ScoringProfile::Minimal,
            Self::Standard => ScoringProfile::Standard,
            Self::Security => ScoringProfile::Security,
            Self::LicenseCompliance => ScoringProfile::LicenseCompliance,
            Self::Cra => ScoringProfile::Cra,
            Self::Comprehensive => ScoringProfile::Comprehensive,
            Self::AiReadiness => ScoringProfile::AiReadiness,
        }
    }
}

/// Generic string payload result for the C ABI.
#[repr(C)]
#[derive(Debug)]
pub struct SbomToolsStringResult {
    /// JSON payload on success.
    pub data: *mut c_char,
    /// Stable ABI error code.
    pub error_code: SbomToolsErrorCode,
    /// UTF-8 error message on failure.
    pub error_message: *mut c_char,
}

impl SbomToolsStringResult {
    fn success(payload: String) -> Self {
        Self {
            data: into_c_string(payload),
            error_code: SbomToolsErrorCode::Ok,
            error_message: std::ptr::null_mut(),
        }
    }

    fn error(code: SbomToolsErrorCode, message: impl Into<String>) -> Self {
        Self {
            data: std::ptr::null_mut(),
            error_code: code,
            error_message: into_c_string(message.into()),
        }
    }
}

struct FfiError {
    code: SbomToolsErrorCode,
    message: String,
}

#[derive(Debug, Serialize, serde::Deserialize)]
struct AbiComponentEntry {
    canonical_id: CanonicalId,
    component: Component,
}

#[derive(Debug, Serialize, serde::Deserialize)]
struct AbiNormalizedSbom {
    document: DocumentMetadata,
    components: Vec<AbiComponentEntry>,
    edges: Vec<DependencyEdge>,
    extensions: FormatExtensions,
    content_hash: u64,
    primary_component_id: Option<CanonicalId>,
    collision_count: usize,
}

impl AbiNormalizedSbom {
    fn from_sbom(sbom: NormalizedSbom) -> Self {
        Self {
            document: sbom.document,
            components: sbom
                .components
                .into_iter()
                .map(|(canonical_id, component)| AbiComponentEntry {
                    canonical_id,
                    component,
                })
                .collect(),
            edges: sbom.edges,
            extensions: sbom.extensions,
            content_hash: sbom.content_hash,
            primary_component_id: sbom.primary_component_id,
            collision_count: sbom.collision_count,
        }
    }

    fn into_sbom(self) -> NormalizedSbom {
        let components = self
            .components
            .into_iter()
            .map(|entry| (entry.canonical_id, entry.component))
            .collect::<IndexMap<_, _>>();

        NormalizedSbom {
            document: self.document,
            components,
            edges: self.edges,
            extensions: self.extensions,
            content_hash: self.content_hash,
            primary_component_id: self.primary_component_id,
            collision_count: self.collision_count,
        }
    }
}

#[derive(Serialize)]
struct AbiVersionPayload<'a> {
    abi_version: &'a str,
    crate_version: &'a str,
}

fn into_c_string(value: String) -> *mut c_char {
    let sanitized = value.replace('\0', " ");
    match CString::new(sanitized) {
        Ok(c_string) => c_string.into_raw(),
        Err(_) => std::ptr::null_mut(),
    }
}

fn read_input(value: *const c_char, field: &str) -> Result<String, FfiError> {
    if value.is_null() {
        return Err(FfiError {
            code: SbomToolsErrorCode::Validation,
            message: format!("{field} pointer must not be null"),
        });
    }

    // SAFETY: The caller guarantees a valid NUL-terminated string pointer.
    let c_string = unsafe { CStr::from_ptr(value) };
    c_string
        .to_str()
        .map(str::to_owned)
        .map_err(|err| FfiError {
            code: SbomToolsErrorCode::Validation,
            message: format!("{field} must be valid UTF-8: {err}"),
        })
}

fn parse_normalized_sbom(json: &str, field: &str) -> Result<NormalizedSbom, FfiError> {
    serde_json::from_str::<AbiNormalizedSbom>(json)
        .map(AbiNormalizedSbom::into_sbom)
        .map_err(|err| FfiError {
            code: SbomToolsErrorCode::Validation,
            message: format!("invalid normalized SBOM JSON in {field}: {err}"),
        })
}

fn map_parse_error(err: ParseError) -> FfiError {
    let (code, message) = match err {
        ParseError::IoError(_) => (
            SbomToolsErrorCode::Io,
            "failed to read file (permission denied, file not found, or I/O error)".to_string(),
        ),
        ParseError::UnsupportedVersion(v) => (
            SbomToolsErrorCode::Unsupported,
            format!("unsupported SBOM version: {v}"),
        ),
        ParseError::UnknownFormat(_) => (
            SbomToolsErrorCode::Unsupported,
            "unknown SBOM format (expected CycloneDX or SPDX)".to_string(),
        ),
        ParseError::ValidationError(msg) => (
            SbomToolsErrorCode::Validation,
            format!("SBOM validation failed: {msg}"),
        ),
        ParseError::MissingField(field) => (
            SbomToolsErrorCode::Validation,
            format!("required field missing: {field}"),
        ),
        ParseError::JsonError(msg) => (
            SbomToolsErrorCode::Parse,
            format!("JSON parsing failed: {msg}"),
        ),
        ParseError::XmlError(msg) => (
            SbomToolsErrorCode::Parse,
            format!("XML parsing failed: {msg}"),
        ),
        ParseError::YamlError(msg) => (
            SbomToolsErrorCode::Parse,
            format!("YAML parsing failed: {msg}"),
        ),
        ParseError::InvalidStructure(msg) => (
            SbomToolsErrorCode::Parse,
            format!("invalid SBOM structure: {msg}"),
        ),
    };

    FfiError { code, message }
}

fn run_json<T, F>(operation: F) -> SbomToolsStringResult
where
    T: Serialize,
    F: FnOnce() -> Result<T, FfiError>,
{
    match operation() {
        Ok(value) => match serde_json::to_string_pretty(&value) {
            Ok(payload) => SbomToolsStringResult::success(payload),
            Err(err) => SbomToolsStringResult::error(
                SbomToolsErrorCode::Internal,
                format!("failed to serialize ABI response: {err}"),
            ),
        },
        Err(err) => SbomToolsStringResult::error(err.code, err.message),
    }
}

/// Wrap an FFI function body with panic catching.
///
/// Any panic inside the closure will be caught and converted to an FFI error.
/// This prevents undefined behavior from panics crossing the FFI boundary.
///
/// # SAFETY & CORRECTNESS
/// Panics must never unwind across the FFI boundary into C code (UB).
/// This wrapper converts `catch_unwind` panic payload into an error result.
fn catch_ffi_panic<F>(f: F) -> SbomToolsStringResult
where
    F: FnOnce() -> SbomToolsStringResult + std::panic::UnwindSafe,
{
    match std::panic::catch_unwind(f) {
        Ok(result) => result,
        Err(_) => SbomToolsStringResult::error(
            SbomToolsErrorCode::Internal,
            "internal panic caught at FFI boundary",
        ),
    }
}

/// Return the ABI and crate versions as JSON.
#[unsafe(no_mangle)]
pub extern "C" fn sbom_tools_abi_version_json() -> SbomToolsStringResult {
    catch_ffi_panic(|| {
        run_json(|| {
            Ok(AbiVersionPayload {
                abi_version: "1",
                crate_version: ABI_VERSION,
            })
        })
    })
}

/// Detect the SBOM format from raw content and return JSON.
#[unsafe(no_mangle)]
pub extern "C" fn sbom_tools_detect_format_json(content: *const c_char) -> SbomToolsStringResult {
    catch_ffi_panic(|| {
        run_json(|| {
            let content = read_input(content, "content")?;
            Ok(detect_format(&content))
        })
    })
}

/// Parse an SBOM file from disk and return normalized JSON.
#[unsafe(no_mangle)]
pub extern "C" fn sbom_tools_parse_sbom_path_json(path: *const c_char) -> SbomToolsStringResult {
    catch_ffi_panic(|| {
        run_json(|| {
            let path = read_input(path, "path")?;
            parse_sbom(Path::new(&path))
                .map(AbiNormalizedSbom::from_sbom)
                .map_err(map_parse_error)
        })
    })
}

/// Parse raw SBOM content and return normalized JSON.
#[unsafe(no_mangle)]
pub extern "C" fn sbom_tools_parse_sbom_str_json(content: *const c_char) -> SbomToolsStringResult {
    catch_ffi_panic(|| {
        run_json(|| {
            let content = read_input(content, "content")?;
            parse_sbom_str(&content)
                .map(AbiNormalizedSbom::from_sbom)
                .map_err(map_parse_error)
        })
    })
}

/// Diff two normalized SBOM JSON documents and return a diff result as JSON.
#[unsafe(no_mangle)]
pub extern "C" fn sbom_tools_diff_sboms_json(
    old_sbom_json: *const c_char,
    new_sbom_json: *const c_char,
) -> SbomToolsStringResult {
    catch_ffi_panic(|| {
        run_json(|| {
            let old_json = read_input(old_sbom_json, "old_sbom_json")?;
            let new_json = read_input(new_sbom_json, "new_sbom_json")?;
            let old = parse_normalized_sbom(&old_json, "old_sbom_json")?;
            let new = parse_normalized_sbom(&new_json, "new_sbom_json")?;

            DiffEngine::new().diff(&old, &new).map_err(|err| FfiError {
                code: SbomToolsErrorCode::Diff,
                message: err.to_string(),
            })
        })
    })
}

/// Score a normalized SBOM JSON document and return a quality report as JSON.
#[unsafe(no_mangle)]
pub extern "C" fn sbom_tools_score_sbom_json(
    sbom_json: *const c_char,
    profile: SbomToolsScoringProfile,
) -> SbomToolsStringResult {
    catch_ffi_panic(|| {
        run_json(|| {
            let sbom_json = read_input(sbom_json, "sbom_json")?;
            let sbom = parse_normalized_sbom(&sbom_json, "sbom_json")?;
            Ok(QualityScorer::new(profile.into_rust()).score(&sbom))
        })
    })
}

/// Free memory allocated by the ABI result.
///
/// # Safety
/// - The caller must call this exactly once per result.
/// - The result must not be used after this call.
/// - Calling free twice on the same result is **undefined behavior**: the struct
///   is passed by value (C calling convention), so the caller's copy retains
///   the original (now-dangling) pointers. The internal pointer zeroing only
///   affects the local copy inside this function.
///
/// # C Usage
/// ```c
/// SbomToolsStringResult result = sbom_tools_parse_sbom_str_json(content);
/// // use result.data and result.error_message
/// sbom_tools_string_result_free(result);
/// // Do NOT call sbom_tools_string_result_free(result) again — undefined behavior.
/// ```
#[unsafe(no_mangle)]
pub extern "C" fn sbom_tools_string_result_free(mut result: SbomToolsStringResult) {
    if !result.data.is_null() {
        // SAFETY: The pointer was allocated by CString::into_raw in this module.
        // Caller must guarantee this is the first and only free of this pointer.
        unsafe {
            drop(CString::from_raw(result.data));
        }
        result.data = std::ptr::null_mut(); // Zero to defend against caller copies
    }

    if !result.error_message.is_null() {
        // SAFETY: The pointer was allocated by CString::into_raw in this module.
        // Caller must guarantee this is the first and only free of this pointer.
        unsafe {
            drop(CString::from_raw(result.error_message));
        }
        #[allow(unused_assignments)]
        {
            result.error_message = std::ptr::null_mut(); // Zero to defend against caller copies
        }
    }
}