diff --git a/Cargo.lock b/Cargo.lock index 472ca09..72758bf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -427,6 +427,16 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "filetime" +version = "0.2.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1255e7a9f1902190d4c10a75f2f7f495d3d3ce13e9ba26e6c48683a0f4dbed7" +dependencies = [ + "cfg-if", + "libc", +] + [[package]] name = "find-msvc-tools" version = "0.1.10" @@ -445,6 +455,7 @@ version = "1.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" dependencies = [ + "crc32fast", "miniz_oxide", "zlib-rs", ] @@ -1738,6 +1749,7 @@ dependencies = [ "builderlab-auth", "clap", "clap_complete", + "flate2", "pbjson", "pbjson-build", "pbjson-types", @@ -1749,6 +1761,7 @@ dependencies = [ "serde_json", "serde_yaml", "sha2", + "tar", "tempfile", "tiny_http", "tonic", @@ -1819,6 +1832,16 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", +] + [[package]] name = "tempfile" version = "3.27.0" diff --git a/Cargo.toml b/Cargo.toml index c7c2323..bba0ed5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,6 +23,7 @@ anyhow = "1" builderlab-auth = { path = "crates/builderlab-auth", features = ["blocking-client"] } clap = { version = "4.5", features = ["env"] } clap_complete = "4.5" +flate2 = "1" pbjson = "0.9" pbjson-types = "0.9" prost = "0.14" @@ -32,6 +33,8 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" serde_yaml = "0.9" sha2 = "0.10" +tar = { version = "0.4", default-features = false } +tempfile = "3" tiny_http = "0.12" tonic = { version = "0.14", features = ["transport"] } tonic-prost = "0.14" @@ -43,6 +46,3 @@ zip = { version = "4", default-features = false, features = ["deflate"] } pbjson-build = "0.9" protoc-bin-vendored = "3" tonic-prost-build = "0.14" - -[dev-dependencies] -tempfile = "3" diff --git a/README.md b/README.md index 912e856..875c9f2 100644 --- a/README.md +++ b/README.md @@ -73,6 +73,33 @@ Use `--json` for machine-readable output and `--verbose` for request diagnostics. Do not include credentials or other sensitive data when sharing verbose output. +## Static sites + +To publish a built static site or single-page app, create a static app once, +then deploy the build output directory: + +```bash +bl apps create --app-id docs-site --runtime-profile static --json +bl apps deploy docs-site --dir dist --json +``` + +`--dir` takes the folder your build writes, with `index.html` at its root. The +CLI writes the static manifest, packages the files under `public/`, and uploads +the result, so no manifest or tarball is needed. It skips `.DS_Store`, `._*` +AppleDouble files, `__MACOSX/` and `.git`, plus `.env*`/`.envrc` files and +`node_modules/` so `--dir .` doesn't publish secrets or dependencies, and +refuses other symlinks. The same +directory always produces the same archive. + +Unknown paths return 404. For client-side routing, pass `--spa` to serve +`index.html` for unknown paths instead. Current platform static runtimes also +serve `/about` from `about.html` and answer a 404 with the site's root +`404.html` when present. + +The JSON response adds `packaged_site` with the file count, byte sizes and +skipped paths. To deploy a prebuilt `artifact.tar.gz` instead, pass its path in +place of `--dir`. + ## Managed MySQL apps When the selected Apps Platform contract and server support managed MySQL, diff --git a/src/bl/apps.rs b/src/bl/apps.rs index c832825..ab0305d 100644 --- a/src/bl/apps.rs +++ b/src/bl/apps.rs @@ -36,6 +36,7 @@ use super::runner; use super::skills_api::failure_info; use super::skills_api::{exit_codes, failure, failure_trace_id, with_failure_trace_id, CliFailure}; use super::skills_config::{kgoose_service_url, SkillsConfig}; +use super::static_site::{package_static_dir, NotFoundHandling}; const APPS_BASE_URL_ENV_VAR: &str = "BL_APPS_CONTROL_PLANE_URL"; // Set to `enabled` by Blox workstations whose proxy asks Kgoose for a @@ -216,11 +217,26 @@ pub fn command() -> Command { )) .subcommand(control_plane_args( Command::new("deploy") - .about("Deploy a prebuilt app artifact") + .about("Deploy a prebuilt app artifact or a built static site directory") .long_about( - "Upload a prebuilt Hot Pod artifact.tar.gz to Apps Platform. The response \ + "Upload a prebuilt Hot Pod artifact.tar.gz to Apps Platform, or pass --dir \ + with a built static site (a folder with index.html at its root, such as \ + dist/) and the CLI packages it as a static artifact first. A --dir deploy needs \ + an app created with `bl apps create --runtime-profile static`. \ + Unknown paths return 404 with the site's root 404.html when present; pass \ + --spa to serve index.html instead for client-side routing. The response \ includes the deployed URL and control-plane readiness and diagnostics endpoints.", ) + // A required group would otherwise print before APP_ID, but + // parsing expects APP_ID first. + .override_usage( + "bl apps deploy [OPTIONS] --base-url >", + ) + .group( + ArgGroup::new("deploy-source") + .args(["artifact", "dir"]) + .required(true), + ) .arg( Arg::new("app-id") .value_name("APP_ID") @@ -230,10 +246,23 @@ pub fn command() -> Command { .arg( Arg::new("artifact") .value_name("ARTIFACT_TAR_GZ") - .required(true) .value_parser(clap::value_parser!(PathBuf)) .help("Path to the prebuilt artifact.tar.gz"), ) + .arg( + Arg::new("dir") + .long("dir") + .value_name("DIR") + .value_parser(clap::value_parser!(PathBuf)) + .help("Built static site directory to package and deploy (index.html at its root)"), + ) + .arg( + Arg::new("spa") + .long("spa") + .conflicts_with("artifact") + .action(clap::ArgAction::SetTrue) + .help("With --dir, serve index.html for unknown paths (single-page app routing)"), + ) .arg( Arg::new("environment") .long("environment") @@ -1565,20 +1594,42 @@ fn require_exact_app_id(stage: &str, expected: &str, actual: &str) -> Result<()> } fn run_deploy(config: &SkillsConfig, matches: &ArgMatches) -> Result<()> { - let artifact = matches - .get_one::("artifact") - .context("expected artifact.tar.gz path")?; - validate_artifact_path(artifact)?; let app_id = matches .get_one::("app-id") .context("expected app id")?; + // The packaged site lives in a temporary file that is removed on drop. + let packaged = match matches.get_one::("dir") { + Some(dir) => { + let not_found_handling = if matches.get_flag("spa") { + NotFoundHandling::Spa + } else { + NotFoundHandling::NotFound + }; + let site = package_static_dir(dir, app_id, not_found_handling)?; + Some((dir, site)) + } + None => None, + }; + let artifact = match packaged.as_ref() { + Some((_, site)) => site.path(), + None => { + let artifact = matches + .get_one::("artifact") + .context("expected artifact.tar.gz path or --dir")?; + validate_artifact_path(artifact)?; + artifact.as_path() + } + }; let options = DeployOptions { environment: matches.get_one::("environment").cloned(), version_id: matches.get_one::("version-id").cloned(), deployment_id: matches.get_one::("deployment-id").cloned(), }; let (client, credential) = control_plane_context(config, matches)?; - let response = client.deploy(&credential, app_id, artifact, &options)?; + let mut response = client.deploy(&credential, app_id, artifact, &options)?; + if let (Some((dir, site)), Some(object)) = (packaged.as_ref(), response.as_object_mut()) { + object.insert("packaged_site".to_string(), site.summary(dir)); + } print_json(&response) } @@ -7393,6 +7444,187 @@ mod tests { } } + #[test] + fn bl_apps_deploy_dir_packages_static_site_and_uploads_it() { + let credential = "apps-e2e-only.deploy-dir.session+credential"; + let deployed = json!({ + "ok": true, + "app_id": "docs-site", + "version_id": "ver-123", + "status": "pending_validation" + }); + let auth_server = ProcessServer::start(vec![process_auth_response()]); + let control_plane = ProcessServer::start(vec![ProcessResponse::json(deployed.clone())]); + let site = tempfile::tempdir().expect("create static site directory"); + fs::write(site.path().join("index.html"), "deploy-dir-index-marker").unwrap(); + fs::write(site.path().join("._index.html"), "appledouble").unwrap(); + let site_text = site.path().to_str().expect("site path UTF-8"); + let output = process_command( + &auth_server, + &control_plane, + &[ + "apps", + "deploy", + "docs-site", + "--dir", + site_text, + "--spa", + "--base-url", + APPROVED_TEST_BASE_URL, + "--json", + ], + credential, + ) + .output() + .expect("run Apps deploy --dir process command"); + assert!(output.status.success()); + + let printed: Value = serde_json::from_str(&process_stdout(&output)) + .expect("parse deploy --dir process output"); + assert_eq!(printed["version_id"], "ver-123"); + assert_eq!( + printed["packaged_site"], + json!({ + "source_dir": site_text, + "runtime_profile": "static", + "not_found_handling": "spa", + "files": 1, + "content_bytes": 23, + "archive_bytes": printed["packaged_site"]["archive_bytes"], + "skipped": ["._index.html"], + }) + ); + + let auth_requests = auth_server.finish(); + let requests = control_plane.finish(); + assert_process_auth(&auth_requests[0], credential); + assert_eq!(requests.len(), 1); + assert_process_control_plane( + &requests[0], + "POST", + "/v1/agent/apps/docs-site/deploy", + credential, + ); + let body = &requests[0].body_bytes; + assert!(String::from_utf8_lossy(body).contains("filename=\"artifact.tar.gz\"")); + let gzip_start = body + .windows(2) + .position(|bytes| bytes == [0x1f, 0x8b]) + .expect("multipart carries a gzip artifact"); + let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(&body[gzip_start..])); + let mut entries = BTreeMap::new(); + for entry in archive.entries().expect("read uploaded artifact") { + let mut entry = entry.expect("read uploaded artifact entry"); + let name = entry.path().unwrap().to_string_lossy().into_owned(); + let mut contents = String::new(); + entry.read_to_string(&mut contents).unwrap(); + entries.insert(name, contents); + } + assert_eq!( + entries.keys().map(String::as_str).collect::>(), + vec!["hotpod.manifest.json", "public/", "public/index.html"] + ); + assert_eq!(entries["public/index.html"], "deploy-dir-index-marker"); + let manifest: Value = serde_json::from_str(&entries["hotpod.manifest.json"]).unwrap(); + assert_eq!(manifest["app"]["app_id"], "docs-site"); + assert_eq!(manifest["runtime"]["profile"], "static"); + assert_eq!(manifest["runtime"]["not_found_handling"], "spa"); + } + + #[test] + fn bl_apps_deploy_dir_rejects_a_site_without_index_before_auth_or_network() { + let credential = "apps-e2e-only.deploy-dir-invalid.session+credential"; + let auth_server = ProcessServer::start(vec![]); + let control_plane = ProcessServer::start(vec![]); + let project = tempfile::tempdir().expect("create project directory"); + fs::create_dir(project.path().join("dist")).unwrap(); + fs::write(project.path().join("dist/index.html"), "built").unwrap(); + let output = process_command( + &auth_server, + &control_plane, + &[ + "apps", + "deploy", + "docs-site", + "--dir", + project.path().to_str().unwrap(), + "--base-url", + APPROVED_TEST_BASE_URL, + "--json", + ], + credential, + ) + .output() + .expect("run Apps deploy --dir process command"); + assert!(!output.status.success()); + let combined = format!( + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + assert!(combined.contains("no index.html at its root"), "{combined}"); + assert!(auth_server.finish().is_empty()); + assert!(control_plane.finish().is_empty()); + } + + #[test] + fn bl_apps_deploy_usage_puts_app_id_before_the_source() { + let mut apps = command(); + let deploy = apps + .find_subcommand_mut("deploy") + .expect("deploy subcommand"); + let usage = deploy.render_usage().to_string(); + let app_id = usage.find("").expect("usage names APP_ID"); + let source = usage + .find(">") + .expect("usage names the deploy source"); + assert!(app_id < source, "{usage}"); + } + + #[test] + fn bl_apps_deploy_takes_exactly_one_source() { + let error = command() + .try_get_matches_from([ + "apps", + "deploy", + "docs-site", + "--base-url", + APPROVED_TEST_BASE_URL, + ]) + .expect_err("deploy without a source must fail"); + assert_eq!( + error.kind(), + clap::error::ErrorKind::MissingRequiredArgument + ); + + let error = command() + .try_get_matches_from([ + "apps", + "deploy", + "docs-site", + "artifact.tar.gz", + "--dir", + "dist", + "--base-url", + APPROVED_TEST_BASE_URL, + ]) + .expect_err("deploy with both sources must fail"); + assert_eq!(error.kind(), clap::error::ErrorKind::ArgumentConflict); + + let error = command() + .try_get_matches_from([ + "apps", + "deploy", + "docs-site", + "artifact.tar.gz", + "--spa", + "--base-url", + APPROVED_TEST_BASE_URL, + ]) + .expect_err("--spa with a prebuilt artifact must fail"); + assert_eq!(error.kind(), clap::error::ErrorKind::ArgumentConflict); + } + #[test] fn bl_apps_rollback_process_sends_target_and_preserves_readiness() { let credential = "apps-e2e-only.rollback.session+credential"; diff --git a/src/bl/mod.rs b/src/bl/mod.rs index 81bde69..3114220 100644 --- a/src/bl/mod.rs +++ b/src/bl/mod.rs @@ -19,4 +19,5 @@ pub mod skills_install; pub mod skills_models; pub mod skills_slug; pub mod skills_targets; +pub mod static_site; pub mod workspace; diff --git a/src/bl/static_site.rs b/src/bl/static_site.rs new file mode 100644 index 0000000..37bbcca --- /dev/null +++ b/src/bl/static_site.rs @@ -0,0 +1,593 @@ +//! Package a built static site directory as a Hot Pod static artifact. +//! +//! `bl apps deploy --dir` uses this so a caller can publish a plain build +//! output folder (for example `dist/`) without writing a manifest or tarball. +//! The archive is deterministic: the same directory always produces the same +//! bytes, so a repeated deploy uploads an identical bundle. + +use std::fs; +use std::io::Write; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result}; +use flate2::write::GzEncoder; +use flate2::{Compression, GzBuilder}; +use serde_json::json; + +pub const MANIFEST_NAME: &str = "hotpod.manifest.json"; +const SITE_ROOT: &str = "public"; +const INDEX_NAME: &str = "index.html"; +// These match the Compose artifact validator's limits. +const MAX_ENTRIES: usize = 100_000; +const MAX_TOTAL_BYTES: u64 = 2 << 30; +// Fixed metadata keeps the archive byte-for-byte reproducible. +const ENTRY_MTIME: u64 = 0; +const FILE_MODE: u32 = 0o644; +const DIR_MODE: u32 = 0o755; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NotFoundHandling { + /// Unknown paths return 404, with the site's root `404.html` when present. + NotFound, + /// Unknown paths serve the root `index.html` for client-side routing. + Spa, +} + +impl NotFoundHandling { + fn manifest_value(self) -> &'static str { + match self { + NotFoundHandling::NotFound => "404", + NotFoundHandling::Spa => "spa", + } + } +} + +#[derive(Debug)] +pub struct PackagedSite { + pub archive: tempfile::NamedTempFile, + pub files: usize, + pub content_bytes: u64, + pub archive_bytes: u64, + pub skipped: Vec, + pub not_found_handling: NotFoundHandling, +} + +impl PackagedSite { + pub fn path(&self) -> &Path { + self.archive.path() + } + + pub fn summary(&self, source: &Path) -> serde_json::Value { + json!({ + "source_dir": source.display().to_string(), + "runtime_profile": "static", + "not_found_handling": self.not_found_handling.manifest_value(), + "files": self.files, + "content_bytes": self.content_bytes, + "archive_bytes": self.archive_bytes, + "skipped": self.skipped, + }) + } +} + +struct SiteEntry { + relative: String, + source: PathBuf, + is_dir: bool, + size: u64, +} + +/// Build a static artifact for `app_id` from the files in `dir`. +pub fn package_static_dir( + dir: &Path, + app_id: &str, + not_found_handling: NotFoundHandling, +) -> Result { + let metadata = fs::metadata(dir) + .with_context(|| format!("read static site directory {}", dir.display()))?; + if !metadata.is_dir() { + anyhow::bail!( + "--dir must be a directory containing the built site: {}", + dir.display() + ); + } + if fs::symlink_metadata(dir.join(MANIFEST_NAME)).is_ok() { + anyhow::bail!( + "{} contains {MANIFEST_NAME}, so it is already a Hot Pod artifact directory. \ + Pass --dir the built site files themselves (for example dist/), or package this \ + directory as artifact.tar.gz and pass that path instead.", + dir.display() + ); + } + let index = fs::symlink_metadata(dir.join(INDEX_NAME)); + if !index.as_ref().is_ok_and(|metadata| metadata.is_file()) { + anyhow::bail!( + "{} has no {INDEX_NAME} at its root. Pass the directory your build writes the site \ + to (for example dist/ or build/), not the project directory.", + dir.display() + ); + } + + let mut entries = Vec::new(); + let mut skipped = Vec::new(); + collect_entries(dir, "", &mut entries, &mut skipped)?; + let files = entries.iter().filter(|entry| !entry.is_dir).count(); + let content_bytes: u64 = entries.iter().map(|entry| entry.size).sum(); + let manifest = manifest_bytes(app_id, not_found_handling)?; + check_archive_limits(dir, entries.len(), content_bytes, manifest.len() as u64)?; + + let mut archive = tempfile::Builder::new() + .prefix("bl-static-site-") + .suffix(".tar.gz") + .tempfile() + .context("create temporary static site artifact")?; + write_archive(archive.as_file_mut(), &manifest, &entries)?; + archive + .as_file_mut() + .flush() + .context("flush static site artifact")?; + let archive_bytes = archive + .as_file() + .metadata() + .context("read static site artifact size")? + .len(); + Ok(PackagedSite { + archive, + files, + content_bytes, + archive_bytes, + skipped, + not_found_handling, + }) +} + +/// Mirrors the platform validator, which also counts the manifest and the +/// public/ directory entry, so a site at the limit fails here rather than +/// after upload. +fn check_archive_limits( + dir: &Path, + site_entries: usize, + content_bytes: u64, + manifest_bytes: u64, +) -> Result<()> { + let archive_entries = site_entries + 2; + if archive_entries > MAX_ENTRIES { + anyhow::bail!( + "{} has {site_entries} files and directories; with the manifest and {SITE_ROOT}/ \ + that is {archive_entries} archive entries, and Apps Platform accepts at most \ + {MAX_ENTRIES}", + dir.display() + ); + } + let archive_bytes = content_bytes + manifest_bytes; + if archive_bytes > MAX_TOTAL_BYTES { + anyhow::bail!( + "{} holds {content_bytes} bytes; with the manifest that is {archive_bytes} bytes, \ + and Apps Platform accepts at most {MAX_TOTAL_BYTES} bytes uncompressed", + dir.display() + ); + } + Ok(()) +} + +fn manifest_bytes(app_id: &str, not_found_handling: NotFoundHandling) -> Result> { + let manifest = json!({ + "schema": "hotpod.manifest.v1", + "app": { "app_id": app_id }, + "runtime": { + "profile": "static", + "root": SITE_ROOT, + "not_found_handling": not_found_handling.manifest_value(), + } + }); + let mut bytes = serde_json::to_vec_pretty(&manifest).context("serialize static manifest")?; + bytes.push(b'\n'); + Ok(bytes) +} + +/// Names a built site never serves, matched whatever the entry type: +/// - macOS metadata: `.DS_Store`, `._*` AppleDouble files, `__MACOSX/`; +/// - version control: `.git`, which is a file in worktrees and submodules; +/// - project files that `--dir .` would otherwise publish to every viewer: +/// `.env`, `.env.*` and `.envrc` secrets, and `node_modules/`. +fn is_skipped_name(name: &str) -> bool { + matches!(name, ".DS_Store" | "__MACOSX" | ".git" | "node_modules") + || name.starts_with("._") + || name.starts_with(".env") +} + +fn collect_entries( + dir: &Path, + prefix: &str, + entries: &mut Vec, + skipped: &mut Vec, +) -> Result<()> { + let mut children = fs::read_dir(dir) + .with_context(|| format!("list static site directory {}", dir.display()))? + .map(|child| child.map(|child| child.path())) + .collect::>>() + .with_context(|| format!("list static site directory {}", dir.display()))?; + children.sort(); + for source in children { + let name = source + .file_name() + .and_then(|name| name.to_str()) + .with_context(|| format!("static site path is not valid UTF-8: {}", source.display()))? + .to_string(); + let relative = if prefix.is_empty() { + name.clone() + } else { + format!("{prefix}/{name}") + }; + let metadata = fs::symlink_metadata(&source) + .with_context(|| format!("read static site path {}", source.display()))?; + let file_type = metadata.file_type(); + if is_skipped_name(&name) { + skipped.push(relative); + continue; + } + if file_type.is_symlink() { + anyhow::bail!( + "static site path {relative} is a symlink; Apps Platform artifacts can only \ + contain regular files. Copy the target into the build output instead." + ); + } + if file_type.is_dir() { + entries.push(SiteEntry { + relative: relative.clone(), + source: source.clone(), + is_dir: true, + size: 0, + }); + collect_entries(&source, &relative, entries, skipped)?; + } else if file_type.is_file() { + entries.push(SiteEntry { + relative, + source, + is_dir: false, + size: metadata.len(), + }); + } else { + anyhow::bail!("static site path {relative} is not a regular file or directory"); + } + } + Ok(()) +} + +fn write_archive(file: &mut fs::File, manifest: &[u8], entries: &[SiteEntry]) -> Result<()> { + // A zero gzip mtime and no file name keep the compressed bytes reproducible. + let encoder: GzEncoder<&mut fs::File> = GzBuilder::new() + .mtime(0) + .write(file, Compression::default()); + let mut builder = tar::Builder::new(encoder); + builder.mode(tar::HeaderMode::Deterministic); + + append_bytes(&mut builder, MANIFEST_NAME, manifest)?; + append_dir(&mut builder, SITE_ROOT)?; + for entry in entries { + let name = format!("{SITE_ROOT}/{}", entry.relative); + if entry.is_dir { + append_dir(&mut builder, &name)?; + continue; + } + let source = fs::File::open(&entry.source) + .with_context(|| format!("open static site file {}", entry.source.display()))?; + // Use the size observed during the walk; a file that changes while + // packaging fails here instead of producing a corrupt archive. + let mut header = file_header(entry.size); + let reader = ExactReader { + inner: std::io::Read::take(source, entry.size), + remaining: entry.size, + }; + builder + .append_data(&mut header, &name, reader) + .with_context(|| format!("add {name} to static site artifact"))?; + } + let encoder = builder + .into_inner() + .context("finish static site tar archive")?; + encoder.finish().context("finish static site gzip stream")?; + Ok(()) +} + +/// Fails instead of returning early EOF, so a file that shrinks while it is +/// being packaged can't leave a tar entry shorter than its header says. +struct ExactReader { + inner: R, + remaining: u64, +} + +impl std::io::Read for ExactReader { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let read = self.inner.read(buf)?; + if read == 0 && self.remaining > 0 && !buf.is_empty() { + return Err(std::io::Error::new( + std::io::ErrorKind::UnexpectedEof, + "static site file changed size while packaging; rebuild and retry", + )); + } + self.remaining -= read as u64; + Ok(read) + } +} + +fn file_header(size: u64) -> tar::Header { + let mut header = tar::Header::new_ustar(); + header.set_entry_type(tar::EntryType::Regular); + header.set_size(size); + header.set_mode(FILE_MODE); + header.set_mtime(ENTRY_MTIME); + header.set_uid(0); + header.set_gid(0); + header +} + +fn append_bytes(builder: &mut tar::Builder, name: &str, bytes: &[u8]) -> Result<()> { + let mut header = file_header(bytes.len() as u64); + builder + .append_data(&mut header, name, bytes) + .with_context(|| format!("add {name} to static site artifact")) +} + +fn append_dir(builder: &mut tar::Builder, name: &str) -> Result<()> { + let mut header = tar::Header::new_ustar(); + header.set_entry_type(tar::EntryType::Directory); + header.set_size(0); + header.set_mode(DIR_MODE); + header.set_mtime(ENTRY_MTIME); + header.set_uid(0); + header.set_gid(0); + builder + .append_data(&mut header, format!("{name}/"), std::io::empty()) + .with_context(|| format!("add {name}/ to static site artifact")) +} + +#[cfg(test)] +mod tests { + use super::*; + use flate2::read::GzDecoder; + use std::collections::BTreeMap; + use std::io::Read; + + fn write(root: &Path, relative: &str, contents: &str) { + let path = root.join(relative); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, contents).unwrap(); + } + + fn site() -> tempfile::TempDir { + let dir = tempfile::tempdir().unwrap(); + write(dir.path(), "index.html", "

home

"); + write(dir.path(), "about.html", "

about

"); + write(dir.path(), "404.html", "

missing

"); + write(dir.path(), "assets/app.js", "console.log(1)"); + write(dir.path(), ".well-known/security.txt", "Contact: x"); + dir + } + + struct Entry { + kind: tar::EntryType, + mode: u32, + mtime: u64, + body: String, + } + + fn read_archive(path: &Path) -> BTreeMap { + let file = fs::File::open(path).unwrap(); + let mut archive = tar::Archive::new(GzDecoder::new(file)); + let mut entries = BTreeMap::new(); + for entry in archive.entries().unwrap() { + let mut entry = entry.unwrap(); + let name = entry.path().unwrap().to_string_lossy().into_owned(); + let header = entry.header().clone(); + let mut body = String::new(); + entry.read_to_string(&mut body).unwrap(); + entries.insert( + name, + Entry { + kind: header.entry_type(), + mode: header.mode().unwrap(), + mtime: header.mtime().unwrap(), + body, + }, + ); + } + entries + } + + #[test] + fn packages_site_under_public_with_static_manifest() { + let dir = site(); + let packaged = + package_static_dir(dir.path(), "docs-site", NotFoundHandling::NotFound).unwrap(); + let entries = read_archive(packaged.path()); + + let manifest: serde_json::Value = + serde_json::from_str(&entries[MANIFEST_NAME].body).unwrap(); + assert_eq!( + manifest, + json!({ + "schema": "hotpod.manifest.v1", + "app": {"app_id": "docs-site"}, + "runtime": {"profile": "static", "root": "public", "not_found_handling": "404"} + }) + ); + assert_eq!(entries["public/index.html"].body, "

home

"); + assert_eq!(entries["public/assets/app.js"].body, "console.log(1)"); + assert_eq!( + entries["public/.well-known/security.txt"].body, + "Contact: x" + ); + assert_eq!(entries["public/assets/"].kind, tar::EntryType::Directory); + assert_eq!(entries["public/assets/"].mode, DIR_MODE); + assert_eq!(entries["public/about.html"].mode, FILE_MODE); + assert!(entries.values().all(|entry| entry.mtime == ENTRY_MTIME)); + assert_eq!(packaged.files, 5); + assert_eq!(packaged.content_bytes, 13 + 14 + 16 + 14 + 10); + assert!(packaged.archive_bytes > 0); + } + + #[test] + fn spa_sets_not_found_handling() { + let dir = site(); + let packaged = package_static_dir(dir.path(), "spa-site", NotFoundHandling::Spa).unwrap(); + let entries = read_archive(packaged.path()); + let manifest: serde_json::Value = + serde_json::from_str(&entries[MANIFEST_NAME].body).unwrap(); + assert_eq!(manifest["runtime"]["not_found_handling"], "spa"); + assert_eq!(packaged.summary(dir.path())["not_found_handling"], "spa"); + } + + #[test] + fn same_directory_produces_identical_archives() { + let dir = site(); + let first = + package_static_dir(dir.path(), "docs-site", NotFoundHandling::NotFound).unwrap(); + let second = + package_static_dir(dir.path(), "docs-site", NotFoundHandling::NotFound).unwrap(); + assert_eq!( + fs::read(first.path()).unwrap(), + fs::read(second.path()).unwrap() + ); + } + + #[test] + fn skips_macos_metadata_and_git() { + let dir = site(); + write(dir.path(), ".DS_Store", "x"); + write(dir.path(), "._index.html", "x"); + write(dir.path(), "assets/._app.js", "x"); + write(dir.path(), ".git/HEAD", "ref"); + write(dir.path(), "__MACOSX/._index.html", "x"); + // In a worktree or submodule, .git is a file rather than a directory. + write(dir.path(), "vendor/.git", "gitdir: ../.git/modules/vendor"); + write(dir.path(), "vendor/lib.js", "lib"); + let packaged = + package_static_dir(dir.path(), "docs-site", NotFoundHandling::NotFound).unwrap(); + let entries = read_archive(packaged.path()); + assert!(entries.contains_key("public/vendor/lib.js")); + assert_eq!( + packaged.skipped, + vec![ + ".DS_Store", + "._index.html", + ".git", + "__MACOSX", + "assets/._app.js", + "vendor/.git", + ] + ); + for skipped in &packaged.skipped { + let prefix = format!("public/{skipped}"); + assert!( + entries.keys().all(|name| !name.starts_with(&prefix)), + "{skipped} was packaged" + ); + } + } + + #[test] + fn skips_secrets_and_dependencies_when_given_a_project_directory() { + let dir = site(); + write(dir.path(), ".env", "TOKEN=secret"); + write(dir.path(), ".env.local", "TOKEN=secret"); + write(dir.path(), ".envrc", "export TOKEN=secret"); + write( + dir.path(), + "node_modules/left-pad/index.js", + "module.exports = 1", + ); + write(dir.path(), "assets/node_modules/x.js", "x"); + let packaged = + package_static_dir(dir.path(), "docs-site", NotFoundHandling::NotFound).unwrap(); + let entries = read_archive(packaged.path()); + assert!(entries + .keys() + .all(|name| !name.contains(".env") && !name.contains("node_modules"))); + assert_eq!( + packaged.skipped, + vec![ + ".env", + ".env.local", + ".envrc", + "assets/node_modules", + "node_modules", + ] + ); + assert_eq!(packaged.files, 5); + } + + #[cfg(unix)] + #[test] + fn skips_symlinked_dependencies_instead_of_failing() { + let dir = site(); + let store = tempfile::tempdir().unwrap(); + std::os::unix::fs::symlink(store.path(), dir.path().join("node_modules")).unwrap(); + let packaged = + package_static_dir(dir.path(), "docs-site", NotFoundHandling::NotFound).unwrap(); + assert_eq!(packaged.skipped, vec!["node_modules"]); + } + + #[test] + fn limits_count_the_manifest_and_public_entries() { + let dir = Path::new("dist"); + check_archive_limits(dir, MAX_ENTRIES - 2, 0, 200).unwrap(); + let error = check_archive_limits(dir, MAX_ENTRIES - 1, 0, 200) + .unwrap_err() + .to_string(); + assert!(error.contains("100001 archive entries"), "{error}"); + + check_archive_limits(dir, 10, MAX_TOTAL_BYTES - 200, 200).unwrap(); + let error = check_archive_limits(dir, 10, MAX_TOTAL_BYTES - 199, 200) + .unwrap_err() + .to_string(); + assert!(error.contains("accepts at most"), "{error}"); + } + + #[test] + fn requires_root_index_html() { + let dir = tempfile::tempdir().unwrap(); + write(dir.path(), "dist/index.html", "x"); + let error = package_static_dir(dir.path(), "docs-site", NotFoundHandling::NotFound) + .unwrap_err() + .to_string(); + assert!(error.contains("no index.html at its root"), "{error}"); + } + + #[test] + fn rejects_an_artifact_directory() { + let dir = site(); + write(dir.path(), MANIFEST_NAME, "{}"); + let error = package_static_dir(dir.path(), "docs-site", NotFoundHandling::NotFound) + .unwrap_err() + .to_string(); + assert!( + error.contains("already a Hot Pod artifact directory"), + "{error}" + ); + } + + #[test] + fn rejects_a_file_path() { + let dir = site(); + let error = package_static_dir( + &dir.path().join("index.html"), + "docs-site", + NotFoundHandling::NotFound, + ) + .unwrap_err() + .to_string(); + assert!(error.contains("must be a directory"), "{error}"); + } + + #[cfg(unix)] + #[test] + fn rejects_symlinks() { + let dir = site(); + std::os::unix::fs::symlink("index.html", dir.path().join("home.html")).unwrap(); + let error = package_static_dir(dir.path(), "docs-site", NotFoundHandling::NotFound) + .unwrap_err() + .to_string(); + assert!(error.contains("home.html is a symlink"), "{error}"); + } +}