Revert "fix(maestro): maestro-web is now a proxy, not a local registry (NAP-231)"
This reverts commit 3b6dd50c1d.
This commit is contained in:
@@ -1,15 +0,0 @@
|
||||
//! Local web-UI front-end.
|
||||
//!
|
||||
//! Serves the same embedded web bundle the registry serves at `/`, and
|
||||
//! reverse-proxies everything under `/api` (HTTP + WS) to an upstream
|
||||
//! registry. Lets you run the web UI on `127.0.0.1` while continuing to
|
||||
//! talk to whatever registry the daemon is registered with — local or
|
||||
//! remote.
|
||||
|
||||
#![deny(missing_debug_implementations)]
|
||||
|
||||
pub mod proxy;
|
||||
pub mod server;
|
||||
pub mod web_assets;
|
||||
|
||||
pub use server::{router, Config};
|
||||
@@ -1,107 +0,0 @@
|
||||
//! `maestro-web` — local web-UI front-end.
|
||||
|
||||
use std::error::Error;
|
||||
use std::net::SocketAddr;
|
||||
use std::process::ExitCode;
|
||||
use std::sync::Arc;
|
||||
|
||||
use maestro_web::proxy::UpstreamConfig;
|
||||
use maestro_web::router;
|
||||
use tokio::net::TcpListener;
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
const DEFAULT_BIND_ADDR: &str = "127.0.0.1:8888";
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExitCode {
|
||||
let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
|
||||
tracing_subscriber::fmt().with_env_filter(filter).init();
|
||||
|
||||
match run().await {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(e) => {
|
||||
tracing::error!(error = %e, "maestro-web failed");
|
||||
eprintln!("maestro-web: {e}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn run() -> Result<(), Box<dyn Error>> {
|
||||
let upstream_raw = std::env::var("MAESTRO_REGISTRY")
|
||||
.map_err(|_| "MAESTRO_REGISTRY must be set (e.g. https://maestro-registry.example.com)")?;
|
||||
// Accept the daemon-facing URL form too (wss://.../daemon) — the proxy
|
||||
// wants the base URL.
|
||||
let upstream = normalize_upstream(&upstream_raw);
|
||||
let upstream = UpstreamConfig::new(&upstream)?;
|
||||
let upstream = Arc::new(upstream);
|
||||
|
||||
let bind_raw =
|
||||
std::env::var("MAESTRO_WEB_BIND_ADDR").unwrap_or_else(|_| DEFAULT_BIND_ADDR.to_string());
|
||||
let bind: SocketAddr = bind_raw
|
||||
.parse()
|
||||
.map_err(|e| format!("invalid MAESTRO_WEB_BIND_ADDR ({bind_raw:?}): {e}"))?;
|
||||
|
||||
tracing::info!(
|
||||
upstream = %upstream.http_base,
|
||||
bind = %bind,
|
||||
"maestro-web starting"
|
||||
);
|
||||
|
||||
let app = router(upstream);
|
||||
let listener = TcpListener::bind(bind).await?;
|
||||
let bound = listener.local_addr()?;
|
||||
tracing::info!(addr = %bound, "listening");
|
||||
|
||||
let shutdown = async {
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
tracing::info!("ctrl-c received — shutting down");
|
||||
};
|
||||
|
||||
axum::serve(listener, app)
|
||||
.with_graceful_shutdown(shutdown)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Turn a daemon-facing URL (`wss://x/daemon`) into the base URL the proxy
|
||||
/// needs (`https://x`). Bare HTTPS/HTTP URLs pass through with any trailing
|
||||
/// `/daemon` stripped, so users can paste either form.
|
||||
fn normalize_upstream(raw: &str) -> String {
|
||||
let s = raw
|
||||
.strip_prefix("wss://")
|
||||
.map(|rest| format!("https://{rest}"))
|
||||
.or_else(|| {
|
||||
raw.strip_prefix("ws://")
|
||||
.map(|rest| format!("http://{rest}"))
|
||||
})
|
||||
.unwrap_or_else(|| raw.to_string());
|
||||
let trimmed = s.trim_end_matches('/');
|
||||
let without_daemon = trimmed.strip_suffix("/daemon").unwrap_or(trimmed);
|
||||
without_daemon.to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn normalize_strips_ws_scheme_and_daemon_suffix() {
|
||||
assert_eq!(
|
||||
normalize_upstream("wss://maestro.example.com/daemon"),
|
||||
"https://maestro.example.com"
|
||||
);
|
||||
assert_eq!(
|
||||
normalize_upstream("ws://127.0.0.1:8080/daemon/"),
|
||||
"http://127.0.0.1:8080"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_passes_through_https() {
|
||||
assert_eq!(
|
||||
normalize_upstream("https://example.com/"),
|
||||
"https://example.com"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,280 +0,0 @@
|
||||
//! Reverse proxy for `/api/*` — both HTTP and WebSocket flavours.
|
||||
//!
|
||||
//! Cookies, headers, and the request body all pass through. The upstream
|
||||
//! base URL (e.g. `https://maestro-registry.example.com`) lives in
|
||||
//! [`UpstreamConfig`]; everything past `/api/...` in the request URI is
|
||||
//! appended verbatim.
|
||||
//!
|
||||
//! The WS proxy upgrades both ends and shuttles frames between them with
|
||||
//! `tokio::select!`. We deliberately don't try to interpret the payloads —
|
||||
//! the registry is the source of truth for event shape.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::extract::ws::{Message as AxumMsg, WebSocket, WebSocketUpgrade};
|
||||
use axum::extract::{OriginalUri, Request, State};
|
||||
use axum::http::{header, HeaderMap, HeaderName, HeaderValue, Method, StatusCode, Uri};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use reqwest::Client as ReqClient;
|
||||
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
|
||||
use tokio_tungstenite::tungstenite::Message as TungMsg;
|
||||
|
||||
/// Headers that must not be forwarded — they describe the hop-by-hop
|
||||
/// connection, not the underlying request/response, and copying them
|
||||
/// breaks things (chunked encoding, keep-alive, etc.).
|
||||
const HOP_BY_HOP: &[HeaderName] = &[
|
||||
header::CONNECTION,
|
||||
header::PROXY_AUTHENTICATE,
|
||||
header::PROXY_AUTHORIZATION,
|
||||
header::TE,
|
||||
header::TRAILER,
|
||||
header::TRANSFER_ENCODING,
|
||||
header::UPGRADE,
|
||||
header::HOST,
|
||||
];
|
||||
|
||||
/// Where to forward `/api/*` requests.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct UpstreamConfig {
|
||||
/// Base URL ending without a trailing slash, e.g.
|
||||
/// `https://maestro-registry.example.com` or `http://127.0.0.1:8080`.
|
||||
pub http_base: String,
|
||||
/// WebSocket base, derived from `http_base` — `http://` → `ws://`,
|
||||
/// `https://` → `wss://`. Stored explicitly so we don't redo string
|
||||
/// surgery per-request.
|
||||
pub ws_base: String,
|
||||
pub client: ReqClient,
|
||||
}
|
||||
|
||||
impl UpstreamConfig {
|
||||
pub fn new(http_base: &str) -> Result<Self, ProxyError> {
|
||||
let http_base = http_base.trim_end_matches('/').to_string();
|
||||
let ws_base = if let Some(rest) = http_base.strip_prefix("https://") {
|
||||
format!("wss://{rest}")
|
||||
} else if let Some(rest) = http_base.strip_prefix("http://") {
|
||||
format!("ws://{rest}")
|
||||
} else {
|
||||
return Err(ProxyError::BadUpstream {
|
||||
input: http_base,
|
||||
reason: "must start with http:// or https://",
|
||||
});
|
||||
};
|
||||
let client = ReqClient::builder()
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.build()
|
||||
.map_err(ProxyError::Client)?;
|
||||
Ok(Self {
|
||||
http_base,
|
||||
ws_base,
|
||||
client,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ProxyError {
|
||||
#[error("invalid upstream URL ({input}): {reason}")]
|
||||
BadUpstream { input: String, reason: &'static str },
|
||||
#[error("upstream client build: {0}")]
|
||||
Client(reqwest::Error),
|
||||
}
|
||||
|
||||
/// Axum handler: dispatch to HTTP proxy or WS proxy based on the inbound
|
||||
/// request. Mounted at any `/api/*` route.
|
||||
pub async fn proxy_api(
|
||||
State(upstream): State<Arc<UpstreamConfig>>,
|
||||
OriginalUri(uri): OriginalUri,
|
||||
ws: Option<WebSocketUpgrade>,
|
||||
req: Request,
|
||||
) -> Response {
|
||||
if let Some(ws) = ws {
|
||||
return proxy_ws(upstream, uri, ws, req.headers().clone()).await;
|
||||
}
|
||||
proxy_http(upstream, uri, req).await
|
||||
}
|
||||
|
||||
async fn proxy_http(upstream: Arc<UpstreamConfig>, uri: Uri, req: Request) -> Response {
|
||||
let method = req.method().clone();
|
||||
let headers = req.headers().clone();
|
||||
let body_bytes = match axum::body::to_bytes(req.into_body(), 16 * 1024 * 1024).await {
|
||||
Ok(b) => b,
|
||||
Err(e) => return error_response(StatusCode::BAD_REQUEST, &format!("read body: {e}")),
|
||||
};
|
||||
|
||||
let target = build_upstream_url(&upstream.http_base, &uri);
|
||||
let mut builder = upstream
|
||||
.client
|
||||
.request(reqwest_method(&method), target)
|
||||
.body(body_bytes.to_vec());
|
||||
for (name, value) in headers.iter() {
|
||||
if HOP_BY_HOP.contains(name) {
|
||||
continue;
|
||||
}
|
||||
builder = builder.header(name, value);
|
||||
}
|
||||
|
||||
let resp = match builder.send().await {
|
||||
Ok(r) => r,
|
||||
Err(e) => return error_response(StatusCode::BAD_GATEWAY, &format!("upstream: {e}")),
|
||||
};
|
||||
|
||||
let status =
|
||||
StatusCode::from_u16(resp.status().as_u16()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
|
||||
let mut out_headers = HeaderMap::new();
|
||||
for (name, value) in resp.headers().iter() {
|
||||
if HOP_BY_HOP.contains(name) {
|
||||
continue;
|
||||
}
|
||||
out_headers.append(name, value.clone());
|
||||
}
|
||||
let body = match resp.bytes().await {
|
||||
Ok(b) => Body::from(b.to_vec()),
|
||||
Err(e) => return error_response(StatusCode::BAD_GATEWAY, &format!("upstream body: {e}")),
|
||||
};
|
||||
|
||||
(status, out_headers, body).into_response()
|
||||
}
|
||||
|
||||
async fn proxy_ws(
|
||||
upstream: Arc<UpstreamConfig>,
|
||||
uri: Uri,
|
||||
ws: WebSocketUpgrade,
|
||||
incoming_headers: HeaderMap,
|
||||
) -> Response {
|
||||
let url = build_upstream_url(&upstream.ws_base, &uri);
|
||||
ws.on_upgrade(move |socket| async move {
|
||||
if let Err(e) = drive_ws(socket, url, incoming_headers).await {
|
||||
tracing::warn!(error = %e, "ws proxy ended with error");
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async fn drive_ws(
|
||||
client_ws: WebSocket,
|
||||
upstream_url: String,
|
||||
incoming_headers: HeaderMap,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
let mut req = upstream_url.into_client_request()?;
|
||||
// Forward Cookie + Authorization so the upstream sees the browser's
|
||||
// session. Skip hop-by-hop and the headers tungstenite sets itself.
|
||||
for (name, value) in incoming_headers.iter() {
|
||||
if HOP_BY_HOP.contains(name) {
|
||||
continue;
|
||||
}
|
||||
let lower = name.as_str().to_ascii_lowercase();
|
||||
if matches!(
|
||||
lower.as_str(),
|
||||
"sec-websocket-key"
|
||||
| "sec-websocket-version"
|
||||
| "sec-websocket-protocol"
|
||||
| "sec-websocket-extensions"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
req.headers_mut().insert(name.clone(), value.clone());
|
||||
}
|
||||
|
||||
let (upstream_ws, _resp) = tokio_tungstenite::connect_async(req).await?;
|
||||
let (mut up_sink, mut up_stream) = upstream_ws.split();
|
||||
let (mut client_sink, mut client_stream) = client_ws.split();
|
||||
|
||||
let to_upstream = async {
|
||||
while let Some(msg) = client_stream.next().await {
|
||||
let msg = msg?;
|
||||
let tung = match msg {
|
||||
AxumMsg::Text(t) => TungMsg::Text(t),
|
||||
AxumMsg::Binary(b) => TungMsg::Binary(b),
|
||||
AxumMsg::Ping(b) => TungMsg::Ping(b),
|
||||
AxumMsg::Pong(b) => TungMsg::Pong(b),
|
||||
AxumMsg::Close(frame) => TungMsg::Close(frame.map(|f| {
|
||||
tokio_tungstenite::tungstenite::protocol::CloseFrame {
|
||||
code: f.code.into(),
|
||||
reason: f.reason,
|
||||
}
|
||||
})),
|
||||
};
|
||||
up_sink.send(tung).await?;
|
||||
}
|
||||
Ok::<_, Box<dyn std::error::Error + Send + Sync>>(())
|
||||
};
|
||||
|
||||
let to_client = async {
|
||||
while let Some(msg) = up_stream.next().await {
|
||||
let msg = msg?;
|
||||
let axum_msg = match msg {
|
||||
TungMsg::Text(t) => AxumMsg::Text(t),
|
||||
TungMsg::Binary(b) => AxumMsg::Binary(b),
|
||||
TungMsg::Ping(b) => AxumMsg::Ping(b),
|
||||
TungMsg::Pong(b) => AxumMsg::Pong(b),
|
||||
TungMsg::Close(frame) => {
|
||||
AxumMsg::Close(frame.map(|f| axum::extract::ws::CloseFrame {
|
||||
code: f.code.into(),
|
||||
reason: f.reason,
|
||||
}))
|
||||
}
|
||||
TungMsg::Frame(_) => continue,
|
||||
};
|
||||
client_sink.send(axum_msg).await?;
|
||||
}
|
||||
Ok::<_, Box<dyn std::error::Error + Send + Sync>>(())
|
||||
};
|
||||
|
||||
tokio::select! {
|
||||
r = to_upstream => r?,
|
||||
r = to_client => r?,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn build_upstream_url(base: &str, uri: &Uri) -> String {
|
||||
let path = uri.path();
|
||||
match uri.query() {
|
||||
Some(q) => format!("{base}{path}?{q}"),
|
||||
None => format!("{base}{path}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn reqwest_method(m: &Method) -> reqwest::Method {
|
||||
reqwest::Method::from_bytes(m.as_str().as_bytes()).unwrap_or(reqwest::Method::GET)
|
||||
}
|
||||
|
||||
fn error_response(status: StatusCode, msg: &str) -> Response {
|
||||
(
|
||||
status,
|
||||
[(header::CONTENT_TYPE, HeaderValue::from_static("text/plain"))],
|
||||
msg.to_string(),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn upstream_config_derives_ws_base_from_http() {
|
||||
let u = UpstreamConfig::new("http://127.0.0.1:8080").unwrap();
|
||||
assert_eq!(u.ws_base, "ws://127.0.0.1:8080");
|
||||
|
||||
let u = UpstreamConfig::new("https://example.com/").unwrap();
|
||||
assert_eq!(u.http_base, "https://example.com");
|
||||
assert_eq!(u.ws_base, "wss://example.com");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upstream_config_rejects_non_http() {
|
||||
let err = UpstreamConfig::new("ws://example.com").unwrap_err();
|
||||
assert!(format!("{err}").contains("http://"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_url_appends_path_and_query() {
|
||||
let uri: Uri = "/api/sessions/abc?since=42".parse().unwrap();
|
||||
assert_eq!(
|
||||
build_upstream_url("https://r.example", &uri),
|
||||
"https://r.example/api/sessions/abc?since=42"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
//! Axum router that ties the embedded web assets and the upstream proxy
|
||||
//! together.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::extract::Path;
|
||||
use axum::response::Response;
|
||||
use axum::routing::{any, get};
|
||||
use axum::Router;
|
||||
|
||||
use crate::proxy::{proxy_api, UpstreamConfig};
|
||||
use crate::web_assets;
|
||||
|
||||
/// Resolved runtime configuration. `bind` is local; `upstream` is the
|
||||
/// registry the proxy forwards `/api/*` to.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Config {
|
||||
pub bind_addr: std::net::SocketAddr,
|
||||
pub upstream: Arc<UpstreamConfig>,
|
||||
}
|
||||
|
||||
pub fn router(upstream: Arc<UpstreamConfig>) -> Router {
|
||||
Router::new()
|
||||
.route("/", get(index))
|
||||
.route("/assets/*file", get(asset))
|
||||
// Everything under /api goes to the upstream registry — including
|
||||
// the events WebSocket. axum dispatches WS via the
|
||||
// `WebSocketUpgrade` extractor inside the handler.
|
||||
.route("/api", any(proxy_api))
|
||||
.route("/api/*rest", any(proxy_api))
|
||||
.with_state(upstream)
|
||||
}
|
||||
|
||||
async fn index() -> Response {
|
||||
web_assets::serve_index()
|
||||
}
|
||||
|
||||
async fn asset(Path(file): Path<String>) -> Response {
|
||||
web_assets::serve_asset(&file)
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
//! Embedded static assets for the web client bundle.
|
||||
//!
|
||||
//! Mirror of `maestro-registry::web_assets` — kept independent so the two
|
||||
//! binaries don't have to share a code path. The web bundle is built by Vite
|
||||
//! under `web/dist/` and embedded at `cargo build` time via `rust-embed`.
|
||||
|
||||
use axum::http::{header, StatusCode};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use rust_embed::RustEmbed;
|
||||
|
||||
#[derive(RustEmbed)]
|
||||
#[folder = "../../web/dist/"]
|
||||
struct WebAssets;
|
||||
|
||||
const FALLBACK_INDEX: &str = "<!doctype html><meta charset=utf-8><title>maestro</title>\
|
||||
<h1>maestro web</h1>\
|
||||
<p>Web bundle not built. Run <code>pnpm --dir web install</code> \
|
||||
then <code>pnpm --dir web build</code>, then rebuild <code>maestro-web</code>.</p>";
|
||||
|
||||
fn content_type_for(path: &str) -> &'static str {
|
||||
let ext = path.rsplit('.').next().unwrap_or("");
|
||||
match ext {
|
||||
"html" | "htm" => "text/html; charset=utf-8",
|
||||
"js" | "mjs" => "text/javascript; charset=utf-8",
|
||||
"css" => "text/css; charset=utf-8",
|
||||
"json" => "application/json",
|
||||
"svg" => "image/svg+xml",
|
||||
"png" => "image/png",
|
||||
"ico" => "image/x-icon",
|
||||
"woff" => "font/woff",
|
||||
"woff2" => "font/woff2",
|
||||
"map" => "application/json",
|
||||
"txt" => "text/plain; charset=utf-8",
|
||||
_ => "application/octet-stream",
|
||||
}
|
||||
}
|
||||
|
||||
fn cache_headers(path: &str) -> &'static str {
|
||||
if path.starts_with("assets/") {
|
||||
"public, max-age=31536000, immutable"
|
||||
} else {
|
||||
"no-cache"
|
||||
}
|
||||
}
|
||||
|
||||
fn serve(path: &str) -> Option<Response> {
|
||||
let asset = WebAssets::get(path)?;
|
||||
let body = asset.data.into_owned();
|
||||
Some(
|
||||
(
|
||||
[
|
||||
(header::CONTENT_TYPE, content_type_for(path)),
|
||||
(header::CACHE_CONTROL, cache_headers(path)),
|
||||
],
|
||||
body,
|
||||
)
|
||||
.into_response(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn serve_index() -> Response {
|
||||
if let Some(resp) = serve("index.html") {
|
||||
return resp;
|
||||
}
|
||||
(
|
||||
StatusCode::OK,
|
||||
[(header::CONTENT_TYPE, "text/html; charset=utf-8")],
|
||||
FALLBACK_INDEX,
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
pub fn serve_asset(file: &str) -> Response {
|
||||
if file.contains("..") || file.starts_with('/') {
|
||||
return StatusCode::NOT_FOUND.into_response();
|
||||
}
|
||||
let path = format!("assets/{file}");
|
||||
match serve(&path) {
|
||||
Some(resp) => resp,
|
||||
None => StatusCode::NOT_FOUND.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn content_type_routes_common_extensions() {
|
||||
assert_eq!(content_type_for("foo.js"), "text/javascript; charset=utf-8");
|
||||
assert_eq!(content_type_for("a/b.css"), "text/css; charset=utf-8");
|
||||
assert_eq!(content_type_for("index.html"), "text/html; charset=utf-8");
|
||||
assert_eq!(content_type_for("noext"), "application/octet-stream");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serve_asset_rejects_traversal() {
|
||||
let resp = serve_asset("../secret");
|
||||
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user