feat(import): preserve supported HTTP contracts
This commit is contained in:
1 parent
083974c27f
commit
f8ee7c9bfe
87 files changed
+7496
-534
No files matched your search
@@ -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,
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user