Skip to content

A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.

mux-server: accept browser clients on a web port

RoversXe34f12dc5915
diff --git a/Cargo.lock b/Cargo.lock
index 98e6cdc5..373a9bb4 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5933,6 +5933,21 @@ dependencies = [
"windows-sys 0.60.2",
]
+[[package]]
+name = "soketto"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2e859df029d160cb88608f5d7df7fb4753fd20fdfb4de5644f3d8b8440841721"
+dependencies = [
+ "base64 0.22.1",
+ "bytes",
+ "futures",
+ "httparse",
+ "log",
+ "rand 0.8.5",
+ "sha1",
+]
+
[[package]]
name = "spa"
version = "0.3.1"
@@ -7450,8 +7465,6 @@ dependencies = [
[[package]]
name = "varbincode"
version = "0.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b712fa900b441e2d5226a094ca37ca70c0d26d26b79822a5cf34a853a9e26f9f"
dependencies = [
"byteorder",
"leb128",
@@ -8222,6 +8235,7 @@ dependencies = [
"portable-pty",
"promise",
"signal-hook",
+ "smol",
"umask",
"wezterm-blob-leases 0.1.1",
"wezterm-gui-subcommands",
@@ -8237,11 +8251,15 @@ dependencies = [
"anyhow",
"async-io",
"async_ossl",
+ "base64 0.22.1",
"codec",
"config",
"dns-lookup",
"futures",
+ "getrandom 0.3.4",
+ "hex",
"hostname",
+ "httparse",
"lazy_static",
"libc",
"log",
@@ -8255,7 +8273,10 @@ dependencies = [
"rcgen",
"serde",
"serde_json",
+ "sha1",
+ "sha2",
"smol",
+ "soketto",
"tempfile",
"termwiz 0.24.0",
"thinkterm-proto",
diff --git a/Cargo.toml b/Cargo.toml
index 55b16dd2..e90cb3f1 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -131,6 +131,7 @@ governor = {version="0.5", default-features=false, features=["std"]}
guillotiere = "0.6"
harfbuzz = { path = "deps/harfbuzz" }
heapless = "0.8"
+httparse = "1.10"
hdrhistogram = "7.1"
hex = {version="0.4", default-features=false}
hostname = "0.4"
@@ -217,6 +218,7 @@ serde_with = {version="2.0", features = ["chrono_0_4"]}
serde_yaml = "0.9"
semver = "1.0"
serial2 = "0.2"
+sha1 = "0.10"
sha2 = "0.10"
share-data = { path = "lua-api-crates/share-data" }
shared_library = "0.1"
@@ -226,6 +228,7 @@ signal-hook = "0.3"
siphasher = "1.0.1"
smithay-client-toolkit = {version = "0.19", default-features=false}
smol = "2.0"
+soketto = "0.8"
socket2 = "0.5"
spa = "0.3.1"
spawn-funcs = { path = "lua-api-crates/spawn-funcs" }
@@ -310,3 +313,5 @@ zvariant = "4.0"
# We use our own vendored cairo, which has minimal deps and should just
# build via cargo.
cairo-sys-rs = {path="deps/cairo", version="0.18.0"}
+# Vendored to bound allocations by the bytes present, not by declared lengths.
+varbincode = {path="deps/varbincode", version="0.1.0"}
diff --git a/codec/src/lib.rs b/codec/src/lib.rs
index 9cf63022..1301c97a 100644
--- a/codec/src/lib.rs
+++ b/codec/src/lib.rs
@@ -25,6 +25,7 @@ use futures_lite::io::AsyncWriteExt;
use futures_lite::prelude::*;
use std::collections::HashMap;
use std::convert::TryInto;
+use std::convert::TryFrom;
use std::io::Cursor;
use std::ops::Range;
use std::path::PathBuf;
@@ -175,6 +176,28 @@ struct Decoded {
is_compressed: bool,
}
+/// The largest payload a PDU may declare. Nothing legitimate comes near
+/// it (a pane's worth of lines with images is megabytes); anything past it
+/// is a corrupt or hostile header, refused before a byte is allocated for
+/// it rather than aborting the process when the allocation fails.
+pub const MAX_PDU_PAYLOAD: usize = 256 * 1024 * 1024;
+/// How much of a payload is allocated at a time while it is read.
+const PAYLOAD_READ_STEP: usize = 1024 * 1024;
+/// The most a compressed payload may inflate to. Bounded separately from
+/// the wire length: a small frame can otherwise expand without limit.
+const MAX_DECOMPRESSED: u64 = 1024 * 1024 * 1024;
+
+fn check_payload_length(data_len: usize, len: u64, serial: u64, ident: u64) -> anyhow::Result<()> {
+ if data_len > MAX_PDU_PAYLOAD {
+ return Err(CorruptResponse(format!(
+ "PDU payload of {data_len} bytes (len:{len} serial:{serial} ident:{ident}) \
+ exceeds the {MAX_PDU_PAYLOAD} byte limit"
+ ))
+ .into());
+ }
+ Ok(())
+}
+
/// Decode a frame.
/// See encode_raw() for the frame format.
async fn decode_raw_async<R: Unpin + AsyncRead + std::fmt::Debug>(
@@ -205,7 +228,10 @@ async fn decode_raw_async<R: Unpin + AsyncRead + std::fmt::Debug>(
.await
.context("decode_raw_async failed to read PDU ident")?;
let data_len =
- match (len as usize).overflowing_sub(encoded_length(ident) + encoded_length(serial)) {
+ match usize::try_from(len)
+ .map_err(|_| CorruptResponse(format!("PDU length {len} does not fit in memory")))?
+ .overflowing_sub(encoded_length(ident) + encoded_length(serial))
+ {
(_, true) => {
return Err(CorruptResponse(format!(
"decode_raw_async: sizes don't make sense: \
@@ -218,20 +244,28 @@ async fn decode_raw_async<R: Unpin + AsyncRead + std::fmt::Debug>(
(data_len, false) => data_len,
};
+ check_payload_length(data_len, len, serial, ident)?;
if is_compressed {
metrics::histogram!("pdu.decode.compressed.size").record(data_len as f64);
} else {
metrics::histogram!("pdu.decode.size").record(data_len as f64);
}
- let mut data = vec![0u8; data_len];
- r.read_exact(&mut data).await.with_context(|| {
- format!(
- "decode_raw_async failed to read {} bytes of data \
- for PDU of length {} with serial={} ident={}",
- data_len, len, serial, ident
- )
- })?;
+ // Grown as the bytes arrive: the declared length is a peer's claim,
+ // and must not cost anything before the bytes do.
+ let mut data = Vec::with_capacity(data_len.min(PAYLOAD_READ_STEP));
+ while data.len() < data_len {
+ let start = data.len();
+ let chunk = (data_len - start).min(PAYLOAD_READ_STEP);
+ data.resize(start + chunk, 0);
+ r.read_exact(&mut data[start..]).await.with_context(|| {
+ format!(
+ "decode_raw_async failed to read {} bytes of data \
+ for PDU of length {} with serial={} ident={}",
+ data_len, len, serial, ident
+ )
+ })?;
+ }
Ok(Decoded {
ident,
serial,
@@ -252,7 +286,10 @@ fn decode_raw<R: std::io::Read>(mut r: R) -> anyhow::Result<Decoded> {
let serial = read_u64(r.by_ref()).context("reading PDU serial")?;
let ident = read_u64(r.by_ref()).context("reading PDU ident")?;
let data_len =
- match (len as usize).overflowing_sub(encoded_length(ident) + encoded_length(serial)) {
+ match usize::try_from(len)
+ .map_err(|_| CorruptResponse(format!("PDU length {len} does not fit in memory")))?
+ .overflowing_sub(encoded_length(ident) + encoded_length(serial))
+ {
(_, true) => {
anyhow::bail!(
"sizes don't make sense: len:{} serial:{} (enc={}) ident:{} (enc={})",
@@ -266,19 +303,25 @@ fn decode_raw<R: std::io::Read>(mut r: R) -> anyhow::Result<Decoded> {
(data_len, false) => data_len,
};
+ check_payload_length(data_len, len, serial, ident)?;
if is_compressed {
metrics::histogram!("pdu.decode.compressed.size").record(data_len as f64);
} else {
metrics::histogram!("pdu.decode.size").record(data_len as f64);
}
- let mut data = vec![0u8; data_len];
- r.read_exact(&mut data).with_context(|| {
- format!(
- "reading {} bytes of data for PDU of length {} with serial={} ident={}",
- data_len, len, serial, ident
- )
- })?;
+ let mut data = Vec::with_capacity(data_len.min(PAYLOAD_READ_STEP));
+ while data.len() < data_len {
+ let start = data.len();
+ let chunk = (data_len - start).min(PAYLOAD_READ_STEP);
+ data.resize(start + chunk, 0);
+ r.read_exact(&mut data[start..]).with_context(|| {
+ format!(
+ "reading {} bytes of data for PDU of length {} with serial={} ident={}",
+ data_len, len, serial, ident
+ )
+ })?;
+ }
Ok(Decoded {
ident,
serial,
@@ -352,12 +395,14 @@ fn deserialize<T: serde::de::DeserializeOwned, R: std::io::Read>(
) -> Result<T, Error> {
if is_compressed {
#[cfg(not(target_family = "wasm"))]
- let mut decompress = zstd::Decoder::new(r)?;
+ let decompress = zstd::Decoder::new(r)?;
// The pure-Rust decoder stands in where the zstd C library cannot
// build; it also implements std::io::Read, so the shape is identical.
#[cfg(target_family = "wasm")]
- let mut decompress = ruzstd::decoding::StreamingDecoder::new(r)
+ let decompress = ruzstd::decoding::StreamingDecoder::new(r)
.map_err(|e| anyhow::anyhow!("ruzstd: {e}"))?;
+ use std::io::Read as _;
+ let mut decompress = decompress.take(MAX_DECOMPRESSED);
let mut decode = varbincode::Deserializer::new(&mut decompress);
serde::Deserialize::deserialize(&mut decode).map_err(Into::into)
} else {
@@ -528,7 +573,10 @@ macro_rules! pdu {
/// answer 64 and mis-decode every render push.
/// 66: CommandSpec carries require_cwd, so a spawn whose named directory
/// cannot be opened fails on the server instead of landing in `$HOME`.
-pub const CODEC_VERSION: usize = 66;
+/// 67: Web tokens: the credential a browser presents at the server's web
+/// port is minted, listed and revoked over the mux connection
+/// (WebTokenMint/List/Revoke), the way TLS credentials are obtained.
+pub const CODEC_VERSION: usize = 67;
// Defines the Pdu enum.
// Each struct has an explicit identifying number.
@@ -611,6 +659,12 @@ pdu! {
GetAgentStatusesResponse: 82,
GetServerOsRelease: 83,
GetServerOsReleaseResponse: 84,
+ WebTokenMint: 85,
+ WebTokenMintResponse: 86,
+ WebTokenList: 87,
+ WebTokenListResponse: 88,
+ WebTokenRevoke: 89,
+ WebTokenRevokeResponse: 90,
}
impl Pdu {
@@ -795,6 +849,64 @@ pub struct GetTlsCredsResponse {
pub client_cert_pem: String,
}
+/// Mint a web token: the bearer credential a browser presents when it
+/// opens the server's web port. Like TLS credentials, it is full access as
+/// the server's user; unlike them it can expire and be revoked.
+#[derive(Deserialize, Serialize, PartialEq, Debug)]
+pub struct WebTokenMint {
+ /// A name for `web-token list`; the connecting browser is shown under
+ /// it in `list-clients`.
+ pub label: Option<String>,
+ /// Lifetime in seconds. None means until revoked or the server forgets
+ /// it (a restart, when tokens are not persisted).
+ pub ttl_secs: Option<u64>,
+}
+
+#[derive(Deserialize, Serialize, PartialEq, Debug)]
+pub struct WebTokenMintResponse {
+ pub id: String,
+ pub label: String,
+ /// The secret. Shown once; the server keeps only a digest.
+ pub token: String,
+ /// Unix seconds.
+ pub expires_at: Option<u64>,
+ /// Ready-to-open URLs, one per spelling of each web listener, with
+ /// the token in the URL fragment for the page to pick up (never sent
+ /// to the server, never in a Referer).
+ pub urls: Vec<String>,
+}
+
+#[derive(Deserialize, Serialize, PartialEq, Debug)]
+pub struct WebTokenList {}
+
+#[derive(Deserialize, Serialize, PartialEq, Debug, Clone)]
+pub struct WebTokenInfo {
+ pub id: String,
+ pub label: String,
+ /// Unix seconds.
+ pub created_at: u64,
+ pub expires_at: Option<u64>,
+ pub last_used_at: Option<u64>,
+ pub live_connections: u32,
+}
+
+#[derive(Deserialize, Serialize, PartialEq, Debug)]
+pub struct WebTokenListResponse {
+ pub tokens: Vec<WebTokenInfo>,
+}
+
+/// Revoke one token by id, or every token when `id` is None. Connections
+/// admitted by a revoked token are dropped at once.
+#[derive(Deserialize, Serialize, PartialEq, Debug)]
+pub struct WebTokenRevoke {
+ pub id: Option<String>,
+}
+
+#[derive(Deserialize, Serialize, PartialEq, Debug)]
+pub struct WebTokenRevokeResponse {
+ pub revoked: u32,
+}
+
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct ListPanes {}
@@ -2028,6 +2140,23 @@ mod test {
/// The wasm client's receive path: a native server compresses with the
/// zstd C library, the wasm side decodes with pure-Rust ruzstd. Proven
/// here on native, where both libraries are available.
+ #[test]
+ fn a_pdu_declaring_an_absurd_length_is_refused_before_allocation() {
+ // A frame whose header claims a 2^40 byte payload, then nothing.
+ let mut bytes = Vec::new();
+ leb128::write::unsigned(&mut bytes, 1u64 << 40).unwrap();
+ leb128::write::unsigned(&mut bytes, 1).unwrap(); // serial
+ leb128::write::unsigned(&mut bytes, 1).unwrap(); // ident
+ let err = Pdu::decode(std::io::Cursor::new(bytes.clone())).expect_err("refused");
+ assert!(format!("{:#}", err).contains("exceeds"), "{:#}", err);
+ let err = futures_lite::future::block_on(Pdu::decode_async(
+ &mut futures_lite::io::Cursor::new(bytes),
+ None,
+ ))
+ .expect_err("refused");
+ assert!(format!("{:#}", err).contains("exceeds"), "{:#}", err);
+ }
+
#[test]
fn ruzstd_decodes_zstd_output() {
let payload: Vec<u8> = (0u32..500).flat_map(|v| v.to_le_bytes()).collect();
@@ -2254,7 +2383,7 @@ mod test {
// The exact assertion is the tripwire: whoever bumps the codec must
// come here, confirm the round-trips still cover the new version,
// and advance it deliberately.
- assert_eq!(CODEC_VERSION, 66);
+ assert_eq!(CODEC_VERSION, 67);
use thinkterm_proto::{AgentEvidence, AgentState, AgentStatus};
fn round_trip(pdu: Pdu) {
diff --git a/config/src/config.rs b/config/src/config.rs
index 22c5a230..3b1cd043 100644
--- a/config/src/config.rs
+++ b/config/src/config.rs
@@ -4,6 +4,7 @@ use crate::color::{
ColorSchemeFile, HsbTransform, Palette, SrgbaTuple, TabBarStyle, WindowFrameConfig,
};
use crate::daemon::DaemonOptions;
+use crate::web::WebServer;
use crate::exec_domain::ExecDomain;
use crate::font::{
AllowSquareGlyphOverflow, DisplayPixelGeometry, FontLocatorSelection, FontRasterizerSelection,
@@ -407,6 +408,12 @@ pub struct Config {
#[dynamic(default)]
pub tls_servers: Vec<TlsDomainServer>,
+ /// When running in server mode, web entries: each serves the browser
+ /// client's bundle over HTTP and accepts its WebSocket, admitted by a
+ /// web token. Read at server start, like `tls_servers`.
+ #[dynamic(default)]
+ pub web_servers: Vec<WebServer>,
+
/// The set of tls domains that we can connect to as a client
#[dynamic(default)]
pub tls_clients: Vec<TlsDomainClient>,
diff --git a/config/src/lib.rs b/config/src/lib.rs
index 66afe1a9..9aaeb0b3 100644
--- a/config/src/lib.rs
+++ b/config/src/lib.rs
@@ -41,6 +41,7 @@ mod tls;
mod units;
mod unix;
mod version;
+mod web;
pub mod window;
mod wsl;
@@ -61,6 +62,7 @@ pub use tls::*;
pub use units::*;
pub use unix::*;
pub use version::*;
+pub use web::*;
pub use wsl::*;
type ErrorCallback = fn(&str);
diff --git a/config/src/web.rs b/config/src/web.rs
new file mode 100644
index 00000000..2305393f
--- /dev/null
+++ b/config/src/web.rs
@@ -0,0 +1,348 @@
+use crate::*;
+use std::path::PathBuf;
+use wezterm_dynamic::{FromDynamic, ToDynamic};
+
+/// A web entry to the multiplexer: one TCP port that serves the browser
+/// client's bundle over HTTP and accepts its WebSocket. Every WebSocket
+/// must present a web token minted with `thinkterm cli web-token mint`;
+/// the token equals full access as the server's user, exactly like the
+/// unix socket and the TLS credentials.
+///
+/// Like `tls_servers`, these are read when the server starts; a config
+/// reload does not open or close web ports.
+#[derive(Debug, Clone, FromDynamic, ToDynamic)]
+pub struct WebServer {
+ /// The address:port to listen on. Loopback by default: browsers only
+ /// expose WebGPU to secure contexts, and `http://localhost` is one
+ /// while a plain `http://` to any other host is not.
+ #[dynamic(default = "default_web_bind_address")]
+ pub bind_address: String,
+
+ /// The path to an x509 PEM encoded private key file. Setting this and
+ /// `pem_cert` turns the port into `https`/`wss`.
+ pub pem_private_key: Option<PathBuf>,
+
+ /// The path to an x509 PEM encoded certificate file.
+ pub pem_cert: Option<PathBuf>,
+
+ /// The path to an x509 PEM encoded CA chain file.
+ pub pem_ca: Option<PathBuf>,
+
+ /// Where the browser client's `index.html`, JavaScript and wasm live.
+ /// Defaults to the `share/thinkterm/web` directory next to the
+ /// installed executable.
+ pub static_dir: Option<PathBuf>,
+
+ /// Where minted tokens are kept (as digests, never the tokens
+ /// themselves). Unset means memory only: a restart of the server
+ /// forgets every token.
+ pub token_file: Option<PathBuf>,
+
+ /// Origins allowed to open the WebSocket. Empty means "this
+ /// listener's own address", which is what a page served from the same
+ /// port sends. A page served from anywhere else must be listed.
+ #[dynamic(default)]
+ pub allowed_origins: Vec<String>,
+
+ /// Refuse to start without TLS when `bind_address` is not loopback.
+ /// Off, the port still works, but a browser reaching it over plain
+ /// `http://` has no WebGPU and shows nothing. Leave this on and use
+ /// `ssh -L` to reach a remote server instead.
+ #[dynamic(default = "default_true")]
+ pub require_tls_off_loopback: bool,
+}
+
+fn default_web_bind_address() -> String {
+ "127.0.0.1:8088".to_string()
+}
+
+impl Default for WebServer {
+ fn default() -> Self {
+ Self {
+ bind_address: default_web_bind_address(),
+ pem_private_key: None,
+ pem_cert: None,
+ pem_ca: None,
+ static_dir: None,
+ token_file: None,
+ allowed_origins: vec![],
+ require_tls_off_loopback: true,
+ }
+ }
+}
+
+/// The host and port of an authority (`host`, `host:port`, `[v6]:port`),
+/// host lowercase with any brackets removed. `None` when it is not one.
+pub fn split_authority(authority: &str) -> Option<(String, Option<u16>)> {
+ let authority = authority.trim();
+ if authority.is_empty() || authority.contains(['/', '?', '#', '@', ' ']) {
+ return None;
+ }
+ let (host, port) = if let Some(rest) = authority.strip_prefix('[') {
+ let (v6, after) = rest.split_once(']')?;
+ match after {
+ "" => (v6, None),
+ p => (v6, Some(p.strip_prefix(':')?.parse::<u16>().ok()?)),
+ }
+ } else {
+ match authority.rsplit_once(':') {
+ // A bare IPv6 literal has several colons and no brackets.
+ Some((host, port)) if !host.contains(':') => {
+ (host, Some(port.parse::<u16>().ok()?))
+ }
+ _ => (authority, None),
+ }
+ };
+ if host.is_empty() {
+ return None;
+ }
+ Some((host.to_ascii_lowercase(), port))
+}
+
+/// The port a URL without one means.
+pub fn default_port(scheme: &str) -> Option<u16> {
+ match scheme {
+ "http" | "ws" => Some(80),
+ "https" | "wss" => Some(443),
+ _ => None,
+ }
+}
+
+/// A name that can only ever mean this machine.
+pub fn is_loopback_host(host: &str) -> bool {
+ match host.parse::<std::net::IpAddr>() {
+ Ok(ip) => ip.is_loopback(),
+ Err(_) => host.eq_ignore_ascii_case("localhost"),
+ }
+}
+
+/// An origin taken apart: scheme, host and the port it means (the
+/// scheme's default when the string carries none).
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Origin {
+ pub scheme: String,
+ pub host: String,
+ pub port: Option<u16>,
+ /// The port as written, if any: a `Host` header names the same
+ /// authority without a scheme to default from.
+ pub port_given: Option<u16>,
+}
+
+impl Origin {
+ pub fn parse(origin: &str) -> Option<Self> {
+ let origin = origin.trim().trim_end_matches('/');
+ let (scheme, authority) = origin.split_once("://")?;
+ let scheme = scheme.to_ascii_lowercase();
+ let (host, port) = split_authority(authority)?;
+ Some(Self {
+ port: port.or(default_port(&scheme)),
+ port_given: port,
+ scheme,
+ host,
+ })
+ }
+
+ /// The same origin, however its port was spelled.
+ pub fn same_as(&self, other: &Origin) -> bool {
+ self.scheme == other.scheme && self.host == other.host && self.port == other.port
+ }
+}
+
+impl WebServer {
+ pub fn uses_tls(&self) -> bool {
+ self.pem_cert.is_some() && self.pem_private_key.is_some()
+ }
+
+ /// A certificate without its key, or the reverse.
+ pub fn tls_half_configured(&self) -> bool {
+ self.pem_cert.is_some() != self.pem_private_key.is_some()
+ }
+
+ pub fn scheme(&self) -> &'static str {
+ if self.uses_tls() {
+ "https"
+ } else {
+ "http"
+ }
+ }
+
+ /// The host and port parts of `bind_address`.
+ pub fn host_and_port(&self) -> (String, Option<u16>) {
+ match self.bind_address.rsplit_once(':') {
+ Some((host, port)) if !host.is_empty() => {
+ let host = host.trim_start_matches('[').trim_end_matches(']');
+ (host.to_string(), port.parse().ok())
+ }
+ _ => (self.bind_address.clone(), None),
+ }
+ }
+
+ pub fn is_loopback(&self) -> bool {
+ let (host, _) = self.host_and_port();
+ match host.parse::<std::net::IpAddr>() {
+ Ok(ip) => ip.is_loopback(),
+ Err(_) => host == "localhost",
+ }
+ }
+
+ /// The `host[:port]` values a browser will send in `Host:` and use in
+ /// a URL. A loopback listener answers to both spellings of itself.
+ /// A scheme's default port is left out, as a browser leaves it out.
+ pub fn url_hosts(&self) -> Vec<String> {
+ let (host, port) = self.host_and_port();
+ let shown = port.filter(|p| Some(*p) != default_port(self.scheme()));
+ let with_port = |h: &str| match shown {
+ Some(p) => format!("{h}:{p}"),
+ None => h.to_string(),
+ };
+ let mut hosts = vec![];
+ let ip = host.parse::<std::net::IpAddr>().ok();
+ match ip {
+ Some(ip) if ip.is_loopback() => {
+ hosts.push(with_port("127.0.0.1"));
+ hosts.push(with_port("localhost"));
+ hosts.push(with_port("[::1]"));
+ }
+ Some(ip) if ip.is_unspecified() => {
+ // Bound everywhere: any name reaches it, and the listener
+ // cannot enumerate them. Loopback spellings at least.
+ hosts.push(with_port("127.0.0.1"));
+ hosts.push(with_port("localhost"));
+ hosts.push(with_port("[::1]"));
+ }
+ Some(std::net::IpAddr::V6(v6)) => hosts.push(with_port(&format!("[{v6}]"))),
+ _ => hosts.push(with_port(&host)),
+ }
+ hosts
+ }
+
+ /// The origins the upgrade accepts: the configured list, or every
+ /// spelling of this listener's own address.
+ pub fn effective_allowed_origins(&self) -> Vec<String> {
+ if !self.allowed_origins.is_empty() {
+ return self.allowed_origins.clone();
+ }
+ let scheme = self.scheme();
+ self.url_hosts()
+ .into_iter()
+ .map(|host| format!("{scheme}://{host}"))
+ .collect()
+ }
+
+ /// The URLs a person can open to reach this listener: the configured
+ /// origins when there are any (that is where the page is reached),
+ /// else every spelling of the bind address.
+ pub fn urls(&self) -> Vec<String> {
+ if !self.allowed_origins.is_empty() {
+ return self
+ .allowed_origins
+ .iter()
+ .map(|origin| format!("{}/", origin.trim_end_matches('/')))
+ .collect();
+ }
+ let scheme = self.scheme();
+ self.url_hosts()
+ .into_iter()
+ .map(|host| format!("{scheme}://{host}/"))
+ .collect()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn loopback_listener_answers_to_every_spelling_of_itself() {
+ let server = WebServer::default();
+ assert!(server.is_loopback());
+ assert_eq!(
+ server.effective_allowed_origins(),
+ vec![
+ "http://127.0.0.1:8088",
+ "http://localhost:8088",
+ "http://[::1]:8088"
+ ]
+ );
+ }
+
+ #[test]
+ fn a_named_host_with_tls_is_https_and_only_itself() {
+ let server = WebServer {
+ bind_address: "mux.example.net:8443".into(),
+ pem_cert: Some("/c.pem".into()),
+ pem_private_key: Some("/k.pem".into()),
+ ..WebServer::default()
+ };
+ assert!(!server.is_loopback());
+ assert_eq!(server.urls(), vec!["https://mux.example.net:8443/"]);
+ assert_eq!(
+ server.effective_allowed_origins(),
+ vec!["https://mux.example.net:8443"]
+ );
+ }
+
+ #[test]
+ fn configured_origins_win_and_name_the_urls() {
+ let server = WebServer {
+ allowed_origins: vec!["https://app.example.net".into()],
+ ..WebServer::default()
+ };
+ assert_eq!(
+ server.effective_allowed_origins(),
+ vec!["https://app.example.net"]
+ );
+ assert_eq!(server.urls(), vec!["https://app.example.net/"]);
+ }
+
+ #[test]
+ fn default_ports_are_left_out_as_browsers_leave_them_out() {
+ let server = WebServer {
+ bind_address: "mux.example.net:443".into(),
+ pem_cert: Some("/c.pem".into()),
+ pem_private_key: Some("/k.pem".into()),
+ ..WebServer::default()
+ };
+ assert_eq!(server.urls(), vec!["https://mux.example.net/"]);
+ assert_eq!(
+ server.effective_allowed_origins(),
+ vec!["https://mux.example.net"]
+ );
+ }
+
+ #[test]
+ fn authorities_and_origins_take_apart() {
+ assert_eq!(split_authority("Localhost:8088"), Some(("localhost".into(), Some(8088))));
+ assert_eq!(split_authority("localhost"), Some(("localhost".into(), None)));
+ assert_eq!(split_authority("[::1]:9000"), Some(("::1".into(), Some(9000))));
+ assert_eq!(split_authority("[::1]"), Some(("::1".into(), None)));
+ assert_eq!(split_authority("::1"), Some(("::1".into(), None)));
+ assert_eq!(split_authority("host:x"), None);
+ assert_eq!(split_authority("a/b"), None);
+ assert_eq!(split_authority(""), None);
+ assert_eq!(
+ Origin::parse("HTTPS://App.Example.net/"),
+ Some(Origin {
+ scheme: "https".into(),
+ host: "app.example.net".into(),
+ port: Some(443),
+ port_given: None
+ })
+ );
+ assert_eq!(
+ Origin::parse("http://localhost:9000"),
+ Some(Origin {
+ scheme: "http".into(),
+ host: "localhost".into(),
+ port: Some(9000),
+ port_given: Some(9000)
+ })
+ );
+ assert_eq!(Origin::parse("null"), None);
+ assert!(is_loopback_host("127.0.0.1"));
+ assert!(is_loopback_host("::1"));
+ assert!(is_loopback_host("LOCALHOST"));
+ assert!(!is_loopback_host("10.0.0.5"));
+ assert!(!is_loopback_host("localhost.example"));
+ }
+}
diff --git a/deps/varbincode/Cargo.toml b/deps/varbincode/Cargo.toml
new file mode 100644
index 00000000..7bb61dce
--- /dev/null
+++ b/deps/varbincode/Cargo.toml
@@ -0,0 +1,21 @@
+# Vendored from crates.io varbincode 0.1.0 (Wez Furlong, MIT) with one
+# change: a declared byte/string length no longer allocates up front, so a
+# corrupt or hostile length costs only the bytes actually present in the
+# stream instead of aborting the process on allocation failure.
+[package]
+name = "varbincode"
+version = "0.1.0"
+authors = ["Wez Furlong <[email protected]>"]
+edition = "2018"
+description = "A binary encoder / decoder with variable length integer encoding implementation in Rust."
+license = "MIT"
+repository = "https://github.com/wez/varbincode"
+publish = false
+
+[dependencies]
+byteorder = "1.3"
+leb128 = "0.2"
+serde = "1.0"
+
+[dev-dependencies]
+serde_derive = "1.0"
diff --git a/deps/varbincode/src/de.rs b/deps/varbincode/src/de.rs
new file mode 100644
index 00000000..224ab6ed
--- /dev/null
+++ b/deps/varbincode/src/de.rs
@@ -0,0 +1,392 @@
+use crate::error::{Error, Result};
+use byteorder::{LittleEndian, ReadBytesExt};
+use serde::de::IntoDeserializer;
+
+pub struct Deserializer<'a> {
+ reader: &'a mut std::io::Read,
+}
+
+impl<'a> Deserializer<'a> {
+ pub fn new(reader: &'a mut std::io::Read) -> Self {
+ Self { reader }
+ }
+
+ fn read_signed(&mut self) -> Result<i64> {
+ leb128::read::signed(&mut self.reader).map_err(Into::into)
+ }
+
+ fn read_unsigned(&mut self) -> Result<u64> {
+ leb128::read::unsigned(&mut self.reader).map_err(Into::into)
+ }
+
+ fn read_vec(&mut self) -> Result<Vec<u8>> {
+ let len: usize = serde::Deserialize::deserialize(&mut *self)?;
+ // Grow as the bytes arrive rather than trusting the declared
+ // length: the stream, not the header, bounds the allocation.
+ const STEP: usize = 64 * 1024;
+ let mut result = Vec::with_capacity(len.min(STEP));
+ let mut remaining = len;
+ while remaining > 0 {
+ let chunk = remaining.min(STEP);
+ let start = result.len();
+ result.resize(start + chunk, 0);
+ self.reader.read_exact(&mut result[start..])?;
+ remaining -= chunk;
+ }
+ Ok(result)
+ }
+
+ fn read_string(&mut self) -> Result<String> {
+ let vec = self.read_vec()?;
+ String::from_utf8(vec).map_err(|e| Error::InvalidUtf8Encoding(e.utf8_error()))
+ }
+}
+
+macro_rules! impl_uint {
+ ($ty:ty, $dser_method:ident, $visitor_method:ident, $reader_method:ident) => {
+ #[inline]
+ fn $dser_method<V>(self, visitor: V) -> Result<V::Value>
+ where V: serde::de::Visitor<'de>,
+ {
+ let value = self.$reader_method()?;
+ if value > <$ty>::max_value() as u64 {
+ Err(Error::NumberOutOfRange)
+ } else {
+ visitor.$visitor_method(value as $ty)
+ }
+ }
+ }
+}
+
+macro_rules! impl_int {
+ ($ty:ty, $dser_method:ident, $visitor_method:ident, $reader_method:ident) => {
+ #[inline]
+ fn $dser_method<V>(self, visitor: V) -> Result<V::Value>
+ where V: serde::de::Visitor<'de>,
+ {
+ let value = self.$reader_method()?;
+ if value < <$ty>::min_value() as i64 || value > <$ty>::max_value() as i64 {
+ Err(Error::NumberOutOfRange)
+ } else {
+ visitor.$visitor_method(value as $ty)
+ }
+ }
+ }
+}
+macro_rules! impl_float {
+ ($dser_method:ident, $visitor_method:ident, $reader_method:ident) => {
+ #[inline]
+ fn $dser_method<V>(self, visitor: V) -> Result<V::Value>
+ where V: serde::de::Visitor<'de>,
+ {
+ let value = self.reader.$reader_method::<LittleEndian>()?;
+ visitor.$visitor_method(value)
+ }
+ }
+}
+
+impl<'de, 'a, 'b> serde::Deserializer<'de> for &'a mut Deserializer<'b> {
+ type Error = Error;
+
+ #[inline]
+ fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value>
+ where
+ V: serde::de::Visitor<'de>,
+ {
+ visitor.visit_u8(self.reader.read_u8()?)
+ }
+
+ #[inline]
+ fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value>
+ where
+ V: serde::de::Visitor<'de>,
+ {
+ visitor.visit_i8(self.reader.read_i8()?)
+ }
+
+ impl_uint!(u16, deserialize_u16, visit_u16, read_unsigned);
+ impl_uint!(u32, deserialize_u32, visit_u32, read_unsigned);
+ impl_uint!(u64, deserialize_u64, visit_u64, read_unsigned);
+
+ impl_int!(i16, deserialize_i16, visit_i16, read_signed);
+ impl_int!(i32, deserialize_i32, visit_i32, read_signed);
+ impl_int!(i64, deserialize_i64, visit_i64, read_signed);
+
+ impl_float!(deserialize_f32, visit_f32, read_f32);
+ impl_float!(deserialize_f64, visit_f64, read_f64);
+
+ #[inline]
+ fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value>
+ where
+ V: serde::de::Visitor<'de>,
+ {
+ Err(Error::DeserializeAnyNotSupported)
+ }
+
+ fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value>
+ where
+ V: serde::de::Visitor<'de>,
+ {
+ let value: u8 = serde::Deserialize::deserialize(self)?;
+ match value {
+ 1 => visitor.visit_bool(true),
+ 0 => visitor.visit_bool(false),
+ value => Err(Error::InvalidBoolEncoding(value).into()),
+ }
+ }
+
+ fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value>
+ where
+ V: serde::de::Visitor<'de>,
+ {
+ visitor.visit_unit()
+ }
+
+ fn deserialize_char<V>(self, visitor: V) -> Result<V::Value>
+ where
+ V: serde::de::Visitor<'de>,
+ {
+ let value: u32 = serde::Deserialize::deserialize(self)?;
+ match std::char::from_u32(value) {
+ Some(c) => visitor.visit_char(c),
+ None => Err(Error::InvalidCharEncoding(value)),
+ }
+ }
+
+ fn deserialize_str<V>(self, visitor: V) -> Result<V::Value>
+ where
+ V: serde::de::Visitor<'de>,
+ {
+ visitor.visit_string(self.read_string()?)
+ }
+
+ fn deserialize_string<V>(self, visitor: V) -> Result<V::Value>
+ where
+ V: serde::de::Visitor<'de>,
+ {
+ visitor.visit_string(self.read_string()?)
+ }
+
+ fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value>
+ where
+ V: serde::de::Visitor<'de>,
+ {
+ visitor.visit_byte_buf(self.read_vec()?)
+ }
+
+ fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value>
+ where
+ V: serde::de::Visitor<'de>,
+ {
+ visitor.visit_byte_buf(self.read_vec()?)
+ }
+
+ fn deserialize_enum<V>(
+ self,
+ _enum: &'static str,
+ _variants: &'static [&'static str],
+ visitor: V,
+ ) -> Result<V::Value>
+ where
+ V: serde::de::Visitor<'de>,
+ {
+ visitor.visit_enum(self)
+ }
+
+ fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value>
+ where
+ V: serde::de::Visitor<'de>,
+ {
+ visitor.visit_seq(Access {
+ deserializer: self,
+ len,
+ })
+ }
+
+ fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
+ where
+ V: serde::de::Visitor<'de>,
+ {
+ let value: u8 = serde::de::Deserialize::deserialize(&mut *self)?;
+ match value {
+ 0 => visitor.visit_none(),
+ 1 => visitor.visit_some(&mut *self),
+ v => Err(Error::InvalidTagEncoding(v as usize)),
+ }
+ }
+
+ fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value>
+ where
+ V: serde::de::Visitor<'de>,
+ {
+ let len = serde::Deserialize::deserialize(&mut *self)?;
+
+ self.deserialize_tuple(len, visitor)
+ }
+
+ fn deserialize_map<V>(self, visitor: V) -> Result<V::Value>
+ where
+ V: serde::de::Visitor<'de>,
+ {
+ let len = serde::Deserialize::deserialize(&mut *self)?;
+
+ visitor.visit_map(Access {
+ deserializer: self,
+ len,
+ })
+ }
+
+ fn deserialize_struct<V>(
+ self,
+ _name: &str,
+ fields: &'static [&'static str],
+ visitor: V,
+ ) -> Result<V::Value>
+ where
+ V: serde::de::Visitor<'de>,
+ {
+ self.deserialize_tuple(fields.len(), visitor)
+ }
+
+ fn deserialize_identifier<V>(self, _visitor: V) -> Result<V::Value>
+ where
+ V: serde::de::Visitor<'de>,
+ {
+ Err(Error::DeserializeIdentifierNotSupported)
+ }
+
+ fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value>
+ where
+ V: serde::de::Visitor<'de>,
+ {
+ visitor.visit_newtype_struct(self)
+ }
+
+ fn deserialize_unit_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value>
+ where
+ V: serde::de::Visitor<'de>,
+ {
+ visitor.visit_unit()
+ }
+
+ fn deserialize_tuple_struct<V>(
+ self,
+ _name: &'static str,
+ len: usize,
+ visitor: V,
+ ) -> Result<V::Value>
+ where
+ V: serde::de::Visitor<'de>,
+ {
+ self.deserialize_tuple(len, visitor)
+ }
+
+ fn deserialize_ignored_any<V>(self, _visitor: V) -> Result<V::Value>
+ where
+ V: serde::de::Visitor<'de>,
+ {
+ Err(Error::DeserializeIgnoredAnyNotSupported)
+ }
+
+ fn is_human_readable(&self) -> bool {
+ false
+ }
+}
+
+struct Access<'a, 'b> {
+ deserializer: &'a mut Deserializer<'b>,
+ len: usize,
+}
+
+impl<'de, 'a, 'b> serde::de::SeqAccess<'de> for Access<'a, 'b> {
+ type Error = Error;
+
+ fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
+ where
+ T: serde::de::DeserializeSeed<'de>,
+ {
+ if self.len > 0 {
+ self.len -= 1;
+ let value = serde::de::DeserializeSeed::deserialize(seed, &mut *self.deserializer)?;
+ Ok(Some(value))
+ } else {
+ Ok(None)
+ }
+ }
+
+ fn size_hint(&self) -> Option<usize> {
+ Some(self.len)
+ }
+}
+
+impl<'de, 'a, 'b> serde::de::MapAccess<'de> for Access<'a, 'b> {
+ type Error = Error;
+
+ fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
+ where
+ K: serde::de::DeserializeSeed<'de>,
+ {
+ if self.len > 0 {
+ self.len -= 1;
+ let key = serde::de::DeserializeSeed::deserialize(seed, &mut *self.deserializer)?;
+ Ok(Some(key))
+ } else {
+ Ok(None)
+ }
+ }
+
+ fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
+ where
+ V: serde::de::DeserializeSeed<'de>,
+ {
+ let value = serde::de::DeserializeSeed::deserialize(seed, &mut *self.deserializer)?;
+ Ok(value)
+ }
+
+ fn size_hint(&self) -> Option<usize> {
+ Some(self.len)
+ }
+}
+
+impl<'de, 'a, 'b> serde::de::EnumAccess<'de> for &'a mut Deserializer<'b> {
+ type Error = Error;
+ type Variant = Self;
+
+ fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant)>
+ where
+ V: serde::de::DeserializeSeed<'de>,
+ {
+ let idx: u32 = serde::de::Deserialize::deserialize(&mut *self)?;
+ let val: Result<_> = seed.deserialize(idx.into_deserializer());
+ Ok((val?, self))
+ }
+}
+
+impl<'de, 'a, 'b> serde::de::VariantAccess<'de> for &'a mut Deserializer<'b> {
+ type Error = Error;
+
+ fn unit_variant(self) -> Result<()> {
+ Ok(())
+ }
+
+ fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value>
+ where
+ T: serde::de::DeserializeSeed<'de>,
+ {
+ serde::de::DeserializeSeed::deserialize(seed, self)
+ }
+
+ fn tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value>
+ where
+ V: serde::de::Visitor<'de>,
+ {
+ serde::de::Deserializer::deserialize_tuple(self, len, visitor)
+ }
+
+ fn struct_variant<V>(self, fields: &'static [&'static str], visitor: V) -> Result<V::Value>
+ where
+ V: serde::de::Visitor<'de>,
+ {
+ serde::de::Deserializer::deserialize_tuple(self, fields.len(), visitor)
+ }
+}
diff --git a/deps/varbincode/src/error.rs b/deps/varbincode/src/error.rs
new file mode 100644
index 00000000..5cfd8699
--- /dev/null
+++ b/deps/varbincode/src/error.rs
@@ -0,0 +1,72 @@
+use serde::{de, ser};
+use std::fmt::{self, Display};
+
+#[derive(Clone, Debug, PartialEq)]
+pub enum Error {
+ Message(String),
+ Io(String),
+ SequenceMustHaveLength,
+ LebOverflow,
+ DeserializeAnyNotSupported,
+ DeserializeIdentifierNotSupported,
+ DeserializeIgnoredAnyNotSupported,
+ InvalidBoolEncoding(u8),
+ InvalidCharEncoding(u32),
+ InvalidUtf8Encoding(std::str::Utf8Error),
+ InvalidTagEncoding(usize),
+ NumberOutOfRange,
+}
+
+pub type Result<T> = std::result::Result<T, Error>;
+
+impl ser::Error for Error {
+ fn custom<T: Display>(msg: T) -> Self {
+ Error::Message(msg.to_string())
+ }
+}
+
+impl de::Error for Error {
+ fn custom<T: Display>(msg: T) -> Self {
+ Error::Message(msg.to_string())
+ }
+}
+
+impl From<std::io::Error> for Error {
+ fn from(err: std::io::Error) -> Error {
+ Error::Io(format!("{}", err))
+ }
+}
+
+impl From<leb128::read::Error> for Error {
+ fn from(err: leb128::read::Error) -> Error {
+ match err {
+ leb128::read::Error::IoError(err) => Error::Io(format!("{}", err)),
+ leb128::read::Error::Overflow => Error::LebOverflow,
+ }
+ }
+}
+
+impl Display for Error {
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str(std::error::Error::description(self))
+ }
+}
+
+impl std::error::Error for Error {
+ fn description(&self) -> &str {
+ match *self {
+ Error::Message(ref msg) => msg,
+ Error::Io(ref msg) => msg,
+ Error::SequenceMustHaveLength => "SequenceMustHaveLength",
+ Error::DeserializeAnyNotSupported => "DeserializeAnyNotSupported",
+ Error::LebOverflow => "LEB128 Overflow",
+ Error::InvalidBoolEncoding(_) => "Invalid Bool Encoding",
+ Error::InvalidCharEncoding(_) => "Invalid char encoding",
+ Error::DeserializeIdentifierNotSupported => "DeserializeIdentifierNotSupported",
+ Error::DeserializeIgnoredAnyNotSupported => "DeserializeIgnoredAnyNotSupported",
+ Error::InvalidUtf8Encoding(_) => "InvalidUtf8Encoding",
+ Error::InvalidTagEncoding(_) => "InvalidTagEncoding",
+ Error::NumberOutOfRange => "NumberOutOfRange",
+ }
+ }
+}
diff --git a/deps/varbincode/src/lib.rs b/deps/varbincode/src/lib.rs
new file mode 100644
index 00000000..026a3140
--- /dev/null
+++ b/deps/varbincode/src/lib.rs
@@ -0,0 +1,31 @@
+// Vendored: see Cargo.toml. Kept as upstream wrote it apart from `read_vec`.
+#![allow(bare_trait_objects, deprecated, unused_attributes, unused_mut, dropping_references)]
+//! varbincode is a binary serialization format that uses variable
+//! length encoding for integer values, which typically results in
+//! reduced size of the encoded data.
+pub mod de;
+pub mod error;
+pub mod ser;
+#[cfg(test)]
+mod test;
+
+pub use de::Deserializer;
+pub use ser::Serializer;
+
+/// A convenience function for serializing a value as a byte vector
+/// See also `ser::Serializer`.
+pub fn serialize<T: serde::Serialize>(t: &T) -> Result<Vec<u8>, error::Error> {
+ let mut result = Vec::new();
+ let mut s = Serializer::new(&mut result);
+ t.serialize(&mut s)?;
+ Ok(result)
+}
+
+/// A convenience function for deserializing from a stream.
+/// See also `de::Deserializer`.
+pub fn deserialize<T: serde::de::DeserializeOwned, R: std::io::Read>(
+ mut r: R,
+) -> Result<T, error::Error> {
+ let mut d = Deserializer::new(&mut r);
+ serde::Deserialize::deserialize(&mut d)
+}
diff --git a/deps/varbincode/src/ser.rs b/deps/varbincode/src/ser.rs
new file mode 100644
index 00000000..c4f20011
--- /dev/null
+++ b/deps/varbincode/src/ser.rs
@@ -0,0 +1,345 @@
+use crate::error::Error;
+use byteorder::{LittleEndian, WriteBytesExt};
+use serde::ser;
+
+pub struct Serializer<'a> {
+ writer: &'a mut std::io::Write,
+}
+
+impl<'a> Serializer<'a> {
+ pub fn new(writer: &'a mut std::io::Write) -> Self {
+ Self { writer }
+ }
+
+ fn write_signed(&mut self, val: i64) -> Result<usize, std::io::Error> {
+ leb128::write::signed(&mut self.writer, val)
+ }
+
+ fn write_unsigned(&mut self, val: u64) -> Result<usize, std::io::Error> {
+ leb128::write::unsigned(&mut self.writer, val)
+ }
+}
+
+impl<'a, 'b> ser::Serializer for &'a mut Serializer<'b> {
+ type Ok = ();
+ type Error = Error;
+ type SerializeSeq = Self;
+ type SerializeTuple = Self;
+ type SerializeTupleStruct = Self;
+ type SerializeTupleVariant = Self;
+ type SerializeMap = Self;
+ type SerializeStruct = Self;
+ type SerializeStructVariant = Self;
+
+ fn serialize_bool(self, v: bool) -> Result<(), Error> {
+ self.write_unsigned(if v { 1 } else { 0 })?;
+ Ok(())
+ }
+
+ fn serialize_unit(self) -> Result<(), Error> {
+ Ok(())
+ }
+
+ fn serialize_unit_struct(self, _: &'static str) -> Result<(), Error> {
+ Ok(())
+ }
+
+ fn serialize_u8(self, v: u8) -> Result<(), Error> {
+ self.writer.write_u8(v as _)?;
+ Ok(())
+ }
+
+ fn serialize_u16(self, v: u16) -> Result<(), Error> {
+ self.write_unsigned(v as _)?;
+ Ok(())
+ }
+
+ fn serialize_u32(self, v: u32) -> Result<(), Error> {
+ self.write_unsigned(v as _)?;
+ Ok(())
+ }
+
+ fn serialize_u64(self, v: u64) -> Result<(), Error> {
+ self.write_unsigned(v as _)?;
+ Ok(())
+ }
+
+ fn serialize_i8(self, v: i8) -> Result<(), Error> {
+ self.writer.write_i8(v as _)?;
+ Ok(())
+ }
+
+ fn serialize_i16(self, v: i16) -> Result<(), Error> {
+ self.write_signed(v as _)?;
+ Ok(())
+ }
+
+ fn serialize_i32(self, v: i32) -> Result<(), Error> {
+ self.write_signed(v as _)?;
+ Ok(())
+ }
+
+ fn serialize_i64(self, v: i64) -> Result<(), Error> {
+ self.write_signed(v as _)?;
+ Ok(())
+ }
+
+ fn serialize_f32(self, v: f32) -> Result<(), Error> {
+ self.writer.write_f32::<LittleEndian>(v)?;
+ Ok(())
+ }
+
+ fn serialize_f64(self, v: f64) -> Result<(), Error> {
+ self.writer.write_f64::<LittleEndian>(v)?;
+ Ok(())
+ }
+
+ fn serialize_str(self, v: &str) -> Result<(), Error> {
+ self.serialize_bytes(v.as_bytes())
+ }
+
+ fn serialize_char(self, c: char) -> Result<(), Error> {
+ self.serialize_u32(c as u32)
+ }
+
+ fn serialize_bytes(self, v: &[u8]) -> Result<(), Error> {
+ self.serialize_u64(v.len() as u64)?;
+ self.writer.write_all(v)?;
+ Ok(())
+ }
+
+ fn serialize_none(self) -> Result<(), Error> {
+ self.serialize_u8(0)
+ }
+
+ fn serialize_some<T: serde::Serialize + ?Sized>(self, v: &T) -> Result<(), Error> {
+ self.serialize_u8(1)?;
+ v.serialize(self)
+ }
+
+ fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Error> {
+ let len = len.ok_or(Error::SequenceMustHaveLength)?;
+ self.serialize_u64(len as u64)?;
+ Ok(self)
+ }
+
+ fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Error> {
+ Ok(self)
+ }
+
+ fn serialize_tuple_struct(
+ self,
+ _name: &'static str,
+ _len: usize,
+ ) -> Result<Self::SerializeTupleStruct, Error> {
+ Ok(self)
+ }
+
+ fn serialize_tuple_variant(
+ self,
+ _name: &'static str,
+ variant_index: u32,
+ _variant: &'static str,
+ _len: usize,
+ ) -> Result<Self::SerializeTupleVariant, Error> {
+ self.serialize_u32(variant_index)?;
+ Ok(self)
+ }
+
+ fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Error> {
+ let len = len.ok_or(Error::SequenceMustHaveLength)?;
+ self.serialize_u64(len as u64)?;
+ Ok(self)
+ }
+
+ fn serialize_struct(
+ self,
+ _name: &'static str,
+ _len: usize,
+ ) -> Result<Self::SerializeStruct, Error> {
+ Ok(self)
+ }
+
+ fn serialize_struct_variant(
+ self,
+ _name: &'static str,
+ variant_index: u32,
+ _variant: &'static str,
+ _len: usize,
+ ) -> Result<Self::SerializeStructVariant, Error> {
+ self.serialize_u32(variant_index)?;
+ Ok(self)
+ }
+
+ fn serialize_newtype_struct<T: ?Sized>(
+ self,
+ _name: &'static str,
+ value: &T,
+ ) -> Result<(), Error>
+ where
+ T: serde::ser::Serialize,
+ {
+ value.serialize(self)
+ }
+
+ fn serialize_newtype_variant<T: ?Sized>(
+ self,
+ _name: &'static str,
+ variant_index: u32,
+ _variant: &'static str,
+ value: &T,
+ ) -> Result<(), Error>
+ where
+ T: serde::ser::Serialize,
+ {
+ self.serialize_u32(variant_index)?;
+ value.serialize(self)
+ }
+
+ fn serialize_unit_variant(
+ self,
+ _name: &'static str,
+ variant_index: u32,
+ _variant: &'static str,
+ ) -> Result<(), Error> {
+ self.serialize_u32(variant_index)
+ }
+
+ fn is_human_readable(&self) -> bool {
+ false
+ }
+}
+
+impl<'a, 'b> ser::SerializeSeq for &'a mut Serializer<'b> {
+ type Ok = ();
+ type Error = Error;
+
+ #[inline]
+ fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
+ where
+ T: serde::ser::Serialize,
+ {
+ value.serialize(&mut **self)
+ }
+
+ #[inline]
+ fn end(self) -> Result<(), Error> {
+ Ok(())
+ }
+}
+
+impl<'a, 'b> ser::SerializeTuple for &'a mut Serializer<'b> {
+ type Ok = ();
+ type Error = Error;
+
+ #[inline]
+ fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
+ where
+ T: serde::ser::Serialize,
+ {
+ value.serialize(&mut **self)
+ }
+
+ #[inline]
+ fn end(self) -> Result<(), Error> {
+ Ok(())
+ }
+}
+
+impl<'a, 'b> ser::SerializeTupleStruct for &'a mut Serializer<'b> {
+ type Ok = ();
+ type Error = Error;
+
+ #[inline]
+ fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
+ where
+ T: serde::ser::Serialize,
+ {
+ value.serialize(&mut **self)
+ }
+
+ #[inline]
+ fn end(self) -> Result<(), Error> {
+ Ok(())
+ }
+}
+
+impl<'a, 'b> ser::SerializeTupleVariant for &'a mut Serializer<'b> {
+ type Ok = ();
+ type Error = Error;
+
+ #[inline]
+ fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
+ where
+ T: serde::ser::Serialize,
+ {
+ value.serialize(&mut **self)
+ }
+
+ #[inline]
+ fn end(self) -> Result<(), Error> {
+ Ok(())
+ }
+}
+
+impl<'a, 'b> ser::SerializeMap for &'a mut Serializer<'b> {
+ type Ok = ();
+ type Error = Error;
+
+ #[inline]
+ fn serialize_key<K: ?Sized>(&mut self, value: &K) -> Result<(), Error>
+ where
+ K: serde::ser::Serialize,
+ {
+ value.serialize(&mut **self)
+ }
+
+ #[inline]
+ fn serialize_value<V: ?Sized>(&mut self, value: &V) -> Result<(), Error>
+ where
+ V: serde::ser::Serialize,
+ {
+ value.serialize(&mut **self)
+ }
+
+ #[inline]
+ fn end(self) -> Result<(), Error> {
+ Ok(())
+ }
+}
+
+impl<'a, 'b> ser::SerializeStruct for &'a mut Serializer<'b> {
+ type Ok = ();
+ type Error = Error;
+
+ #[inline]
+ fn serialize_field<T: ?Sized>(&mut self, _key: &'static str, value: &T) -> Result<(), Error>
+ where
+ T: serde::ser::Serialize,
+ {
+ value.serialize(&mut **self)
+ }
+
+ #[inline]
+ fn end(self) -> Result<(), Error> {
+ Ok(())
+ }
+}
+
+impl<'a, 'b> ser::SerializeStructVariant for &'a mut Serializer<'b> {
+ type Ok = ();
+ type Error = Error;
+
+ #[inline]
+ fn serialize_field<T: ?Sized>(&mut self, _key: &'static str, value: &T) -> Result<(), Error>
+ where
+ T: serde::ser::Serialize,
+ {
+ value.serialize(&mut **self)
+ }
+
+ #[inline]
+ fn end(self) -> Result<(), Error> {
+ Ok(())
+ }
+}
diff --git a/deps/varbincode/src/test.rs b/deps/varbincode/src/test.rs
new file mode 100644
index 00000000..4885825e
--- /dev/null
+++ b/deps/varbincode/src/test.rs
@@ -0,0 +1,141 @@
+use super::{deserialize, serialize};
+use serde::Serialize;
+use serde_derive::*;
+use std::collections::HashMap;
+
+fn same<'de, T: serde::de::DeserializeOwned + Serialize + std::fmt::Debug + PartialEq>(a: T) {
+ let encoded = serialize(&a).unwrap();
+ let decoded: T = deserialize(encoded.as_slice()).unwrap();
+ assert_eq!(decoded, a);
+ eprintln!("{:?} encoded as {:?}", a, encoded);
+}
+
+#[test]
+fn test() {
+ same(0u8);
+ same(1u8);
+ same(1i8);
+ same(0i8);
+ same(0u16);
+ same(255u16);
+ same(0xffffu16);
+ same(0x7fffi16);
+ same(-0x7fffi16);
+ same(0x00ff_ffffu32);
+ same(0xffff_ffffu32);
+ same(0x00ff_ffffu64);
+ same(0xffff_ffffu64);
+ same(0xffff_ffff_ffffu64);
+ same(0xffff_ffff_ffff_ffffu64);
+ same(0f32);
+ same(10.5f32);
+ same(10.5f64);
+ same(-10.5f64);
+
+ same("".to_string());
+ same("hello".to_string());
+
+ same((1u8,));
+ same((1u8, 2, 3));
+ same((1u8, "foo".to_string()));
+
+ same(true);
+ same(false);
+
+ same(Some(true));
+ same(None::<bool>);
+
+ same('c');
+ same(b'c');
+}
+
+#[test]
+fn test_structs() {
+ #[derive(Serialize, Deserialize, PartialEq, Debug)]
+ struct Struct {
+ a: isize,
+ b: String,
+ c: bool,
+ };
+
+ #[derive(Serialize, Deserialize, PartialEq, Debug)]
+ struct Outer {
+ inner: Struct,
+ b: bool,
+ second: Struct,
+ };
+
+ same(Struct {
+ a: -42,
+ b: "hello".to_string(),
+ c: true,
+ });
+
+ same(Outer {
+ inner: Struct {
+ a: 1,
+ b: "bee".to_string(),
+ c: false,
+ },
+ b: true,
+ second: Struct {
+ a: 2,
+ b: "other".to_string(),
+ c: true,
+ },
+ });
+
+ #[derive(Serialize, Deserialize, PartialEq, Debug)]
+ struct NewType(usize);
+ same(NewType(123));
+
+ #[derive(Serialize, Deserialize, PartialEq, Debug)]
+ struct NewTypeTuple(usize, bool);
+ same(NewTypeTuple(123, true));
+}
+
+#[test]
+fn test_enum() {
+ #[derive(Serialize, Deserialize, PartialEq, Debug)]
+ enum TestEnum {
+ NoArg,
+ OneArg(usize),
+ Args(usize, usize),
+ AnotherNoArg,
+ StructLike { x: usize, y: f32 },
+ }
+ same(TestEnum::NoArg);
+ same(TestEnum::OneArg(4));
+ same(TestEnum::Args(4, 5));
+ same(TestEnum::AnotherNoArg);
+ same(TestEnum::StructLike { x: 4, y: 3.14159 });
+ same(vec![
+ TestEnum::NoArg,
+ TestEnum::OneArg(5),
+ TestEnum::AnotherNoArg,
+ TestEnum::StructLike { x: 4, y: 1.4 },
+ ]);
+}
+
+#[test]
+fn test_vec() {
+ let v: Vec<u8> = vec![];
+ same(v);
+ same(vec![1u64]);
+ same(vec![1u64, 2, 3, 4, 5, 6]);
+}
+
+#[test]
+fn test_map() {
+ let mut m = HashMap::new();
+ m.insert(4u64, "foo".to_string());
+ m.insert(0u64, "bar".to_string());
+ same(m);
+}
+
+#[test]
+fn test_fixed_size_array() {
+ same([24u32; 32]);
+ same([1u64, 2, 3, 4, 5, 6, 7, 8]);
+ same([0u8; 19]);
+}
diff --git a/docs/multiplexing.md b/docs/multiplexing.md
index b8a55d18..44684bb0 100644
--- a/docs/multiplexing.md
+++ b/docs/multiplexing.md
@@ -282,3 +282,43 @@ remote terminal session
```console
$ wezterm connect server.name
```
+
+## Browser access
+
+A multiplexer can also serve a browser client: one TCP port delivers the
+page, its JavaScript and wasm, and accepts a WebSocket that speaks the same
+protocol as every other client. The browser mirrors a pane the way the
+desktop does, and takes over input the moment you type into it.
+
+### Configuring the server
+
+```lua
+config.web_servers = {
+ {
+ -- loopback by default; see WebServer for TLS and other hosts
+ bind_address = '127.0.0.1:8088',
+ },
+}
+```
+
+[See Browser access](thinkterm/web-access.md) for every setting, TLS and
+remote use.
+
+### Minting a token and opening the page
+
+A browser is admitted by a *web token*, minted where the server already
+trusts you: over the unix socket, or through `thinkterm cli` over ssh.
+
+```console
+$ thinkterm cli web-token mint --label laptop --ttl 12h
+```
+
+prints a URL to open. The token is a login as your user on that machine;
+`thinkterm cli web-token list` shows what exists and who is connected, and
+`thinkterm cli web-token revoke <id>` cuts a token and its browsers off at
+once.
+
+For a server on another machine, forward the port over ssh rather than
+exposing it: `ssh -L 8088:127.0.0.1:8088 server.hostname`, then open the
+loopback URL locally. Browsers only render the client in a secure context,
+which `http://localhost` is and a plain `http://` to a remote host is not.
diff --git a/docs/thinkterm/web-access.md b/docs/thinkterm/web-access.md
new file mode 100644
index 00000000..3325025a
--- /dev/null
+++ b/docs/thinkterm/web-access.md
@@ -0,0 +1,100 @@
+# Browser access
+
+**Status:** Landing in phases (server entry and token CLI first, browser client next)
+
+ThinkTerm's multiplexer can serve a browser client. One TCP port per
+`web_servers` entry delivers the page, its JavaScript and wasm over HTTP and
+accepts a WebSocket that speaks the same protocol as every other client. The
+browser mirrors a pane the way the desktop does and takes over input the
+moment you type into it.
+
+## `web_servers`
+
+`config.web_servers` is a list of `WebServer` objects, read when
+`thinkterm-mux-server` starts, like `tls_servers`; reloading the configuration
+does not open or close web ports.
+
+```lua
+config.web_servers = {
+ {
+ -- The address:port to listen on. Loopback by default. Browsers only
+ -- expose WebGPU (which the client renders with) to secure contexts:
+ -- http://localhost is one, plain http:// to any other host is not.
+ bind_address = '127.0.0.1:8088',
+
+ -- Set both to serve https/wss. Required off loopback.
+ -- pem_cert = '/path/to/cert.pem',
+ -- pem_private_key = '/path/to/key.pem',
+ -- pem_ca = '/path/to/chain.pem',
+
+ -- Where index.html, the JavaScript and the wasm live. Defaults to the
+ -- share/thinkterm/web directory next to the installed executable.
+ -- static_dir = '/usr/share/thinkterm/web',
+
+ -- Where minted tokens are kept, as digests. Unset means memory only:
+ -- restarting the server forgets every token.
+ -- token_file = wezterm.home_dir .. '/.local/share/thinkterm/web-tokens.json',
+
+ -- Origins allowed to open the WebSocket. Empty means this listener's
+ -- own address, which is what a page served from this port sends.
+ -- allowed_origins = { 'https://terminal.example.net' },
+
+ -- Refuse to start without TLS when bind_address is not loopback.
+ -- require_tls_off_loopback = true,
+ },
+}
+```
+
+## Tokens
+
+```console
+$ thinkterm cli web-token mint --label laptop --ttl 12h # prints the URL to open
+$ thinkterm cli web-token list
+$ thinkterm cli web-token revoke <id> # or --all
+```
+
+A token is minted where the server already trusts you: over the unix socket,
+or through `thinkterm cli` over ssh. It is a login as your user on that
+machine; anyone holding it can open a shell and read every pane. Revoking a
+token drops the browsers it admitted at once. The server keeps digests only,
+so a copied token file reveals nothing.
+
+## Reaching a remote server
+
+The recommended way to use a server on another machine is to keep it on
+loopback and forward the port over ssh, which makes it a loopback origin on
+your side too and needs no certificate:
+
+```console
+$ ssh -L 8088:127.0.0.1:8088 server.hostname
+$ thinkterm cli --prefer-mux web-token mint # on the server, or over ssh
+```
+
+The local port need not match: with `ssh -L 9000:127.0.0.1:8088` the page is
+at `http://localhost:9000/`, and a loopback listener accepts any loopback
+name on any port, because the port a forward uses is the client's choice.
+Put the minted URL's token fragment on that address. A listener that is
+reached under some other name (a reverse proxy, a non-loopback bind) must
+list that name in `allowed_origins`; the minted URLs then point there.
+
+Serving TLS directly needs a certificate the browser trusts; the server's own
+TLS PKI is regenerated every time it starts and is not suitable for that.
+
+## Building and serving the bundle
+
+`ci/build-web.sh` builds `thinkterm-web` for `wasm32-unknown-unknown`, runs
+`wasm-bindgen` (the CLI must match the version pinned in `Cargo.toml`) and
+copies the fonts into `thinkterm-web/www`. The release tarballs and the macOS
+app carry that directory as `share/thinkterm/web` (or `Contents/Resources/web`),
+which is where the server looks by default; `static_dir` in a `web_servers`
+entry or the `THINKTERM_WEB_STATIC_DIR` environment variable point it elsewhere,
+for instance at a development checkout.
+
+## What the first version does not do
+
+Images (kitty, sixel, iTerm2) and colour emoji are not drawn; tabs, splits and
+the ThinkTerm tree are not shown -- the page mirrors one pane; there is no
+reconnect after the socket drops (reload the page); the cursor does not blink;
+box-drawing comes from the font rather than the desktop's custom block glyphs;
+font fallback is the bundled list (JetBrains Mono, Symbols Nerd Font Mono), so
+scripts outside it show as missing-glyph boxes.
diff --git a/wezterm-client/src/client.rs b/wezterm-client/src/client.rs
index 00c2a5fb..b4e2d0bf 100644
--- a/wezterm-client/src/client.rs
+++ b/wezterm-client/src/client.rs
@@ -2312,6 +2312,9 @@ impl Client {
);
rpc!(get_codec_version, GetCodecVersion, GetCodecVersionResponse);
rpc!(get_tls_creds, GetTlsCreds = (), GetTlsCredsResponse);
+ rpc!(web_token_mint, WebTokenMint, WebTokenMintResponse);
+ rpc!(web_token_list, WebTokenList = (), WebTokenListResponse);
+ rpc!(web_token_revoke, WebTokenRevoke, WebTokenRevokeResponse);
rpc!(
search_scrollback,
SearchScrollbackRequest,
diff --git a/wezterm-mux-server-impl/Cargo.toml b/wezterm-mux-server-impl/Cargo.toml
index 5992aaec..15d50e64 100644
--- a/wezterm-mux-server-impl/Cargo.toml
+++ b/wezterm-mux-server-impl/Cargo.toml
@@ -28,7 +28,14 @@ rangeset.workspace = true
rcgen.workspace = true
serde.workspace = true
serde_json.workspace = true
+sha1.workspace = true
+sha2.workspace = true
smol.workspace = true
+soketto.workspace = true
+base64.workspace = true
+getrandom.workspace = true
+hex = { workspace = true, features = ["alloc"] }
+httparse.workspace = true
tempfile.workspace = true
termwiz = { workspace=true, features=["use_serde"] }
url.workspace = true
diff --git a/wezterm-mux-server-impl/src/connections.rs b/wezterm-mux-server-impl/src/connections.rs
index 5d1466c0..18177184 100644
--- a/wezterm-mux-server-impl/src/connections.rs
+++ b/wezterm-mux-server-impl/src/connections.rs
@@ -43,24 +43,32 @@ static EXECUTOR: LazyLock<Arc<Executor<'static>>> = LazyLock::new(|| {
/// Run `future` -- one client connection, start to finish -- on the
/// connection threads.
pub fn spawn<F>(future: F)
+where
+ F: Future<Output = ()> + Send + 'static,
+{
+ spawn_task(future).detach();
+}
+
+/// Like `spawn`, but the caller keeps the handle: dropping it cancels
+/// the task, which is how a connection's helper tasks are tied to its
+/// lifetime.
+pub fn spawn_task<F>(future: F) -> smol::Task<()>
where
F: Future<Output = ()> + Send + 'static,
{
// The executor catches a task's panic and hands it to whoever holds
// the task; detached, that would be nobody, and the connection would
// simply vanish. Say so, at least.
- EXECUTOR
- .spawn(async move {
- if let Err(payload) = AssertUnwindSafe(future).catch_unwind().await {
- let message = payload
- .downcast_ref::<String>()
- .map(String::as_str)
- .or_else(|| payload.downcast_ref::<&str>().copied())
- .unwrap_or("(no message)");
- log::error!("a client connection panicked and was dropped: {message}");
- }
- })
- .detach();
+ EXECUTOR.spawn(async move {
+ if let Err(payload) = AssertUnwindSafe(future).catch_unwind().await {
+ let message = payload
+ .downcast_ref::<String>()
+ .map(String::as_str)
+ .or_else(|| payload.downcast_ref::<&str>().copied())
+ .unwrap_or("(no message)");
+ log::error!("a client connection panicked and was dropped: {message}");
+ }
+ })
}
#[cfg(test)]
diff --git a/wezterm-mux-server-impl/src/dispatch.rs b/wezterm-mux-server-impl/src/dispatch.rs
index bfccbb59..6b36dca6 100644
--- a/wezterm-mux-server-impl/src/dispatch.rs
+++ b/wezterm-mux-server-impl/src/dispatch.rs
@@ -1,4 +1,4 @@
-use crate::sessionhandler::{PduSender, SessionHandler};
+use crate::sessionhandler::{ConnectionPeer, PduSender, SessionHandler};
use anyhow::Context;
use async_ossl::AsyncSslStream;
use codec::{DecodedPdu, Pdu};
@@ -6,6 +6,7 @@ use futures::FutureExt;
use mux::{Mux, MuxNotification};
use smol::prelude::*;
use smol::Async;
+use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::{AtomicU64, Ordering};
use std::task::{Context as TaskContext, Poll};
@@ -26,6 +27,30 @@ enum Item {
WritePdu(DecodedPdu),
Readable,
LivenessTick,
+ /// The accept layer withdrew this connection's admission (a web token
+ /// was revoked).
+ Shutdown,
+}
+
+/// A client's byte stream as the connection loop sees it: async reads and
+/// writes, plus a wait for readability the loop races against its queue
+/// and clocks. `Async<T>` is the unix-socket and TLS shape; the web
+/// listener supplies a WebSocket-backed one.
+pub trait ConnectionStream: AsyncRead + AsyncWrite + Unpin + Send + std::fmt::Debug + 'static {
+ /// Resolves once a read would return at least one byte, or end of
+ /// stream. It must not resolve while nothing is buffered: the loop
+ /// enters a decode on it, and would otherwise sit inside a read with
+ /// pushes waiting unsent in the write queue.
+ fn wait_for_readable(&self) -> impl Future<Output = std::io::Result<()>> + Send + '_;
+}
+
+impl<T> ConnectionStream for Async<T>
+where
+ T: std::io::Read + std::io::Write + Send + Sync + std::fmt::Debug + async_io::IoSafe + 'static,
+{
+ fn wait_for_readable(&self) -> impl Future<Output = std::io::Result<()>> + Send + '_ {
+ self.readable()
+ }
}
/// Noticing a client that died without closing its socket.
@@ -138,34 +163,42 @@ where
T: AsRawDesc,
T: std::fmt::Debug,
T: async_io::IoSafe,
+ T: Send + Sync,
{
let stream = smol::Async::new(stream)?;
process_async(stream).await
}
-pub async fn process_async<T>(stream: Async<T>) -> anyhow::Result<()>
-where
- T: 'static,
- T: std::io::Read,
- T: std::io::Write,
- T: std::fmt::Debug,
- T: async_io::IoSafe,
-{
+pub async fn process_async<S: ConnectionStream>(stream: S) -> anyhow::Result<()> {
process_async_with(stream, Liveness::new(Instant::now())).await
}
-pub(crate) async fn process_async_with<T>(
- mut stream: Async<T>,
+/// A connection whose peer the accept layer has already identified: the
+/// web listener, after the token check at the HTTP upgrade.
+pub async fn process_stream<S: ConnectionStream>(
+ stream: S,
+ peer: ConnectionPeer,
+) -> anyhow::Result<()> {
+ process_async_with_peer(stream, Liveness::new(Instant::now()), peer).await
+}
+
+pub(crate) async fn process_async_with<S: ConnectionStream>(
+ stream: S,
+ liveness: Liveness,
+) -> anyhow::Result<()> {
+ process_async_with_peer(stream, liveness, ConnectionPeer::Local).await
+}
+
+async fn process_async_with_peer<S: ConnectionStream>(
+ mut stream: S,
mut liveness: Liveness,
-) -> anyhow::Result<()>
-where
- T: 'static,
- T: std::io::Read,
- T: std::io::Write,
- T: std::fmt::Debug,
- T: async_io::IoSafe,
-{
+ peer: ConnectionPeer,
+) -> anyhow::Result<()> {
log::trace!("process_async called");
+ let revoked = match &peer {
+ ConnectionPeer::Web(web) => Some(web.revoked.clone()),
+ ConnectionPeer::Local => None,
+ };
let (item_tx, item_rx) = smol::channel::unbounded::<Item>();
@@ -183,7 +216,7 @@ where
move || item_tx.is_closed()
},
);
- let mut handler = SessionHandler::new(pdu_sender);
+ let mut handler = SessionHandler::for_peer(pdu_sender, peer);
{
// Notifications take one hop through the main thread's queue before
@@ -233,14 +266,30 @@ where
};
loop {
+ // Checked first, unconditionally: the race below polls its arms in
+ // order and a busy pane keeps the queue arm ready on every turn, so
+ // a revocation that only lived in the race could wait forever.
+ if admission_is_withdrawn(&revoked) {
+ log::warn!("the client's web token was revoked; dropping the connection");
+ return Ok(());
+ }
let rx_msg = item_rx.recv();
- let wait_for_read = stream.readable().map(|_| Ok(Item::Readable));
+ let wait_for_read = stream.wait_for_readable().map(|_| Ok(Item::Readable));
let tick = async {
smol::Timer::at(liveness.next_check()).await;
Ok(Item::LivenessTick)
};
+ let shutdown = async {
+ admission_withdrawn(&revoked).await;
+ Ok(Item::Shutdown)
+ };
- let item = match smol::future::or(smol::future::or(rx_msg, wait_for_read), tick).await {
+ let item = match smol::future::or(
+ smol::future::or(smol::future::or(rx_msg, wait_for_read), tick),
+ shutdown,
+ )
+ .await
+ {
Ok(Item::LivenessTick) => match liveness.check(Instant::now()) {
Verdict::Fine => continue,
// Through the write queue like every other push, so a
@@ -278,24 +327,33 @@ where
// the read waiting for the rest with no clock running;
// the clock here runs once the first byte is in, and only
// while nothing more arrives.
+ // Revocation races the read as well: a peer dribbling one
+ // byte at a time keeps the decode alive indefinitely, and
+ // must still be gone the moment its token is.
let moved = AtomicU64::new(0);
let decoded = smol::future::or(
+ smol::future::or(
+ async {
+ let mut counted = Counted {
+ stream: &mut stream,
+ bytes: &moved,
+ };
+ Read::Decoded(Pdu::decode_async(&mut counted, None).await)
+ },
+ async {
+ stalled(&moved, READ_STALL_LIMIT, true).await;
+ Read::Stalled
+ },
+ ),
async {
- let mut counted = Counted {
- stream: &mut stream,
- bytes: &moved,
- };
- Some(Pdu::decode_async(&mut counted, None).await)
- },
- async {
- stalled(&moved, READ_STALL_LIMIT, true).await;
- None
+ admission_withdrawn(&revoked).await;
+ Read::Revoked
},
)
.await;
let decoded = match decoded {
- Some(Ok(data)) => data,
- Some(Err(err)) => {
+ Read::Decoded(Ok(data)) => data,
+ Read::Decoded(Err(err)) => {
if let Some(err) = err.root_cause().downcast_ref::<std::io::Error>() {
if err.kind() == std::io::ErrorKind::UnexpectedEof {
// Client disconnected: no need to make a noise
@@ -304,18 +362,32 @@ where
}
return Err(err).context("reading Pdu from client");
}
- None => {
+ Read::Stalled => {
log::warn!(
"the client stopped part-way through a PDU and sent nothing more \
for {READ_STALL_LIMIT:?}; dropping the connection"
);
return Ok(());
}
+ Read::Revoked => {
+ log::warn!("the client's web token was revoked; dropping the connection");
+ return Ok(());
+ }
};
+ // Decoded, but not yet acted on: a revocation that landed
+ // during the read must not get this one last request in.
+ if admission_is_withdrawn(&revoked) {
+ log::warn!("the client's web token was revoked; dropping the connection");
+ return Ok(());
+ }
liveness.heard(Instant::now());
handler.process_one(decoded);
}
Ok(Item::LivenessTick) => unreachable!("handled above"),
+ Ok(Item::Shutdown) => {
+ log::warn!("the client's web token was revoked; dropping the connection");
+ return Ok(());
+ }
Ok(Item::WritePdu(decoded)) => {
log::trace!("write {} serial {}", decoded.pdu.pdu_name(), decoded.serial);
let is_probe = decoded.serial == 0 && matches!(decoded.pdu, Pdu::Ping(_));
@@ -324,23 +396,31 @@ where
// cannot run while this arm waits, so the wait itself is
// bounded. Progress, not completion: a large picture over
// a slow link takes as long as it takes.
+ // A revocation also stops a transfer mid-way: pane contents
+ // must not go on streaming to a browser whose token is gone.
let moved = AtomicU64::new(0);
let written = smol::future::or(
+ smol::future::or(
+ async {
+ let mut counted = Counted {
+ stream: &mut stream,
+ bytes: &moved,
+ };
+ decoded
+ .pdu
+ .encode_async(&mut counted, decoded.serial)
+ .await
+ .map_err(WriteFailure::Encode)?;
+ counted.flush().await.map_err(WriteFailure::Flush)
+ },
+ async {
+ stalled(&moved, WRITE_STALL_LIMIT, false).await;
+ Err(WriteFailure::Stalled)
+ },
+ ),
async {
- let mut counted = Counted {
- stream: &mut stream,
- bytes: &moved,
- };
- decoded
- .pdu
- .encode_async(&mut counted, decoded.serial)
- .await
- .map_err(WriteFailure::Encode)?;
- counted.flush().await.map_err(WriteFailure::Flush)
- },
- async {
- stalled(&moved, WRITE_STALL_LIMIT, false).await;
- Err(WriteFailure::Stalled)
+ admission_withdrawn(&revoked).await;
+ Err(WriteFailure::Revoked)
},
)
.await;
@@ -357,6 +437,10 @@ where
);
return Ok(());
}
+ Err(WriteFailure::Revoked) => {
+ log::warn!("the client's web token was revoked; dropping the connection");
+ return Ok(());
+ }
Err(WriteFailure::Encode(err)) => {
if let Some(err) = err.root_cause().downcast_ref::<std::io::Error>() {
if err.kind() == std::io::ErrorKind::BrokenPipe {
@@ -419,8 +503,8 @@ const STALL_CHECK: Duration = Duration::from_secs(1);
const DEAD_GRACE: Duration = Duration::from_millis(250);
/// Whether the socket has something to read, given a moment to say so.
-async fn socket_has_data<T>(stream: &Async<T>) -> bool {
- smol::future::or(async { stream.readable().await.is_ok() }, async {
+async fn socket_has_data<S: ConnectionStream>(stream: &S) -> bool {
+ smol::future::or(async { stream.wait_for_readable().await.is_ok() }, async {
smol::Timer::after(DEAD_GRACE).await;
false
})
@@ -455,15 +539,12 @@ async fn stalled(bytes: &AtomicU64, limit: Duration, from_first_byte: bool) {
/// The stream with a count of the bytes that cross it, so a transfer that
/// is merely long can be told from one that has stopped.
#[derive(Debug)]
-struct Counted<'a, T> {
- stream: &'a mut Async<T>,
+struct Counted<'a, S> {
+ stream: &'a mut S,
bytes: &'a AtomicU64,
}
-impl<T> AsyncRead for Counted<'_, T>
-where
- Async<T>: AsyncRead + Unpin,
-{
+impl<S: AsyncRead + Unpin> AsyncRead for Counted<'_, S> {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut TaskContext<'_>,
@@ -478,10 +559,7 @@ where
}
}
-impl<T> AsyncWrite for Counted<'_, T>
-where
- Async<T>: AsyncWrite + Unpin,
-{
+impl<S: AsyncWrite + Unpin> AsyncWrite for Counted<'_, S> {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut TaskContext<'_>,
@@ -508,6 +586,33 @@ enum WriteFailure {
Encode(anyhow::Error),
Flush(std::io::Error),
Stalled,
+ Revoked,
+}
+
+enum Read {
+ Decoded(anyhow::Result<DecodedPdu>),
+ Stalled,
+ Revoked,
+}
+
+/// Whether the accept layer has withdrawn this connection's admission:
+/// either the revocation itself or the store letting go of its sender.
+/// A local connection has no admission to lose.
+fn admission_is_withdrawn(revoked: &Option<smol::channel::Receiver<()>>) -> bool {
+ match revoked {
+ Some(rx) => rx.try_recv().is_ok() || rx.is_closed(),
+ None => false,
+ }
+}
+
+/// Resolves when the admission is withdrawn; never, for a local peer.
+async fn admission_withdrawn(revoked: &Option<smol::channel::Receiver<()>>) {
+ match revoked {
+ Some(rx) => {
+ let _ = rx.recv().await;
+ }
+ None => std::future::pending().await,
+ }
}
/// What the connection loop needs for a mux notification, prepared on the
@@ -680,6 +785,119 @@ mod tests {
/// its Pong. (The first cut replied to the Pong with an ErrorResponse,
/// which the client could not handle: every client died ten seconds
/// after connecting.)
+ /// Revocation reaches the loop even when nothing else is idle: the
+ /// check runs before the race, every turn.
+ #[cfg(unix)]
+ #[test]
+ fn a_revoked_web_peer_is_dropped_promptly() {
+ use crate::sessionhandler::{ConnectionPeer, WebPeer};
+ use std::os::fd::{FromRawFd, IntoRawFd};
+
+ let mux = Arc::new(Mux::new(None));
+ Mux::set_mux(&mux);
+
+ let (ours, theirs) = std::os::unix::net::UnixStream::pair().unwrap();
+ let ours = unsafe { UnixStream::from_raw_fd(ours.into_raw_fd()) };
+ let stream = Async::new(ours).unwrap();
+ let (kill, revoked) = smol::channel::bounded(1);
+ let peer = ConnectionPeer::Web(WebPeer {
+ token_id: "t".into(),
+ label: "test".into(),
+ username: "me".into(),
+ revoked,
+ });
+ // Keep the loop busy: a stream of pushes has the queue arm ready on
+ // every turn, which is exactly when a revocation must still win.
+ let busy = std::thread::spawn(move || {
+ let started = Instant::now();
+ while started.elapsed() < Duration::from_millis(600) {
+ Pdu::Ping(codec::Ping {}).encode(&theirs, 1).ok();
+ std::thread::sleep(Duration::from_millis(1));
+ }
+ theirs
+ });
+ std::thread::spawn(move || {
+ std::thread::sleep(Duration::from_millis(150));
+ kill.try_send(()).unwrap();
+ });
+ let outcome = smol::block_on(smol::future::or(
+ async {
+ process_async_with_peer(stream, Liveness::new(Instant::now()), peer).await?;
+ Ok(true)
+ },
+ async {
+ smol::Timer::after(Duration::from_millis(500)).await;
+ Ok::<bool, anyhow::Error>(false)
+ },
+ ));
+ assert_eq!(outcome.unwrap(), true, "the revoked connection did not end in time");
+ busy.join().unwrap();
+ }
+
+ /// A peer part-way through a PDU, still sending, is not out of reach
+ /// of a revocation: the read is raced against it.
+ #[cfg(unix)]
+ #[test]
+ fn a_revoked_web_peer_is_dropped_mid_pdu() {
+ use crate::sessionhandler::{ConnectionPeer, WebPeer};
+ use std::io::Write;
+ use std::os::fd::{FromRawFd, IntoRawFd};
+
+ let mux = Arc::new(Mux::new(None));
+ Mux::set_mux(&mux);
+
+ let (ours, mut theirs) = std::os::unix::net::UnixStream::pair().unwrap();
+ let ours = unsafe { UnixStream::from_raw_fd(ours.into_raw_fd()) };
+ let stream = Async::new(ours).unwrap();
+ let (kill, revoked) = smol::channel::bounded(1);
+ let peer = ConnectionPeer::Web(WebPeer {
+ token_id: "t".into(),
+ label: "test".into(),
+ username: "me".into(),
+ revoked,
+ });
+ // Incompressible, so the PDU really is thousands of bytes long.
+ let mut noise = vec![0u8; 4000];
+ getrandom::fill(&mut noise).unwrap();
+ let data = noise.iter().map(|b| (b'a' + b % 26) as char).collect::<String>();
+ let mut bytes = Vec::new();
+ Pdu::SendPaste(codec::SendPaste { pane_id: 1, data })
+ .encode(&mut bytes, 1)
+ .unwrap();
+ assert!(bytes.len() > 1000, "{} bytes", bytes.len());
+ // The header and a little of the body, then one byte at a time,
+ // forever as far as the loop can tell.
+ let dribble = std::thread::spawn(move || {
+ theirs.write_all(&bytes[..64]).ok();
+ let started = Instant::now();
+ for byte in &bytes[64..] {
+ if started.elapsed() > Duration::from_millis(900) {
+ break;
+ }
+ if theirs.write_all(std::slice::from_ref(byte)).is_err() {
+ break;
+ }
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ });
+ std::thread::spawn(move || {
+ std::thread::sleep(Duration::from_millis(150));
+ kill.try_send(()).unwrap();
+ });
+ let outcome = smol::block_on(smol::future::or(
+ async {
+ process_async_with_peer(stream, Liveness::new(Instant::now()), peer).await?;
+ Ok(true)
+ },
+ async {
+ smol::Timer::after(Duration::from_millis(600)).await;
+ Ok::<bool, anyhow::Error>(false)
+ },
+ ));
+ assert_eq!(outcome.unwrap(), true, "the revoked connection did not end mid-PDU");
+ dribble.join().unwrap();
+ }
+
#[cfg(unix)]
#[test]
fn a_peer_that_answers_the_probe_is_kept_and_not_answered_back() {
diff --git a/wezterm-mux-server-impl/src/lib.rs b/wezterm-mux-server-impl/src/lib.rs
index 748e6f17..920f781c 100644
--- a/wezterm-mux-server-impl/src/lib.rs
+++ b/wezterm-mux-server-impl/src/lib.rs
@@ -17,6 +17,9 @@ pub mod thinkterm_access;
pub mod thinkterm_layout;
pub mod thinkterm_session;
pub mod thinkterm_tree;
+pub mod web_auth;
+pub mod web_http;
+pub mod web_stream;
fn client_domains(config: &config::ConfigHandle) -> Vec<ClientDomainConfig> {
let mut domains = vec![];
diff --git a/wezterm-mux-server-impl/src/sessionhandler.rs b/wezterm-mux-server-impl/src/sessionhandler.rs
index 60a7d310..04faf045 100644
--- a/wezterm-mux-server-impl/src/sessionhandler.rs
+++ b/wezterm-mux-server-impl/src/sessionhandler.rs
@@ -985,8 +985,86 @@ fn schedule_palette_session_cleanup(session_id: PaletteSessionId, reason: &'stat
.detach();
}
+/// Who is on the other end of a connection, as far as the accept layer
+/// could tell. The unix socket and the mTLS port are the server's own
+/// user by construction; a browser is whoever presented a web token.
+#[derive(Debug, Clone)]
+pub enum ConnectionPeer {
+ Local,
+ Web(WebPeer),
+}
+
+/// A browser connection admitted by `web_auth`. The identity it presents
+/// in `SetClientId` is overwritten with this, so `cli list-clients` shows
+/// the token that let it in rather than whatever the page claimed.
+#[derive(Debug, Clone)]
+pub struct WebPeer {
+ pub token_id: String,
+ pub label: String,
+ /// The server's own user: every web session runs as that user.
+ pub username: String,
+ /// Fires when the token is revoked; the connection loop drops the
+ /// socket the moment it does.
+ pub revoked: smol::channel::Receiver<()>,
+}
+
+/// What a browser admitted by a web token may ask for: the terminal, the
+/// mux and the ThinkTerm tree, exactly as a local client would. Not on
+/// the list, deliberately: `GetTlsCreds` (a client certificate neither
+/// expires nor revokes, so a leaked token must not become one) and the
+/// token administration PDUs (a browser minting further browsers is how
+/// one leaked token becomes many).
+fn web_peer_may_send(pdu: &Pdu) -> bool {
+ matches!(
+ pdu,
+ Pdu::Ping(_)
+ | Pdu::Pong(_)
+ | Pdu::GetCodecVersion(_)
+ | Pdu::GetServerOsRelease(_)
+ | Pdu::SetClientId(_)
+ | Pdu::GetClientList(_)
+ | Pdu::ListPanes(_)
+ | Pdu::WriteToPane(_)
+ | Pdu::SendKeyDown(_)
+ | Pdu::SendMouseEvent(_)
+ | Pdu::SendPaste(_)
+ | Pdu::Resize(_)
+ | Pdu::GetLines(_)
+ | Pdu::GetPaneRenderChanges(_)
+ | Pdu::GetPaneRenderableDimensions(_)
+ | Pdu::GetImageCell(_)
+ | Pdu::SearchScrollbackRequest(_)
+ | Pdu::EraseScrollbackRequest(_)
+ | Pdu::SetPalette(_)
+ | Pdu::SetPaneZoomed(_)
+ | Pdu::SplitPane(_)
+ | Pdu::KillPane(_)
+ | Pdu::SpawnV2(_)
+ | Pdu::SetWindowWorkspace(_)
+ | Pdu::RenameWorkspace(_)
+ | Pdu::SetFocusedPane(_)
+ | Pdu::MovePaneToNewTab(_)
+ | Pdu::ActivatePaneDirection(_)
+ | Pdu::GetPaneDirection(_)
+ | Pdu::AdjustPaneSize(_)
+ | Pdu::SpawnPaneInStack(_)
+ | Pdu::ActivatePaneInStack(_)
+ | Pdu::MovePaneToStack(_)
+ | Pdu::GetThinkTermTree(_)
+ | Pdu::MutateThinkTermTree(_)
+ | Pdu::GetThinkTermSessionState(_)
+ | Pdu::EnsureThinkTermThread(_)
+ | Pdu::SetClientViewport(_)
+ | Pdu::ClaimClientViewport(_)
+ | Pdu::SetClientView(_)
+ | Pdu::SetFrontendAccessMode(_)
+ | Pdu::GetAgentStatuses(_)
+ )
+}
+
pub struct SessionHandler {
to_write_tx: PduSender,
+ peer: ConnectionPeer,
per_pane: HashMap<TabId, Arc<Mutex<PerPane>>>,
client_id: Option<Arc<ClientId>>,
client_registration: Option<ClientRegistrationId>,
@@ -1009,8 +1087,13 @@ impl Drop for SessionHandler {
impl SessionHandler {
pub fn new(to_write_tx: PduSender) -> Self {
+ Self::for_peer(to_write_tx, ConnectionPeer::Local)
+ }
+
+ pub fn for_peer(to_write_tx: PduSender, peer: ConnectionPeer) -> Self {
Self {
to_write_tx,
+ peer,
per_pane: HashMap::new(),
client_id: None,
client_registration: None,
@@ -1150,6 +1233,19 @@ impl SessionHandler {
sender.send(DecodedPdu { pdu, serial }).ok();
};
+ // A web session is admitted by a revocable, expiring token; it
+ // may do everything the user could at a keyboard, and nothing that
+ // would turn the token into another credential. The list names
+ // what is allowed, so a request added later is refused here until
+ // someone decides it belongs.
+ if matches!(self.peer, ConnectionPeer::Web(_)) && !web_peer_may_send(&decoded.pdu) {
+ send_response(Err(anyhow!(
+ "{} is not available to a web session",
+ decoded.pdu.pdu_name()
+ )));
+ return;
+ }
+
if requires_existing_frontend_access(&decoded.pdu) {
if let Err(err) = require_registered_frontend_access(
&Mux::get(),
@@ -1218,6 +1314,11 @@ impl SessionHandler {
client_id.hostname =
format!("{} (via proxy pid {})", client_id.hostname, proxy_id.pid);
}
+ if let ConnectionPeer::Web(web) = &self.peer {
+ client_id.username = web.username.clone();
+ client_id.hostname = format!("web:{}", web.label);
+ client_id.ssh_auth_sock = None;
+ }
let client_id = Arc::new(client_id);
if let Some(old_session_id) = self.palette_session_id.take() {
@@ -2184,6 +2285,43 @@ impl SessionHandler {
},
))),
+ Pdu::WebTokenMint(WebTokenMint { label, ttl_secs }) => {
+ catch(
+ move || {
+ let minted = crate::web_auth::WEB_TOKENS.mint(
+ label,
+ ttl_secs.map(Duration::from_secs),
+ )?;
+ let urls = config::configuration()
+ .web_servers
+ .iter()
+ .flat_map(|server| server.urls())
+ // In the fragment: never sent to any server, never
+ // in a Referer, never in an access log.
+ .map(|url| format!("{url}#token={}", minted.token))
+ .collect();
+ Ok(Pdu::WebTokenMintResponse(WebTokenMintResponse {
+ id: minted.id,
+ label: minted.label,
+ token: minted.token,
+ expires_at: minted.expires_at,
+ urls,
+ }))
+ },
+ send_response,
+ );
+ }
+ Pdu::WebTokenList(_) => {
+ send_response(Ok(Pdu::WebTokenListResponse(WebTokenListResponse {
+ tokens: crate::web_auth::WEB_TOKENS.list(),
+ })));
+ }
+ Pdu::WebTokenRevoke(WebTokenRevoke { id }) => {
+ let revoked = crate::web_auth::WEB_TOKENS.revoke(id.as_deref());
+ send_response(Ok(Pdu::WebTokenRevokeResponse(WebTokenRevokeResponse {
+ revoked,
+ })));
+ }
Pdu::GetTlsCreds(_) => {
catch(
move || {
@@ -2317,6 +2455,9 @@ impl SessionHandler {
| Pdu::GetCodecVersionResponse { .. }
| Pdu::WindowWorkspaceChanged { .. }
| Pdu::GetTlsCredsResponse { .. }
+ | Pdu::WebTokenMintResponse { .. }
+ | Pdu::WebTokenListResponse { .. }
+ | Pdu::WebTokenRevokeResponse { .. }
| Pdu::GetClientListResponse { .. }
| Pdu::PaneRemoved { .. }
| Pdu::PaneFocused { .. }
diff --git a/wezterm-mux-server-impl/src/web_auth.rs b/wezterm-mux-server-impl/src/web_auth.rs
new file mode 100644
index 00000000..67a607d6
--- /dev/null
+++ b/wezterm-mux-server-impl/src/web_auth.rs
@@ -0,0 +1,430 @@
+//! Web tokens: the credential a browser presents at the web port.
+//!
+//! A token is full access as the server's user -- everything the unix
+//! socket grants, because everything a mux client can do (spawn a shell,
+//! type into it, read every scrollback) is what the browser client does.
+//! What the token adds over a TLS client certificate is a lifetime and a
+//! revocation: the server keeps only a digest, so a leaked store reveals
+//! nothing, and revoking a token drops the connections it admitted on the
+//! spot.
+
+use anyhow::Context;
+use base64::Engine;
+use codec::WebTokenInfo;
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, LazyLock, Mutex};
+use std::time::{Duration, SystemTime, UNIX_EPOCH};
+
+/// The process-wide store. Configured once at server start with where to
+/// persist, if anywhere.
+pub static WEB_TOKENS: LazyLock<WebTokenStore> = LazyLock::new(WebTokenStore::default);
+
+/// Bytes of entropy in a token; rendered URL-safe base64 without padding.
+const TOKEN_BYTES: usize = 32;
+
+#[derive(Default)]
+pub struct WebTokenStore {
+ /// Shared with every `Admission`, which forgets its connection on drop.
+ inner: Arc<Mutex<Inner>>,
+}
+
+#[derive(Default)]
+struct Inner {
+ tokens: Vec<TokenRecord>,
+ live: Vec<LiveConnection>,
+ persist: Option<PathBuf>,
+ next_connection: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+struct TokenRecord {
+ id: String,
+ label: String,
+ /// sha256 of the token, hex.
+ digest: String,
+ created_at: u64,
+ expires_at: Option<u64>,
+ last_used_at: Option<u64>,
+}
+
+struct LiveConnection {
+ connection: u64,
+ token_id: String,
+ kill: smol::channel::Sender<()>,
+}
+
+/// What `mint` hands back; the token itself is shown once and not kept.
+#[derive(Debug)]
+pub struct MintedToken {
+ pub id: String,
+ pub label: String,
+ pub token: String,
+ pub expires_at: Option<u64>,
+}
+
+/// A connection the store has admitted. Dropping it forgets the
+/// connection; `revoked` fires if its token is revoked while it lives.
+pub struct Admission {
+ pub token_id: String,
+ pub label: String,
+ pub revoked: smol::channel::Receiver<()>,
+ connection: u64,
+ store: Arc<Mutex<Inner>>,
+}
+
+impl std::fmt::Debug for Admission {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("Admission")
+ .field("token_id", &self.token_id)
+ .field("label", &self.label)
+ .finish()
+ }
+}
+
+impl Drop for Admission {
+ fn drop(&mut self) {
+ self.store
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+ .live
+ .retain(|live| live.connection != self.connection);
+ }
+}
+
+fn now_secs() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|d| d.as_secs())
+ .unwrap_or(0)
+}
+
+fn digest_hex(token: &str) -> String {
+ hex::encode(Sha256::digest(token.as_bytes()))
+}
+
+/// Equal without an early exit, so the time taken says nothing about how
+/// many leading bytes matched.
+fn constant_time_eq(a: &str, b: &str) -> bool {
+ let (a, b) = (a.as_bytes(), b.as_bytes());
+ if a.len() != b.len() {
+ return false;
+ }
+ a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
+}
+
+impl WebTokenStore {
+ /// Say where tokens persist, and load what is there. Memory only when
+ /// `persist` is None, in which case a restart forgets every token.
+ /// A store that cannot be read is an empty store, said loudly: the
+ /// server must start whatever state a cache file is in, and a corrupt
+ /// file is moved aside so it can be looked at.
+ pub fn configure(&self, persist: Option<PathBuf>) -> anyhow::Result<()> {
+ let mut inner = self.lock();
+ if let Some(path) = &persist {
+ match std::fs::read(path) {
+ Ok(bytes) => match serde_json::from_slice::<Vec<TokenRecord>>(&bytes) {
+ Ok(tokens) => inner.tokens = tokens,
+ Err(err) => {
+ let aside = path.with_extension("json.corrupt");
+ log::error!(
+ "web token store {} is unreadable ({err}); starting with no web \
+ tokens and moving it to {}",
+ path.display(),
+ aside.display()
+ );
+ if let Err(err) = std::fs::rename(path, &aside) {
+ log::error!("could not move the corrupt store aside: {err}");
+ }
+ }
+ },
+ Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
+ Err(err) => {
+ log::error!(
+ "web token store {} could not be read ({err}); starting with no web tokens",
+ path.display()
+ );
+ }
+ }
+ }
+ inner.persist = persist;
+ if Self::expire(&mut inner, now_secs()) {
+ Self::save(&inner)?;
+ }
+ Ok(())
+ }
+
+ pub fn mint(
+ &self,
+ label: Option<String>,
+ ttl: Option<Duration>,
+ ) -> anyhow::Result<MintedToken> {
+ let mut raw = [0u8; TOKEN_BYTES];
+ getrandom::fill(&mut raw).map_err(|e| anyhow::anyhow!("no entropy: {e}"))?;
+ let token = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(raw);
+ let id = uuid::Uuid::new_v4().simple().to_string()[..12].to_string();
+ let now = now_secs();
+ let expires_at = ttl.map(|ttl| now.saturating_add(ttl.as_secs()));
+ let label = label
+ .filter(|l| !l.trim().is_empty())
+ .unwrap_or_else(|| format!("token-{id}"));
+ let record = TokenRecord {
+ id: id.clone(),
+ label: label.clone(),
+ digest: digest_hex(&token),
+ created_at: now,
+ expires_at,
+ last_used_at: None,
+ };
+ let mut inner = self.lock();
+ Self::expire(&mut inner, now);
+ inner.tokens.push(record);
+ Self::save(&inner)?;
+ Ok(MintedToken {
+ id,
+ label,
+ token,
+ expires_at,
+ })
+ }
+
+ /// Check a presented token. On success the connection is registered
+ /// so that revoking the token can drop it.
+ pub fn verify(&self, presented: &str) -> Option<Admission> {
+ let digest = digest_hex(presented);
+ let now = now_secs();
+ let mut inner = self.lock();
+ if Self::expire(&mut inner, now) {
+ if let Err(err) = Self::save(&inner) {
+ log::warn!("web token store not saved: {err:#}");
+ }
+ }
+ // Compare against every record: the match position must not leak
+ // through timing either.
+ let mut found: Option<usize> = None;
+ for (idx, record) in inner.tokens.iter().enumerate() {
+ if constant_time_eq(&record.digest, &digest) {
+ found = Some(idx);
+ }
+ }
+ let idx = found?;
+ // Recorded in memory; written out with the next mint, revoke or
+ // sweep rather than on every connection.
+ inner.tokens[idx].last_used_at = Some(now);
+ let token_id = inner.tokens[idx].id.clone();
+ let label = inner.tokens[idx].label.clone();
+ let (kill, revoked) = smol::channel::bounded(1);
+ inner.next_connection += 1;
+ let connection = inner.next_connection;
+ inner.live.push(LiveConnection {
+ connection,
+ token_id: token_id.clone(),
+ kill,
+ });
+ Some(Admission {
+ token_id,
+ label,
+ revoked,
+ connection,
+ store: Arc::clone(&self.inner),
+ })
+ }
+
+ /// Drop expired tokens and cut their connections. The listener runs
+ /// this on a timer: a token's lifetime ends when it says, not when
+ /// someone next happens to mint or list.
+ pub fn sweep(&self) {
+ let mut inner = self.lock();
+ if Self::expire(&mut inner, now_secs()) {
+ if let Err(err) = Self::save(&inner) {
+ log::warn!("web token store not saved: {err:#}");
+ }
+ }
+ }
+
+ pub fn list(&self) -> Vec<WebTokenInfo> {
+ let mut inner = self.lock();
+ if Self::expire(&mut inner, now_secs()) {
+ if let Err(err) = Self::save(&inner) {
+ log::warn!("web token store not saved: {err:#}");
+ }
+ }
+ inner
+ .tokens
+ .iter()
+ .map(|record| WebTokenInfo {
+ id: record.id.clone(),
+ label: record.label.clone(),
+ created_at: record.created_at,
+ expires_at: record.expires_at,
+ last_used_at: record.last_used_at,
+ live_connections: inner
+ .live
+ .iter()
+ .filter(|live| live.token_id == record.id)
+ .count() as u32,
+ })
+ .collect()
+ }
+
+ /// Revoke one token, or all of them. Returns how many were revoked;
+ /// their live connections are told to drop.
+ pub fn revoke(&self, id: Option<&str>) -> u32 {
+ let mut inner = self.lock();
+ let before = inner.tokens.len();
+ let gone: Vec<String> = match id {
+ Some(id) => {
+ inner.tokens.retain(|record| record.id != id);
+ vec![id.to_string()]
+ }
+ None => {
+ let ids = inner.tokens.iter().map(|r| r.id.clone()).collect();
+ inner.tokens.clear();
+ ids
+ }
+ };
+ let revoked = (before - inner.tokens.len()) as u32;
+ for live in inner.live.iter().filter(|live| gone.contains(&live.token_id)) {
+ let _ = live.kill.try_send(());
+ }
+ if let Err(err) = Self::save(&inner) {
+ log::warn!("web token store not saved: {err:#}");
+ }
+ revoked
+ }
+
+ fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
+ self.inner.lock().unwrap_or_else(|e| e.into_inner())
+ }
+
+ /// Drop tokens past their expiry and cut their connections. True when
+ /// something was dropped, so the caller knows to save.
+ fn expire(inner: &mut Inner, now: u64) -> bool {
+ let expired: Vec<String> = inner
+ .tokens
+ .iter()
+ .filter(|r| r.expires_at.is_some_and(|t| t <= now))
+ .map(|r| r.id.clone())
+ .collect();
+ if expired.is_empty() {
+ return false;
+ }
+ inner.tokens.retain(|r| !expired.contains(&r.id));
+ for live in inner.live.iter().filter(|l| expired.contains(&l.token_id)) {
+ let _ = live.kill.try_send(());
+ }
+ true
+ }
+
+ fn save(inner: &Inner) -> anyhow::Result<()> {
+ let Some(path) = &inner.persist else {
+ return Ok(());
+ };
+ write_private(path, &serde_json::to_vec_pretty(&inner.tokens)?)
+ }
+}
+
+/// Write `bytes` to `path` readable by the owner only, replacing whatever
+/// was there in one step. A uniquely named temporary file (created 0600,
+/// never following a planted symlink), synced before the rename so a
+/// crash leaves either the old file or the new one, never a torn one.
+fn write_private(path: &Path, bytes: &[u8]) -> anyhow::Result<()> {
+ let dir = match path.parent() {
+ Some(dir) if !dir.as_os_str().is_empty() => dir,
+ _ => Path::new("."),
+ };
+ std::fs::create_dir_all(dir)?;
+ let mut tmp = tempfile::Builder::new()
+ .prefix(".web-tokens.")
+ .tempfile_in(dir)
+ .with_context(|| format!("creating a temporary file in {}", dir.display()))?;
+ std::io::Write::write_all(&mut tmp, bytes)?;
+ tmp.as_file().sync_all()?;
+ tmp.persist(path)
+ .with_context(|| format!("replacing {}", path.display()))?;
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn fresh() -> WebTokenStore {
+ WebTokenStore::default()
+ }
+
+ #[test]
+ fn a_minted_token_verifies_and_a_stranger_does_not() {
+ let store = fresh();
+ let minted = store.mint(Some("laptop".into()), None).unwrap();
+ let admitted = store.verify(&minted.token).expect("the real token");
+ assert_eq!(admitted.token_id, minted.id);
+ assert_eq!(admitted.label, "laptop");
+ assert!(store.verify("not-a-token").is_none());
+ let mut wrong = minted.token.clone();
+ wrong.replace_range(0..1, if minted.token.starts_with('A') { "B" } else { "A" });
+ assert!(store.verify(&wrong).is_none());
+ assert_eq!(store.list()[0].live_connections, 1);
+ drop(admitted);
+ assert_eq!(store.list()[0].live_connections, 0);
+ }
+
+ #[test]
+ fn revoking_drops_the_live_connection_and_forgets_the_token() {
+ let store = fresh();
+ let minted = store.mint(None, None).unwrap();
+ let admitted = store.verify(&minted.token).unwrap();
+ assert_eq!(store.revoke(Some(&minted.id)), 1);
+ assert!(admitted.revoked.try_recv().is_ok(), "the kill switch fired");
+ assert!(store.verify(&minted.token).is_none());
+ assert_eq!(store.revoke(Some(&minted.id)), 0);
+ }
+
+ #[test]
+ fn expired_tokens_are_gone_and_nothing_persists_but_digests() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("web-tokens.json");
+ let store = fresh();
+ store.configure(Some(path.clone())).unwrap();
+ let keep = store.mint(Some("keep".into()), None).unwrap();
+ let brief = store
+ .mint(Some("brief".into()), Some(Duration::from_secs(0)))
+ .unwrap();
+ assert!(store.verify(&brief.token).is_none(), "already expired");
+ let on_disk = std::fs::read_to_string(&path).unwrap();
+ assert!(on_disk.contains("keep"));
+ assert!(!on_disk.contains(&keep.token), "the token itself is never written");
+ assert!(!on_disk.contains("brief"), "expired tokens are dropped from the file");
+
+ let reloaded = fresh();
+ reloaded.configure(Some(path)).unwrap();
+ assert!(reloaded.verify(&keep.token).is_some());
+ }
+
+ #[test]
+ fn revoke_all_clears_everything() {
+ let store = fresh();
+ store.mint(None, None).unwrap();
+ store.mint(None, None).unwrap();
+ assert_eq!(store.revoke(None), 2);
+ assert!(store.list().is_empty());
+ }
+
+ /// A torn or garbage store file must not stop the server: it is moved
+ /// aside and the store starts empty.
+ #[test]
+ fn a_corrupt_store_starts_empty_and_is_moved_aside() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("web-tokens.json");
+ std::fs::write(&path, b"[{\"id\": \"trunc").unwrap();
+ let store = WebTokenStore::default();
+ store.configure(Some(path.clone())).expect("a corrupt store is not an error");
+ assert!(store.list().is_empty());
+ assert!(!path.exists(), "the corrupt file was left in place");
+ assert!(dir.path().join("web-tokens.json.corrupt").exists());
+ // And the store is usable: a mint persists a fresh file.
+ store.mint(Some("after".into()), None).unwrap();
+ assert!(path.exists());
+ }
+}
diff --git a/wezterm-mux-server-impl/src/web_http.rs b/wezterm-mux-server-impl/src/web_http.rs
new file mode 100644
index 00000000..5fe83eb0
--- /dev/null
+++ b/wezterm-mux-server-impl/src/web_http.rs
@@ -0,0 +1,959 @@
+//! The HTTP side of a web listener: serve the browser client's bundle, and
+//! turn a WebSocket upgrade into a mux connection once the token checks
+//! out. The check happens here, before `dispatch` ever sees the peer: the
+//! session handler answers `ListPanes` and `GetLines` to anyone, so an
+//! unauthenticated socket must never reach it.
+//!
+//! Only the request head is parsed by hand (httparse); the WebSocket
+//! framing after the upgrade is soketto's, through `web_stream`.
+
+use crate::dispatch::process_stream;
+use crate::sessionhandler::{ConnectionPeer, WebPeer};
+use crate::web_auth::WEB_TOKENS;
+use crate::web_stream::{Prefixed, WebStream};
+use base64::Engine;
+use config::{default_port, is_loopback_host, split_authority, Origin};
+use futures::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
+use sha1::{Digest, Sha1};
+use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::Arc;
+use std::time::Duration;
+
+/// The one subprotocol the browser client speaks. A token rides beside it
+/// in the same header, the only request header a browser lets a page set.
+pub const SUBPROTOCOL: &str = "thinkterm.v1";
+pub const TOKEN_PROTOCOL_PREFIX: &str = "tt-token.";
+
+const MAX_HEAD: usize = 16 * 1024;
+/// The whole request head must arrive within this, not each byte of it.
+const HEAD_TIMEOUT: Duration = Duration::from_secs(10);
+/// Each piece of a response must be taken within this. A peer that opens
+/// its window slower than that is holding a seat for nothing.
+const WRITE_STALL: Duration = Duration::from_secs(15);
+/// Files leave in pieces of this size; a response never holds more.
+const WRITE_CHUNK: usize = 64 * 1024;
+/// Connections allowed to sit before the token check at once. Beyond it a
+/// new socket gets 503 and is closed: the port must not be able to exhaust
+/// the process's descriptors, which the unix listener shares. The seat is
+/// held for the whole of a plain response too, so slow readers of the
+/// bundle are bounded by the same number.
+const MAX_PRE_AUTH: usize = 128;
+
+static PRE_AUTH: AtomicUsize = AtomicUsize::new(0);
+
+/// One connection's seat before authentication; released on drop. The
+/// TLS listener takes it before the handshake, which is the point: the
+/// handshake is what a stranger can make cost the most.
+pub struct PreAuthSeat;
+
+impl PreAuthSeat {
+ pub fn take() -> Option<Self> {
+ if PRE_AUTH.fetch_add(1, Ordering::SeqCst) < MAX_PRE_AUTH {
+ Some(Self)
+ } else {
+ PRE_AUTH.fetch_sub(1, Ordering::SeqCst);
+ None
+ }
+ }
+}
+
+impl Drop for PreAuthSeat {
+ fn drop(&mut self) {
+ PRE_AUTH.fetch_sub(1, Ordering::SeqCst);
+ }
+}
+
+/// A request line for the log: never the query string, which is where a
+/// bootstrap token would be.
+fn describe(req: &Request) -> String {
+ let path = req.path.split(['?', '#']).next().unwrap_or("");
+ format!("{} {}", req.method, path)
+}
+const WS_GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
+
+/// What a listener needs to answer requests, derived once from its config.
+/// Hosts and origins are compared taken apart -- scheme, host, the port
+/// the URL means -- so `mux.example.net` and `mux.example.net:443` are
+/// the same name, as they are to a browser.
+#[derive(Debug)]
+pub struct WebSite {
+ /// Names, with the port they mean, that this listener answers to.
+ hosts: Vec<(String, Option<u16>)>,
+ /// Origins allowed to open the WebSocket.
+ allowed_origins: Vec<Origin>,
+ /// Whether the origins were configured, as opposed to derived from
+ /// the bind address.
+ configured_origins: bool,
+ scheme: &'static str,
+ /// The port clients reach us on, when the bind address has one.
+ port: Option<u16>,
+ /// A loopback listener is reached through `ssh -L` on whatever local
+ /// port the user chose, so any loopback name is ours.
+ loopback: bool,
+ static_dir: Option<PathBuf>,
+ /// The server's own user; every web session runs as that user.
+ username: String,
+ pub describe: String,
+}
+
+impl WebSite {
+ pub fn from_config(
+ server: &config::WebServer,
+ static_dir: Option<PathBuf>,
+ username: String,
+ ) -> Self {
+ let scheme = server.scheme();
+ let allowed_origins: Vec<Origin> = server
+ .effective_allowed_origins()
+ .iter()
+ .filter_map(|o| {
+ let parsed = Origin::parse(o);
+ if parsed.is_none() {
+ log::warn!("allowed_origins entry {o:?} is not an origin; ignored");
+ }
+ parsed
+ })
+ .collect();
+ let mut hosts: Vec<(String, Option<u16>)> = server
+ .url_hosts()
+ .iter()
+ .filter_map(|h| split_authority(h))
+ .map(|(host, port)| (host, port.or(default_port(scheme))))
+ .collect();
+ // A page served from a configured origin reaches us by whatever
+ // name it was told; those names are ours too, spelled as the
+ // origin spells them (a `Host` has no scheme to default from).
+ for origin in &allowed_origins {
+ let name = (origin.host.clone(), origin.port_given);
+ if !hosts.contains(&name) {
+ hosts.push(name);
+ }
+ }
+ let (_, port) = server.host_and_port();
+ Self {
+ hosts,
+ allowed_origins,
+ configured_origins: !server.allowed_origins.is_empty(),
+ scheme,
+ port: port.or(default_port(scheme)),
+ loopback: server.is_loopback(),
+ static_dir,
+ username,
+ describe: server.bind_address.clone(),
+ }
+ }
+
+ /// The `Host` header taken apart, with the port it means.
+ fn host_name(&self, host: &str) -> Option<(String, Option<u16>)> {
+ let (name, port) = split_authority(host)?;
+ Some((name, port.or(default_port(self.scheme))))
+ }
+
+ fn host_allowed(&self, host: &str) -> bool {
+ let Some(name) = self.host_name(host) else {
+ return false;
+ };
+ let Some(as_written) = split_authority(host) else {
+ return false;
+ };
+ if self.hosts.contains(&name) || self.hosts.contains(&as_written) {
+ return true;
+ }
+ let (host, port) = &name;
+ // Loopback names cannot be rebound to point elsewhere, and a
+ // loopback listener has no say in which local port a forward uses.
+ if self.loopback && is_loopback_host(host) {
+ return true;
+ }
+ // An IP literal cannot be a DNS-rebinding name; accept it when it
+ // carries our port.
+ host.parse::<std::net::IpAddr>().is_ok() && *port == self.port
+ }
+
+ /// Whether `origin` may open the socket, given the `Host` the same
+ /// request carried. Without configured origins a loopback listener
+ /// also accepts the page it served itself through a forward: a
+ /// loopback origin, on our scheme, at exactly the authority the
+ /// request was addressed to.
+ fn origin_allowed(&self, origin: &str, host: Option<&str>) -> bool {
+ let Some(origin) = Origin::parse(origin) else {
+ return false;
+ };
+ if self.allowed_origins.iter().any(|o| o.same_as(&origin)) {
+ return true;
+ }
+ if self.configured_origins || !self.loopback || !is_loopback_host(&origin.host) {
+ return false;
+ }
+ origin.scheme == self.scheme
+ && host.and_then(|h| self.host_name(h)) == Some((origin.host, origin.port))
+ }
+}
+
+/// A parsed request head.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Request {
+ pub method: String,
+ pub path: String,
+ /// Names lowercase.
+ pub headers: Vec<(String, String)>,
+}
+
+impl Request {
+ pub fn header(&self, name: &str) -> Option<&str> {
+ self.headers
+ .iter()
+ .find(|(n, _)| n == name)
+ .map(|(_, v)| v.as_str())
+ }
+
+ /// A comma-separated header, each item trimmed; every occurrence of
+ /// the header contributes.
+ pub fn header_list(&self, name: &str) -> Vec<String> {
+ self.headers
+ .iter()
+ .filter(|(n, _)| n == name)
+ .flat_map(|(_, v)| v.split(',').map(|s| s.trim().to_string()))
+ .filter(|s| !s.is_empty())
+ .collect()
+ }
+
+ fn header_has_token(&self, name: &str, token: &str) -> bool {
+ self.header_list(name)
+ .iter()
+ .any(|v| v.eq_ignore_ascii_case(token))
+ }
+}
+
+/// Parse a request head. `Ok(None)` means more bytes are needed;
+/// `Ok(Some((request, head_len)))` says how many bytes the head took.
+pub fn parse_head(bytes: &[u8]) -> Result<Option<(Request, usize)>, String> {
+ let mut headers = [httparse::EMPTY_HEADER; 64];
+ let mut req = httparse::Request::new(&mut headers);
+ match req.parse(bytes) {
+ Ok(httparse::Status::Partial) => Ok(None),
+ Ok(httparse::Status::Complete(len)) => {
+ let method = req.method.unwrap_or("").to_string();
+ let path = req.path.unwrap_or("/").to_string();
+ let headers = req
+ .headers
+ .iter()
+ .map(|h| {
+ (
+ h.name.to_ascii_lowercase(),
+ String::from_utf8_lossy(h.value).trim().to_string(),
+ )
+ })
+ .collect();
+ Ok(Some((
+ Request {
+ method,
+ path,
+ headers,
+ },
+ len,
+ )))
+ }
+ Err(err) => Err(err.to_string()),
+ }
+}
+
+/// Where a request goes.
+#[derive(Debug, PartialEq, Eq)]
+pub enum Route {
+ /// Serve this file from the bundle.
+ Static(PathBuf),
+ /// A WebSocket upgrade carrying a token; verified by the caller.
+ Upgrade { key: String, token: String },
+ Reject { status: u16, reason: &'static str },
+}
+
+fn reject(status: u16, reason: &'static str) -> Route {
+ Route::Reject { status, reason }
+}
+
+pub fn route(site: &WebSite, req: &Request) -> Route {
+ if req.headers.iter().filter(|(n, _)| n == "host").count() > 1 {
+ return reject(400, "One Host header, please");
+ }
+ match req.header("host") {
+ Some(host) if site.host_allowed(host) => {}
+ Some(_) => return reject(403, "Host not served here"),
+ None => return reject(400, "Host header required"),
+ }
+ if req.method != "GET" {
+ return reject(405, "Method not allowed");
+ }
+
+ let wants_upgrade = req.header_has_token("connection", "upgrade")
+ && req
+ .header("upgrade")
+ .is_some_and(|u| u.eq_ignore_ascii_case("websocket"));
+ if !wants_upgrade {
+ let Some(root) = &site.static_dir else {
+ return reject(404, "No web bundle is installed on this server");
+ };
+ return match safe_static_path(root, &req.path) {
+ Some(path) => Route::Static(path),
+ None => reject(404, "Not found"),
+ };
+ }
+
+ if req.header("sec-websocket-version") != Some("13") {
+ return reject(400, "Unsupported WebSocket version");
+ }
+ let Some(key) = req.header("sec-websocket-key") else {
+ return reject(400, "Sec-WebSocket-Key required");
+ };
+ // Every browser sends Origin on an upgrade and no page can forge it.
+ // Without this check any site the user visits could open our socket:
+ // WebSocket handshakes are not subject to the same-origin policy.
+ match req.header("origin") {
+ Some(origin) if site.origin_allowed(origin, req.header("host")) => {}
+ Some(_) => return reject(403, "Origin not allowed"),
+ None => return reject(403, "Origin required"),
+ }
+ let protocols = req.header_list("sec-websocket-protocol");
+ if !protocols.iter().any(|p| p == SUBPROTOCOL) {
+ return reject(400, "Unknown WebSocket subprotocol");
+ }
+ let mut tokens = protocols
+ .iter()
+ .filter_map(|p| p.strip_prefix(TOKEN_PROTOCOL_PREFIX));
+ match (tokens.next(), tokens.next()) {
+ (Some(token), None) if !token.is_empty() => Route::Upgrade {
+ key: key.to_string(),
+ token: token.to_string(),
+ },
+ _ => reject(401, "Web token required"),
+ }
+}
+
+/// RFC 6455 §4.2.2: the key the client sent, the GUID, sha1, base64.
+pub fn accept_key(key: &str) -> String {
+ let mut hasher = Sha1::new();
+ hasher.update(key.as_bytes());
+ hasher.update(WS_GUID.as_bytes());
+ base64::engine::general_purpose::STANDARD.encode(hasher.finalize())
+}
+
+/// Resolve a URL path inside the bundle directory. `/` is the page; every
+/// segment must be a plain file name, so nothing outside `root` can be
+/// named however the path is spelled.
+pub fn safe_static_path(root: &Path, url_path: &str) -> Option<PathBuf> {
+ let path = url_path.split(['?', '#']).next().unwrap_or("");
+ let path = if path == "/" || path.is_empty() {
+ "/index.html"
+ } else {
+ path
+ };
+ let mut resolved = root.to_path_buf();
+ for segment in path.strip_prefix('/').unwrap_or(path).split('/') {
+ let plain = !segment.is_empty()
+ && !segment.starts_with('.')
+ && segment
+ .bytes()
+ .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'));
+ if !plain {
+ return None;
+ }
+ resolved.push(segment);
+ }
+ Some(resolved)
+}
+
+pub fn content_type(path: &Path) -> &'static str {
+ match path.extension().and_then(|e| e.to_str()).unwrap_or("") {
+ "html" => "text/html; charset=utf-8",
+ "js" | "mjs" => "text/javascript; charset=utf-8",
+ "wasm" => "application/wasm",
+ "css" => "text/css; charset=utf-8",
+ "json" | "map" => "application/json",
+ "ttf" => "font/ttf",
+ "otf" => "font/otf",
+ "woff2" => "font/woff2",
+ "png" => "image/png",
+ "svg" => "image/svg+xml",
+ "ico" => "image/x-icon",
+ "txt" => "text/plain; charset=utf-8",
+ _ => "application/octet-stream",
+ }
+}
+
+fn response_head(status: u16, reason: &str, extra: &[(&str, &str)], body_len: usize) -> Vec<u8> {
+ let mut out = format!(
+ "HTTP/1.1 {status} {reason}\r\nConnection: close\r\n\
+ X-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer\r\n"
+ );
+ for (name, value) in extra {
+ out.push_str(name);
+ out.push_str(": ");
+ out.push_str(value);
+ out.push_str("\r\n");
+ }
+ out.push_str(&format!("Content-Length: {body_len}\r\n\r\n"));
+ out.into_bytes()
+}
+
+/// Write `bytes` a piece at a time, each within `WRITE_STALL`. `Err` means
+/// the peer stopped taking them; the caller gives up on it.
+async fn write_within<S: AsyncWrite + Unpin>(stream: &mut S, bytes: &[u8]) -> Result<(), ()> {
+ for chunk in bytes.chunks(WRITE_CHUNK) {
+ let written = smol::future::or(
+ async { stream.write_all(chunk).await.is_ok() },
+ async {
+ smol::Timer::after(WRITE_STALL).await;
+ false
+ },
+ )
+ .await;
+ if !written {
+ return Err(());
+ }
+ }
+ Ok(())
+}
+
+/// Flush and close, neither for longer than a stalled write is allowed.
+async fn finish<S: AsyncWrite + Unpin>(stream: &mut S) {
+ smol::future::or(
+ async {
+ let _ = stream.flush().await;
+ let _ = stream.close().await;
+ },
+ async {
+ smol::Timer::after(WRITE_STALL).await;
+ },
+ )
+ .await;
+}
+
+async fn respond<S: AsyncWrite + Unpin>(
+ stream: &mut S,
+ status: u16,
+ reason: &str,
+ extra: &[(&str, &str)],
+ body: &[u8],
+) {
+ let mut bytes = response_head(status, reason, extra, body.len());
+ bytes.extend_from_slice(body);
+ if write_within(stream, &bytes).await.is_ok() {
+ finish(stream).await;
+ }
+}
+
+/// Send a file from the bundle without holding more than one piece of it:
+/// a slow reader of the wasm costs a seat, not megabytes.
+async fn send_file<S: AsyncWrite + Unpin>(stream: &mut S, path: &Path) {
+ let file = match smol::fs::File::open(path).await {
+ Ok(file) => file,
+ Err(_) => {
+ return respond(
+ stream,
+ 404,
+ "Not Found",
+ &[("Content-Type", "text/plain; charset=utf-8")],
+ b"Not found",
+ )
+ .await;
+ }
+ };
+ let len = match file.metadata().await {
+ Ok(meta) if meta.is_file() => meta.len(),
+ _ => {
+ return respond(
+ stream,
+ 404,
+ "Not Found",
+ &[("Content-Type", "text/plain; charset=utf-8")],
+ b"Not found",
+ )
+ .await;
+ }
+ };
+ let head = response_head(
+ 200,
+ "OK",
+ &[
+ ("Content-Type", content_type(path)),
+ ("Cache-Control", "no-cache"),
+ ],
+ len as usize,
+ );
+ if write_within(stream, &head).await.is_err() {
+ return;
+ }
+ let mut file = file;
+ let mut buf = vec![0u8; WRITE_CHUNK];
+ let mut sent = 0u64;
+ while sent < len {
+ let want = ((len - sent) as usize).min(buf.len());
+ let n = match file.read(&mut buf[..want]).await {
+ // A file that shrank under us: the browser sees a short body
+ // and retries; nothing better can be said mid-response.
+ Ok(0) | Err(_) => break,
+ Ok(n) => n,
+ };
+ if write_within(stream, &buf[..n]).await.is_err() {
+ return;
+ }
+ sent += n as u64;
+ }
+ finish(stream).await;
+}
+
+/// One accepted socket, from the first byte of the request to the end of
+/// the response -- or, for an admitted WebSocket, the end of the session.
+pub async fn serve<S>(mut stream: S, site: Arc<WebSite>)
+where
+ S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
+{
+ let Some(seat) = PreAuthSeat::take() else {
+ respond(&mut stream, 503, "Service Unavailable", &[], b"").await;
+ return;
+ };
+ serve_seated(stream, site, seat).await
+}
+
+/// `serve` for a connection whose seat was taken earlier (before a TLS
+/// handshake).
+pub async fn serve_seated<S>(mut stream: S, site: Arc<WebSite>, seat: PreAuthSeat)
+where
+ S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
+{
+ let mut head = Vec::with_capacity(1024);
+ let mut buf = [0u8; 4096];
+ let mut deadline = smol::Timer::after(HEAD_TIMEOUT);
+ let (request, head_len) = loop {
+ let read = smol::future::or(
+ async { Some(stream.read(&mut buf).await) },
+ async {
+ (&mut deadline).await;
+ None
+ },
+ )
+ .await;
+ match read {
+ None => {
+ respond(&mut stream, 408, "Request Timeout", &[], b"").await;
+ return;
+ }
+ Some(Ok(0)) => return,
+ Some(Err(err)) => {
+ log::debug!("web request read failed: {err}");
+ return;
+ }
+ Some(Ok(n)) => head.extend_from_slice(&buf[..n]),
+ }
+ match parse_head(&head) {
+ Ok(Some(parsed)) => break parsed,
+ Ok(None) if head.len() > MAX_HEAD => {
+ respond(&mut stream, 431, "Request Header Fields Too Large", &[], b"").await;
+ return;
+ }
+ Ok(None) => continue,
+ Err(err) => {
+ log::debug!("web request rejected: {err}");
+ respond(&mut stream, 400, "Bad Request", &[], b"").await;
+ return;
+ }
+ }
+ };
+
+ match route(&site, &request) {
+ Route::Reject { status, reason } => {
+ log::debug!(
+ "web request {} from origin {:?} rejected: {status} {reason}",
+ describe(&request),
+ request.header("origin")
+ );
+ respond(
+ &mut stream,
+ status,
+ reason,
+ &[("Content-Type", "text/plain; charset=utf-8")],
+ reason.as_bytes(),
+ )
+ .await;
+ }
+ Route::Static(path) => send_file(&mut stream, &path).await,
+ Route::Upgrade { key, token } => {
+ let Some(admission) = WEB_TOKENS.verify(&token) else {
+ log::warn!(
+ "web socket from origin {:?} refused: unknown or expired token",
+ request.header("origin")
+ );
+ respond(
+ &mut stream,
+ 401,
+ "Unauthorized",
+ &[("Content-Type", "text/plain; charset=utf-8")],
+ b"Web token unknown or expired",
+ )
+ .await;
+ return;
+ };
+ // Admitted: the seat is for the unauthenticated wait only.
+ drop(seat);
+ let accept = accept_key(&key);
+ let reply = format!(
+ "HTTP/1.1 101 Switching Protocols\r\n\
+ Upgrade: websocket\r\n\
+ Connection: Upgrade\r\n\
+ Sec-WebSocket-Accept: {accept}\r\n\
+ Sec-WebSocket-Protocol: {SUBPROTOCOL}\r\n\r\n"
+ );
+ if let Err(err) = stream.write_all(reply.as_bytes()).await {
+ log::debug!("web socket upgrade reply failed: {err}");
+ return;
+ }
+ let _ = stream.flush().await;
+ log::info!(
+ "web client admitted on {} with token {} ({})",
+ site.describe,
+ admission.token_id,
+ admission.label
+ );
+ let peer = ConnectionPeer::Web(WebPeer {
+ token_id: admission.token_id.clone(),
+ label: admission.label.clone(),
+ username: site.username.clone(),
+ revoked: admission.revoked.clone(),
+ });
+ let leftover = head[head_len..].to_vec();
+ let ws = WebStream::new(Prefixed::new(leftover, stream));
+ if let Err(err) = process_stream(ws, peer).await {
+ log::error!("web client connection ended: {err:#}");
+ }
+ log::info!(
+ "web client with token {} disconnected",
+ admission.token_id
+ );
+ drop(admission);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn site() -> WebSite {
+ WebSite::from_config(&config::WebServer::default(), Some("/srv/web".into()), "me".into())
+ }
+
+ fn request(method: &str, path: &str, headers: &[(&str, &str)]) -> Request {
+ Request {
+ method: method.into(),
+ path: path.into(),
+ headers: headers
+ .iter()
+ .map(|(n, v)| (n.to_ascii_lowercase(), v.to_string()))
+ .collect(),
+ }
+ }
+
+ fn upgrade_headers<'a>(origin: &'a str, protocols: &'a str) -> Vec<(&'a str, &'a str)> {
+ vec![
+ ("Host", "127.0.0.1:8088"),
+ ("Connection", "keep-alive, Upgrade"),
+ ("Upgrade", "websocket"),
+ ("Sec-WebSocket-Version", "13"),
+ ("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="),
+ ("Origin", origin),
+ ("Sec-WebSocket-Protocol", protocols),
+ ]
+ }
+
+ #[test]
+ fn the_rfc_sample_key_produces_the_rfc_sample_accept() {
+ // RFC 6455 section 1.3.
+ assert_eq!(
+ accept_key("dGhlIHNhbXBsZSBub25jZQ=="),
+ "s3pPLMBiTxaQ9kYGzzhZRbK+xOo="
+ );
+ }
+
+ #[test]
+ fn a_complete_head_parses_and_reports_its_length() {
+ let bytes = b"GET /index.html HTTP/1.1\r\nHost: localhost:8088\r\nX-A: 1, 2\r\nX-A: 3\r\n\r\nrest";
+ let (req, len) = parse_head(bytes).unwrap().expect("complete");
+ assert_eq!(len, bytes.len() - 4);
+ assert_eq!(req.method, "GET");
+ assert_eq!(req.path, "/index.html");
+ assert_eq!(req.header("host"), Some("localhost:8088"));
+ assert_eq!(req.header_list("x-a"), vec!["1", "2", "3"]);
+ assert!(parse_head(b"GET / HTTP/1.1\r\nHost: x").unwrap().is_none());
+ assert!(parse_head(b"\x00\x01 garbage").is_err());
+ }
+
+ #[test]
+ fn static_paths_stay_inside_the_bundle() {
+ let root = Path::new("/srv/web");
+ assert_eq!(safe_static_path(root, "/"), Some("/srv/web/index.html".into()));
+ assert_eq!(
+ safe_static_path(root, "/pkg/app.js?v=1"),
+ Some("/srv/web/pkg/app.js".into())
+ );
+ assert_eq!(safe_static_path(root, "/../etc/passwd"), None);
+ assert_eq!(safe_static_path(root, "/pkg/../../x"), None);
+ assert_eq!(safe_static_path(root, "/.hidden"), None);
+ assert_eq!(safe_static_path(root, "//x"), None);
+ assert_eq!(safe_static_path(root, "/a%2fb"), None);
+ }
+
+ #[test]
+ fn plain_requests_are_static_and_need_a_known_host() {
+ let site = site();
+ let ok = request("GET", "/", &[("Host", "localhost:8088")]);
+ assert_eq!(route(&site, &ok), Route::Static("/srv/web/index.html".into()));
+ let ip = request("GET", "/", &[("Host", "127.0.0.1:8088")]);
+ assert!(matches!(route(&site, &ip), Route::Static(_)));
+ let rebound = request("GET", "/", &[("Host", "evil.example:8088")]);
+ assert_eq!(route(&site, &rebound), reject(403, "Host not served here"));
+ let wrong_port = request("GET", "/", &[("Host", "10.0.0.5:9999")]);
+ assert_eq!(route(&site, &wrong_port), reject(403, "Host not served here"));
+ // Through `ssh -L 9000:127.0.0.1:8088`: a loopback name on a port
+ // the listener never heard of is still this machine.
+ let forwarded = request("GET", "/", &[("Host", "localhost:9000")]);
+ assert!(matches!(route(&site, &forwarded), Route::Static(_)));
+ let bare = request("GET", "/", &[("Host", "localhost")]);
+ assert!(matches!(route(&site, &bare), Route::Static(_)));
+ let junk = request("GET", "/", &[("Host", "local host")]);
+ assert_eq!(route(&site, &junk), reject(403, "Host not served here"));
+ let post = request("POST", "/", &[("Host", "localhost:8088")]);
+ assert_eq!(route(&site, &post), reject(405, "Method not allowed"));
+ let nohost = request("GET", "/", &[]);
+ assert_eq!(route(&site, &nohost), reject(400, "Host header required"));
+ let two_hosts = request("GET", "/", &[("Host", "localhost:8088"), ("Host", "evil.example")]);
+ assert_eq!(route(&site, &two_hosts), reject(400, "One Host header, please"));
+ let v6 = request("GET", "/", &[("Host", "[::1]:8088")]);
+ assert!(matches!(route(&site, &v6), Route::Static(_)));
+ }
+
+ #[test]
+ fn an_upgrade_needs_our_origin_our_subprotocol_and_one_token() {
+ let site = site();
+ let good = request(
+ "GET",
+ "/ws",
+ &upgrade_headers("http://localhost:8088", "thinkterm.v1, tt-token.abc"),
+ );
+ assert_eq!(
+ route(&site, &good),
+ Route::Upgrade {
+ key: "dGhlIHNhbXBsZSBub25jZQ==".into(),
+ token: "abc".into()
+ }
+ );
+ let foreign = request(
+ "GET",
+ "/ws",
+ &upgrade_headers("https://evil.example", "thinkterm.v1, tt-token.abc"),
+ );
+ assert_eq!(route(&site, &foreign), reject(403, "Origin not allowed"));
+ let no_token = request("GET", "/ws", &upgrade_headers("http://localhost:8088", "thinkterm.v1"));
+ assert_eq!(route(&site, &no_token), reject(401, "Web token required"));
+ let two_tokens = request(
+ "GET",
+ "/ws",
+ &upgrade_headers("http://localhost:8088", "thinkterm.v1, tt-token.a, tt-token.b"),
+ );
+ assert_eq!(route(&site, &two_tokens), reject(401, "Web token required"));
+ let other_proto = request("GET", "/ws", &upgrade_headers("http://localhost:8088", "tt-token.abc"));
+ assert_eq!(route(&site, &other_proto), reject(400, "Unknown WebSocket subprotocol"));
+ let mut headers = upgrade_headers("http://localhost:8088", "thinkterm.v1, tt-token.abc");
+ headers.retain(|(n, _)| *n != "Origin");
+ let no_origin = request("GET", "/ws", &headers);
+ assert_eq!(route(&site, &no_origin), reject(403, "Origin required"));
+ }
+
+ /// The page a loopback listener served through a forward comes back
+ /// on the forward's port: its origin is that port, on our scheme, at
+ /// the authority the request names. Another local port's page is not.
+ #[test]
+ fn a_forwarded_loopback_page_may_open_the_socket() {
+ let site = site();
+ let mut headers = upgrade_headers("http://localhost:9000", "thinkterm.v1, tt-token.abc");
+ headers.retain(|(n, _)| *n != "Host");
+ headers.push(("Host", "localhost:9000"));
+ let good = request("GET", "/ws", &headers);
+ assert!(matches!(route(&site, &good), Route::Upgrade { .. }));
+ // A different local port than the one addressed: not the page we served.
+ let other = request("GET", "/ws", &upgrade_headers("http://localhost:9000", "thinkterm.v1, tt-token.abc"));
+ assert_eq!(route(&site, &other), reject(403, "Origin not allowed"));
+ let mut headers = upgrade_headers("https://localhost:9000", "thinkterm.v1, tt-token.abc");
+ headers.retain(|(n, _)| *n != "Host");
+ headers.push(("Host", "localhost:9000"));
+ let wrong_scheme = request("GET", "/ws", &headers);
+ assert_eq!(route(&site, &wrong_scheme), reject(403, "Origin not allowed"));
+ }
+
+ /// A listener on a scheme's default port is named without it, which
+ /// is how a browser spells it.
+ #[test]
+ fn default_ports_match_with_or_without_the_number() {
+ let server = config::WebServer {
+ bind_address: "mux.example.net:443".into(),
+ pem_cert: Some("/c.pem".into()),
+ pem_private_key: Some("/k.pem".into()),
+ ..config::WebServer::default()
+ };
+ let site = WebSite::from_config(&server, Some("/srv/web".into()), "me".into());
+ for host in ["mux.example.net", "mux.example.net:443", "MUX.example.net"] {
+ let req = request("GET", "/", &[("Host", host)]);
+ assert!(matches!(route(&site, &req), Route::Static(_)), "{}", host);
+ }
+ let odd = request("GET", "/", &[("Host", "mux.example.net:8443")]);
+ assert_eq!(route(&site, &odd), reject(403, "Host not served here"));
+ let mut headers = upgrade_headers("https://mux.example.net", "thinkterm.v1, tt-token.abc");
+ headers.retain(|(n, _)| *n != "Host");
+ headers.push(("Host", "mux.example.net"));
+ assert!(matches!(route(&site, &request("GET", "/ws", &headers)), Route::Upgrade { .. }));
+ // Not loopback: a stranger's port is not ours.
+ let mut headers = upgrade_headers("https://mux.example.net:9000", "thinkterm.v1, tt-token.abc");
+ headers.retain(|(n, _)| *n != "Host");
+ headers.push(("Host", "mux.example.net:9000"));
+ assert_eq!(route(&site, &request("GET", "/ws", &headers)), reject(403, "Host not served here"));
+ }
+
+ #[test]
+ fn a_configured_origin_also_names_an_allowed_host() {
+ let server = config::WebServer {
+ allowed_origins: vec!["https://app.example.net".into()],
+ ..config::WebServer::default()
+ };
+ let site = WebSite::from_config(&server, None, "me".into());
+ let req = request("GET", "/", &[("Host", "app.example.net")]);
+ assert_eq!(route(&site, &req), reject(404, "No web bundle is installed on this server"));
+ }
+}
+
+#[cfg(all(test, unix))]
+mod end_to_end {
+ use super::*;
+ use codec::Pdu;
+ use mux::Mux;
+ use smol::Async;
+ use std::os::fd::{FromRawFd, IntoRawFd};
+ use std::os::unix::net::UnixStream;
+
+ fn pair() -> (Async<UnixStream>, Async<UnixStream>) {
+ let (a, b) = UnixStream::pair().unwrap();
+ let a = unsafe { UnixStream::from_raw_fd(a.into_raw_fd()) };
+ let b = unsafe { UnixStream::from_raw_fd(b.into_raw_fd()) };
+ (Async::new(a).unwrap(), Async::new(b).unwrap())
+ }
+
+ async fn read_response(client: &mut Async<UnixStream>) -> String {
+ let mut out = Vec::new();
+ let mut buf = [0u8; 1024];
+ loop {
+ let n = client.read(&mut buf).await.unwrap();
+ if n == 0 {
+ break;
+ }
+ out.extend_from_slice(&buf[..n]);
+ if out.windows(4).any(|w| w == b"\r\n\r\n") && out.starts_with(b"HTTP/1.1 101") {
+ break;
+ }
+ }
+ String::from_utf8_lossy(&out).to_string()
+ }
+
+ #[test]
+ fn an_unauthenticated_socket_gets_no_pdu_answered() {
+ let site = Arc::new(WebSite::from_config(&config::WebServer::default(), None, "me".into()));
+ let (server, mut client) = pair();
+ crate::connections::spawn(serve(server, site));
+ smol::block_on(async {
+ let req = "GET /ws HTTP/1.1\r\nHost: localhost:8088\r\nOrigin: http://localhost:8088\r\n\
+ Connection: Upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Version: 13\r\n\
+ Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\
+ Sec-WebSocket-Protocol: thinkterm.v1, tt-token.nope\r\n\r\n";
+ client.write_all(req.as_bytes()).await.unwrap();
+ let response = read_response(&mut client).await;
+ assert!(response.starts_with("HTTP/1.1 401"), "{}", response);
+ // Nothing sent after the refusal is answered: the socket is gone.
+ let mut bytes = Vec::new();
+ Pdu::GetCodecVersion(codec::GetCodecVersion {})
+ .encode(&mut bytes, 1)
+ .unwrap();
+ let _ = client.write_all(&bytes).await;
+ let mut buf = [0u8; 64];
+ let n = smol::future::or(
+ async { client.read(&mut buf).await.unwrap_or(0) },
+ async {
+ smol::Timer::after(Duration::from_secs(2)).await;
+ usize::MAX
+ },
+ )
+ .await;
+ assert_eq!(n, 0, "expected end of stream, got {n} bytes");
+ });
+ }
+
+ #[test]
+ fn a_good_token_reaches_dispatch_and_answers_the_version_handshake() {
+ let mux = Arc::new(Mux::new(None));
+ Mux::set_mux(&mux);
+ let minted = WEB_TOKENS.mint(Some("e2e".into()), None).unwrap();
+ let site = Arc::new(WebSite::from_config(&config::WebServer::default(), None, "me".into()));
+ let (server, mut client) = pair();
+ crate::connections::spawn(serve(server, site));
+ smol::block_on(async {
+ let req = format!(
+ "GET /ws HTTP/1.1\r\nHost: 127.0.0.1:8088\r\nOrigin: http://127.0.0.1:8088\r\n\
+ Connection: Upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Version: 13\r\n\
+ Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\
+ Sec-WebSocket-Protocol: thinkterm.v1, tt-token.{}\r\n\r\n",
+ minted.token
+ );
+ client.write_all(req.as_bytes()).await.unwrap();
+ let response = read_response(&mut client).await;
+ assert!(response.starts_with("HTTP/1.1 101"), "{}", response);
+ assert!(response.contains("Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo="));
+ assert!(response.contains("Sec-WebSocket-Protocol: thinkterm.v1"));
+
+ let (mut tx, mut rx) =
+ soketto::connection::Builder::new(client, soketto::connection::Mode::Client)
+ .finish();
+ let mut bytes = Vec::new();
+ Pdu::GetCodecVersion(codec::GetCodecVersion {})
+ .encode(&mut bytes, 5)
+ .unwrap();
+ tx.send_binary(&bytes).await.unwrap();
+ tx.flush().await.unwrap();
+ let mut answer = Vec::new();
+ rx.receive_data(&mut answer).await.unwrap();
+ let decoded = Pdu::decode(std::io::Cursor::new(answer)).unwrap();
+ assert_eq!(decoded.serial, 5);
+ assert!(matches!(decoded.pdu, Pdu::GetCodecVersionResponse(_)));
+ });
+ WEB_TOKENS.revoke(Some(&minted.id));
+ }
+
+ #[test]
+ fn the_page_is_served_from_the_bundle_directory() {
+ let dir = tempfile::tempdir().unwrap();
+ std::fs::write(dir.path().join("index.html"), b"<!doctype html>hello").unwrap();
+ let site = Arc::new(WebSite::from_config(
+ &config::WebServer::default(),
+ Some(dir.path().to_path_buf()),
+ "me".into(),
+ ));
+ let (server, mut client) = pair();
+ crate::connections::spawn(serve(server, site));
+ smol::block_on(async {
+ client
+ .write_all(b"GET / HTTP/1.1\r\nHost: localhost:8088\r\n\r\n")
+ .await
+ .unwrap();
+ let response = read_response(&mut client).await;
+ assert!(response.starts_with("HTTP/1.1 200"), "{}", response);
+ assert!(response.contains("Content-Type: text/html"));
+ assert!(response.ends_with("<!doctype html>hello"), "{}", response);
+ });
+ }
+}
diff --git a/wezterm-mux-server-impl/src/web_stream.rs b/wezterm-mux-server-impl/src/web_stream.rs
new file mode 100644
index 00000000..51fc6ad1
--- /dev/null
+++ b/wezterm-mux-server-impl/src/web_stream.rs
@@ -0,0 +1,620 @@
+//! A browser's WebSocket presented to the connection loop as the ordered
+//! byte stream the codec wants.
+//!
+//! The codec's framing is self-delimiting, so WebSocket message boundaries
+//! carry no meaning: inbound messages are appended to one byte queue and
+//! outbound bytes are cut into binary messages of a fixed size, however
+//! the codec chose to write them. Two tasks on the connection executor
+//! own the socket halves; the stream itself talks to them through bounded
+//! channels, which is what gives the dispatch loop's stall clocks
+//! something to measure -- a peer that stops reading fills the outbound
+//! channel and `poll_write` stops making progress, exactly as a full
+//! kernel buffer would.
+//!
+//! The socket's lifetime is the stream's: the reader task is cancelled
+//! when the stream drops (soketto only closes the socket once both halves
+//! are gone), and the writer says goodbye with a close frame but is given
+//! a bounded time to do so, since the peer it is closing may be dead.
+
+use crate::dispatch::ConnectionStream;
+use futures::channel::oneshot;
+use futures::io::{AsyncRead, AsyncWrite};
+use smol::channel::{Receiver, Sender};
+use soketto::connection::{Builder, Error as WsError, Mode};
+use soketto::Data;
+use std::collections::VecDeque;
+use std::future::Future;
+use std::pin::Pin;
+use std::sync::{Arc, Mutex};
+use std::task::{Context, Poll};
+use std::time::Duration;
+
+/// Outbound bytes leave in messages of at most this size; the client
+/// concatenates, so the number only bounds the writer's staging.
+const OUTBOUND_CHUNK: usize = 64 * 1024;
+/// Messages the reader may run ahead of the codec, and PDUs the codec may
+/// run ahead of the socket, before either side is made to wait.
+const CHANNEL_DEPTH: usize = 16;
+/// Largest single WebSocket message accepted from a browser. What a browser
+/// sends is keys, pastes and small requests; soketto allocates the declared
+/// length up front, so this is the most one frame header can make the
+/// server allocate. (PDU lengths are bounded separately, by the codec:
+/// a PDU may span messages.)
+const MAX_INBOUND_MESSAGE: usize = 8 * 1024 * 1024;
+/// How long the writer waits for its close frame to leave once the
+/// stream is gone. A dead peer never drains the socket; the fd must not
+/// wait on it.
+const CLOSE_GRACE: Duration = Duration::from_secs(5);
+
+/// Sync as well as Send: the dispatch loop holds `&WebStream` across an
+/// await, so the stream has to be shareable for its future to be Send.
+type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send + Sync>>;
+
+/// What the stream hands the writer task.
+enum Outbound {
+ Data(Vec<u8>),
+ /// Flush the socket and say when it is done.
+ Flush(oneshot::Sender<()>),
+}
+
+/// The byte stream side of an upgraded WebSocket.
+pub struct WebStream {
+ /// Bytes received but not yet read. Behind a mutex only so that
+ /// `wait_for_readable`, which takes `&self`, can stash the message it
+ /// pulled; the loop that owns the stream is a single task.
+ inbound: Mutex<VecDeque<u8>>,
+ /// Behind `Arc` because a channel end is not `Unpin` and the stream
+ /// has to be.
+ rx_in: Arc<Receiver<Vec<u8>>>,
+ recv: Option<BoxFuture<Option<Vec<u8>>>>,
+ /// `None` once closed.
+ tx_out: Option<Arc<Sender<Outbound>>>,
+ /// A send the writer channel has not yet accepted, with the number of
+ /// bytes it carries; `poll_write` reports that count once it lands.
+ send: Option<(BoxFuture<bool>, usize)>,
+ /// A flush the writer has not yet acknowledged.
+ flush: Option<BoxFuture<()>>,
+ /// The reader task; dropped with the stream, which cancels it.
+ _reader: smol::Task<()>,
+}
+
+impl std::fmt::Debug for WebStream {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("WebStream")
+ .field("buffered", &self.inbound.lock().map(|q| q.len()).unwrap_or(0))
+ .field("closed", &self.tx_out.is_none())
+ .finish()
+ }
+}
+
+impl WebStream {
+ /// Take over `socket` right after a successful HTTP upgrade and run the
+ /// WebSocket protocol over it.
+ pub fn new<T>(socket: T) -> Self
+ where
+ T: AsyncRead + AsyncWrite + Unpin + Send + 'static,
+ {
+ let mut builder = Builder::new(socket, Mode::Server);
+ builder.set_max_message_size(MAX_INBOUND_MESSAGE);
+ builder.set_max_frame_size(MAX_INBOUND_MESSAGE);
+ let (mut sender, mut receiver) = builder.finish();
+
+ let (tx_in, rx_in) = smol::channel::bounded::<Vec<u8>>(CHANNEL_DEPTH);
+ let (tx_out, rx_out) = smol::channel::bounded::<Outbound>(CHANNEL_DEPTH);
+
+ let reader = crate::connections::spawn_task(async move {
+ let mut message = Vec::new();
+ loop {
+ message.clear();
+ match receiver.receive_data(&mut message).await {
+ Ok(Data::Binary(_)) => {
+ // An empty message carries nothing to deliver, and
+ // must not wake a reader that would then find the
+ // queue empty.
+ if message.is_empty() {
+ continue;
+ }
+ if tx_in.send(std::mem::take(&mut message)).await.is_err() {
+ // The stream is gone; nothing to deliver to.
+ return;
+ }
+ }
+ Ok(Data::Text(_)) => {
+ // The codec is bytes; a text frame has been through
+ // UTF-8 validation and cannot be what a client of
+ // ours sent. Treat it as end of stream.
+ log::warn!("web client sent a text frame; closing its connection");
+ return;
+ }
+ Err(WsError::Closed) => return,
+ Err(err) => {
+ log::debug!("web socket read ended: {err}");
+ return;
+ }
+ }
+ }
+ // tx_in drops here: the reader side sees end of stream once the
+ // queue drains.
+ });
+
+ crate::connections::spawn(async move {
+ while let Ok(out) = rx_out.recv().await {
+ let result = match out {
+ Outbound::Data(chunk) => match sender.send_binary(&chunk).await {
+ Ok(()) => sender.flush().await,
+ Err(err) => Err(err),
+ },
+ Outbound::Flush(ack) => {
+ let flushed = sender.flush().await;
+ let _ = ack.send(());
+ flushed
+ }
+ };
+ if let Err(err) = result {
+ log::debug!("web socket write failed: {err}");
+ return;
+ }
+ }
+ // The stream closed: say goodbye properly so the browser sees a
+ // clean close rather than a reset -- for as long as a live
+ // peer needs, no longer.
+ smol::future::or(
+ async {
+ let _ = sender.close().await;
+ },
+ async {
+ smol::Timer::after(CLOSE_GRACE).await;
+ },
+ )
+ .await;
+ });
+
+ Self {
+ inbound: Mutex::new(VecDeque::new()),
+ rx_in: Arc::new(rx_in),
+ recv: None,
+ tx_out: Some(Arc::new(tx_out)),
+ send: None,
+ flush: None,
+ _reader: reader,
+ }
+ }
+}
+
+impl AsyncRead for WebStream {
+ fn poll_read(
+ mut self: Pin<&mut Self>,
+ cx: &mut Context<'_>,
+ buf: &mut [u8],
+ ) -> Poll<std::io::Result<usize>> {
+ loop {
+ {
+ let mut queue = self.inbound.lock().unwrap_or_else(|e| e.into_inner());
+ if !queue.is_empty() {
+ let n = queue.len().min(buf.len());
+ for (dst, src) in buf.iter_mut().zip(queue.drain(..n)) {
+ *dst = src;
+ }
+ return Poll::Ready(Ok(n));
+ }
+ }
+ let this = &mut *self;
+ let rx_in = &this.rx_in;
+ let recv = this.recv.get_or_insert_with(|| {
+ let rx = Arc::clone(rx_in);
+ Box::pin(async move { rx.recv().await.ok() })
+ });
+ match recv.as_mut().poll(cx) {
+ Poll::Pending => return Poll::Pending,
+ Poll::Ready(None) => {
+ self.recv = None;
+ return Poll::Ready(Ok(0));
+ }
+ Poll::Ready(Some(message)) => {
+ self.recv = None;
+ self.inbound
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+ .extend(message);
+ }
+ }
+ }
+ }
+}
+
+impl AsyncWrite for WebStream {
+ fn poll_write(
+ mut self: Pin<&mut Self>,
+ cx: &mut Context<'_>,
+ buf: &[u8],
+ ) -> Poll<std::io::Result<usize>> {
+ if self.send.is_none() {
+ let Some(tx) = self.tx_out.clone() else {
+ return Poll::Ready(Err(std::io::ErrorKind::BrokenPipe.into()));
+ };
+ if buf.is_empty() {
+ return Poll::Ready(Ok(0));
+ }
+ let chunk = buf[..buf.len().min(OUTBOUND_CHUNK)].to_vec();
+ let len = chunk.len();
+ self.send = Some((
+ Box::pin(async move { tx.send(Outbound::Data(chunk)).await.is_ok() }),
+ len,
+ ));
+ }
+ let (fut, len) = self.send.as_mut().expect("just set");
+ let len = *len;
+ match fut.as_mut().poll(cx) {
+ Poll::Pending => Poll::Pending,
+ Poll::Ready(true) => {
+ self.send = None;
+ Poll::Ready(Ok(len))
+ }
+ Poll::Ready(false) => {
+ self.send = None;
+ Poll::Ready(Err(std::io::ErrorKind::BrokenPipe.into()))
+ }
+ }
+ }
+
+ /// Resolves once everything queued before it has reached the socket:
+ /// the liveness clock stamps a probe as written from here, so it must
+ /// not report a Ping still sitting behind pane output.
+ fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
+ if self.flush.is_none() {
+ let Some(tx) = self.tx_out.clone() else {
+ return Poll::Ready(Ok(()));
+ };
+ self.flush = Some(Box::pin(async move {
+ let (ack, done) = oneshot::channel();
+ if tx.send(Outbound::Flush(ack)).await.is_ok() {
+ let _ = done.await;
+ }
+ }));
+ }
+ let fut = self.flush.as_mut().expect("just set");
+ match fut.as_mut().poll(cx) {
+ Poll::Pending => Poll::Pending,
+ Poll::Ready(()) => {
+ self.flush = None;
+ Poll::Ready(Ok(()))
+ }
+ }
+ }
+
+ fn poll_close(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
+ // Dropping the sender ends the writer task, which sends the close
+ // frame.
+ self.tx_out = None;
+ self.send = None;
+ self.flush = None;
+ Poll::Ready(Ok(()))
+ }
+}
+
+impl ConnectionStream for WebStream {
+ fn wait_for_readable(&self) -> impl Future<Output = std::io::Result<()>> + Send + '_ {
+ // Only these two fields are captured: the pending-future slots are
+ // not Sync, and a future holding `&self` would not be Send.
+ let inbound = &self.inbound;
+ let rx_in = &self.rx_in;
+ async move {
+ loop {
+ if inbound.lock().map(|q| !q.is_empty()).unwrap_or(false) {
+ return Ok(());
+ }
+ // Park until a message with something in it arrives, then
+ // keep it for the read that follows. A closed channel is
+ // readable too: the read returns end of stream.
+ match rx_in.recv().await {
+ Ok(message) if message.is_empty() => continue,
+ Ok(message) => {
+ inbound
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+ .extend(message);
+ return Ok(());
+ }
+ Err(_) => return Ok(()),
+ }
+ }
+ }
+ }
+}
+
+/// A stream with some bytes already taken off it: the HTTP layer reads the
+/// request head in one gulp, and whatever followed it belongs to the
+/// WebSocket protocol.
+#[derive(Debug)]
+pub struct Prefixed<T> {
+ prefix: VecDeque<u8>,
+ inner: T,
+}
+
+impl<T> Prefixed<T> {
+ pub fn new(prefix: Vec<u8>, inner: T) -> Self {
+ Self {
+ prefix: prefix.into(),
+ inner,
+ }
+ }
+}
+
+impl<T: AsyncRead + Unpin> AsyncRead for Prefixed<T> {
+ fn poll_read(
+ mut self: Pin<&mut Self>,
+ cx: &mut Context<'_>,
+ buf: &mut [u8],
+ ) -> Poll<std::io::Result<usize>> {
+ if !self.prefix.is_empty() {
+ let n = self.prefix.len().min(buf.len());
+ for (dst, src) in buf.iter_mut().zip(self.prefix.drain(..n)) {
+ *dst = src;
+ }
+ return Poll::Ready(Ok(n));
+ }
+ Pin::new(&mut self.inner).poll_read(cx, buf)
+ }
+}
+
+impl<T: AsyncWrite + Unpin> AsyncWrite for Prefixed<T> {
+ fn poll_write(
+ mut self: Pin<&mut Self>,
+ cx: &mut Context<'_>,
+ buf: &[u8],
+ ) -> Poll<std::io::Result<usize>> {
+ Pin::new(&mut self.inner).poll_write(cx, buf)
+ }
+
+ fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
+ Pin::new(&mut self.inner).poll_flush(cx)
+ }
+
+ fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
+ Pin::new(&mut self.inner).poll_close(cx)
+ }
+}
+
+#[cfg(all(test, unix))]
+mod tests {
+ use super::*;
+ use codec::Pdu;
+ use futures::io::AsyncReadExt;
+ use smol::Async;
+ use std::os::fd::{FromRawFd, IntoRawFd};
+ use std::os::unix::net::UnixStream;
+ use std::time::Duration;
+
+ /// A browser stand-in: the client half of a WebSocket over a socket
+ /// pair, speaking soketto's client mode to our server-mode stream.
+ fn pair() -> (
+ WebStream,
+ soketto::connection::Sender<Async<UnixStream>>,
+ soketto::connection::Receiver<Async<UnixStream>>,
+ ) {
+ let (ours, theirs) = UnixStream::pair().unwrap();
+ let ours = unsafe { UnixStream::from_raw_fd(ours.into_raw_fd()) };
+ let theirs = unsafe { UnixStream::from_raw_fd(theirs.into_raw_fd()) };
+ let server = WebStream::new(Async::new(ours).unwrap());
+ let (tx, rx) = Builder::new(Async::new(theirs).unwrap(), Mode::Client).finish();
+ (server, tx, rx)
+ }
+
+ fn encoded(pdu: Pdu, serial: u64) -> Vec<u8> {
+ let mut out = Vec::new();
+ pdu.encode(&mut out, serial).unwrap();
+ out
+ }
+
+ #[test]
+ fn a_pdu_split_across_three_messages_decodes_whole() {
+ let (mut server, mut client, _rx) = pair();
+ let bytes = encoded(Pdu::Ping(codec::Ping {}), 7);
+ let cut = bytes.len() / 3;
+ smol::block_on(async {
+ client.send_binary(&bytes[..cut]).await.unwrap();
+ client.send_binary(&bytes[cut..2 * cut]).await.unwrap();
+ client.send_binary(&bytes[2 * cut..]).await.unwrap();
+ client.flush().await.unwrap();
+ let decoded = Pdu::decode_async(&mut server, None).await.unwrap();
+ assert_eq!(decoded.serial, 7);
+ assert!(matches!(decoded.pdu, Pdu::Ping(_)));
+ });
+ }
+
+ #[test]
+ fn three_pdus_in_one_message_decode_one_by_one() {
+ let (mut server, mut client, _rx) = pair();
+ let mut bytes = encoded(Pdu::Ping(codec::Ping {}), 1);
+ bytes.extend(encoded(Pdu::Pong(codec::Pong {}), 2));
+ bytes.extend(encoded(Pdu::GetCodecVersion(codec::GetCodecVersion {}), 3));
+ smol::block_on(async {
+ client.send_binary(&bytes).await.unwrap();
+ client.flush().await.unwrap();
+ for expected in 1..=3 {
+ let decoded = Pdu::decode_async(&mut server, None).await.unwrap();
+ assert_eq!(decoded.serial, expected);
+ }
+ });
+ }
+
+ #[test]
+ fn readability_waits_for_bytes_and_survives_into_the_read() {
+ let (mut server, mut client, _rx) = pair();
+ smol::block_on(async {
+ let idle = smol::future::or(
+ async {
+ server.wait_for_readable().await.unwrap();
+ true
+ },
+ async {
+ smol::Timer::after(Duration::from_millis(150)).await;
+ false
+ },
+ )
+ .await;
+ assert!(!idle, "readable with nothing sent");
+
+ client.send_binary(b"abc").await.unwrap();
+ client.flush().await.unwrap();
+ server.wait_for_readable().await.unwrap();
+ // The wait pulled the message; a second wait is immediate and
+ // the read gets the bytes the wait saw.
+ server.wait_for_readable().await.unwrap();
+ let mut buf = [0u8; 8];
+ let n = server.read(&mut buf).await.unwrap();
+ assert_eq!(&buf[..n], b"abc");
+ });
+ }
+
+ #[test]
+ fn writes_arrive_as_binary_messages_that_concatenate() {
+ let (mut server, _client, mut rx) = pair();
+ // Incompressible, or the codec's zstd would shrink it to one message.
+ let mut noise = vec![0u8; 150_000];
+ getrandom::fill(&mut noise).unwrap();
+ use base64::Engine;
+ let big = Pdu::SendPaste(codec::SendPaste {
+ pane_id: 1,
+ data: base64::engine::general_purpose::STANDARD.encode(&noise),
+ });
+ let bytes = encoded(big, 9);
+ assert!(bytes.len() > 2 * OUTBOUND_CHUNK, "{} bytes", bytes.len());
+ smol::block_on(async {
+ use futures::io::AsyncWriteExt;
+ // Read while writing: the flush is honest now and waits for
+ // the socket, which a peer that never reads would never drain.
+ let write = async {
+ server.write_all(&bytes).await.unwrap();
+ server.flush().await.unwrap();
+ };
+ let read = async {
+ let mut got = Vec::new();
+ let mut messages = 0;
+ while got.len() < bytes.len() {
+ let mut m = Vec::new();
+ match rx.receive_data(&mut m).await.unwrap() {
+ Data::Binary(_) => got.extend(m),
+ Data::Text(_) => panic!("server sent a text frame"),
+ }
+ messages += 1;
+ }
+ (got, messages)
+ };
+ let ((), (got, messages)) = futures::future::join(write, read).await;
+ assert_eq!(got, bytes);
+ assert!(messages > 1, "a 200 KB PDU should leave in several messages");
+ });
+ }
+
+ #[test]
+ fn a_peer_that_closes_mid_pdu_ends_the_stream() {
+ let (mut server, mut client, _rx) = pair();
+ let bytes = encoded(Pdu::GetCodecVersion(codec::GetCodecVersion {}), 4);
+ smol::block_on(async {
+ client.send_binary(&bytes[..2]).await.unwrap();
+ client.flush().await.unwrap();
+ client.close().await.unwrap();
+ let err = Pdu::decode_async(&mut server, None)
+ .await
+ .expect_err("half a PDU cannot decode");
+ let io = err
+ .root_cause()
+ .downcast_ref::<std::io::Error>()
+ .expect("an io error");
+ assert_eq!(io.kind(), std::io::ErrorKind::UnexpectedEof);
+ });
+ }
+
+ #[test]
+ fn closing_the_stream_sends_a_close_frame() {
+ let (mut server, _client, mut rx) = pair();
+ smol::block_on(async {
+ use futures::io::AsyncWriteExt;
+ server.close().await.unwrap();
+ let mut m = Vec::new();
+ let err = rx.receive_data(&mut m).await.expect_err("closed");
+ assert!(matches!(err, WsError::Closed), "{}", err);
+ });
+ }
+
+ /// An empty binary frame is nothing, not a wake: a reader woken by it
+ /// would enter a decode on an empty queue and sit there with the
+ /// stall clock never started.
+ #[test]
+ fn an_empty_frame_does_not_report_readable() {
+ let (mut server, mut client, _rx) = pair();
+ smol::block_on(async {
+ client.send_binary(b"").await.unwrap();
+ client.flush().await.unwrap();
+ let woke = smol::future::or(
+ async {
+ server.wait_for_readable().await.unwrap();
+ true
+ },
+ async {
+ smol::Timer::after(Duration::from_millis(200)).await;
+ false
+ },
+ )
+ .await;
+ assert!(!woke, "an empty frame woke the reader");
+ // And a real message after it still gets through.
+ client.send_binary(b"xyz").await.unwrap();
+ client.flush().await.unwrap();
+ server.wait_for_readable().await.unwrap();
+ let mut buf = [0u8; 8];
+ let n = server.read(&mut buf).await.unwrap();
+ assert_eq!(&buf[..n], b"xyz");
+ });
+ }
+
+ /// Dropping the stream closes the socket: the reader task is
+ /// cancelled and the writer's goodbye is bounded, so a peer that never
+ /// answers cannot keep the descriptor.
+ #[test]
+ fn dropping_the_stream_closes_the_socket() {
+ use std::os::fd::AsRawFd;
+ let (ours, theirs) = UnixStream::pair().unwrap();
+ let fd = ours.as_raw_fd();
+ let ours = unsafe { UnixStream::from_raw_fd(ours.into_raw_fd()) };
+ let server = WebStream::new(Async::new(ours).unwrap());
+ // The peer never reads or writes; it is only kept alive.
+ let _theirs = theirs;
+ let open = |fd: i32| unsafe { libc::fcntl(fd, libc::F_GETFD) } != -1;
+ assert!(open(fd));
+ drop(server);
+ let started = std::time::Instant::now();
+ while open(fd) {
+ assert!(
+ started.elapsed() < CLOSE_GRACE + Duration::from_secs(5),
+ "the socket stayed open after the stream was dropped"
+ );
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ }
+
+ /// A flush resolves only once the writer has put everything before it
+ /// on the wire, so a probe stamped as written really has left.
+ #[test]
+ fn a_flush_waits_for_the_writer() {
+ let (mut server, _client, mut rx) = pair();
+ smol::block_on(async {
+ use futures::io::AsyncWriteExt;
+ server.write_all(b"before").await.unwrap();
+ server.flush().await.unwrap();
+ let mut m = Vec::new();
+ // Already there: no waiting on the peer to see it.
+ let got = smol::future::or(
+ async { rx.receive_data(&mut m).await.is_ok() },
+ async {
+ smol::Timer::after(Duration::from_millis(500)).await;
+ false
+ },
+ )
+ .await;
+ assert!(got, "the flushed bytes had not been written");
+ assert_eq!(m, b"before");
+ });
+ }
+}
diff --git a/wezterm-mux-server/Cargo.toml b/wezterm-mux-server/Cargo.toml
index 2593afee..0ff21d2d 100644
--- a/wezterm-mux-server/Cargo.toml
+++ b/wezterm-mux-server/Cargo.toml
@@ -31,6 +31,7 @@ openssl.workspace = true
portable-pty = { workspace=true, features = ["serde_support"]}
promise.workspace = true
signal-hook.workspace = true
+smol.workspace = true
umask.workspace = true
wezterm-blob-leases = {workspace=true, features=["simple_tempdir"]}
wezterm-mux-server-impl.workspace = true
diff --git a/wezterm-mux-server/src/main.rs b/wezterm-mux-server/src/main.rs
index d7806c8e..c2d136ff 100644
--- a/wezterm-mux-server/src/main.rs
+++ b/wezterm-mux-server/src/main.rs
@@ -456,6 +456,7 @@ async fn async_run(
// over. Everything is ours already; not listening for the next
// successor is worth a log line, not an exit.
let tls_servers = config.tls_servers.clone();
+ let web_servers = config.web_servers.clone();
thread::spawn(move || {
wezterm_mux_server_impl::handoff::wait_for_predecessor_exit(stream);
// Its descriptors close one after another as it exits; the
@@ -491,6 +492,14 @@ async fn async_run(
log::error!("problem spawning TLS listener after the takeover: {err:#}");
}
}
+ if let Err(err) = web::configure_tokens(&web_servers) {
+ log::error!("problem loading web tokens after the takeover: {err:#}");
+ }
+ for web_server in &web_servers {
+ if let Err(err) = web::spawn_web_listener(web_server) {
+ log::error!("problem spawning web listener after the takeover: {err:#}");
+ }
+ }
});
}
#[cfg(not(unix))]
@@ -589,6 +598,7 @@ fn install_shutdown_signal_handler() -> anyhow::Result<()> {
}
mod ossl;
+mod web;
pub fn spawn_listener() -> anyhow::Result<()> {
let config = configuration();
@@ -626,5 +636,14 @@ pub fn spawn_listener() -> anyhow::Result<()> {
ossl::spawn_tls_listener(tls_server)?;
}
+ // Not fatal: a token store that cannot be read means no web tokens,
+ // not no server.
+ if let Err(err) = web::configure_tokens(&config.web_servers) {
+ log::error!("problem loading web tokens: {err:#}");
+ }
+ for web_server in &config.web_servers {
+ web::spawn_web_listener(web_server)?;
+ }
+
Ok(())
}
diff --git a/wezterm-mux-server/src/ossl.rs b/wezterm-mux-server/src/ossl.rs
index f14baf83..39be9eac 100644
--- a/wezterm-mux-server/src/ossl.rs
+++ b/wezterm-mux-server/src/ossl.rs
@@ -78,8 +78,10 @@ impl OpenSSLNetListener {
match acceptor.accept(stream) {
Ok(stream) => {
if let Err(err) = Self::verify_peer_cert(&stream) {
+ // One bad client is one refused connection,
+ // not the end of the listener.
log::error!("problem with peer cert: {}", err);
- break;
+ continue;
}
wezterm_mux_server_impl::connections::spawn(async move {
log::debug!("Making new AsyncSslStream");
@@ -98,8 +100,11 @@ impl OpenSSLNetListener {
}
}
Err(err) => {
+ // As above: a failed accept (a peer that reset before
+ // we got to it, a moment without descriptors) is not
+ // the end of the listener.
log::error!("accept failed: {}", err);
- return;
+ std::thread::sleep(std::time::Duration::from_millis(100));
}
}
}
diff --git a/wezterm-mux-server/src/web.rs b/wezterm-mux-server/src/web.rs
new file mode 100644
index 00000000..efc4a112
--- /dev/null
+++ b/wezterm-mux-server/src/web.rs
@@ -0,0 +1,244 @@
+//! The web listener: one TCP port per `web_servers` entry, plain or TLS,
+//! whose connections go to `web_http::serve` on the connection executor.
+
+use anyhow::{anyhow, bail, Context};
+use async_ossl::AsyncSslStream;
+use config::WebServer;
+use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};
+use smol::Async;
+use std::net::TcpListener;
+use std::path::PathBuf;
+use std::sync::Arc;
+use std::time::Duration;
+use wezterm_mux_server_impl::web_auth::WEB_TOKENS;
+use wezterm_mux_server_impl::web_http::{serve, serve_seated, PreAuthSeat, WebSite};
+
+/// A TLS handshake is given this long in total; the accept thread never
+/// waits on it at all.
+const TLS_HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
+/// How often expired tokens are swept and their connections dropped.
+const TOKEN_SWEEP_INTERVAL: Duration = Duration::from_secs(30);
+
+/// Point the token store at its file. One store serves every web listener,
+/// so the first entry's choice wins; the others are told.
+pub fn configure_tokens(servers: &[WebServer]) -> anyhow::Result<()> {
+ let Some(first) = servers.first() else {
+ return Ok(());
+ };
+ WEB_TOKENS
+ .configure(first.token_file.clone())
+ .context("loading the web token store")?;
+ for other in &servers[1..] {
+ if other.token_file != first.token_file {
+ log::warn!(
+ "web_servers share one token store; token_file on {} is ignored in favour of {:?}",
+ other.bind_address,
+ first.token_file
+ );
+ }
+ }
+ // A token's lifetime ends when it says, whether or not anyone touches
+ // the store again.
+ wezterm_mux_server_impl::connections::spawn(async {
+ loop {
+ smol::Timer::after(TOKEN_SWEEP_INTERVAL).await;
+ WEB_TOKENS.sweep();
+ }
+ });
+ Ok(())
+}
+
+/// Where the browser bundle lives: the configured directory, an override
+/// for development, or the share directory next to the executable.
+fn resolve_static_dir(server: &WebServer) -> Option<PathBuf> {
+ let mut candidates: Vec<PathBuf> = vec![];
+ if let Some(dir) = &server.static_dir {
+ candidates.push(dir.clone());
+ }
+ if let Some(dir) = std::env::var_os("THINKTERM_WEB_STATIC_DIR") {
+ candidates.push(dir.into());
+ }
+ if let Ok(exe) = std::env::current_exe() {
+ if let Some(bin) = exe.parent() {
+ candidates.push(bin.join("../share/thinkterm/web"));
+ candidates.push(bin.join("../Resources/web"));
+ }
+ }
+ for candidate in candidates {
+ if candidate.join("index.html").is_file() {
+ return Some(candidate);
+ }
+ }
+ None
+}
+
+fn build_acceptor(server: &WebServer) -> anyhow::Result<SslAcceptor> {
+ openssl::init();
+ let (Some(cert), Some(key)) = (&server.pem_cert, &server.pem_private_key) else {
+ bail!(
+ "web server {}: pem_cert and pem_private_key must both be set for TLS",
+ server.bind_address
+ );
+ };
+ let mut acceptor = SslAcceptor::mozilla_modern(SslMethod::tls())?;
+ acceptor
+ .set_certificate_file(cert, SslFiletype::PEM)
+ .with_context(|| format!("set_certificate_file {}", cert.display()))?;
+ acceptor
+ .set_private_key_file(key, SslFiletype::PEM)
+ .with_context(|| format!("set_private_key_file {}", key.display()))?;
+ if let Some(chain) = &server.pem_ca {
+ acceptor
+ .set_certificate_chain_file(chain)
+ .with_context(|| format!("set_certificate_chain_file {}", chain.display()))?;
+ }
+ // No client certificate: a browser has none. The token is the
+ // credential; TLS is here for the secure context and the wire.
+ Ok(acceptor.build())
+}
+
+pub fn spawn_web_listener(server: &WebServer) -> anyhow::Result<()> {
+ if server.tls_half_configured() {
+ bail!(
+ "web server {}: pem_cert and pem_private_key must both be set for TLS",
+ server.bind_address
+ );
+ }
+ let (host, _) = server.host_and_port();
+ let unspecified = host
+ .parse::<std::net::IpAddr>()
+ .is_ok_and(|ip| ip.is_unspecified());
+ if unspecified && server.allowed_origins.is_empty() {
+ bail!(
+ "web server {} listens on every address but names no allowed_origins; \
+ a browser reaching it by hostname would be refused. List the origins \
+ (e.g. \"https://host.example:port\") or bind one address",
+ server.bind_address
+ );
+ }
+ if !server.is_loopback() && !server.uses_tls() && server.require_tls_off_loopback {
+ bail!(
+ "web server {} is not on loopback and has no TLS; browsers only expose WebGPU \
+ to secure contexts, so it could not render. Add pem_cert/pem_private_key, \
+ reach it through `ssh -L`, or set require_tls_off_loopback = false",
+ server.bind_address
+ );
+ }
+ let acceptor = if server.uses_tls() {
+ Some(build_acceptor(server)?)
+ } else {
+ None
+ };
+ let static_dir = resolve_static_dir(server);
+ match &static_dir {
+ Some(dir) => log::info!("web bundle for {} at {}", server.bind_address, dir.display()),
+ None => log::warn!(
+ "no web bundle found for {}; the port accepts WebSockets but serves no page \
+ (set static_dir or install the bundle under share/thinkterm/web)",
+ server.bind_address
+ ),
+ }
+ let username = config::username_from_env()
+ .map_err(|e| anyhow!("resolving the server's user for web sessions: {e}"))?;
+ let site = Arc::new(WebSite::from_config(server, static_dir, username));
+
+ let listener = TcpListener::bind(&server.bind_address)
+ .with_context(|| format!("binding web server to {}", server.bind_address))?;
+ log::error!(
+ "listening for web clients on {}{}",
+ server.bind_address,
+ if acceptor.is_some() { " with TLS" } else { "" }
+ );
+
+ std::thread::Builder::new()
+ .name(format!("web-accept-{}", server.bind_address))
+ .spawn(move || accept_loop(listener, acceptor, site))
+ .context("spawning the web accept thread")?;
+ Ok(())
+}
+
+/// How long the accept loop pauses after a failed accept. A refused
+/// peer costs nothing; an exhausted descriptor table would otherwise spin.
+const ACCEPT_RETRY: Duration = Duration::from_millis(100);
+
+fn accept_loop(listener: TcpListener, acceptor: Option<SslAcceptor>, site: Arc<WebSite>) {
+ for stream in listener.incoming() {
+ let stream = match stream {
+ Ok(stream) => stream,
+ Err(err) => {
+ // One bad client (or a moment without descriptors) is one
+ // refused connection, not the end of the listener.
+ log::error!("web accept failed on {}: {err}", site.describe);
+ std::thread::sleep(ACCEPT_RETRY);
+ continue;
+ }
+ };
+ stream.set_nodelay(true).ok();
+ let site = Arc::clone(&site);
+ match &acceptor {
+ None => match Async::new(stream) {
+ Ok(stream) => {
+ wezterm_mux_server_impl::connections::spawn(serve(stream, site));
+ }
+ Err(err) => log::warn!("web connection not registered: {err}"),
+ },
+ Some(acceptor) => {
+ // The seat is taken before the handshake: the handshake is
+ // blocking OpenSSL on the blocking pool, and the seats are
+ // what bound how many of its threads a crowd of strangers
+ // can hold. No seat, no handshake -- the socket is simply
+ // closed; a 503 cannot be written before TLS is up.
+ let Some(seat) = PreAuthSeat::take() else {
+ log::warn!("web TLS connection refused: too many unauthenticated peers");
+ continue;
+ };
+ // The deadline has to reach the socket itself: dropping the
+ // pool task cannot interrupt SSL_accept, and the per-call
+ // timeouts restart with every dribbled byte.
+ let guard = match stream.try_clone() {
+ Ok(guard) => guard,
+ Err(err) => {
+ log::warn!("web TLS connection not accepted: {err}");
+ continue;
+ }
+ };
+ let acceptor = acceptor.clone();
+ wezterm_mux_server_impl::connections::spawn(async move {
+ stream.set_read_timeout(Some(TLS_HANDSHAKE_TIMEOUT)).ok();
+ stream.set_write_timeout(Some(TLS_HANDSHAKE_TIMEOUT)).ok();
+ let handshake = smol::unblock(move || acceptor.accept(stream));
+ let tls = smol::future::or(
+ async { Some(handshake.await) },
+ async {
+ smol::Timer::after(TLS_HANDSHAKE_TIMEOUT).await;
+ None
+ },
+ )
+ .await;
+ let tls = match tls {
+ Some(Ok(tls)) => tls,
+ Some(Err(err)) => {
+ log::warn!("web TLS handshake failed: {err}");
+ return;
+ }
+ None => {
+ log::warn!(
+ "web TLS handshake took longer than {TLS_HANDSHAKE_TIMEOUT:?}; \
+ shutting the socket down"
+ );
+ let _ = guard.shutdown(std::net::Shutdown::Both);
+ return;
+ }
+ };
+ drop(guard);
+ tls.get_ref().set_read_timeout(None).ok();
+ tls.get_ref().set_write_timeout(None).ok();
+ match Async::new(AsyncSslStream::new(tls)) {
+ Ok(stream) => serve_seated(stream, site, seat).await,
+ Err(err) => log::warn!("web TLS connection not registered: {err}"),
+ }
+ });
+ }
+ }
+ }
+}
diff --git a/wezterm/src/cli/mod.rs b/wezterm/src/cli/mod.rs
index 31730075..4c1870b9 100644
--- a/wezterm/src/cli/mod.rs
+++ b/wezterm/src/cli/mod.rs
@@ -22,6 +22,7 @@ mod set_window_title;
mod spawn_command;
mod split_pane;
mod tls_creds;
+mod web_token;
mod zoom_pane;
#[derive(Debug, Parser, Clone, Copy)]
@@ -88,6 +89,11 @@ enum CliSubCommand {
#[command(name = "tlscreds", about = "obtain tls credentials")]
TlsCreds(tls_creds::TlsCredsCommand),
+ /// Mint, list and revoke the tokens a browser presents at the
+ /// server's web port
+ #[command(name = "web-token", rename_all = "kebab")]
+ WebToken(web_token::WebTokenCommand),
+
#[command(
name = "move-pane-to-new-tab",
rename_all = "kebab",
@@ -204,6 +210,7 @@ async fn run_cli_async(opts: &crate::Opt, cli: CliCommand) -> anyhow::Result<()>
CliSubCommand::SpawnCommand(cmd) => cmd.run(client, &crate::init_config(opts)?).await,
CliSubCommand::Proxy(cmd) => cmd.run(client, &crate::init_config(opts)?).await,
CliSubCommand::TlsCreds(cmd) => cmd.run(client).await,
+ CliSubCommand::WebToken(cmd) => cmd.run(client).await,
CliSubCommand::ActivatePaneDirection(cmd) => cmd.run(client).await,
CliSubCommand::GetPaneDirection(cmd) => cmd.run(client).await,
CliSubCommand::KillPane(cmd) => cmd.run(client).await,
diff --git a/wezterm/src/cli/web_token.rs b/wezterm/src/cli/web_token.rs
new file mode 100644
index 00000000..76ca493c
--- /dev/null
+++ b/wezterm/src/cli/web_token.rs
@@ -0,0 +1,247 @@
+//! `thinkterm cli web-token …`: mint, list and revoke the tokens a browser
+//! presents at the server's web port.
+
+use crate::cli::CliOutputFormatKind;
+use anyhow::{anyhow, bail};
+use clap::Parser;
+use tabout::{tabulate_output, Alignment, Column};
+use wezterm_client::client::Client;
+
+#[derive(Debug, Parser, Clone)]
+pub struct WebTokenCommand {
+ #[command(subcommand)]
+ sub: WebTokenSubCommand,
+}
+
+#[derive(Debug, Parser, Clone)]
+enum WebTokenSubCommand {
+ /// Mint a token and print the URL to open.
+ ///
+ /// Whoever holds the token has the same access as you do on this
+ /// machine: a shell as your user, every pane's scrollback. Treat it
+ /// like an ssh key. `revoke` cuts it off at once.
+ #[command(name = "mint")]
+ Mint(MintCommand),
+
+ /// List the tokens the server knows, with their live connections.
+ #[command(name = "list")]
+ List(ListCommand),
+
+ /// Revoke a token (or every token) and drop its connections.
+ #[command(name = "revoke")]
+ Revoke(RevokeCommand),
+}
+
+#[derive(Debug, Parser, Clone)]
+struct MintCommand {
+ /// A name to recognise the token by; the browser shows up under it in
+ /// `list-clients`.
+ #[arg(long)]
+ label: Option<String>,
+
+ /// How long the token lives: a number of seconds, or with a suffix
+ /// such as 30m, 12h, 7d. Without it the token lasts until revoked or
+ /// until the server forgets it.
+ #[arg(long)]
+ ttl: Option<String>,
+
+ /// Print only the URL, for scripts.
+ #[arg(long)]
+ url_only: bool,
+}
+
+#[derive(Debug, Parser, Clone)]
+struct ListCommand {
+ /// Controls the output format.
+ /// "table" and "json" are possible formats.
+ #[arg(long = "format", default_value = "table")]
+ format: CliOutputFormatKind,
+}
+
+#[derive(Debug, Parser, Clone)]
+struct RevokeCommand {
+ /// The token id, as shown by `list`.
+ id: Option<String>,
+
+ /// Revoke every token.
+ #[arg(long, conflicts_with = "id")]
+ all: bool,
+}
+
+impl WebTokenCommand {
+ pub async fn run(&self, client: Client) -> anyhow::Result<()> {
+ match &self.sub {
+ WebTokenSubCommand::Mint(cmd) => cmd.run(client).await,
+ WebTokenSubCommand::List(cmd) => cmd.run(client).await,
+ WebTokenSubCommand::Revoke(cmd) => cmd.run(client).await,
+ }
+ }
+}
+
+/// `90`, `90s`, `30m`, `12h`, `7d` → seconds.
+fn parse_ttl(spec: &str) -> anyhow::Result<u64> {
+ let spec = spec.trim();
+ let (number, unit) = match spec.char_indices().rfind(|(_, c)| c.is_ascii_digit()) {
+ Some((idx, _)) => spec.split_at(idx + 1),
+ None => bail!("ttl `{spec}` has no number"),
+ };
+ let n: u64 = number
+ .parse()
+ .map_err(|_| anyhow!("ttl `{spec}` is not a number"))?;
+ let scale = match unit.trim() {
+ "" | "s" => 1,
+ "m" => 60,
+ "h" => 60 * 60,
+ "d" => 24 * 60 * 60,
+ other => bail!("ttl unit `{other}` is not one of s, m, h, d"),
+ };
+ n.checked_mul(scale)
+ .ok_or_else(|| anyhow!("ttl `{spec}` is too large"))
+}
+
+fn local_time(secs: u64) -> String {
+ chrono::DateTime::<chrono::Utc>::from_timestamp(secs as i64, 0)
+ .map(|t| {
+ t.with_timezone(&chrono::Local)
+ .format("%Y-%m-%d %H:%M")
+ .to_string()
+ })
+ .unwrap_or_else(|| secs.to_string())
+}
+
+impl MintCommand {
+ async fn run(&self, client: Client) -> anyhow::Result<()> {
+ let ttl_secs = self.ttl.as_deref().map(parse_ttl).transpose()?;
+ let minted = client
+ .web_token_mint(codec::WebTokenMint {
+ label: self.label.clone(),
+ ttl_secs,
+ })
+ .await?;
+ if self.url_only {
+ match minted.urls.first() {
+ Some(url) => println!("{url}"),
+ None => {
+ // A script asked for a URL and there is none: do not
+ // leave a live token behind for it to try again with.
+ let _ = client
+ .web_token_revoke(codec::WebTokenRevoke {
+ id: Some(minted.id.clone()),
+ })
+ .await;
+ bail!("the server has no web_servers configured; nothing minted");
+ }
+ }
+ return Ok(());
+ }
+ println!("Token {} ({}) minted.", minted.id, minted.label);
+ match minted.expires_at {
+ Some(at) => println!("Expires {}.", local_time(at)),
+ None => println!("Does not expire; revoke it with `thinkterm cli web-token revoke {}`.", minted.id),
+ }
+ println!();
+ println!("This token is a login as your user on this machine. Anyone holding it can");
+ println!("open a shell and read every pane. Treat it like an ssh key.");
+ println!();
+ if minted.urls.is_empty() {
+ println!("The server has no web_servers configured. The token is:");
+ println!(" {}", minted.token);
+ } else {
+ println!("Open one of:");
+ for url in &minted.urls {
+ println!(" {url}");
+ }
+ }
+ Ok(())
+ }
+}
+
+#[derive(serde::Serialize)]
+struct CliWebTokenItem {
+ id: String,
+ label: String,
+ created_at: u64,
+ expires_at: Option<u64>,
+ last_used_at: Option<u64>,
+ live_connections: u32,
+}
+
+impl ListCommand {
+ async fn run(&self, client: Client) -> anyhow::Result<()> {
+ let response = client.web_token_list().await?;
+ let out = std::io::stdout();
+ match self.format {
+ CliOutputFormatKind::Json => {
+ let items: Vec<CliWebTokenItem> = response
+ .tokens
+ .into_iter()
+ .map(|t| CliWebTokenItem {
+ id: t.id,
+ label: t.label,
+ created_at: t.created_at,
+ expires_at: t.expires_at,
+ last_used_at: t.last_used_at,
+ live_connections: t.live_connections,
+ })
+ .collect();
+ serde_json::to_writer_pretty(out.lock(), &items)?;
+ println!();
+ }
+ CliOutputFormatKind::Table => {
+ let columns = [
+ Column { name: "ID".into(), alignment: Alignment::Left },
+ Column { name: "LABEL".into(), alignment: Alignment::Left },
+ Column { name: "CREATED".into(), alignment: Alignment::Left },
+ Column { name: "EXPIRES".into(), alignment: Alignment::Left },
+ Column { name: "LAST USED".into(), alignment: Alignment::Left },
+ Column { name: "LIVE".into(), alignment: Alignment::Right },
+ ];
+ let rows: Vec<Vec<String>> = response
+ .tokens
+ .iter()
+ .map(|t| {
+ vec![
+ t.id.clone(),
+ t.label.clone(),
+ local_time(t.created_at),
+ t.expires_at.map(local_time).unwrap_or_else(|| "never".into()),
+ t.last_used_at.map(local_time).unwrap_or_else(|| "-".into()),
+ t.live_connections.to_string(),
+ ]
+ })
+ .collect();
+ tabulate_output(&columns, &rows, &mut out.lock())?;
+ }
+ }
+ Ok(())
+ }
+}
+
+impl RevokeCommand {
+ async fn run(&self, client: Client) -> anyhow::Result<()> {
+ let id = match (&self.id, self.all) {
+ (Some(id), false) => Some(id.clone()),
+ (None, true) => None,
+ _ => bail!("give a token id, or --all"),
+ };
+ let response = client.web_token_revoke(codec::WebTokenRevoke { id }).await?;
+ println!("Revoked {} token(s).", response.revoked);
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::parse_ttl;
+
+ #[test]
+ fn ttl_specs() {
+ assert_eq!(parse_ttl("90").unwrap(), 90);
+ assert_eq!(parse_ttl("90s").unwrap(), 90);
+ assert_eq!(parse_ttl("30m").unwrap(), 1800);
+ assert_eq!(parse_ttl("12h").unwrap(), 43_200);
+ assert_eq!(parse_ttl("7d").unwrap(), 604_800);
+ assert!(parse_ttl("soon").is_err());
+ assert!(parse_ttl("3w").is_err());
+ }
+}