feat(import): preserve supported HTTP contracts

This commit is contained in:
bsodfather committed 2026-09-13 03:30:31 +03:00
1 parent 083974c27f
commit f8ee7c9bfe
87 files changed
+7496 -534

No files matched your search

+488
View File
@@ -0,0 +1,488 @@
use std::{collections::BTreeMap, io};
use base64::{Engine as _, engine::general_purpose::STANDARD};
use crank_core::RestTarget;
use futures_util::StreamExt;
use serde_json::Value;
use crate::RestAdapterError;
pub(crate) async fn apply_body(
builder: reqwest::RequestBuilder,
body: &Value,
content_type: &str,
multipart_mime_types: Option<&BTreeMap<String, Vec<String>>>,
max_request_bytes: usize,
) -> Result<reqwest::RequestBuilder, RestAdapterError> {
match content_type {
"application/x-www-form-urlencoded" => {
let encoded = form_urlencoded(body, max_request_bytes)?;
Ok(builder.header("content-type", content_type).body(encoded))
}
"multipart/form-data" => {
let form = multipart_form(body, multipart_mime_types, max_request_bytes)?;
let boundary = form.boundary().to_owned();
let mut encoded = BoundedBuffer::new(max_request_bytes);
let mut stream = Box::pin(form.into_stream());
while let Some(chunk) = stream.next().await {
let chunk = chunk?;
encoded.append(&chunk)?;
}
Ok(builder
.header(
"content-type",
format!("multipart/form-data; boundary={boundary}"),
)
.body(encoded.into_bytes()))
}
content_type if content_type == "application/json" || content_type.ends_with("+json") => {
let encoded = json_bytes(body, max_request_bytes)?;
Ok(builder.header("content-type", content_type).body(encoded))
}
_ => Err(RestAdapterError::InvalidBodyContract {
reason: "unsupported request content type".to_owned(),
}),
}
}
pub(crate) fn apply_legacy_json_body(
builder: reqwest::RequestBuilder,
body: &Value,
has_content_type: bool,
limit_bytes: usize,
) -> Result<reqwest::RequestBuilder, RestAdapterError> {
let builder = if has_content_type {
builder
} else {
builder.header("content-type", "application/json")
};
Ok(builder.body(json_bytes(body, limit_bytes)?))
}
pub(crate) fn selected_request_content_type(
target: &RestTarget,
request: &crate::RestRequest,
) -> Result<Option<String>, RestAdapterError> {
let Some(contract) = &target.request_contract else {
if request.body_content_type.is_some() {
return Err(RestAdapterError::InvalidBodyContract {
reason: "body content type requires a typed request contract".to_owned(),
});
}
return Ok(None);
};
let selected = match (&contract.selector_field, &request.body_content_type) {
(Some(_), Some(selected)) => selected,
(Some(_), None) => {
return Err(RestAdapterError::InvalidBodyContract {
reason: "content_type selector is required".to_owned(),
});
}
(None, Some(_)) => {
return Err(RestAdapterError::InvalidBodyContract {
reason: "single-variant request does not accept a selector".to_owned(),
});
}
(None, None) => contract
.variants
.as_slice()
.first()
.filter(|_| contract.variants.len() == 1)
.map(|variant| &variant.media_type)
.ok_or_else(|| RestAdapterError::InvalidBodyContract {
reason: "request contract without selector must have one media variant".to_owned(),
})?,
};
contract
.variants
.iter()
.any(|variant| variant.media_type == *selected)
.then(|| selected.clone())
.map(Some)
.ok_or_else(|| RestAdapterError::InvalidBodyContract {
reason: "content_type selector is not declared by request contract".to_owned(),
})
}
fn json_bytes(body: &Value, limit_bytes: usize) -> Result<Vec<u8>, RestAdapterError> {
let mut encoded = BoundedBuffer::new(limit_bytes);
let result = serde_json::to_writer(&mut encoded, body);
if encoded.exceeded {
return Err(RestAdapterError::RequestTooLarge { limit_bytes });
}
result.map_err(|_| RestAdapterError::InvalidBodyContract {
reason: "body cannot be serialized as JSON".to_owned(),
})?;
Ok(encoded.into_bytes())
}
fn form_urlencoded(body: &Value, limit_bytes: usize) -> Result<Vec<u8>, RestAdapterError> {
let object = body
.as_object()
.ok_or_else(|| RestAdapterError::InvalidBodyContract {
reason: "form body must be an object".to_owned(),
})?;
let mut encoded = BoundedBuffer::new(limit_bytes);
let mut first = true;
for (name, value) in object {
match value {
Value::Array(values) => {
for value in values {
append_form_pair(&mut encoded, &mut first, name, &form_scalar(value)?)?;
}
}
value => {
append_form_pair(&mut encoded, &mut first, name, &form_scalar(value)?)?;
}
};
}
Ok(encoded.into_bytes())
}
fn append_form_pair(
encoded: &mut BoundedBuffer,
first: &mut bool,
name: &str,
value: &str,
) -> Result<(), RestAdapterError> {
if !*first {
encoded.append(b"&")?;
}
*first = false;
append_form_component(encoded, name.as_bytes())?;
encoded.append(b"=")?;
append_form_component(encoded, value.as_bytes())
}
fn append_form_component(
encoded: &mut BoundedBuffer,
value: &[u8],
) -> Result<(), RestAdapterError> {
const HEX: &[u8; 16] = b"0123456789ABCDEF";
for byte in value {
match byte {
b'*' | b'-' | b'.' | b'0'..=b'9' | b'A'..=b'Z' | b'_' | b'a'..=b'z' => {
encoded.append(&[*byte])?;
}
b' ' => encoded.append(b"+")?,
_ => encoded.append(&[b'%', HEX[(byte >> 4) as usize], HEX[(byte & 0x0f) as usize]])?,
}
}
Ok(())
}
fn form_scalar(value: &Value) -> Result<String, RestAdapterError> {
match value {
Value::Null => Ok("null".to_owned()),
Value::Bool(value) => Ok(value.to_string()),
Value::Number(value) => Ok(value.to_string()),
Value::String(value) => Ok(value.clone()),
Value::Array(_) | Value::Object(_) => Err(RestAdapterError::InvalidBodyContract {
reason: "form fields must be scalar or arrays of scalars".to_owned(),
}),
}
}
fn multipart_form(
body: &Value,
source_mime_types: Option<&BTreeMap<String, Vec<String>>>,
max_request_bytes: usize,
) -> Result<reqwest::multipart::Form, RestAdapterError> {
let object = body
.as_object()
.ok_or_else(|| RestAdapterError::InvalidBodyContract {
reason: "multipart body must be an object".to_owned(),
})?;
let mut form = reqwest::multipart::Form::new();
let mut payload_budget = MultipartPayloadBudget::new(max_request_bytes);
for (name, value) in object {
let values = value
.as_array()
.map_or_else(|| vec![value], |values| values.iter().collect());
for value in values {
if let Some(file) = value
.as_object()
.filter(|file| file.contains_key("data_base64"))
{
form = form.part(
name.clone(),
multipart_file(name, file, source_mime_types, &mut payload_budget)?,
);
} else {
let value = form_scalar(value)?;
payload_budget.reserve(value.len())?;
form = form.text(name.clone(), value);
}
}
}
Ok(form)
}
fn multipart_file(
field_name: &str,
file: &serde_json::Map<String, Value>,
source_mime_types: Option<&BTreeMap<String, Vec<String>>>,
payload_budget: &mut MultipartPayloadBudget,
) -> Result<reqwest::multipart::Part, RestAdapterError> {
if file
.keys()
.any(|key| !matches!(key.as_str(), "data_base64" | "filename" | "content_type"))
{
return Err(RestAdapterError::InvalidBodyContract {
reason: "file object contains unsupported field".to_owned(),
});
}
let encoded = file
.get("data_base64")
.and_then(Value::as_str)
.ok_or_else(|| RestAdapterError::InvalidBodyContract {
reason: "file data_base64 must be a string".to_owned(),
})?;
if encoded.chars().any(char::is_whitespace)
|| encoded.contains('-')
|| encoded.contains('_')
|| encoded.starts_with("data:")
{
return Err(RestAdapterError::InvalidBodyContract {
reason: "file data_base64 is not standard base64".to_owned(),
});
}
payload_budget.reserve(decoded_base64_len(encoded)?)?;
let bytes = STANDARD
.decode(encoded)
.map_err(|_| RestAdapterError::InvalidBodyContract {
reason: "file data_base64 is invalid".to_owned(),
})?;
let mut part = reqwest::multipart::Part::bytes(bytes);
if let Some(filename) = file.get("filename") {
let filename = filename
.as_str()
.filter(|value| !value.chars().any(char::is_control))
.ok_or_else(|| RestAdapterError::InvalidBodyContract {
reason: "filename is invalid".to_owned(),
})?;
part = part.file_name(filename.to_owned());
}
let allowed_mime_types = source_mime_types.and_then(|fields| fields.get(field_name));
if let Some(mime) = file.get("content_type") {
let mime = mime
.as_str()
.filter(|value| !value.chars().any(char::is_control))
.ok_or_else(|| RestAdapterError::InvalidBodyContract {
reason: "content_type is invalid".to_owned(),
})?;
validate_part_mime_type(mime, allowed_mime_types)?;
part = part
.mime_str(mime)
.map_err(|_| RestAdapterError::InvalidBodyContract {
reason: "content_type is invalid".to_owned(),
})?;
} else if let Some(allowed) = allowed_mime_types {
match allowed.as_slice() {
[mime] => {
validate_part_mime_type(mime, Some(allowed))?;
part = part
.mime_str(mime)
.map_err(|_| RestAdapterError::InvalidBodyContract {
reason: "source content_type is invalid".to_owned(),
})?;
}
[] => {}
_ => {
return Err(RestAdapterError::InvalidBodyContract {
reason: "content_type is required for this file field".to_owned(),
});
}
}
} else {
part = part.mime_str("application/octet-stream").map_err(|_| {
RestAdapterError::InvalidBodyContract {
reason: "default content_type is invalid".to_owned(),
}
})?;
}
Ok(part)
}
fn decoded_base64_len(encoded: &str) -> Result<usize, RestAdapterError> {
let padding = if encoded.ends_with("==") {
2
} else if encoded.ends_with('=') {
1
} else {
0
};
encoded
.len()
.checked_div(4)
.and_then(|groups| groups.checked_mul(3))
.and_then(|bytes| bytes.checked_sub(padding))
.ok_or_else(|| RestAdapterError::InvalidBodyContract {
reason: "file data_base64 is invalid".to_owned(),
})
}
struct MultipartPayloadBudget {
bytes: usize,
limit_bytes: usize,
}
impl MultipartPayloadBudget {
fn new(limit_bytes: usize) -> Self {
Self {
bytes: 0,
limit_bytes,
}
}
fn reserve(&mut self, bytes: usize) -> Result<(), RestAdapterError> {
if self.bytes.saturating_add(bytes) > self.limit_bytes {
return Err(RestAdapterError::RequestTooLarge {
limit_bytes: self.limit_bytes,
});
}
self.bytes += bytes;
Ok(())
}
}
struct BoundedBuffer {
bytes: Vec<u8>,
limit_bytes: usize,
exceeded: bool,
}
impl BoundedBuffer {
fn new(limit_bytes: usize) -> Self {
Self {
bytes: Vec::new(),
limit_bytes,
exceeded: false,
}
}
fn append(&mut self, bytes: &[u8]) -> Result<(), RestAdapterError> {
if self.bytes.len().saturating_add(bytes.len()) > self.limit_bytes {
self.exceeded = true;
return Err(RestAdapterError::RequestTooLarge {
limit_bytes: self.limit_bytes,
});
}
self.bytes.extend_from_slice(bytes);
Ok(())
}
fn into_bytes(self) -> Vec<u8> {
self.bytes
}
}
impl io::Write for BoundedBuffer {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
if self.bytes.len().saturating_add(bytes.len()) > self.limit_bytes {
self.exceeded = true;
return Err(io::Error::other("request body exceeds configured limit"));
}
self.bytes.extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
fn validate_part_mime_type(
value: &str,
allowed: Option<&Vec<String>>,
) -> Result<(), RestAdapterError> {
let normalized = mime_essence(value).ok_or_else(|| RestAdapterError::InvalidBodyContract {
reason: "content_type is invalid".to_owned(),
})?;
if let Some(allowed) = allowed
&& !allowed.iter().any(|candidate| {
mime_essence(candidate)
.map(|candidate| candidate.eq_ignore_ascii_case(normalized))
.unwrap_or(false)
})
{
return Err(RestAdapterError::InvalidBodyContract {
reason: "content_type is not allowed by the source contract".to_owned(),
});
}
Ok(())
}
fn mime_essence(value: &str) -> Option<&str> {
let essence = value.split(';').next()?.trim();
(essence.contains('/')
&& !essence.starts_with('/')
&& !essence.ends_with('/')
&& essence
.chars()
.all(|character| character.is_ascii_graphic() && !character.is_control()))
.then_some(essence)
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::{RestAdapterError, form_urlencoded, multipart_form};
#[test]
fn form_and_multipart_reject_invalid_contract_before_dispatch() {
assert_eq!(
String::from_utf8(form_urlencoded(&json!({"tag": ["a", "b"]}), 1024).unwrap()).unwrap(),
"tag=a&tag=b"
);
for invalid in [
"not base64!",
"SGVs bG8=",
"SGVsbG8_",
"data:text/plain,SGVsbG8=",
] {
assert!(
multipart_form(
&json!({"file": {"data_base64": invalid}}),
None,
4 * 1024 * 1024,
)
.is_err()
);
}
assert!(
multipart_form(
&json!({"file": {"data_base64": "SGVsbG8=", "path": "/tmp/secret"}}),
None,
4 * 1024 * 1024,
)
.is_err()
);
}
#[test]
fn form_encoding_escapes_incrementally_and_respects_the_limit() {
assert_eq!(
String::from_utf8(form_urlencoded(&json!({"sp ace": "a+b&/ёж"}), 1024).unwrap())
.unwrap(),
"sp+ace=a%2Bb%26%2F%D1%91%D0%B6"
);
assert!(matches!(
form_urlencoded(&json!({"field": "abcdef"}), 8),
Err(RestAdapterError::RequestTooLarge { limit_bytes: 8 })
));
}
#[test]
fn multipart_payload_limit_counts_multiple_decoded_files() {
assert!(matches!(
multipart_form(
&json!({"files": [{"data_base64": "AA=="}, {"data_base64": "AQ=="}]}),
None,
1,
),
Err(RestAdapterError::RequestTooLarge { limit_bytes: 1 })
));
}
}
+134 -152
View File
@@ -21,11 +21,14 @@ use reqwest::{
header::{HeaderMap, HeaderName, HeaderValue},
redirect,
};
use serde_json::Value;
use tracing::{Instrument, Span};
use tracing_opentelemetry::OpenTelemetrySpanExt;
use crate::{ExternalReferenceFetchError, RestAdapterError, RestRequest, RestResponse};
use crate::{
ExternalReferenceFetchError, RestAdapterError, RestRequest, RestResponse,
body::{apply_body, apply_legacy_json_body, selected_request_content_type},
response::{decode_body, normalize_headers, validate_response_contract},
};
#[derive(Clone, Debug)]
pub struct RestAdapter {
@@ -128,7 +131,22 @@ impl RestAdapter {
let result = async {
let url = build_url(target, request)?;
self.policy.validate_url(&url)?;
let mut headers = build_headers(target, request)?;
let mut header_request = request.clone();
let cookie_header = extract_mapped_cookies(&mut header_request.headers)?;
let mut headers = build_headers(target, &header_request)?;
if let Some(cookie_header) = cookie_header {
if headers.contains_key("cookie") {
return Err(RestAdapterError::InvalidBodyContract {
reason: "mapped cookie conflicts with an existing cookie header".to_owned(),
});
}
let value = HeaderValue::try_from(cookie_header).map_err(|_| {
RestAdapterError::InvalidBodyContract {
reason: "cookie parameter is invalid".to_owned(),
}
})?;
headers.insert("cookie", value);
}
if let Some(context) = trusted_context {
for (name, value) in context.outbound_headers() {
let (Ok(name), Ok(value)) =
@@ -152,14 +170,55 @@ impl RestAdapter {
.map_err(|details| RestAdapterError::InvalidConfiguration {
details: details.to_string(),
})?;
if request.body.is_none()
&& (request.body_content_type.is_some()
|| target
.request_contract
.as_ref()
.is_some_and(|contract| contract.body_required))
{
return Err(RestAdapterError::InvalidBodyContract {
reason: "request body contract requires a body".to_owned(),
});
}
let typed_content_type = if request.body.is_some() && target.request_contract.is_some()
{
selected_request_content_type(target, request)?
} else {
if request.body.is_some() && request.body_content_type.is_some() {
selected_request_content_type(target, request)?;
}
None
};
if typed_content_type.is_some() {
headers.remove("content-type");
}
let legacy_has_content_type = headers.contains_key("content-type");
let mut builder = client
.request(to_reqwest_method(target.method), url)
.headers(headers)
.timeout(Duration::from_millis(request.timeout_ms));
if let Some(body) = &request.body {
enforce_request_body_limit(body, self.policy.max_request_bytes)?;
builder = builder.json(body);
if let Some(content_type) = typed_content_type {
builder = apply_body(
builder,
body,
&content_type,
target.multipart_field_mime_types.get(&content_type),
self.policy.max_request_bytes,
)
.await?;
} else {
builder = apply_legacy_json_body(
builder,
body,
legacy_has_content_type,
self.policy.max_request_bytes,
)?;
}
}
if let Some(context) = trusted_context {
@@ -171,7 +230,8 @@ impl RestAdapter {
if status.is_redirection() {
return Err(RestAdapterError::RedirectNotAllowed);
}
let body = decode_body(response, self.policy.max_response_bytes).await?;
let (body, has_body, valid_json) =
decode_body(response, self.policy.max_response_bytes).await?;
if !status.is_success() {
return Err(RestAdapterError::UnexpectedStatus {
@@ -179,6 +239,7 @@ impl RestAdapter {
body,
});
}
validate_response_contract(target, status.as_u16(), &headers, has_body, valid_json)?;
Ok(RestResponse {
status_code: status.as_u16(),
@@ -199,6 +260,43 @@ impl RestAdapter {
}
}
fn extract_mapped_cookies(
headers: &mut BTreeMap<String, String>,
) -> Result<Option<String>, RestAdapterError> {
let internal = headers
.keys()
.filter(|name| name.starts_with("x-crank-internal-cookie-"))
.cloned()
.collect::<Vec<_>>();
if internal.is_empty() {
return Ok(None);
}
let mut cookies = Vec::with_capacity(internal.len());
for key in internal {
let value = headers.remove(&key).unwrap_or_default();
let (name, value) =
value
.split_once('\t')
.ok_or_else(|| RestAdapterError::InvalidBodyContract {
reason: "cookie parameter is malformed".to_owned(),
})?;
if name.is_empty()
|| name
.chars()
.any(|character| character.is_control() || matches!(character, ';' | '='))
|| value
.chars()
.any(|character| character.is_control() || character == ';')
{
return Err(RestAdapterError::InvalidBodyContract {
reason: "cookie parameter is invalid".to_owned(),
});
}
cookies.push(format!("{name}={value}"));
}
Ok(Some(cookies.join("; ")))
}
impl ExternalReferenceFetcher {
pub fn try_new(
policy: OutboundHttpPolicy,
@@ -363,12 +461,15 @@ fn upstream_outcome(error: &RestAdapterError) -> UpstreamOutcome {
UpstreamOutcome::Rejected
}
RestAdapterError::WindowExpired => UpstreamOutcome::WindowExpired,
RestAdapterError::InvalidSseEvent => UpstreamOutcome::InvalidResponse,
RestAdapterError::InvalidSseEvent | RestAdapterError::InvalidResponseContract { .. } => {
UpstreamOutcome::InvalidResponse
}
RestAdapterError::InvalidBaseUrl { .. }
| RestAdapterError::InvalidPathParameter { .. }
| RestAdapterError::InvalidQueryParameter { .. }
| RestAdapterError::InvalidHeaderName { .. }
| RestAdapterError::InvalidHeaderValue { .. } => UpstreamOutcome::InvalidRequest,
| RestAdapterError::InvalidHeaderValue { .. }
| RestAdapterError::InvalidBodyContract { .. } => UpstreamOutcome::InvalidRequest,
RestAdapterError::InvalidConfiguration { .. } => UpstreamOutcome::Configuration,
}
}
@@ -494,7 +595,7 @@ impl OutboundHttpPolicy {
.any(|pattern| host_matches(pattern, &host))
}
fn is_denied_ip(&self, address: IpAddr) -> bool {
pub(crate) fn is_denied_ip(&self, address: IpAddr) -> bool {
ip_match_hosts(address).iter().any(|host| {
self.denied_hosts
.iter()
@@ -502,7 +603,7 @@ impl OutboundHttpPolicy {
})
}
fn is_explicitly_allowed(&self, host: &str) -> bool {
pub(crate) fn is_explicitly_allowed(&self, host: &str) -> bool {
let host = normalize_host(host);
self.allowed_hosts
.iter()
@@ -601,7 +702,7 @@ fn is_public_ip(address: IpAddr) -> bool {
}
}
fn ip_match_hosts(address: IpAddr) -> Vec<String> {
pub(crate) fn ip_match_hosts(address: IpAddr) -> Vec<String> {
match address {
IpAddr::V4(address) => vec![address.to_string()],
IpAddr::V6(address) => {
@@ -667,11 +768,26 @@ fn build_url(target: &RestTarget, request: &RestRequest) -> Result<reqwest::Url,
url: "url".to_owned(),
})?;
let path = substitute_path_params(&target.path_template, &request.path_params);
let mut url = base_url.join(path.trim_start_matches('/')).map_err(|_| {
RestAdapterError::InvalidBaseUrl {
url: "url".to_owned(),
}
})?;
let mut url = if target.request_contract.is_some() || !target.response_contract.is_empty() {
let base_path = base_url.path().trim_end_matches('/');
let target_path = path.trim_start_matches('/');
let combined_path = if target_path.is_empty() {
base_path.to_owned()
} else if base_path.is_empty() {
format!("/{target_path}")
} else {
format!("{base_path}/{target_path}")
};
let mut url = base_url;
url.set_path(&combined_path);
url
} else {
base_url.join(path.trim_start_matches('/')).map_err(|_| {
RestAdapterError::InvalidBaseUrl {
url: "url".to_owned(),
}
})?
};
{
let mut query = url.query_pairs_mut();
@@ -842,107 +958,6 @@ impl Injector for ReqwestHeaderInjector<'_> {
}
}
async fn decode_body(
response: reqwest::Response,
max_response_bytes: usize,
) -> Result<Value, RestAdapterError> {
if response
.content_length()
.is_some_and(|length| length > max_response_bytes as u64)
{
return Err(RestAdapterError::ResponseTooLarge {
limit_bytes: max_response_bytes,
});
}
let mut stream = response.bytes_stream();
let mut bytes = Vec::new();
while let Some(chunk) = stream.next().await {
let chunk = chunk?;
if bytes.len().saturating_add(chunk.len()) > max_response_bytes {
return Err(RestAdapterError::ResponseTooLarge {
limit_bytes: max_response_bytes,
});
}
bytes.extend_from_slice(&chunk);
}
if bytes.is_empty() {
return Ok(Value::Null);
}
match serde_json::from_slice::<Value>(&bytes) {
Ok(value) => Ok(value),
Err(_) => Ok(Value::String(
String::from_utf8_lossy(&bytes).trim().to_owned(),
)),
}
}
fn enforce_request_body_limit(
body: &Value,
max_request_bytes: usize,
) -> Result<(), RestAdapterError> {
if max_request_bytes == 0 {
return Err(RestAdapterError::InvalidConfiguration {
details: "outbound request limit must be greater than zero".to_owned(),
});
}
let mut writer = LimitWriter::new(max_request_bytes);
let result = serde_json::to_writer(&mut writer, body);
if writer.exceeded {
return Err(RestAdapterError::RequestTooLarge {
limit_bytes: max_request_bytes,
});
}
result.map_err(|_| RestAdapterError::InvalidHeaderValue {
header: "body".to_owned(),
})?;
Ok(())
}
struct LimitWriter {
written: usize,
limit: usize,
exceeded: bool,
}
impl LimitWriter {
fn new(limit: usize) -> Self {
Self {
written: 0,
limit,
exceeded: false,
}
}
}
impl io::Write for LimitWriter {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
if self.written.saturating_add(buf.len()) > self.limit {
self.exceeded = true;
return Err(io::Error::other("request body exceeds configured limit"));
}
self.written += buf.len();
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
fn normalize_headers(headers: &HeaderMap) -> BTreeMap<String, String> {
headers
.iter()
.filter_map(|(name, value)| {
value
.to_str()
.ok()
.map(|value| (name.as_str().to_owned(), value.to_owned()))
})
.collect()
}
fn to_reqwest_method(method: HttpMethod) -> reqwest::Method {
match method {
HttpMethod::Get => reqwest::Method::GET,
@@ -950,40 +965,7 @@ fn to_reqwest_method(method: HttpMethod) -> reqwest::Method {
HttpMethod::Put => reqwest::Method::PUT,
HttpMethod::Patch => reqwest::Method::PATCH,
HttpMethod::Delete => reqwest::Method::DELETE,
}
}
#[cfg(test)]
mod tests {
use super::{OutboundHttpPolicy, ip_match_hosts};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
#[test]
fn denied_resolved_ip_overrides_explicitly_allowed_hostname() {
let policy = OutboundHttpPolicy::try_new_with_limits(
vec!["api.example.test".to_owned()],
vec!["169.254.169.254".to_owned()],
4 * 1024 * 1024,
4 * 1024 * 1024,
)
.unwrap();
assert!(policy.is_explicitly_allowed("api.example.test"));
assert!(policy.is_denied_ip(IpAddr::V4(Ipv4Addr::new(169, 254, 169, 254))));
}
#[test]
fn denied_resolved_ip_checks_ipv4_mapped_ipv6_alias() {
let policy = OutboundHttpPolicy::try_new_with_limits(
vec!["api.example.test".to_owned()],
vec!["127.0.0.1".to_owned()],
4 * 1024 * 1024,
4 * 1024 * 1024,
)
.unwrap();
let mapped = IpAddr::V6(Ipv6Addr::from(0xffff_7f00_0001u128));
assert!(ip_match_hosts(mapped).contains(&"127.0.0.1".to_owned()));
assert!(policy.is_denied_ip(mapped));
HttpMethod::Head => reqwest::Method::HEAD,
HttpMethod::Options => reqwest::Method::OPTIONS,
}
}
@@ -0,0 +1,32 @@
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use crate::client::{OutboundHttpPolicy, ip_match_hosts};
#[test]
fn denied_resolved_ip_overrides_explicitly_allowed_hostname() {
let policy = OutboundHttpPolicy::try_new_with_limits(
vec!["api.example.test".to_owned()],
vec!["169.254.169.254".to_owned()],
4 * 1024 * 1024,
4 * 1024 * 1024,
)
.unwrap();
assert!(policy.is_explicitly_allowed("api.example.test"));
assert!(policy.is_denied_ip(IpAddr::V4(Ipv4Addr::new(169, 254, 169, 254))));
}
#[test]
fn denied_resolved_ip_checks_ipv4_mapped_ipv6_alias() {
let policy = OutboundHttpPolicy::try_new_with_limits(
vec!["api.example.test".to_owned()],
vec!["127.0.0.1".to_owned()],
4 * 1024 * 1024,
4 * 1024 * 1024,
)
.unwrap();
let mapped = IpAddr::V6(Ipv6Addr::from(0xffff_7f00_0001u128));
assert!(ip_match_hosts(mapped).contains(&"127.0.0.1".to_owned()));
assert!(policy.is_denied_ip(mapped));
}
+4
View File
@@ -33,6 +33,8 @@ pub enum RestAdapterError {
InvalidHeaderName { header: String },
#[error("invalid header value for {header}")]
InvalidHeaderValue { header: String },
#[error("invalid REST request body contract")]
InvalidBodyContract { reason: String },
#[error("outbound target is not allowed")]
TargetNotAllowed { target: String },
#[error("outbound redirects are not allowed")]
@@ -49,6 +51,8 @@ pub enum RestAdapterError {
WindowExpired,
#[error("rest endpoint returned status {status}")]
UnexpectedStatus { status: u16, body: Value },
#[error("rest endpoint response does not match the Operation contract: {reason}")]
InvalidResponseContract { reason: String },
#[error("sse stream produced malformed event payload")]
InvalidSseEvent,
}
+10 -1
View File
@@ -1,6 +1,10 @@
mod body;
mod client;
#[cfg(test)]
mod client_tests;
mod error;
mod model;
mod response;
use async_trait::async_trait;
use crank_core::{
@@ -35,6 +39,7 @@ impl ProtocolAdapter for RestAdapter {
headers: prepared.headers.clone(),
trusted_header_names: prepared.trusted_header_names.clone(),
body: prepared.body.clone(),
body_content_type: prepared.body_content_type.clone(),
timeout_ms: prepared.timeout_ms,
};
let response = self.execute_with_context(target, &request, context).await?;
@@ -62,7 +67,8 @@ impl From<RestAdapterError> for ProtocolAdapterError {
RestAdapterError::InvalidPathParameter { .. }
| RestAdapterError::InvalidQueryParameter { .. }
| RestAdapterError::InvalidHeaderName { .. }
| RestAdapterError::InvalidHeaderValue { .. } => Self::InvalidPreparedRequest,
| RestAdapterError::InvalidHeaderValue { .. }
| RestAdapterError::InvalidBodyContract { .. } => Self::InvalidPreparedRequest,
RestAdapterError::RedirectNotAllowed => Self::TargetRejected,
RestAdapterError::TargetNotAllowed { .. } => Self::TargetRejected,
RestAdapterError::RequestTooLarge { .. } => Self::RequestTooLarge,
@@ -93,6 +99,9 @@ impl From<RestAdapterError> for ProtocolAdapterError {
RestAdapterError::InvalidSseEvent => Self::InvalidResponse {
dispatch: DispatchEvidence::MayHaveDispatched,
},
RestAdapterError::InvalidResponseContract { .. } => Self::InvalidResponse {
dispatch: DispatchEvidence::MayHaveDispatched,
},
}
}
}
+2
View File
@@ -15,6 +15,8 @@ pub struct RestRequest {
pub trusted_header_names: BTreeSet<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub body: Option<Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub body_content_type: Option<String>,
pub timeout_ms: u64,
}
+127
View File
@@ -0,0 +1,127 @@
use std::collections::BTreeMap;
use crank_core::RestTarget;
use futures_util::StreamExt;
use reqwest::header::HeaderMap;
use serde_json::Value;
use crate::RestAdapterError;
pub(crate) async fn decode_body(
response: reqwest::Response,
max_response_bytes: usize,
) -> Result<(Value, bool, bool), RestAdapterError> {
if response
.content_length()
.is_some_and(|length| length > max_response_bytes as u64)
{
return Err(RestAdapterError::ResponseTooLarge {
limit_bytes: max_response_bytes,
});
}
let mut stream = response.bytes_stream();
let mut bytes = Vec::new();
while let Some(chunk) = stream.next().await {
let chunk = chunk?;
if bytes.len().saturating_add(chunk.len()) > max_response_bytes {
return Err(RestAdapterError::ResponseTooLarge {
limit_bytes: max_response_bytes,
});
}
bytes.extend_from_slice(&chunk);
}
if bytes.is_empty() {
return Ok((Value::Null, false, false));
}
match serde_json::from_slice::<Value>(&bytes) {
Ok(value) => Ok((value, true, true)),
Err(_) => Ok((
Value::String(String::from_utf8_lossy(&bytes).trim().to_owned()),
true,
false,
)),
}
}
pub(crate) fn validate_response_contract(
target: &RestTarget,
status_code: u16,
headers: &BTreeMap<String, String>,
has_body: bool,
valid_json: bool,
) -> Result<(), RestAdapterError> {
if target.response_contract.is_empty() {
return Ok(());
}
let matching_status = target
.response_contract
.iter()
.filter(|descriptor| descriptor.status_code == status_code)
.collect::<Vec<_>>();
if matching_status.is_empty() {
return Err(RestAdapterError::UnexpectedStatus {
status: status_code,
body: Value::Null,
});
}
if !has_body {
return matching_status
.iter()
.any(|descriptor| descriptor.media_type.is_none())
.then_some(())
.ok_or_else(|| RestAdapterError::InvalidResponseContract {
reason: format!("status {status_code} requires a response body"),
});
}
let content_type = headers
.get("content-type")
.map(|value| normalized_media_type(value));
let Some(content_type) = content_type else {
return Err(RestAdapterError::InvalidResponseContract {
reason: format!("status {status_code} has a body without a content-type"),
});
};
if matching_status.iter().any(|descriptor| {
descriptor
.media_type
.as_deref()
.is_some_and(|expected| normalized_media_type(expected) == content_type)
}) {
if (content_type == "application/json" || content_type.ends_with("+json")) && !valid_json {
return Err(RestAdapterError::InvalidResponseContract {
reason: format!("status {status_code} has invalid JSON response body"),
});
}
return Ok(());
}
Err(RestAdapterError::InvalidResponseContract {
reason: format!("status {status_code} with content-type {content_type} is not declared"),
})
}
fn normalized_media_type(value: &str) -> String {
value
.split(';')
.next()
.unwrap_or_default()
.trim()
.to_ascii_lowercase()
}
pub(crate) fn normalize_headers(headers: &HeaderMap) -> BTreeMap<String, String> {
headers
.iter()
.filter_map(|(name, value)| {
value
.to_str()
.ok()
.map(|value| (name.as_str().to_owned(), value.to_owned()))
})
.collect()
}