1#![forbid(unsafe_code)]
3
4use async_trait::async_trait;
5use minco_core::{
6 CapabilityProvision, ConfigurationField, ConfigurationValueKind, IdleCostClass, Plugin,
7 PluginContext, PluginDescriptor, PluginError, PluginId, PluginStability, ResourceIntent,
8 ResourceKind, WakeSource,
9};
10use semver::{Version, VersionReq};
11use serde::{Deserialize, Serialize};
12use sha2::{Digest, Sha256};
13use std::{
14 fs,
15 io::{BufReader, Read},
16 path::{Component, Path, PathBuf},
17 sync::{Arc, Mutex},
18};
19
20#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
21#[serde(rename_all = "snake_case")]
22pub enum CloudFrontPriceClass {
23 #[default]
24 PriceClass100,
25 PriceClass200,
26 PriceClassAll,
27}
28
29impl CloudFrontPriceClass {
30 #[must_use]
31 pub const fn as_aws_value(self) -> &'static str {
32 match self {
33 Self::PriceClass100 => "PriceClass_100",
34 Self::PriceClass200 => "PriceClass_200",
35 Self::PriceClassAll => "PriceClass_All",
36 }
37 }
38}
39
40#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
41#[serde(deny_unknown_fields)]
42pub struct StaticSiteConfig {
43 #[serde(default = "default_source_directory")]
44 pub source_directory: String,
45 #[serde(default = "default_index_document")]
46 pub index_document: String,
47 #[serde(default = "default_true")]
48 pub spa_fallback: bool,
49 #[serde(default = "default_immutable_cache_seconds")]
50 pub immutable_cache_seconds: u32,
51 #[serde(default)]
52 pub html_cache_seconds: u32,
53 #[serde(default)]
54 pub price_class: CloudFrontPriceClass,
55 #[serde(default = "default_true")]
56 pub ipv6_enabled: bool,
57 #[serde(default)]
58 pub custom_domain: Option<String>,
59 #[serde(default)]
60 pub manage_dns_alias: bool,
61}
62
63impl Default for StaticSiteConfig {
64 fn default() -> Self {
65 Self {
66 source_directory: default_source_directory(),
67 index_document: default_index_document(),
68 spa_fallback: true,
69 immutable_cache_seconds: default_immutable_cache_seconds(),
70 html_cache_seconds: 0,
71 price_class: CloudFrontPriceClass::PriceClass100,
72 ipv6_enabled: true,
73 custom_domain: None,
74 manage_dns_alias: false,
75 }
76 }
77}
78
79impl StaticSiteConfig {
80 pub fn validate(&self) -> Result<(), StaticSiteError> {
81 validate_relative_path("source_directory", &self.source_directory)?;
82 validate_relative_path("index_document", &self.index_document)?;
83 if self.immutable_cache_seconds > 31_536_000 || self.html_cache_seconds > 86_400 {
84 return Err(StaticSiteError::InvalidConfiguration(
85 "immutable cache must not exceed one year and HTML cache must not exceed one day"
86 .into(),
87 ));
88 }
89 if self.manage_dns_alias && self.custom_domain.is_none() {
90 return Err(StaticSiteError::InvalidConfiguration(
91 "manage_dns_alias requires custom_domain".into(),
92 ));
93 }
94 if let Some(domain) = self.custom_domain.as_deref() {
95 validate_domain(domain)?;
96 }
97 Ok(())
98 }
99}
100
101#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
102#[serde(deny_unknown_fields)]
103pub struct StaticSitePlan {
104 pub source_directory: String,
105 pub index_document: String,
106 pub spa_fallback: bool,
107 pub immutable_cache_seconds: u32,
108 pub html_cache_seconds: u32,
109 pub price_class: String,
110 pub ipv6_enabled: bool,
111 pub custom_domain: Option<String>,
112 pub manage_dns_alias: bool,
113}
114
115impl From<StaticSiteConfig> for StaticSitePlan {
116 fn from(value: StaticSiteConfig) -> Self {
117 Self {
118 source_directory: value.source_directory,
119 index_document: value.index_document,
120 spa_fallback: value.spa_fallback,
121 immutable_cache_seconds: value.immutable_cache_seconds,
122 html_cache_seconds: value.html_cache_seconds,
123 price_class: value.price_class.as_aws_value().into(),
124 ipv6_enabled: value.ipv6_enabled,
125 custom_domain: value.custom_domain,
126 manage_dns_alias: value.manage_dns_alias,
127 }
128 }
129}
130
131#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
132#[serde(deny_unknown_fields)]
133pub struct StaticSitePublication {
134 pub url: String,
135 pub release_manifest_digest: String,
136 pub assets: Vec<StaticSiteAsset>,
137 pub uploaded: usize,
138 pub removed: usize,
139 #[serde(default, skip_serializing_if = "Option::is_none")]
140 pub invalidation_id: Option<String>,
141 pub invalidation_completed: bool,
142}
143
144#[async_trait]
145pub trait StaticSitePublisher: Send + Sync + std::fmt::Debug {
146 async fn publish_manifest(
147 &self,
148 manifest: &StaticSiteReleaseManifest,
149 repository_root: &Path,
150 ) -> Result<StaticSitePublication, StaticSiteError>;
151}
152
153#[derive(Clone)]
154pub struct StaticSitePublisherService(pub Arc<dyn StaticSitePublisher>);
155
156impl std::fmt::Debug for StaticSitePublisherService {
157 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
158 formatter.debug_tuple("StaticSitePublisherService").finish()
159 }
160}
161
162impl StaticSitePublisherService {
163 pub fn new(publisher: Arc<dyn StaticSitePublisher>) -> Self {
164 Self(publisher)
165 }
166
167 pub async fn publish(
168 &self,
169 plan: &StaticSitePlan,
170 repository_root: &Path,
171 ) -> Result<StaticSitePublication, StaticSiteError> {
172 let manifest = StaticSiteReleaseManifest::build(plan, repository_root)?;
173 self.publish_manifest(&manifest, repository_root).await
174 }
175
176 pub async fn publish_manifest(
177 &self,
178 manifest: &StaticSiteReleaseManifest,
179 repository_root: &Path,
180 ) -> Result<StaticSitePublication, StaticSiteError> {
181 manifest.verify_at(repository_root)?;
182 self.0.publish_manifest(manifest, repository_root).await
183 }
184}
185
186impl StaticSitePlan {
187 pub fn validate(&self) -> Result<(), StaticSiteError> {
188 self.clone().try_into_config()?.validate()
189 }
190
191 fn try_into_config(self) -> Result<StaticSiteConfig, StaticSiteError> {
192 let price_class = match self.price_class.as_str() {
193 "PriceClass_100" => CloudFrontPriceClass::PriceClass100,
194 "PriceClass_200" => CloudFrontPriceClass::PriceClass200,
195 "PriceClass_All" => CloudFrontPriceClass::PriceClassAll,
196 _ => {
197 return Err(StaticSiteError::InvalidConfiguration(
198 "price_class is not a supported CloudFront price class".into(),
199 ));
200 }
201 };
202 Ok(StaticSiteConfig {
203 source_directory: self.source_directory,
204 index_document: self.index_document,
205 spa_fallback: self.spa_fallback,
206 immutable_cache_seconds: self.immutable_cache_seconds,
207 html_cache_seconds: self.html_cache_seconds,
208 price_class,
209 ipv6_enabled: self.ipv6_enabled,
210 custom_domain: self.custom_domain,
211 manage_dns_alias: self.manage_dns_alias,
212 })
213 }
214}
215
216#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
217#[serde(deny_unknown_fields)]
218pub struct StaticSiteAsset {
219 pub path: String,
220 pub bytes: u64,
221 pub sha256: String,
222 pub content_type: String,
223 pub cache_control: String,
224}
225
226#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
227#[serde(deny_unknown_fields)]
228pub struct StaticSiteReleaseManifest {
229 pub schema_version: u32,
230 pub plan: StaticSitePlan,
231 pub assets: Vec<StaticSiteAsset>,
232}
233
234impl StaticSiteReleaseManifest {
235 pub fn build(plan: &StaticSitePlan, repository_root: &Path) -> Result<Self, StaticSiteError> {
236 plan.validate()?;
237 let repository_root = fs::canonicalize(repository_root)
238 .map_err(|error| manifest_error("repository root", &error))?;
239 let source = fs::canonicalize(repository_root.join(&plan.source_directory))
240 .map_err(|error| manifest_error("static-site source", &error))?;
241 if !source.starts_with(&repository_root) {
242 return Err(StaticSiteError::Publish(
243 "static-site source resolves outside the repository root".into(),
244 ));
245 }
246
247 let mut paths = Vec::new();
248 collect_release_files(&source, &source, &mut paths)?;
249 paths.sort_by(|left, right| left.0.cmp(&right.0));
250 if paths
251 .iter()
252 .any(|(relative, _)| relative == ".minco" || relative.starts_with(".minco/"))
253 {
254 return Err(StaticSiteError::Publish(
255 "static-site assets cannot use the reserved .minco provider-control prefix".into(),
256 ));
257 }
258 if !paths
259 .iter()
260 .any(|(relative, _)| relative == &plan.index_document)
261 {
262 return Err(StaticSiteError::Publish(format!(
263 "static-site index document {} is missing",
264 plan.index_document
265 )));
266 }
267
268 let assets = paths
269 .into_iter()
270 .map(|(relative, absolute)| release_asset(plan, relative, &absolute))
271 .collect::<Result<Vec<_>, _>>()?;
272 let manifest = Self {
273 schema_version: 1,
274 plan: plan.clone(),
275 assets,
276 };
277 manifest.validate_structure()?;
278 Ok(manifest)
279 }
280
281 pub fn verify_at(&self, repository_root: &Path) -> Result<(), StaticSiteError> {
282 self.validate_structure()?;
283 let actual = Self::build(&self.plan, repository_root)?;
284 if &actual == self {
285 return Ok(());
286 }
287 let changed = self
288 .assets
289 .iter()
290 .zip(&actual.assets)
291 .find_map(|(expected, actual)| (expected != actual).then(|| expected.path.clone()))
292 .or_else(|| {
293 self.assets
294 .get(actual.assets.len())
295 .or_else(|| actual.assets.get(self.assets.len()))
296 .map(|asset| asset.path.clone())
297 })
298 .unwrap_or_else(|| "manifest".into());
299 Err(StaticSiteError::Publish(format!(
300 "static-site release asset {changed} no longer matches the manifest"
301 )))
302 }
303
304 pub fn validate_structure(&self) -> Result<(), StaticSiteError> {
305 if self.schema_version != 1 {
306 return Err(StaticSiteError::Publish(format!(
307 "unsupported static-site release manifest schema {}",
308 self.schema_version
309 )));
310 }
311 self.plan.validate()?;
312 if self.assets.is_empty()
313 || self
314 .assets
315 .windows(2)
316 .any(|assets| assets[0].path >= assets[1].path)
317 || !self
318 .assets
319 .iter()
320 .any(|asset| asset.path == self.plan.index_document)
321 {
322 return Err(StaticSiteError::Publish(
323 "static-site release asset set is empty, unsorted, duplicated, or missing its index"
324 .into(),
325 ));
326 }
327 for asset in &self.assets {
328 validate_relative_path("static-site asset path", &asset.path)?;
329 if asset.path.len() > 1_024
330 || asset.path == ".minco"
331 || asset.path.starts_with(".minco/")
332 || asset.sha256.len() != 64
333 || !asset
334 .sha256
335 .bytes()
336 .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
337 || !safe_metadata_value(&asset.content_type, 255)
338 || !safe_metadata_value(&asset.cache_control, 1_024)
339 {
340 return Err(StaticSiteError::Publish(format!(
341 "static-site release asset {} has invalid path, digest, or metadata",
342 asset.path
343 )));
344 }
345 }
346 Ok(())
347 }
348
349 pub fn digest_sha256(&self) -> Result<String, StaticSiteError> {
350 self.validate_structure()?;
351 let encoded = serde_json::to_vec(self).map_err(|error| {
352 StaticSiteError::Publish(format!(
353 "static-site release manifest cannot be encoded: {error}"
354 ))
355 })?;
356 Ok(hex::encode(Sha256::digest(encoded)))
357 }
358}
359
360fn safe_metadata_value(value: &str, max_bytes: usize) -> bool {
361 !value.is_empty()
362 && value.len() <= max_bytes
363 && value.bytes().all(|byte| matches!(byte, b' '..=b'~'))
364}
365
366fn collect_release_files(
367 source: &Path,
368 directory: &Path,
369 output: &mut Vec<(String, PathBuf)>,
370) -> Result<(), StaticSiteError> {
371 let entries = fs::read_dir(directory)
372 .map_err(|error| manifest_error("static-site source directory", &error))?;
373 for entry in entries {
374 let entry = entry.map_err(|error| manifest_error("static-site directory entry", &error))?;
375 let path = entry.path();
376 let metadata = fs::symlink_metadata(&path)
377 .map_err(|error| manifest_error("static-site asset", &error))?;
378 if metadata.file_type().is_symlink() {
379 return Err(StaticSiteError::Publish(
380 "static-site source contains a symlink".into(),
381 ));
382 }
383 if metadata.is_dir() {
384 collect_release_files(source, &path, output)?;
385 continue;
386 }
387 if !metadata.is_file() {
388 return Err(StaticSiteError::Publish(
389 "static-site source contains a non-regular file".into(),
390 ));
391 }
392 let canonical =
393 fs::canonicalize(&path).map_err(|error| manifest_error("static-site asset", &error))?;
394 if !canonical.starts_with(source) {
395 return Err(StaticSiteError::Publish(
396 "static-site asset resolves outside the source directory".into(),
397 ));
398 }
399 let relative = canonical
400 .strip_prefix(source)
401 .map_err(|_| StaticSiteError::Publish("static-site asset prefix changed".into()))?;
402 output.push((slash_path(relative)?, canonical));
403 }
404 Ok(())
405}
406
407fn release_asset(
408 plan: &StaticSitePlan,
409 relative: String,
410 absolute: &Path,
411) -> Result<StaticSiteAsset, StaticSiteError> {
412 let file = fs::File::open(absolute).map_err(|error| manifest_error(&relative, &error))?;
413 let bytes = file
414 .metadata()
415 .map_err(|error| manifest_error(&relative, &error))?
416 .len();
417 let mut reader = BufReader::new(file);
418 let mut hasher = Sha256::new();
419 let mut buffer = vec![0_u8; 64 * 1024].into_boxed_slice();
420 loop {
421 let read = reader
422 .read(&mut buffer)
423 .map_err(|error| manifest_error(&relative, &error))?;
424 if read == 0 {
425 break;
426 }
427 hasher.update(&buffer[..read]);
428 }
429 Ok(StaticSiteAsset {
430 content_type: asset_content_type(&relative).into(),
431 cache_control: asset_cache_control(plan, &relative),
432 path: relative,
433 bytes,
434 sha256: hex::encode(hasher.finalize()),
435 })
436}
437
438fn asset_content_type(relative: &str) -> &'static str {
439 let extension = Path::new(relative)
440 .extension()
441 .and_then(|extension| extension.to_str())
442 .map(str::to_ascii_lowercase);
443 match extension.as_deref() {
444 Some("html" | "htm") => "text/html",
445 Some("css") => "text/css",
446 Some("js" | "mjs") => "text/javascript",
447 Some("json" | "map" | "webmanifest") => "application/json",
448 Some("txt") => "text/plain",
449 Some("csv") => "text/csv",
450 Some("xml") => "application/xml",
451 Some("svg") => "image/svg+xml",
452 Some("png") => "image/png",
453 Some("jpg" | "jpeg") => "image/jpeg",
454 Some("gif") => "image/gif",
455 Some("webp") => "image/webp",
456 Some("ico") => "image/x-icon",
457 Some("avif") => "image/avif",
458 Some("wasm") => "application/wasm",
459 Some("pdf") => "application/pdf",
460 Some("woff") => "font/woff",
461 Some("woff2") => "font/woff2",
462 Some("ttf") => "font/ttf",
463 Some("otf") => "font/otf",
464 Some("mp3") => "audio/mpeg",
465 Some("wav") => "audio/wav",
466 Some("mp4") => "video/mp4",
467 Some("webm") => "video/webm",
468 _ => "application/octet-stream",
469 }
470}
471
472fn slash_path(path: &Path) -> Result<String, StaticSiteError> {
473 let mut parts = Vec::new();
474 for component in path.components() {
475 match component {
476 Component::Normal(value) => parts.push(value.to_str().ok_or_else(|| {
477 StaticSiteError::Publish("static-site asset paths must be valid UTF-8".into())
478 })?),
479 _ => {
480 return Err(StaticSiteError::Publish(
481 "static-site asset path is not relative".into(),
482 ));
483 }
484 }
485 }
486 if parts.is_empty() {
487 return Err(StaticSiteError::Publish(
488 "static-site asset path is empty".into(),
489 ));
490 }
491 Ok(parts.join("/"))
492}
493
494fn asset_cache_control(plan: &StaticSitePlan, relative: &str) -> String {
495 let fingerprinted = relative
496 .split(|character: char| !character.is_ascii_hexdigit())
497 .any(|token| token.len() >= 8);
498 if fingerprinted {
499 format!("public,max-age={},immutable", plan.immutable_cache_seconds)
500 } else {
501 format!("public,max-age={},must-revalidate", plan.html_cache_seconds)
502 }
503}
504
505fn manifest_error(context: &str, error: &std::io::Error) -> StaticSiteError {
506 StaticSiteError::Publish(format!("{context} is unavailable: {error}"))
507}
508
509#[derive(Debug)]
510pub struct MemoryStaticSitePublisher {
511 public_url: String,
512 publications: Mutex<Vec<StaticSitePlan>>,
513}
514
515impl Default for MemoryStaticSitePublisher {
516 fn default() -> Self {
517 Self {
518 public_url: "http://localhost/static".into(),
519 publications: Mutex::new(Vec::new()),
520 }
521 }
522}
523
524impl MemoryStaticSitePublisher {
525 pub fn published(&self) -> Result<Vec<StaticSitePlan>, StaticSiteError> {
526 Ok(self
527 .publications
528 .lock()
529 .map_err(|_| StaticSiteError::Publish("static-site memory lock was poisoned".into()))?
530 .clone())
531 }
532}
533
534#[async_trait]
535impl StaticSitePublisher for MemoryStaticSitePublisher {
536 async fn publish_manifest(
537 &self,
538 manifest: &StaticSiteReleaseManifest,
539 _repository_root: &Path,
540 ) -> Result<StaticSitePublication, StaticSiteError> {
541 self.publications
542 .lock()
543 .map_err(|_| StaticSiteError::Publish("static-site memory lock was poisoned".into()))?
544 .push(manifest.plan.clone());
545 Ok(StaticSitePublication {
546 url: self.public_url.clone(),
547 release_manifest_digest: manifest.digest_sha256()?,
548 assets: manifest.assets.clone(),
549 uploaded: 0,
550 removed: 0,
551 invalidation_id: None,
552 invalidation_completed: false,
553 })
554 }
555}
556
557#[derive(Debug, Clone, Default)]
558pub struct StaticSitePlugin {
559 publisher: Option<StaticSitePublisherService>,
560}
561
562impl StaticSitePlugin {
563 #[must_use]
564 pub fn with_publisher(mut self, publisher: Arc<dyn StaticSitePublisher>) -> Self {
565 self.publisher = Some(StaticSitePublisherService::new(publisher));
566 self
567 }
568}
569
570impl Plugin for StaticSitePlugin {
571 fn descriptor(&self) -> PluginDescriptor {
572 let mut descriptor = PluginDescriptor::new(
573 PluginId::new("static-site").expect("static plugin ID"),
574 Version::new(1, 0, 0),
575 "Private static assets distributed through a CDN without assuming a frontend framework",
576 );
577 descriptor.documentation = Some("https://docs.rs/minco-plugin-static-site".into());
578 descriptor.core_compatibility =
579 VersionReq::parse(concat!("^", env!("CARGO_PKG_VERSION"))).expect("package version");
580 descriptor.stability = PluginStability::Beta;
581 descriptor.provides.push(CapabilityProvision {
582 name: "static-site.publish".into(),
583 version: Version::new(1, 0, 0),
584 });
585 if self.publisher.is_some() {
586 descriptor.provides.push(CapabilityProvision {
587 name: "static-site.provider".into(),
588 version: Version::new(1, 0, 0),
589 });
590 }
591 descriptor.configuration = configuration_fields();
592 descriptor
593 }
594
595 fn configure_descriptor(
596 &self,
597 descriptor: &mut PluginDescriptor,
598 configuration: Option<&serde_json::Value>,
599 ) -> Result<(), PluginError> {
600 let configuration = configuration
601 .cloned()
602 .unwrap_or_else(|| serde_json::json!({}));
603 let configuration =
604 serde_json::from_value::<StaticSiteConfig>(configuration).map_err(|source| {
605 PluginError::InvalidConfiguration {
606 plugin: descriptor.id.clone(),
607 source,
608 }
609 })?;
610 configuration
611 .validate()
612 .map_err(|error| PluginError::Installation(error.to_string()))?;
613 descriptor
614 .resources
615 .extend(static_site_resources(&configuration));
616 Ok(())
617 }
618
619 fn install(&self, context: &mut PluginContext<'_>) -> Result<(), PluginError> {
620 let configuration = context.configuration::<StaticSiteConfig>()?;
621 configuration
622 .validate()
623 .map_err(|error| PluginError::Installation(error.to_string()))?;
624 context
625 .services()
626 .insert(Arc::new(StaticSitePlan::from(configuration)))?;
627 if let Some(publisher) = &self.publisher {
628 context.services().insert(Arc::new(publisher.clone()))?;
629 }
630 Ok(())
631 }
632}
633
634fn static_site_resources(configuration: &StaticSiteConfig) -> Vec<ResourceIntent> {
635 let mut resources = vec![
636 ResourceIntent {
637 id: "static-site-bucket".into(),
638 kind: ResourceKind::S3Bucket,
639 idle_cost: IdleCostClass::StorageOnly,
640 wake_sources: Vec::new(),
641 dependencies: Vec::new(),
642 },
643 ResourceIntent {
644 id: "static-site-cdn".into(),
645 kind: ResourceKind::CloudFrontDistribution,
646 idle_cost: IdleCostClass::ProviderManaged,
647 wake_sources: vec![WakeSource::HttpRequest],
648 dependencies: vec!["static-site-bucket".into()],
649 },
650 ];
651 if configuration.custom_domain.is_some() {
652 resources.push(ResourceIntent {
653 id: "static-site-certificate".into(),
654 kind: ResourceKind::AcmCertificate,
655 idle_cost: IdleCostClass::ProviderManaged,
656 wake_sources: Vec::new(),
657 dependencies: Vec::new(),
658 });
659 if let Some(cdn) = resources
660 .iter_mut()
661 .find(|resource| resource.id == "static-site-cdn")
662 {
663 cdn.dependencies.push("static-site-certificate".into());
664 }
665 }
666 if configuration.manage_dns_alias {
667 resources.push(ResourceIntent {
668 id: "static-site-dns".into(),
669 kind: ResourceKind::Route53Alias,
670 idle_cost: IdleCostClass::ProviderManaged,
671 wake_sources: Vec::new(),
672 dependencies: vec!["static-site-cdn".into()],
673 });
674 }
675 resources
676}
677
678fn configuration_fields() -> Vec<ConfigurationField> {
679 vec![
680 string_field(
681 "source_directory",
682 "dist",
683 "Directory containing the built static artifact",
684 ),
685 string_field(
686 "index_document",
687 "index.html",
688 "Default document served at the site root",
689 ),
690 boolean_field(
691 "spa_fallback",
692 true,
693 "Rewrite missing browser routes to the index document",
694 ),
695 integer_field(
696 "immutable_cache_seconds",
697 31_536_000,
698 "Cache lifetime for fingerprinted immutable assets",
699 ),
700 integer_field(
701 "html_cache_seconds",
702 0,
703 "Cache lifetime for HTML entrypoints",
704 ),
705 string_field(
706 "price_class",
707 "price_class100",
708 "CloudFront price class: price_class100, price_class200, or price_class_all",
709 ),
710 boolean_field("ipv6_enabled", true, "Enable IPv6 on the CDN distribution"),
711 ConfigurationField {
712 key: "custom_domain".into(),
713 kind: ConfigurationValueKind::String,
714 required: false,
715 secret: false,
716 description: "Optional application hostname".into(),
717 default: None,
718 },
719 boolean_field(
720 "manage_dns_alias",
721 false,
722 "Create a DNS alias for custom_domain in the selected deployment renderer",
723 ),
724 ]
725}
726
727fn string_field(key: &str, default: &str, description: &str) -> ConfigurationField {
728 ConfigurationField {
729 key: key.into(),
730 kind: ConfigurationValueKind::String,
731 required: false,
732 secret: false,
733 description: description.into(),
734 default: Some(serde_json::Value::String(default.into())),
735 }
736}
737
738fn boolean_field(key: &str, default: bool, description: &str) -> ConfigurationField {
739 ConfigurationField {
740 key: key.into(),
741 kind: ConfigurationValueKind::Boolean,
742 required: false,
743 secret: false,
744 description: description.into(),
745 default: Some(serde_json::Value::Bool(default)),
746 }
747}
748
749fn integer_field(key: &str, default: u32, description: &str) -> ConfigurationField {
750 ConfigurationField {
751 key: key.into(),
752 kind: ConfigurationValueKind::Integer,
753 required: false,
754 secret: false,
755 description: description.into(),
756 default: Some(serde_json::json!(default)),
757 }
758}
759
760fn validate_relative_path(field: &str, value: &str) -> Result<(), StaticSiteError> {
761 let path = Path::new(value);
762 if value.trim().is_empty()
763 || value.chars().any(char::is_control)
764 || path.is_absolute()
765 || path
766 .components()
767 .any(|component| !matches!(component, std::path::Component::Normal(_)))
768 {
769 return Err(StaticSiteError::InvalidConfiguration(format!(
770 "{field} must contain only normal relative path components"
771 )));
772 }
773 Ok(())
774}
775
776fn validate_domain(value: &str) -> Result<(), StaticSiteError> {
777 if value.len() > 253
778 || value.starts_with('.')
779 || value.ends_with('.')
780 || value.split('.').count() < 2
781 || value.bytes().any(|byte| byte.is_ascii_uppercase())
782 || value.split('.').any(|label| {
783 label.is_empty()
784 || label.len() > 63
785 || label.starts_with('-')
786 || label.ends_with('-')
787 || !label
788 .bytes()
789 .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
790 })
791 {
792 return Err(StaticSiteError::InvalidConfiguration(
793 "custom_domain must be a valid lower-ASCII DNS name".into(),
794 ));
795 }
796 Ok(())
797}
798
799fn default_source_directory() -> String {
800 "dist".into()
801}
802
803fn default_index_document() -> String {
804 "index.html".into()
805}
806
807const fn default_true() -> bool {
808 true
809}
810
811const fn default_immutable_cache_seconds() -> u32 {
812 31_536_000
813}
814
815#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)]
816pub enum StaticSiteError {
817 #[error("invalid static-site configuration: {0}")]
818 InvalidConfiguration(String),
819 #[error("static-site publication failed: {0}")]
820 Publish(String),
821}
822
823#[cfg(test)]
824mod tests {
825 use super::*;
826 use minco_core::{PluginManager, PluginSelection};
827
828 #[test]
829 fn default_profile_declares_private_storage_and_cdn() {
830 let mut manager = PluginManager::default();
831 manager.register(StaticSitePlugin::default()).unwrap();
832 let mut selection = PluginSelection::default();
833 selection
834 .enabled
835 .insert(PluginId::new("static-site").unwrap());
836 let application = manager.compose(&selection).unwrap();
837 assert!(
838 application
839 .graph
840 .resources
841 .contains_key("static-site-bucket")
842 );
843 assert!(application.graph.resources.contains_key("static-site-cdn"));
844 assert!(!application.graph.resources.contains_key("static-site-dns"));
845 }
846
847 #[test]
848 fn custom_domain_configuration_changes_the_validated_resource_graph() {
849 let mut manager = PluginManager::default();
850 manager.register(StaticSitePlugin::default()).unwrap();
851 let id = PluginId::new("static-site").unwrap();
852 let mut selection = PluginSelection::default();
853 selection.enabled.insert(id.clone());
854 selection.configuration.insert(
855 id,
856 serde_json::json!({
857 "custom_domain": "app.example.test",
858 "manage_dns_alias": true
859 }),
860 );
861 let application = manager.compose(&selection).unwrap();
862 assert!(
863 application
864 .graph
865 .resources
866 .contains_key("static-site-certificate")
867 );
868 assert!(application.graph.resources.contains_key("static-site-dns"));
869 }
870
871 #[test]
872 fn dns_management_requires_a_custom_domain() {
873 let configuration = StaticSiteConfig {
874 manage_dns_alias: true,
875 ..StaticSiteConfig::default()
876 };
877 assert!(configuration.validate().is_err());
878 }
879
880 #[test]
881 fn provider_neutral_paths_reject_components_the_publisher_cannot_accept() {
882 for source_directory in [".", "./dist", "../dist"] {
883 let configuration = StaticSiteConfig {
884 source_directory: source_directory.into(),
885 ..StaticSiteConfig::default()
886 };
887 assert!(configuration.validate().is_err(), "{source_directory}");
888 }
889 }
890
891 #[tokio::test]
892 async fn publisher_is_an_explicit_injected_service() {
893 let root = tempfile::tempdir().unwrap();
894 fs::create_dir(root.path().join("dist")).unwrap();
895 fs::write(root.path().join("dist/index.html"), b"<!doctype html>").unwrap();
896 let publisher = Arc::new(MemoryStaticSitePublisher::default());
897 let mut manager = PluginManager::default();
898 manager
899 .register(StaticSitePlugin::default().with_publisher(publisher.clone()))
900 .unwrap();
901 let mut selection = PluginSelection::default();
902 selection
903 .enabled
904 .insert(PluginId::new("static-site").unwrap());
905 let application = manager.compose(&selection).unwrap();
906 assert!(
907 application
908 .graph
909 .capabilities
910 .contains_key("static-site.provider")
911 );
912 let service = application
913 .services
914 .get::<StaticSitePublisherService>()
915 .unwrap();
916 let plan = application.services.get::<StaticSitePlan>().unwrap();
917 service.publish(&plan, root.path()).await.unwrap();
918 assert_eq!(publisher.published().unwrap().len(), 1);
919 }
920}