use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use http::HeaderMap;
use url::Url;
use crate::{ChannelEnd, Context, Error, FetchPolicy, Result};
#[non_exhaustive]
pub struct WebSocketRequest {
pub url: Url,
pub protocols: Vec<String>,
pub headers: HeaderMap,
pub context: Option<Context>,
pub end: ChannelEnd,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct WebSocketAccept {
pub protocol: String,
pub extensions: String,
}
pub type WebSocketFuture = Pin<Box<dyn Future<Output = Result<WebSocketAccept>> + Send + 'static>>;
pub trait WebSocketTransport: Send + Sync + 'static {
fn connect(&self, request: WebSocketRequest) -> WebSocketFuture;
}
impl<T: WebSocketTransport + ?Sized> WebSocketTransport for Arc<T> {
fn connect(&self, request: WebSocketRequest) -> WebSocketFuture {
(**self).connect(request)
}
}
struct FunctionTransport<F>(F);
impl<F, Fut> WebSocketTransport for FunctionTransport<F>
where
F: Fn(WebSocketRequest) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<WebSocketAccept>> + Send + 'static,
{
fn connect(&self, request: WebSocketRequest) -> WebSocketFuture {
Box::pin((self.0)(request))
}
}
pub fn websocket_fn<F, Fut>(function: F) -> impl WebSocketTransport
where
F: Fn(WebSocketRequest) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<WebSocketAccept>> + Send + 'static,
{
FunctionTransport(function)
}
type UrlRewrite = Arc<dyn Fn(&mut Url) -> Result<()> + Send + Sync>;
type CredentialProvider = Arc<dyn Fn(&Url, &mut HeaderMap) -> Result<()> + Send + Sync>;
#[derive(Clone)]
pub struct WebSocketService {
transport: Arc<dyn WebSocketTransport>,
policy: FetchPolicy,
rewrite: Option<UrlRewrite>,
credentials: Option<CredentialProvider>,
forward_context: bool,
}
impl WebSocketService {
pub fn new(transport: impl WebSocketTransport, policy: FetchPolicy) -> Self {
Self {
transport: Arc::new(transport),
policy,
rewrite: None,
credentials: None,
forward_context: false,
}
}
pub fn rewrite(
mut self,
rewrite: impl Fn(&mut Url) -> Result<()> + Send + Sync + 'static,
) -> Self {
self.rewrite = Some(Arc::new(rewrite));
self
}
pub fn credentials(
mut self,
credentials: impl Fn(&Url, &mut HeaderMap) -> Result<()> + Send + Sync + 'static,
) -> Self {
self.credentials = Some(Arc::new(credentials));
self
}
pub fn forward_context(mut self) -> Self {
self.forward_context = true;
self
}
pub(crate) fn open(
&self,
url: &str,
protocols: Vec<String>,
context: Option<Context>,
end: ChannelEnd,
) -> Result<WebSocketFuture> {
let mut url = websocket_url(url)?;
validate_protocols(&protocols)?;
if let Some(rewrite) = &self.rewrite {
rewrite(&mut url)?;
url = websocket_url(url.as_str())?;
}
self.policy.check_websocket(&url)?;
let mut headers = HeaderMap::new();
if let Some(credentials) = &self.credentials {
credentials(&url, &mut headers)?;
}
Ok(self.transport.connect(WebSocketRequest {
url,
protocols,
headers,
context: context.filter(|_| self.forward_context),
end,
}))
}
}
fn websocket_url(input: &str) -> Result<Url> {
let url = Url::parse(input).map_err(|_| invalid("invalid WebSocket URL"))?;
if !matches!(url.scheme(), "ws" | "wss")
|| url.host_str().is_none()
|| !url.username().is_empty()
|| url.password().is_some()
|| url.fragment().is_some()
{
return Err(invalid(
"expected a ws: or wss: URL without credentials or fragment",
));
}
Ok(url)
}
fn validate_protocols(protocols: &[String]) -> Result<()> {
let token = |protocol: &str| {
!protocol.is_empty()
&& protocol
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&byte))
};
for (index, protocol) in protocols.iter().enumerate() {
if !token(protocol) || protocols[..index].contains(protocol) {
return Err(invalid("invalid WebSocket subprotocol"));
}
}
Ok(())
}
fn invalid(message: &str) -> Error {
Error::InvalidRequest(message.into())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn urls_and_protocols_are_checked() {
assert!(websocket_url("wss://example.test/chat?room=1").is_ok());
for url in [
"https://example.test/",
"ws://user@example.test/",
"ws://example.test/#top",
"wss://",
"not a url",
] {
assert!(websocket_url(url).is_err(), "{url}");
}
assert!(validate_protocols(&["chat".into(), "v2.json".into()]).is_ok());
for protocols in [
vec!["".to_owned()],
vec!["a b".into()],
vec!["x".into(), "x".into()],
] {
assert!(validate_protocols(&protocols).is_err(), "{protocols:?}");
}
}
#[test]
fn the_policy_treats_ws_as_http() -> Result<()> {
let policy = FetchPolicy::deny_all()
.allow_origin("https://example.test")?
.allow_origin("http://plain.test:8080")?;
let check = |url: &str| policy.check_websocket(&Url::parse(url).unwrap());
assert!(check("wss://example.test/socket").is_ok());
assert!(check("ws://plain.test:8080/").is_ok());
assert!(matches!(
check("ws://example.test/"),
Err(Error::PermissionDenied)
));
assert!(matches!(
check("wss://plain.test:8080/"),
Err(Error::PermissionDenied)
));
assert!(matches!(
check("wss://other.test/"),
Err(Error::PermissionDenied)
));
Ok(())
}
}