use std::fmt::Write as _;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::sync::Arc;
use axum::extract::ConnectInfo;
use hmac::{Hmac, KeyInit, Mac};
use laravel::http::{Request, header};
use sha2::Sha256;
use subtle::ConstantTimeEq;
use crate::gate::{AnyGate, Gate};
pub(crate) const COOKIE: &str = "devtools_key";
pub(crate) const COOKIE_HOURS: i64 = 12;
const PROXY_HEADERS: [&str; 13] = [
"forwarded",
"x-forwarded-for",
"x-forwarded-host",
"x-forwarded-port",
"x-forwarded-prefix",
"x-forwarded-proto",
"x-forwarded-server",
"x-real-ip",
"via",
"cf-connecting-ip",
"true-client-ip",
"x-client-ip",
"fastly-client-ip",
];
#[derive(Clone)]
pub(crate) struct Access {
pub(crate) key: Option<Arc<str>>,
local: bool,
gate: Option<Gate>,
}
impl Access {
pub(crate) fn new(key: Option<&str>, local: bool, gate: Option<Gate>) -> Self {
Self {
key: key.map(Arc::from),
local,
gate,
}
}
pub(crate) async fn allows(&self, request: &Request) -> bool {
let by_the_rules = self.this_machine_or_key(request, Some);
match &self.gate {
None => by_the_rules,
Some(Gate::Narrowing(gate)) => by_the_rules && asked(gate.as_ref(), request).await,
Some(Gate::Admitting(gate)) => by_the_rules || asked(gate.as_ref(), request).await,
}
}
pub(crate) fn gate_admits(&self) -> bool {
matches!(self.gate, Some(Gate::Admitting(_)))
}
pub(crate) fn admits(&self, request: &Request) -> bool {
self.this_machine_or_key(request, |cookie| {
let encrypter = request.encrypter().ok()?;
Some(
encrypter
.decrypt_string(&cookie)
.ok()
.and_then(|plain| plain.split_once('|').map(|(_, value)| value.to_owned()))
.unwrap_or(cookie),
)
})
}
fn this_machine_or_key(&self, request: &Request, value: impl FnOnce(String) -> Option<String>) -> bool {
(self.local && on_this_machine(request))
|| request.cookie(COOKIE).and_then(value).is_some_and(|value| {
request
.encrypter()
.is_ok_and(|encrypter| self.signed_and_fresh(&value, encrypter.key()))
})
}
pub(crate) fn cookie(&self, app_key: &[u8]) -> Option<String> {
let issued = laravel::now().timestamp().as_second().to_string();
let signature = self.signature(app_key, &issued)?;
Some(format!("{issued}.{signature}"))
}
fn signed_and_fresh(&self, cookie: &str, app_key: &[u8]) -> bool {
let Some((issued, signature)) = cookie.split_once('.') else {
return false;
};
let now = laravel::now().timestamp().as_second();
let fresh = issued
.parse::<i64>()
.is_ok_and(|issued| issued <= now && now - issued < COOKIE_HOURS * 60 * 60);
let signed = self.key.is_some()
&& self
.signature(app_key, issued)
.is_some_and(|expected| bool::from(expected.as_bytes().ct_eq(signature.as_bytes())));
fresh && signed
}
fn signature(&self, app_key: &[u8], issued: &str) -> Option<String> {
let mut mac = <Hmac<Sha256> as KeyInit>::new_from_slice(app_key).ok()?;
mac.update(issued.as_bytes());
mac.update(b".");
mac.update(self.key.as_deref().unwrap_or_default().as_bytes());
Some(
mac.finalize()
.into_bytes()
.iter()
.fold(String::with_capacity(64), |mut hex, byte| {
let _ = write!(hex, "{byte:02x}");
hex
}),
)
}
pub(crate) fn is_key(&self, given: &str) -> bool {
self.key
.as_deref()
.is_some_and(|key| bool::from(key.as_bytes().ct_eq(given.as_bytes())))
}
}
async fn asked(gate: &dyn AnyGate, request: &Request) -> bool {
gate.allows(request).await.unwrap_or_else(|error| {
tracing::warn!(%error, "the developer tools' gate failed, so it counts as no");
false
})
}
pub(crate) fn peer(request: &Request) -> Option<IpAddr> {
request
.extension::<ConnectInfo<SocketAddr>>()
.map(|info| info.0.ip().to_canonical())
}
fn on_this_machine(request: &Request) -> bool {
peer(request).is_some_and(|peer| peer.is_loopback())
&& the_host(request).is_some_and(loopback_host)
&& PROXY_HEADERS.iter().all(|name| request.header(*name).is_none())
}
fn the_host(request: &Request) -> Option<&str> {
let mut hosts = request.headers().get_all(header::HOST).iter();
let host = match (hosts.next(), hosts.next()) {
(Some(host), None) => host.to_str().ok()?,
_ => return None,
};
request
.uri()
.authority()
.is_none_or(|target| target.as_str().eq_ignore_ascii_case(host))
.then_some(host)
}
fn loopback_host(host: &str) -> bool {
if let Some(rest) = host.strip_prefix('[') {
return rest.split_once(']').is_some_and(|(address, port)| {
address.parse::<Ipv6Addr>().is_ok_and(|address| address.is_loopback()) && valid_port(port)
});
}
let (name, port) = host.find(':').map_or((host, ""), |colon| host.split_at(colon));
let under_localhost = name
.len()
.checked_sub(".localhost".len())
.and_then(|end| {
name.get(..end)
.filter(|_| name[end..].eq_ignore_ascii_case(".localhost"))
})
.is_some_and(|labels| {
labels.split('.').all(|label| {
!label.is_empty() && label.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
})
});
valid_port(port)
&& (name.eq_ignore_ascii_case("localhost")
|| under_localhost
|| name.parse::<Ipv4Addr>().is_ok_and(|address| address.is_loopback()))
}
fn valid_port(rest: &str) -> bool {
rest.is_empty()
|| rest
.strip_prefix(':')
.is_some_and(|port| port.bytes().all(|byte| byte.is_ascii_digit()) && port.parse::<u16>().is_ok())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_the_machine_s_own_names_are_loopback_hosts() {
for host in [
"localhost",
"LOCALHOST:8000",
"app.localhost",
"my-app.dev.localhost:3000",
"127.0.0.1",
"127.8.0.1:8000",
"[::1]",
"[::1]:8000",
] {
assert!(loopback_host(host), "{host}");
}
for host in [
"",
"::1",
"example.com",
"localhost.example.com",
"evil example.com",
"evil example.localhost",
".localhost",
"a..localhost",
"localhost.",
"localhost:",
"localhost:abc",
"localhost:+80",
"localhost:99999",
"x:abc",
"10.0.0.1",
"0.0.0.0",
"127.1",
"0x7f.0.0.1",
"[::1",
"[::1]x",
"[::ffff:127.0.0.1]",
"evil-localhost",
] {
assert!(!loopback_host(host), "{host}");
}
}
#[test]
fn a_cookie_holds_a_signature_not_the_key() {
let key = "k".repeat(32);
let access = Access::new(Some(key.as_str()), true, None);
let app_key = [7; 32];
let signature = |access: &Access, app_key: &[u8], issued: &str| access.signature(app_key, issued).unwrap();
let cookie = signature(&access, &app_key, "1700000000");
assert_eq!(cookie.len(), 64);
assert!(!cookie.contains(&key));
assert_ne!(cookie, signature(&access, &[8; 32], "1700000000"));
assert_ne!(cookie, signature(&access, &app_key, "1700000001"));
let other = Access::new(Some("j".repeat(32).as_str()), true, None);
assert_ne!(cookie, signature(&other, &app_key, "1700000000"));
}
#[test]
fn only_the_key_itself_is_the_key() {
let access = Access::new(Some("k".repeat(32).as_str()), true, None);
assert!(access.is_key(&"k".repeat(32)));
assert!(!access.is_key(&"k".repeat(31)));
assert!(!access.is_key(&"k".repeat(33)));
assert!(!access.is_key(""));
assert!(!Access::new(None, true, None).is_key(""));
}
}