Skip to content
1        10        20        30        40        50        60        70        80        901//! Local console for managing apps on a remote Ino server.2//!3//! The console serves one page on 127.0.0.1 and forwards `/up` and `/api/v1`4//! requests to the server. The bearer key is added here, so it never reaches5//! the browser. Git deploys under `/_console/jobs` run on this machine: they6//! clone the repository and run the `ino` release in the clone, with progress7//! events the page polls for. Requests must use a loopback Host header and, when a browser sends8//! an Origin, the console's own origin. That keeps other local origins, DNS9//! rebinding and other websites out without a per-run token.1011mod jobs;12mod repos;13mod service;1415use std::{16    net::SocketAddr,17    process::{Command, Stdio},18    time::Duration,19};2021use super::{22    cli::{ServerUiArgs, UiCommand},23    error::OnceError,24    remote,25};26use crate::commands::release;27use actix_web::{28    App, Error, HttpRequest, HttpResponse, HttpServer,29    body::{EitherBody, MessageBody},30    dev::{ServiceRequest, ServiceResponse},31    http::header,32    middleware::{self, Next},33    web,34};3536const INDEX_HTML: &str = include_str!("ui/index.html");37const STYLESHEET: &str = include_str!("ui/app.css");38const SCRIPT: &str = include_str!("ui/app.js");39const CONTENT_SECURITY_POLICY: &str = "default-src 'self'; script-src 'self'; style-src 'self'; \40     img-src 'self' data:; connect-src 'self'; base-uri 'none'; form-action 'none'; \41     frame-ancestors 'none'";42/// Long enough for `exec` commands; the server bounds their output itself.43const UPSTREAM_TIMEOUT: Duration = Duration::from_mins(3);4445pub fn run(command: UiCommand) -> Result<(), Box<dyn std::error::Error>> {46    match command {47        UiCommand::Start(args) => service::start(&args),48        UiCommand::Stop => service::stop(),49        UiCommand::Run(args) => run_foreground(&args),50    }51}5253fn run_foreground(args: &ServerUiArgs) -> Result<(), Box<dyn std::error::Error>> {54    let open = !args.no_open;55    let (server, api_key) = prepare(args)?;56    actix_web::rt::System::new().block_on(serve(server, api_key, args.port, open))?;57    Ok(())58}5960/// Checks the console settings and reads the server and key it manages.61fn prepare(args: &ServerUiArgs) -> Result<(reqwest::Url, String), Box<dyn std::error::Error>> {62    if args.port == 0 {63        return Err("console port must be between 1 and 65535".into());64    }65    let server = resolve_server(args.server.clone(), std::env::var("INO_SERVER_URL").ok())66        .ok_or("pass --server or set INO_SERVER_URL to the Ino server URL")?;67    let server = release::parse_deployment_server(&server)?;68    let api_key = remote::read_api_key()?;69    Ok((server, api_key))70}7172/// The flag wins; `INO_SERVER_URL` is used when the flag is absent or blank.73fn resolve_server(flag: Option<String>, env: Option<String>) -> Option<String> {74    flag.filter(|value| !value.trim().is_empty())75        .or_else(|| env.filter(|value| !value.trim().is_empty()))76}7778struct ConsoleState {79    server: reqwest::Url,80    api_key: String,81    port: u16,82    client: reqwest::Client,83    /// The Deploy tab's background job. Clones and releases share folders and84    /// the Docker build cache, so only one runs at a time.85    jobs: std::sync::Mutex<jobs::Jobs>,86}8788impl ConsoleState {89    fn origin(&self) -> &str {90        self.server.as_str().trim_end_matches('/')91    }9293    fn is_local_host(&self, host: &str) -> bool {94        host == format!("127.0.0.1:{}", self.port) || host == format!("localhost:{}", self.port)95    }9697    fn is_local_origin(&self, origin: &str) -> bool {98        origin99            .strip_prefix("http://")100            .is_some_and(|authority| self.is_local_host(authority))101    }102103    /// Accepts requests addressed to this console. A browser sends `Origin` on104    /// cross-site requests, so pages from other sites are refused.105    fn accepts(&self, request: &ServiceRequest) -> bool {106        let headers = request.headers();107        let host = headers108            .get(header::HOST)109            .and_then(|value| value.to_str().ok())110            .is_some_and(|host| self.is_local_host(host));111        let origin = headers.get(header::ORIGIN).is_none_or(|value| {112            value113                .to_str()114                .is_ok_and(|origin| self.is_local_origin(origin))115        });116        host && origin117    }118}119120async fn serve(121    server: reqwest::Url,122    api_key: String,123    port: u16,124    open: bool,125) -> Result<(), OnceError> {126    let client = reqwest::Client::builder()127        .timeout(UPSTREAM_TIMEOUT)128        // A redirect could move the bearer key to another host.129        .redirect(reqwest::redirect::Policy::none())130        .build()131        .map_err(|error| OnceError::Io(format!("preparing the HTTP client: {error}")))?;132    let address = SocketAddr::from(([127, 0, 0, 1], port));133    let url = format!("http://{address}/");134    let origin = server.as_str().trim_end_matches('/').to_owned();135    let state = web::Data::new(ConsoleState {136        server,137        api_key,138        port,139        client,140        jobs: std::sync::Mutex::new(jobs::Jobs::default()),141    });142    let http_server = HttpServer::new(move || {143        App::new()144            .app_data(state.clone())145            .wrap(middleware::from_fn(require_local_request))146            .configure(configure)147    })148    .bind(address)149    .map_err(|error| OnceError::Io(format!("binding the Ino console to {address}: {error}")))?150    .run();151152    println!("Ino console at {url}");153    println!("Managing {origin}. Press Ctrl+C to stop.");154    if open {155        open_browser(&url);156    }157    http_server158        .await159        .map_err(|error| OnceError::Io(format!("running the Ino console: {error}")))160}161162fn configure(config: &mut web::ServiceConfig) {163    config164        .route("/", web::get().to(index))165        .route("/assets/app.css", web::get().to(stylesheet))166        .route("/assets/app.js", web::get().to(script))167        .route("/_console/session", web::get().to(session))168        .route("/_console/jobs/check", web::post().to(repos::start_check))169        .route(170            "/_console/jobs/release",171            web::post().to(repos::start_release),172        )173        .route("/_console/jobs/{id}", web::get().to(repos::status))174        .route("/up", web::get().to(forward))175        .route("/api/v1/{tail:.*}", web::route().to(forward));176}177178async fn index() -> HttpResponse {179    page("text/html; charset=utf-8", INDEX_HTML)180}181182async fn stylesheet() -> HttpResponse {183    page("text/css; charset=utf-8", STYLESHEET)184}185186async fn script() -> HttpResponse {187    page("text/javascript; charset=utf-8", SCRIPT)188}189190async fn session(state: web::Data<ConsoleState>) -> HttpResponse {191    HttpResponse::Ok().json(serde_json::json!({ "server": state.origin() }))192}193194/// Relays one request to the server, adding the bearer key. Only `/up` and195/// `/api/v1` routes reach this function, so the console cannot be used as a196/// general proxy.197async fn forward(198    state: web::Data<ConsoleState>,199    request: HttpRequest,200    body: web::Bytes,201) -> HttpResponse {202    let Ok(method) = reqwest::Method::from_bytes(request.method().as_str().as_bytes()) else {203        return HttpResponse::MethodNotAllowed().finish();204    };205    let path = request206        .uri()207        .path_and_query()208        .map_or_else(|| request.path(), |value| value.as_str());209    let mut upstream = state210        .client211        .request(method, format!("{}{path}", state.origin()))212        .bearer_auth(&state.api_key);213    if let Some(content_type) = request.headers().get(header::CONTENT_TYPE) {214        upstream = upstream.header(reqwest::header::CONTENT_TYPE, content_type.as_bytes());215    }216    if !body.is_empty() {217        upstream = upstream.body(body);218    }219    match upstream.send().await {220        Ok(response) => relay(response).await,221        Err(_) => unreachable_server(),222    }223}224225async fn relay(response: reqwest::Response) -> HttpResponse {226    let status = actix_web::http::StatusCode::from_u16(response.status().as_u16())227        .unwrap_or(actix_web::http::StatusCode::BAD_GATEWAY);228    let content_type = response229        .headers()230        .get(reqwest::header::CONTENT_TYPE)231        .and_then(|value| value.to_str().ok())232        .map(str::to_owned);233    let Ok(body) = response.bytes().await else {234        return unreachable_server();235    };236    let mut builder = HttpResponse::build(status);237    if let Some(content_type) = content_type {238        builder.content_type(content_type);239    }240    builder.body(body)241}242243fn page(content_type: &'static str, body: &'static str) -> HttpResponse {244    HttpResponse::Ok()245        .content_type(content_type)246        .insert_header(("content-security-policy", CONTENT_SECURITY_POLICY))247        .insert_header(("x-content-type-options", "nosniff"))248        .insert_header(("referrer-policy", "no-referrer"))249        .insert_header(("cache-control", "no-store"))250        .body(body)251}252253fn unreachable_server() -> HttpResponse {254    HttpResponse::BadGateway().json(serde_json::json!({255        "error": {256            "code": "server_unreachable",257            "message": "the Ino server could not be reached"258        }259    }))260}261262async fn require_local_request<B>(263    request: ServiceRequest,264    next: Next<B>,265) -> Result<ServiceResponse<EitherBody<B>>, Error>266where267    B: MessageBody + 'static,268{269    let local = request270        .app_data::<web::Data<ConsoleState>>()271        .is_some_and(|state| state.accepts(&request));272    if local {273        return Ok(next.call(request).await?.map_into_left_body());274    }275    Ok(request276        .into_response(HttpResponse::Forbidden().finish())277        .map_into_right_body())278}279280fn open_browser(url: &str) {281    for opener in ["xdg-open", "open"] {282        let opened = Command::new(opener)283            .arg(url)284            .stdin(Stdio::null())285            .stdout(Stdio::null())286            .stderr(Stdio::null())287            .spawn()288            .is_ok();289        if opened {290            return;291        }292    }293}294295#[cfg(test)]296mod tests {297    use super::resolve_server;298299    #[test]300    fn server_comes_from_the_flag_then_the_environment() {301        let url = |value: &str| Some(value.to_owned());302        assert_eq!(303            resolve_server(url("https://a"), url("https://b")),304            url("https://a")305        );306        assert_eq!(resolve_server(None, url("https://b")), url("https://b"));307        assert_eq!(resolve_server(url(" "), url("https://b")), url("https://b"));308        assert_eq!(resolve_server(None, url("")), None);309        assert_eq!(resolve_server(None, None), None);310    }311}