use rtflow_core::error::{Error, Result};
use std::time::Duration;
use tokio::io::{AsyncWrite, AsyncWriteExt};
pub struct ResponseWriter<W: AsyncWrite + Unpin> {
inner: W,
headers_written: bool,
connection_close: bool,
write_timeout: Option<Duration>,
egress: u64,
}
const EGRESS_FLUSH_BYTES: u64 = 64 * 1024;
const SECURITY_HEADERS: &[(&str, &str)] = &[
("X-Content-Type-Options", "nosniff"),
("X-Frame-Options", "DENY"),
("Referrer-Policy", "no-referrer"),
];
impl<W: AsyncWrite + Unpin> ResponseWriter<W> {
pub fn new(writer: W) -> Self {
Self {
inner: writer,
headers_written: false,
connection_close: false,
write_timeout: None,
egress: 0,
}
}
pub fn with_write_timeout(mut self, timeout: Option<Duration>) -> Self {
self.write_timeout = timeout;
self
}
pub fn reset(&mut self) {
self.headers_written = false;
self.connection_close = false;
}
async fn write_all_with_timeout(&mut self, buf: &[u8]) -> Result<()> {
match self.write_timeout {
Some(timeout) => tokio::time::timeout(timeout, self.inner.write_all(buf))
.await
.map_err(|_| Error::Http("response write timed out".into()))??,
None => self.inner.write_all(buf).await?,
}
self.record_egress(buf.len());
Ok(())
}
fn record_egress(&mut self, bytes: usize) {
self.egress = self
.egress
.saturating_add(u64::try_from(bytes).unwrap_or(u64::MAX));
if self.egress >= EGRESS_FLUSH_BYTES {
self.flush_egress();
}
}
fn flush_egress(&mut self) {
if self.egress > 0 {
rtflow_security::guard::global().note_egress(self.egress);
self.egress = 0;
}
}
pub fn should_close(&self) -> bool {
self.connection_close
}
pub async fn write_headers(&mut self, status: u16, headers: &[(&str, &str)]) -> Result<()> {
if self.headers_written {
return Err(Error::Http("HTTP response headers already written".into()));
}
let reason = status_reason(status);
let mut buf = format!("HTTP/1.1 {} {}\r\n", status, reason);
for (key, value) in headers {
if key.eq_ignore_ascii_case("connection") && value.eq_ignore_ascii_case("close") {
self.connection_close = true;
}
buf.push_str(key);
buf.push_str(": ");
buf.push_str(value);
buf.push_str("\r\n");
}
for (key, value) in SECURITY_HEADERS {
if headers
.iter()
.any(|(existing, _)| existing.eq_ignore_ascii_case(key))
{
continue;
}
buf.push_str(key);
buf.push_str(": ");
buf.push_str(value);
buf.push_str("\r\n");
}
buf.push_str("\r\n");
self.write_all_with_timeout(buf.as_bytes()).await?;
self.headers_written = true;
Ok(())
}
pub async fn write_chunked_headers(
&mut self,
content_type: &str,
extra_headers: &[(&str, &str)],
) -> Result<()> {
let mut headers = vec![
("Transfer-Encoding", "chunked"),
("Content-Type", content_type),
("Cache-Control", "no-cache, no-store"),
("Connection", "keep-alive"),
];
for (k, v) in extra_headers {
headers.push((k, v));
}
self.write_headers(200, &headers).await
}
pub async fn write_chunk(&mut self, data: &[u8]) -> Result<()> {
if !self.headers_written {
return Err(Error::Http("HTTP chunk written before headers".into()));
}
if data.is_empty() {
return Ok(());
}
let header = format!("{:x}\r\n", data.len());
self.write_all_with_timeout(header.as_bytes()).await?;
self.write_all_with_timeout(data).await?;
self.write_all_with_timeout(b"\r\n").await?;
Ok(())
}
pub async fn write_raw(&mut self, data: &[u8]) -> Result<()> {
if data.is_empty() {
return Ok(());
}
self.write_all_with_timeout(data).await?;
Ok(())
}
pub async fn write_body(&mut self, status: u16, content_type: &str, body: &[u8]) -> Result<()> {
let content_length = body.len().to_string();
let headers = vec![
("Content-Type", content_type),
("Content-Length", content_length.as_str()),
("Cache-Control", "no-cache"),
("Connection", "close"),
("Access-Control-Allow-Origin", "*"),
];
self.write_headers(status, &headers).await?;
self.write_all_with_timeout(body).await?;
Ok(())
}
pub async fn write_json(&mut self, status: u16, json: &str) -> Result<()> {
self.write_body(status, "application/json", json.as_bytes())
.await
}
pub async fn flush(&mut self) -> Result<()> {
self.flush_egress();
self.inner.flush().await.map_err(Error::from)
}
pub fn into_inner(mut self) -> W {
self.flush_egress();
self.inner
}
}
fn status_reason(status: u16) -> &'static str {
match status {
200 => "OK",
201 => "Created",
204 => "No Content",
206 => "Partial Content",
301 => "Moved Permanently",
302 => "Found",
304 => "Not Modified",
400 => "Bad Request",
401 => "Unauthorized",
403 => "Forbidden",
404 => "Not Found",
405 => "Method Not Allowed",
408 => "Request Timeout",
409 => "Conflict",
416 => "Range Not Satisfiable",
429 => "Too Many Requests",
500 => "Internal Server Error",
502 => "Bad Gateway",
503 => "Service Unavailable",
_ => "Unknown",
}
}
#[cfg(test)]
mod tests {
use super::*;
async fn render(headers: &[(&str, &str)]) -> String {
let mut writer = ResponseWriter::new(Vec::new());
writer.write_headers(200, headers).await.expect("headers");
String::from_utf8_lossy(&writer.into_inner()).into_owned()
}
#[tokio::test]
async fn every_response_carries_security_headers() {
let text = render(&[]).await;
assert!(
text.contains("X-Content-Type-Options: nosniff\r\n"),
"{text}"
);
assert!(text.contains("X-Frame-Options: DENY\r\n"), "{text}");
assert!(text.contains("Referrer-Policy: no-referrer\r\n"), "{text}");
}
#[tokio::test]
async fn handler_supplied_header_wins_and_is_not_duplicated() {
let text = render(&[("X-Frame-Options", "SAMEORIGIN")]).await;
assert_eq!(text.matches("X-Frame-Options").count(), 1, "{text}");
assert!(text.contains("X-Frame-Options: SAMEORIGIN\r\n"), "{text}");
assert!(
text.contains("X-Content-Type-Options: nosniff\r\n"),
"{text}"
);
}
}