fix(adapters): input-schema enforcement + header/cookie params (OAI-02, OAI-03, OAI-07, OAI-09)
- build_request takes the op's input_schema and rejects undeclared input keys (INVALID_INPUT) before any outbound request is built; explicit `additionalProperties: true` opts into catch-all input; non-object inputs rejected (OAI-02) - in: header parameters are stamped `wire: header` in the generated input schema and sent as upstream request headers, not query params; in: cookie fails import with a clear error (OAI-03) - a spec parameter named `body` is rejected at import unconditionally (OAI-07) - FromJsonSchema::new returns Result and validates method/path template/ base_url at construction; registered visibility forced to Internal like from_openapi; module doc corrected (OAI-09) Verified: cargo test, cargo test --all-features, clippy (both feature sets, -D warnings), cargo fmt --check
This commit is contained in:
+276
-12
@@ -9,6 +9,18 @@
|
||||
//! (ADR-014): it reads `OperationContext.capabilities`, never
|
||||
//! `std::env::var`. Imported error codes are `HTTP_<status>` to avoid
|
||||
//! collision with the protocol-level codes (ADR-023).
|
||||
//!
|
||||
//! Input-schema enforcement (review 001 OAI-02): every input key must be
|
||||
//! declared by the operation's `input_schema` or consumed by a path
|
||||
//! template placeholder; undeclared keys are rejected with `INVALID_INPUT`
|
||||
//! at call time. There is no pass-through knob — a request the forwarder
|
||||
//! sends must match what `/schema` advertises, so peer-supplied input
|
||||
//! cannot add upstream query parameters, headers, or craft a request body
|
||||
//! the contract does not declare. Declared keys route by designation: a
|
||||
//! property marked [`HEADER_PARAM_IN_MARKER`]` = "header"` is sent as a
|
||||
//! request header, the declared [`GATEWAY_BODY_KEY`] property becomes the
|
||||
//! request body, and every other declared key becomes an upstream query
|
||||
//! parameter.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
@@ -40,12 +52,33 @@ pub(crate) const RESPONSE_BODY_CAP: usize = 16 * 1024 * 1024;
|
||||
/// that would otherwise be discarded (FWD-10).
|
||||
pub(crate) const ERROR_BODY_ECHO_CAP: usize = 4096;
|
||||
|
||||
// Fractional-path helpers and body echo caps follow; the gateway body key
|
||||
// and the header-param wire marker used by the input routing live with the
|
||||
// other request-construction defaults here.
|
||||
|
||||
/// Upper bound on how much of a non-2xx upstream body is read, both for
|
||||
/// the bounded echo and for connection reuse. A larger error body is
|
||||
/// truncated in the surfaced message and the connection is dropped —
|
||||
/// a deliberate trade of pool reuse against unbounded drain time (FWD-10).
|
||||
const STATUS_BODY_DRAIN: usize = 64 * 1024;
|
||||
|
||||
/// The input key that carries the request body on the gateway shape
|
||||
/// (ADR-047). Declared by `from_openapi`'s generated input schemas
|
||||
/// (OAI-07 rejects a spec parameter with the same name at import) and
|
||||
/// consumed by [`build_request`] ahead of the query-parameter routing.
|
||||
pub(crate) const GATEWAY_BODY_KEY: &str = "body";
|
||||
|
||||
/// Property-level marker inside an operation's `input_schema` properties
|
||||
/// that routes the declared value into an HTTP request header instead of
|
||||
/// the query string (review 001 OAI-03). `from_openapi` stamps
|
||||
/// `"wire": "header"` on properties generated from `in: header`
|
||||
/// parameters; `from_jsonschema` callers can mark their declared
|
||||
/// properties the same way. Unmarked properties default to query
|
||||
/// placement, preserving the pre-OAI-03 wire behavior for
|
||||
/// `in: query`/`in: path` parameters.
|
||||
pub(crate) const HEADER_PARAM_IN_MARKER: &str = "wire";
|
||||
pub(crate) const HEADER_PARAM_MARKER_VALUE: &str = "header";
|
||||
|
||||
#[derive(Clone)]
|
||||
pub enum HttpAuthScheme {
|
||||
Bearer,
|
||||
@@ -68,27 +101,39 @@ pub(crate) fn build_request(
|
||||
auth_scheme: &Option<HttpAuthScheme>,
|
||||
default_headers: &HashMap<String, String>,
|
||||
namespace: &str,
|
||||
input_schema: &Value,
|
||||
input: &Value,
|
||||
context: &OperationContext,
|
||||
) -> Result<(Method, Url, Option<Value>, HeaderMap), CallError> {
|
||||
let inputs = input.as_object();
|
||||
let inputs = input.as_object().ok_or_else(|| {
|
||||
CallError::invalid_input(format!(
|
||||
"input must be a JSON object (got {}); adapter operations take a named-key input",
|
||||
type_name_of(input)
|
||||
))
|
||||
})?;
|
||||
|
||||
enforce_input_schema(input_schema, inputs)?;
|
||||
|
||||
let mut query_params: Vec<(String, String)> = Vec::new();
|
||||
let mut header_params: Vec<(String, String)> = Vec::new();
|
||||
let param_locations = param_locations(input_schema);
|
||||
let mut body: Option<Value> = None;
|
||||
if let Some(obj) = inputs {
|
||||
for (key, value) in obj {
|
||||
if is_path_placeholder(key, path_template) {
|
||||
continue;
|
||||
}
|
||||
if key == "body" {
|
||||
body = Some(value.clone());
|
||||
} else {
|
||||
query_params.push((key.clone(), value_to_query(value)));
|
||||
}
|
||||
for (key, value) in inputs {
|
||||
if is_path_placeholder(key, path_template) {
|
||||
continue;
|
||||
}
|
||||
if key == GATEWAY_BODY_KEY {
|
||||
body = Some(value.clone());
|
||||
continue;
|
||||
}
|
||||
if param_locations.get(key.as_str()) == Some(&ParamLocation::Header) {
|
||||
header_params.push((key.clone(), value_to_query(value)));
|
||||
} else {
|
||||
query_params.push((key.clone(), value_to_query(value)));
|
||||
}
|
||||
}
|
||||
|
||||
let rendered_path = render_path_template(path_template, inputs)?;
|
||||
let rendered_path = render_path_template(path_template, Some(inputs))?;
|
||||
let mut url = assemble_request_url(base_url, &rendered_path)?;
|
||||
if !query_params.is_empty() {
|
||||
let mut pairs = url.query_pairs_mut();
|
||||
@@ -98,6 +143,19 @@ pub(crate) fn build_request(
|
||||
}
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
for (k, v) in &header_params {
|
||||
let name = HeaderName::try_from(k.as_str()).map_err(|_| {
|
||||
CallError::internal(format!(
|
||||
"declared header parameter `{k}` is not a valid HTTP header name; refusing to build a request that silently drops it"
|
||||
))
|
||||
})?;
|
||||
let value = HeaderValue::try_from(v.as_str()).map_err(|_| {
|
||||
CallError::internal(format!(
|
||||
"declared header parameter `{k}` has an invalid value (control or non-ASCII bytes are not permitted); refusing to build a request that silently drops it"
|
||||
))
|
||||
})?;
|
||||
headers.insert(name, value);
|
||||
}
|
||||
for (k, v) in default_headers {
|
||||
let name = HeaderName::try_from(k.as_str()).map_err(|_| {
|
||||
CallError::internal(format!(
|
||||
@@ -161,6 +219,92 @@ pub(crate) fn build_request(
|
||||
Ok((http_method, url, body, headers))
|
||||
}
|
||||
|
||||
/// Upstream placement of a declared input property (review 001 OAI-03).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum ParamLocation {
|
||||
Query,
|
||||
Header,
|
||||
}
|
||||
|
||||
/// Map of declared property name → upstream placement, read from the
|
||||
/// `input_schema`'s `properties` entries via [`HEADER_PARAM_IN_MARKER`]
|
||||
/// (query placement is the default).
|
||||
fn param_locations(input_schema: &Value) -> HashMap<&str, ParamLocation> {
|
||||
let mut out = HashMap::new();
|
||||
let Some(properties) = input_schema.get("properties").and_then(|p| p.as_object()) else {
|
||||
return out;
|
||||
};
|
||||
for (name, schema) in properties {
|
||||
let is_header = schema
|
||||
.get(HEADER_PARAM_IN_MARKER)
|
||||
.and_then(|w| w.as_str())
|
||||
.is_some_and(|w| w == HEADER_PARAM_MARKER_VALUE);
|
||||
out.insert(
|
||||
name.as_str(),
|
||||
if is_header {
|
||||
ParamLocation::Header
|
||||
} else {
|
||||
ParamLocation::Query
|
||||
},
|
||||
);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn type_name_of(value: &Value) -> &'static str {
|
||||
match value {
|
||||
Value::Null => "null",
|
||||
Value::Bool(_) => "a boolean",
|
||||
Value::Number(_) => "a number",
|
||||
Value::String(_) => "a string",
|
||||
Value::Array(_) => "an array",
|
||||
Value::Object(_) => "an object",
|
||||
}
|
||||
}
|
||||
|
||||
/// Input-schema enforcement at call time (review 001 OAI-02).
|
||||
///
|
||||
/// Every input key must be declared by the input schema's `properties` —
|
||||
/// including the gateway body property, which `from_openapi` declares as
|
||||
/// `body` whenever the operation has a requestBody, and including the
|
||||
/// path-consumed placeholders, which `from_openapi` also declares. An
|
||||
/// explicit `"additionalProperties": true` opts the operation into
|
||||
/// catch-all input (JSON Schema semantics: the schema advertises that
|
||||
/// extra properties are valid), which `from_jsonschema` callers can use
|
||||
/// for open-shaped endpoints. Anything else undeclared is a rejected
|
||||
/// `INVALID_INPUT` rather than a silently-added upstream query parameter,
|
||||
/// so peer input like `{debug: true}` or `{impersonate_id: …}` cannot
|
||||
/// decorate an upstream request the contract does not advertise.
|
||||
fn enforce_input_schema(
|
||||
input_schema: &Value,
|
||||
inputs: &serde_json::Map<String, Value>,
|
||||
) -> Result<(), CallError> {
|
||||
let declared = input_schema
|
||||
.get("properties")
|
||||
.and_then(|p| p.as_object())
|
||||
.map(|p| p.keys().cloned().collect::<Vec<_>>())
|
||||
.unwrap_or_default();
|
||||
let catch_all = input_schema.get("additionalProperties") == Some(&Value::Bool(true));
|
||||
let unknown: Vec<String> = inputs
|
||||
.keys()
|
||||
.filter(|key| !catch_all && !declared.iter().any(|d| d == *key))
|
||||
.cloned()
|
||||
.collect();
|
||||
if let Some(first) = unknown.first() {
|
||||
let declared_list = if declared.is_empty() {
|
||||
"none".to_string()
|
||||
} else {
|
||||
declared.join(", ")
|
||||
};
|
||||
return Err(CallError::invalid_input(format!(
|
||||
"input key `{first}` is not declared by the operation's input schema \
|
||||
(declared: {declared_list}); undeclared keys are rejected so peer \
|
||||
input cannot shape the upstream request beyond the advertised contract"
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Percent-encode set for a spliced path-parameter value: the WHATWG
|
||||
/// path set (controls, space, `"`, `<`, `>`, `` ` ``, `#`, `?`, `{`, `}`)
|
||||
/// plus `/` so a value stays one literal segment, plus `%` `?` `#`
|
||||
@@ -502,6 +646,7 @@ pub(crate) async fn forward(
|
||||
auth_scheme: &Option<HttpAuthScheme>,
|
||||
default_headers: &HashMap<String, String>,
|
||||
namespace: &str,
|
||||
input_schema: &Value,
|
||||
error_status_codes: &[(u16, String)],
|
||||
input: Value,
|
||||
context: OperationContext,
|
||||
@@ -515,6 +660,7 @@ pub(crate) async fn forward(
|
||||
auth_scheme,
|
||||
default_headers,
|
||||
namespace,
|
||||
input_schema,
|
||||
&input,
|
||||
&context,
|
||||
) {
|
||||
@@ -620,6 +766,7 @@ pub(crate) fn forward_stream(
|
||||
auth_scheme: &Option<HttpAuthScheme>,
|
||||
default_headers: &HashMap<String, String>,
|
||||
namespace: &str,
|
||||
input_schema: &Value,
|
||||
error_status_codes: &[(u16, String)],
|
||||
input: Value,
|
||||
context: OperationContext,
|
||||
@@ -633,6 +780,7 @@ pub(crate) fn forward_stream(
|
||||
auth_scheme,
|
||||
default_headers,
|
||||
namespace,
|
||||
input_schema,
|
||||
&input,
|
||||
&context,
|
||||
) {
|
||||
@@ -973,6 +1121,7 @@ mod tests {
|
||||
&None,
|
||||
&TestHashMap::new(),
|
||||
"svc",
|
||||
&serde_json::json!({"type": "object", "additionalProperties": true}),
|
||||
&input,
|
||||
&ctx,
|
||||
)?;
|
||||
@@ -1116,6 +1265,115 @@ mod tests {
|
||||
assert_eq!(url.query(), Some("lang=en&q=a%26b%3Dc+d"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undeclared_input_keys_are_rejected_not_sent_upstream() {
|
||||
let ctx = noop_context();
|
||||
let schema = json!({
|
||||
"type": "object",
|
||||
"properties": {"owner": {"type": "string"}, "body": {"type": "object"}},
|
||||
});
|
||||
for input in [
|
||||
json!({"owner": "a", "debug": "true"}),
|
||||
json!({"owner": "a", "impersonate_id": "x"}),
|
||||
json!({"debug": "true"}),
|
||||
] {
|
||||
let err = build_request(
|
||||
"https://api.example.com",
|
||||
"/x/{owner}",
|
||||
"GET",
|
||||
&None,
|
||||
&TestHashMap::new(),
|
||||
"svc",
|
||||
&schema,
|
||||
&input,
|
||||
&ctx,
|
||||
)
|
||||
.expect_err("undeclared peer input must be rejected");
|
||||
assert_eq!(err.code, "INVALID_INPUT", "input was: {input}");
|
||||
assert!(err.message.contains("not declared"), "input was: {input}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn declared_body_and_header_params_route_off_the_query_string() {
|
||||
let ctx = noop_context();
|
||||
let schema = json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"q": {"type": "string"},
|
||||
"X-Trace-Id": {"type": "string", "wire": "header"},
|
||||
"body": {"type": "object"},
|
||||
},
|
||||
});
|
||||
let (_, url, body, headers) = build_request(
|
||||
"https://api.example.com",
|
||||
"/search",
|
||||
"POST",
|
||||
&None,
|
||||
&TestHashMap::new(),
|
||||
"svc",
|
||||
&schema,
|
||||
&json!({"q": "rust", "X-Trace-Id": "t-1", "body": {"page": 2}}),
|
||||
&ctx,
|
||||
)
|
||||
.expect("declared input builds");
|
||||
assert_eq!(url.query(), Some("q=rust"));
|
||||
assert_eq!(
|
||||
headers
|
||||
.get("x-trace-id")
|
||||
.expect("header param sent as header")
|
||||
.to_str()
|
||||
.expect("ascii header"),
|
||||
"t-1"
|
||||
);
|
||||
assert_eq!(body, Some(json!({"page": 2})));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_object_input_is_rejected() {
|
||||
let ctx = noop_context();
|
||||
let schema = json!({"type": "object", "properties": {"q": {"type": "string"}}});
|
||||
for input in [json!(null), json!([1]), json!("str"), json!(42)] {
|
||||
let err = build_request(
|
||||
"https://api.example.com",
|
||||
"/x",
|
||||
"GET",
|
||||
&None,
|
||||
&TestHashMap::new(),
|
||||
"svc",
|
||||
&schema,
|
||||
&input,
|
||||
&ctx,
|
||||
)
|
||||
.expect_err("non-object input must be rejected");
|
||||
assert_eq!(err.code, "INVALID_INPUT");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn additional_properties_true_opts_into_catch_all_input() {
|
||||
let ctx = noop_context();
|
||||
let schema = json!({
|
||||
"type": "object",
|
||||
"properties": {"q": {"type": "string"}},
|
||||
"additionalProperties": true,
|
||||
});
|
||||
let (_, url, _, _) = build_request(
|
||||
"https://api.example.com",
|
||||
"/search",
|
||||
"GET",
|
||||
&None,
|
||||
&TestHashMap::new(),
|
||||
"svc",
|
||||
&schema,
|
||||
&json!({"q": "rust", "debug": "true"}),
|
||||
&ctx,
|
||||
)
|
||||
.expect("catch-all input builds");
|
||||
let q = url.query().expect("query present");
|
||||
assert!(q.contains("q=rust") && q.contains("debug=true"), "{q}");
|
||||
}
|
||||
|
||||
fn ctx_with_capability(namespace: &str, value: String) -> OperationContext {
|
||||
let mut ctx = noop_context();
|
||||
ctx.capabilities = Capabilities::new().with_http_token(namespace, value);
|
||||
@@ -1228,6 +1486,7 @@ mod tests {
|
||||
auth_scheme,
|
||||
&TestHashMap::new(),
|
||||
"svc",
|
||||
&serde_json::json!({"type": "object"}),
|
||||
&[],
|
||||
json!({}),
|
||||
ctx,
|
||||
@@ -1310,6 +1569,7 @@ mod tests {
|
||||
&None,
|
||||
&TestHashMap::new(),
|
||||
"svc",
|
||||
&serde_json::json!({"type": "object"}),
|
||||
&[],
|
||||
json!({}),
|
||||
noop_context(),
|
||||
@@ -1348,6 +1608,7 @@ mod tests {
|
||||
&None,
|
||||
&TestHashMap::new(),
|
||||
"svc",
|
||||
&serde_json::json!({"type": "object"}),
|
||||
&[],
|
||||
json!({}),
|
||||
noop_context(),
|
||||
@@ -1399,6 +1660,7 @@ mod tests {
|
||||
}),
|
||||
&TestHashMap::new(),
|
||||
"svc",
|
||||
&serde_json::json!({"type": "object"}),
|
||||
&json!({}),
|
||||
&ctx,
|
||||
);
|
||||
@@ -1422,6 +1684,7 @@ mod tests {
|
||||
&None,
|
||||
&defaults,
|
||||
"svc",
|
||||
&serde_json::json!({"type": "object"}),
|
||||
&json!({}),
|
||||
&noop_context(),
|
||||
)
|
||||
@@ -1441,6 +1704,7 @@ mod tests {
|
||||
&None,
|
||||
&defaults,
|
||||
"svc",
|
||||
&serde_json::json!({"type": "object"}),
|
||||
&json!({}),
|
||||
&noop_context(),
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user