use crate::{Error, Page, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
pub const MAX_TEXT_FETCH_BYTES: usize = 16 * 1024 * 1024;
#[derive(Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BoundedFetchRequest {
pub url: String,
pub method: String,
pub headers: HashMap<String, String>,
pub body: Option<String>,
pub redirect: String,
pub max_bytes: usize,
}
impl BoundedFetchRequest {
pub fn get(url: impl Into<String>) -> Self {
Self {
url: url.into(),
method: "GET".into(),
headers: HashMap::new(),
body: None,
redirect: "follow".into(),
max_bytes: 8192,
}
}
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BoundedFetchResponse {
pub url: String,
pub status: u16,
pub status_text: String,
pub r#type: String,
pub redirected: bool,
pub headers: HashMap<String, String>,
pub body: String,
pub truncated: bool,
pub bytes_read: usize,
pub body_omitted: Option<String>,
}
impl std::fmt::Debug for BoundedFetchRequest {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BoundedFetchRequest")
.field("url", &crate::util::without_query(&self.url))
.field("method", &self.method)
.field("header_names", &self.headers.keys())
.field("body_bytes", &self.body.as_ref().map(String::len))
.field("redirect", &self.redirect)
.field("max_bytes", &self.max_bytes)
.finish()
}
}
impl std::fmt::Debug for BoundedFetchResponse {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BoundedFetchResponse")
.field("url", &crate::util::without_query(&self.url))
.field("status", &self.status)
.field("status_text", &self.status_text)
.field("type", &self.r#type)
.field("redirected", &self.redirected)
.field("header_names", &self.headers.keys())
.field("body_bytes", &self.body.len())
.field("truncated", &self.truncated)
.field("bytes_read", &self.bytes_read)
.field("body_omitted", &self.body_omitted)
.finish()
}
}
impl Page {
pub async fn fetch_bounded(
&self,
request: &BoundedFetchRequest,
) -> Result<BoundedFetchResponse> {
if request.max_bytes > MAX_TEXT_FETCH_BYTES {
return Err(Error::invalid_argument(format!(
"max_bytes must not exceed {MAX_TEXT_FETCH_BYTES} bytes"
)));
}
if !matches!(request.redirect.as_str(), "follow" | "manual" | "error") {
return Err(Error::invalid_argument(
"redirect must be follow, manual, or error",
));
}
let request = serde_json::to_string(request)?;
let script = format!(
"(async () => {{ const request = {request}; {} }})()",
include_str!("bounded.js")
);
self.evaluate(&script).await
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn debug_redacts_query_header_values_and_body() {
let mut request = BoundedFetchRequest::get("https://example.test/api?token=secret-query");
request
.headers
.insert("authorization".into(), "secret-header".into());
request.body = Some("secret-body".into());
let response = BoundedFetchResponse {
url: request.url.clone(),
status: 200,
status_text: "OK".into(),
r#type: "basic".into(),
redirected: false,
headers: request.headers.clone(),
body: "secret-body".into(),
truncated: false,
bytes_read: 11,
body_omitted: None,
};
for debug in [format!("{request:?}"), format!("{response:?}")] {
assert!(debug.contains("https://example.test/api"), "{debug}");
assert!(debug.contains("authorization"), "{debug}");
assert!(debug.contains("body_bytes"), "{debug}");
for secret in ["secret-query", "secret-header", "secret-body"] {
assert!(!debug.contains(secret), "{debug}");
}
}
}
}