forked from vhaudiquet/rhema-together
The preview tool could only name a port, so a static build needed a server the terminal had to keep alive. `preview` now accepts a path: the app reads the file or folder over the room's ssh sandbox and serves it from a signed host, with `..` and dotfiles refused and a 16 MiB cap. The target is stored with the room and replayed as a durable event. The pane shows a static path with a reload control and keeps the port field as a local fallback.
878 lines
30 KiB
Rust
878 lines
30 KiB
Rust
//! The preview proxy: a room's dev server or static build, served under
|
|
//! a signed subdomain of the preview origin.
|
|
//!
|
|
//! `r<room>-p<port>-<expiry>-<sig>.<preview host>` routes to
|
|
//! 127.0.0.1:<port> inside the room's sandbox over the same ssh connection
|
|
//! settings the agent uses. `r<room>-s<hash>-<expiry>-<sig>.<preview host>`
|
|
//! serves a file or folder with `index.html` read over ssh. Paths and the
|
|
//! origin stay stable, so absolute asset URLs keep working.
|
|
|
|
use std::collections::HashMap;
|
|
use std::sync::atomic::AtomicBool;
|
|
use std::sync::{Arc, Mutex};
|
|
use std::time::Duration;
|
|
|
|
use axum::body::Body;
|
|
use axum::http::{HeaderMap, HeaderName, HeaderValue, Method, Request, StatusCode, Uri, header};
|
|
use axum::response::{IntoResponse, Response};
|
|
use hyper_util::rt::TokioIo;
|
|
use percent_encoding::percent_decode_str;
|
|
use rhema_sandbox::Sandbox;
|
|
use rhema_sandbox::exec_util::shquote;
|
|
use rusqlite::OptionalExtension;
|
|
|
|
use crate::config::Config;
|
|
use crate::crypto::Secrets;
|
|
use crate::error::{AppError, AppResult};
|
|
use crate::models::PreviewTarget;
|
|
use crate::room::agent::{self, TargetRow};
|
|
use crate::state::Shared;
|
|
use crate::util::safe_rel_path;
|
|
|
|
/// One ssh connection per sandbox, opened lazily by the first preview
|
|
/// request and reused by the channels after it.
|
|
#[derive(Default)]
|
|
pub struct PreviewTunnels {
|
|
handles: Mutex<HashMap<String, Arc<russh::client::Handle<crate::ssh::HostKey>>>>,
|
|
}
|
|
|
|
impl PreviewTunnels {
|
|
fn get(&self, target: &str) -> Option<Arc<russh::client::Handle<crate::ssh::HostKey>>> {
|
|
self.handles
|
|
.lock()
|
|
.unwrap_or_else(|err| err.into_inner())
|
|
.get(target)
|
|
.cloned()
|
|
}
|
|
|
|
fn put(&self, target: &str, handle: Arc<russh::client::Handle<crate::ssh::HostKey>>) {
|
|
self.handles
|
|
.lock()
|
|
.unwrap_or_else(|err| err.into_inner())
|
|
.insert(target.to_owned(), handle);
|
|
}
|
|
|
|
pub(crate) fn forget(&self, target: &str) {
|
|
self.handles
|
|
.lock()
|
|
.unwrap_or_else(|err| err.into_inner())
|
|
.remove(target);
|
|
}
|
|
}
|
|
|
|
/// The preview scheme and host for this configuration, if previews
|
|
/// are on.
|
|
fn domain(config: &Config) -> Option<(&str, &str)> {
|
|
let origin = config.preview_origin.trim_end_matches('/');
|
|
let (scheme, rest) = origin.split_once("://")?;
|
|
let (host, _port) = match rest.rsplit_once(':') {
|
|
Some((host, port)) if port.chars().all(|c| c.is_ascii_digit()) => (host, Some(port)),
|
|
_ => (rest, None),
|
|
};
|
|
if host.is_empty() {
|
|
return None;
|
|
}
|
|
Some((scheme, host))
|
|
}
|
|
|
|
/// Whether a Host header belongs to the preview listener.
|
|
pub fn is_preview_host(config: &Config, host: &str) -> bool {
|
|
let Some((_, domain)) = domain(config) else {
|
|
return false;
|
|
};
|
|
let name = host.split(':').next().unwrap_or(host);
|
|
name.ends_with(&format!(".{domain}"))
|
|
}
|
|
|
|
/// How long a preview host stays valid. The browser keeps using the
|
|
/// host it was given; a reload of the room mints a fresh one.
|
|
const PREVIEW_TTL_SECONDS: i64 = 24 * 60 * 60;
|
|
|
|
/// The signed URL for one room and port.
|
|
pub fn url(config: &Config, secrets: &Secrets, room: &str, port: u16) -> AppResult<String> {
|
|
url_for_target(config, secrets, room, &PreviewTarget::Port { port })
|
|
}
|
|
|
|
/// The signed URL for the room's current target.
|
|
pub fn url_for_target(
|
|
config: &Config,
|
|
secrets: &Secrets,
|
|
room: &str,
|
|
target: &PreviewTarget,
|
|
) -> AppResult<String> {
|
|
let Some((scheme, domain)) = domain(config) else {
|
|
return Err(AppError::bad_request("the preview proxy is not configured"));
|
|
};
|
|
let expires = crate::util::now_ms() / 1000 + PREVIEW_TTL_SECONDS;
|
|
let (kind, value) = match target {
|
|
PreviewTarget::Port { port } => ('p', port.to_string()),
|
|
PreviewTarget::Static { root, entry, .. } => ('s', static_key(root, entry)),
|
|
};
|
|
let signature = secrets.sign(&signature_text(room, kind, &value, expires));
|
|
let port_part = config
|
|
.preview_origin
|
|
.split_once("://")
|
|
.map(|(_, rest)| rest)
|
|
.unwrap_or("")
|
|
.rsplit_once(':')
|
|
.filter(|(_, value)| value.chars().all(|c| c.is_ascii_digit()))
|
|
.map(|(_, value)| format!(":{value}"))
|
|
.unwrap_or_default();
|
|
Ok(format!(
|
|
"{scheme}://r{room}-{kind}{value}-{expires}-{signature}.{domain}{port_part}/"
|
|
))
|
|
}
|
|
|
|
/// A short identity for a static target. The signed link names it, so a
|
|
/// link minted for one path stops matching after the agent points the
|
|
/// preview somewhere else.
|
|
fn static_key(root: &str, entry: &str) -> String {
|
|
crate::util::sha256_hex(format!("{root}\n{entry}").as_bytes())[..12].to_owned()
|
|
}
|
|
|
|
/// What a preview host label names.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
enum HostTarget {
|
|
Port(u16),
|
|
Static(String),
|
|
}
|
|
|
|
/// One parsed preview host label.
|
|
struct HostClaim {
|
|
room: String,
|
|
target: HostTarget,
|
|
expires: i64,
|
|
signature: String,
|
|
}
|
|
|
|
/// Splits `r<room>-p<port>-<expiry>-<sig>` or
|
|
/// `r<room>-s<hash>-<expiry>-<sig>` from the Host header.
|
|
fn target_of_host(config: &Config, host: &str) -> Option<HostClaim> {
|
|
let (_, domain) = domain(config)?;
|
|
let name = host.split(':').next().unwrap_or(host);
|
|
let label = name.strip_suffix(&format!(".{domain}"))?;
|
|
let rest = label.strip_prefix('r')?;
|
|
let (room, rest) = rest.split_once('-')?;
|
|
let (target, rest) = rest.split_once('-')?;
|
|
let (expires, signature) = rest.split_once('-')?;
|
|
if room.is_empty()
|
|
|| signature.is_empty()
|
|
|| signature.contains('-')
|
|
|| !expires.chars().all(|c| c.is_ascii_digit())
|
|
{
|
|
return None;
|
|
}
|
|
let expires: i64 = expires.parse().ok()?;
|
|
let kind = target.chars().next()?;
|
|
let value = &target[kind.len_utf8()..];
|
|
if value.is_empty() {
|
|
return None;
|
|
}
|
|
let target = match kind {
|
|
'p' => HostTarget::Port(value.parse().ok()?),
|
|
's' if value.chars().all(|c| c.is_ascii_hexdigit()) => HostTarget::Static(value.to_owned()),
|
|
_ => return None,
|
|
};
|
|
Some(HostClaim {
|
|
room: room.to_owned(),
|
|
target,
|
|
expires,
|
|
signature: signature.to_owned(),
|
|
})
|
|
}
|
|
|
|
fn signature_text(room: &str, kind: char, value: &str, expires: i64) -> String {
|
|
match kind {
|
|
'p' => format!("{room}:{value}:{expires}"),
|
|
_ => format!("{room}:static:{value}:{expires}"),
|
|
}
|
|
}
|
|
|
|
/// The stored columns of one preview row.
|
|
type PreviewRow = (
|
|
String,
|
|
Option<i64>,
|
|
Option<String>,
|
|
Option<String>,
|
|
Option<String>,
|
|
);
|
|
|
|
/// The room's current preview target, if one is set.
|
|
pub fn load_target(state: &Shared, room: &str) -> AppResult<Option<PreviewTarget>> {
|
|
let row: Option<PreviewRow> = state
|
|
.db
|
|
.conn()
|
|
.query_row(
|
|
"SELECT kind, port, path, root, entry FROM room_previews WHERE room_id = ?1",
|
|
rusqlite::params![room],
|
|
|row| {
|
|
Ok((
|
|
row.get(0)?,
|
|
row.get(1)?,
|
|
row.get(2)?,
|
|
row.get(3)?,
|
|
row.get(4)?,
|
|
))
|
|
},
|
|
)
|
|
.optional()?;
|
|
let Some((kind, port, path, root, entry)) = row else {
|
|
return Ok(None);
|
|
};
|
|
let target = match kind.as_str() {
|
|
"port" => PreviewTarget::Port {
|
|
port: u16::try_from(port.unwrap_or(0))
|
|
.map_err(|_| AppError::internal("the saved preview port is invalid"))?,
|
|
},
|
|
"static" => PreviewTarget::Static {
|
|
path: path.ok_or_else(|| AppError::internal("the saved preview has no path"))?,
|
|
root: root.ok_or_else(|| AppError::internal("the saved preview has no root"))?,
|
|
entry: entry.ok_or_else(|| AppError::internal("the saved preview has no entry"))?,
|
|
},
|
|
_ => return Err(AppError::internal("the saved preview kind is unknown")),
|
|
};
|
|
Ok(Some(target))
|
|
}
|
|
|
|
/// Stores a target without announcing it.
|
|
pub fn store_target(state: &Shared, room: &str, target: &PreviewTarget) -> AppResult<()> {
|
|
let (kind, port, path, root, entry) = match target {
|
|
PreviewTarget::Port { port } => ("port", Some(i64::from(*port)), None, None, None),
|
|
PreviewTarget::Static { path, root, entry } => (
|
|
"static",
|
|
None,
|
|
Some(path.as_str()),
|
|
Some(root.as_str()),
|
|
Some(entry.as_str()),
|
|
),
|
|
};
|
|
state.db.conn().execute(
|
|
"INSERT INTO room_previews (room_id, kind, port, path, root, entry, updated_at)
|
|
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
|
|
ON CONFLICT(room_id) DO UPDATE SET
|
|
kind = excluded.kind,
|
|
port = excluded.port,
|
|
path = excluded.path,
|
|
root = excluded.root,
|
|
entry = excluded.entry,
|
|
updated_at = excluded.updated_at",
|
|
rusqlite::params![room, kind, port, path, root, entry, crate::util::now_ms()],
|
|
)?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Stores a target and adds it to the room log, so every open pane and
|
|
/// every later reconnect learns about it.
|
|
pub fn publish(state: &Shared, room: &str, target: &PreviewTarget) -> AppResult<()> {
|
|
store_target(state, room, target)?;
|
|
state
|
|
.hub
|
|
.durable(&state.db, room, "preview", serde_json::to_value(target)?)?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Validates a workspace path for the static preview and answers the
|
|
/// target to store. A folder must have an `index.html`; a file is served
|
|
/// as itself and its parent becomes the asset root.
|
|
pub async fn static_target(
|
|
state: &Shared,
|
|
workspace: &str,
|
|
sandbox_target: &TargetRow,
|
|
path: &str,
|
|
) -> Result<PreviewTarget, String> {
|
|
let rel = visible_rel_path(path)?;
|
|
let abs = workspace_path(workspace, &rel);
|
|
let index = if rel == "." {
|
|
format!("{}/index.html", workspace.trim_end_matches('/'))
|
|
} else {
|
|
format!("{}/{rel}/index.html", workspace.trim_end_matches('/'))
|
|
};
|
|
let command = format!(
|
|
"if [ -d {p} ]; then \
|
|
if [ -f {i} ]; then printf 'dir'; else printf 'noindex'; fi; \
|
|
elif [ -f {p} ]; then printf 'file'; else printf 'missing'; fi",
|
|
p = shquote(&abs),
|
|
i = shquote(&index)
|
|
);
|
|
let sandbox = agent::sandbox_for(state, workspace, sandbox_target).map_err(|e| e.message)?;
|
|
let cancelled = AtomicBool::new(false);
|
|
let mut progress = rhema_sandbox::OutputOnly(|_| {});
|
|
let outcome = sandbox
|
|
.run(
|
|
rhema_sandbox::RunRequest {
|
|
command,
|
|
cwd: workspace.into(),
|
|
timeout: Duration::from_secs(15),
|
|
env: Default::default(),
|
|
},
|
|
&cancelled,
|
|
&mut progress,
|
|
)
|
|
.await
|
|
.map_err(|err| err.to_string())?;
|
|
let kind = String::from_utf8_lossy(&outcome.stdout).trim().to_owned();
|
|
match kind.as_str() {
|
|
"dir" => {
|
|
let entry = if rel == "." {
|
|
"index.html".to_owned()
|
|
} else {
|
|
format!("{rel}/index.html")
|
|
};
|
|
Ok(PreviewTarget::Static {
|
|
path: rel.clone(),
|
|
root: rel,
|
|
entry,
|
|
})
|
|
}
|
|
"file" => {
|
|
let root = rel
|
|
.rsplit_once('/')
|
|
.map(|(parent, _)| parent.to_owned())
|
|
.unwrap_or_else(|| ".".to_owned());
|
|
Ok(PreviewTarget::Static {
|
|
path: rel.clone(),
|
|
root,
|
|
entry: rel,
|
|
})
|
|
}
|
|
"noindex" => Err(format!("{rel} has no index.html to serve")),
|
|
"missing" => Err(format!("{rel} does not exist in the workspace")),
|
|
_ => Err(format!("could not inspect {rel} in the workspace")),
|
|
}
|
|
}
|
|
|
|
/// A static target must not name a hidden file or folder. The request
|
|
/// side refuses dotfiles too, but checking here stops a model from
|
|
/// publishing `.env` or `.git` as the entry.
|
|
fn visible_rel_path(path: &str) -> Result<String, String> {
|
|
let rel = safe_rel_path(path)?;
|
|
if rel
|
|
.split('/')
|
|
.any(|part| part != "." && part.starts_with('.') && part != ".well-known")
|
|
{
|
|
return Err("the preview cannot point at a hidden file or folder".into());
|
|
}
|
|
Ok(rel)
|
|
}
|
|
|
|
fn workspace_path(workspace: &str, rel: &str) -> String {
|
|
if rel == "." {
|
|
workspace.trim_end_matches('/').to_owned()
|
|
} else {
|
|
format!("{}/{}", workspace.trim_end_matches('/'), rel)
|
|
}
|
|
}
|
|
|
|
fn signatures_match(a: &str, b: &str) -> bool {
|
|
if a.len() != b.len() {
|
|
return false;
|
|
}
|
|
let mut diff = 0u8;
|
|
for (left, right) in a.as_bytes().iter().zip(b.as_bytes()) {
|
|
diff |= left ^ right;
|
|
}
|
|
diff == 0
|
|
}
|
|
|
|
fn frame_ancestors(config: &Config, mut response: Response) -> Response {
|
|
if let Ok(value) = HeaderValue::from_str(&format!(
|
|
"frame-ancestors {}",
|
|
config.public_url.trim_end_matches('/')
|
|
)) {
|
|
response
|
|
.headers_mut()
|
|
.insert(header::CONTENT_SECURITY_POLICY, value);
|
|
}
|
|
response
|
|
}
|
|
|
|
fn no_referrer(mut response: Response) -> Response {
|
|
response.headers_mut().insert(
|
|
header::REFERRER_POLICY,
|
|
HeaderValue::from_static("no-referrer"),
|
|
);
|
|
response
|
|
}
|
|
|
|
/// Verifies the signed label against the target it names, then serves
|
|
/// that target.
|
|
pub async fn proxy(state: Shared, request: Request<Body>) -> Response {
|
|
let host = request
|
|
.headers()
|
|
.get(header::HOST)
|
|
.and_then(|value| value.to_str().ok())
|
|
.unwrap_or("")
|
|
.to_owned();
|
|
let Some(claim) = target_of_host(&state.config, &host) else {
|
|
return (StatusCode::NOT_FOUND, "not a preview host").into_response();
|
|
};
|
|
if claim.expires < crate::util::now_ms() / 1000 {
|
|
return (StatusCode::NOT_FOUND, "this preview link has expired").into_response();
|
|
}
|
|
let (kind, value) = match &claim.target {
|
|
HostTarget::Port(port) => ('p', port.to_string()),
|
|
HostTarget::Static(key) => ('s', key.clone()),
|
|
};
|
|
let expected = state
|
|
.secrets
|
|
.sign(&signature_text(&claim.room, kind, &value, claim.expires));
|
|
if !signatures_match(&claim.signature, &expected) {
|
|
return (StatusCode::NOT_FOUND, "not a preview host").into_response();
|
|
}
|
|
match claim.target {
|
|
HostTarget::Port(port) => match try_proxy(&state, &claim.room, port, request).await {
|
|
Ok(response) => no_referrer(frame_ancestors(&state.config, response)),
|
|
Err(message) => no_referrer(
|
|
(
|
|
StatusCode::BAD_GATEWAY,
|
|
format!("the preview did not answer: {message}"),
|
|
)
|
|
.into_response(),
|
|
),
|
|
},
|
|
HostTarget::Static(key) => match try_static(&state, &claim.room, &key, request).await {
|
|
Ok(response) => no_referrer(response),
|
|
Err((status, message)) => no_referrer((status, message).into_response()),
|
|
},
|
|
}
|
|
}
|
|
|
|
async fn try_proxy(
|
|
state: &Shared,
|
|
room: &str,
|
|
port: u16,
|
|
request: Request<Body>,
|
|
) -> Result<Response, String> {
|
|
let (workspace, target) = agent::load_room_target(state, room).map_err(|err| err.message)?;
|
|
let _ = workspace;
|
|
let key = state
|
|
.secrets
|
|
.open_str(&target.private_key_ciphertext)
|
|
.map_err(|err| err.message)?;
|
|
let handle = match state.previews.get(&target.id) {
|
|
Some(handle) => handle,
|
|
None => {
|
|
let (handle, learned) = crate::ssh::connect_handle(&target, &key).await?;
|
|
crate::ssh::remember_host_key(state, &target, learned);
|
|
let handle = Arc::new(handle);
|
|
state.previews.put(&target.id, handle.clone());
|
|
handle
|
|
}
|
|
};
|
|
let channel = match handle
|
|
.channel_open_direct_tcpip("127.0.0.1", port as u32, "127.0.0.1", 0)
|
|
.await
|
|
{
|
|
Ok(channel) => channel,
|
|
Err(_) => {
|
|
state.previews.forget(&target.id);
|
|
let (handle, learned) = crate::ssh::connect_handle(&target, &key).await?;
|
|
crate::ssh::remember_host_key(state, &target, learned);
|
|
let handle = Arc::new(handle);
|
|
state.previews.put(&target.id, handle.clone());
|
|
handle
|
|
.channel_open_direct_tcpip("127.0.0.1", port as u32, "127.0.0.1", 0)
|
|
.await
|
|
.map_err(|err| format!("the sandbox refused port {port}: {err}"))?
|
|
}
|
|
};
|
|
let stream = channel.into_stream();
|
|
let io = TokioIo::new(stream);
|
|
let (mut sender, connection) = hyper::client::conn::http1::handshake(io)
|
|
.await
|
|
.map_err(|err| format!("http handshake failed: {err}"))?;
|
|
tokio::spawn(async move {
|
|
let _ = connection.await;
|
|
});
|
|
let path = request
|
|
.uri()
|
|
.path_and_query()
|
|
.map(|value| value.as_str())
|
|
.unwrap_or("/");
|
|
let uri: Uri = path.parse().map_err(|err| format!("bad path: {err}"))?;
|
|
let (parts, body) = request.into_parts();
|
|
let mut outbound = Request::builder()
|
|
.method(parts.method)
|
|
.uri(uri)
|
|
.body(body)
|
|
.map_err(|err| format!("could not build the request: {err}"))?;
|
|
*outbound.headers_mut() = parts.headers;
|
|
strip_hop_by_hop(outbound.headers_mut());
|
|
outbound.headers_mut().insert(
|
|
header::HOST,
|
|
HeaderValue::from_str(&format!("127.0.0.1:{port}")).unwrap(),
|
|
);
|
|
let response = sender
|
|
.send_request(outbound)
|
|
.await
|
|
.map_err(|err| format!("the preview did not answer: {err}"))?;
|
|
let (parts, body) = response.into_parts();
|
|
let mut out = Response::new(Body::new(body));
|
|
*out.status_mut() = parts.status;
|
|
*out.headers_mut() = parts.headers;
|
|
strip_hop_by_hop(out.headers_mut());
|
|
Ok(no_referrer(out))
|
|
}
|
|
|
|
/// The largest static file the preview serves. The sandbox read caps at
|
|
/// 32 MiB; this leaves room for the status line and keeps one request
|
|
/// from holding a whole build artifact in memory.
|
|
const STATIC_MAX_BYTES: usize = 16 * 1024 * 1024;
|
|
|
|
/// Serves one request from a static target over the room's ssh sandbox.
|
|
async fn try_static(
|
|
state: &Shared,
|
|
room: &str,
|
|
key: &str,
|
|
request: Request<Body>,
|
|
) -> Result<Response, (StatusCode, String)> {
|
|
let target = load_target(state, room)
|
|
.map_err(|err| (StatusCode::BAD_GATEWAY, err.message))?
|
|
.ok_or_else(|| (StatusCode::NOT_FOUND, "this room has no preview".to_owned()))?;
|
|
let PreviewTarget::Static { root, entry, .. } = target else {
|
|
return Err((
|
|
StatusCode::NOT_FOUND,
|
|
"this preview link no longer matches the room".to_owned(),
|
|
));
|
|
};
|
|
if static_key(&root, &entry) != key {
|
|
return Err((
|
|
StatusCode::NOT_FOUND,
|
|
"this preview link no longer matches the room".to_owned(),
|
|
));
|
|
}
|
|
let method = request.method();
|
|
if method != Method::GET && method != Method::HEAD {
|
|
return Err((
|
|
StatusCode::METHOD_NOT_ALLOWED,
|
|
"the static preview only answers GET and HEAD".to_owned(),
|
|
));
|
|
}
|
|
let rel = static_request_path(request.uri(), &root, &entry)?;
|
|
let (workspace, sandbox_target) = agent::load_room_target(state, room)
|
|
.map_err(|err| (StatusCode::BAD_GATEWAY, err.message))?;
|
|
let abs = workspace_path(&workspace, &rel);
|
|
let sandbox = agent::sandbox_for(state, &workspace, &sandbox_target)
|
|
.map_err(|err| (StatusCode::BAD_GATEWAY, err.message))?;
|
|
let cancelled = AtomicBool::new(false);
|
|
let mut progress = rhema_sandbox::OutputOnly(|_| {});
|
|
let outcome = sandbox
|
|
.run(
|
|
rhema_sandbox::RunRequest {
|
|
command: static_read_command(&abs),
|
|
cwd: workspace.into(),
|
|
timeout: Duration::from_secs(20),
|
|
env: Default::default(),
|
|
},
|
|
&cancelled,
|
|
&mut progress,
|
|
)
|
|
.await
|
|
.map_err(|err| (StatusCode::BAD_GATEWAY, err.to_string()))?;
|
|
let read = parse_static_output(outcome.stdout).ok_or_else(|| {
|
|
(
|
|
StatusCode::BAD_GATEWAY,
|
|
"the static preview returned no status".to_owned(),
|
|
)
|
|
})?;
|
|
let body = match read {
|
|
StaticRead::Body(body) => body,
|
|
StaticRead::Missing => {
|
|
return Err((StatusCode::NOT_FOUND, "file not found".to_owned()));
|
|
}
|
|
StaticRead::Large => {
|
|
return Err((
|
|
StatusCode::PAYLOAD_TOO_LARGE,
|
|
"this file is too large for the static preview".to_owned(),
|
|
));
|
|
}
|
|
};
|
|
let length = body.len();
|
|
let body = if method == Method::HEAD {
|
|
Body::empty()
|
|
} else {
|
|
Body::from(body)
|
|
};
|
|
let frame_ancestors = format!(
|
|
"frame-ancestors {}",
|
|
state.config.public_url.trim_end_matches('/')
|
|
);
|
|
Response::builder()
|
|
.status(StatusCode::OK)
|
|
.header(header::CONTENT_TYPE, content_type(&rel))
|
|
.header(header::CONTENT_LENGTH, length)
|
|
.header(header::CACHE_CONTROL, "no-store")
|
|
.header(header::X_CONTENT_TYPE_OPTIONS, "nosniff")
|
|
.header(header::CONTENT_SECURITY_POLICY, frame_ancestors)
|
|
.body(body)
|
|
.map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()))
|
|
}
|
|
|
|
/// Maps a request path onto the static root, refusing escapes and
|
|
/// dotfiles. A trailing slash asks for that directory's `index.html`.
|
|
fn static_request_path(uri: &Uri, root: &str, entry: &str) -> Result<String, (StatusCode, String)> {
|
|
let decoded = percent_decode_str(uri.path())
|
|
.decode_utf8()
|
|
.map_err(|_| (StatusCode::NOT_FOUND, "file not found".to_owned()))?;
|
|
let raw = decoded.trim_start_matches('/');
|
|
if raw.is_empty() {
|
|
return Ok(entry.to_owned());
|
|
}
|
|
if raw.contains('\0') {
|
|
return Err((StatusCode::NOT_FOUND, "file not found".to_owned()));
|
|
}
|
|
let trailing = raw.ends_with('/');
|
|
let mut parts = Vec::new();
|
|
for part in raw.split('/') {
|
|
if part.is_empty() || part == "." {
|
|
continue;
|
|
}
|
|
if part == ".." {
|
|
return Err((StatusCode::NOT_FOUND, "file not found".to_owned()));
|
|
}
|
|
if part.starts_with('.') && part != ".well-known" {
|
|
return Err((StatusCode::NOT_FOUND, "file not found".to_owned()));
|
|
}
|
|
parts.push(part);
|
|
}
|
|
if trailing {
|
|
parts.push("index.html");
|
|
}
|
|
let rel = parts.join("/");
|
|
if rel.is_empty() {
|
|
return Ok(entry.to_owned());
|
|
}
|
|
Ok(if root == "." {
|
|
rel
|
|
} else {
|
|
format!("{root}/{rel}")
|
|
})
|
|
}
|
|
|
|
fn static_read_command(path: &str) -> String {
|
|
format!(
|
|
"p={q}; if [ ! -f \"$p\" ]; then printf 'missing'; exit 0; fi; \
|
|
s=$(stat -c %s -- \"$p\" 2>/dev/null) || {{ printf 'missing'; exit 0; }}; \
|
|
if [ \"$s\" -gt {max} ]; then printf 'large'; exit 0; fi; \
|
|
printf 'ok\\n'; cat -- \"$p\"",
|
|
q = shquote(path),
|
|
max = STATIC_MAX_BYTES
|
|
)
|
|
}
|
|
|
|
enum StaticRead {
|
|
Body(Vec<u8>),
|
|
Missing,
|
|
Large,
|
|
}
|
|
|
|
fn parse_static_output(stdout: Vec<u8>) -> Option<StaticRead> {
|
|
let boundary = stdout.iter().position(|byte| *byte == b'\n');
|
|
let (head, body) = match boundary {
|
|
Some(index) => (&stdout[..index], stdout[index + 1..].to_vec()),
|
|
None => (&stdout[..], Vec::new()),
|
|
};
|
|
match head {
|
|
b"ok" => Some(StaticRead::Body(body)),
|
|
b"missing" => Some(StaticRead::Missing),
|
|
b"large" => Some(StaticRead::Large),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
fn content_type(path: &str) -> HeaderValue {
|
|
let mime = mime_guess::from_path(path).first_or_octet_stream();
|
|
let mut value = mime.to_string();
|
|
if value.starts_with("text/")
|
|
|| matches!(
|
|
value.as_str(),
|
|
"application/javascript" | "application/json" | "application/xml" | "image/svg+xml"
|
|
)
|
|
{
|
|
value.push_str("; charset=utf-8");
|
|
}
|
|
HeaderValue::from_str(&value)
|
|
.unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream"))
|
|
}
|
|
|
|
fn strip_hop_by_hop(headers: &mut HeaderMap) {
|
|
for name in [
|
|
header::CONNECTION,
|
|
HeaderName::from_static("keep-alive"),
|
|
HeaderName::from_static("proxy-authenticate"),
|
|
HeaderName::from_static("proxy-authorization"),
|
|
header::TE,
|
|
header::TRAILER,
|
|
header::TRANSFER_ENCODING,
|
|
header::UPGRADE,
|
|
] {
|
|
headers.remove(name);
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::config::Config;
|
|
|
|
fn secrets() -> (Secrets, std::path::PathBuf) {
|
|
let path = std::env::temp_dir().join(format!(
|
|
"rhema-together-preview-test-{}.key",
|
|
crate::util::random_id(10)
|
|
));
|
|
let secrets = Secrets::load_or_create(&path).expect("test key");
|
|
(secrets, path)
|
|
}
|
|
|
|
#[test]
|
|
fn a_preview_host_carries_room_port_expiry_and_signature() {
|
|
let config = Config {
|
|
preview_origin: "https://preview.example.com".into(),
|
|
..Default::default()
|
|
};
|
|
let (secrets, path) = secrets();
|
|
let url = url(&config, &secrets, "room123", 5173).expect("url");
|
|
let host = url
|
|
.trim_start_matches("https://")
|
|
.split('/')
|
|
.next()
|
|
.expect("host");
|
|
let claim = target_of_host(&config, host).expect("parsed host");
|
|
assert_eq!(claim.room, "room123");
|
|
assert_eq!(claim.target, HostTarget::Port(5173));
|
|
assert!(claim.expires >= crate::util::now_ms() / 1000);
|
|
assert_eq!(
|
|
claim.signature,
|
|
secrets.sign(&format!("room123:5173:{}", claim.expires))
|
|
);
|
|
let _ = std::fs::remove_file(path);
|
|
}
|
|
|
|
#[test]
|
|
fn a_static_target_refuses_hidden_paths() {
|
|
assert!(visible_rel_path(".env").is_err());
|
|
assert!(visible_rel_path(".git/config").is_err());
|
|
assert!(visible_rel_path("dist/../.env").is_err());
|
|
assert_eq!(visible_rel_path("dist").unwrap(), "dist");
|
|
assert_eq!(visible_rel_path(".").unwrap(), ".");
|
|
assert_eq!(visible_rel_path(".well-known").unwrap(), ".well-known");
|
|
}
|
|
|
|
#[test]
|
|
fn a_static_host_carries_the_target_and_signature() {
|
|
let config = Config {
|
|
preview_origin: "https://preview.example.com".into(),
|
|
..Default::default()
|
|
};
|
|
let (secrets, path) = secrets();
|
|
let target = PreviewTarget::Static {
|
|
path: "web/dist".into(),
|
|
root: "web/dist".into(),
|
|
entry: "web/dist/index.html".into(),
|
|
};
|
|
let url = url_for_target(&config, &secrets, "room123", &target).expect("url");
|
|
let host = url
|
|
.trim_start_matches("https://")
|
|
.split('/')
|
|
.next()
|
|
.expect("host");
|
|
let claim = target_of_host(&config, host).expect("parsed host");
|
|
assert_eq!(claim.room, "room123");
|
|
assert_eq!(
|
|
claim.signature,
|
|
secrets.sign(&format!(
|
|
"room123:static:{}:{}",
|
|
static_key("web/dist", "web/dist/index.html"),
|
|
claim.expires
|
|
))
|
|
);
|
|
assert!(matches!(claim.target, HostTarget::Static(_)));
|
|
let _ = std::fs::remove_file(path);
|
|
}
|
|
|
|
#[test]
|
|
fn the_old_host_shape_is_not_accepted() {
|
|
let config = Config {
|
|
preview_origin: "https://preview.example.com".into(),
|
|
..Default::default()
|
|
};
|
|
assert!(
|
|
target_of_host(
|
|
&config,
|
|
"rroom123-p5173-0123456789abcdef01234567.preview.example.com"
|
|
)
|
|
.is_none()
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn static_paths_stay_inside_the_root() {
|
|
let uri: Uri = "/assets/app.js?version=2".parse().unwrap();
|
|
assert_eq!(
|
|
static_request_path(&uri, "dist", "dist/index.html").unwrap(),
|
|
"dist/assets/app.js"
|
|
);
|
|
let uri: Uri = "/".parse().unwrap();
|
|
assert_eq!(
|
|
static_request_path(&uri, "dist", "dist/index.html").unwrap(),
|
|
"dist/index.html"
|
|
);
|
|
let uri: Uri = "/docs/".parse().unwrap();
|
|
assert_eq!(
|
|
static_request_path(&uri, "dist", "dist/index.html").unwrap(),
|
|
"dist/docs/index.html"
|
|
);
|
|
let uri: Uri = "/../secret".parse().unwrap();
|
|
assert!(static_request_path(&uri, "dist", "dist/index.html").is_err());
|
|
let uri: Uri = "/%2e%2e/secret".parse().unwrap();
|
|
assert!(static_request_path(&uri, "dist", "dist/index.html").is_err());
|
|
let uri: Uri = "/.env".parse().unwrap();
|
|
assert!(static_request_path(&uri, "dist", "dist/index.html").is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn a_single_file_uses_its_parent_as_the_root() {
|
|
let uri: Uri = "/".parse().unwrap();
|
|
assert_eq!(
|
|
static_request_path(&uri, ".", "index.html").unwrap(),
|
|
"index.html"
|
|
);
|
|
let uri: Uri = "/style.css".parse().unwrap();
|
|
assert_eq!(
|
|
static_request_path(&uri, ".", "index.html").unwrap(),
|
|
"style.css"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn static_reads_split_the_status_from_the_body() {
|
|
assert!(matches!(
|
|
parse_static_output(b"ok\n<html></html>".to_vec()),
|
|
Some(StaticRead::Body(body)) if body == b"<html></html>"
|
|
));
|
|
assert!(matches!(
|
|
parse_static_output(b"missing".to_vec()),
|
|
Some(StaticRead::Missing)
|
|
));
|
|
assert!(matches!(
|
|
parse_static_output(b"large".to_vec()),
|
|
Some(StaticRead::Large)
|
|
));
|
|
assert!(parse_static_output(Vec::new()).is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn text_types_get_a_charset() {
|
|
assert_eq!(content_type("index.html"), "text/html; charset=utf-8");
|
|
assert_eq!(content_type("app.js"), "text/javascript; charset=utf-8");
|
|
assert_eq!(content_type("logo.png"), "image/png");
|
|
}
|
|
|
|
#[test]
|
|
fn signatures_compare_by_value() {
|
|
assert!(signatures_match("abcd", "abcd"));
|
|
assert!(!signatures_match("abcd", "abce"));
|
|
assert!(!signatures_match("abcd", "abc"));
|
|
}
|
|
}
|