mod access;
mod api;
mod assets;
mod login;
mod panel;
mod toolbar;
use std::sync::Arc;
use axum::http::Uri;
use laravel::container::Registrar;
use laravel::http::middleware::PreventRequestForgery;
use laravel::http::{Method, Middleware, Next, Request, Response};
pub(crate) use access::Access;
use crate::store::Store;
pub(crate) const PREFIX: &str = "/_devtools";
const INTERNAL: &str = "/_devtools-routes";
type Guarded = (Method, &'static str);
const PANEL: Guarded = (Method::GET, "/");
const LAUNCHER: Guarded = (Method::GET, "/launcher.js");
const PANEL_SCRIPT: Guarded = (Method::GET, "/panel.js");
const PANEL_STYLES: Guarded = (Method::GET, "/panel.css");
const LOGOUT: Guarded = (Method::POST, "/logout");
const TRACES: Guarded = (Method::GET, "/api/traces");
const CLEAR: Guarded = (Method::DELETE, "/api/traces");
const TRACE: Guarded = (Method::GET, "/api/traces/{id}");
const SUMMARY: Guarded = (Method::GET, "/api/traces/{id}/summary");
const GUARDED: [Guarded; 9] = [
PANEL,
LAUNCHER,
PANEL_SCRIPT,
PANEL_STYLES,
LOGOUT,
TRACES,
CLEAR,
TRACE,
SUMMARY,
];
pub(crate) fn register(app: &mut Registrar, store: Arc<dyn Store>, collector: u64, access: Access) {
let login = access.key.is_some();
app.instance(api::History(store));
app.instance(access.clone());
app.middleware().append(Hidden(access.clone()));
app.middleware().web(move |web| {
web.append(toolbar::Toolbar { access, collector });
});
app.routing().web(move |route| {
route.prefix(INTERNAL).group(|route| {
if login {
route.get("/login", login::show);
route.post("/login", login::store);
}
route
.middleware(Guard)
.without_middleware::<PreventRequestForgery>()
.group(|route| {
route.on(&[PANEL.0], PANEL.1, panel::show);
route.on(&[LAUNCHER.0], LAUNCHER.1, assets::launcher);
route.on(&[PANEL_SCRIPT.0], PANEL_SCRIPT.1, assets::panel_script);
route.on(&[PANEL_STYLES.0], PANEL_STYLES.1, assets::panel_styles);
route.on(&[LOGOUT.0], LOGOUT.1, login::destroy);
route.on(&[TRACES.0], TRACES.1, api::index);
route.on(&[CLEAR.0], CLEAR.1, api::destroy);
route.on(&[TRACE.0], TRACE.1, api::show);
route.on(&[SUMMARY.0], SUMMARY.1, api::summary);
});
});
});
}
struct Hidden(Access);
impl Middleware for Hidden {
async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
let path = request.uri().path();
let target = if let Some(rest) = under(path, INTERNAL) {
Some(format!("{PREFIX}{rest}"))
} else if let Some(rest) = under(path, PREFIX) {
let login = self.0.key.is_some()
&& rest == "/login"
&& matches!(*request.method(), Method::GET | Method::HEAD | Method::POST);
let guarded = self.0.gate_admits() && is_guarded(request.method(), rest);
(login || guarded || self.0.admits(&request)).then(|| format!("{INTERNAL}{rest}"))
} else {
None
};
let Some(target) = target else {
return Ok(next.run(request).await);
};
let mut request = request.into_http();
let uri = match request.uri().query() {
Some(query) => format!("{target}?{query}"),
None => target,
};
if let Ok(uri) = uri.parse::<Uri>() {
*request.uri_mut() = uri;
}
Ok(next.run(Request::from_http(request)).await)
}
}
fn is_guarded(method: &Method, rest: &str) -> bool {
let rest = if rest.is_empty() { "/" } else { rest };
GUARDED.iter().any(|(takes, path)| {
let method_fits = takes == method || (*takes == Method::GET && *method == Method::HEAD);
method_fits && fits(path, rest)
})
}
fn fits(path: &str, rest: &str) -> bool {
let mut wanted = path.split('/');
let mut given = rest.split('/');
loop {
match (wanted.next(), given.next()) {
(None, None) => return true,
(Some(want), Some(give)) if want == give || (want.starts_with('{') && !give.is_empty()) => {}
_ => return false,
}
}
}
pub(crate) fn is_own(path: &str) -> bool {
under(path, PREFIX).is_some() || under(path, INTERNAL).is_some()
}
fn under<'a>(path: &'a str, prefix: &str) -> Option<&'a str> {
path.strip_prefix(prefix)
.filter(|rest| rest.is_empty() || rest.starts_with('/'))
}
struct Guard;
impl Middleware for Guard {
async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
if !matches!(request.extension(), Some(toolbar::Allowed(true))) {
laravel::abort!(404);
}
PreventRequestForgery::new().handle(request, next).await
}
}
#[cfg(test)]
mod tests {
use laravel::http::Method;
use super::is_guarded;
#[test]
fn only_a_guarded_route_s_own_methods_pass_before_the_gate() {
for (method, rest) in [
(Method::GET, ""),
(Method::HEAD, "/"),
(Method::GET, "/launcher.js"),
(Method::GET, "/panel.js"),
(Method::GET, "/panel.css"),
(Method::POST, "/logout"),
(Method::GET, "/api/traces"),
(Method::DELETE, "/api/traces"),
(Method::GET, "/api/traces/0123456789abcdef0123456789abcdef"),
(Method::HEAD, "/api/traces/0123456789abcdef0123456789abcdef/summary"),
] {
assert!(is_guarded(&method, rest), "{method} {rest}");
}
for (method, rest) in [
(Method::POST, ""),
(Method::OPTIONS, "/"),
(Method::GET, "/login"),
(Method::GET, "/logout"),
(Method::PUT, "/api/traces"),
(Method::DELETE, "/api/traces/0123456789abcdef0123456789abcdef"),
(Method::GET, "/api/traces/"),
(Method::GET, "/api/traces/a/b"),
(Method::GET, "/api/traces//summary"),
(Method::GET, "/api/tracesx"),
(Method::GET, "/nothing"),
] {
assert!(!is_guarded(&method, rest), "{method} {rest}");
}
}
}