Skip to content

Building 70 Projects ranging from beginner to advanced so anyone can — learn from, build upon, use as a reference, or even copy directly. Owned by my cybersecurity company 👇

6.0 KB
Raw Blame
// ©AngelaMos | 2026
// lib.rs

pub mod wire;

use std::io;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::sync::Arc;

use axum::Router;
use axum::extract::State;
use axum::http::{StatusCode, header};
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use lisdex_monitor::snapshot::{MonitorError, Snapshot, Source};

use crate::wire::Console;

pub const DEFAULT_PORT: u16 = 47119;
pub const DEFAULT_HOST: IpAddr = IpAddr::V4(Ipv4Addr::LOCALHOST);
const OFF_MACHINE_WARNING: &str = "warning: this console is bound off-loopback, so anyone who can reach this address can read \
     the crash inputs and unfixed vulnerabilities it serves";
pub const CONSOLE_ROUTE: &str = "/";
pub const SNAPSHOT_ROUTE: &str = "/api/snapshot";

const CONSOLE_HTML: &str = include_str!("console.html");
const HTML_CONTENT_TYPE: &str = "text/html; charset=utf-8";

#[derive(Debug, thiserror::Error)]
pub enum DashboardError {
    #[error("could not start the console server: {0}")]
    Io(#[from] io::Error),
    #[error("{0}")]
    Monitor(#[from] MonitorError),
}

#[must_use]
pub fn loopback(port: u16) -> SocketAddr {
    SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port)
}

pub fn router(source: Source) -> Router {
    Router::new()
        .route(CONSOLE_ROUTE, get(console))
        .route(SNAPSHOT_ROUTE, get(snapshot))
        .with_state(Arc::new(source))
}

pub fn serve(source: Source, addr: SocketAddr) -> Result<(), DashboardError> {
    Snapshot::read(&source)?;
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()?;
    runtime.block_on(async move {
        let listener = tokio::net::TcpListener::bind(addr).await?;
        let bound = listener.local_addr()?;
        println!("lisdex console  http://{bound}");
        if !bound.ip().is_loopback() {
            eprintln!("{OFF_MACHINE_WARNING}");
        }
        println!("press ctrl-c to stop");
        axum::serve(listener, router(source)).await
    })?;
    Ok(())
}

async fn console() -> Response {
    (
        StatusCode::OK,
        [(header::CONTENT_TYPE, HTML_CONTENT_TYPE)],
        CONSOLE_HTML,
    )
        .into_response()
}

async fn snapshot(State(source): State<Arc<Source>>) -> Response {
    match Snapshot::read(&source) {
        Ok(snapshot) => axum::Json(Console::of(&snapshot)).into_response(),
        Err(err) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            axum::Json(Error {
                error: err.to_string(),
            }),
        )
            .into_response(),
    }
}

#[derive(serde::Serialize)]
struct Error {
    error: String,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_console_binds_loopback_so_a_local_campaign_is_not_published_to_the_network() {
        let addr = loopback(DEFAULT_PORT);
        assert!(
            addr.ip().is_loopback(),
            "this console reads crash inputs and unfixed vulnerabilities; binding anything but loopback would publish them"
        );
        assert_eq!(addr.port(), DEFAULT_PORT);
    }

    #[test]
    fn the_default_bind_address_stays_on_this_machine() {
        assert!(
            DEFAULT_HOST.is_loopback(),
            "a wider default would publish unfixed vulnerabilities to the network the moment someone runs the console without reading the flags"
        );
        assert_eq!(DEFAULT_HOST, loopback(DEFAULT_PORT).ip());
    }

    #[test]
    fn binding_off_loopback_is_possible_but_says_what_it_costs() {
        let exposed = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), DEFAULT_PORT);
        assert!(
            !exposed.ip().is_loopback(),
            "a container has to bind 0.0.0.0 to be reachable through a published port, so the code must be able to tell the difference and warn"
        );
        assert!(OFF_MACHINE_WARNING.contains("unfixed vulnerabilities"));
    }

    #[test]
    fn the_default_port_is_not_one_something_else_is_likely_to_hold() {
        for taken in [80_u16, 443, 3000, 5000, 5173, 8000, 8080, 8081, 8140, 9090] {
            assert_ne!(
                DEFAULT_PORT, taken,
                "the obvious port is the one already in use; the console must not fight for it"
            );
        }
        assert!(
            (30000..=60000).contains(&DEFAULT_PORT),
            "a console that grabs a low or well-known port loses the race with whatever already holds it"
        );
    }

    #[test]
    fn the_console_page_loads_nothing_from_the_network() {
        for loader in [
            "src=\"http",
            "src=\"//",
            "href=\"http",
            "href=\"//",
            "@import",
            "srcset",
            "<iframe",
        ] {
            assert!(
                !CONSOLE_HTML.contains(loader),
                "the console must fetch nothing off this machine; a keyless local tool cannot depend on a CDN being reachable, and this page renders unfixed vulnerabilities"
            );
        }
        assert!(CONSOLE_HTML.contains("<style>"));
        assert!(CONSOLE_HTML.contains("<script>"));
    }

    #[test]
    fn the_only_absolute_url_on_the_page_is_the_svg_namespace_the_dom_requires() {
        let absolute: Vec<&str> = CONSOLE_HTML
            .match_indices("://")
            .map(|(at, _)| {
                let start = CONSOLE_HTML[..at]
                    .rfind(['"', '\'', ' ', '('])
                    .map_or(0, |i| i + 1);
                let rest = &CONSOLE_HTML[start..];
                let end = rest.find(['"', '\'', ' ', ')']).unwrap_or(rest.len());
                &rest[..end]
            })
            .collect();
        assert_eq!(
            absolute,
            vec!["http://www.w3.org/2000/svg"],
            "createElementNS needs that namespace string and no browser ever fetches it; any other absolute URL is a real network dependency"
        );
    }

    #[test]
    fn the_console_page_reads_the_route_the_server_actually_serves() {
        assert!(
            CONSOLE_HTML.contains(SNAPSHOT_ROUTE),
            "the page fetches its data from a path the router must really answer"
        );
    }
}