fix(gateway): fail-closed publish_schema compile + compile-once cache (GW-01 follow-up)
- new gateway::schema_cache — PublishSchemaCache: compile the op's publish_schema once per registration (value-keyed invalidation for hot reload), cache compile failures (logged once at error level, never retried per request) - /publish compile failure is now fail-closed: the chunk stream terminates with INTERNAL (500), the error text stays in the log (no schema internals on the wire) — the per-request warn-and-skip unvalidated ingest path is removed - schema resolution is lazy (first chunk poll, after invoke_sink's 404/403/422 pre-checks — GW-11 order preserved) and keyed by schema value, so re-registration/hot reload is picked up (test) - NdjsonChunkStream: first Err item is terminal (done + stream end), mirroring the wire pump's send(Err) + break — Ok chunks can never follow an error on the HTTP path either (found by spy-handler test) Verified: cargo test (308), cargo test --all-features, clippy --all-targets -D warnings (default + all-features), fmt --check. Tasks: review-001-publish-schema-validation-robust
This commit is contained in:
+368
-40
@@ -33,6 +33,7 @@ use serde_json::{json, Value};
|
||||
|
||||
use super::dispatch::GatewayDispatch;
|
||||
use super::error::call_error_to_http_response_with_identity;
|
||||
use super::schema_cache::{CompileFailed, PublishSchemaCache};
|
||||
use crate::server::auth::ResolvedIdentity;
|
||||
use crate::server::state::RouterState;
|
||||
|
||||
@@ -53,16 +54,19 @@ type ByteStream = futures::stream::BoxStream<'static, Result<Bytes, axum::Error>
|
||||
pub(crate) struct GatewayState {
|
||||
registry: Arc<OperationRegistry>,
|
||||
identity_provider: Arc<dyn IdentityProvider>,
|
||||
publish_schemas: crate::gateway::schema_cache::PublishSchemaCache,
|
||||
}
|
||||
|
||||
impl GatewayState {
|
||||
pub(crate) fn new(
|
||||
registry: Arc<OperationRegistry>,
|
||||
identity_provider: Arc<dyn IdentityProvider>,
|
||||
publish_schemas: crate::gateway::schema_cache::PublishSchemaCache,
|
||||
) -> Self {
|
||||
Self {
|
||||
registry,
|
||||
identity_provider,
|
||||
publish_schemas,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,6 +83,7 @@ impl FromRef<RouterState> for GatewayState {
|
||||
GatewayState::new(
|
||||
Arc::clone(&state.registry),
|
||||
Arc::clone(&state.identity_provider),
|
||||
state.publish_schemas.clone(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -219,13 +224,22 @@ pub type SubscribeStream = BoxStream<'static, Result<Event, Infallible>>;
|
||||
/// a client disconnect drops the body stream and the sink (and the
|
||||
/// handler's `PublishStream`) sees EOF, matching call-protocol
|
||||
/// write-half close semantics.
|
||||
///
|
||||
/// Chunk validation (GW-01, ADR-046 §4): each chunk is validated
|
||||
/// against the op's `publish_schema` via the compile-once
|
||||
/// [`PublishSchemaCache`]. A schema that **fails to compile** is
|
||||
/// fail-closed, not fail-open (review-001 post-remediation follow-up):
|
||||
/// the chunk stream terminates with `INTERNAL` before any chunk reaches
|
||||
/// the handler — the unvalidated-ingest hole the per-request
|
||||
/// `warn`-and-skip opened is shut. The compile error itself is logged
|
||||
/// at error level and never echoed on the wire.
|
||||
pub(crate) async fn publish_handler(
|
||||
State(state): State<GatewayState>,
|
||||
ResolvedIdentity(identity): ResolvedIdentity,
|
||||
body: axum::body::Body,
|
||||
) -> Response {
|
||||
let mut header_lines = BufferedLines::new(Box::pin(body.into_data_stream()));
|
||||
let (operation, first_chunk, validator): (String, Value, Option<jsonschema::Validator>) = {
|
||||
let (operation, first_chunk) = {
|
||||
let line = match header_lines.next_line().await {
|
||||
Ok(Some(line)) => line,
|
||||
Ok(None) => {
|
||||
@@ -251,25 +265,16 @@ pub(crate) async fn publish_handler(
|
||||
let Some(chunk) = value.get("chunk") else {
|
||||
return missing_header_field_response();
|
||||
};
|
||||
let validator = state
|
||||
.registry
|
||||
.registration(op.strip_prefix('/').unwrap_or(&op))
|
||||
.and_then(|reg| reg.spec.publish_schema.clone())
|
||||
.and_then(|schema| match jsonschema::options().build(&schema) {
|
||||
Ok(v) => Some(v),
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
operation = %op,
|
||||
error = %e,
|
||||
"publish_schema failed to compile; chunks will not be validated"
|
||||
);
|
||||
None
|
||||
}
|
||||
});
|
||||
(op, chunk.clone(), validator)
|
||||
(op, chunk.clone())
|
||||
};
|
||||
|
||||
let chunks = NdjsonChunkStream::new(header_lines, validator, Some(first_chunk));
|
||||
let chunks = NdjsonChunkStream::new(
|
||||
header_lines,
|
||||
Arc::clone(&state.registry),
|
||||
state.publish_schemas.clone(),
|
||||
operation.clone(),
|
||||
Some(first_chunk),
|
||||
);
|
||||
let dispatch = state.dispatch();
|
||||
let envelope = dispatch
|
||||
.invoke_sink(identity.clone(), &operation, Value::Null, Box::pin(chunks))
|
||||
@@ -277,6 +282,88 @@ pub(crate) async fn publish_handler(
|
||||
envelope_to_response(envelope, identity.as_ref())
|
||||
}
|
||||
|
||||
/// The per-request `publish_schema` situation for a `/publish` call
|
||||
/// (ADR-046 §4). Resolution is lazy — the chunk stream resolves against
|
||||
/// the [`PublishSchemaCache`] on its first poll, which runs only after
|
||||
/// `invoke_sink`'s pre-checks have admitted the operation (an unknown,
|
||||
/// internal, or wrong-type op is rejected before any schema resolution
|
||||
/// or compile happens, preserving the GW-11 dispatch-owned pre-check
|
||||
/// order and keeping 404/403/422 intact).
|
||||
enum PublishSchemaState {
|
||||
/// Not yet resolved: the stream holds the registry + cache until
|
||||
/// the first chunk is polled.
|
||||
Unresolved {
|
||||
registry: Arc<OperationRegistry>,
|
||||
cache: PublishSchemaCache,
|
||||
operation: String,
|
||||
},
|
||||
/// The op registers no `publish_schema`; chunks pass as-is (the
|
||||
/// wire path's behavior for schema-less Pub ops).
|
||||
Unvalidated,
|
||||
/// Chunks are validated against this compiled validator.
|
||||
Validated(std::sync::Arc<jsonschema::Validator>),
|
||||
/// The op's `publish_schema` failed to compile (GW-01 follow-up):
|
||||
/// fail-closed — the stream yields one terminal `INTERNAL` error
|
||||
/// and ends, so no chunk ever reaches the handler unvalidated.
|
||||
Failed(CompileFailed),
|
||||
}
|
||||
|
||||
impl PublishSchemaState {
|
||||
fn resolve(&mut self) {
|
||||
let Self::Unresolved {
|
||||
registry,
|
||||
cache,
|
||||
operation,
|
||||
} = self
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let operation = std::mem::take(operation);
|
||||
*self = match cache.validator(registry, &operation) {
|
||||
Ok(None) => Self::Unvalidated,
|
||||
Ok(Some(validator)) => Self::Validated(validator),
|
||||
Err(compile_failed) => {
|
||||
tracing::debug!(
|
||||
operation = %operation,
|
||||
"rejecting /publish: the operation's publish_schema could not be compiled \
|
||||
(fail-closed)"
|
||||
);
|
||||
Self::Failed(compile_failed)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Validate one chunk; also flips a terminal compile failure into
|
||||
/// stream-end after the first error item (an `Err` from this stream
|
||||
/// is terminal — the handler sees the error and the stream closes,
|
||||
/// mirroring the wire pump's `send(Err)` + `break`).
|
||||
fn validate_chunk(
|
||||
&mut self,
|
||||
value: Value,
|
||||
) -> std::task::Poll<Option<Result<Value, CallError>>> {
|
||||
self.resolve();
|
||||
match self {
|
||||
Self::Unvalidated => std::task::Poll::Ready(Some(Ok(value))),
|
||||
Self::Validated(validator) => {
|
||||
if Validator::is_valid(validator, &value) {
|
||||
std::task::Poll::Ready(Some(Ok(value)))
|
||||
} else {
|
||||
std::task::Poll::Ready(Some(Err(CallError::invalid_input(
|
||||
"published chunk failed publish_schema validation",
|
||||
)
|
||||
.with_details(json!({ "chunk": value })))))
|
||||
}
|
||||
}
|
||||
Self::Failed(failed) => {
|
||||
let error = failed.call_error();
|
||||
*self = Self::Unvalidated;
|
||||
std::task::Poll::Ready(Some(Err(error)))
|
||||
}
|
||||
Self::Unresolved { .. } => unreachable!("resolve() runs before validation"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn missing_header_field_response() -> Response {
|
||||
invalid_input_response("first publish line must carry {\"operation\": ..., \"chunk\": ...}")
|
||||
}
|
||||
@@ -371,40 +458,53 @@ impl LineError {
|
||||
/// validated against the op's compiled `publish_schema` — matching the
|
||||
/// wire dispatcher's per-chunk validation (alkcall ADR-046). Malformed
|
||||
/// JSON, a schema violation, or a body-read failure yields a terminal
|
||||
/// `Err(INVALID_INPUT)` item — the same shape an initiator-side
|
||||
/// `call.error` produces on the wire.
|
||||
/// `Err` item — the same shape an initiator-side `call.error` produces
|
||||
/// on the wire, and equally terminal: like the wire pump's
|
||||
/// `send(Err)` + `break`, the first `Err` ends the stream. A schema
|
||||
/// that failed to compile yields that terminal `Err(INTERNAL)` on the
|
||||
/// first chunk — fail-closed (review-001 post-remediation follow-up).
|
||||
struct NdjsonChunkStream {
|
||||
lines: std::pin::Pin<Box<BufferedLines>>,
|
||||
validator: Option<jsonschema::Validator>,
|
||||
schema_state: PublishSchemaState,
|
||||
pending_first: Option<Value>,
|
||||
done: bool,
|
||||
}
|
||||
|
||||
impl NdjsonChunkStream {
|
||||
fn new(
|
||||
lines: BufferedLines,
|
||||
validator: Option<jsonschema::Validator>,
|
||||
registry: Arc<OperationRegistry>,
|
||||
cache: PublishSchemaCache,
|
||||
operation: String,
|
||||
pending_first: Option<Value>,
|
||||
) -> Self {
|
||||
Self {
|
||||
lines: Box::pin(lines),
|
||||
validator,
|
||||
schema_state: PublishSchemaState::Unresolved {
|
||||
registry,
|
||||
cache,
|
||||
operation,
|
||||
},
|
||||
pending_first,
|
||||
done: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_chunk(
|
||||
/// `Some(item)` from `validate_chunk` where an `Err` item sets
|
||||
/// `done` — the stream does not yield after an error (the wire
|
||||
/// pump's semantics; the dropping mpsc sender below is the same
|
||||
/// contract).
|
||||
fn poll_validated(
|
||||
&mut self,
|
||||
value: Value,
|
||||
) -> std::task::Poll<Option<Result<Value, CallError>>> {
|
||||
if let Some(validator) = &self.validator {
|
||||
if !Validator::is_valid(validator, &value) {
|
||||
return std::task::Poll::Ready(Some(Err(CallError::invalid_input(
|
||||
"published chunk failed publish_schema validation",
|
||||
)
|
||||
.with_details(json!({ "chunk": value })))));
|
||||
match self.schema_state.validate_chunk(value) {
|
||||
std::task::Poll::Ready(Some(Err(e))) => {
|
||||
self.done = true;
|
||||
std::task::Poll::Ready(Some(Err(e)))
|
||||
}
|
||||
other => other,
|
||||
}
|
||||
std::task::Poll::Ready(Some(Ok(value)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -415,30 +515,44 @@ impl futures::Stream for NdjsonChunkStream {
|
||||
mut self: std::pin::Pin<&mut Self>,
|
||||
cx: &mut std::task::Context<'_>,
|
||||
) -> std::task::Poll<Option<Self::Item>> {
|
||||
if self.done {
|
||||
return std::task::Poll::Ready(None);
|
||||
}
|
||||
if self.pending_first.is_some() {
|
||||
let first = self.pending_first.take().unwrap_or(Value::Null);
|
||||
return self.validate_chunk(first);
|
||||
return self.poll_validated(first);
|
||||
}
|
||||
let line = {
|
||||
let mut next = Box::pin(self.lines.next_line());
|
||||
match std::future::Future::poll(next.as_mut(), cx) {
|
||||
std::task::Poll::Ready(Ok(Some(line))) => line,
|
||||
std::task::Poll::Ready(Ok(None)) => return std::task::Poll::Ready(None),
|
||||
std::task::Poll::Ready(Err(e)) => {
|
||||
return std::task::Poll::Ready(Some(Err(CallError::invalid_input(e.message()))))
|
||||
let polled = match std::future::Future::poll(next.as_mut(), cx) {
|
||||
std::task::Poll::Ready(Ok(Some(line))) => Ok(Some(line)),
|
||||
std::task::Poll::Ready(Ok(None)) => Ok(None),
|
||||
std::task::Poll::Ready(Err(e)) => Err(e.message()),
|
||||
std::task::Poll::Pending => {
|
||||
drop(next);
|
||||
return std::task::Poll::Pending;
|
||||
}
|
||||
};
|
||||
drop(next);
|
||||
match polled {
|
||||
Ok(Some(line)) => line,
|
||||
Ok(None) => return std::task::Poll::Ready(None),
|
||||
Err(message) => {
|
||||
self.done = true;
|
||||
return std::task::Poll::Ready(Some(Err(CallError::invalid_input(message))));
|
||||
}
|
||||
std::task::Poll::Pending => return std::task::Poll::Pending,
|
||||
}
|
||||
};
|
||||
let value = match serde_json::from_slice::<Value>(&line) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
self.done = true;
|
||||
return std::task::Poll::Ready(Some(Err(CallError::invalid_input(format!(
|
||||
"publish line is not valid JSON: {e}"
|
||||
)))))
|
||||
)))));
|
||||
}
|
||||
};
|
||||
self.validate_chunk(value)
|
||||
self.poll_validated(value)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -862,6 +976,7 @@ mod tests {
|
||||
crate::websocket::DEFAULT_WS_MAX_SESSIONS,
|
||||
)),
|
||||
ws_idle_timeout: Some(crate::websocket::DEFAULT_WS_IDLE_TIMEOUT),
|
||||
publish_schemas: crate::gateway::schema_cache::PublishSchemaCache::new(),
|
||||
};
|
||||
let auth_state = Arc::clone(&provider);
|
||||
gateway_router()
|
||||
@@ -2243,4 +2358,217 @@ mod tests {
|
||||
"the prematurely terminated body reaches the handler as an INVALID_INPUT Err item: {resp}"
|
||||
);
|
||||
}
|
||||
|
||||
// --- publish_schema fail-closed (GW-01 follow-up) ----------------------
|
||||
|
||||
fn registry_with_broken_publish_schema() -> Arc<OperationRegistry> {
|
||||
let mut registry = OperationRegistry::new();
|
||||
registry
|
||||
.register(HandlerRegistration::new(
|
||||
OperationSpec::new(
|
||||
"ingest/broken",
|
||||
OperationType::Pub,
|
||||
Visibility::External,
|
||||
json!({}),
|
||||
json!({}),
|
||||
vec![],
|
||||
AccessControl::default(),
|
||||
None,
|
||||
)
|
||||
.with_publish_schema(json!({ "required": "n" })), // `required` must be an array
|
||||
HandlerKind::Sink(make_sink_handler(
|
||||
|_unused_input, ctx, mut chunks| async move {
|
||||
use futures::StreamExt;
|
||||
let mut collected: Vec<Value> = Vec::new();
|
||||
while let Some(chunk) = chunks.next().await {
|
||||
match chunk {
|
||||
Ok(v) => collected.push(v),
|
||||
Err(e) => return ResponseEnvelope::error(ctx.request_id, e),
|
||||
}
|
||||
}
|
||||
ResponseEnvelope::ok(
|
||||
ctx.request_id,
|
||||
json!({ "count": collected.len(), "chunks": collected }),
|
||||
)
|
||||
},
|
||||
)),
|
||||
OperationProvenance::Local,
|
||||
None,
|
||||
None,
|
||||
Capabilities::new(),
|
||||
))
|
||||
.unwrap();
|
||||
Arc::new(registry)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn publish_with_uncompilable_schema_fails_closed_with_internal() {
|
||||
let router = build_router(registry_with_broken_publish_schema(), unused_provider());
|
||||
let body = ndjson(&[
|
||||
json!({ "operation": "ingest/broken", "chunk": { "n": 1 } }),
|
||||
json!({ "n": 2 }),
|
||||
]);
|
||||
let req = raw_request("POST", "/publish", body);
|
||||
let (status, resp) = send(router, req).await;
|
||||
assert_eq!(
|
||||
status,
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"an un-compilable publish_schema must fail the request loudly (500), not skip validation: {resp}"
|
||||
);
|
||||
assert_eq!(
|
||||
resp.get("code"),
|
||||
Some(&json!("INTERNAL")),
|
||||
"fail-closed maps to INTERNAL, not INVALID_INPUT (this is a server-side defect): {resp}"
|
||||
);
|
||||
assert!(
|
||||
resp.get("message")
|
||||
.and_then(|m| m.as_str())
|
||||
.map(|m| m.contains("failed to compile"))
|
||||
.unwrap_or(false),
|
||||
"the wire message names the compile failure without echoing schema internals: {resp}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn publish_with_uncompilable_schema_never_delivers_chunks_to_the_handler() {
|
||||
let mut registry = OperationRegistry::new();
|
||||
registry
|
||||
.register(HandlerRegistration::new(
|
||||
OperationSpec::new(
|
||||
"ingest/spy",
|
||||
OperationType::Pub,
|
||||
Visibility::External,
|
||||
json!({}),
|
||||
json!({}),
|
||||
vec![],
|
||||
AccessControl::default(),
|
||||
None,
|
||||
)
|
||||
.with_publish_schema(json!({ "type": 123 })), // non-string `type` never compiles
|
||||
HandlerKind::Sink(make_sink_handler(|_input, ctx, mut chunks| async move {
|
||||
use futures::StreamExt;
|
||||
let received: Vec<Result<Value, CallError>> = chunks.by_ref().collect().await;
|
||||
ResponseEnvelope::ok(
|
||||
ctx.request_id,
|
||||
json!({
|
||||
"chunk_count": received.len(),
|
||||
"ok_chunks": received.iter().filter(|r| r.is_ok()).count(),
|
||||
"error_codes": received
|
||||
.iter()
|
||||
.filter_map(|r| r.as_ref().err().map(|e| e.code.clone()))
|
||||
.collect::<Vec<String>>(),
|
||||
}),
|
||||
)
|
||||
})),
|
||||
OperationProvenance::Local,
|
||||
None,
|
||||
None,
|
||||
Capabilities::new(),
|
||||
))
|
||||
.unwrap();
|
||||
let router = build_router(Arc::new(registry), unused_provider());
|
||||
let body = ndjson(&[
|
||||
json!({ "operation": "ingest/spy", "chunk": { "n": 1 } }),
|
||||
json!({ "n": 2 }),
|
||||
]);
|
||||
let (status, resp) = send(router, raw_request("POST", "/publish", body)).await;
|
||||
let output = resp.get("output").expect("spy handler output");
|
||||
assert_eq!(
|
||||
output.get("ok_chunks"),
|
||||
Some(&json!(0)),
|
||||
"no chunk may reach the handler when the publish_schema failed to compile: {resp}"
|
||||
);
|
||||
assert_eq!(
|
||||
output.get("chunk_count"),
|
||||
Some(&json!(1)),
|
||||
"exactly one item flows: the terminal INTERNAL error (stream ends after it): {resp}"
|
||||
);
|
||||
assert_eq!(
|
||||
output.get("error_codes"),
|
||||
Some(&json!(["INTERNAL"])),
|
||||
"the terminal item is the fail-closed INTERNAL compile error: {resp}"
|
||||
);
|
||||
let _ = status;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn publish_hot_reload_replacement_schema_is_picked_up() {
|
||||
let cache = PublishSchemaCache::new();
|
||||
let mut registry = OperationRegistry::new();
|
||||
registry
|
||||
.register(HandlerRegistration::new(
|
||||
OperationSpec::new(
|
||||
"ingest/typed",
|
||||
OperationType::Pub,
|
||||
Visibility::External,
|
||||
json!({}),
|
||||
json!({}),
|
||||
vec![],
|
||||
AccessControl::default(),
|
||||
None,
|
||||
)
|
||||
.with_publish_schema(json!({
|
||||
"type": "object",
|
||||
"properties": { "n": { "type": "integer" } },
|
||||
"required": ["n"],
|
||||
"additionalProperties": false
|
||||
})),
|
||||
HandlerKind::Sink(make_sink_handler(|input, ctx, _chunks| async move {
|
||||
ResponseEnvelope::ok(ctx.request_id, input)
|
||||
})),
|
||||
OperationProvenance::Local,
|
||||
None,
|
||||
None,
|
||||
Capabilities::new(),
|
||||
))
|
||||
.unwrap();
|
||||
|
||||
let v1 = cache
|
||||
.validator(®istry, "ingest/typed")
|
||||
.unwrap()
|
||||
.expect("compiled validator");
|
||||
assert!(!v1.is_valid(&json!({ "n": 1, "extra": true })));
|
||||
|
||||
// Hot reload: re-register the same op with a schema that drops
|
||||
// `additionalProperties`; the same cache entry must recompile.
|
||||
registry
|
||||
.register(HandlerRegistration::new(
|
||||
OperationSpec::new(
|
||||
"ingest/typed",
|
||||
OperationType::Pub,
|
||||
Visibility::External,
|
||||
json!({}),
|
||||
json!({}),
|
||||
vec![],
|
||||
AccessControl::default(),
|
||||
None,
|
||||
)
|
||||
.with_publish_schema(json!({
|
||||
"type": "object",
|
||||
"properties": { "n": { "type": "integer" } },
|
||||
"required": ["n"]
|
||||
})),
|
||||
HandlerKind::Sink(make_sink_handler(|input, ctx, _chunks| async move {
|
||||
ResponseEnvelope::ok(ctx.request_id, input)
|
||||
})),
|
||||
OperationProvenance::Local,
|
||||
None,
|
||||
None,
|
||||
Capabilities::new(),
|
||||
))
|
||||
.unwrap();
|
||||
|
||||
let v2 = cache
|
||||
.validator(®istry, "ingest/typed")
|
||||
.unwrap()
|
||||
.expect("recompiled validator");
|
||||
assert!(
|
||||
!Arc::ptr_eq(&v1, &v2),
|
||||
"a changed schema value must invalidate the cached validator"
|
||||
);
|
||||
assert!(
|
||||
v2.is_valid(&json!({ "n": 1, "extra": true })),
|
||||
"the recompiled schema must reflect the new registration"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user