#![forbid(unsafe_code)]
mod asset_urls;
pub mod csp;
pub mod csrf;
pub mod dev_reload;
mod dev_startup;
pub use dev_startup::DevServerStartup;
pub mod discovery;
pub mod public_assets;
pub mod readiness;
pub mod route;
pub mod rsjs_assets;
pub mod security_headers;
pub mod server;
pub mod static_service;
pub use asset_urls::base_path_assets;
pub use csp::{CspNonceLayer, CspPolicy};
pub use csrf::CrossOriginProtectionLayer;
pub use dev_reload::{DevReloadLayer, RELOAD_PORT_ENV, RELOAD_TOKEN_ENV};
pub use discovery::{robots_txt, sitemap_index_xml, sitemap_xml};
pub use proa_core::{
AppUrl, ArticleMetadata, BasePath, ComponentRole, CspNonce, HeadAlternate, HeadAuthor,
HeadConfig, HeadDefaults, HeadIcon, HeadMedia, HeadMetadata, HeadTitle, HeadUrlPolicy,
HeadValue, HeadVerification, IconKind, ImagePreview, InvalidBasePath, ReferrerPolicy, Robots,
SyncHeadOperation, Twitter, TwitterCard,
};
pub use proa_framework_core::{
absolute_http_url, ChangeFreq, DiscoveryError, RobotsGroup, RobotsRule, RobotsTxt, Sitemap,
SitemapFile, SitemapIndex, SitemapIndexEntry, SitemapPriority, SitemapUrl, MAX_ROBOTS_BYTES,
MAX_SITEMAP_BYTES, MAX_SITEMAP_ENTRIES,
};
pub use public_assets::{
AssetPrefix, InvalidAssetPrefix, PublicAssetError, PublicAssets, ASSET_PREFIX_ENV,
};
pub use readiness::{Readiness, DEFAULT_READINESS_TIMEOUT};
pub use route::{
app_url, drive_dyn_render, drive_dyn_send_render, explicit_markdown,
explicit_markdown_async_with_loader, negotiate, negotiate_async_with_loader,
render_metadata_head, resolved_metadata, router_from_spec, CascadeOpenGraph, CascadeValue,
ComputedRouteMeta, DynRenderOutcome, DynSendRenderOutcome, DynWebRender, DynWebRenderSend,
Layout, LayoutRef, LocalStreamExecutorConfig, ManagedPreparationTimeout, MarkdownAlternate,
Metadata, MetadataRef, OpenGraph, OpenGraphImage, OpenGraphMedia, PageCacheLayer,
PageCacheService, RepresentationResponse, ResolvedMetadata, ResolvedOpenGraphImage,
ResolvedOpenGraphMedia, Route, RouteContextLayer, RouteMode, RouteResponse, RouteSpec,
StaticPathsFn,
};
pub use rsjs_assets::{RsjsAssets, RsjsAssetsError, RsjsFile};
pub use security_headers::{FrameOptions, SecurityHeadersConfig, SecurityHeadersLayer};
pub use server::{serve, serve_with_shutdown, ShutdownOutcome, DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT};
pub use static_service::EmbeddedStaticService;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use axum::http::{header, HeaderValue};
use axum::{extract::DefaultBodyLimit, Router};
use tower::limit::GlobalConcurrencyLimitLayer;
use tower::Layer as _;
use tower_http::catch_panic::CatchPanicLayer;
use tower_http::services::ServeDir;
use tower_http::set_header::SetResponseHeaderLayer;
use tower_http::timeout::TimeoutLayer;
pub const DEFAULT_BODY_LIMIT_BYTES: usize = 1024 * 1024;
pub const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum FrameworkBuildError {
#[error(transparent)]
Discovery(#[from] DiscoveryError),
#[error("could not load published public assets: {0}")]
PublicAssets(#[from] PublicAssetError),
#[error(transparent)]
RsjsAssets(#[from] RsjsAssetsError),
}
pub struct FrameworkBuilder {
base_path: BasePath,
public_origin: Option<String>,
head: Option<proa_core::HeadConfig>,
sitemaps: Option<discovery::SitemapConfig>,
robots: Option<RobotsTxt>,
rsjs_assets: bool,
public_assets: Option<PublicAssets>,
static_router: Option<Router>,
dynamic_router: Option<Router>,
computed_metadata: Option<Arc<HashMap<String, ComputedRouteMeta>>>,
body_limit: Option<usize>,
cross_origin_protection: bool,
trusted_origins: Vec<String>,
security_headers: SecurityHeadersConfig,
csp: Option<CspPolicy>,
request_timeout: Option<Duration>,
concurrency_limit: Option<usize>,
catch_panic: bool,
local_stream_executor: LocalStreamExecutorConfig,
}
impl Default for FrameworkBuilder {
fn default() -> Self {
Self::new()
}
}
impl FrameworkBuilder {
pub fn new() -> Self {
Self {
base_path: BasePath::default(),
public_origin: None,
head: None,
sitemaps: None,
robots: None,
rsjs_assets: true,
public_assets: None,
static_router: None,
dynamic_router: None,
computed_metadata: None,
body_limit: None,
cross_origin_protection: true,
trusted_origins: Vec::new(),
security_headers: SecurityHeadersConfig::default(),
csp: None,
request_timeout: Some(DEFAULT_REQUEST_TIMEOUT),
concurrency_limit: None,
catch_panic: false,
local_stream_executor: LocalStreamExecutorConfig::default(),
}
}
pub fn with_head(mut self, head: proa_core::HeadConfig) -> Self {
self.head = Some(head);
self
}
pub fn with_base_path(mut self, base_path: BasePath) -> Self {
self.base_path = base_path;
self
}
pub fn with_public_origin(mut self, origin: &str) -> Result<Self, DiscoveryError> {
let validated = Sitemap::new(origin)?;
self.public_origin = Some(validated.origin().to_owned());
Ok(self)
}
pub fn with_sitemap(mut self, urls: impl IntoIterator<Item = SitemapUrl>) -> Self {
self.sitemaps = Some(discovery::SitemapConfig::Single(urls.into_iter().collect()));
self
}
pub fn with_sitemaps(mut self, files: impl IntoIterator<Item = SitemapFile>) -> Self {
self.sitemaps = Some(discovery::SitemapConfig::Multiple(
files.into_iter().collect(),
));
self
}
pub fn with_robots(mut self, robots: RobotsTxt) -> Self {
self.robots = Some(robots);
self
}
pub fn with_rsjs_assets(mut self) -> Self {
self.rsjs_assets = true;
self
}
pub fn without_rsjs_assets(mut self) -> Self {
self.rsjs_assets = false;
self
}
pub fn with_public_assets(mut self, assets: PublicAssets) -> Self {
self.public_assets = Some(assets);
self
}
pub fn with_body_limit(mut self, bytes: usize) -> Self {
self.body_limit = Some(bytes);
self
}
pub fn with_cross_origin_protection(mut self, enabled: bool) -> Self {
self.cross_origin_protection = enabled;
self
}
pub fn with_trusted_origin(mut self, origin: &str) -> Self {
self.trusted_origins.push(origin.to_owned());
self
}
pub fn with_security_headers(mut self, config: SecurityHeadersConfig) -> Self {
self.security_headers = config;
self
}
pub fn with_strict_csp(mut self) -> Self {
self.csp = Some(CspPolicy::strict());
self
}
pub fn with_csp_policy(mut self, policy: CspPolicy) -> Self {
self.csp = Some(policy);
self
}
pub fn with_request_timeout(mut self, timeout: Duration) -> Self {
self.request_timeout = Some(timeout);
self
}
pub fn without_request_timeout(mut self) -> Self {
self.request_timeout = None;
self
}
pub fn with_concurrency_limit(mut self, max: usize) -> Self {
self.concurrency_limit = Some(max);
self
}
pub fn with_catch_panic(mut self, enabled: bool) -> Self {
self.catch_panic = enabled;
self
}
pub fn with_local_stream_executor(mut self, config: LocalStreamExecutorConfig) -> Self {
self.local_stream_executor = config;
self
}
pub fn with_static_service(mut self, service: Router) -> Self {
self.static_router = Some(service);
self
}
pub fn with_dynamic_routes(mut self, router: Router) -> Self {
self.dynamic_router = Some(router);
self
}
pub fn with_dynamic_routes_and_metadata(
mut self,
router: Router,
metadata: Arc<HashMap<String, ComputedRouteMeta>>,
) -> Self {
self.dynamic_router = Some(router);
self.computed_metadata = Some(metadata);
self
}
pub fn build(self) -> Router {
self.try_build().expect("could not build framework router")
}
pub fn try_build(self) -> Result<Router, FrameworkBuildError> {
let FrameworkBuilder {
base_path,
public_origin,
head,
sitemaps,
robots,
rsjs_assets,
public_assets,
static_router,
dynamic_router,
computed_metadata,
body_limit,
cross_origin_protection,
trusted_origins,
security_headers,
csp,
request_timeout,
concurrency_limit,
catch_panic,
local_stream_executor,
} = self;
let body_limit_bytes = body_limit.unwrap_or(DEFAULT_BODY_LIMIT_BYTES);
let mut app =
discovery::discovery_routes(public_origin.as_deref(), &base_path, sitemaps, robots)?;
let public_assets = match public_assets {
Some(assets) => Some(assets),
None => PublicAssets::from_env(&base_path)?,
};
let rsjs_assets = rsjs_assets
.then(|| RsjsAssets::load(public_assets.as_ref()))
.transpose()?;
let asset_origin = public_assets
.as_ref()
.and_then(PublicAssets::asset_prefix)
.and_then(AssetPrefix::origin)
.map(str::to_owned);
let csp = match (csp, &asset_origin) {
(Some(policy), Some(origin)) => Some(policy.allow_asset_origin(origin)),
(csp, _) => csp,
};
let asset_prefix = public_assets
.as_ref()
.and_then(PublicAssets::asset_prefix)
.cloned();
let head = match (head, asset_prefix) {
(Some(mut head), Some(prefix)) => {
if let Some(urls) = head.urls.take() {
let urls = Arc::unwrap_or_clone(urls);
let urls = match prefix.origin() {
Some(origin) => urls.allow_resource_origin(origin),
None => urls.allow_asset_path(prefix.as_str()),
}
.map_err(|_| {
PublicAssetError::AssetPrefix(InvalidAssetPrefix(
prefix.as_str().to_owned(),
))
})?;
head.urls = Some(Arc::new(urls));
}
Some(head)
}
(head, _) => head,
};
if let Some(assets) = &rsjs_assets {
app = app.merge(assets.router());
}
if let Some(static_router) = static_router {
app = app.nest(
"/static",
base_path_assets(static_router, base_path.clone()),
);
}
if let Some(dynamic_router) = dynamic_router {
app = app.merge(dynamic_router);
}
let computed_metadata = computed_metadata.unwrap_or_else(|| Arc::new(HashMap::new()));
let mut layer = RouteContextLayer::new(computed_metadata);
if let Some(assets) = public_assets {
app = assets.serve_root_files(app.merge(assets.router()));
layer = layer.with_public_assets(assets);
}
if let Some(assets) = &rsjs_assets {
layer = layer.with_rsjs_assets(assets);
}
let layer = layer
.with_base_path(base_path)
.with_local_stream_executor_config(local_stream_executor);
let layer = if let Some(head) = head {
layer.with_head(head)
} else {
layer
};
app = app.layer(layer);
app = app.layer(DefaultBodyLimit::max(body_limit_bytes));
if cross_origin_protection {
let mut csrf_layer = CrossOriginProtectionLayer::new();
for origin in trusted_origins {
csrf_layer = csrf_layer.with_trusted_origin(origin);
}
app = app.layer(csrf_layer);
}
if let Some(timeout) = request_timeout {
app = app.layer(default_request_timeout_layer(timeout));
}
if let Some(max) = concurrency_limit {
app = app.layer(GlobalConcurrencyLimitLayer::new(max));
}
if catch_panic {
app = app.layer(CatchPanicLayer::new());
}
if let Some(policy) = &csp {
if security_headers.content_security_policy.is_some() && !policy.is_report_only() {
tracing::warn!(
"both with_security_headers(..with_content_security_policy(..)) and a \
nonce-based CSP are configured; the static policy is sent and the nonce \
directives are not. Keep only one."
);
}
if security_headers.frame_options != FrameOptions::Deny
&& policy.frame_ancestors_is_default()
&& !policy.is_report_only()
{
tracing::warn!(
"X-Frame-Options is relaxed but the CSP still sends `frame-ancestors \
'none'`, which blocks framing anyway; set it with \
CspPolicy::with_directive(\"frame-ancestors\", ..)."
);
}
}
app = app.layer(SecurityHeadersLayer::new(security_headers));
if let Some(policy) = csp {
app = app.layer(CspNonceLayer::new(policy));
}
Ok(app)
}
}
#[allow(deprecated)]
fn default_request_timeout_layer(timeout: Duration) -> TimeoutLayer {
TimeoutLayer::new(timeout)
}
fn hardened_serve_dir(
source_dir: std::path::PathBuf,
) -> tower_http::set_header::SetResponseHeader<ServeDir, HeaderValue> {
SetResponseHeaderLayer::if_not_present(
header::X_CONTENT_TYPE_OPTIONS,
HeaderValue::from_static("nosniff"),
)
.layer(ServeDir::new(source_dir))
}
pub fn standalone_static_router(dir: &str) -> Router {
Router::new().fallback_service(hardened_serve_dir(dir.into()))
}
pub use route::PageCache;