#![forbid(unsafe_code)]
#![deny(missing_docs)]
mod api;
#[cfg(feature = "jobs")]
mod jobs;
mod log_level;
mod supervisors;
mod ui;
pub use api::{API_PREFIX, Console, FiberView, MetricView};
#[cfg(feature = "jobs")]
pub use jobs::{JobView, JobsView, QueueView};
pub use log_level::{EnvFilterHandle, LogLevelChange, LogLevelView};
pub use supervisors::{SupervisorsView, UnreachableSupervisor};
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::sync::Arc;
use axum::Router;
use axum::extract::Request;
use axum::http::{StatusCode, header};
use axum::middleware::Next;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ConsoleConfig {
bind: SocketAddr,
allowed_hosts: Vec<String>,
}
impl ConsoleConfig {
pub const fn new(bind: SocketAddr) -> Self {
ConsoleConfig {
bind,
allowed_hosts: Vec::new(),
}
}
pub const fn loopback(port: u16) -> Self {
ConsoleConfig::new(SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port))
}
pub const fn bind(&self) -> SocketAddr {
self.bind
}
pub fn requires_guard(&self) -> bool {
!self.bind.ip().is_loopback()
}
#[must_use]
pub fn allow_hosts<H: Into<String>>(mut self, hosts: impl IntoIterator<Item = H>) -> Self {
self.allowed_hosts = hosts
.into_iter()
.map(|host| host.into().trim().to_ascii_lowercase())
.filter(|host| !host.is_empty())
.collect();
self
}
pub fn allowed_hosts(&self) -> Vec<String> {
if !self.allowed_hosts.is_empty() {
return self.allowed_hosts.clone();
}
let ip = match self.bind.ip() {
IpAddr::V4(ip) => ip.to_string(),
IpAddr::V6(ip) => format!("[{ip}]"),
};
let mut names = vec![ip];
if self.bind.ip().is_loopback() {
names.push("localhost".to_owned());
}
match self.bind.port() {
0 => names,
port => names
.into_iter()
.map(|name| format!("{name}:{port}"))
.collect(),
}
}
pub fn allows_host(&self, authority: &str) -> bool {
host_allowed(&self.allowed_hosts(), authority)
}
pub fn check_host_and_origin(&self, routes: Router) -> Router {
let allowed: Arc<[String]> = self.allowed_hosts().into();
routes.layer(axum::middleware::from_fn(
move |request: Request, next: Next| {
let allowed = Arc::clone(&allowed);
async move {
match foreign_request(&allowed, &request) {
Some(detail) => api::problem(StatusCode::FORBIDDEN, detail),
None => next.run(request).await,
}
}
},
))
}
}
fn foreign_request(allowed: &[String], request: &Request) -> Option<&'static str> {
let host = request
.headers()
.get(header::HOST)
.and_then(|v| v.to_str().ok())
.map(str::to_owned)
.or_else(|| request.uri().authority().map(|a| a.as_str().to_owned()));
match host {
Some(host) if host_allowed(allowed, &host) => {}
_ => return Some("the console does not answer to this host"),
}
let origin = request.headers().get(header::ORIGIN)?;
let origin = origin.to_str().unwrap_or_default();
let authority = origin
.strip_prefix("https://")
.or_else(|| origin.strip_prefix("http://"));
match authority {
Some(authority) if host_allowed(allowed, authority) => None,
_ => Some("the console does not answer to this origin"),
}
}
fn host_allowed(allowed: &[String], authority: &str) -> bool {
let (host, port) = split_authority(authority.trim());
!host.is_empty()
&& allowed.iter().any(|entry| {
let (allowed_host, allowed_port) = split_authority(entry);
allowed_host.eq_ignore_ascii_case(host) && allowed_port.is_none_or(|p| Some(p) == port)
})
}
fn split_authority(authority: &str) -> (&str, Option<&str>) {
if authority.starts_with('[') {
return match authority.find(']') {
Some(end) => {
let port = authority[end + 1..].strip_prefix(':');
(&authority[..=end], port)
}
None => (authority, None),
};
}
match authority.rsplit_once(':') {
Some((host, port)) if !host.contains(':') => (host, Some(port)),
_ => (authority, None),
}
}