use std::net::IpAddr;
use std::sync::Arc;
use std::time::Duration;
use axum::Router;
use axum::extract::{Request, State};
use axum::http::{HeaderName, HeaderValue, Method, StatusCode, header};
use axum::middleware::{self, Next};
use axum::response::{IntoResponse, Response};
use base64::Engine as _;
use sha2::{Digest, Sha256};
use tower_http::catch_panic::CatchPanicLayer;
use tower_http::cors::{AllowOrigin, CorsLayer};
use tower_http::set_header::SetResponseHeaderLayer;
use crate::AppIdentity;
const TOKEN_BYTES: usize = 32;
const MIN_TOKEN_LEN: usize = 16;
const MAX_TOKEN_LEN: usize = 128;
const PREFLIGHT_MAX_AGE: Duration = Duration::from_secs(600);
const CSP_HEAD: &str = "default-src 'self'; script-src 'self'";
const CSP_TAIL: &str = "; style-src 'self' 'unsafe-inline'; img-src 'self' data:; \
connect-src 'self'; font-src 'self'; object-src 'none'; base-uri 'none'; \
form-action 'none'; frame-ancestors 'none'";
const FALLBACK_CSP: &str =
"default-src 'none'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'";
#[derive(Debug, thiserror::Error)]
pub enum SecurityError {
#[error("generating an access token: {0}")]
Random(#[from] getrandom::Error),
#[error(
"an access token must be {MIN_TOKEN_LEN}–{MAX_TOKEN_LEN} characters of [A-Za-z0-9._-] (it is embedded in a script and a URL, so the character set is restricted)"
)]
MalformedToken,
#[error(
"${var} must be {MIN_TOKEN_LEN}–{MAX_TOKEN_LEN} characters of [A-Za-z0-9._-] (it is embedded in a script and a URL, so the character set is restricted)"
)]
MalformedEnvToken { var: &'static str },
#[error("--allow-origin {origin}: not a usable origin (expected e.g. http://localhost:5173)")]
BadOrigin { origin: String },
}
#[derive(Clone)]
pub struct AccessToken(Arc<str>);
impl AccessToken {
pub fn generate() -> Result<Self, SecurityError> {
let mut bytes = [0u8; TOKEN_BYTES];
getrandom::fill(&mut bytes)?;
Ok(Self(hex(&bytes).into()))
}
pub fn parse(raw: &str) -> Result<Self, SecurityError> {
let well_formed = (MIN_TOKEN_LEN..=MAX_TOKEN_LEN).contains(&raw.len())
&& raw
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'));
well_formed
.then(|| Self(raw.into()))
.ok_or(SecurityError::MalformedToken)
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn matches(&self, presented: &str) -> bool {
let (expected, actual) = (self.0.as_bytes(), presented.as_bytes());
expected.len() == actual.len()
&& expected
.iter()
.zip(actual)
.fold(0u8, |acc, (a, b)| acc | (a ^ b))
== 0
}
}
pub const HANDOFF_PATH: &str = "/.ledgeline/open";
#[must_use]
pub fn plain_https(raw: &str) -> Option<url::Url> {
let url = url::Url::parse(raw.trim()).ok()?;
let plain = url.scheme() == "https"
&& url.host_str().is_some()
&& url.port().is_none()
&& url.username().is_empty()
&& url.password().is_none();
plain.then_some(url)
}
#[must_use]
pub fn plain_mailto(raw: &str) -> Option<url::Url> {
let url = url::Url::parse(raw.trim()).ok()?;
let addressed = url.scheme() == "mailto" && !url.path().trim().is_empty();
addressed.then_some(url)
}
pub struct ProcessToken {
pub token: AccessToken,
pub from_env: bool,
}
pub fn token_from_env_or_random(var: &'static str) -> Result<ProcessToken, SecurityError> {
match std::env::var(var).ok().filter(|raw| !raw.is_empty()) {
Some(raw) => Ok(ProcessToken {
token: AccessToken::parse(&raw)
.map_err(|_| SecurityError::MalformedEnvToken { var })?,
from_env: true,
}),
None => Ok(ProcessToken {
token: AccessToken::generate()?,
from_env: false,
}),
}
}
#[derive(Clone)]
pub struct Security {
token: Option<AccessToken>,
hosts: Option<Arc<[String]>>,
origins: Arc<[HeaderValue]>,
}
impl Security {
#[must_use]
pub fn open() -> Self {
Self {
token: None,
hosts: None,
origins: Arc::from([]),
}
}
#[must_use]
pub fn local(token: AccessToken, port: u16) -> Self {
let hosts = ["127.0.0.1", "localhost", "[::1]"]
.into_iter()
.map(|host| format!("{host}:{port}"))
.collect::<Vec<_>>();
Self {
token: Some(token),
hosts: Some(hosts.into()),
origins: Arc::from([]),
}
}
#[must_use]
pub fn in_process(token: AccessToken) -> Self {
Self::any_host(token)
}
#[must_use]
pub fn any_host(token: AccessToken) -> Self {
Self {
token: Some(token),
hosts: None,
origins: Arc::from([]),
}
}
pub fn allow_origins<S: AsRef<str>>(self, origins: &[S]) -> Result<Self, SecurityError> {
let parsed = origins
.iter()
.map(|origin| {
let origin = origin.as_ref().trim_end_matches('/');
let usable = origin.starts_with("http://") || origin.starts_with("https://");
HeaderValue::from_str(origin)
.ok()
.filter(|_| usable)
.ok_or_else(|| SecurityError::BadOrigin {
origin: origin.to_string(),
})
})
.collect::<Result<Vec<_>, _>>()?;
Ok(Self {
origins: parsed.into(),
..self
})
}
#[must_use]
pub fn cors_layer(&self, extra_headers: &[HeaderName]) -> Option<CorsLayer> {
if self.origins.is_empty() {
return None;
}
Some(
CorsLayer::new()
.allow_origin(AllowOrigin::list(self.origins.iter().cloned()))
.allow_methods([
Method::GET,
Method::POST,
Method::PUT,
Method::PATCH,
Method::DELETE,
])
.allow_credentials(false)
.allow_headers(
[header::AUTHORIZATION, header::CONTENT_TYPE, header::ACCEPT]
.into_iter()
.chain(extra_headers.iter().cloned())
.collect::<Vec<_>>(),
)
.max_age(PREFLIGHT_MAX_AGE),
)
}
}
#[must_use]
pub fn in_spa(origin: &str, spa_base: &str, candidate: &str) -> bool {
let Ok(url) = url::Url::parse(candidate) else {
return false;
};
let candidate_origin = url.origin();
matches!(url.scheme(), "http" | "https")
&& candidate_origin.is_tuple()
&& candidate_origin.ascii_serialization() == origin
&& path_in_spa(spa_base, url.path())
}
fn path_in_spa(spa_base: &str, path: &str) -> bool {
spa_base == "/" || path.starts_with(spa_base) || path == spa_base.trim_end_matches('/')
}
#[must_use]
pub fn token_init_script(app: &AppIdentity, origin: &str, token: &AccessToken) -> String {
let literal = |value: &str| serde_json::Value::from(value).to_string();
let path_guard = if app.spa_base == "/" {
String::new()
} else {
format!(
" && (window.location.pathname === {bare} \
|| window.location.pathname.startsWith({base}))",
bare = literal(app.spa_base.trim_end_matches('/')),
base = literal(app.spa_base),
)
};
format!(
"if (window.location.origin === {origin}{path_guard}) {{ window.{global} = {token}; }}",
origin = literal(origin),
global = app.token_global,
token = literal(token.as_str()),
)
}
pub async fn host_guard(
State(security): State<Security>,
request: Request,
next: Next,
) -> Response {
let Some(allowed) = security.hosts.clone() else {
return next.run(request).await;
};
let presented = request
.headers()
.get(header::HOST)
.and_then(|value| value.to_str().ok())
.map(str::to_owned)
.or_else(|| {
request
.uri()
.authority()
.map(|authority| authority.as_str().to_owned())
});
match presented {
Some(host) if allowed.iter().any(|ok| ok.eq_ignore_ascii_case(&host)) => {
next.run(request).await
}
_ => (
StatusCode::FORBIDDEN,
"Rejected: this server only answers to a loopback Host.\n",
)
.into_response(),
}
}
pub async fn token_guard(
State(security): State<Security>,
request: Request,
next: Next,
) -> Response {
let Some(expected) = security.token.clone() else {
return next.run(request).await;
};
let presented = request
.headers()
.get(header::AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.and_then(bearer_token);
match presented {
Some(token) if expected.matches(token) => next.run(request).await,
_ => (
StatusCode::UNAUTHORIZED,
[(header::WWW_AUTHENTICATE, "Bearer")],
"Missing or invalid access token.\n",
)
.into_response(),
}
}
#[must_use]
pub fn bearer_token(value: &str) -> Option<&str> {
let (scheme, token) = value.split_once(' ')?;
scheme
.eq_ignore_ascii_case("Bearer")
.then(|| token.trim())
.filter(|token| !token.is_empty())
}
#[must_use]
pub fn no_store() -> HeaderValue {
HeaderValue::from_static("no-store")
}
pub fn no_store_json<T: serde::Serialize>(body: T) -> Response {
([(header::CACHE_CONTROL, no_store())], axum::Json(body)).into_response()
}
#[must_use]
pub fn base_csp() -> HeaderValue {
csp_value(CSP_TAIL)
}
#[must_use]
pub fn shell_csp(app: &AppIdentity, html: &str) -> HeaderValue {
let hashes = inline_script_hashes(html)
.iter()
.map(|hash| format!(" '{hash}'"))
.collect::<String>();
let frames = app
.spa_frame_src
.map(|sources| format!("; frame-src {sources}"))
.unwrap_or_default();
csp_value(&format!("{hashes}{CSP_TAIL}{frames}"))
}
fn csp_value(rest: &str) -> HeaderValue {
HeaderValue::from_str(&format!("{CSP_HEAD}{rest}"))
.unwrap_or_else(|_| HeaderValue::from_static(FALLBACK_CSP))
}
fn inline_script_hashes(html: &str) -> Vec<String> {
let mut hashes = Vec::new();
let mut rest = html;
while let Some(open) = rest.find("<script") {
let Some(open_len) = rest[open..].find('>') else {
break;
};
let body_start = open + open_len + 1;
let Some(close) = rest[body_start..].find("</script>") else {
break;
};
let body_end = body_start + close;
if !rest[open..body_start].contains("src=") {
hashes.push(csp_sha256(&rest[body_start..body_end]));
}
rest = &rest[body_end + "</script>".len()..];
}
hashes
}
#[must_use]
pub fn csp_sha256(script: &str) -> String {
let digest = Sha256::digest(script.as_bytes());
format!(
"sha256-{}",
base64::engine::general_purpose::STANDARD.encode(digest)
)
}
#[must_use]
pub fn is_loopback_host(host: &str) -> bool {
let bare = host.trim_start_matches('[').trim_end_matches(']');
bare.eq_ignore_ascii_case("localhost")
|| bare
.parse::<IpAddr>()
.is_ok_and(|address| address.is_loopback())
}
pub struct SecurityPlan {
token: AccessToken,
loopback: bool,
origins: Vec<String>,
}
impl SecurityPlan {
#[must_use]
pub fn new(token: AccessToken, host: &str, origins: Vec<String>) -> Self {
Self {
token,
loopback: is_loopback_host(host),
origins,
}
}
#[must_use]
pub fn is_loopback(&self) -> bool {
self.loopback
}
pub fn build(&self, port: u16) -> Result<Security, SecurityError> {
let base = if self.loopback {
Security::local(self.token.clone(), port)
} else {
Security::any_host(self.token.clone())
};
base.allow_origins(&self.origins)
}
}
pub fn protect<S>(router: Router<S>, security: &Security, cors_headers: &[HeaderName]) -> Router<S>
where
S: Clone + Send + Sync + 'static,
{
let router = router.route_layer(middleware::from_fn_with_state(
security.clone(),
token_guard,
));
match security.cors_layer(cors_headers) {
Some(cors) => router.route_layer(cors),
None => router,
}
}
pub fn harden<S>(router: Router<S>, security: Security) -> Router<S>
where
S: Clone + Send + Sync + 'static,
{
router
.layer(middleware::from_fn_with_state(security, host_guard))
.layer(CatchPanicLayer::new())
.layer(SetResponseHeaderLayer::overriding(
header::X_CONTENT_TYPE_OPTIONS,
HeaderValue::from_static("nosniff"),
))
.layer(SetResponseHeaderLayer::overriding(
header::REFERRER_POLICY,
HeaderValue::from_static("no-referrer"),
))
.layer(SetResponseHeaderLayer::if_not_present(
header::CONTENT_SECURITY_POLICY,
base_csp(),
))
}
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|byte| format!("{byte:02x}")).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn plain_mailto_needs_an_address() {
for allowed in [
" mailto:ap@example.com ",
"mailto:ap@example.com?subject=Invoice%20108&body=Hello",
"MAILTO:ap@example.com",
] {
assert!(plain_mailto(allowed).is_some(), "{allowed}");
}
assert_eq!(
plain_mailto("mailto:ap@example.com?subject=Invoice 108")
.map(String::from)
.as_deref(),
Some("mailto:ap@example.com?subject=Invoice%20108"),
"answered re-serialized"
);
for refused in [
"mailto:",
"mailto:?subject=hi",
"https://example.com/",
"tel:+15551234567",
"javascript:alert(1)",
"not a url",
] {
assert!(plain_mailto(refused).is_none(), "{refused}");
}
}
#[test]
fn generated_tokens_are_long_and_unique() {
let first = AccessToken::generate().expect("entropy available");
let second = AccessToken::generate().expect("entropy available");
assert_eq!(first.as_str().len(), TOKEN_BYTES * 2);
assert!(first.as_str().chars().all(|c| c.is_ascii_hexdigit()));
assert_ne!(
first.as_str(),
second.as_str(),
"two generated tokens must differ"
);
}
#[test]
fn parse_rejects_short_and_unsafe_tokens() {
assert!(AccessToken::parse("dev").is_err(), "too short");
assert!(
AccessToken::parse(&"x".repeat(MAX_TOKEN_LEN + 1)).is_err(),
"too long"
);
assert!(AccessToken::parse("abcdefghijklmnop\"").is_err());
assert!(AccessToken::parse("abcdefghij</script>klmno").is_err());
assert!(AccessToken::parse("dev-token_for.e2e").is_ok());
}
#[test]
fn token_matches_only_itself() {
let token = AccessToken::parse("dev-token_for.e2e").expect("well-formed");
assert!(token.matches("dev-token_for.e2e"));
assert!(!token.matches("dev-token_for.e2f"));
assert!(!token.matches("dev-token_for.e2"), "prefix must not match");
assert!(!token.matches(""));
}
#[test]
fn bearer_token_parses_case_insensitively() {
assert_eq!(bearer_token("Bearer abc"), Some("abc"));
assert_eq!(bearer_token("bearer abc"), Some("abc"));
assert_eq!(bearer_token("Basic abc"), None);
assert_eq!(bearer_token("abc"), None);
assert_eq!(bearer_token("Bearer "), None);
}
#[test]
fn allow_origins_rejects_wildcards_and_bare_hosts() {
assert!(Security::open().allow_origins(&["*"]).is_err());
assert!(Security::open().allow_origins(&["localhost:5173"]).is_err());
assert!(
Security::open()
.allow_origins(&["http://localhost:5173"])
.is_ok()
);
}
#[test]
fn no_allowed_origins_means_no_cors_layer() {
assert!(
Security::local(sample_token(), 5000)
.cors_layer(&[])
.is_none()
);
assert!(
Security::local(sample_token(), 5000)
.allow_origins(&["http://localhost:4173"])
.expect("valid origin")
.cors_layer(&[])
.is_some()
);
}
#[test]
fn loopback_hosts_are_recognised_and_nothing_else_is() {
for host in [
"127.0.0.1",
"localhost",
"LOCALHOST",
"::1",
"[::1]",
"127.0.0.2",
] {
assert!(is_loopback_host(host), "{host}");
}
for host in [
"0.0.0.0",
"::",
"192.168.1.5",
"example.com",
"localhost.evil",
] {
assert!(!is_loopback_host(host), "{host}");
}
}
#[test]
fn an_env_token_names_its_variable_when_malformed() {
let error = SecurityError::MalformedEnvToken {
var: "LEDGELINE_TOKEN",
};
assert!(
error
.to_string()
.starts_with("$LEDGELINE_TOKEN must be 16–128 characters"),
"{error}"
);
}
const WHOLE_ORIGIN: AppIdentity = AppIdentity {
name: "Ledgeline",
bundle_id: "com.zmre.ledgeline",
log_prefix: "ledgeline",
token_env: "LEDGELINE_TOKEN",
token_global: "__LEDGELINE_TOKEN__",
embedded_global: "__LEDGELINE_EMBEDDED__",
spa_base: "/",
spa_frame_src: None,
};
const UNDER_APP: AppIdentity = AppIdentity {
name: "Ledgeline Invoicer",
bundle_id: "com.zmre.ledgeline.invoicer",
log_prefix: "ledgeline-invoicer",
token_env: "LEDGELINE_INVOICER_TOKEN",
token_global: "__LEDGELINE_TOKEN__",
embedded_global: "__LEDGELINE_EMBEDDED__",
spa_base: "/app/",
spa_frame_src: Some("'self' https:"),
};
#[test]
fn the_token_script_is_guarded_by_our_exact_origin() {
let script = token_init_script(&WHOLE_ORIGIN, "http://127.0.0.1:5000", &sample_token());
assert_eq!(
script,
"if (window.location.origin === \"http://127.0.0.1:5000\") \
{ window.__LEDGELINE_TOKEN__ = \"token-for-unit-tests\"; }"
);
}
#[test]
fn the_token_script_is_guarded_by_the_spa_base_too() {
let script = token_init_script(&UNDER_APP, "http://127.0.0.1:5000", &sample_token());
assert_eq!(
script,
"if (window.location.origin === \"http://127.0.0.1:5000\" \
&& (window.location.pathname === \"/app\" \
|| window.location.pathname.startsWith(\"/app/\"))) \
{ window.__LEDGELINE_TOKEN__ = \"token-for-unit-tests\"; }"
);
}
#[test]
fn the_token_scripts_path_guard_agrees_with_in_spa() {
let origin = "http://127.0.0.1:5000";
for candidate in [
"http://127.0.0.1:5000/app",
"http://127.0.0.1:5000/app/",
"http://127.0.0.1:5000/app/invoices/7?x=1#y",
"http://127.0.0.1:5000/app/../notes/x.md",
"http://127.0.0.1:5000/app/%2e%2e/notes/x.md",
"http://127.0.0.1:5000/app%2f../notes/x.md",
"http://127.0.0.1:5000/apps/",
"http://127.0.0.1:5000/App/",
"http://127.0.0.1:5000/customers/contracts/sow.html",
"http://127.0.0.1:5000/",
] {
let url = url::Url::parse(candidate).expect("test URL parses");
let pathname = url.path();
let guard = pathname == "/app" || pathname.starts_with("/app/");
assert_eq!(
guard,
in_spa(origin, UNDER_APP.spa_base, candidate),
"{candidate}"
);
}
}
#[test]
fn in_spa_allows_only_documents_under_the_base_on_our_origin() {
let origin = "http://127.0.0.1:5000";
let base = UNDER_APP.spa_base;
for allowed in [
"http://127.0.0.1:5000/app",
"http://127.0.0.1:5000/app/",
"http://127.0.0.1:5000/app/new",
"http://127.0.0.1:5000/app/invoices/2026-001?tab=pdf#top",
"http://127.0.0.1:5000/app/customers/a%20b",
"http://127.0.0.1:5000/app/x/../y",
"http://127.0.0.1:5000/./app/",
"http://127.0.0.1:5000/app/..%2fnotes",
"HTTP://127.0.0.1:5000/app/",
] {
assert!(in_spa(origin, base, allowed), "{allowed}");
}
for refused in [
"http://127.0.0.1:5000/",
"http://127.0.0.1:5000",
"http://127.0.0.1:5000/customers/contracts/sow.html",
"http://127.0.0.1:5000/notes/acme.md",
"http://127.0.0.1:5000/.mbr/notes",
"http://127.0.0.1:5000/.ledgeline-invoicer/preview",
"http://127.0.0.1:5000/api/books",
"http://127.0.0.1:5000/apps",
"http://127.0.0.1:5000/app.html",
"http://127.0.0.1:5000/application/",
"http://127.0.0.1:5000/App/",
"http://127.0.0.1:5000/APP/",
"http://127.0.0.1:5000//app/",
"http://127.0.0.1:5000/app/../notes/acme.md",
"http://127.0.0.1:5000/app/%2e%2e/notes/acme.md",
"http://127.0.0.1:5000/app/%2E%2E/notes/acme.md",
"http://127.0.0.1:5000/app/.%2e/notes/acme.md",
"http://127.0.0.1:5000/app/..\\notes/acme.md",
"http://127.0.0.1:5000/app%2f../notes/acme.md",
"http://127.0.0.1:5000/%61pp/",
"http://127.0.0.1:5001/app/",
"http://127.0.0.1:50000/app/",
"http://127.0.0.1/app/",
"https://127.0.0.1:5000/app/",
"http://localhost:5000/app/",
"http://[::1]:5000/app/",
"http://127.0.0.1:5000.evil.example/app/",
"http://127.0.0.1:5000@evil.example/app/",
"http://evil.example/app/",
"https://evil.example/app/",
"file:///app/",
"ws://127.0.0.1:5000/app/",
"about:blank",
"about:srcdoc",
"data:text/html,<script>alert(1)</script>",
"javascript:alert(1)",
"blob:http://127.0.0.1:5000/0b0e6a4c-0000-4000-8000-000000000000",
"",
"/app/",
"not a url",
] {
assert!(!in_spa(origin, base, refused), "{refused}");
}
}
#[test]
fn a_whole_origin_spa_allows_every_path_on_our_origin_and_nothing_else() {
let origin = "http://127.0.0.1:5000";
let base = WHOLE_ORIGIN.spa_base;
for allowed in [
"http://127.0.0.1:5000/",
"http://127.0.0.1:5000",
"http://127.0.0.1:5000/reports?tab=1",
"http://127.0.0.1:5000/new",
"http://127.0.0.1:5000/settings?rule=x",
] {
assert!(in_spa(origin, base, allowed), "{allowed}");
}
for refused in [
"http://127.0.0.1:5001/",
"http://127.0.0.1:5000@evil.example/",
"https://evil.example/",
"about:blank",
"data:text/html,x",
"javascript:alert(1)",
"blob:http://127.0.0.1:5000/0b0e6a4c-0000-4000-8000-000000000000",
] {
assert!(!in_spa(origin, base, refused), "{refused}");
}
}
#[test]
fn inline_script_hashes_skips_external_scripts() {
let html = "<head><script>window.x=1</script><script src=\"/a.js\"></script></head>";
let hashes = inline_script_hashes(html);
assert_eq!(hashes.len(), 1, "only the inline script is hashed");
assert_eq!(hashes[0], csp_sha256("window.x=1"));
}
#[test]
fn csp_sha256_matches_the_known_answer_for_the_empty_script() {
assert_eq!(
csp_sha256(""),
"sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU="
);
}
#[test]
fn shell_csp_carries_every_inline_hash_and_the_exfiltration_guard() {
let html = "<head><script>a</script></head><body><script>b</script></body>";
for app in [&WHOLE_ORIGIN, &UNDER_APP] {
let csp = shell_csp(app, html);
let csp = csp.to_str().expect("ascii");
assert!(csp.contains(&format!("'{}'", csp_sha256("a"))));
assert!(csp.contains(&format!("'{}'", csp_sha256("b"))));
assert!(csp.contains("connect-src 'self'"));
assert!(csp.contains("frame-ancestors 'none'"));
assert!(!csp.contains("unsafe-eval"));
}
}
#[test]
fn shell_csp_has_no_frame_src_unless_the_app_asks() {
let html = "<script>a</script>";
let hash = csp_sha256("a");
assert_eq!(
shell_csp(&WHOLE_ORIGIN, html).to_str().expect("ascii"),
format!(
"default-src 'self'; script-src 'self' '{hash}'; \
style-src 'self' 'unsafe-inline'; img-src 'self' data:; \
connect-src 'self'; font-src 'self'; object-src 'none'; \
base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
)
);
assert_eq!(
base_csp().to_str().expect("ascii"),
"default-src 'self'; script-src 'self'; \
style-src 'self' 'unsafe-inline'; img-src 'self' data:; \
connect-src 'self'; font-src 'self'; object-src 'none'; \
base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
);
}
#[test]
fn shell_csp_appends_the_apps_frame_src() {
let html = "<script>a</script>";
let with = shell_csp(&UNDER_APP, html);
let without = shell_csp(&WHOLE_ORIGIN, html);
assert_eq!(
with.to_str().expect("ascii"),
format!(
"{}; frame-src 'self' https:",
without.to_str().expect("ascii")
)
);
assert!(
!base_csp().to_str().expect("ascii").contains("frame-src"),
"only the shell carries the app's frame-src"
);
}
#[test]
fn a_bad_frame_src_falls_back_to_the_tighter_policy() {
let broken = AppIdentity {
spa_frame_src: Some("'self'\n"),
..UNDER_APP
};
assert_eq!(
shell_csp(&broken, "").to_str().expect("ascii"),
FALLBACK_CSP
);
}
fn sample_token() -> AccessToken {
AccessToken::parse("token-for-unit-tests").expect("well-formed")
}
}