use std::fmt::Write as _;
use std::sync::atomic::{AtomicBool, Ordering};
use axum::body::{Body, HttpBody};
use axum::http::HeaderMap;
use laravel::http::{Middleware, Next, Request, Response, StatusCode, header};
use super::access::Access;
use crate::collector::{Running, running};
const MAX_PAGE: u64 = 5 * 1024 * 1024;
pub(crate) const TRACE_HEADER: &str = "x-devtools-trace";
#[derive(Clone, Copy)]
pub(crate) struct Allowed(pub(crate) bool);
pub(crate) struct Toolbar {
pub(crate) access: Access,
pub(crate) collector: u64,
}
impl Middleware for Toolbar {
async fn handle(&self, mut request: Request, next: Next) -> laravel::Result<Response> {
let allowed = self.access.allows(&request).await;
request.extensions_mut().insert(Allowed(allowed));
if super::under(request.path(), super::PREFIX).is_some() || !allowed {
return Ok(next.run(request).await);
}
let head = request.method() == laravel::http::Method::HEAD;
let response = next.run(request).await;
let Some(running) = running(self.collector) else {
return Ok(response);
};
let response = marked(response, running);
if head {
return Ok(response);
}
Ok(with_toolbar(response, running).await)
}
}
fn marked(mut response: Response, running: Running) -> Response {
let mut timing = format!(
"db;dur={:.1};desc=\"{} {}\"",
running.query_time.as_secs_f64() * 1000.0,
running.queries,
if running.queries == 1 { "query" } else { "queries" }
);
let _ = write!(timing, ", app;dur={:.1}", running.elapsed.as_secs_f64() * 1000.0);
let headers = response.headers_mut();
if let Ok(value) = running.id.to_string().parse() {
headers.insert(TRACE_HEADER, value);
}
if let Ok(value) = timing.parse() {
headers.append("server-timing", value);
}
response
}
async fn with_toolbar(response: Response, running: Running) -> Response {
if !takes_toolbar(&response) {
return response;
}
let (mut parts, body) = response.into_http().into_parts();
let Ok(page) = axum::body::to_bytes(body, usize::MAX).await else {
return Response::new(StatusCode::INTERNAL_SERVER_ERROR);
};
let Some(at) = closing_body(&page) else {
return Response::new(axum::http::Response::from_parts(parts, Body::from(page)));
};
let nonce = nonce(&parts.headers, &page);
if nonce.is_none() && blocks_without_nonce(&parts.headers) {
warn_once();
}
let script = format!(
"<script type=\"module\" src=\"{}/launcher.js?v={}\"{} data-devtools-trace=\"{}\"></script>",
super::PREFIX,
super::assets::LAUNCHER.version(),
nonce.map_or_else(String::new, |nonce| format!(" nonce=\"{nonce}\"")),
running.id
);
let page = [&page[..at], script.as_bytes(), &page[at..]].concat();
parts.headers.remove(header::CONTENT_LENGTH);
parts.headers.remove(header::ETAG);
Response::new(axum::http::Response::from_parts(parts, Body::from(page)))
}
fn takes_toolbar(response: &Response) -> bool {
let headers = response.headers();
let html = headers
.get(header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.is_some_and(|value| value.trim_start().to_ascii_lowercase().starts_with("text/html"));
let download = headers
.get(header::CONTENT_DISPOSITION)
.and_then(|value| value.to_str().ok())
.is_some_and(|value| value.trim_start().to_ascii_lowercase().starts_with("attachment"));
let sized = response.body().size_hint().exact().is_some_and(|size| size <= MAX_PAGE);
html && !download
&& sized
&& !headers.contains_key(header::CONTENT_ENCODING)
&& !matches!(response.status().as_u16(), 100..=199 | 204 | 206 | 304)
}
const SCRIPT_DIRECTIVES: [&str; 3] = ["script-src-elem", "script-src", "default-src"];
fn script_sources(headers: &HeaderMap) -> impl Iterator<Item = &str> {
headers
.get_all(header::CONTENT_SECURITY_POLICY)
.iter()
.filter_map(|value| value.to_str().ok())
.filter_map(|policy| {
let directives: Vec<(String, &str)> = policy
.split(';')
.filter_map(|directive| {
let directive = directive.trim();
let (name, sources) = directive.split_once(char::is_whitespace).unwrap_or((directive, ""));
(!name.is_empty()).then(|| (name.to_ascii_lowercase(), sources))
})
.collect();
SCRIPT_DIRECTIVES.iter().find_map(|wanted| {
directives
.iter()
.find(|(name, _)| name == wanted)
.map(|(_, sources)| *sources)
})
})
}
fn nonce(headers: &HeaderMap, page: &[u8]) -> Option<String> {
let from_header = script_sources(headers).find_map(|sources| {
sources.split_whitespace().find_map(|source| {
source
.strip_prefix("'nonce-")
.and_then(|rest| rest.strip_suffix('\''))
.filter(|nonce| is_nonce(nonce))
.map(str::to_owned)
})
});
from_header.or_else(|| nonce_in_page(page))
}
fn nonce_in_page(page: &[u8]) -> Option<String> {
const SCRIPT: &[u8] = b"<script";
const NONCE: &[u8] = b"nonce=";
let mut rest = page;
while let Some(at) = rest
.windows(SCRIPT.len())
.position(|window| window.eq_ignore_ascii_case(SCRIPT))
{
let tag = &rest[at + SCRIPT.len()..];
let tag = &tag[..tag.iter().position(|&byte| byte == b'>').unwrap_or(tag.len())];
let attribute = (1..tag.len()).find(|&at| {
tag[at - 1].is_ascii_whitespace()
&& tag[at..]
.get(..NONCE.len())
.is_some_and(|name| name.eq_ignore_ascii_case(NONCE))
});
if let Some(found) = attribute {
let value = &tag[found + NONCE.len()..];
let value = match value.split_first() {
Some(("e @ (b'"' | b'\''), quoted)) => {
"ed[..quoted.iter().position(|&byte| byte == quote).unwrap_or(quoted.len())]
}
_ => &value[..value.iter().position(u8::is_ascii_whitespace).unwrap_or(value.len())],
};
return std::str::from_utf8(value)
.ok()
.filter(|nonce| is_nonce(nonce))
.map(str::to_owned);
}
rest = &rest[at + SCRIPT.len()..];
}
None
}
fn is_nonce(value: &str) -> bool {
!value.is_empty()
&& value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'/' | b'=' | b'-' | b'_'))
}
fn blocks_without_nonce(headers: &HeaderMap) -> bool {
script_sources(headers).any(|sources| {
let sources: Vec<String> = sources.split_whitespace().map(str::to_ascii_lowercase).collect();
let has = |source: &str| sources.iter().any(|given| given == source);
has("'strict-dynamic'") || !(has("'self'") || has("*"))
})
}
fn warn_once() {
static WARNED: AtomicBool = AtomicBool::new(false);
if !WARNED.swap(true, Ordering::Relaxed) {
tracing::warn!(
"a page's Content-Security-Policy blocks the developer tools' launcher: give the page's \
scripts a nonce, which the launcher takes over, or allow 'self' in script-src"
);
}
}
fn closing_body(page: &[u8]) -> Option<usize> {
const TAG: &[u8] = b"</body";
page.windows(TAG.len())
.rposition(|window| window.eq_ignore_ascii_case(TAG))
}
#[cfg(test)]
mod tests {
use axum::http::{HeaderMap, HeaderValue, header};
use super::{blocks_without_nonce, closing_body, nonce};
fn policy(policies: &[&'static str]) -> HeaderMap {
let mut headers = HeaderMap::new();
for value in policies {
headers.append(header::CONTENT_SECURITY_POLICY, HeaderValue::from_static(value));
}
headers
}
#[test]
fn the_nonce_comes_from_the_directive_the_script_falls_under() {
let most_specific = policy(&["default-src 'nonce-d'; script-src 'nonce-s'; script-src-elem 'nonce-e'"]);
assert_eq!(nonce(&most_specific, b"").as_deref(), Some("e"));
assert_eq!(
nonce(&policy(&["Default-Src 'self' 'nonce-d'"]), b"").as_deref(),
Some("d")
);
assert_eq!(
nonce(&policy(&["script-src 'self'"]), b"<script nonce='p'>").as_deref(),
Some("p")
);
assert_eq!(nonce(&policy(&["script-src 'nonce-<x>'"]), b""), None);
assert_eq!(nonce(&HeaderMap::new(), b"<p nonce=\"p\"><script src=a.js>"), None);
assert_eq!(
nonce(&HeaderMap::new(), b"<script nonce=p async>").as_deref(),
Some("p")
);
}
#[test]
fn a_policy_that_needs_a_nonce_is_told() {
assert!(!blocks_without_nonce(&HeaderMap::new()));
assert!(!blocks_without_nonce(&policy(&["default-src 'self'"])));
assert!(!blocks_without_nonce(&policy(&["img-src 'none'"])));
assert!(blocks_without_nonce(&policy(&["script-src 'self' 'strict-dynamic'"])));
assert!(blocks_without_nonce(&policy(&["default-src 'none'"])));
assert!(blocks_without_nonce(&policy(&[
"default-src 'self'",
"script-src 'sha256-x'"
])));
}
#[test]
fn the_script_goes_before_the_last_closing_body() {
assert_eq!(closing_body(b"<body>a</body>"), Some(7));
assert_eq!(closing_body(b"<BODY>a</BODY >"), Some(7));
assert_eq!(closing_body(b"<p></body></p></body></body>"), Some(27));
assert_eq!(closing_body(b"<p>no body</p>"), None);
assert_eq!(closing_body(b""), None);
}
}