ssg 0.0.47

A secure-by-default static site generator built in Rust. WCAG 2.2 AA validation, CSP/SRI hardening, native JS/CSS minification, automated CycloneDX SBOM, local LLM content pipeline, WebAssembly target, interactive islands, streaming compilation for 100K+ pages, 28-locale i18n, and one-command deployment.
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
// Copyright © 2023 - 2026 Static Site Generator (SSG). All rights reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! Build-time SBOM generation (issue #457).
//!
//! Emits a `CycloneDX` 1.5 JSON Software Bill of Materials at the
//! root of the generated site (`sbom.cdx.json`) and links to it
//! from every HTML page via `<link rel="sbom" type="application/vnd.cyclonedx+json">`.
//!
//! # Why ship an SBOM with the static site?
//!
//! Procurement teams in regulated industries (finance, healthcare,
//! government) increasingly require SBOMs for any deployed software
//! — including the build pipeline that produced static assets. The
//! `scheduled.yml` workflow already generates a `CycloneDX` SBOM via
//! `cargo cyclonedx` and attaches a Sigstore provenance attestation,
//! but those artifacts live in CI; they're not discoverable from
//! the deployed site. This plugin fixes that gap by **embedding**
//! the SBOM into every site, making the supply chain machine-
//! introspectable from the consumer's browser.
//!
//! # Format
//!
//! Minimal `CycloneDX` 1.5 (the JSON Schema is documented at
//! <https://cyclonedx.org/docs/1.5/json/>). The component list
//! covers the SSG package itself; transitive Cargo dependencies
//! are out of scope here (they're in the CI-generated SBOM
//! published as a release artifact). The rendered SBOM declares:
//!
//! - `bomFormat`: "`CycloneDX`"
//! - `specVersion`: "1.5"
//! - `version`: 1
//! - `metadata.timestamp`: build time (ISO 8601, UTC)
//! - `metadata.tools[]`: SSG name + version
//! - `metadata.component`: the site itself (type: "application")
//! - `components[]`: SSG generator
//!
//! # Discoverability
//!
//! Every HTML page emitted by the build receives a
//! `<link rel="sbom" type="application/vnd.cyclonedx+json"
//!  href="/sbom.cdx.json">` element in `<head>`. This is the
//! IANA-registered link relation for SBOM discovery (registered
//! 2023; see <https://www.iana.org/assignments/link-relations/>).
//!
//! # Idempotency
//!
//! The HTML transform is idempotent — pages that already contain
//! `rel="sbom"` are left unchanged. The JSON file is rewritten on
//! every build (so timestamps stay current).

use crate::error::{PathErrorExt, SsgError};
use crate::plugin::{Plugin, PluginContext};
use crate::util::head_dom::inject_before_head_close;
use std::fs;
use std::path::Path;

/// Plugin that emits a `CycloneDX` SBOM and links to it from every
/// HTML page.
#[derive(Debug, Clone, Copy, Default)]
pub struct SbomPlugin;

impl SbomPlugin {
    /// Returns the relative path of the SBOM file under `site_dir`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ssg::sbom::SbomPlugin;
    ///
    /// assert_eq!(SbomPlugin::sbom_path(), "sbom.cdx.json");
    /// ```
    pub const fn sbom_path() -> &'static str {
        "sbom.cdx.json"
    }
}

impl Plugin for SbomPlugin {
    fn name(&self) -> &'static str {
        "sbom"
    }

    fn after_compile(&self, ctx: &PluginContext) -> Result<(), SsgError> {
        if !ctx.site_dir.exists() {
            return Ok(());
        }
        let sbom = build_sbom();
        let path = ctx.site_dir.join(Self::sbom_path());
        let json = serialize_sbom(&sbom).map_err(|e| SsgError::Io {
            path: path.clone(),
            source: std::io::Error::other(e),
        })?;
        fs::write(&path, json).with_path(&path)?;
        log::info!("[sbom] Wrote CycloneDX SBOM to {}", path.display());
        Ok(())
    }

    fn has_transform(&self) -> bool {
        true
    }

    fn transform_html(
        &self,
        html: &str,
        _path: &Path,
        _ctx: &PluginContext,
    ) -> Result<String, SsgError> {
        // Idempotent: skip if an SBOM link is already present.
        if html.contains("rel=\"sbom\"") || html.contains("rel='sbom'") {
            return Ok(html.to_string());
        }
        let link = format!(
            "<link rel=\"sbom\" type=\"application/vnd.cyclonedx+json\" \
             href=\"/{}\">\n",
            Self::sbom_path()
        );
        Ok(inject_before_head_close(html, &link))
    }
}

/// Builds the minimal `CycloneDX` 1.5 SBOM document for this site.
fn build_sbom() -> serde_json::Value {
    let now = current_iso_timestamp();
    let ssg_version = env!("CARGO_PKG_VERSION");
    serde_json::json!({
        "bomFormat": "CycloneDX",
        "specVersion": "1.5",
        "version": 1,
        "metadata": {
            "timestamp": now,
            "tools": [{
                "vendor": "SSG Contributors",
                "name": "ssg",
                "version": ssg_version,
            }],
            "component": {
                "type": "application",
                "bom-ref": "site",
                "name": "static-site",
                "description": "Site generated by SSG",
            }
        },
        "components": [{
            "type": "application",
            "bom-ref": format!("ssg@{ssg_version}"),
            "name": "ssg",
            "version": ssg_version,
            "description": "Static site generator",
            "purl": format!("pkg:cargo/ssg@{ssg_version}"),
            "licenses": [
                {"license": {"id": "MIT"}},
                {"license": {"id": "Apache-2.0"}}
            ],
            "externalReferences": [
                {"type": "vcs", "url": "https://github.com/sebastienrousseau/static-site-generator"},
                {"type": "documentation", "url": "https://docs.rs/ssg"}
            ]
        }]
    })
}

/// Serialize the SBOM with a fault-injection hook so tests can drive
/// the error branch (pretty-printing a `Value` built from hardcoded
/// strings and numbers cannot fail in practice).
fn serialize_sbom(sbom: &serde_json::Value) -> serde_json::Result<String> {
    fail_point!("sbom::serialize", |_| Err(
        <serde_json::Error as serde::ser::Error>::custom(
            "injected: sbom::serialize"
        )
    ));
    serde_json::to_string_pretty(sbom)
}

/// Cheap ISO 8601 timestamp without pulling in a date crate.
/// Uses `std::time::SystemTime` and converts `UNIX_EPOCH` seconds to
/// `YYYY-MM-DDTHH:MM:SSZ` via the proleptic Gregorian calendar.
///
/// Reproducible builds (SECURITY.md convention, determinism.yml CI
/// gate): a wall-clock timestamp makes `sbom.cdx.json` differ across
/// otherwise-identical builds, so `SOURCE_DATE_EPOCH` wins when set —
/// same convention as `postprocess::sbom::current_timestamp`.
fn current_iso_timestamp() -> String {
    use std::time::{SystemTime, UNIX_EPOCH};
    if let Ok(epoch) = std::env::var("SOURCE_DATE_EPOCH") {
        if let Ok(secs) = epoch.trim().parse::<u64>() {
            return epoch_to_iso(secs);
        }
    }
    let secs = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| d.as_secs());
    epoch_to_iso(secs)
}

/// Converts seconds since UNIX epoch to ISO 8601 `YYYY-MM-DDTHH:MM:SSZ`.
fn epoch_to_iso(secs: u64) -> String {
    // Days since 1970-01-01 + seconds within day.
    let days = secs / 86_400;
    let sec_in_day = secs % 86_400;
    let hour = (sec_in_day / 3600) as u32;
    let minute = ((sec_in_day % 3600) / 60) as u32;
    let second = (sec_in_day % 60) as u32;

    // Convert `days` to YYYY-MM-DD via proleptic Gregorian rules.
    // Algorithm from Howard Hinnant's date library (public domain).
    let z = days as i64 + 719_468;
    let era = z.div_euclid(146_097);
    let doe = (z - era * 146_097) as u64;
    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
    let y = (yoe as i64) + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
    let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
    let year = if month <= 2 { y + 1 } else { y };

    format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}Z")
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::Path;
    use tempfile::tempdir;

    #[test]
    fn epoch_to_iso_handles_unix_epoch() {
        assert_eq!(epoch_to_iso(0), "1970-01-01T00:00:00Z");
    }

    #[test]
    fn epoch_to_iso_handles_known_timestamps() {
        // 1700000000 = 2023-11-14 22:13:20 UTC
        assert_eq!(epoch_to_iso(1_700_000_000), "2023-11-14T22:13:20Z");
        // 1577836800 = 2020-01-01 00:00:00 UTC
        assert_eq!(epoch_to_iso(1_577_836_800), "2020-01-01T00:00:00Z");
    }

    #[test]
    #[serial_test::serial(source_date_epoch)]
    fn current_iso_timestamp_honours_source_date_epoch() {
        // determinism.yml gate: SOURCE_DATE_EPOCH must pin this SBOM's
        // timestamp too — crate::sbom::SbomPlugin runs after (and
        // overwrites the output of) postprocess::SbomPlugin, so this
        // is the timestamp that actually survives into sbom.cdx.json.
        let prev = std::env::var("SOURCE_DATE_EPOCH").ok();
        std::env::set_var("SOURCE_DATE_EPOCH", "1700000000");
        let pinned = current_iso_timestamp();
        std::env::set_var("SOURCE_DATE_EPOCH", "not-a-number");
        let fallback = current_iso_timestamp();
        match prev {
            Some(v) => std::env::set_var("SOURCE_DATE_EPOCH", v),
            None => std::env::remove_var("SOURCE_DATE_EPOCH"),
        }
        assert_eq!(pinned, "2023-11-14T22:13:20Z");
        // Unparseable epoch falls back to wall clock — assert only the
        // shape so the test never depends on today's date.
        assert!(fallback.ends_with('Z') && fallback.len() == 20);
    }

    #[test]
    fn build_sbom_includes_required_cyclonedx_fields() {
        let sbom = build_sbom();
        assert_eq!(sbom["bomFormat"], "CycloneDX");
        assert_eq!(sbom["specVersion"], "1.5");
        assert_eq!(sbom["version"], 1);
        assert!(sbom["metadata"]["timestamp"].as_str().is_some());
        assert!(sbom["metadata"]["tools"].as_array().is_some());
        let components = sbom["components"].as_array().unwrap();
        assert!(!components.is_empty());
        // Every component must have a name and a purl.
        for c in components {
            assert!(c["name"].as_str().is_some());
            assert!(c["purl"].as_str().is_some());
        }
    }

    #[test]
    #[serial_test::parallel]
    fn sbom_plugin_writes_file_after_compile() {
        let dir = tempdir().unwrap();
        let site = dir.path().join("site");
        fs::create_dir_all(&site).unwrap();
        let ctx = PluginContext::new(dir.path(), dir.path(), &site, dir.path());
        SbomPlugin.after_compile(&ctx).unwrap();
        let sbom_file = site.join(SbomPlugin::sbom_path());
        assert!(sbom_file.exists());
        let body = fs::read_to_string(&sbom_file).unwrap();
        assert!(body.contains("\"CycloneDX\""));
        assert!(body.contains("\"specVersion\": \"1.5\""));
    }

    #[test]
    fn sbom_plugin_injects_link_into_head() {
        let dir = tempdir().unwrap();
        let ctx =
            PluginContext::new(dir.path(), dir.path(), dir.path(), dir.path());
        let html = "<html><head><title>x</title></head><body></body></html>";
        let out = SbomPlugin
            .transform_html(html, Path::new("x.html"), &ctx)
            .unwrap();
        assert!(out.contains("rel=\"sbom\""));
        assert!(out.contains("application/vnd.cyclonedx+json"));
        assert!(out.contains("href=\"/sbom.cdx.json\""));
    }

    #[test]
    fn sbom_plugin_is_idempotent() {
        let dir = tempdir().unwrap();
        let ctx =
            PluginContext::new(dir.path(), dir.path(), dir.path(), dir.path());
        let html = r#"<html><head><link rel="sbom" type="application/vnd.cyclonedx+json" href="/sbom.cdx.json"></head><body></body></html>"#;
        let out = SbomPlugin
            .transform_html(html, Path::new("x.html"), &ctx)
            .unwrap();
        assert_eq!(out, html);
    }

    #[test]
    fn sbom_plugin_is_idempotent_with_single_quoted_attribute() {
        // Covers the `rel='sbom'` disjunct of the idempotency check —
        // every other test only exercises the double-quoted form.
        let dir = tempdir().unwrap();
        let ctx =
            PluginContext::new(dir.path(), dir.path(), dir.path(), dir.path());
        let html = r"<html><head><link rel='sbom' type='application/vnd.cyclonedx+json' href='/sbom.cdx.json'></head><body></body></html>";
        let out = SbomPlugin
            .transform_html(html, Path::new("x.html"), &ctx)
            .unwrap();
        assert_eq!(out, html);
    }

    #[test]
    fn sbom_plugin_skips_pages_without_head_tag() {
        let dir = tempdir().unwrap();
        let ctx =
            PluginContext::new(dir.path(), dir.path(), dir.path(), dir.path());
        let html = "<p>orphan content with no head</p>";
        let out = SbomPlugin
            .transform_html(html, Path::new("x.html"), &ctx)
            .unwrap();
        assert_eq!(out, html);
    }

    #[test]
    #[serial_test::parallel]
    fn sbom_plugin_after_compile_noop_when_site_missing() {
        let dir = tempdir().unwrap();
        let missing = dir.path().join("missing");
        let ctx =
            PluginContext::new(dir.path(), dir.path(), &missing, dir.path());
        SbomPlugin.after_compile(&ctx).unwrap();
        assert!(!missing.exists());
    }

    #[test]
    fn sbom_path_constant() {
        assert_eq!(SbomPlugin::sbom_path(), "sbom.cdx.json");
    }

    #[test]
    #[serial_test::parallel]
    fn after_compile_write_failure_returns_io_error() {
        let dir = tempdir().unwrap();
        let site = dir.path().join("site");
        fs::create_dir_all(&site).unwrap();

        // Create a directory where the SBOM is expected to be written, causing fs::write to fail.
        let sbom_dir = site.join(SbomPlugin::sbom_path());
        fs::create_dir(&sbom_dir).unwrap();

        let ctx = PluginContext::new(dir.path(), dir.path(), &site, dir.path());
        let res = SbomPlugin.after_compile(&ctx);
        assert!(res.is_err());
        let err = res.unwrap_err();
        assert!(
            matches!(err, SsgError::Io { ref path, .. } if path == &sbom_dir)
        );
    }
}

#[cfg(all(test, feature = "test-fault-injection"))]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod fault_tests {
    use super::*;
    use crate::plugin::PluginContext;
    use serial_test::serial;
    use tempfile::tempdir;

    /// RAII guard that disables a failpoint on drop.
    struct FailGuard(&'static str);

    impl Drop for FailGuard {
        fn drop(&mut self) {
            let _ = fail::cfg(self.0, "off");
        }
    }

    #[test]
    #[serial]
    fn after_compile_maps_serialize_failure_to_io_error() {
        // `serde_json::to_string_pretty` on the hardcoded `build_sbom()`
        // literal cannot fail in practice, so the only way to exercise
        // `after_compile`'s serialize-error branch is fault injection.
        let _guard = FailGuard("sbom::serialize");
        fail::cfg("sbom::serialize", "return").expect("activate failpoint");

        let dir = tempdir().unwrap();
        let site = dir.path().join("site");
        fs::create_dir_all(&site).unwrap();
        let ctx = PluginContext::new(dir.path(), dir.path(), &site, dir.path());

        let err = SbomPlugin
            .after_compile(&ctx)
            .expect_err("injected serialize failure must propagate");
        let msg = format!("{err}");
        assert!(msg.contains("sbom.cdx.json"), "got: {msg}");
        assert!(msg.contains("injected: sbom::serialize"), "got: {msg}");
    }
}