Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dc9a7f0dbf | ||
|
|
3c4dbf3ad0 | ||
|
|
df006ee706 | ||
|
|
65c51006ad | ||
|
|
55c784c22d |
Generated
+4
-4
@@ -1237,7 +1237,7 @@ checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
|
|||||||
name = "wip-client"
|
name = "wip-client"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"wip-https",
|
"wip-http",
|
||||||
"wip-protocol",
|
"wip-protocol",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -1249,7 +1249,7 @@ dependencies = [
|
|||||||
"rustix 1.1.5",
|
"rustix 1.1.5",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
"wip-host",
|
"wip-host",
|
||||||
"wip-https",
|
"wip-http",
|
||||||
"wip-interface",
|
"wip-interface",
|
||||||
"wip-protocol",
|
"wip-protocol",
|
||||||
]
|
]
|
||||||
@@ -1264,7 +1264,7 @@ dependencies = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "wip-https"
|
name = "wip-http"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
@@ -1318,7 +1318,7 @@ dependencies = [
|
|||||||
"ureq",
|
"ureq",
|
||||||
"wip-client",
|
"wip-client",
|
||||||
"wip-fs-server",
|
"wip-fs-server",
|
||||||
"wip-https",
|
"wip-http",
|
||||||
"wip-protocol",
|
"wip-protocol",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ Rust building blocks for the Web Interface Protocol (WIP).
|
|||||||
|
|
||||||
The repository is a resolver-3 virtual Cargo workspace whose packages all live
|
The repository is a resolver-3 virtual Cargo workspace whose packages all live
|
||||||
under `crates/*`. It provides a transport-independent protocol model, the
|
under `crates/*`. It provides a transport-independent protocol model, the
|
||||||
standard framework-independent WIP over HTTPS v1 binding, a stateful
|
standard framework-independent WIP over HTTP v1 binding, a stateful
|
||||||
presentation-independent client runtime, a Rust interface-authoring facade, a
|
presentation-independent client runtime, a Rust interface-authoring facade, a
|
||||||
request-scoped host runtime, a bounded Linux filesystem projection server, an
|
request-scoped host runtime, a bounded Linux filesystem projection server, an
|
||||||
interactive terminal client, and a private public-API conformance consumer. The
|
interactive terminal client, and a private public-API conformance consumer. The
|
||||||
@@ -15,20 +15,20 @@ repository root is not itself a package.
|
|||||||
```text
|
```text
|
||||||
wip-tui (interactive Worldspace explorer and operation editor)
|
wip-tui (interactive Worldspace explorer and operation editor)
|
||||||
├── wip-client Known Space, request identity, validators, and calls
|
├── wip-client Known Space, request identity, validators, and calls
|
||||||
├── wip-https framework-neutral HTTP request/response messages
|
├── wip-http framework-neutral HTTP request/response messages
|
||||||
└── wip-protocol descriptors and logical values
|
└── wip-protocol descriptors and logical values
|
||||||
|
|
||||||
wip-fs-server (request-time filesystem projection and loopback listener)
|
wip-fs-server (request-time filesystem projection and loopback listener)
|
||||||
├── wip-https standard routes/codecs/envelopes/batching
|
├── wip-http standard routes/codecs/envelopes
|
||||||
├── wip-host request-scoped publication and dispatch
|
├── wip-host request-scoped publication and dispatch
|
||||||
└── wip-interface macro-generated filesystem capabilities
|
└── wip-interface macro-generated filesystem capabilities
|
||||||
|
|
||||||
wip-public-api-example (workspace-only executable, integration tests, doctest)
|
wip-public-api-example (workspace-only executable, integration tests, doctest)
|
||||||
├── wip-protocol logical declarations, values, calls, and validation
|
├── wip-protocol logical declarations, values, calls, and validation
|
||||||
├── wip-https standard HTTPS v1 routes, JSON codecs, envelopes, and batching
|
├── wip-http standard HTTP v1 routes, JSON codecs, and envelopes
|
||||||
│ └── wip-protocol
|
│ └── wip-protocol
|
||||||
├── wip-client stateful Known Space, lazy tree, observation, and call runtime
|
├── wip-client stateful Known Space, lazy tree, observation, and call runtime
|
||||||
│ ├── wip-https
|
│ ├── wip-http
|
||||||
│ └── wip-protocol
|
│ └── wip-protocol
|
||||||
├── wip-interface application DTO codecs and interface authoring facade
|
├── wip-interface application DTO codecs and interface authoring facade
|
||||||
│ ├── wip-protocol
|
│ ├── wip-protocol
|
||||||
@@ -41,18 +41,18 @@ wip-public-api-example (workspace-only executable, integration tests, doctest)
|
|||||||
| Crate | Responsibility | Does not own |
|
| Crate | Responsibility | Does not own |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `wip-protocol` | Transport-independent descriptors, object/call/result types, logical `Value`s, validation, and stable protocol error categories. | Application DTOs, implementations, persistence, or wire encoding. |
|
| `wip-protocol` | Transport-independent descriptors, object/call/result types, logical `Value`s, validation, and stable protocol error categories. | Application DTOs, implementations, persistence, or wire encoding. |
|
||||||
| `wip-https` | Standard HTTPS v1 endpoint/route derivation, UTF-8 JSON codecs, direct success bodies, error/status classification, and retrieval batches. | HTTP I/O, TLS termination, authentication schemes, server frameworks, filesystem projection, or client presentation/cache policy. |
|
| `wip-http` | Standard WIP over HTTP v1 endpoint/route derivation, UTF-8 JSON codecs, direct success bodies, and error/status classification. | HTTP I/O, URL scheme or TLS policy, authentication schemes, server frameworks, filesystem projection, or client presentation/cache policy. |
|
||||||
| `wip-client` | Endpoint/security-context-isolated Known Space, normalized object and interface observations, intent-driven object and descriptor coverage with bounded request deduplication, immutable operation call contexts, stale transitions, and bounded histories. | HTTP I/O, credentials, persistent cache, automatic operation retries, or presentation widgets/events. |
|
| `wip-client` | Endpoint/security-context-isolated Known Space, normalized object and interface observations, intent-driven object and descriptor coverage with bounded request deduplication, immutable operation call contexts, stale transitions, and bounded histories. | HTTP I/O, credentials, persistent cache, automatic operation retries, or presentation widgets/events. |
|
||||||
| `wip-tui` | Keyboard-only interactive Worldspace tree, selected Entry and qualified operation panes, descriptor-driven argument editing, bounded result/diagnostic rendering, terminal lifecycle, and HTTPS I/O workers over `wip-client`. | Independent cache/validator semantics, automatic operation retries, Host internals, backend paths, or persistent state. |
|
| `wip-tui` | Keyboard-only interactive Worldspace tree, selected Entry and qualified operation panes, descriptor-driven argument editing, bounded result/diagnostic rendering, terminal lifecycle, and HTTP I/O workers over `wip-client`. | Independent cache/validator semantics, automatic operation retries, Host internals, backend paths, or persistent state. |
|
||||||
| `wip-interface` | The public `WipType`/`interface` authoring API, Rust-to-protocol codecs, generated descriptors, and typed implementation dispatch. | Object publication, backend lifetime, or transport policy. |
|
| `wip-interface` | The public `WipType`/`interface` authoring API, Rust-to-protocol codecs, generated descriptors, and typed implementation dispatch. | Object publication, backend lifetime, or transport policy. |
|
||||||
| `wip-interface-macros` | Procedural-macro expansion used by `wip-interface`. It is not an application dependency. | A supported direct user API. |
|
| `wip-interface-macros` | Procedural-macro expansion used by `wip-interface`. It is not an application dependency. | A supported direct user API. |
|
||||||
| `wip-host` | Opaque interface registration, explicit object membership, validator checks, interface-qualified dispatch against one host-owned instance, and descriptor-guided argument decoding inside that same resolution boundary. | Backend atomicity, global object lookup, or network serving. |
|
| `wip-host` | Opaque interface registration, explicit object membership, validator checks, interface-qualified dispatch against one host-owned instance, and descriptor-guided argument decoding inside that same resolution boundary. | Backend atomicity, global object lookup, or network serving. |
|
||||||
| `wip-fs-server` | Linux directory-handle-confined request-time projection, complete depth-bounded observations and bounded file operations, standard `wip-https` dispatch/batch handling, and a loopback HTTP binary for TLS-proxy or explicit development use. | A new wire profile, implicit symlink following, non-loopback cleartext, authentication policy, or filesystem-wide preregistration. |
|
| `wip-fs-server` | Linux directory-handle-confined request-time projection, complete depth-bounded observations and bounded file operations, standard `wip-http` dispatch, and a loopback HTTP binary. | A new wire profile, implicit symlink following, non-loopback cleartext, authentication policy, TLS termination, or filesystem-wide preregistration. |
|
||||||
| `wip-public-api-example` | An independently compiled consumer of the protocol, authoring, and host public crates. Its DTOs and traits are application-owned; its implementation and backend handle remain host-private. | Reusable library API or a production server. |
|
| `wip-public-api-example` | An independently compiled consumer of the protocol, authoring, and host public crates. Its DTOs and traits are application-owned; its implementation and backend handle remain host-private. | Reusable library API or a production server. |
|
||||||
|
|
||||||
The boundary is intentional: protocol types describe what can cross a
|
The boundary is intentional: protocol types describe what can cross a
|
||||||
transport; application DTOs opt into that model with `WipType`; a host-private
|
transport; application DTOs opt into that model with `WipType`; a host-private
|
||||||
implementation owns credentials, handles, and backend state; and `wip-https`
|
implementation owns credentials, handles, and backend state; and `wip-http`
|
||||||
maps standard routes/envelopes to `CallOperationRequest` and
|
maps standard routes/envelopes to `CallOperationRequest` and
|
||||||
`CallOperationResponse` without placing transport-specific types in descriptors
|
`CallOperationResponse` without placing transport-specific types in descriptors
|
||||||
or application traits.
|
or application traits.
|
||||||
@@ -263,8 +263,10 @@ from Worldspace `/`, lazily expands materialized tree nodes, displays current
|
|||||||
object/interface/operation metadata, validates all canonical descriptor types in
|
object/interface/operation metadata, validates all canonical descriptor types in
|
||||||
a field editor, and requires a separate confirmation action before every call.
|
a field editor, and requires a separate confirmation action before every call.
|
||||||
It uses the stateful `wip-client` runtime for request correlation, observed
|
It uses the stateful `wip-client` runtime for request correlation, observed
|
||||||
validators, stale transitions, and unknown outcomes. HTTPS is the default;
|
validators, stale transitions, and unknown outcomes. One canonical `http` or
|
||||||
loopback plain HTTP requires `--allow-http`. Full startup, TLS, key binding,
|
`https` endpoint is used unchanged for request construction, transport, and
|
||||||
|
cache partitioning. Scheme, TLS, certificates, authentication, and proxy policy
|
||||||
|
belong to the HTTP implementation and deployment. Full startup, key binding,
|
||||||
layout, validator, and filesystem-operation examples are in the
|
layout, validator, and filesystem-operation examples are in the
|
||||||
[package README](crates/wip-tui/README.md).
|
[package README](crates/wip-tui/README.md).
|
||||||
|
|
||||||
@@ -277,8 +279,9 @@ state, uses pinned directory-relative handles without following symlinks, omits
|
|||||||
non-UTF-8 backend names, returns complete recursive observations through the
|
non-UTF-8 backend names, returns complete recursive observations through the
|
||||||
requested depth or a resource-limit failure, and publishes validator-protected
|
requested depth or a resource-limit failure, and publishes validator-protected
|
||||||
replacement only in explicit read-write mode.
|
replacement only in explicit read-write mode.
|
||||||
The built-in cleartext listener is loopback-only: production HTTPS is explicitly
|
The built-in HTTP listener is loopback-only. Externally visible URL schemes,
|
||||||
delegated to a reverse proxy, while local plain HTTP requires an opt-in flag.
|
TLS termination, certificates, authentication, and proxy routing are deployment
|
||||||
|
concerns rather than separate WIP profiles.
|
||||||
|
|
||||||
## Validation
|
## Validation
|
||||||
|
|
||||||
|
|||||||
@@ -6,5 +6,5 @@ description = "Presentation-independent stateful WIP client runtime"
|
|||||||
license = "MIT OR Apache-2.0"
|
license = "MIT OR Apache-2.0"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
wip-https = { path = "../wip-https" }
|
wip-http = { path = "../wip-http" }
|
||||||
wip-protocol = { path = "../wip-protocol" }
|
wip-protocol = { path = "../wip-protocol" }
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
//! Presentation-independent stateful runtime for WIP clients.
|
//! Presentation-independent stateful runtime for WIP clients.
|
||||||
//!
|
//!
|
||||||
//! [`Client`] separates observations by canonical HTTPS endpoint and caller-
|
//! [`Client`] separates observations by canonical WIP over HTTP endpoint and caller-
|
||||||
//! supplied security context. It reconciles requested observation coverage without
|
//! supplied security context. It reconciles requested observation coverage without
|
||||||
//! duplicating fresh or loading work, creates requests with the standard
|
//! duplicating fresh or loading work, creates requests with the standard
|
||||||
//! [`wip_https`] adapter, correlates responses by [`RequestId`], and retains
|
//! [`wip_http`] adapter, correlates responses by [`RequestId`], and retains
|
||||||
//! bounded object, tree, interface, diagnostic, and operation state. The crate
|
//! bounded object, tree, interface, diagnostic, and operation state. The crate
|
||||||
//! contains no terminal, widget, or UI event types.
|
//! contains no terminal, widget, or UI event types.
|
||||||
|
|
||||||
@@ -13,8 +13,8 @@ use std::collections::{BTreeMap, VecDeque};
|
|||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use std::fmt::{self, Display, Formatter};
|
use std::fmt::{self, Display, Formatter};
|
||||||
|
|
||||||
use wip_https::http::{Request, Response};
|
use wip_http::http::{Request, Response};
|
||||||
use wip_https::{
|
use wip_http::{
|
||||||
ClientResponseError, DecodedResponse, Endpoint, Limits, decode_call_operation_response,
|
ClientResponseError, DecodedResponse, Endpoint, Limits, decode_call_operation_response,
|
||||||
decode_fetch_interface_response, decode_observe_response, encode_call_operation_request,
|
decode_fetch_interface_response, decode_observe_response, encode_call_operation_request,
|
||||||
encode_fetch_interface_request, encode_observe_request,
|
encode_fetch_interface_request, encode_observe_request,
|
||||||
@@ -364,7 +364,7 @@ pub struct Diagnostic {
|
|||||||
pub struct PreparedRequest {
|
pub struct PreparedRequest {
|
||||||
/// Identity required when completing or failing this request.
|
/// Identity required when completing or failing this request.
|
||||||
pub id: RequestId,
|
pub id: RequestId,
|
||||||
/// Standard WIP over HTTPS request.
|
/// Standard WIP over HTTP request.
|
||||||
pub request: Request<Vec<u8>>,
|
pub request: Request<Vec<u8>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1399,7 +1399,7 @@ impl Client {
|
|||||||
&mut self,
|
&mut self,
|
||||||
session: &SessionId,
|
session: &SessionId,
|
||||||
id: RequestId,
|
id: RequestId,
|
||||||
mismatch: Option<wip_https::StatusMismatch>,
|
mismatch: Option<wip_http::StatusMismatch>,
|
||||||
) -> Result<(), ClientError> {
|
) -> Result<(), ClientError> {
|
||||||
if let Some(mismatch) = mismatch {
|
if let Some(mismatch) = mismatch {
|
||||||
let maximum = self.limits.history;
|
let maximum = self.limits.history;
|
||||||
|
|||||||
@@ -4,8 +4,8 @@ use wip_client::{
|
|||||||
CallOutcome, Client, ClientErrorKind, ClientLimits, Completion, DiagnosticKind,
|
CallOutcome, Client, ClientErrorKind, ClientLimits, Completion, DiagnosticKind,
|
||||||
ObservationState, OutcomeUnknownReason, SecurityContext,
|
ObservationState, OutcomeUnknownReason, SecurityContext,
|
||||||
};
|
};
|
||||||
use wip_https::http::{Response, StatusCode};
|
use wip_http::http::{Response, StatusCode};
|
||||||
use wip_https::{
|
use wip_http::{
|
||||||
Limits, encode_fetch_interface_response, encode_observe_response,
|
Limits, encode_fetch_interface_response, encode_observe_response,
|
||||||
encode_protocol_error_response,
|
encode_protocol_error_response,
|
||||||
};
|
};
|
||||||
@@ -16,7 +16,7 @@ use wip_protocol::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
fn limits() -> Limits {
|
fn limits() -> Limits {
|
||||||
Limits::new(64 * 1024, 64 * 1024, 64, 64).unwrap()
|
Limits::new(64 * 1024, 64 * 1024, 64).unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn setup() -> (Client, wip_client::SessionId) {
|
fn setup() -> (Client, wip_client::SessionId) {
|
||||||
@@ -145,16 +145,37 @@ fn valid_error_envelope_is_authoritative_and_status_mismatch_is_diagnostic() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn non_success_without_valid_envelope_remains_transport_failure() {
|
fn resource_envelope_on_413_uses_code_and_records_canonical_422_mismatch() {
|
||||||
let (mut client, session) = setup();
|
let (mut client, session) = setup();
|
||||||
let request = client.refresh_observed(&session, "/item", 0).unwrap();
|
let request = client.refresh_observed(&session, "/item", 0).unwrap();
|
||||||
let error = client
|
let error = ProtocolError {
|
||||||
.complete(
|
code: ProtocolErrorCode::ResourceLimitExceeded,
|
||||||
request.id,
|
message: "logical observation limit exceeded".into(),
|
||||||
response(StatusCode::BAD_GATEWAY, b"gateway html"),
|
};
|
||||||
)
|
let mut encoded =
|
||||||
.unwrap_err();
|
encode_protocol_error_response(ProtocolInteraction::Observe, &error, limits()).unwrap();
|
||||||
assert_eq!(error.kind, ClientErrorKind::Transport);
|
*encoded.status_mut() = StatusCode::PAYLOAD_TOO_LARGE;
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
client.complete(request.id, encoded).unwrap(),
|
||||||
|
Completion::ProtocolFailure(error)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
client.diagnostics(&session).unwrap().back().unwrap().kind,
|
||||||
|
DiagnosticKind::HttpStatusMismatch
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn non_success_without_valid_envelope_remains_transport_failure() {
|
||||||
|
for status in [StatusCode::BAD_GATEWAY, StatusCode::PAYLOAD_TOO_LARGE] {
|
||||||
|
let (mut client, session) = setup();
|
||||||
|
let request = client.refresh_observed(&session, "/item", 0).unwrap();
|
||||||
|
let error = client
|
||||||
|
.complete(request.id, response(status, b"infrastructure failure"))
|
||||||
|
.unwrap_err();
|
||||||
|
assert_eq!(error.kind, ClientErrorKind::Transport);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -250,3 +271,80 @@ fn malformed_call_success_after_dispatch_is_outcome_unknown_and_stales_object()
|
|||||||
);
|
);
|
||||||
assert_eq!(client.in_flight_len(), 0);
|
assert_eq!(client.in_flight_len(), 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn plain_413_after_call_dispatch_is_unknown_transport_outcome() {
|
||||||
|
let (mut client, session) = setup();
|
||||||
|
let observation = client.refresh_observed(&session, "/item", 0).unwrap();
|
||||||
|
client
|
||||||
|
.complete(
|
||||||
|
observation.id,
|
||||||
|
encode_observe_response(
|
||||||
|
&ObserveRequest {
|
||||||
|
path: "/item".into(),
|
||||||
|
depth: 0,
|
||||||
|
},
|
||||||
|
&ObjectObservation {
|
||||||
|
object: object(),
|
||||||
|
children: None,
|
||||||
|
},
|
||||||
|
limits(),
|
||||||
|
)
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let interface = client.prepare_interface(&session, "math").unwrap();
|
||||||
|
client
|
||||||
|
.complete(
|
||||||
|
interface.id,
|
||||||
|
encode_fetch_interface_response(
|
||||||
|
&FetchInterfaceRequest {
|
||||||
|
interface: "math".into(),
|
||||||
|
},
|
||||||
|
&FetchInterfaceResponse {
|
||||||
|
interface: "math".into(),
|
||||||
|
descriptor: descriptor(INTERFACE_FORMAT_V1),
|
||||||
|
validator: None,
|
||||||
|
},
|
||||||
|
limits(),
|
||||||
|
)
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let call = client
|
||||||
|
.prepare_call(
|
||||||
|
&session,
|
||||||
|
"/item",
|
||||||
|
"math",
|
||||||
|
"calculate",
|
||||||
|
BTreeMap::from([("value".into(), Value::Integer(2))]),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
client.mark_dispatched(call.id).unwrap();
|
||||||
|
|
||||||
|
let completion = client
|
||||||
|
.complete(
|
||||||
|
call.id,
|
||||||
|
Response::builder()
|
||||||
|
.status(StatusCode::PAYLOAD_TOO_LARGE)
|
||||||
|
.body(Vec::<u8>::new())
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
completion,
|
||||||
|
Completion::Call(record)
|
||||||
|
if matches!(
|
||||||
|
&record.outcome,
|
||||||
|
CallOutcome::Unknown {
|
||||||
|
reason: OutcomeUnknownReason::ResponseDecode,
|
||||||
|
failure: Some(failure),
|
||||||
|
} if failure.kind == ClientErrorKind::Transport
|
||||||
|
)
|
||||||
|
));
|
||||||
|
assert_eq!(
|
||||||
|
client.object(&session, "/item").unwrap().state,
|
||||||
|
ObservationState::Stale
|
||||||
|
);
|
||||||
|
assert_eq!(client.in_flight_len(), 0);
|
||||||
|
}
|
||||||
|
|||||||
@@ -4,8 +4,8 @@ use wip_client::{
|
|||||||
CallOutcome, Client, ClientErrorKind, ClientLimits, Completion, DispatchedTransportFailure,
|
CallOutcome, Client, ClientErrorKind, ClientLimits, Completion, DispatchedTransportFailure,
|
||||||
ObservationState, OutcomeUnknownReason, SecurityContext,
|
ObservationState, OutcomeUnknownReason, SecurityContext,
|
||||||
};
|
};
|
||||||
use wip_https::http::Response;
|
use wip_http::http::Response;
|
||||||
use wip_https::{
|
use wip_http::{
|
||||||
EncodeHttpError, Limits, encode_call_operation_response, encode_fetch_interface_response,
|
EncodeHttpError, Limits, encode_call_operation_response, encode_fetch_interface_response,
|
||||||
encode_observe_response, encode_protocol_error_response,
|
encode_observe_response, encode_protocol_error_response,
|
||||||
};
|
};
|
||||||
@@ -17,7 +17,7 @@ use wip_protocol::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
fn wire_limits() -> Limits {
|
fn wire_limits() -> Limits {
|
||||||
Limits::new(64 * 1024, 64 * 1024, 64, 64).unwrap()
|
Limits::new(64 * 1024, 64 * 1024, 64).unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
@@ -399,6 +399,67 @@ fn ensure_interface_waits_for_request_and_cache_capacity_without_evicting() {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn independent_retrievals_run_concurrently_and_complete_out_of_order() {
|
||||||
|
let mut client = client(8, 8, 8, 8);
|
||||||
|
let session = client
|
||||||
|
.open_session("https://example.test/wip", SecurityContext::new("subject"))
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let first = client.refresh_observed(&session, "/one", 0).unwrap();
|
||||||
|
let second = client.refresh_observed(&session, "/two", 0).unwrap();
|
||||||
|
let interface = client.prepare_interface(&session, "math").unwrap();
|
||||||
|
|
||||||
|
assert_eq!(first.request.uri().path(), "/wip/v1/observe");
|
||||||
|
assert_eq!(second.request.uri().path(), "/wip/v1/observe");
|
||||||
|
assert_eq!(interface.request.uri().path(), "/wip/v1/fetch_interface");
|
||||||
|
assert_eq!(client.in_flight_len(), 3);
|
||||||
|
|
||||||
|
client
|
||||||
|
.complete(
|
||||||
|
second.id,
|
||||||
|
observation_response("/two", &object("two", None, b"two")),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
client
|
||||||
|
.complete(
|
||||||
|
interface.id,
|
||||||
|
encode_fetch_interface_response(
|
||||||
|
&FetchInterfaceRequest {
|
||||||
|
interface: "math".into(),
|
||||||
|
},
|
||||||
|
&FetchInterfaceResponse {
|
||||||
|
interface: "math".into(),
|
||||||
|
descriptor: descriptor(TypeExpr::Integer),
|
||||||
|
validator: Some(b"math-v1".to_vec()),
|
||||||
|
},
|
||||||
|
wire_limits(),
|
||||||
|
)
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
client
|
||||||
|
.complete(
|
||||||
|
first.id,
|
||||||
|
observation_response("/one", &object("one", None, b"one")),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
client.object(&session, "/one").unwrap().state,
|
||||||
|
ObservationState::Fresh
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
client.object(&session, "/two").unwrap().state,
|
||||||
|
ObservationState::Fresh
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
client.interface(&session, "math").unwrap().state,
|
||||||
|
ObservationState::Fresh
|
||||||
|
);
|
||||||
|
assert_eq!(client.in_flight_len(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn newer_refresh_rejects_out_of_order_response_for_the_same_subject() {
|
fn newer_refresh_rejects_out_of_order_response_for_the_same_subject() {
|
||||||
let mut client = client(8, 8, 8, 8);
|
let mut client = client(8, 8, 8, 8);
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
name = "wip-fs-server"
|
name = "wip-fs-server"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
description = "Request-time filesystem projection server for WIP over HTTPS"
|
description = "Request-time filesystem projection server for WIP over HTTP"
|
||||||
license = "MIT OR Apache-2.0"
|
license = "MIT OR Apache-2.0"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
publish = false
|
publish = false
|
||||||
@@ -11,7 +11,7 @@ publish = false
|
|||||||
http = "1"
|
http = "1"
|
||||||
rustix = { version = "1.1", features = ["fs"] }
|
rustix = { version = "1.1", features = ["fs"] }
|
||||||
wip-host = { path = "../wip-host" }
|
wip-host = { path = "../wip-host" }
|
||||||
wip-https = { path = "../wip-https" }
|
wip-http = { path = "../wip-http" }
|
||||||
wip-interface = { path = "../wip-interface" }
|
wip-interface = { path = "../wip-interface" }
|
||||||
wip-protocol = { path = "../wip-protocol" }
|
wip-protocol = { path = "../wip-protocol" }
|
||||||
|
|
||||||
|
|||||||
@@ -3,8 +3,8 @@
|
|||||||
`wip-fs-server` projects one configured Linux filesystem directory onto WIP
|
`wip-fs-server` projects one configured Linux filesystem directory onto WIP
|
||||||
Worldspace `/` at request time. It does not register the filesystem contents or
|
Worldspace `/` at request time. It does not register the filesystem contents or
|
||||||
keep one object instance per entry. It uses `wip-host` for publication and typed
|
keep one object instance per entry. It uses `wip-host` for publication and typed
|
||||||
operation dispatch and uses the standard `wip-https` routes, JSON codecs,
|
operation dispatch and uses the standard `wip-http` routes, JSON codecs,
|
||||||
envelopes, batching, and HTTP status mapping.
|
envelopes, and HTTP status mapping.
|
||||||
|
|
||||||
## Security model
|
## Security model
|
||||||
|
|
||||||
@@ -28,9 +28,9 @@ envelopes, batching, and HTTP status mapping.
|
|||||||
- Protocol metadata and errors never contain the backend absolute path. Startup
|
- Protocol metadata and errors never contain the backend absolute path. Startup
|
||||||
prints only the explicitly configured effective root and security-sensitive
|
prints only the explicitly configured effective root and security-sensitive
|
||||||
modes.
|
modes.
|
||||||
- The built-in listener is cleartext and loopback-only. Production deployments
|
- The built-in HTTP listener is loopback-only. TLS termination, certificates,
|
||||||
must pass `--behind-tls-proxy` and terminate HTTPS at a trusted reverse proxy.
|
authentication, an externally visible URL scheme, and proxy routing are
|
||||||
Plain development HTTP requires the explicit `--development-http` flag.
|
deployment concerns rather than separate WIP transport profiles.
|
||||||
|
|
||||||
The implementation currently targets Linux because it uses `O_PATH`,
|
The implementation currently targets Linux because it uses `O_PATH`,
|
||||||
directory-relative descriptor traversal, and `/proc/self/fd` to reopen the same
|
directory-relative descriptor traversal, and `/proc/self/fd` to reopen the same
|
||||||
@@ -38,34 +38,32 @@ pinned backend object without resolving the untrusted Worldspace path twice.
|
|||||||
|
|
||||||
## Run
|
## Run
|
||||||
|
|
||||||
Read-only behind a TLS-terminating reverse proxy:
|
Run the loopback listener in read-only mode:
|
||||||
|
|
||||||
```console
|
```console
|
||||||
cargo run -p wip-fs-server -- \
|
cargo run -p wip-fs-server -- \
|
||||||
--root /srv/public-files \
|
--root /srv/public-files \
|
||||||
--listen 127.0.0.1:8443 \
|
--listen 127.0.0.1:8080 \
|
||||||
--base-path /wip \
|
--base-path /wip
|
||||||
--behind-tls-proxy
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Local development with the write capability deliberately enabled:
|
Run with the write capability deliberately enabled:
|
||||||
|
|
||||||
```console
|
```console
|
||||||
cargo run -p wip-fs-server -- \
|
cargo run -p wip-fs-server -- \
|
||||||
--root ./example-files \
|
--root ./example-files \
|
||||||
--listen 127.0.0.1:8080 \
|
--listen 127.0.0.1:8080 \
|
||||||
--base-path /wip \
|
--base-path /wip \
|
||||||
--development-http \
|
|
||||||
--read-write
|
--read-write
|
||||||
```
|
```
|
||||||
|
|
||||||
The server reports the effective root, `ReadOnly`/`ReadWrite` mode, transport
|
The server reports the effective root, `ReadOnly`/`ReadWrite` mode, endpoint,
|
||||||
mode, endpoint, and actual listen address. It does not enumerate the root.
|
and actual listen address. It does not enumerate the root.
|
||||||
|
|
||||||
## Standard interactions
|
## Standard interactions
|
||||||
|
|
||||||
The following examples use development HTTP for readability. The JSON is the
|
The following examples use the built-in HTTP listener. The JSON follows the
|
||||||
standard `wip-https` profile; validators and operation `Bytes` are base64 body
|
standard WIP over HTTP binding; validators and operation `Bytes` are base64 body
|
||||||
fields, never `ETag` or `If-Match` headers.
|
fields, never `ETag` or `If-Match` headers.
|
||||||
|
|
||||||
Observe only the root Object:
|
Observe only the root Object:
|
||||||
@@ -120,14 +118,11 @@ curl -sS -X POST http://127.0.0.1:8080/wip/v1/call_operation \
|
|||||||
}'
|
}'
|
||||||
```
|
```
|
||||||
|
|
||||||
`observe` and `fetch_interface` can also be combined through the standard
|
|
||||||
`POST /wip/v1/batch` route. `call_operation` is never batchable.
|
|
||||||
|
|
||||||
## Resource and failure behavior
|
## Resource and failure behavior
|
||||||
|
|
||||||
`ResourceLimits` bounds request/response bytes, HTTP request-head bytes, JSON
|
`ResourceLimits` bounds request/response bytes, HTTP request-head bytes, JSON
|
||||||
nesting, batch items, file read/write bytes, tree depth/node count, pinned handles,
|
nesting, file read/write bytes, tree depth/node count, pinned handles, and active
|
||||||
and active connections/requests. One absolute request deadline covers header and
|
connections/requests. One absolute request deadline covers header and
|
||||||
body intake, dispatch, cooperative filesystem work, and response transmission;
|
body intake, dispatch, cooperative filesystem work, and response transmission;
|
||||||
stalled clients are closed and cannot occupy a worker beyond that bound. Workers
|
stalled clients are closed and cannot occupy a worker beyond that bound. Workers
|
||||||
accept connections directly, so the listener never moves more than the configured
|
accept connections directly, so the listener never moves more than the configured
|
||||||
|
|||||||
@@ -1,15 +1,15 @@
|
|||||||
//! Request-time filesystem projection served through the standard WIP HTTPS binding.
|
//! Request-time filesystem projection served through the standard WIP over HTTP binding.
|
||||||
//!
|
//!
|
||||||
//! This crate deliberately keeps the boundaries visible:
|
//! This crate deliberately keeps the boundaries visible:
|
||||||
//!
|
//!
|
||||||
//! - [`wip_protocol`] owns logical requests and responses;
|
//! - [`wip_protocol`] owns logical requests and responses;
|
||||||
//! - [`wip_host`] owns object publication, validators, and typed dispatch;
|
//! - [`wip_host`] owns object publication, validators, and typed dispatch;
|
||||||
//! - [`wip_https`] owns routes, JSON, envelopes, batching, and status mapping;
|
//! - [`wip_http`] owns routes, JSON, envelopes, and status mapping;
|
||||||
//! - this crate owns the filesystem capability boundary and the real HTTP listener.
|
//! - this crate owns the filesystem capability boundary and the real HTTP listener.
|
||||||
//!
|
//!
|
||||||
//! TLS is terminated by an explicitly configured reverse proxy. The built-in
|
//! The built-in HTTP listener is intentionally loopback-only. TLS termination,
|
||||||
//! listener accepts cleartext only on loopback, either behind that proxy or when
|
//! certificates, authentication, and externally visible schemes are independent
|
||||||
//! [`TransportSecurity::DevelopmentHttp`] is deliberately selected.
|
//! deployment concerns rather than WIP transport profiles.
|
||||||
|
|
||||||
#![deny(missing_docs)]
|
#![deny(missing_docs)]
|
||||||
|
|
||||||
@@ -33,20 +33,11 @@ pub enum AccessMode {
|
|||||||
ReadWrite,
|
ReadWrite,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// How HTTPS is provided for the endpoint.
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub enum TransportSecurity {
|
|
||||||
/// A trusted reverse proxy terminates TLS and forwards to the loopback listener.
|
|
||||||
ReverseProxyTls,
|
|
||||||
/// Cleartext HTTP is deliberately enabled for local development only.
|
|
||||||
DevelopmentHttp,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Bounded resource policy applied by the HTTP adapter and filesystem provider.
|
/// Bounded resource policy applied by the HTTP adapter and filesystem provider.
|
||||||
#[derive(Debug, Clone, Copy)]
|
#[derive(Debug, Clone, Copy)]
|
||||||
pub struct ResourceLimits {
|
pub struct ResourceLimits {
|
||||||
/// Standard JSON, body-size, nesting, and batch limits.
|
/// Standard JSON, body-size, and nesting limits.
|
||||||
pub wire: wip_https::Limits,
|
pub wire: wip_http::Limits,
|
||||||
/// Maximum bytes returned by one file read.
|
/// Maximum bytes returned by one file read.
|
||||||
pub max_file_read_bytes: usize,
|
pub max_file_read_bytes: usize,
|
||||||
/// Maximum bytes accepted by one file replacement.
|
/// Maximum bytes accepted by one file replacement.
|
||||||
@@ -68,7 +59,7 @@ pub struct ResourceLimits {
|
|||||||
impl Default for ResourceLimits {
|
impl Default for ResourceLimits {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
wire: wip_https::Limits::new(256 * 1024, 2 * 1024 * 1024, 64, 64)
|
wire: wip_http::Limits::new(256 * 1024, 2 * 1024 * 1024, 64)
|
||||||
.expect("default wire limits are nonzero"),
|
.expect("default wire limits are nonzero"),
|
||||||
max_file_read_bytes: 1024 * 1024,
|
max_file_read_bytes: 1024 * 1024,
|
||||||
max_file_write_bytes: 1024 * 1024,
|
max_file_write_bytes: 1024 * 1024,
|
||||||
@@ -93,8 +84,6 @@ pub struct ServerConfig {
|
|||||||
pub endpoint_base_path: String,
|
pub endpoint_base_path: String,
|
||||||
/// Read-only or explicit read-write publication mode.
|
/// Read-only or explicit read-write publication mode.
|
||||||
pub access: AccessMode,
|
pub access: AccessMode,
|
||||||
/// TLS termination or explicit development HTTP policy.
|
|
||||||
pub transport_security: TransportSecurity,
|
|
||||||
/// Request, operation, traversal, and concurrency bounds.
|
/// Request, operation, traversal, and concurrency bounds.
|
||||||
pub limits: ResourceLimits,
|
pub limits: ResourceLimits,
|
||||||
}
|
}
|
||||||
@@ -102,8 +91,7 @@ pub struct ServerConfig {
|
|||||||
impl ServerConfig {
|
impl ServerConfig {
|
||||||
/// Builds a secure-by-default configuration for `root`.
|
/// Builds a secure-by-default configuration for `root`.
|
||||||
///
|
///
|
||||||
/// The listener defaults to an ephemeral loopback port, read-only access,
|
/// The listener defaults to an ephemeral loopback port and read-only access.
|
||||||
/// and TLS termination delegated to a reverse proxy.
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn for_root(root: impl Into<PathBuf>) -> Self {
|
pub fn for_root(root: impl Into<PathBuf>) -> Self {
|
||||||
Self {
|
Self {
|
||||||
@@ -111,7 +99,6 @@ impl ServerConfig {
|
|||||||
listen: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
|
listen: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
|
||||||
endpoint_base_path: "/wip".into(),
|
endpoint_base_path: "/wip".into(),
|
||||||
access: AccessMode::ReadOnly,
|
access: AccessMode::ReadOnly,
|
||||||
transport_security: TransportSecurity::ReverseProxyTls,
|
|
||||||
limits: ResourceLimits::default(),
|
limits: ResourceLimits::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -142,9 +129,9 @@ impl ServerConfig {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn endpoint(&self) -> Result<wip_https::Endpoint, ConfigError> {
|
pub(crate) fn endpoint(&self) -> Result<wip_http::Endpoint, ConfigError> {
|
||||||
let endpoint = format!("https://localhost{}", self.endpoint_base_path);
|
let endpoint = format!("http://localhost{}", self.endpoint_base_path);
|
||||||
wip_https::Endpoint::parse(&endpoint).map_err(|_| ConfigError::InvalidBasePath)
|
wip_http::Endpoint::parse(&endpoint).map_err(|_| ConfigError::InvalidBasePath)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,14 +2,13 @@ use std::error::Error;
|
|||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
use wip_fs_server::{AccessMode, ServerConfig, TransportSecurity, WipFsServer};
|
use wip_fs_server::{AccessMode, ServerConfig, WipFsServer};
|
||||||
|
|
||||||
fn main() -> Result<(), Box<dyn Error>> {
|
fn main() -> Result<(), Box<dyn Error>> {
|
||||||
let mut root: Option<PathBuf> = None;
|
let mut root: Option<PathBuf> = None;
|
||||||
let mut listen: SocketAddr = "127.0.0.1:8443".parse()?;
|
let mut listen: SocketAddr = "127.0.0.1:8080".parse()?;
|
||||||
let mut base_path = "/wip".to_owned();
|
let mut base_path = "/wip".to_owned();
|
||||||
let mut access = AccessMode::ReadOnly;
|
let mut access = AccessMode::ReadOnly;
|
||||||
let mut security = None;
|
|
||||||
let mut arguments = std::env::args().skip(1);
|
let mut arguments = std::env::args().skip(1);
|
||||||
while let Some(argument) = arguments.next() {
|
while let Some(argument) = arguments.next() {
|
||||||
match argument.as_str() {
|
match argument.as_str() {
|
||||||
@@ -17,12 +16,6 @@ fn main() -> Result<(), Box<dyn Error>> {
|
|||||||
"--listen" => listen = required_value(&mut arguments, "--listen")?.parse()?,
|
"--listen" => listen = required_value(&mut arguments, "--listen")?.parse()?,
|
||||||
"--base-path" => base_path = required_value(&mut arguments, "--base-path")?,
|
"--base-path" => base_path = required_value(&mut arguments, "--base-path")?,
|
||||||
"--read-write" => access = AccessMode::ReadWrite,
|
"--read-write" => access = AccessMode::ReadWrite,
|
||||||
"--development-http" => {
|
|
||||||
set_security(&mut security, TransportSecurity::DevelopmentHttp)?
|
|
||||||
}
|
|
||||||
"--behind-tls-proxy" => {
|
|
||||||
set_security(&mut security, TransportSecurity::ReverseProxyTls)?
|
|
||||||
}
|
|
||||||
"--help" | "-h" => {
|
"--help" | "-h" => {
|
||||||
print_help();
|
print_help();
|
||||||
return Ok(());
|
return Ok(());
|
||||||
@@ -32,20 +25,17 @@ fn main() -> Result<(), Box<dyn Error>> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let root = root.ok_or("--root is required")?;
|
let root = root.ok_or("--root is required")?;
|
||||||
let transport_security =
|
|
||||||
security.ok_or("select exactly one of --behind-tls-proxy or --development-http")?;
|
|
||||||
let mut config = ServerConfig::for_root(root);
|
let mut config = ServerConfig::for_root(root);
|
||||||
config.listen = listen;
|
config.listen = listen;
|
||||||
config.endpoint_base_path = base_path;
|
config.endpoint_base_path = base_path;
|
||||||
config.access = access;
|
config.access = access;
|
||||||
config.transport_security = transport_security;
|
|
||||||
|
|
||||||
let server = WipFsServer::new(config)?;
|
let server = WipFsServer::new(config)?;
|
||||||
let effective_root = server.effective_root().to_owned();
|
let effective_root = server.effective_root().to_owned();
|
||||||
let endpoint = server.endpoint().clone();
|
let endpoint = server.endpoint().clone();
|
||||||
let bound = server.bind()?;
|
let bound = server.bind()?;
|
||||||
eprintln!(
|
eprintln!(
|
||||||
"wip-fs-server root={} access={access:?} transport={transport_security:?} endpoint={} listen={}",
|
"wip-fs-server root={} access={access:?} endpoint={} listen={}",
|
||||||
effective_root.display(),
|
effective_root.display(),
|
||||||
endpoint,
|
endpoint,
|
||||||
bound.local_addr()
|
bound.local_addr()
|
||||||
@@ -63,21 +53,10 @@ fn required_value(
|
|||||||
.ok_or_else(|| format!("{option} requires a value").into())
|
.ok_or_else(|| format!("{option} requires a value").into())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_security(
|
|
||||||
security: &mut Option<TransportSecurity>,
|
|
||||||
value: TransportSecurity,
|
|
||||||
) -> Result<(), Box<dyn Error>> {
|
|
||||||
if security.replace(value).is_some() {
|
|
||||||
Err("select only one transport-security mode".into())
|
|
||||||
} else {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn print_help() {
|
fn print_help() {
|
||||||
println!(
|
println!(
|
||||||
"Usage: wip-fs-server --root PATH [--listen 127.0.0.1:8443] \\\n [--base-path /wip] [--read-write] \\\n (--behind-tls-proxy | --development-http)\n\n\
|
"Usage: wip-fs-server --root PATH [--listen 127.0.0.1:8080] \\\n [--base-path /wip] [--read-write]\n\n\
|
||||||
The built-in listener is cleartext and loopback-only. In production, \
|
The built-in HTTP listener is loopback-only. TLS termination, authentication, \
|
||||||
select --behind-tls-proxy and terminate HTTPS at a trusted reverse proxy."
|
and external routing are deployment concerns."
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,15 +5,14 @@ use std::sync::atomic::{AtomicBool, Ordering};
|
|||||||
use std::thread;
|
use std::thread;
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use http::header::ALLOW;
|
||||||
use http::{Request, Response, StatusCode};
|
use http::{Request, Response, StatusCode};
|
||||||
use wip_host::{ExecutionContext, ObjectProvider};
|
use wip_host::{ExecutionContext, ObjectProvider};
|
||||||
use wip_https::{
|
use wip_http::{
|
||||||
BatchRequestKind, BatchResponse, BatchResponseItem, BatchSuccess, CodecError, EncodeHttpError,
|
CodecError, EncodeHttpError, Endpoint, RequestMetadataError, Route,
|
||||||
Endpoint, RequestMetadataError, ResourceLimitKind, Route, decode_batch_request,
|
|
||||||
decode_call_operation_metadata, decode_fetch_interface_request, decode_observe_request,
|
decode_call_operation_metadata, decode_fetch_interface_request, decode_observe_request,
|
||||||
encode_batch_error_response, encode_batch_resource_limit_error_response, encode_batch_response,
|
|
||||||
encode_call_operation_response, encode_fetch_interface_response, encode_observe_response,
|
encode_call_operation_response, encode_fetch_interface_response, encode_observe_response,
|
||||||
encode_protocol_error_response, encode_resource_limit_error_response, validate_http_request,
|
encode_protocol_error_response, validate_http_request,
|
||||||
};
|
};
|
||||||
use wip_protocol::{ProtocolError, ProtocolErrorCode, ProtocolInteraction};
|
use wip_protocol::{ProtocolError, ProtocolErrorCode, ProtocolInteraction};
|
||||||
|
|
||||||
@@ -55,7 +54,7 @@ impl WipFsServer {
|
|||||||
&self.endpoint
|
&self.endpoint
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handles one already-buffered HTTP request with the standard `wip-https` codecs.
|
/// Handles one already-buffered HTTP request with the standard `wip-http` codecs.
|
||||||
///
|
///
|
||||||
/// Listener integrations must enforce the same body limit while collecting bytes.
|
/// Listener integrations must enforce the same body limit while collecting bytes.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
@@ -68,27 +67,32 @@ impl WipFsServer {
|
|||||||
request: Request<Vec<u8>>,
|
request: Request<Vec<u8>>,
|
||||||
deadline: Instant,
|
deadline: Instant,
|
||||||
) -> Response<Vec<u8>> {
|
) -> Response<Vec<u8>> {
|
||||||
let Some(route) = self.route(request.uri().path()) else {
|
let Some(route) = self.route(request.uri()) else {
|
||||||
return empty_response(StatusCode::NOT_FOUND);
|
return empty_response(StatusCode::NOT_FOUND);
|
||||||
};
|
};
|
||||||
if let Err(error) = validate_http_request(&self.endpoint, route, &request) {
|
if let Err(error) = validate_http_request(&self.endpoint, route, &request) {
|
||||||
return self.metadata_error(route, error);
|
return self.metadata_error(error);
|
||||||
}
|
}
|
||||||
let context = ExecutionContext::new()
|
let context = ExecutionContext::new()
|
||||||
.with_deadline(deadline)
|
.with_deadline(deadline)
|
||||||
.with_resource_budget(u64::from(self.config.limits.max_observation_nodes));
|
.with_resource_budget(u64::from(self.config.limits.max_observation_nodes));
|
||||||
match route {
|
let response = match route {
|
||||||
Route::Observe => self.observe(request.body(), &context),
|
Route::Observe => self.observe(request.body(), &context),
|
||||||
Route::FetchInterface => self.fetch_interface(request.body()),
|
Route::FetchInterface => self.fetch_interface(request.body()),
|
||||||
Route::CallOperation => self.call_operation(request.body(), &context),
|
Route::CallOperation => self.call_operation(request.body(), &context),
|
||||||
Route::Batch => self.batch(request.body(), &context),
|
};
|
||||||
|
if Instant::now() >= deadline {
|
||||||
|
empty_response(StatusCode::GATEWAY_TIMEOUT)
|
||||||
|
} else {
|
||||||
|
response
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Binds the built-in bounded loopback HTTP listener.
|
/// Binds the built-in bounded loopback HTTP listener.
|
||||||
///
|
///
|
||||||
/// The listener is cleartext by design. Configuration must explicitly state
|
/// The built-in listener is cleartext and loopback-only. Externally visible
|
||||||
/// whether TLS is terminated by a reverse proxy or development HTTP is in use.
|
/// schemes, TLS termination, authentication, and proxy routing are deployment
|
||||||
|
/// concerns rather than WIP transport profiles.
|
||||||
pub fn bind(self) -> Result<BoundServer, ServerBuildError> {
|
pub fn bind(self) -> Result<BoundServer, ServerBuildError> {
|
||||||
let listener = TcpListener::bind(self.config.listen)
|
let listener = TcpListener::bind(self.config.listen)
|
||||||
.map_err(|error| ServerBuildError::Listener(error.to_string()))?;
|
.map_err(|error| ServerBuildError::Listener(error.to_string()))?;
|
||||||
@@ -105,15 +109,13 @@ impl WipFsServer {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn route(&self, path: &str) -> Option<Route> {
|
fn route(&self, uri: &http::Uri) -> Option<Route> {
|
||||||
[
|
if uri.query().is_some() {
|
||||||
Route::Observe,
|
return None;
|
||||||
Route::FetchInterface,
|
}
|
||||||
Route::CallOperation,
|
[Route::Observe, Route::FetchInterface, Route::CallOperation]
|
||||||
Route::Batch,
|
.into_iter()
|
||||||
]
|
.find(|route| self.endpoint.route(*route).path() == uri.path())
|
||||||
.into_iter()
|
|
||||||
.find(|route| self.endpoint.route(*route).path() == path)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn observe(&self, body: &[u8], context: &ExecutionContext) -> Response<Vec<u8>> {
|
fn observe(&self, body: &[u8], context: &ExecutionContext) -> Response<Vec<u8>> {
|
||||||
@@ -126,7 +128,7 @@ impl WipFsServer {
|
|||||||
.unwrap_or_else(|error| {
|
.unwrap_or_else(|error| {
|
||||||
self.read_encode_error(ProtocolInteraction::Observe, error)
|
self.read_encode_error(ProtocolInteraction::Observe, error)
|
||||||
}),
|
}),
|
||||||
Err(error) => self.protocol_error(ProtocolInteraction::Observe, &error, None),
|
Err(error) => self.protocol_error(ProtocolInteraction::Observe, &error),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -142,7 +144,7 @@ impl WipFsServer {
|
|||||||
self.read_encode_error(ProtocolInteraction::FetchInterface, error)
|
self.read_encode_error(ProtocolInteraction::FetchInterface, error)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
Err(error) => self.protocol_error(ProtocolInteraction::FetchInterface, &error, None),
|
Err(error) => self.protocol_error(ProtocolInteraction::FetchInterface, &error),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -180,7 +182,7 @@ impl WipFsServer {
|
|||||||
},
|
},
|
||||||
message: "operation completed without response metadata".into(),
|
message: "operation completed without response metadata".into(),
|
||||||
};
|
};
|
||||||
return self.protocol_error(ProtocolInteraction::CallOperation, &error, None);
|
return self.protocol_error(ProtocolInteraction::CallOperation, &error);
|
||||||
};
|
};
|
||||||
encode_call_operation_response(
|
encode_call_operation_response(
|
||||||
&request,
|
&request,
|
||||||
@@ -189,6 +191,12 @@ impl WipFsServer {
|
|||||||
self.config.limits.wire,
|
self.config.limits.wire,
|
||||||
)
|
)
|
||||||
.unwrap_or_else(|encode_error| {
|
.unwrap_or_else(|encode_error| {
|
||||||
|
if matches!(
|
||||||
|
&encode_error,
|
||||||
|
EncodeHttpError::Codec(codec) if is_transport_limit(codec)
|
||||||
|
) {
|
||||||
|
return empty_response(StatusCode::INTERNAL_SERVER_ERROR);
|
||||||
|
}
|
||||||
if !may_commit {
|
if !may_commit {
|
||||||
return self
|
return self
|
||||||
.read_encode_error(ProtocolInteraction::CallOperation, encode_error);
|
.read_encode_error(ProtocolInteraction::CallOperation, encode_error);
|
||||||
@@ -199,58 +207,26 @@ impl WipFsServer {
|
|||||||
code: ProtocolErrorCode::OperationOutcomeUnknown,
|
code: ProtocolErrorCode::OperationOutcomeUnknown,
|
||||||
message: "operation completed but its response could not be encoded".into(),
|
message: "operation completed but its response could not be encoded".into(),
|
||||||
};
|
};
|
||||||
self.protocol_error(ProtocolInteraction::CallOperation, &error, None)
|
self.protocol_error(ProtocolInteraction::CallOperation, &error)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
Err(error) => self.protocol_error(ProtocolInteraction::CallOperation, &error, None),
|
Err(error) => self.protocol_error(ProtocolInteraction::CallOperation, &error),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn batch(&self, body: &[u8], context: &ExecutionContext) -> Response<Vec<u8>> {
|
fn metadata_error(&self, error: RequestMetadataError) -> Response<Vec<u8>> {
|
||||||
let request = match decode_batch_request(body, self.config.limits.wire) {
|
|
||||||
Ok(request) => request,
|
|
||||||
Err(error) => return self.batch_codec_error(error),
|
|
||||||
};
|
|
||||||
let responses = request
|
|
||||||
.requests
|
|
||||||
.iter()
|
|
||||||
.map(|item| {
|
|
||||||
let outcome = match &item.request {
|
|
||||||
BatchRequestKind::Observe(request) => self
|
|
||||||
.projection
|
|
||||||
.observe(context, request)
|
|
||||||
.map(BatchSuccess::Observe),
|
|
||||||
BatchRequestKind::FetchInterface(request) => self
|
|
||||||
.projection
|
|
||||||
.fetch_interface(request)
|
|
||||||
.map(BatchSuccess::FetchInterface),
|
|
||||||
BatchRequestKind::Invalid { error, .. } => Err(error.clone()),
|
|
||||||
};
|
|
||||||
BatchResponseItem {
|
|
||||||
id: item.id.clone(),
|
|
||||||
outcome,
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
let response = BatchResponse { responses };
|
|
||||||
encode_batch_response(&request, &response, self.config.limits.wire).unwrap_or_else(
|
|
||||||
|error| match error {
|
|
||||||
EncodeHttpError::Codec(codec) => self.batch_codec_error(codec),
|
|
||||||
EncodeHttpError::Http(_) => self.batch_top_error(&internal_error(), None),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn metadata_error(&self, route: Route, error: RequestMetadataError) -> Response<Vec<u8>> {
|
|
||||||
match error {
|
match error {
|
||||||
RequestMetadataError::InvalidRequest(_) => self.protocol_error(
|
RequestMetadataError::NotFound => empty_response(StatusCode::NOT_FOUND),
|
||||||
interaction(route),
|
error @ RequestMetadataError::MethodNotAllowed => Response::builder()
|
||||||
&ProtocolError {
|
.status(error.status())
|
||||||
code: ProtocolErrorCode::InvalidRequest,
|
.header(
|
||||||
message: "invalid HTTP request metadata".into(),
|
ALLOW,
|
||||||
},
|
error
|
||||||
None,
|
.allow()
|
||||||
),
|
.expect("method-not-allowed metadata has an Allow value"),
|
||||||
|
)
|
||||||
|
.body(Vec::new())
|
||||||
|
.expect("static method response is valid"),
|
||||||
RequestMetadataError::UnsupportedMediaType => {
|
RequestMetadataError::UnsupportedMediaType => {
|
||||||
empty_response(StatusCode::UNSUPPORTED_MEDIA_TYPE)
|
empty_response(StatusCode::UNSUPPORTED_MEDIA_TYPE)
|
||||||
}
|
}
|
||||||
@@ -263,8 +239,8 @@ impl WipFsServer {
|
|||||||
interaction: ProtocolInteraction,
|
interaction: ProtocolInteraction,
|
||||||
error: CodecError,
|
error: CodecError,
|
||||||
) -> Response<Vec<u8>> {
|
) -> Response<Vec<u8>> {
|
||||||
if let Some(kind) = error.resource_limit_kind() {
|
if is_transport_limit(&error) {
|
||||||
self.protocol_error(interaction, &resource_error(), Some(kind))
|
empty_response(StatusCode::PAYLOAD_TOO_LARGE)
|
||||||
} else {
|
} else {
|
||||||
self.protocol_error(
|
self.protocol_error(
|
||||||
interaction,
|
interaction,
|
||||||
@@ -272,21 +248,6 @@ impl WipFsServer {
|
|||||||
code: ProtocolErrorCode::InvalidRequest,
|
code: ProtocolErrorCode::InvalidRequest,
|
||||||
message: "malformed WIP request".into(),
|
message: "malformed WIP request".into(),
|
||||||
},
|
},
|
||||||
None,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn batch_codec_error(&self, error: CodecError) -> Response<Vec<u8>> {
|
|
||||||
if let Some(kind) = error.resource_limit_kind() {
|
|
||||||
self.batch_top_error(&resource_error(), Some(kind))
|
|
||||||
} else {
|
|
||||||
self.batch_top_error(
|
|
||||||
&ProtocolError {
|
|
||||||
code: ProtocolErrorCode::InvalidRequest,
|
|
||||||
message: "malformed WIP batch request".into(),
|
|
||||||
},
|
|
||||||
None,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -297,10 +258,10 @@ impl WipFsServer {
|
|||||||
error: EncodeHttpError,
|
error: EncodeHttpError,
|
||||||
) -> Response<Vec<u8>> {
|
) -> Response<Vec<u8>> {
|
||||||
match error {
|
match error {
|
||||||
EncodeHttpError::Codec(codec) if codec.resource_limit_kind().is_some() => {
|
EncodeHttpError::Codec(codec) if is_transport_limit(&codec) => {
|
||||||
self.protocol_error(interaction, &resource_error(), codec.resource_limit_kind())
|
empty_response(StatusCode::INTERNAL_SERVER_ERROR)
|
||||||
}
|
}
|
||||||
_ => self.protocol_error(interaction, &internal_error(), None),
|
_ => self.protocol_error(interaction, &internal_error()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -308,32 +269,9 @@ impl WipFsServer {
|
|||||||
&self,
|
&self,
|
||||||
interaction: ProtocolInteraction,
|
interaction: ProtocolInteraction,
|
||||||
error: &ProtocolError,
|
error: &ProtocolError,
|
||||||
resource_kind: Option<ResourceLimitKind>,
|
|
||||||
) -> Response<Vec<u8>> {
|
) -> Response<Vec<u8>> {
|
||||||
let encoded = match resource_kind {
|
encode_protocol_error_response(interaction, error, self.config.limits.wire)
|
||||||
Some(kind) => encode_resource_limit_error_response(
|
.unwrap_or_else(|_| empty_response(StatusCode::INTERNAL_SERVER_ERROR))
|
||||||
interaction,
|
|
||||||
error,
|
|
||||||
kind,
|
|
||||||
self.config.limits.wire,
|
|
||||||
),
|
|
||||||
None => encode_protocol_error_response(interaction, error, self.config.limits.wire),
|
|
||||||
};
|
|
||||||
encoded.unwrap_or_else(|_| empty_response(StatusCode::INTERNAL_SERVER_ERROR))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn batch_top_error(
|
|
||||||
&self,
|
|
||||||
error: &ProtocolError,
|
|
||||||
resource_kind: Option<ResourceLimitKind>,
|
|
||||||
) -> Response<Vec<u8>> {
|
|
||||||
let encoded = match resource_kind {
|
|
||||||
Some(kind) => {
|
|
||||||
encode_batch_resource_limit_error_response(error, kind, self.config.limits.wire)
|
|
||||||
}
|
|
||||||
None => encode_batch_error_response(error, self.config.limits.wire),
|
|
||||||
};
|
|
||||||
encoded.unwrap_or_else(|_| empty_response(StatusCode::INTERNAL_SERVER_ERROR))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -403,7 +341,7 @@ struct ParsedRequestHead {
|
|||||||
enum IntakeError {
|
enum IntakeError {
|
||||||
Timeout,
|
Timeout,
|
||||||
HeaderTooLarge,
|
HeaderTooLarge,
|
||||||
PayloadTooLarge { target: String },
|
PayloadTooLarge,
|
||||||
BadRequest,
|
BadRequest,
|
||||||
Socket,
|
Socket,
|
||||||
}
|
}
|
||||||
@@ -424,9 +362,7 @@ fn serve_connection(service: &WipFsServer, mut stream: TcpStream) {
|
|||||||
Err(IntakeError::HeaderTooLarge) => {
|
Err(IntakeError::HeaderTooLarge) => {
|
||||||
Some(empty_response(StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE))
|
Some(empty_response(StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE))
|
||||||
}
|
}
|
||||||
Err(IntakeError::PayloadTooLarge { target }) => {
|
Err(IntakeError::PayloadTooLarge) => Some(empty_response(StatusCode::PAYLOAD_TOO_LARGE)),
|
||||||
Some(payload_too_large_response(service, &target))
|
|
||||||
}
|
|
||||||
Err(IntakeError::BadRequest) => Some(empty_response(StatusCode::BAD_REQUEST)),
|
Err(IntakeError::BadRequest) => Some(empty_response(StatusCode::BAD_REQUEST)),
|
||||||
Err(IntakeError::Timeout | IntakeError::Socket) => None,
|
Err(IntakeError::Timeout | IntakeError::Socket) => None,
|
||||||
};
|
};
|
||||||
@@ -465,9 +401,7 @@ fn read_http_request(
|
|||||||
|
|
||||||
let parsed = parse_request_head(&received[..header_end])?;
|
let parsed = parse_request_head(&received[..header_end])?;
|
||||||
if parsed.content_length > maximum_body {
|
if parsed.content_length > maximum_body {
|
||||||
return Err(IntakeError::PayloadTooLarge {
|
return Err(IntakeError::PayloadTooLarge);
|
||||||
target: parsed.target,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
let mut body = Vec::with_capacity(parsed.content_length);
|
let mut body = Vec::with_capacity(parsed.content_length);
|
||||||
let buffered = &received[header_end..];
|
let buffered = &received[header_end..];
|
||||||
@@ -566,27 +500,6 @@ fn read_with_deadline(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn payload_too_large_response(service: &WipFsServer, target: &str) -> Response<Vec<u8>> {
|
|
||||||
let route = service.route(target.split('?').next().unwrap_or_default());
|
|
||||||
route.map_or_else(
|
|
||||||
|| empty_response(StatusCode::PAYLOAD_TOO_LARGE),
|
|
||||||
|route| {
|
|
||||||
if route == Route::Batch {
|
|
||||||
service.batch_top_error(
|
|
||||||
&resource_error(),
|
|
||||||
Some(ResourceLimitKind::RepresentationBytes),
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
service.protocol_error(
|
|
||||||
interaction(route),
|
|
||||||
&resource_error(),
|
|
||||||
Some(ResourceLimitKind::RepresentationBytes),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn write_http_response(
|
fn write_http_response(
|
||||||
stream: &mut TcpStream,
|
stream: &mut TcpStream,
|
||||||
response: &Response<Vec<u8>>,
|
response: &Response<Vec<u8>>,
|
||||||
@@ -647,20 +560,11 @@ fn write_all_with_deadline(
|
|||||||
stream.flush()
|
stream.flush()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn interaction(route: Route) -> ProtocolInteraction {
|
fn is_transport_limit(error: &CodecError) -> bool {
|
||||||
match route {
|
matches!(
|
||||||
Route::Observe => ProtocolInteraction::Observe,
|
error,
|
||||||
Route::FetchInterface => ProtocolInteraction::FetchInterface,
|
CodecError::BodyTooLarge { .. } | CodecError::NestingTooDeep { .. }
|
||||||
Route::CallOperation => ProtocolInteraction::CallOperation,
|
)
|
||||||
Route::Batch => ProtocolInteraction::Observe,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn resource_error() -> ProtocolError {
|
|
||||||
ProtocolError {
|
|
||||||
code: ProtocolErrorCode::ResourceLimitExceeded,
|
|
||||||
message: "configured resource limit exceeded".into(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn internal_error() -> ProtocolError {
|
fn internal_error() -> ProtocolError {
|
||||||
|
|||||||
@@ -7,12 +7,11 @@ use std::thread;
|
|||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
use tempfile::tempdir;
|
use tempfile::tempdir;
|
||||||
use wip_fs_server::{AccessMode, ServerConfig, TransportSecurity, WipFsServer};
|
use wip_fs_server::{AccessMode, ServerConfig, WipFsServer};
|
||||||
use wip_https::{
|
use wip_http::{
|
||||||
BatchRequest, BatchRequestItem, BatchRequestKind, BatchResponse, BatchSuccess, DecodedResponse,
|
ClientResponseError, DecodedResponse, Endpoint, JSON_CONTENT_TYPE, Limits, Route,
|
||||||
Endpoint, JSON_CONTENT_TYPE, Limits, Route, decode_batch_request, decode_batch_response,
|
TransportFailureKind, decode_call_operation_response, decode_fetch_interface_response,
|
||||||
decode_call_operation_response, decode_fetch_interface_response, decode_observe_response,
|
decode_observe_response, encode_call_operation_request, encode_fetch_interface_request,
|
||||||
encode_batch_request, encode_call_operation_request, encode_fetch_interface_request,
|
|
||||||
encode_observe_request,
|
encode_observe_request,
|
||||||
};
|
};
|
||||||
use wip_protocol::{
|
use wip_protocol::{
|
||||||
@@ -21,14 +20,13 @@ use wip_protocol::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn real_listener_serves_three_core_interactions_batch_and_write() {
|
fn real_listener_serves_three_core_interactions_and_write() {
|
||||||
let temporary = tempdir().expect("temporary root");
|
let temporary = tempdir().expect("temporary root");
|
||||||
std::fs::write(temporary.path().join("hello.txt"), b"hello world").expect("write file");
|
std::fs::write(temporary.path().join("hello.txt"), b"hello world").expect("write file");
|
||||||
std::fs::create_dir(temporary.path().join("nested")).expect("create directory");
|
std::fs::create_dir(temporary.path().join("nested")).expect("create directory");
|
||||||
|
|
||||||
let mut config = ServerConfig::for_root(temporary.path());
|
let mut config = ServerConfig::for_root(temporary.path());
|
||||||
config.access = AccessMode::ReadWrite;
|
config.access = AccessMode::ReadWrite;
|
||||||
config.transport_security = TransportSecurity::DevelopmentHttp;
|
|
||||||
let limits = config.limits.wire;
|
let limits = config.limits.wire;
|
||||||
let bound = Arc::new(
|
let bound = Arc::new(
|
||||||
WipFsServer::new(config)
|
WipFsServer::new(config)
|
||||||
@@ -43,7 +41,7 @@ fn real_listener_serves_three_core_interactions_batch_and_write() {
|
|||||||
let shutdown = Arc::clone(&shutdown);
|
let shutdown = Arc::clone(&shutdown);
|
||||||
thread::spawn(move || bound.serve_until(shutdown))
|
thread::spawn(move || bound.serve_until(shutdown))
|
||||||
};
|
};
|
||||||
let endpoint = Endpoint::parse(&format!("https://localhost:{}/wip", address.port()))
|
let endpoint = Endpoint::parse(&format!("http://localhost:{}/wip", address.port()))
|
||||||
.expect("client endpoint");
|
.expect("client endpoint");
|
||||||
|
|
||||||
let file_request = ObserveRequest {
|
let file_request = ObserveRequest {
|
||||||
@@ -125,36 +123,6 @@ fn real_listener_serves_three_core_interactions_batch_and_write() {
|
|||||||
);
|
);
|
||||||
assert_eq!(read.result, Value::Bytes(b"world".to_vec()));
|
assert_eq!(read.result, Value::Bytes(b"world".to_vec()));
|
||||||
|
|
||||||
let batch_request = BatchRequest {
|
|
||||||
requests: vec![
|
|
||||||
BatchRequestItem {
|
|
||||||
id: "root".into(),
|
|
||||||
request: BatchRequestKind::Observe(ObserveRequest {
|
|
||||||
path: "/".into(),
|
|
||||||
depth: 0,
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
BatchRequestItem {
|
|
||||||
id: "tree".into(),
|
|
||||||
request: BatchRequestKind::Observe(ObserveRequest {
|
|
||||||
path: "/nested".into(),
|
|
||||||
depth: 1,
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
BatchRequestItem {
|
|
||||||
id: "interface".into(),
|
|
||||||
request: BatchRequestKind::FetchInterface(read_interface_request.clone()),
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
let response = exchange(
|
|
||||||
address,
|
|
||||||
encode_batch_request(&endpoint, &batch_request, limits).expect("encode batch"),
|
|
||||||
);
|
|
||||||
let batch =
|
|
||||||
success(decode_batch_response(&batch_request, &response, limits).expect("decode batch"));
|
|
||||||
assert_batch_successes(&batch);
|
|
||||||
|
|
||||||
let write_interface_request = FetchInterfaceRequest {
|
let write_interface_request = FetchInterfaceRequest {
|
||||||
interface: file.interfaces[1].clone(),
|
interface: file.interfaces[1].clone(),
|
||||||
};
|
};
|
||||||
@@ -211,11 +179,166 @@ fn real_listener_serves_three_core_interactions_batch_and_write() {
|
|||||||
.expect("listener exits cleanly");
|
.expect("listener exits cleanly");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn real_listener_keeps_route_method_and_malformed_body_boundaries_distinct() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
let mut config = ServerConfig::for_root(temporary.path());
|
||||||
|
config.limits.wire = Limits::new(64, 4_096, 64).expect("wire limits");
|
||||||
|
let bound = Arc::new(
|
||||||
|
WipFsServer::new(config)
|
||||||
|
.expect("build server")
|
||||||
|
.bind()
|
||||||
|
.expect("bind"),
|
||||||
|
);
|
||||||
|
let address = bound.local_addr();
|
||||||
|
let shutdown = Arc::new(AtomicBool::new(false));
|
||||||
|
let worker = {
|
||||||
|
let bound = Arc::clone(&bound);
|
||||||
|
let shutdown = Arc::clone(&shutdown);
|
||||||
|
thread::spawn(move || bound.serve_until(shutdown))
|
||||||
|
};
|
||||||
|
|
||||||
|
for uri in [
|
||||||
|
"/wip/v1/unknown",
|
||||||
|
"/wip/v1/batch",
|
||||||
|
"/wip/v1/observe?unexpected=true",
|
||||||
|
"/wip/v1/observe/extra",
|
||||||
|
] {
|
||||||
|
let response = exchange(address, json_request(http::Method::POST, uri, b"{}"));
|
||||||
|
assert_eq!(response.status(), http::StatusCode::NOT_FOUND);
|
||||||
|
assert!(response.body().is_empty());
|
||||||
|
assert!(!response.headers().contains_key(http::header::CONTENT_TYPE));
|
||||||
|
assert!(!response.headers().contains_key(http::header::ALLOW));
|
||||||
|
}
|
||||||
|
|
||||||
|
let wrong_method = exchange(
|
||||||
|
address,
|
||||||
|
json_request(http::Method::GET, "/wip/v1/observe", b""),
|
||||||
|
);
|
||||||
|
assert_eq!(wrong_method.status(), http::StatusCode::METHOD_NOT_ALLOWED);
|
||||||
|
assert_eq!(wrong_method.headers()[http::header::ALLOW], "POST");
|
||||||
|
assert!(wrong_method.body().is_empty());
|
||||||
|
assert!(
|
||||||
|
!wrong_method
|
||||||
|
.headers()
|
||||||
|
.contains_key(http::header::CONTENT_TYPE)
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut unsupported_coding = json_request(
|
||||||
|
http::Method::POST,
|
||||||
|
"/wip/v1/observe",
|
||||||
|
br#"{"path":"/","depth":0}"#,
|
||||||
|
);
|
||||||
|
unsupported_coding
|
||||||
|
.headers_mut()
|
||||||
|
.insert(http::header::CONTENT_ENCODING, "gzip".parse().unwrap());
|
||||||
|
let unsupported_coding = exchange(address, unsupported_coding);
|
||||||
|
assert_eq!(
|
||||||
|
unsupported_coding.status(),
|
||||||
|
http::StatusCode::UNSUPPORTED_MEDIA_TYPE
|
||||||
|
);
|
||||||
|
assert!(unsupported_coding.body().is_empty());
|
||||||
|
assert!(
|
||||||
|
!unsupported_coding
|
||||||
|
.headers()
|
||||||
|
.contains_key(http::header::CONTENT_TYPE)
|
||||||
|
);
|
||||||
|
|
||||||
|
let malformed = exchange(
|
||||||
|
address,
|
||||||
|
json_request(http::Method::POST, "/wip/v1/observe", b"{"),
|
||||||
|
);
|
||||||
|
assert_eq!(malformed.status(), http::StatusCode::BAD_REQUEST);
|
||||||
|
assert_eq!(
|
||||||
|
malformed.headers()[http::header::CONTENT_TYPE],
|
||||||
|
JSON_CONTENT_TYPE
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
std::str::from_utf8(malformed.body())
|
||||||
|
.expect("UTF-8 error envelope")
|
||||||
|
.contains("\"invalid_request\"")
|
||||||
|
);
|
||||||
|
|
||||||
|
let oversized = exchange(
|
||||||
|
address,
|
||||||
|
json_request(http::Method::POST, "/wip/v1/observe", &[b'x'; 65]),
|
||||||
|
);
|
||||||
|
assert_eq!(oversized.status(), http::StatusCode::PAYLOAD_TOO_LARGE);
|
||||||
|
assert!(oversized.body().is_empty());
|
||||||
|
assert!(!oversized.headers().contains_key(http::header::CONTENT_TYPE));
|
||||||
|
|
||||||
|
let mut header_only = TcpStream::connect(address).expect("connect header-only client");
|
||||||
|
header_only
|
||||||
|
.set_read_timeout(Some(Duration::from_secs(1)))
|
||||||
|
.expect("set header-only timeout");
|
||||||
|
write!(
|
||||||
|
header_only,
|
||||||
|
"POST /wip/v1/observe HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\nContent-Length: 65\r\n\r\n"
|
||||||
|
)
|
||||||
|
.expect("write oversized request head");
|
||||||
|
header_only.flush().expect("flush oversized request head");
|
||||||
|
let mut raw = Vec::new();
|
||||||
|
header_only
|
||||||
|
.read_to_end(&mut raw)
|
||||||
|
.expect("read immediate limit response");
|
||||||
|
assert!(raw.starts_with(b"HTTP/1.1 413 "));
|
||||||
|
assert!(raw.ends_with(b"\r\n\r\n"));
|
||||||
|
assert!(
|
||||||
|
!raw.windows(b"resource_limit_exceeded".len())
|
||||||
|
.any(|window| { window == b"resource_limit_exceeded" })
|
||||||
|
);
|
||||||
|
|
||||||
|
shutdown.store(true, Ordering::Release);
|
||||||
|
worker
|
||||||
|
.join()
|
||||||
|
.expect("join listener")
|
||||||
|
.expect("listener exits cleanly");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn raw_decoder_limits_are_transport_failures() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
let mut config = ServerConfig::for_root(temporary.path());
|
||||||
|
config.limits.wire = Limits::new(4_096, 4_096, 8).expect("wire limits");
|
||||||
|
let server = WipFsServer::new(config).expect("build server");
|
||||||
|
|
||||||
|
let nested = br#"{"path":[[[[[[[[["/"]]]]]]]]],"depth":0}"#;
|
||||||
|
let response = server.handle_http(json_request(http::Method::POST, "/wip/v1/observe", nested));
|
||||||
|
assert_eq!(response.status(), http::StatusCode::PAYLOAD_TOO_LARGE);
|
||||||
|
assert!(response.body().is_empty());
|
||||||
|
assert!(!response.headers().contains_key(http::header::CONTENT_TYPE));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn logical_observation_limit_remains_protocol_resource_failure() {
|
||||||
|
let temporary = tempdir().expect("temporary root");
|
||||||
|
let mut config = ServerConfig::for_root(temporary.path());
|
||||||
|
config.limits.max_observation_depth = 0;
|
||||||
|
let limits = config.limits.wire;
|
||||||
|
let server = WipFsServer::new(config).expect("build server");
|
||||||
|
let endpoint = Endpoint::parse("http://localhost/wip").expect("endpoint");
|
||||||
|
let request = ObserveRequest {
|
||||||
|
path: "/".into(),
|
||||||
|
depth: 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
let response = server.handle_http(
|
||||||
|
encode_observe_request(&endpoint, &request, limits).expect("encode observation"),
|
||||||
|
);
|
||||||
|
assert_eq!(response.status(), http::StatusCode::UNPROCESSABLE_ENTITY);
|
||||||
|
assert!(matches!(
|
||||||
|
decode_observe_response(&request, &response, limits).expect("decode logical limit"),
|
||||||
|
DecodedResponse::ProtocolFailure {
|
||||||
|
error,
|
||||||
|
status_mismatch: None,
|
||||||
|
} if error.code == ProtocolErrorCode::ResourceLimitExceeded
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn stalled_request_body_times_out_and_releases_the_only_worker() {
|
fn stalled_request_body_times_out_and_releases_the_only_worker() {
|
||||||
let temporary = tempdir().expect("temporary root");
|
let temporary = tempdir().expect("temporary root");
|
||||||
let mut config = ServerConfig::for_root(temporary.path());
|
let mut config = ServerConfig::for_root(temporary.path());
|
||||||
config.transport_security = TransportSecurity::DevelopmentHttp;
|
|
||||||
config.limits.max_concurrent_requests = 1;
|
config.limits.max_concurrent_requests = 1;
|
||||||
config.limits.request_timeout = Duration::from_millis(200);
|
config.limits.request_timeout = Duration::from_millis(200);
|
||||||
let limits = config.limits.wire;
|
let limits = config.limits.wire;
|
||||||
@@ -245,7 +368,7 @@ fn stalled_request_body_times_out_and_releases_the_only_worker() {
|
|||||||
stalled.flush().expect("flush partial request");
|
stalled.flush().expect("flush partial request");
|
||||||
thread::sleep(Duration::from_millis(25));
|
thread::sleep(Duration::from_millis(25));
|
||||||
|
|
||||||
let endpoint = Endpoint::parse(&format!("https://localhost:{}/wip", address.port()))
|
let endpoint = Endpoint::parse(&format!("http://localhost:{}/wip", address.port()))
|
||||||
.expect("client endpoint");
|
.expect("client endpoint");
|
||||||
let observe = ObserveRequest {
|
let observe = ObserveRequest {
|
||||||
path: "/".into(),
|
path: "/".into(),
|
||||||
@@ -283,43 +406,12 @@ fn stalled_request_body_times_out_and_releases_the_only_worker() {
|
|||||||
.expect("listener exits cleanly");
|
.expect("listener exits cleanly");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn batch_keeps_known_malformed_arguments_item_local() {
|
|
||||||
let temporary = tempdir().expect("temporary root");
|
|
||||||
let config = ServerConfig::for_root(temporary.path());
|
|
||||||
let limits = config.limits.wire;
|
|
||||||
let server = WipFsServer::new(config).expect("build server");
|
|
||||||
let endpoint = Endpoint::parse("https://localhost/wip").expect("endpoint");
|
|
||||||
let body = br#"{"requests":[{"id":"ok","method":"observe","arguments":{"path":"/","depth":0}},{"id":"bad","method":"observe","arguments":{"path":"/","depth":"bad"}}]}"#;
|
|
||||||
let logical = decode_batch_request(body, limits).expect("decode item-local invalid request");
|
|
||||||
assert!(matches!(
|
|
||||||
logical.requests[1].request,
|
|
||||||
BatchRequestKind::Invalid { .. }
|
|
||||||
));
|
|
||||||
let request = http::Request::builder()
|
|
||||||
.method(http::Method::POST)
|
|
||||||
.uri(endpoint.route(Route::Batch).as_str())
|
|
||||||
.header(http::header::CONTENT_TYPE, JSON_CONTENT_TYPE)
|
|
||||||
.header(http::header::ACCEPT, "application/json")
|
|
||||||
.body(body.to_vec())
|
|
||||||
.expect("build request");
|
|
||||||
let response = server.handle_http(request);
|
|
||||||
let batch = success(
|
|
||||||
decode_batch_response(&logical, &response, limits).expect("decode mixed batch response"),
|
|
||||||
);
|
|
||||||
assert!(matches!(
|
|
||||||
batch.responses[0].outcome,
|
|
||||||
Ok(BatchSuccess::Observe(_))
|
|
||||||
));
|
|
||||||
assert!(batch.responses[1].outcome.is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn call_argument_decoding_does_not_mask_missing_target() {
|
fn call_argument_decoding_does_not_mask_missing_target() {
|
||||||
let temporary = tempdir().expect("temporary root");
|
let temporary = tempdir().expect("temporary root");
|
||||||
let config = ServerConfig::for_root(temporary.path());
|
let config = ServerConfig::for_root(temporary.path());
|
||||||
let server = WipFsServer::new(config).expect("build server");
|
let server = WipFsServer::new(config).expect("build server");
|
||||||
let endpoint = Endpoint::parse("https://localhost/wip").expect("endpoint");
|
let endpoint = Endpoint::parse("http://localhost/wip").expect("endpoint");
|
||||||
let body = br#"{"target":{"path":"/missing"},"interface":{"reference":"unknown"},"operation":"missing","arguments":{"bytes":"not-base64"}}"#;
|
let body = br#"{"target":{"path":"/missing"},"interface":{"reference":"unknown"},"operation":"missing","arguments":{"bytes":"not-base64"}}"#;
|
||||||
let request = http::Request::builder()
|
let request = http::Request::builder()
|
||||||
.method(http::Method::POST)
|
.method(http::Method::POST)
|
||||||
@@ -343,7 +435,7 @@ fn backend_invalid_unicode_path_is_not_found_not_internal() {
|
|||||||
let config = ServerConfig::for_root(temporary.path());
|
let config = ServerConfig::for_root(temporary.path());
|
||||||
let limits = config.limits.wire;
|
let limits = config.limits.wire;
|
||||||
let server = WipFsServer::new(config).expect("build server");
|
let server = WipFsServer::new(config).expect("build server");
|
||||||
let endpoint = Endpoint::parse("https://localhost/wip").expect("endpoint");
|
let endpoint = Endpoint::parse("http://localhost/wip").expect("endpoint");
|
||||||
let request = ObserveRequest {
|
let request = ObserveRequest {
|
||||||
path: "/bad\0name".into(),
|
path: "/bad\0name".into(),
|
||||||
depth: 0,
|
depth: 0,
|
||||||
@@ -361,14 +453,14 @@ fn backend_invalid_unicode_path_is_not_found_not_internal() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn read_response_size_failure_preserves_non_commit_guarantee() {
|
fn read_response_size_failure_is_transport_local() {
|
||||||
let temporary = tempdir().expect("temporary root");
|
let temporary = tempdir().expect("temporary root");
|
||||||
std::fs::write(temporary.path().join("large"), vec![b'x'; 2_000]).expect("write file");
|
std::fs::write(temporary.path().join("large"), vec![b'x'; 2_000]).expect("write file");
|
||||||
let mut config = ServerConfig::for_root(temporary.path());
|
let mut config = ServerConfig::for_root(temporary.path());
|
||||||
config.limits.wire = Limits::new(4_096, 1_024, 64, 64).expect("wire limits");
|
config.limits.wire = Limits::new(4_096, 1_024, 64).expect("wire limits");
|
||||||
let limits = config.limits.wire;
|
let limits = config.limits.wire;
|
||||||
let server = WipFsServer::new(config).expect("build server");
|
let server = WipFsServer::new(config).expect("build server");
|
||||||
let endpoint = Endpoint::parse("https://localhost/wip").expect("endpoint");
|
let endpoint = Endpoint::parse("http://localhost/wip").expect("endpoint");
|
||||||
|
|
||||||
let observe_request = ObserveRequest {
|
let observe_request = ObserveRequest {
|
||||||
path: "/large".into(),
|
path: "/large".into(),
|
||||||
@@ -408,30 +500,15 @@ fn read_response_size_failure_preserves_non_commit_guarantee() {
|
|||||||
encode_call_operation_request(&endpoint, &call, &interface.descriptor, limits)
|
encode_call_operation_request(&endpoint, &call, &interface.descriptor, limits)
|
||||||
.expect("encode read call"),
|
.expect("encode read call"),
|
||||||
);
|
);
|
||||||
assert_eq!(response.status(), http::StatusCode::PAYLOAD_TOO_LARGE);
|
assert_eq!(response.status(), http::StatusCode::INTERNAL_SERVER_ERROR);
|
||||||
match decode_call_operation_response(&call, &interface.descriptor, &response, limits)
|
assert!(response.body().is_empty());
|
||||||
.expect("decode resource failure")
|
assert!(!response.headers().contains_key(http::header::CONTENT_TYPE));
|
||||||
{
|
|
||||||
DecodedResponse::ProtocolFailure { error, .. } => {
|
|
||||||
assert_eq!(error.code, ProtocolErrorCode::ResourceLimitExceeded);
|
|
||||||
}
|
|
||||||
DecodedResponse::Success(_) => panic!("oversized read response must fail"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn assert_batch_successes(batch: &BatchResponse) {
|
|
||||||
assert_eq!(batch.responses.len(), 3);
|
|
||||||
assert!(matches!(
|
assert!(matches!(
|
||||||
batch.responses[0].outcome,
|
decode_call_operation_response(&call, &interface.descriptor, &response, limits)
|
||||||
Ok(BatchSuccess::Observe(_))
|
.expect_err("oversized representation is not a protocol failure"),
|
||||||
));
|
ClientResponseError::TransportBinding(failure)
|
||||||
assert!(matches!(
|
if failure.status == http::StatusCode::INTERNAL_SERVER_ERROR
|
||||||
batch.responses[1].outcome,
|
&& failure.kind == TransportFailureKind::HttpStatus
|
||||||
Ok(BatchSuccess::Observe(_))
|
|
||||||
));
|
|
||||||
assert!(matches!(
|
|
||||||
batch.responses[2].outcome,
|
|
||||||
Ok(BatchSuccess::FetchInterface(_))
|
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -442,6 +519,16 @@ fn success<T>(response: DecodedResponse<T>) -> T {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn json_request(method: http::Method, uri: &str, body: &[u8]) -> http::Request<Vec<u8>> {
|
||||||
|
http::Request::builder()
|
||||||
|
.method(method)
|
||||||
|
.uri(uri)
|
||||||
|
.header(http::header::CONTENT_TYPE, JSON_CONTENT_TYPE)
|
||||||
|
.header(http::header::ACCEPT, "application/json")
|
||||||
|
.body(body.to_vec())
|
||||||
|
.expect("build JSON request")
|
||||||
|
}
|
||||||
|
|
||||||
fn exchange(address: SocketAddr, request: http::Request<Vec<u8>>) -> http::Response<Vec<u8>> {
|
fn exchange(address: SocketAddr, request: http::Request<Vec<u8>>) -> http::Response<Vec<u8>> {
|
||||||
let mut stream = TcpStream::connect(address).expect("connect listener");
|
let mut stream = TcpStream::connect(address).expect("connect listener");
|
||||||
stream
|
stream
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "wip-https"
|
name = "wip-http"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
description = "Framework-independent standard WIP over HTTPS v1 binding"
|
description = "Framework-independent standard WIP over HTTP v1 binding"
|
||||||
license = "MIT OR Apache-2.0"
|
license = "MIT OR Apache-2.0"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use std::fmt::{self, Display, Formatter};
|
use std::fmt::{self, Display, Formatter};
|
||||||
|
|
||||||
use http::header::{ACCEPT, CONTENT_TYPE};
|
use http::header::{ACCEPT, CONTENT_ENCODING, CONTENT_TYPE};
|
||||||
use http::{HeaderMap, Method, Request, Response, StatusCode};
|
use http::{HeaderMap, Method, Request, Response, StatusCode};
|
||||||
use wip_protocol::{
|
use wip_protocol::{
|
||||||
CallOperationRequest, CallOperationResponse, FetchInterfaceRequest, FetchInterfaceResponse,
|
CallOperationRequest, CallOperationResponse, FetchInterfaceRequest, FetchInterfaceResponse,
|
||||||
@@ -12,7 +12,7 @@ use wip_protocol::{
|
|||||||
use crate::response::{self, DecodedResponse};
|
use crate::response::{self, DecodedResponse};
|
||||||
use crate::{
|
use crate::{
|
||||||
BodyKind, ClientResponseError, CodecError, Endpoint, InvalidResponseKind, JSON_CONTENT_TYPE,
|
BodyKind, ClientResponseError, CodecError, Endpoint, InvalidResponseKind, JSON_CONTENT_TYPE,
|
||||||
Limits, ResourceLimitKind, Route, json,
|
Limits, Route, json,
|
||||||
};
|
};
|
||||||
|
|
||||||
fn request(
|
fn request(
|
||||||
@@ -36,6 +36,9 @@ fn response(status: StatusCode, body: Vec<u8>) -> Result<Response<Vec<u8>>, http
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn require_response_content_type<B>(response: &Response<B>) -> Result<(), ClientResponseError> {
|
fn require_response_content_type<B>(response: &Response<B>) -> Result<(), ClientResponseError> {
|
||||||
|
if !has_supported_content_coding(response.headers()) {
|
||||||
|
return Err(response::unsupported_content_coding(response.status()));
|
||||||
|
}
|
||||||
let valid = response
|
let valid = response
|
||||||
.headers()
|
.headers()
|
||||||
.get(CONTENT_TYPE)
|
.get(CONTENT_TYPE)
|
||||||
@@ -181,9 +184,11 @@ fn accepts_json(headers: &HeaderMap) -> bool {
|
|||||||
/// A failure while validating inbound HTTP request metadata.
|
/// A failure while validating inbound HTTP request metadata.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum RequestMetadataError {
|
pub enum RequestMetadataError {
|
||||||
/// The method or route does not match the selected WIP interaction.
|
/// The request URI does not exactly identify the selected standard route.
|
||||||
InvalidRequest(CodecError),
|
NotFound,
|
||||||
/// The request body does not use UTF-8 `application/json`.
|
/// A known standard route was requested with a method other than `POST`.
|
||||||
|
MethodNotAllowed,
|
||||||
|
/// The request body does not use UTF-8 `application/json` or identity coding.
|
||||||
UnsupportedMediaType,
|
UnsupportedMediaType,
|
||||||
/// The request's `Accept` metadata excludes `application/json`.
|
/// The request's `Accept` metadata excludes `application/json`.
|
||||||
NotAcceptable,
|
NotAcceptable,
|
||||||
@@ -194,32 +199,47 @@ impl RequestMetadataError {
|
|||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn status(&self) -> StatusCode {
|
pub const fn status(&self) -> StatusCode {
|
||||||
match self {
|
match self {
|
||||||
Self::InvalidRequest(_) => StatusCode::BAD_REQUEST,
|
Self::NotFound => StatusCode::NOT_FOUND,
|
||||||
|
Self::MethodNotAllowed => StatusCode::METHOD_NOT_ALLOWED,
|
||||||
Self::UnsupportedMediaType => StatusCode::UNSUPPORTED_MEDIA_TYPE,
|
Self::UnsupportedMediaType => StatusCode::UNSUPPORTED_MEDIA_TYPE,
|
||||||
Self::NotAcceptable => StatusCode::NOT_ACCEPTABLE,
|
Self::NotAcceptable => StatusCode::NOT_ACCEPTABLE,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns the value for an `Allow` response header, when required.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn allow(&self) -> Option<&'static str> {
|
||||||
|
match self {
|
||||||
|
Self::MethodNotAllowed => Some("POST"),
|
||||||
|
Self::NotFound | Self::UnsupportedMediaType | Self::NotAcceptable => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Display for RequestMetadataError {
|
impl Display for RequestMetadataError {
|
||||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||||
match self {
|
match self {
|
||||||
Self::InvalidRequest(error) => error.fmt(formatter),
|
Self::NotFound => formatter.write_str("request URI is not a standard WIP route"),
|
||||||
|
Self::MethodNotAllowed => formatter.write_str("standard WIP routes require POST"),
|
||||||
Self::UnsupportedMediaType => {
|
Self::UnsupportedMediaType => {
|
||||||
formatter.write_str("expected UTF-8 application/json Content-Type")
|
formatter.write_str("expected identity-coded UTF-8 application/json Content-Type")
|
||||||
}
|
}
|
||||||
Self::NotAcceptable => formatter.write_str("request does not accept application/json"),
|
Self::NotAcceptable => formatter.write_str("request does not accept application/json"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Error for RequestMetadataError {
|
impl Error for RequestMetadataError {}
|
||||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
|
||||||
match self {
|
pub(crate) fn has_supported_content_coding(headers: &HeaderMap) -> bool {
|
||||||
Self::InvalidRequest(error) => Some(error),
|
headers.get_all(CONTENT_ENCODING).iter().all(|value| {
|
||||||
Self::UnsupportedMediaType | Self::NotAcceptable => None,
|
value.to_str().is_ok_and(|value| {
|
||||||
}
|
let mut codings = value.split(',').map(str::trim);
|
||||||
}
|
let first = codings.next();
|
||||||
|
first.is_some_and(|coding| coding.eq_ignore_ascii_case("identity"))
|
||||||
|
&& codings.all(|coding| coding.eq_ignore_ascii_case("identity"))
|
||||||
|
})
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Validates mandatory HTTP metadata for an inbound WIP request.
|
/// Validates mandatory HTTP metadata for an inbound WIP request.
|
||||||
@@ -233,29 +253,19 @@ pub fn validate_http_request<B>(
|
|||||||
route: Route,
|
route: Route,
|
||||||
value: &Request<B>,
|
value: &Request<B>,
|
||||||
) -> Result<(), RequestMetadataError> {
|
) -> Result<(), RequestMetadataError> {
|
||||||
if value.method() != Method::POST {
|
|
||||||
return Err(RequestMetadataError::InvalidRequest(
|
|
||||||
CodecError::InvalidField {
|
|
||||||
field: "method".into(),
|
|
||||||
reason: "standard WIP routes require POST".into(),
|
|
||||||
},
|
|
||||||
));
|
|
||||||
}
|
|
||||||
let expected = endpoint.route(route);
|
let expected = endpoint.route(route);
|
||||||
if value.uri().path() != expected.path() || value.uri().query().is_some() {
|
if value.uri().path() != expected.path() || value.uri().query().is_some() {
|
||||||
return Err(RequestMetadataError::InvalidRequest(
|
return Err(RequestMetadataError::NotFound);
|
||||||
CodecError::InvalidField {
|
}
|
||||||
field: "route".into(),
|
if value.method() != Method::POST {
|
||||||
reason: "request URI does not match the selected standard route".into(),
|
return Err(RequestMetadataError::MethodNotAllowed);
|
||||||
},
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
let valid_content_type = value
|
let valid_content_type = value
|
||||||
.headers()
|
.headers()
|
||||||
.get(CONTENT_TYPE)
|
.get(CONTENT_TYPE)
|
||||||
.and_then(|value| value.to_str().ok())
|
.and_then(|value| value.to_str().ok())
|
||||||
.is_some_and(is_json_content_type);
|
.is_some_and(is_json_content_type);
|
||||||
if !valid_content_type {
|
if !valid_content_type || !has_supported_content_coding(value.headers()) {
|
||||||
return Err(RequestMetadataError::UnsupportedMediaType);
|
return Err(RequestMetadataError::UnsupportedMediaType);
|
||||||
}
|
}
|
||||||
if !accepts_json(value.headers()) {
|
if !accepts_json(value.headers()) {
|
||||||
@@ -526,9 +536,8 @@ fn encode_protocol_error_with_status(
|
|||||||
/// The code must be allowed for `interaction`. This API accepts only
|
/// The code must be allowed for `interaction`. This API accepts only
|
||||||
/// [`ProtocolError`], so client-local `InvalidResponse` and
|
/// [`ProtocolError`], so client-local `InvalidResponse` and
|
||||||
/// `UnsupportedDescriptorFormat` classifications cannot be emitted as Host
|
/// `UnsupportedDescriptorFormat` classifications cannot be emitted as Host
|
||||||
/// error envelopes. Resource-limit errors use the logical-limit status; callers
|
/// error envelopes. Logical `resource_limit_exceeded` failures use HTTP 422;
|
||||||
/// that know the concrete limit class should use
|
/// representation and deployment limits are not protocol errors.
|
||||||
/// [`encode_resource_limit_error_response`].
|
|
||||||
pub fn encode_protocol_error_response(
|
pub fn encode_protocol_error_response(
|
||||||
interaction: ProtocolInteraction,
|
interaction: ProtocolInteraction,
|
||||||
error: &ProtocolError,
|
error: &ProtocolError,
|
||||||
@@ -542,28 +551,6 @@ pub fn encode_protocol_error_response(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Encodes a `resource_limit_exceeded` envelope with its class-specific status.
|
|
||||||
pub fn encode_resource_limit_error_response(
|
|
||||||
interaction: ProtocolInteraction,
|
|
||||||
error: &ProtocolError,
|
|
||||||
kind: ResourceLimitKind,
|
|
||||||
limits: Limits,
|
|
||||||
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
|
||||||
if error.code != wip_protocol::ProtocolErrorCode::ResourceLimitExceeded {
|
|
||||||
return Err(CodecError::InvalidField {
|
|
||||||
field: "error.code".into(),
|
|
||||||
reason: "resource-limit encoder requires resource_limit_exceeded".into(),
|
|
||||||
}
|
|
||||||
.into());
|
|
||||||
}
|
|
||||||
encode_protocol_error_with_status(
|
|
||||||
interaction,
|
|
||||||
error,
|
|
||||||
response::status_for_resource_limit(kind),
|
|
||||||
limits,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Failure while building an outbound framework-neutral HTTP message.
|
/// Failure while building an outbound framework-neutral HTTP message.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum EncodeHttpError {
|
pub enum EncodeHttpError {
|
||||||
@@ -6,7 +6,7 @@ use url::Url;
|
|||||||
/// The media type emitted for every WIP request and every response with a body.
|
/// The media type emitted for every WIP request and every response with a body.
|
||||||
pub const JSON_CONTENT_TYPE: &str = "application/json; charset=utf-8";
|
pub const JSON_CONTENT_TYPE: &str = "application/json; charset=utf-8";
|
||||||
|
|
||||||
/// A fixed standard WIP over HTTPS v1 route.
|
/// A fixed standard WIP over HTTP v1 route.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
pub enum Route {
|
pub enum Route {
|
||||||
/// Observe one object and its indexable descendants.
|
/// Observe one object and its indexable descendants.
|
||||||
@@ -15,8 +15,6 @@ pub enum Route {
|
|||||||
FetchInterface,
|
FetchInterface,
|
||||||
/// Call one operation.
|
/// Call one operation.
|
||||||
CallOperation,
|
CallOperation,
|
||||||
/// Package independent retrieval interactions.
|
|
||||||
Batch,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Route {
|
impl Route {
|
||||||
@@ -27,27 +25,24 @@ impl Route {
|
|||||||
Self::Observe => "v1/observe",
|
Self::Observe => "v1/observe",
|
||||||
Self::FetchInterface => "v1/fetch_interface",
|
Self::FetchInterface => "v1/fetch_interface",
|
||||||
Self::CallOperation => "v1/call_operation",
|
Self::CallOperation => "v1/call_operation",
|
||||||
Self::Batch => "v1/batch",
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A canonical absolute HTTPS base URL whose path always ends in `/`.
|
/// A canonical absolute hierarchical base URL whose path always ends in `/`.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct Endpoint(Url);
|
pub struct Endpoint(Url);
|
||||||
|
|
||||||
impl Endpoint {
|
impl Endpoint {
|
||||||
/// Parses and canonicalizes an endpoint.
|
/// Parses and canonicalizes an endpoint.
|
||||||
///
|
///
|
||||||
/// The input must be an absolute HTTPS URL without a query or fragment. Its
|
/// The input must be an absolute hierarchical URL with a host and without a
|
||||||
/// path is an endpoint prefix, not a Worldspace path. A trailing slash is
|
/// query or fragment. Its path is an endpoint prefix, not a Worldspace path.
|
||||||
/// appended when absent so RFC 3986 relative-reference resolution preserves
|
/// A trailing slash is appended when absent so RFC 3986 relative-reference
|
||||||
/// the final prefix segment.
|
/// resolution preserves the final prefix segment. The supplied scheme is
|
||||||
|
/// preserved; scheme and transport security are deployment concerns.
|
||||||
pub fn parse(input: &str) -> Result<Self, EndpointError> {
|
pub fn parse(input: &str) -> Result<Self, EndpointError> {
|
||||||
let mut url = Url::parse(input).map_err(EndpointError::InvalidUrl)?;
|
let mut url = Url::parse(input).map_err(EndpointError::InvalidUrl)?;
|
||||||
if url.scheme() != "https" {
|
|
||||||
return Err(EndpointError::NotHttps);
|
|
||||||
}
|
|
||||||
if url.cannot_be_a_base() || url.host_str().is_none() {
|
if url.cannot_be_a_base() || url.host_str().is_none() {
|
||||||
return Err(EndpointError::NotAbsoluteBase);
|
return Err(EndpointError::NotAbsoluteBase);
|
||||||
}
|
}
|
||||||
@@ -84,12 +79,7 @@ impl Endpoint {
|
|||||||
/// are not route components and therefore never match.
|
/// are not route components and therefore never match.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn recognize(&self, candidate: &Url) -> Option<Route> {
|
pub fn recognize(&self, candidate: &Url) -> Option<Route> {
|
||||||
const ROUTES: [Route; 4] = [
|
const ROUTES: [Route; 3] = [Route::Observe, Route::FetchInterface, Route::CallOperation];
|
||||||
Route::Observe,
|
|
||||||
Route::FetchInterface,
|
|
||||||
Route::CallOperation,
|
|
||||||
Route::Batch,
|
|
||||||
];
|
|
||||||
if candidate.query().is_some() || candidate.fragment().is_some() {
|
if candidate.query().is_some() || candidate.fragment().is_some() {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
@@ -113,13 +103,11 @@ impl TryFrom<&str> for Endpoint {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Why an endpoint is not a valid standard WIP HTTPS base.
|
/// Why an endpoint is not a valid standard WIP over HTTP base.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum EndpointError {
|
pub enum EndpointError {
|
||||||
/// URL parsing failed.
|
/// URL parsing failed.
|
||||||
InvalidUrl(url::ParseError),
|
InvalidUrl(url::ParseError),
|
||||||
/// The URL scheme is not `https`.
|
|
||||||
NotHttps,
|
|
||||||
/// The URL is not a hierarchical absolute URL with an authority.
|
/// The URL is not a hierarchical absolute URL with an authority.
|
||||||
NotAbsoluteBase,
|
NotAbsoluteBase,
|
||||||
/// A query component was supplied.
|
/// A query component was supplied.
|
||||||
@@ -132,7 +120,6 @@ impl Display for EndpointError {
|
|||||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||||
match self {
|
match self {
|
||||||
Self::InvalidUrl(error) => write!(formatter, "invalid endpoint URL: {error}"),
|
Self::InvalidUrl(error) => write!(formatter, "invalid endpoint URL: {error}"),
|
||||||
Self::NotHttps => formatter.write_str("WIP endpoint must use HTTPS"),
|
|
||||||
Self::NotAbsoluteBase => {
|
Self::NotAbsoluteBase => {
|
||||||
formatter.write_str("WIP endpoint must be an absolute base URL")
|
formatter.write_str("WIP endpoint must be an absolute base URL")
|
||||||
}
|
}
|
||||||
@@ -10,8 +10,6 @@ pub struct Limits {
|
|||||||
pub(crate) max_response_bytes: usize,
|
pub(crate) max_response_bytes: usize,
|
||||||
/// Largest accepted JSON container nesting depth.
|
/// Largest accepted JSON container nesting depth.
|
||||||
pub(crate) max_nesting: usize,
|
pub(crate) max_nesting: usize,
|
||||||
/// Largest accepted number of batch items.
|
|
||||||
pub(crate) max_batch_items: usize,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Limits {
|
impl Limits {
|
||||||
@@ -20,7 +18,6 @@ impl Limits {
|
|||||||
max_request_bytes: usize,
|
max_request_bytes: usize,
|
||||||
max_response_bytes: usize,
|
max_response_bytes: usize,
|
||||||
max_nesting: usize,
|
max_nesting: usize,
|
||||||
max_batch_items: usize,
|
|
||||||
) -> Result<Self, LimitConfigurationError> {
|
) -> Result<Self, LimitConfigurationError> {
|
||||||
if max_request_bytes == 0 {
|
if max_request_bytes == 0 {
|
||||||
return Err(LimitConfigurationError::ZeroRequestBytes);
|
return Err(LimitConfigurationError::ZeroRequestBytes);
|
||||||
@@ -31,14 +28,10 @@ impl Limits {
|
|||||||
if max_nesting == 0 {
|
if max_nesting == 0 {
|
||||||
return Err(LimitConfigurationError::ZeroNesting);
|
return Err(LimitConfigurationError::ZeroNesting);
|
||||||
}
|
}
|
||||||
if max_batch_items == 0 {
|
|
||||||
return Err(LimitConfigurationError::ZeroBatchItems);
|
|
||||||
}
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
max_request_bytes,
|
max_request_bytes,
|
||||||
max_response_bytes,
|
max_response_bytes,
|
||||||
max_nesting,
|
max_nesting,
|
||||||
max_batch_items,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,12 +52,6 @@ impl Limits {
|
|||||||
pub const fn max_nesting(self) -> usize {
|
pub const fn max_nesting(self) -> usize {
|
||||||
self.max_nesting
|
self.max_nesting
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the batch item count limit.
|
|
||||||
#[must_use]
|
|
||||||
pub const fn max_batch_items(self) -> usize {
|
|
||||||
self.max_batch_items
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Why a [`Limits`] configuration is not bounded.
|
/// Why a [`Limits`] configuration is not bounded.
|
||||||
@@ -76,8 +63,6 @@ pub enum LimitConfigurationError {
|
|||||||
ZeroResponseBytes,
|
ZeroResponseBytes,
|
||||||
/// Nesting limit was zero.
|
/// Nesting limit was zero.
|
||||||
ZeroNesting,
|
ZeroNesting,
|
||||||
/// Batch-item limit was zero.
|
|
||||||
ZeroBatchItems,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Display for LimitConfigurationError {
|
impl Display for LimitConfigurationError {
|
||||||
@@ -86,7 +71,6 @@ impl Display for LimitConfigurationError {
|
|||||||
Self::ZeroRequestBytes => "request byte limit must be nonzero",
|
Self::ZeroRequestBytes => "request byte limit must be nonzero",
|
||||||
Self::ZeroResponseBytes => "response byte limit must be nonzero",
|
Self::ZeroResponseBytes => "response byte limit must be nonzero",
|
||||||
Self::ZeroNesting => "nesting limit must be nonzero",
|
Self::ZeroNesting => "nesting limit must be nonzero",
|
||||||
Self::ZeroBatchItems => "batch item limit must be nonzero",
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -102,15 +86,6 @@ pub enum BodyKind {
|
|||||||
Response,
|
Response,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The class of a resource limit exceeded by a wire representation.
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub enum ResourceLimitKind {
|
|
||||||
/// A request or response representation exceeded its byte-size limit.
|
|
||||||
RepresentationBytes,
|
|
||||||
/// A logical limit such as nesting depth, batch count, or collection size was exceeded.
|
|
||||||
Logical,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A malformed or locally disallowed wire representation.
|
/// A malformed or locally disallowed wire representation.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum CodecError {
|
pub enum CodecError {
|
||||||
@@ -157,47 +132,6 @@ pub enum CodecError {
|
|||||||
},
|
},
|
||||||
/// Logical protocol validation rejected the decoded representation.
|
/// Logical protocol validation rejected the decoded representation.
|
||||||
ProtocolValidation(wip_protocol::ValidationError),
|
ProtocolValidation(wip_protocol::ValidationError),
|
||||||
/// The batch exceeds its configured item count.
|
|
||||||
TooManyBatchItems {
|
|
||||||
/// Actual item count.
|
|
||||||
actual: usize,
|
|
||||||
/// Configured maximum.
|
|
||||||
maximum: usize,
|
|
||||||
},
|
|
||||||
/// Batch item identifiers are not unique.
|
|
||||||
DuplicateBatchId {
|
|
||||||
/// Repeated identifier.
|
|
||||||
id: String,
|
|
||||||
},
|
|
||||||
/// A response contains a batch identifier that was not requested.
|
|
||||||
UnexpectedBatchId {
|
|
||||||
/// Unexpected identifier.
|
|
||||||
id: String,
|
|
||||||
},
|
|
||||||
/// A response omitted a requested batch identifier.
|
|
||||||
MissingBatchId {
|
|
||||||
/// Missing identifier.
|
|
||||||
id: String,
|
|
||||||
},
|
|
||||||
/// A batch item result does not match its requested interaction.
|
|
||||||
BatchInteractionMismatch {
|
|
||||||
/// Item identifier.
|
|
||||||
id: String,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CodecError {
|
|
||||||
/// Classifies this failure when it represents a canonical resource limit.
|
|
||||||
#[must_use]
|
|
||||||
pub const fn resource_limit_kind(&self) -> Option<ResourceLimitKind> {
|
|
||||||
match self {
|
|
||||||
Self::BodyTooLarge { .. } => Some(ResourceLimitKind::RepresentationBytes),
|
|
||||||
Self::NestingTooDeep { .. } | Self::TooManyBatchItems { .. } => {
|
|
||||||
Some(ResourceLimitKind::Logical)
|
|
||||||
}
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Display for CodecError {
|
impl Display for CodecError {
|
||||||
@@ -225,15 +159,6 @@ impl Display for CodecError {
|
|||||||
write!(formatter, "field `{field}` is not canonical base64")
|
write!(formatter, "field `{field}` is not canonical base64")
|
||||||
}
|
}
|
||||||
Self::ProtocolValidation(error) => error.fmt(formatter),
|
Self::ProtocolValidation(error) => error.fmt(formatter),
|
||||||
Self::TooManyBatchItems { actual, maximum } => {
|
|
||||||
write!(formatter, "batch has {actual} items; maximum is {maximum}")
|
|
||||||
}
|
|
||||||
Self::DuplicateBatchId { id } => write!(formatter, "duplicate batch id `{id}`"),
|
|
||||||
Self::UnexpectedBatchId { id } => write!(formatter, "unexpected batch id `{id}`"),
|
|
||||||
Self::MissingBatchId { id } => write!(formatter, "missing batch id `{id}`"),
|
|
||||||
Self::BatchInteractionMismatch { id } => {
|
|
||||||
write!(formatter, "batch result does not match request `{id}`")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,61 +1,54 @@
|
|||||||
//! Framework-independent standard WIP over HTTPS v1 binding.
|
//! Framework-independent standard WIP over HTTP v1 binding.
|
||||||
//!
|
//!
|
||||||
//! This crate owns endpoint and route derivation, UTF-8 JSON encoding, canonical
|
//! This crate owns endpoint and route derivation, UTF-8 JSON encoding, canonical
|
||||||
//! success and error response handling, HTTP status mapping, descriptor-guided
|
//! success and error response handling, HTTP status mapping, descriptor-guided
|
||||||
//! operation-value conversion, and retrieval batching. It deliberately performs
|
//! operation-value conversion. It deliberately performs no I/O and depends on no
|
||||||
//! no I/O and depends on no server framework, TLS implementation, filesystem
|
//! server framework, TLS implementation, filesystem projection, client cache, or
|
||||||
//! projection, client cache, or presentation layer.
|
//! presentation layer. URL schemes, TLS, certificates, authentication mechanisms,
|
||||||
|
//! proxies, and caches are selected by the HTTP implementation and deployment
|
||||||
|
//! rather than by WIP conformance.
|
||||||
//!
|
//!
|
||||||
//! Logical values remain owned by [`wip_protocol`]. Validators and `Bytes` are
|
//! Logical values remain owned by [`wip_protocol`]. Validators and `Bytes` are
|
||||||
//! encoded in JSON bodies using canonical RFC 4648 Section 4 base64; this crate
|
//! encoded in JSON bodies using canonical RFC 4648 Section 4 base64; this crate
|
||||||
//! does not infer WIP validator semantics from `ETag` or `If-Match`.
|
//! does not infer WIP validator semantics from `ETag` or `If-Match`.
|
||||||
//!
|
//!
|
||||||
//! ```
|
//! ```
|
||||||
//! use wip_https::{Endpoint, Limits, encode_observe_request};
|
//! use wip_http::{Endpoint, Limits, encode_observe_request};
|
||||||
//! use wip_protocol::ObserveRequest;
|
//! use wip_protocol::ObserveRequest;
|
||||||
//!
|
//!
|
||||||
//! let endpoint = Endpoint::parse("https://example.test/api/wip")?;
|
//! let endpoint = Endpoint::parse("http://example.test/api/wip")?;
|
||||||
//! let limits = Limits::new(64 * 1024, 1024 * 1024, 64, 100)?;
|
//! let limits = Limits::new(64 * 1024, 1024 * 1024, 64)?;
|
||||||
//! let request = encode_observe_request(
|
//! let request = encode_observe_request(
|
||||||
//! &endpoint,
|
//! &endpoint,
|
||||||
//! &ObserveRequest { path: "/items/123".into(), depth: 0 },
|
//! &ObserveRequest { path: "/items/123".into(), depth: 0 },
|
||||||
//! limits,
|
//! limits,
|
||||||
//! )?;
|
//! )?;
|
||||||
//! assert_eq!(request.uri(), "https://example.test/api/wip/v1/observe");
|
//! assert_eq!(request.uri(), "http://example.test/api/wip/v1/observe");
|
||||||
//! assert_eq!(request.method(), http::Method::POST);
|
//! assert_eq!(request.method(), http::Method::POST);
|
||||||
//! # Ok::<(), Box<dyn std::error::Error>>(())
|
//! # Ok::<(), Box<dyn std::error::Error>>(())
|
||||||
//! ```
|
//! ```
|
||||||
|
|
||||||
#![deny(missing_docs)]
|
#![deny(missing_docs)]
|
||||||
|
|
||||||
mod batch;
|
|
||||||
mod codec;
|
mod codec;
|
||||||
mod endpoint;
|
mod endpoint;
|
||||||
mod error;
|
mod error;
|
||||||
mod json;
|
mod json;
|
||||||
mod response;
|
mod response;
|
||||||
|
|
||||||
pub use batch::{
|
|
||||||
BatchMethod, BatchRequest, BatchRequestItem, BatchRequestKind, BatchResponse,
|
|
||||||
BatchResponseItem, BatchSuccess, decode_batch_request, decode_batch_response,
|
|
||||||
encode_batch_error_response, encode_batch_request, encode_batch_resource_limit_error_response,
|
|
||||||
encode_batch_response,
|
|
||||||
};
|
|
||||||
pub use codec::{
|
pub use codec::{
|
||||||
CallOperationMetadata, EncodeHttpError, RequestMetadataError, decode_call_operation_metadata,
|
CallOperationMetadata, EncodeHttpError, RequestMetadataError, decode_call_operation_metadata,
|
||||||
decode_call_operation_request, decode_call_operation_response, decode_fetch_interface_request,
|
decode_call_operation_request, decode_call_operation_response, decode_fetch_interface_request,
|
||||||
decode_fetch_interface_response, decode_observe_request, decode_observe_response,
|
decode_fetch_interface_response, decode_observe_request, decode_observe_response,
|
||||||
encode_call_operation_request, encode_call_operation_response, encode_fetch_interface_request,
|
encode_call_operation_request, encode_call_operation_response, encode_fetch_interface_request,
|
||||||
encode_fetch_interface_response, encode_observe_request, encode_observe_response,
|
encode_fetch_interface_response, encode_observe_request, encode_observe_response,
|
||||||
encode_protocol_error_response, encode_resource_limit_error_response, is_json_content_type,
|
encode_protocol_error_response, is_json_content_type, validate_http_request,
|
||||||
validate_http_request,
|
|
||||||
};
|
};
|
||||||
pub use endpoint::{Endpoint, EndpointError, JSON_CONTENT_TYPE, Route};
|
pub use endpoint::{Endpoint, EndpointError, JSON_CONTENT_TYPE, Route};
|
||||||
pub use error::{BodyKind, CodecError, LimitConfigurationError, Limits, ResourceLimitKind};
|
pub use error::{BodyKind, CodecError, LimitConfigurationError, Limits};
|
||||||
pub use response::{
|
pub use response::{
|
||||||
ClientResponseError, DecodedResponse, InvalidResponseKind, StatusMismatch,
|
ClientResponseError, DecodedResponse, InvalidResponseKind, StatusMismatch,
|
||||||
TransportBindingFailure, TransportFailureKind, error_code_name, status_for_error,
|
TransportBindingFailure, TransportFailureKind, error_code_name, status_for_error,
|
||||||
status_for_resource_limit,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Framework-neutral HTTP types used by this binding's public API.
|
/// Framework-neutral HTTP types used by this binding's public API.
|
||||||
@@ -5,7 +5,7 @@ use http::StatusCode;
|
|||||||
use serde_json::{Map, Value as Json};
|
use serde_json::{Map, Value as Json};
|
||||||
use wip_protocol::{ProtocolError, ProtocolErrorCode, ProtocolInteraction};
|
use wip_protocol::{ProtocolError, ProtocolErrorCode, ProtocolInteraction};
|
||||||
|
|
||||||
use crate::{BodyKind, CodecError, Limits, ResourceLimitKind, json};
|
use crate::{BodyKind, CodecError, Limits, json};
|
||||||
|
|
||||||
/// A successfully classified client response.
|
/// A successfully classified client response.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
@@ -37,6 +37,8 @@ pub enum TransportFailureKind {
|
|||||||
AuthenticationRequired,
|
AuthenticationRequired,
|
||||||
/// HTTP 403, commonly emitted by endpoint policy or infrastructure.
|
/// HTTP 403, commonly emitted by endpoint policy or infrastructure.
|
||||||
EndpointForbidden,
|
EndpointForbidden,
|
||||||
|
/// The response uses a content coding the client does not support.
|
||||||
|
UnsupportedContentCoding,
|
||||||
/// Another non-success HTTP response without a WIP error envelope.
|
/// Another non-success HTTP response without a WIP error envelope.
|
||||||
HttpStatus,
|
HttpStatus,
|
||||||
}
|
}
|
||||||
@@ -63,8 +65,6 @@ pub enum InvalidResponseKind {
|
|||||||
NonCanonicalSuccessStatus,
|
NonCanonicalSuccessStatus,
|
||||||
/// A 2xx body was malformed or semantically invalid.
|
/// A 2xx body was malformed or semantically invalid.
|
||||||
InvalidSuccessBody,
|
InvalidSuccessBody,
|
||||||
/// A batch response did not correlate exactly with its request.
|
|
||||||
InvalidBatch,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A local failure while classifying or validating a peer response.
|
/// A local failure while classifying or validating a peer response.
|
||||||
@@ -119,10 +119,6 @@ impl Display for ClientResponseError {
|
|||||||
impl Error for ClientResponseError {}
|
impl Error for ClientResponseError {}
|
||||||
|
|
||||||
/// Returns the canonical HTTP status for a wire-level protocol error.
|
/// Returns the canonical HTTP status for a wire-level protocol error.
|
||||||
///
|
|
||||||
/// [`ProtocolErrorCode::ResourceLimitExceeded`] defaults to the logical-limit
|
|
||||||
/// status. Use [`status_for_resource_limit`] when the concrete limit class is
|
|
||||||
/// known.
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn status_for_error(code: ProtocolErrorCode) -> StatusCode {
|
pub const fn status_for_error(code: ProtocolErrorCode) -> StatusCode {
|
||||||
match code {
|
match code {
|
||||||
@@ -145,22 +141,8 @@ pub const fn status_for_error(code: ProtocolErrorCode) -> StatusCode {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the canonical HTTP status for a concrete resource-limit class.
|
|
||||||
#[must_use]
|
|
||||||
pub const fn status_for_resource_limit(kind: ResourceLimitKind) -> StatusCode {
|
|
||||||
match kind {
|
|
||||||
ResourceLimitKind::RepresentationBytes => StatusCode::PAYLOAD_TOO_LARGE,
|
|
||||||
ResourceLimitKind::Logical => StatusCode::UNPROCESSABLE_ENTITY,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn status_matches_error(status: StatusCode, code: ProtocolErrorCode) -> bool {
|
fn status_matches_error(status: StatusCode, code: ProtocolErrorCode) -> bool {
|
||||||
match code {
|
status == status_for_error(code)
|
||||||
ProtocolErrorCode::ResourceLimitExceeded => {
|
|
||||||
status == StatusCode::PAYLOAD_TOO_LARGE || status == StatusCode::UNPROCESSABLE_ENTITY
|
|
||||||
}
|
|
||||||
_ => status == status_for_error(code),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the stable snake-case wire spelling of a protocol code.
|
/// Returns the stable snake-case wire spelling of a protocol code.
|
||||||
@@ -213,14 +195,7 @@ pub(crate) fn error_to_json(error: &ProtocolError) -> Json {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn item_error_to_json(error: &ProtocolError) -> Json {
|
fn protocol_error_from_json(value: &Json) -> Result<ProtocolError, CodecError> {
|
||||||
serde_json::json!({
|
|
||||||
"code": error_code_name(error.code),
|
|
||||||
"message": error.message,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn item_error_from_json(value: &Json) -> Result<ProtocolError, CodecError> {
|
|
||||||
let fields = value
|
let fields = value
|
||||||
.as_object()
|
.as_object()
|
||||||
.ok_or_else(|| invalid_field("error", "expected object"))?;
|
.ok_or_else(|| invalid_field("error", "expected object"))?;
|
||||||
@@ -239,7 +214,7 @@ fn envelope_error_from_json(value: &Json) -> Result<Option<ProtocolError>, Codec
|
|||||||
if fields.len() != 1 || !fields.contains_key("error") {
|
if fields.len() != 1 || !fields.contains_key("error") {
|
||||||
return Ok(None);
|
return Ok(None);
|
||||||
}
|
}
|
||||||
item_error_from_json(&fields["error"]).map(Some)
|
protocol_error_from_json(&fields["error"]).map(Some)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn exact(fields: &Map<String, Json>, allowed: &[&str], parent: &str) -> Result<(), CodecError> {
|
fn exact(fields: &Map<String, Json>, allowed: &[&str], parent: &str) -> Result<(), CodecError> {
|
||||||
@@ -355,6 +330,13 @@ pub(crate) fn decode<T>(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn unsupported_content_coding(status: StatusCode) -> ClientResponseError {
|
||||||
|
ClientResponseError::TransportBinding(TransportBindingFailure {
|
||||||
|
status,
|
||||||
|
kind: TransportFailureKind::UnsupportedContentCoding,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) fn transport_failure(status: StatusCode) -> ClientResponseError {
|
pub(crate) fn transport_failure(status: StatusCode) -> ClientResponseError {
|
||||||
let kind = match status {
|
let kind = match status {
|
||||||
StatusCode::UNAUTHORIZED => TransportFailureKind::AuthenticationRequired,
|
StatusCode::UNAUTHORIZED => TransportFailureKind::AuthenticationRequired,
|
||||||
@@ -1,24 +1,24 @@
|
|||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
use wip_https::http::StatusCode;
|
use wip_http::http::StatusCode;
|
||||||
use wip_https::wip_protocol::{
|
use wip_http::wip_protocol::{
|
||||||
CallOperationRequest, CallOperationResponse, Documentation, EnumCase, FetchInterfaceRequest,
|
CallOperationRequest, CallOperationResponse, Documentation, EnumCase, FetchInterfaceRequest,
|
||||||
FetchInterfaceResponse, FieldDeclaration, INTERFACE_FORMAT_V1, InterfaceDescriptor,
|
FetchInterfaceResponse, FieldDeclaration, INTERFACE_FORMAT_V1, InterfaceDescriptor,
|
||||||
InterfaceTarget, MAX_SAFE_INTEGER, Object, ObjectObservation, ObserveRequest,
|
InterfaceTarget, MAX_SAFE_INTEGER, Object, ObjectObservation, ObserveRequest,
|
||||||
OperationDeclaration, ParameterDeclaration, ReturnDeclaration, Target, TypeDeclaration,
|
OperationDeclaration, ParameterDeclaration, ReturnDeclaration, Target, TypeDeclaration,
|
||||||
TypeExpr, UnionCase, Value,
|
TypeExpr, UnionCase, Value,
|
||||||
};
|
};
|
||||||
use wip_https::{
|
use wip_http::{
|
||||||
ClientResponseError, CodecError, DecodedResponse, Endpoint, InvalidResponseKind, Limits,
|
ClientResponseError, CodecError, DecodedResponse, Endpoint, InvalidResponseKind, Limits,
|
||||||
ResourceLimitKind, decode_call_operation_metadata, decode_call_operation_request,
|
decode_call_operation_metadata, decode_call_operation_request, decode_call_operation_response,
|
||||||
decode_call_operation_response, decode_fetch_interface_request,
|
decode_fetch_interface_request, decode_fetch_interface_response, decode_observe_request,
|
||||||
decode_fetch_interface_response, decode_observe_request, decode_observe_response,
|
decode_observe_response, encode_call_operation_request, encode_call_operation_response,
|
||||||
encode_call_operation_request, encode_call_operation_response, encode_fetch_interface_request,
|
encode_fetch_interface_request, encode_fetch_interface_response, encode_observe_request,
|
||||||
encode_fetch_interface_response, encode_observe_request, encode_observe_response,
|
encode_observe_response,
|
||||||
};
|
};
|
||||||
|
|
||||||
fn limits() -> Limits {
|
fn limits() -> Limits {
|
||||||
Limits::new(1_000_000, 1_000_000, 100, 100).unwrap()
|
Limits::new(1_000_000, 1_000_000, 100).unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn endpoint() -> Endpoint {
|
fn endpoint() -> Endpoint {
|
||||||
@@ -404,25 +404,17 @@ fn malformed_unknown_null_and_noncanonical_base64_are_rejected() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn caller_limits_bound_bytes_and_nesting() {
|
fn caller_limits_remain_local_codec_failures() {
|
||||||
let tiny = Limits::new(8, 8, 2, 1).unwrap();
|
let tiny = Limits::new(8, 8, 2).unwrap();
|
||||||
let too_large = decode_observe_request(br#"{"path":"/long","depth":0}"#, tiny).unwrap_err();
|
let too_large = decode_observe_request(br#"{"path":"/long","depth":0}"#, tiny).unwrap_err();
|
||||||
assert!(matches!(&too_large, CodecError::BodyTooLarge { .. }));
|
assert!(matches!(&too_large, CodecError::BodyTooLarge { .. }));
|
||||||
assert_eq!(
|
|
||||||
too_large.resource_limit_kind(),
|
|
||||||
Some(ResourceLimitKind::RepresentationBytes)
|
|
||||||
);
|
|
||||||
|
|
||||||
let nested = br#"{"path":[[["/"]]],"depth":0}"#;
|
let nested = br#"{"path":[[["/"]]],"depth":0}"#;
|
||||||
let nesting_limited = Limits::new(1024, 1024, 2, 1).unwrap();
|
let nesting_limited = Limits::new(1024, 1024, 2).unwrap();
|
||||||
let too_deep = decode_observe_request(nested, nesting_limited).unwrap_err();
|
let too_deep = decode_observe_request(nested, nesting_limited).unwrap_err();
|
||||||
assert!(matches!(&too_deep, CodecError::NestingTooDeep { .. }));
|
assert!(matches!(&too_deep, CodecError::NestingTooDeep { .. }));
|
||||||
assert_eq!(
|
|
||||||
too_deep.resource_limit_kind(),
|
|
||||||
Some(ResourceLimitKind::Logical)
|
|
||||||
);
|
|
||||||
|
|
||||||
let outbound_limited = Limits::new(1_000_000, 1_000_000, 1, 10).unwrap();
|
let outbound_limited = Limits::new(1_000_000, 1_000_000, 1).unwrap();
|
||||||
assert!(
|
assert!(
|
||||||
encode_call_operation_request(
|
encode_call_operation_request(
|
||||||
&endpoint(),
|
&endpoint(),
|
||||||
@@ -466,7 +458,7 @@ fn unsupported_descriptor_format_is_client_local() {
|
|||||||
ClientResponseError::UnsupportedDescriptorFormat { .. }
|
ClientResponseError::UnsupportedDescriptorFormat { .. }
|
||||||
));
|
));
|
||||||
|
|
||||||
let future_shape = wip_https::http::Response::builder()
|
let future_shape = wip_http::http::Response::builder()
|
||||||
.status(StatusCode::OK)
|
.status(StatusCode::OK)
|
||||||
.header("content-type", "application/json; charset=utf-8")
|
.header("content-type", "application/json; charset=utf-8")
|
||||||
.body(
|
.body(
|
||||||
@@ -485,7 +477,7 @@ fn unsupported_descriptor_format_is_client_local() {
|
|||||||
br#"{"interface":"interface-v1","descriptor":{"format":"wip-interface/2"},"validator":null}"#
|
br#"{"interface":"interface-v1","descriptor":{"format":"wip-interface/2"},"validator":null}"#
|
||||||
.as_slice(),
|
.as_slice(),
|
||||||
] {
|
] {
|
||||||
let response = wip_https::http::Response::builder()
|
let response = wip_http::http::Response::builder()
|
||||||
.status(StatusCode::OK)
|
.status(StatusCode::OK)
|
||||||
.header("content-type", "application/json; charset=utf-8")
|
.header("content-type", "application/json; charset=utf-8")
|
||||||
.body(malformed.to_vec())
|
.body(malformed.to_vec())
|
||||||
@@ -502,7 +494,7 @@ fn unsupported_descriptor_format_is_client_local() {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn invalid_success_is_classified_as_invalid_response() {
|
fn invalid_success_is_classified_as_invalid_response() {
|
||||||
let response = wip_https::http::Response::builder()
|
let response = wip_http::http::Response::builder()
|
||||||
.status(StatusCode::OK)
|
.status(StatusCode::OK)
|
||||||
.header("content-type", "application/json; charset=utf-8")
|
.header("content-type", "application/json; charset=utf-8")
|
||||||
.body(br#"{"object":{"name":"wrong","interfaces":[]}}"#.to_vec())
|
.body(br#"{"object":{"name":"wrong","interfaces":[]}}"#.to_vec())
|
||||||
@@ -1,16 +1,15 @@
|
|||||||
use wip_https::http::{Response, StatusCode};
|
use wip_http::http::{Response, StatusCode};
|
||||||
use wip_https::wip_protocol::{
|
use wip_http::wip_protocol::{
|
||||||
ObserveRequest, ProtocolError, ProtocolErrorCode, ProtocolInteraction,
|
ObserveRequest, ProtocolError, ProtocolErrorCode, ProtocolInteraction,
|
||||||
};
|
};
|
||||||
use wip_https::{
|
use wip_http::{
|
||||||
ClientResponseError, DecodedResponse, InvalidResponseKind, Limits, ResourceLimitKind,
|
ClientResponseError, DecodedResponse, InvalidResponseKind, Limits, TransportFailureKind,
|
||||||
TransportFailureKind, decode_observe_response, encode_protocol_error_response,
|
decode_observe_response, encode_protocol_error_response, error_code_name, is_json_content_type,
|
||||||
encode_resource_limit_error_response, error_code_name, is_json_content_type, status_for_error,
|
status_for_error,
|
||||||
status_for_resource_limit,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
fn limits() -> Limits {
|
fn limits() -> Limits {
|
||||||
Limits::new(64 * 1024, 64 * 1024, 32, 16).unwrap()
|
Limits::new(64 * 1024, 64 * 1024, 32).unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn request() -> ObserveRequest {
|
fn request() -> ObserveRequest {
|
||||||
@@ -120,41 +119,45 @@ fn every_protocol_code_has_stable_name_and_status() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn resource_limit_statuses_encode_and_decode_by_concrete_limit_class() {
|
fn logical_resource_limit_uses_only_422_and_bare_413_is_transport_failure() {
|
||||||
let error = ProtocolError {
|
let error = ProtocolError {
|
||||||
code: ProtocolErrorCode::ResourceLimitExceeded,
|
code: ProtocolErrorCode::ResourceLimitExceeded,
|
||||||
message: "bounded".into(),
|
message: "logical observation limit exceeded".into(),
|
||||||
};
|
};
|
||||||
let cases = [
|
let encoded =
|
||||||
(
|
|
||||||
ResourceLimitKind::RepresentationBytes,
|
|
||||||
StatusCode::PAYLOAD_TOO_LARGE,
|
|
||||||
),
|
|
||||||
(ResourceLimitKind::Logical, StatusCode::UNPROCESSABLE_ENTITY),
|
|
||||||
];
|
|
||||||
for (kind, status) in cases {
|
|
||||||
assert_eq!(status_for_resource_limit(kind), status);
|
|
||||||
let encoded = encode_resource_limit_error_response(
|
|
||||||
ProtocolInteraction::Observe,
|
|
||||||
&error,
|
|
||||||
kind,
|
|
||||||
limits(),
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(encoded.status(), status);
|
|
||||||
assert_eq!(
|
|
||||||
decode_observe_response(&request(), &encoded, limits()).unwrap(),
|
|
||||||
DecodedResponse::ProtocolFailure {
|
|
||||||
error: error.clone(),
|
|
||||||
status_mismatch: None,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
let default =
|
|
||||||
encode_protocol_error_response(ProtocolInteraction::Observe, &error, limits()).unwrap();
|
encode_protocol_error_response(ProtocolInteraction::Observe, &error, limits()).unwrap();
|
||||||
assert_eq!(default.status(), StatusCode::UNPROCESSABLE_ENTITY);
|
assert_eq!(encoded.status(), StatusCode::UNPROCESSABLE_ENTITY);
|
||||||
assert_ne!(default.status(), StatusCode::TOO_MANY_REQUESTS);
|
assert_eq!(
|
||||||
|
decode_observe_response(&request(), &encoded, limits()).unwrap(),
|
||||||
|
DecodedResponse::ProtocolFailure {
|
||||||
|
error: error.clone(),
|
||||||
|
status_mismatch: None,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut noncanonical = encoded;
|
||||||
|
*noncanonical.status_mut() = StatusCode::PAYLOAD_TOO_LARGE;
|
||||||
|
assert_eq!(
|
||||||
|
decode_observe_response(&request(), &noncanonical, limits()).unwrap(),
|
||||||
|
DecodedResponse::ProtocolFailure {
|
||||||
|
error,
|
||||||
|
status_mismatch: Some(wip_http::StatusMismatch {
|
||||||
|
actual: StatusCode::PAYLOAD_TOO_LARGE,
|
||||||
|
expected: StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
let bare_413 = Response::builder()
|
||||||
|
.status(StatusCode::PAYLOAD_TOO_LARGE)
|
||||||
|
.body(Vec::<u8>::new())
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
decode_observe_response(&request(), &bare_413, limits()).unwrap_err(),
|
||||||
|
ClientResponseError::TransportBinding(failure)
|
||||||
|
if failure.status == StatusCode::PAYLOAD_TOO_LARGE
|
||||||
|
&& failure.kind == TransportFailureKind::HttpStatus
|
||||||
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -171,6 +174,49 @@ fn rate_limit_status_without_protocol_envelope_stays_transport_failure() {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unsupported_response_content_coding_is_transport_failure() {
|
||||||
|
let mut encoded = encode_protocol_error_response(
|
||||||
|
ProtocolInteraction::Observe,
|
||||||
|
&ProtocolError {
|
||||||
|
code: ProtocolErrorCode::NotFound,
|
||||||
|
message: "missing".into(),
|
||||||
|
},
|
||||||
|
limits(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
encoded
|
||||||
|
.headers_mut()
|
||||||
|
.insert("content-encoding", "gzip".parse().unwrap());
|
||||||
|
assert!(matches!(
|
||||||
|
decode_observe_response(&request(), &encoded, limits()).unwrap_err(),
|
||||||
|
ClientResponseError::TransportBinding(failure)
|
||||||
|
if failure.status == StatusCode::NOT_FOUND
|
||||||
|
&& failure.kind == TransportFailureKind::UnsupportedContentCoding
|
||||||
|
));
|
||||||
|
|
||||||
|
let success = response(StatusCode::OK, br#"{"object":{"name":"","interfaces":[]}}"#);
|
||||||
|
let mut identity = success.clone();
|
||||||
|
identity
|
||||||
|
.headers_mut()
|
||||||
|
.insert("content-encoding", "identity".parse().unwrap());
|
||||||
|
assert!(matches!(
|
||||||
|
decode_observe_response(&request(), &identity, limits()).unwrap(),
|
||||||
|
DecodedResponse::Success(_)
|
||||||
|
));
|
||||||
|
|
||||||
|
let mut unsupported = success;
|
||||||
|
unsupported
|
||||||
|
.headers_mut()
|
||||||
|
.insert("content-encoding", "br".parse().unwrap());
|
||||||
|
assert!(matches!(
|
||||||
|
decode_observe_response(&request(), &unsupported, limits()).unwrap_err(),
|
||||||
|
ClientResponseError::TransportBinding(failure)
|
||||||
|
if failure.status == StatusCode::OK
|
||||||
|
&& failure.kind == TransportFailureKind::UnsupportedContentCoding
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn valid_success_body_requires_exactly_http_200() {
|
fn valid_success_body_requires_exactly_http_200() {
|
||||||
let success_body = br#"{"object":{"name":"","interfaces":[]}}"#;
|
let success_body = br#"{"object":{"name":"","interfaces":[]}}"#;
|
||||||
@@ -211,7 +257,7 @@ fn valid_envelope_code_is_authoritative_when_status_mismatches() {
|
|||||||
decode_observe_response(&request(), &encoded, limits()).unwrap(),
|
decode_observe_response(&request(), &encoded, limits()).unwrap(),
|
||||||
DecodedResponse::ProtocolFailure {
|
DecodedResponse::ProtocolFailure {
|
||||||
error,
|
error,
|
||||||
status_mismatch: Some(wip_https::StatusMismatch {
|
status_mismatch: Some(wip_http::StatusMismatch {
|
||||||
actual: StatusCode::IM_A_TEAPOT,
|
actual: StatusCode::IM_A_TEAPOT,
|
||||||
expected: StatusCode::NOT_FOUND,
|
expected: StatusCode::NOT_FOUND,
|
||||||
}),
|
}),
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
use wip_http::http::{Method, Request, StatusCode};
|
||||||
|
use wip_http::{Endpoint, RequestMetadataError, Route, validate_http_request};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn endpoint_preserves_http_and_https_when_resolving_canonical_routes() {
|
||||||
|
for scheme in ["http", "https"] {
|
||||||
|
let endpoint = Endpoint::parse(&format!("{scheme}://example.test/root/prefix")).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
endpoint.to_string(),
|
||||||
|
format!("{scheme}://example.test/root/prefix/")
|
||||||
|
);
|
||||||
|
|
||||||
|
let expected = [
|
||||||
|
(Route::Observe, "v1/observe"),
|
||||||
|
(Route::FetchInterface, "v1/fetch_interface"),
|
||||||
|
(Route::CallOperation, "v1/call_operation"),
|
||||||
|
];
|
||||||
|
for (route, suffix) in expected {
|
||||||
|
let url = format!("{scheme}://example.test/root/prefix/{suffix}");
|
||||||
|
assert_eq!(endpoint.route(route).as_str(), url);
|
||||||
|
assert_eq!(
|
||||||
|
endpoint.recognize(&wip_http::url::Url::parse(&url).unwrap()),
|
||||||
|
Some(route)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
endpoint.recognize(
|
||||||
|
&wip_http::url::Url::parse(&format!(
|
||||||
|
"{scheme}://example.test/root/prefix/v1/observe?path=/items"
|
||||||
|
))
|
||||||
|
.unwrap()
|
||||||
|
),
|
||||||
|
None
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn routes_never_mix_worldspace_paths_into_endpoint_prefixes() {
|
||||||
|
let endpoint = Endpoint::parse("https://example.test/wip/%E4%B8%96%E7%95%8C/").unwrap();
|
||||||
|
let route = endpoint.route(Route::Observe);
|
||||||
|
assert_eq!(route.path(), "/wip/%E4%B8%96%E7%95%8C/v1/observe");
|
||||||
|
assert!(!route.as_str().contains("items"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn inbound_http_metadata_enforces_post_route_and_json() {
|
||||||
|
let endpoint = Endpoint::parse("https://example.test/wip").unwrap();
|
||||||
|
let valid = Request::builder()
|
||||||
|
.method(Method::POST)
|
||||||
|
.uri("/wip/v1/observe")
|
||||||
|
.header("content-type", "application/json; charset=utf-8")
|
||||||
|
.body(Vec::<u8>::new())
|
||||||
|
.unwrap();
|
||||||
|
assert!(validate_http_request(&endpoint, Route::Observe, &valid).is_ok());
|
||||||
|
|
||||||
|
let wrong_method = Request::builder()
|
||||||
|
.method(Method::GET)
|
||||||
|
.uri("/wip/v1/observe")
|
||||||
|
.header("content-type", "application/json")
|
||||||
|
.body(Vec::<u8>::new())
|
||||||
|
.unwrap();
|
||||||
|
let error = validate_http_request(&endpoint, Route::Observe, &wrong_method).unwrap_err();
|
||||||
|
assert!(matches!(&error, RequestMetadataError::MethodNotAllowed));
|
||||||
|
assert_eq!(error.status(), StatusCode::METHOD_NOT_ALLOWED);
|
||||||
|
assert_eq!(error.allow(), Some("POST"));
|
||||||
|
|
||||||
|
let wrong_route = Request::builder()
|
||||||
|
.method(Method::POST)
|
||||||
|
.uri("/wip/v1/fetch_interface")
|
||||||
|
.header("content-type", "application/json")
|
||||||
|
.body(Vec::<u8>::new())
|
||||||
|
.unwrap();
|
||||||
|
let error = validate_http_request(&endpoint, Route::Observe, &wrong_route).unwrap_err();
|
||||||
|
assert!(matches!(&error, RequestMetadataError::NotFound));
|
||||||
|
assert_eq!(error.status(), StatusCode::NOT_FOUND);
|
||||||
|
assert_eq!(error.allow(), None);
|
||||||
|
|
||||||
|
let query_and_wrong_method = Request::builder()
|
||||||
|
.method(Method::GET)
|
||||||
|
.uri("/wip/v1/observe?unexpected=true")
|
||||||
|
.header("content-type", "application/json")
|
||||||
|
.body(Vec::<u8>::new())
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
validate_http_request(&endpoint, Route::Observe, &query_and_wrong_method).unwrap_err(),
|
||||||
|
RequestMetadataError::NotFound
|
||||||
|
));
|
||||||
|
|
||||||
|
for accept in [
|
||||||
|
"text/plain, */*;q=1, application/json;q=0",
|
||||||
|
"application/json; charset=utf-16",
|
||||||
|
"application/json; profile=future",
|
||||||
|
] {
|
||||||
|
let incompatible_accept = Request::builder()
|
||||||
|
.method(Method::POST)
|
||||||
|
.uri("/wip/v1/observe")
|
||||||
|
.header("content-type", "application/json")
|
||||||
|
.header("accept", accept)
|
||||||
|
.body(Vec::<u8>::new())
|
||||||
|
.unwrap();
|
||||||
|
let error =
|
||||||
|
validate_http_request(&endpoint, Route::Observe, &incompatible_accept).unwrap_err();
|
||||||
|
assert!(matches!(&error, RequestMetadataError::NotAcceptable));
|
||||||
|
assert_eq!(error.status(), StatusCode::NOT_ACCEPTABLE);
|
||||||
|
}
|
||||||
|
|
||||||
|
for accept in [
|
||||||
|
"application/json; charset=UTF-8",
|
||||||
|
"application/json; q=1; profile=accept-extension",
|
||||||
|
] {
|
||||||
|
let compatible_accept = Request::builder()
|
||||||
|
.method(Method::POST)
|
||||||
|
.uri("/wip/v1/observe")
|
||||||
|
.header("content-type", "application/json")
|
||||||
|
.header("accept", accept)
|
||||||
|
.body(Vec::<u8>::new())
|
||||||
|
.unwrap();
|
||||||
|
assert!(validate_http_request(&endpoint, Route::Observe, &compatible_accept).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
let unsupported_media_type = Request::builder()
|
||||||
|
.method(Method::POST)
|
||||||
|
.uri("/wip/v1/observe")
|
||||||
|
.header("content-type", "text/plain")
|
||||||
|
.header("accept", "application/json")
|
||||||
|
.body(Vec::<u8>::new())
|
||||||
|
.unwrap();
|
||||||
|
let error =
|
||||||
|
validate_http_request(&endpoint, Route::Observe, &unsupported_media_type).unwrap_err();
|
||||||
|
assert!(matches!(&error, RequestMetadataError::UnsupportedMediaType));
|
||||||
|
assert_eq!(error.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
|
||||||
|
|
||||||
|
for coding in ["gzip", "identity, gzip"] {
|
||||||
|
let unsupported_coding = Request::builder()
|
||||||
|
.method(Method::POST)
|
||||||
|
.uri("/wip/v1/observe")
|
||||||
|
.header("content-type", "application/json")
|
||||||
|
.header("content-encoding", coding)
|
||||||
|
.body(Vec::<u8>::new())
|
||||||
|
.unwrap();
|
||||||
|
let error =
|
||||||
|
validate_http_request(&endpoint, Route::Observe, &unsupported_coding).unwrap_err();
|
||||||
|
assert!(matches!(&error, RequestMetadataError::UnsupportedMediaType));
|
||||||
|
assert_eq!(error.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
|
||||||
|
}
|
||||||
|
|
||||||
|
let identity_coding = Request::builder()
|
||||||
|
.method(Method::POST)
|
||||||
|
.uri("/wip/v1/observe")
|
||||||
|
.header("content-type", "application/json")
|
||||||
|
.header("content-encoding", "identity")
|
||||||
|
.body(Vec::<u8>::new())
|
||||||
|
.unwrap();
|
||||||
|
assert!(validate_http_request(&endpoint, Route::Observe, &identity_coding).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn invalid_endpoint_components_and_non_routes_are_rejected() {
|
||||||
|
assert!(Endpoint::parse("/relative").is_err());
|
||||||
|
assert!(Endpoint::parse("file:///wip").is_err());
|
||||||
|
assert!(Endpoint::parse("https://example.test/wip?q=1").is_err());
|
||||||
|
assert!(Endpoint::parse("https://example.test/wip#fragment").is_err());
|
||||||
|
|
||||||
|
let deployment_endpoint = Endpoint::parse("http://user:secret@example.test/wip").unwrap();
|
||||||
|
assert_eq!(deployment_endpoint.as_url().scheme(), "http");
|
||||||
|
assert_eq!(deployment_endpoint.as_url().username(), "user");
|
||||||
|
|
||||||
|
let endpoint = Endpoint::parse("http://example.test/wip").unwrap();
|
||||||
|
for outside in [
|
||||||
|
"http://example.test/wip/v1/unknown",
|
||||||
|
"http://example.test/wip/v1/batch",
|
||||||
|
"http://example.test/wip/v1/observe/extra",
|
||||||
|
"https://example.test/wip/v1/observe",
|
||||||
|
"http://other.test/wip/v1/observe",
|
||||||
|
] {
|
||||||
|
assert_eq!(
|
||||||
|
endpoint.recognize(&wip_http::url::Url::parse(outside).unwrap()),
|
||||||
|
None
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,570 +0,0 @@
|
|||||||
use std::collections::{BTreeMap, BTreeSet};
|
|
||||||
|
|
||||||
use http::header::{ACCEPT, CONTENT_TYPE};
|
|
||||||
use http::{Method, Request, Response, StatusCode};
|
|
||||||
use serde_json::{Map, Value as Json};
|
|
||||||
use wip_protocol::{
|
|
||||||
FetchInterfaceRequest, FetchInterfaceResponse, INTERFACE_FORMAT_V1, ObserveRequest,
|
|
||||||
ObserveResponse, ProtocolError, ProtocolErrorCode, ProtocolInteraction,
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::response::{self, DecodedResponse};
|
|
||||||
use crate::{
|
|
||||||
BodyKind, ClientResponseError, CodecError, EncodeHttpError, Endpoint, InvalidResponseKind,
|
|
||||||
JSON_CONTENT_TYPE, Limits, ResourceLimitKind, Route, is_json_content_type, json,
|
|
||||||
};
|
|
||||||
|
|
||||||
/// A retrieval method accepted by the standard v1 batch endpoint.
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub enum BatchMethod {
|
|
||||||
/// Observe one object and its indexable descendants.
|
|
||||||
Observe,
|
|
||||||
/// Fetch one interface descriptor.
|
|
||||||
FetchInterface,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl BatchMethod {
|
|
||||||
fn name(self) -> &'static str {
|
|
||||||
match self {
|
|
||||||
Self::Observe => "observe",
|
|
||||||
Self::FetchInterface => "fetch_interface",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn interaction(self) -> ProtocolInteraction {
|
|
||||||
match self {
|
|
||||||
Self::Observe => ProtocolInteraction::Observe,
|
|
||||||
Self::FetchInterface => ProtocolInteraction::FetchInterface,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One retrieval interaction accepted by the standard v1 batch endpoint.
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub enum BatchRequestKind {
|
|
||||||
/// Observe one object and its indexable descendants.
|
|
||||||
Observe(ObserveRequest),
|
|
||||||
/// Fetch one interface descriptor.
|
|
||||||
FetchInterface(FetchInterfaceRequest),
|
|
||||||
/// A known method whose `arguments` are not a valid logical request.
|
|
||||||
Invalid {
|
|
||||||
/// Method that was successfully identified from the item envelope.
|
|
||||||
method: BatchMethod,
|
|
||||||
/// Item-local `invalid_request` to return without rejecting other items.
|
|
||||||
error: ProtocolError,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
impl BatchRequestKind {
|
|
||||||
fn interaction(&self) -> ProtocolInteraction {
|
|
||||||
match self {
|
|
||||||
Self::Observe(_) => ProtocolInteraction::Observe,
|
|
||||||
Self::FetchInterface(_) => ProtocolInteraction::FetchInterface,
|
|
||||||
Self::Invalid { method, .. } => method.interaction(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One uniquely identified batch subrequest.
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub struct BatchRequestItem {
|
|
||||||
/// Identifier used only to correlate the corresponding subresponse.
|
|
||||||
pub id: String,
|
|
||||||
/// Retrieval interaction and arguments.
|
|
||||||
pub request: BatchRequestKind,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A standard v1 batch request.
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub struct BatchRequest {
|
|
||||||
/// Independent subrequests. Identifiers must be unique.
|
|
||||||
pub requests: Vec<BatchRequestItem>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Successful result of one batch item.
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
|
||||||
pub enum BatchSuccess {
|
|
||||||
/// Successful `observe` result.
|
|
||||||
Observe(ObserveResponse),
|
|
||||||
/// Successful `fetch_interface` result.
|
|
||||||
FetchInterface(FetchInterfaceResponse),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One batch subresponse, correlated by `id` rather than array position.
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
|
||||||
pub struct BatchResponseItem {
|
|
||||||
/// Identifier copied from its subrequest.
|
|
||||||
pub id: String,
|
|
||||||
/// Direct interaction result or canonical item-local protocol failure.
|
|
||||||
pub outcome: Result<BatchSuccess, ProtocolError>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A valid standard v1 batch response.
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
|
||||||
pub struct BatchResponse {
|
|
||||||
/// Exactly one response for each requested identifier, in any order.
|
|
||||||
pub responses: Vec<BatchResponseItem>,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn validate_ids<'a>(ids: impl Iterator<Item = &'a str>, maximum: usize) -> Result<(), CodecError> {
|
|
||||||
let mut seen = BTreeSet::new();
|
|
||||||
let mut count = 0;
|
|
||||||
for id in ids {
|
|
||||||
count += 1;
|
|
||||||
if !seen.insert(id) {
|
|
||||||
return Err(CodecError::DuplicateBatchId { id: id.into() });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if count > maximum {
|
|
||||||
return Err(CodecError::TooManyBatchItems {
|
|
||||||
actual: count,
|
|
||||||
maximum,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn request_item_to_json(item: &BatchRequestItem) -> Result<Json, CodecError> {
|
|
||||||
let (method, arguments) = match &item.request {
|
|
||||||
BatchRequestKind::Observe(value) => ("observe", json::observe_request_to_json(value)),
|
|
||||||
BatchRequestKind::FetchInterface(value) => (
|
|
||||||
"fetch_interface",
|
|
||||||
json::fetch_interface_request_to_json(value),
|
|
||||||
),
|
|
||||||
BatchRequestKind::Invalid { .. } => {
|
|
||||||
return Err(CodecError::InvalidField {
|
|
||||||
field: "requests".into(),
|
|
||||||
reason: "item-local invalid requests cannot be encoded as client requests".into(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
Ok(serde_json::json!({"id": item.id, "method": method, "arguments": arguments}))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn request_to_json(request: &BatchRequest, limits: Limits) -> Result<Json, CodecError> {
|
|
||||||
validate_ids(
|
|
||||||
request.requests.iter().map(|item| item.id.as_str()),
|
|
||||||
limits.max_batch_items,
|
|
||||||
)?;
|
|
||||||
for item in &request.requests {
|
|
||||||
match &item.request {
|
|
||||||
BatchRequestKind::Observe(value) => value.validate()?,
|
|
||||||
BatchRequestKind::FetchInterface(_) | BatchRequestKind::Invalid { .. } => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let requests = request
|
|
||||||
.requests
|
|
||||||
.iter()
|
|
||||||
.map(request_item_to_json)
|
|
||||||
.collect::<Result<Vec<_>, _>>()?;
|
|
||||||
Ok(serde_json::json!({"requests": requests}))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn request_from_json(value: &Json, limits: Limits) -> Result<BatchRequest, CodecError> {
|
|
||||||
let fields = exact_object(value, "batch", &["requests"])?;
|
|
||||||
let values = array(required(fields, "requests")?, "requests")?;
|
|
||||||
if values.len() > limits.max_batch_items {
|
|
||||||
return Err(CodecError::TooManyBatchItems {
|
|
||||||
actual: values.len(),
|
|
||||||
maximum: limits.max_batch_items,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
let mut requests = Vec::with_capacity(values.len());
|
|
||||||
for (index, value) in values.iter().enumerate() {
|
|
||||||
let field = format!("requests[{index}]");
|
|
||||||
let fields = exact_object(value, &field, &["id", "method", "arguments"])?;
|
|
||||||
let id = string(required(fields, "id")?, &format!("{field}.id"))?;
|
|
||||||
let method_name = string(required(fields, "method")?, &format!("{field}.method"))?;
|
|
||||||
let arguments = required(fields, "arguments")?;
|
|
||||||
let method = match method_name.as_str() {
|
|
||||||
"observe" => BatchMethod::Observe,
|
|
||||||
"fetch_interface" => BatchMethod::FetchInterface,
|
|
||||||
_ => {
|
|
||||||
return Err(CodecError::InvalidField {
|
|
||||||
field: format!("{field}.method"),
|
|
||||||
reason: "batch supports only observe and fetch_interface".into(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let decoded = match method {
|
|
||||||
BatchMethod::Observe => {
|
|
||||||
json::observe_request_from_json(arguments).map(BatchRequestKind::Observe)
|
|
||||||
}
|
|
||||||
BatchMethod::FetchInterface => json::fetch_interface_request_from_json(arguments)
|
|
||||||
.map(BatchRequestKind::FetchInterface),
|
|
||||||
};
|
|
||||||
let request = decoded.unwrap_or_else(|error| BatchRequestKind::Invalid {
|
|
||||||
method,
|
|
||||||
error: ProtocolError {
|
|
||||||
code: ProtocolErrorCode::InvalidRequest,
|
|
||||||
message: format!("invalid {} arguments: {error}", method.name()),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
requests.push(BatchRequestItem { id, request });
|
|
||||||
}
|
|
||||||
validate_ids(
|
|
||||||
requests.iter().map(|item| item.id.as_str()),
|
|
||||||
limits.max_batch_items,
|
|
||||||
)?;
|
|
||||||
Ok(BatchRequest { requests })
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Encodes a batch request using `POST v1/batch`.
|
|
||||||
pub fn encode_batch_request(
|
|
||||||
endpoint: &Endpoint,
|
|
||||||
value: &BatchRequest,
|
|
||||||
limits: Limits,
|
|
||||||
) -> Result<Request<Vec<u8>>, EncodeHttpError> {
|
|
||||||
let body = json::serialize(&request_to_json(value, limits)?, BodyKind::Request, limits)?;
|
|
||||||
Ok(Request::builder()
|
|
||||||
.method(Method::POST)
|
|
||||||
.uri(endpoint.route(Route::Batch).as_str())
|
|
||||||
.header(CONTENT_TYPE, JSON_CONTENT_TYPE)
|
|
||||||
.header(ACCEPT, "application/json")
|
|
||||||
.body(body)?)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Decodes and validates a batch request body.
|
|
||||||
pub fn decode_batch_request(body: &[u8], limits: Limits) -> Result<BatchRequest, CodecError> {
|
|
||||||
let value = json::parse(body, BodyKind::Request, limits)?;
|
|
||||||
request_from_json(&value, limits)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn success_to_json(success: &BatchSuccess) -> Json {
|
|
||||||
match success {
|
|
||||||
BatchSuccess::Observe(value) => json::observe_response_to_json(value),
|
|
||||||
BatchSuccess::FetchInterface(value) => json::fetch_interface_response_to_json(value),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn response_to_json(
|
|
||||||
request: &BatchRequest,
|
|
||||||
response: &BatchResponse,
|
|
||||||
limits: Limits,
|
|
||||||
) -> Result<Json, CodecError> {
|
|
||||||
correlate(request, response, limits)?;
|
|
||||||
Ok(serde_json::json!({
|
|
||||||
"responses": response.responses.iter().map(|item| {
|
|
||||||
let mut fields = Map::new();
|
|
||||||
fields.insert("id".into(), Json::String(item.id.clone()));
|
|
||||||
match &item.outcome {
|
|
||||||
Ok(success) => { fields.insert("result".into(), success_to_json(success)); }
|
|
||||||
Err(error) => { fields.insert("error".into(), response::item_error_to_json(error)); }
|
|
||||||
}
|
|
||||||
Json::Object(fields)
|
|
||||||
}).collect::<Vec<_>>()
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn correlate(
|
|
||||||
request: &BatchRequest,
|
|
||||||
response: &BatchResponse,
|
|
||||||
limits: Limits,
|
|
||||||
) -> Result<(), CodecError> {
|
|
||||||
validate_ids(
|
|
||||||
request.requests.iter().map(|item| item.id.as_str()),
|
|
||||||
limits.max_batch_items,
|
|
||||||
)?;
|
|
||||||
validate_ids(
|
|
||||||
response.responses.iter().map(|item| item.id.as_str()),
|
|
||||||
limits.max_batch_items,
|
|
||||||
)?;
|
|
||||||
let requested: BTreeMap<&str, &BatchRequestKind> = request
|
|
||||||
.requests
|
|
||||||
.iter()
|
|
||||||
.map(|item| (item.id.as_str(), &item.request))
|
|
||||||
.collect();
|
|
||||||
for item in &response.responses {
|
|
||||||
let Some(kind) = requested.get(item.id.as_str()) else {
|
|
||||||
return Err(CodecError::UnexpectedBatchId {
|
|
||||||
id: item.id.clone(),
|
|
||||||
});
|
|
||||||
};
|
|
||||||
match (&item.outcome, *kind) {
|
|
||||||
(Ok(BatchSuccess::Observe(value)), BatchRequestKind::Observe(request)) => {
|
|
||||||
request.validate_response(value)?;
|
|
||||||
}
|
|
||||||
(
|
|
||||||
Ok(BatchSuccess::FetchInterface(value)),
|
|
||||||
BatchRequestKind::FetchInterface(request),
|
|
||||||
) => {
|
|
||||||
value.validate_for(request)?;
|
|
||||||
}
|
|
||||||
(
|
|
||||||
Err(error),
|
|
||||||
BatchRequestKind::Invalid {
|
|
||||||
error: expected, ..
|
|
||||||
},
|
|
||||||
) if error == expected => {}
|
|
||||||
(Err(error), kind)
|
|
||||||
if !matches!(kind, BatchRequestKind::Invalid { .. })
|
|
||||||
&& error.code.is_allowed_for(kind.interaction()) => {}
|
|
||||||
_ => {
|
|
||||||
return Err(CodecError::BatchInteractionMismatch {
|
|
||||||
id: item.id.clone(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for item in &request.requests {
|
|
||||||
if !response.responses.iter().any(|other| other.id == item.id) {
|
|
||||||
return Err(CodecError::MissingBatchId {
|
|
||||||
id: item.id.clone(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Encodes a valid batch response. Item failures remain inside HTTP 200.
|
|
||||||
pub fn encode_batch_response(
|
|
||||||
request: &BatchRequest,
|
|
||||||
value: &BatchResponse,
|
|
||||||
limits: Limits,
|
|
||||||
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
|
||||||
let body = json::serialize(
|
|
||||||
&response_to_json(request, value, limits)?,
|
|
||||||
BodyKind::Response,
|
|
||||||
limits,
|
|
||||||
)?;
|
|
||||||
Ok(Response::builder()
|
|
||||||
.status(StatusCode::OK)
|
|
||||||
.header(CONTENT_TYPE, JSON_CONTENT_TYPE)
|
|
||||||
.body(body)?)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Encodes a top-level batch-envelope failure.
|
|
||||||
///
|
|
||||||
/// Item-local failures belong in [`BatchResponseItem`]. Only failures that can
|
|
||||||
/// reject the batch envelope before item execution are accepted here. A
|
|
||||||
/// resource-limit failure defaults to the logical-limit status; use
|
|
||||||
/// [`encode_batch_resource_limit_error_response`] when the concrete class is
|
|
||||||
/// known.
|
|
||||||
pub fn encode_batch_error_response(
|
|
||||||
error: &ProtocolError,
|
|
||||||
limits: Limits,
|
|
||||||
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
|
||||||
if !matches!(
|
|
||||||
error.code,
|
|
||||||
ProtocolErrorCode::InvalidRequest
|
|
||||||
| ProtocolErrorCode::ResourceLimitExceeded
|
|
||||||
| ProtocolErrorCode::Internal
|
|
||||||
) {
|
|
||||||
return Err(CodecError::InvalidField {
|
|
||||||
field: "error.code".into(),
|
|
||||||
reason: "code is not valid for a top-level batch failure".into(),
|
|
||||||
}
|
|
||||||
.into());
|
|
||||||
}
|
|
||||||
let body = json::serialize(&response::error_to_json(error), BodyKind::Response, limits)?;
|
|
||||||
Ok(Response::builder()
|
|
||||||
.status(response::status_for_error(error.code))
|
|
||||||
.header(CONTENT_TYPE, JSON_CONTENT_TYPE)
|
|
||||||
.body(body)?)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Encodes a class-specific top-level batch `resource_limit_exceeded` failure.
|
|
||||||
pub fn encode_batch_resource_limit_error_response(
|
|
||||||
error: &ProtocolError,
|
|
||||||
kind: ResourceLimitKind,
|
|
||||||
limits: Limits,
|
|
||||||
) -> Result<Response<Vec<u8>>, EncodeHttpError> {
|
|
||||||
if error.code != ProtocolErrorCode::ResourceLimitExceeded {
|
|
||||||
return Err(CodecError::InvalidField {
|
|
||||||
field: "error.code".into(),
|
|
||||||
reason: "resource-limit encoder requires resource_limit_exceeded".into(),
|
|
||||||
}
|
|
||||||
.into());
|
|
||||||
}
|
|
||||||
let body = json::serialize(&response::error_to_json(error), BodyKind::Response, limits)?;
|
|
||||||
Ok(Response::builder()
|
|
||||||
.status(response::status_for_resource_limit(kind))
|
|
||||||
.header(CONTENT_TYPE, JSON_CONTENT_TYPE)
|
|
||||||
.body(body)?)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn response_from_json(
|
|
||||||
value: &Json,
|
|
||||||
request: &BatchRequest,
|
|
||||||
limits: Limits,
|
|
||||||
) -> Result<BatchResponse, CodecError> {
|
|
||||||
let fields = exact_object(value, "batch", &["responses"])?;
|
|
||||||
let values = array(required(fields, "responses")?, "responses")?;
|
|
||||||
if values.len() > limits.max_batch_items {
|
|
||||||
return Err(CodecError::TooManyBatchItems {
|
|
||||||
actual: values.len(),
|
|
||||||
maximum: limits.max_batch_items,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
let requested: BTreeMap<&str, &BatchRequestKind> = request
|
|
||||||
.requests
|
|
||||||
.iter()
|
|
||||||
.map(|item| (item.id.as_str(), &item.request))
|
|
||||||
.collect();
|
|
||||||
let mut responses = Vec::with_capacity(values.len());
|
|
||||||
for (index, value) in values.iter().enumerate() {
|
|
||||||
let field = format!("responses[{index}]");
|
|
||||||
let fields = object(value, &field)?;
|
|
||||||
for name in fields.keys() {
|
|
||||||
if !["id", "result", "error"].contains(&name.as_str()) {
|
|
||||||
return Err(CodecError::UnknownField {
|
|
||||||
field: format!("{field}.{name}"),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let id = string(required(fields, "id")?, &format!("{field}.id"))?;
|
|
||||||
let Some(kind) = requested.get(id.as_str()) else {
|
|
||||||
return Err(CodecError::UnexpectedBatchId { id });
|
|
||||||
};
|
|
||||||
let outcome = match (fields.get("result"), fields.get("error")) {
|
|
||||||
(Some(_), Some(_)) | (None, None) => {
|
|
||||||
return Err(CodecError::InvalidField {
|
|
||||||
field,
|
|
||||||
reason: "batch item must contain exactly one of result or error".into(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
(None, Some(error)) => {
|
|
||||||
let error = response::item_error_from_json(error)?;
|
|
||||||
match kind {
|
|
||||||
BatchRequestKind::Invalid {
|
|
||||||
error: expected, ..
|
|
||||||
} if error == *expected => {}
|
|
||||||
BatchRequestKind::Invalid { .. } => {
|
|
||||||
return Err(CodecError::BatchInteractionMismatch { id });
|
|
||||||
}
|
|
||||||
kind if error.code.is_allowed_for(kind.interaction()) => {}
|
|
||||||
_ => return Err(CodecError::BatchInteractionMismatch { id }),
|
|
||||||
}
|
|
||||||
Err(error)
|
|
||||||
}
|
|
||||||
(Some(result), None) => Ok(match kind {
|
|
||||||
BatchRequestKind::Observe(request) => {
|
|
||||||
let value = json::observe_response_from_json(result)?;
|
|
||||||
request.validate_response(&value)?;
|
|
||||||
BatchSuccess::Observe(value)
|
|
||||||
}
|
|
||||||
BatchRequestKind::FetchInterface(request) => {
|
|
||||||
let value = json::fetch_interface_response_from_json(result)?;
|
|
||||||
value.validate_for(request)?;
|
|
||||||
BatchSuccess::FetchInterface(value)
|
|
||||||
}
|
|
||||||
BatchRequestKind::Invalid { .. } => {
|
|
||||||
return Err(CodecError::BatchInteractionMismatch { id });
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
responses.push(BatchResponseItem { id, outcome });
|
|
||||||
}
|
|
||||||
let response = BatchResponse { responses };
|
|
||||||
correlate(request, &response, limits)?;
|
|
||||||
Ok(response)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Decodes a batch response, including item-local failures within HTTP 200.
|
|
||||||
pub fn decode_batch_response<B: AsRef<[u8]>>(
|
|
||||||
request: &BatchRequest,
|
|
||||||
value: &Response<B>,
|
|
||||||
limits: Limits,
|
|
||||||
) -> Result<DecodedResponse<BatchResponse>, ClientResponseError> {
|
|
||||||
let valid_content_type = value
|
|
||||||
.headers()
|
|
||||||
.get(CONTENT_TYPE)
|
|
||||||
.and_then(|value| value.to_str().ok())
|
|
||||||
.is_some_and(is_json_content_type);
|
|
||||||
if !valid_content_type {
|
|
||||||
if value.status().is_success() {
|
|
||||||
return Err(ClientResponseError::invalid(
|
|
||||||
InvalidResponseKind::InvalidBatch,
|
|
||||||
"missing or non-UTF-8 application/json Content-Type",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
return Err(response::transport_failure(value.status()));
|
|
||||||
}
|
|
||||||
let decoded = response::decode(
|
|
||||||
value.status(),
|
|
||||||
value.body().as_ref(),
|
|
||||||
ProtocolInteraction::Observe,
|
|
||||||
limits,
|
|
||||||
|json| response_from_json(json, request, limits),
|
|
||||||
)
|
|
||||||
.map_err(|error| match error {
|
|
||||||
ClientResponseError::InvalidResponse { detail, .. } => {
|
|
||||||
ClientResponseError::invalid(InvalidResponseKind::InvalidBatch, detail)
|
|
||||||
}
|
|
||||||
other => other,
|
|
||||||
})?;
|
|
||||||
if let DecodedResponse::ProtocolFailure { error, .. } = &decoded
|
|
||||||
&& !matches!(
|
|
||||||
error.code,
|
|
||||||
ProtocolErrorCode::InvalidRequest
|
|
||||||
| ProtocolErrorCode::ResourceLimitExceeded
|
|
||||||
| ProtocolErrorCode::Internal
|
|
||||||
)
|
|
||||||
{
|
|
||||||
return Err(ClientResponseError::invalid(
|
|
||||||
InvalidResponseKind::InvalidBatch,
|
|
||||||
"protocol code is not valid for a top-level batch failure",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
if let DecodedResponse::Success(success) = &decoded {
|
|
||||||
for item in &success.responses {
|
|
||||||
if let Ok(BatchSuccess::FetchInterface(interface)) = &item.outcome
|
|
||||||
&& interface.descriptor.format != INTERFACE_FORMAT_V1
|
|
||||||
{
|
|
||||||
return Err(ClientResponseError::UnsupportedDescriptorFormat {
|
|
||||||
format: interface.descriptor.format.clone(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(decoded)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn object<'a>(value: &'a Json, field: &str) -> Result<&'a Map<String, Json>, CodecError> {
|
|
||||||
value.as_object().ok_or_else(|| CodecError::InvalidField {
|
|
||||||
field: field.into(),
|
|
||||||
reason: "expected object".into(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn exact_object<'a>(
|
|
||||||
value: &'a Json,
|
|
||||||
field: &str,
|
|
||||||
allowed: &[&str],
|
|
||||||
) -> Result<&'a Map<String, Json>, CodecError> {
|
|
||||||
let fields = object(value, field)?;
|
|
||||||
for name in fields.keys() {
|
|
||||||
if !allowed.contains(&name.as_str()) {
|
|
||||||
return Err(CodecError::UnknownField {
|
|
||||||
field: format!("{field}.{name}"),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(fields)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn required<'a>(fields: &'a Map<String, Json>, name: &str) -> Result<&'a Json, CodecError> {
|
|
||||||
fields
|
|
||||||
.get(name)
|
|
||||||
.ok_or_else(|| CodecError::MissingField { field: name.into() })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn string(value: &Json, field: &str) -> Result<String, CodecError> {
|
|
||||||
value
|
|
||||||
.as_str()
|
|
||||||
.map(str::to_owned)
|
|
||||||
.ok_or_else(|| CodecError::InvalidField {
|
|
||||||
field: field.into(),
|
|
||||||
reason: "expected string".into(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn array<'a>(value: &'a Json, field: &str) -> Result<&'a [Json], CodecError> {
|
|
||||||
value
|
|
||||||
.as_array()
|
|
||||||
.map(Vec::as_slice)
|
|
||||||
.ok_or_else(|| CodecError::InvalidField {
|
|
||||||
field: field.into(),
|
|
||||||
reason: "expected array".into(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,345 +0,0 @@
|
|||||||
use wip_https::http::StatusCode;
|
|
||||||
use wip_https::wip_protocol::{
|
|
||||||
FetchInterfaceRequest, FetchInterfaceResponse, INTERFACE_FORMAT_V1, InterfaceDescriptor,
|
|
||||||
Object, ObjectObservation, ObserveRequest, ProtocolError, ProtocolErrorCode,
|
|
||||||
};
|
|
||||||
use wip_https::{
|
|
||||||
BatchMethod, BatchRequest, BatchRequestItem, BatchRequestKind, BatchResponse,
|
|
||||||
BatchResponseItem, BatchSuccess, ClientResponseError, DecodedResponse, Endpoint,
|
|
||||||
InvalidResponseKind, Limits, ResourceLimitKind, decode_batch_request, decode_batch_response,
|
|
||||||
encode_batch_error_response, encode_batch_request, encode_batch_resource_limit_error_response,
|
|
||||||
encode_batch_response,
|
|
||||||
};
|
|
||||||
|
|
||||||
fn limits() -> Limits {
|
|
||||||
Limits::new(100_000, 100_000, 64, 4).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn observed_item(validator: Option<Vec<u8>>) -> ObjectObservation {
|
|
||||||
ObjectObservation {
|
|
||||||
object: Object {
|
|
||||||
name: "item".into(),
|
|
||||||
description: None,
|
|
||||||
interfaces: vec![],
|
|
||||||
r#ref: None,
|
|
||||||
validator,
|
|
||||||
},
|
|
||||||
children: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn request() -> BatchRequest {
|
|
||||||
BatchRequest {
|
|
||||||
requests: vec![
|
|
||||||
BatchRequestItem {
|
|
||||||
id: "object".into(),
|
|
||||||
request: BatchRequestKind::Observe(ObserveRequest {
|
|
||||||
path: "/item".into(),
|
|
||||||
depth: 0,
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
BatchRequestItem {
|
|
||||||
id: "interface".into(),
|
|
||||||
request: BatchRequestKind::FetchInterface(FetchInterfaceRequest {
|
|
||||||
interface: "interface-v1".into(),
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn batch_round_trips_by_unique_id_with_item_failures_and_validators() {
|
|
||||||
let request = request();
|
|
||||||
let endpoint = Endpoint::parse("https://example.test/wip").unwrap();
|
|
||||||
let encoded_request = encode_batch_request(&endpoint, &request, limits()).unwrap();
|
|
||||||
assert_eq!(encoded_request.uri().path(), "/wip/v1/batch");
|
|
||||||
assert_eq!(encoded_request.headers()["accept"], "application/json");
|
|
||||||
assert_eq!(
|
|
||||||
decode_batch_request(encoded_request.body(), limits()).unwrap(),
|
|
||||||
request
|
|
||||||
);
|
|
||||||
|
|
||||||
let response = BatchResponse {
|
|
||||||
responses: vec![
|
|
||||||
BatchResponseItem {
|
|
||||||
id: "interface".into(),
|
|
||||||
outcome: Err(ProtocolError {
|
|
||||||
code: ProtocolErrorCode::InterfaceNotFound,
|
|
||||||
message: "gone".into(),
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
BatchResponseItem {
|
|
||||||
id: "object".into(),
|
|
||||||
outcome: Ok(BatchSuccess::Observe(observed_item(Some(vec![
|
|
||||||
0, 1, 2, 255,
|
|
||||||
])))),
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
let encoded = encode_batch_response(&request, &response, limits()).unwrap();
|
|
||||||
assert_eq!(encoded.status(), StatusCode::OK);
|
|
||||||
assert!(
|
|
||||||
std::str::from_utf8(encoded.body())
|
|
||||||
.unwrap()
|
|
||||||
.contains("AAEC/w==")
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
decode_batch_response(&request, &encoded, limits()).unwrap(),
|
|
||||||
DecodedResponse::Success(response)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn batch_interface_validator_round_trips_in_item_body() {
|
|
||||||
let request = BatchRequest {
|
|
||||||
requests: vec![BatchRequestItem {
|
|
||||||
id: "interface".into(),
|
|
||||||
request: BatchRequestKind::FetchInterface(FetchInterfaceRequest {
|
|
||||||
interface: "interface-v1".into(),
|
|
||||||
}),
|
|
||||||
}],
|
|
||||||
};
|
|
||||||
let response = BatchResponse {
|
|
||||||
responses: vec![BatchResponseItem {
|
|
||||||
id: "interface".into(),
|
|
||||||
outcome: Ok(BatchSuccess::FetchInterface(FetchInterfaceResponse {
|
|
||||||
interface: "interface-v1".into(),
|
|
||||||
descriptor: InterfaceDescriptor {
|
|
||||||
format: INTERFACE_FORMAT_V1.into(),
|
|
||||||
documentation: None,
|
|
||||||
types: vec![],
|
|
||||||
operations: vec![],
|
|
||||||
},
|
|
||||||
validator: Some(vec![255, 254, 253]),
|
|
||||||
})),
|
|
||||||
}],
|
|
||||||
};
|
|
||||||
let encoded = encode_batch_response(&request, &response, limits()).unwrap();
|
|
||||||
assert!(
|
|
||||||
std::str::from_utf8(encoded.body())
|
|
||||||
.unwrap()
|
|
||||||
.contains("//79")
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
decode_batch_response(&request, &encoded, limits()).unwrap(),
|
|
||||||
DecodedResponse::Success(response)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn malformed_known_method_arguments_are_item_local() {
|
|
||||||
let body = br#"{
|
|
||||||
"requests": [
|
|
||||||
{"id":"valid","method":"observe","arguments":{"path":"/item","depth":0}},
|
|
||||||
{"id":"invalid","method":"observe","arguments":{"path":"/","depth":"deep"}}
|
|
||||||
]
|
|
||||||
}"#;
|
|
||||||
let decoded = decode_batch_request(body, limits()).unwrap();
|
|
||||||
assert!(matches!(
|
|
||||||
decoded.requests[0].request,
|
|
||||||
BatchRequestKind::Observe(_)
|
|
||||||
));
|
|
||||||
let invalid = match &decoded.requests[1].request {
|
|
||||||
BatchRequestKind::Invalid { method, error } => {
|
|
||||||
assert_eq!(*method, BatchMethod::Observe);
|
|
||||||
assert_eq!(error.code, ProtocolErrorCode::InvalidRequest);
|
|
||||||
error.clone()
|
|
||||||
}
|
|
||||||
other => panic!("expected item-local invalid request, got {other:?}"),
|
|
||||||
};
|
|
||||||
|
|
||||||
let response = BatchResponse {
|
|
||||||
responses: vec![
|
|
||||||
BatchResponseItem {
|
|
||||||
id: "valid".into(),
|
|
||||||
outcome: Ok(BatchSuccess::Observe(observed_item(None))),
|
|
||||||
},
|
|
||||||
BatchResponseItem {
|
|
||||||
id: "invalid".into(),
|
|
||||||
outcome: Err(invalid),
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
let encoded = encode_batch_response(&decoded, &response, limits()).unwrap();
|
|
||||||
assert_eq!(encoded.status(), StatusCode::OK);
|
|
||||||
assert_eq!(
|
|
||||||
decode_batch_response(&decoded, &encoded, limits()).unwrap(),
|
|
||||||
DecodedResponse::Success(response)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn invalid_batch_envelopes_are_rejected_at_top_level() {
|
|
||||||
assert!(decode_batch_request(br#"{}"#, limits()).is_err());
|
|
||||||
|
|
||||||
let malformed_item = br#"{
|
|
||||||
"requests": [
|
|
||||||
{"id":"item","method":"observe","arguments":{"path":"/","depth":0},"extra":true}
|
|
||||||
]
|
|
||||||
}"#;
|
|
||||||
assert!(decode_batch_request(malformed_item, limits()).is_err());
|
|
||||||
|
|
||||||
let duplicate = br#"{
|
|
||||||
"requests": [
|
|
||||||
{"id":"same","method":"observe","arguments":{"path":"/a","depth":0}},
|
|
||||||
{"id":"same","method":"observe","arguments":{"path":"/b","depth":0}}
|
|
||||||
]
|
|
||||||
}"#;
|
|
||||||
assert!(decode_batch_request(duplicate, limits()).is_err());
|
|
||||||
|
|
||||||
let operation = br#"{
|
|
||||||
"requests": [
|
|
||||||
{"id":"call","method":"call_operation","arguments":{}}
|
|
||||||
]
|
|
||||||
}"#;
|
|
||||||
assert!(decode_batch_request(operation, limits()).is_err());
|
|
||||||
|
|
||||||
let too_many = Limits::new(100_000, 100_000, 64, 1).unwrap();
|
|
||||||
assert!(decode_batch_request(duplicate, too_many).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn batch_resource_limits_use_413_or_422_and_never_429() {
|
|
||||||
let error = ProtocolError {
|
|
||||||
code: ProtocolErrorCode::ResourceLimitExceeded,
|
|
||||||
message: "bounded".into(),
|
|
||||||
};
|
|
||||||
for (kind, status) in [
|
|
||||||
(
|
|
||||||
ResourceLimitKind::RepresentationBytes,
|
|
||||||
StatusCode::PAYLOAD_TOO_LARGE,
|
|
||||||
),
|
|
||||||
(ResourceLimitKind::Logical, StatusCode::UNPROCESSABLE_ENTITY),
|
|
||||||
] {
|
|
||||||
let encoded = encode_batch_resource_limit_error_response(&error, kind, limits()).unwrap();
|
|
||||||
assert_eq!(encoded.status(), status);
|
|
||||||
assert_ne!(encoded.status(), StatusCode::TOO_MANY_REQUESTS);
|
|
||||||
assert_eq!(
|
|
||||||
decode_batch_response(&request(), &encoded, limits()).unwrap(),
|
|
||||||
DecodedResponse::ProtocolFailure {
|
|
||||||
error: error.clone(),
|
|
||||||
status_mismatch: None,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn batch_success_body_requires_exactly_http_200() {
|
|
||||||
let request = request();
|
|
||||||
let response = BatchResponse {
|
|
||||||
responses: vec![
|
|
||||||
BatchResponseItem {
|
|
||||||
id: "object".into(),
|
|
||||||
outcome: Ok(BatchSuccess::Observe(observed_item(None))),
|
|
||||||
},
|
|
||||||
BatchResponseItem {
|
|
||||||
id: "interface".into(),
|
|
||||||
outcome: Err(ProtocolError {
|
|
||||||
code: ProtocolErrorCode::InterfaceNotFound,
|
|
||||||
message: "gone".into(),
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
let encoded = encode_batch_response(&request, &response, limits()).unwrap();
|
|
||||||
for status in [StatusCode::CREATED, StatusCode::ACCEPTED] {
|
|
||||||
let mut noncanonical = encoded.clone();
|
|
||||||
*noncanonical.status_mut() = status;
|
|
||||||
assert!(matches!(
|
|
||||||
decode_batch_response(&request, &noncanonical, limits()).unwrap_err(),
|
|
||||||
ClientResponseError::InvalidResponse { .. }
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn top_level_batch_errors_use_the_batch_allowed_code_set() {
|
|
||||||
let invalid = ProtocolError {
|
|
||||||
code: ProtocolErrorCode::InvalidRequest,
|
|
||||||
message: "bad envelope".into(),
|
|
||||||
};
|
|
||||||
let encoded = encode_batch_error_response(&invalid, limits()).unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
decode_batch_response(&request(), &encoded, limits()).unwrap(),
|
|
||||||
DecodedResponse::ProtocolFailure {
|
|
||||||
error: invalid,
|
|
||||||
status_mismatch: None,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
let not_found = wip_https::http::Response::builder()
|
|
||||||
.status(StatusCode::NOT_FOUND)
|
|
||||||
.header("content-type", "application/json; charset=utf-8")
|
|
||||||
.body(br#"{"error":{"code":"not_found","message":"not a batch failure"}}"#.to_vec())
|
|
||||||
.unwrap();
|
|
||||||
assert!(matches!(
|
|
||||||
decode_batch_response(&request(), ¬_found, limits()).unwrap_err(),
|
|
||||||
ClientResponseError::InvalidResponse {
|
|
||||||
kind: InvalidResponseKind::InvalidBatch,
|
|
||||||
..
|
|
||||||
}
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn unsupported_batch_descriptor_waits_for_envelope_correlation() {
|
|
||||||
let duplicate = wip_https::http::Response::builder()
|
|
||||||
.status(StatusCode::OK)
|
|
||||||
.header("content-type", "application/json; charset=utf-8")
|
|
||||||
.body(
|
|
||||||
br#"{"responses":[{"id":"interface","result":{"interface":"interface-v1","descriptor":{"format":"wip-interface/2","future":true}}},{"id":"interface","result":{"interface":"interface-v1","descriptor":{"format":"wip-interface/2"}}}]}"#
|
|
||||||
.to_vec(),
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
assert!(matches!(
|
|
||||||
decode_batch_response(&request(), &duplicate, limits()).unwrap_err(),
|
|
||||||
ClientResponseError::InvalidResponse {
|
|
||||||
kind: InvalidResponseKind::InvalidBatch,
|
|
||||||
..
|
|
||||||
}
|
|
||||||
));
|
|
||||||
|
|
||||||
let missing = wip_https::http::Response::builder()
|
|
||||||
.status(StatusCode::OK)
|
|
||||||
.header("content-type", "application/json; charset=utf-8")
|
|
||||||
.body(
|
|
||||||
br#"{"responses":[{"id":"interface","result":{"interface":"interface-v1","descriptor":{"format":"wip-interface/2"}}}]}"#
|
|
||||||
.to_vec(),
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
assert!(matches!(
|
|
||||||
decode_batch_response(&request(), &missing, limits()).unwrap_err(),
|
|
||||||
ClientResponseError::InvalidResponse {
|
|
||||||
kind: InvalidResponseKind::InvalidBatch,
|
|
||||||
..
|
|
||||||
}
|
|
||||||
));
|
|
||||||
|
|
||||||
let request = BatchRequest {
|
|
||||||
requests: vec![BatchRequestItem {
|
|
||||||
id: "interface".into(),
|
|
||||||
request: BatchRequestKind::FetchInterface(FetchInterfaceRequest {
|
|
||||||
interface: "interface-v1".into(),
|
|
||||||
}),
|
|
||||||
}],
|
|
||||||
};
|
|
||||||
assert!(matches!(
|
|
||||||
decode_batch_response(&request, &missing, limits()).unwrap_err(),
|
|
||||||
ClientResponseError::UnsupportedDescriptorFormat { format }
|
|
||||||
if format == "wip-interface/2"
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn batch_response_must_have_exactly_the_requested_ids() {
|
|
||||||
let request = request();
|
|
||||||
let missing = BatchResponse {
|
|
||||||
responses: vec![BatchResponseItem {
|
|
||||||
id: "object".into(),
|
|
||||||
outcome: Ok(BatchSuccess::Observe(observed_item(None))),
|
|
||||||
}],
|
|
||||||
};
|
|
||||||
assert!(encode_batch_response(&request, &missing, limits()).is_err());
|
|
||||||
}
|
|
||||||
@@ -1,126 +0,0 @@
|
|||||||
use wip_https::http::{Method, Request, StatusCode};
|
|
||||||
use wip_https::{Endpoint, RequestMetadataError, Route, validate_http_request};
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn endpoint_is_https_absolute_queryless_and_canonical() {
|
|
||||||
let endpoint = Endpoint::parse("https://example.test/root/prefix").unwrap();
|
|
||||||
assert_eq!(endpoint.to_string(), "https://example.test/root/prefix/");
|
|
||||||
|
|
||||||
let expected = [
|
|
||||||
(
|
|
||||||
Route::Observe,
|
|
||||||
"https://example.test/root/prefix/v1/observe",
|
|
||||||
),
|
|
||||||
(
|
|
||||||
Route::FetchInterface,
|
|
||||||
"https://example.test/root/prefix/v1/fetch_interface",
|
|
||||||
),
|
|
||||||
(
|
|
||||||
Route::CallOperation,
|
|
||||||
"https://example.test/root/prefix/v1/call_operation",
|
|
||||||
),
|
|
||||||
(Route::Batch, "https://example.test/root/prefix/v1/batch"),
|
|
||||||
];
|
|
||||||
for (route, url) in expected {
|
|
||||||
assert_eq!(endpoint.route(route).as_str(), url);
|
|
||||||
assert_eq!(
|
|
||||||
endpoint.recognize(&wip_https::url::Url::parse(url).unwrap()),
|
|
||||||
Some(route)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
assert_eq!(
|
|
||||||
endpoint.recognize(
|
|
||||||
&wip_https::url::Url::parse("https://example.test/root/prefix/v1/observe?path=/items")
|
|
||||||
.unwrap()
|
|
||||||
),
|
|
||||||
None
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn routes_never_mix_worldspace_paths_into_endpoint_prefixes() {
|
|
||||||
let endpoint = Endpoint::parse("https://example.test/wip/%E4%B8%96%E7%95%8C/").unwrap();
|
|
||||||
let route = endpoint.route(Route::Observe);
|
|
||||||
assert_eq!(route.path(), "/wip/%E4%B8%96%E7%95%8C/v1/observe");
|
|
||||||
assert!(!route.as_str().contains("items"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn inbound_http_metadata_enforces_post_route_and_json() {
|
|
||||||
let endpoint = Endpoint::parse("https://example.test/wip").unwrap();
|
|
||||||
let valid = Request::builder()
|
|
||||||
.method(Method::POST)
|
|
||||||
.uri("/wip/v1/observe")
|
|
||||||
.header("content-type", "application/json; charset=utf-8")
|
|
||||||
.body(Vec::<u8>::new())
|
|
||||||
.unwrap();
|
|
||||||
assert!(validate_http_request(&endpoint, Route::Observe, &valid).is_ok());
|
|
||||||
|
|
||||||
let wrong_method = Request::builder()
|
|
||||||
.method(Method::GET)
|
|
||||||
.uri("/wip/v1/observe")
|
|
||||||
.header("content-type", "application/json")
|
|
||||||
.body(Vec::<u8>::new())
|
|
||||||
.unwrap();
|
|
||||||
assert!(validate_http_request(&endpoint, Route::Observe, &wrong_method).is_err());
|
|
||||||
|
|
||||||
let wrong_route = Request::builder()
|
|
||||||
.method(Method::POST)
|
|
||||||
.uri("/wip/v1/fetch_interface")
|
|
||||||
.header("content-type", "application/json")
|
|
||||||
.body(Vec::<u8>::new())
|
|
||||||
.unwrap();
|
|
||||||
assert!(validate_http_request(&endpoint, Route::Observe, &wrong_route).is_err());
|
|
||||||
|
|
||||||
for accept in [
|
|
||||||
"text/plain, */*;q=1, application/json;q=0",
|
|
||||||
"application/json; charset=utf-16",
|
|
||||||
"application/json; profile=future",
|
|
||||||
] {
|
|
||||||
let incompatible_accept = Request::builder()
|
|
||||||
.method(Method::POST)
|
|
||||||
.uri("/wip/v1/observe")
|
|
||||||
.header("content-type", "application/json")
|
|
||||||
.header("accept", accept)
|
|
||||||
.body(Vec::<u8>::new())
|
|
||||||
.unwrap();
|
|
||||||
let error =
|
|
||||||
validate_http_request(&endpoint, Route::Observe, &incompatible_accept).unwrap_err();
|
|
||||||
assert!(matches!(&error, RequestMetadataError::NotAcceptable));
|
|
||||||
assert_eq!(error.status(), StatusCode::NOT_ACCEPTABLE);
|
|
||||||
}
|
|
||||||
|
|
||||||
for accept in [
|
|
||||||
"application/json; charset=UTF-8",
|
|
||||||
"application/json; q=1; profile=accept-extension",
|
|
||||||
] {
|
|
||||||
let compatible_accept = Request::builder()
|
|
||||||
.method(Method::POST)
|
|
||||||
.uri("/wip/v1/observe")
|
|
||||||
.header("content-type", "application/json")
|
|
||||||
.header("accept", accept)
|
|
||||||
.body(Vec::<u8>::new())
|
|
||||||
.unwrap();
|
|
||||||
assert!(validate_http_request(&endpoint, Route::Observe, &compatible_accept).is_ok());
|
|
||||||
}
|
|
||||||
|
|
||||||
let unsupported_media_type = Request::builder()
|
|
||||||
.method(Method::POST)
|
|
||||||
.uri("/wip/v1/observe")
|
|
||||||
.header("content-type", "text/plain")
|
|
||||||
.header("accept", "application/json")
|
|
||||||
.body(Vec::<u8>::new())
|
|
||||||
.unwrap();
|
|
||||||
let error =
|
|
||||||
validate_http_request(&endpoint, Route::Observe, &unsupported_media_type).unwrap_err();
|
|
||||||
assert!(matches!(&error, RequestMetadataError::UnsupportedMediaType));
|
|
||||||
assert_eq!(error.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn invalid_endpoint_components_are_rejected() {
|
|
||||||
assert!(Endpoint::parse("http://example.test/wip").is_err());
|
|
||||||
assert!(Endpoint::parse("/relative").is_err());
|
|
||||||
assert!(Endpoint::parse("https://example.test/wip?q=1").is_err());
|
|
||||||
assert!(Endpoint::parse("https://example.test/wip#fragment").is_err());
|
|
||||||
}
|
|
||||||
@@ -14,7 +14,7 @@ ratatui = "0.29.0"
|
|||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
ureq = "3.1.2"
|
ureq = "3.1.2"
|
||||||
wip-client = { path = "../wip-client" }
|
wip-client = { path = "../wip-client" }
|
||||||
wip-https = { path = "../wip-https" }
|
wip-http = { path = "../wip-http" }
|
||||||
wip-protocol = { path = "../wip-protocol" }
|
wip-protocol = { path = "../wip-protocol" }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
|
|||||||
@@ -8,12 +8,17 @@ owned by the client runtime.
|
|||||||
|
|
||||||
## Start
|
## Start
|
||||||
|
|
||||||
HTTPS is the normal mode:
|
Supply one `http` or `https` endpoint:
|
||||||
|
|
||||||
```console
|
```console
|
||||||
cargo run -p wip-tui -- --endpoint https://wip.example.test/api/wip
|
cargo run -p wip-tui -- --endpoint https://wip.example.test/api/wip
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The same canonical endpoint is used unchanged to construct requests, perform
|
||||||
|
HTTP I/O, and partition the client cache. WIP over HTTP does not define separate
|
||||||
|
HTTPS and development-HTTP profiles; URL scheme, TLS, certificate, authentication,
|
||||||
|
and proxy policy belong to the HTTP implementation and deployment.
|
||||||
|
|
||||||
The endpoint may instead be supplied as `WIP_ENDPOINT`. A non-secret cache
|
The endpoint may instead be supplied as `WIP_ENDPOINT`. A non-secret cache
|
||||||
partition identity may be supplied with `--security-context NAME` or
|
partition identity may be supplied with `--security-context NAME` or
|
||||||
`WIP_SECURITY_CONTEXT`. The default request timeout is 30 seconds and can be
|
`WIP_SECURITY_CONTEXT`. The default request timeout is 30 seconds and can be
|
||||||
@@ -31,16 +36,6 @@ Use `--authorization-env OTHER_VARIABLE` to select another variable. The value i
|
|||||||
redacted from `Debug` and is never rendered. Shell and process environment security
|
redacted from `Debug` and is never rendered. Shell and process environment security
|
||||||
remain the operator's responsibility.
|
remain the operator's responsibility.
|
||||||
|
|
||||||
Plain HTTP is rejected by default. It is available only as an explicit loopback
|
|
||||||
development mode:
|
|
||||||
|
|
||||||
```console
|
|
||||||
cargo run -p wip-tui -- http://127.0.0.1:8080/wip --allow-http
|
|
||||||
```
|
|
||||||
|
|
||||||
Non-loopback HTTP remains rejected even with `--allow-http`. For production, use a
|
|
||||||
real HTTPS endpoint and a trusted TLS deployment.
|
|
||||||
|
|
||||||
### Filesystem server example
|
### Filesystem server example
|
||||||
|
|
||||||
In one terminal:
|
In one terminal:
|
||||||
@@ -52,14 +47,13 @@ cargo run -p wip-fs-server -- \
|
|||||||
--root /tmp/wip-example \
|
--root /tmp/wip-example \
|
||||||
--listen 127.0.0.1:8080 \
|
--listen 127.0.0.1:8080 \
|
||||||
--base-path /wip \
|
--base-path /wip \
|
||||||
--development-http \
|
|
||||||
--read-write
|
--read-write
|
||||||
```
|
```
|
||||||
|
|
||||||
In another:
|
In another:
|
||||||
|
|
||||||
```console
|
```console
|
||||||
cargo run -p wip-tui -- http://127.0.0.1:8080/wip --allow-http
|
cargo run -p wip-tui -- http://127.0.0.1:8080/wip
|
||||||
```
|
```
|
||||||
|
|
||||||
Expand `/`, select `notes.txt`, focus the Interface/Operation pane, and choose
|
Expand `/`, select `notes.txt`, focus the Interface/Operation pane, and choose
|
||||||
|
|||||||
@@ -939,7 +939,7 @@ mod tests {
|
|||||||
// A request identity has no public constructor; derive one through the runtime.
|
// A request identity has no public constructor; derive one through the runtime.
|
||||||
let mut client = wip_client::Client::new(
|
let mut client = wip_client::Client::new(
|
||||||
wip_client::ClientLimits::new(1, 4, 4, 4, 4).unwrap(),
|
wip_client::ClientLimits::new(1, 4, 4, 4, 4).unwrap(),
|
||||||
wip_https::Limits::new(1024, 1024, 8, 8).unwrap(),
|
wip_http::Limits::new(1024, 1024, 8).unwrap(),
|
||||||
);
|
);
|
||||||
let session = client
|
let session = client
|
||||||
.open_session(
|
.open_session(
|
||||||
|
|||||||
+34
-110
@@ -1,10 +1,10 @@
|
|||||||
//! Secure-by-default command-line and environment configuration.
|
//! Command-line and environment configuration for the HTTP client.
|
||||||
|
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use std::fmt::{self, Debug, Display, Formatter};
|
use std::fmt::{self, Debug, Display, Formatter};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use wip_https::url::Url;
|
use wip_http::Endpoint;
|
||||||
|
|
||||||
/// Credential wrapper whose debug output is always redacted.
|
/// Credential wrapper whose debug output is always redacted.
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
@@ -25,45 +25,33 @@ impl Debug for Secret {
|
|||||||
/// Validated runtime configuration.
|
/// Validated runtime configuration.
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
/// Canonical logical HTTPS endpoint used by `wip-client`.
|
/// Canonical endpoint used for request construction, transport, and cache partitioning.
|
||||||
logical_endpoint: String,
|
endpoint: String,
|
||||||
/// Actual request origin; differs only for explicit loopback development HTTP.
|
|
||||||
transport_endpoint: String,
|
|
||||||
/// Non-secret cache partition identity.
|
/// Non-secret cache partition identity.
|
||||||
security_context: String,
|
security_context: String,
|
||||||
/// Bounded network timeout.
|
/// Bounded network timeout.
|
||||||
timeout: Duration,
|
timeout: Duration,
|
||||||
/// Optional complete Authorization header value, never rendered or logged.
|
/// Optional complete Authorization header value, never rendered or logged.
|
||||||
authorization: Option<Secret>,
|
authorization: Option<Secret>,
|
||||||
/// Whether loopback request URIs are deliberately downgraded to HTTP.
|
|
||||||
development_http: bool,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Debug for Config {
|
impl Debug for Config {
|
||||||
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
|
||||||
formatter
|
formatter
|
||||||
.debug_struct("Config")
|
.debug_struct("Config")
|
||||||
.field("logical_endpoint", &self.logical_endpoint)
|
.field("endpoint", &self.endpoint)
|
||||||
.field("transport_endpoint", &self.transport_endpoint)
|
|
||||||
.field("security_context", &self.security_context)
|
.field("security_context", &self.security_context)
|
||||||
.field("timeout", &self.timeout)
|
.field("timeout", &self.timeout)
|
||||||
.field("authorization", &self.authorization)
|
.field("authorization", &self.authorization)
|
||||||
.field("development_http", &self.development_http)
|
|
||||||
.finish()
|
.finish()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Config {
|
impl Config {
|
||||||
/// Returns the canonical HTTPS endpoint used for protocol request construction.
|
/// Returns the canonical endpoint used by the client and HTTP transport.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn logical_endpoint(&self) -> &str {
|
pub fn endpoint(&self) -> &str {
|
||||||
&self.logical_endpoint
|
&self.endpoint
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the validated effective transport endpoint shown in the UI.
|
|
||||||
#[must_use]
|
|
||||||
pub fn transport_endpoint(&self) -> &str {
|
|
||||||
&self.transport_endpoint
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the non-secret session cache partition identity.
|
/// Returns the non-secret session cache partition identity.
|
||||||
@@ -78,12 +66,6 @@ impl Config {
|
|||||||
self.timeout
|
self.timeout
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether explicit loopback development HTTP is enabled.
|
|
||||||
#[must_use]
|
|
||||||
pub const fn development_http(&self) -> bool {
|
|
||||||
self.development_http
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn authorization(&self) -> Option<&Secret> {
|
pub(crate) fn authorization(&self) -> Option<&Secret> {
|
||||||
self.authorization.as_ref()
|
self.authorization.as_ref()
|
||||||
}
|
}
|
||||||
@@ -115,7 +97,6 @@ impl Config {
|
|||||||
F: FnMut(&str) -> Option<String>,
|
F: FnMut(&str) -> Option<String>,
|
||||||
{
|
{
|
||||||
let mut endpoint = None;
|
let mut endpoint = None;
|
||||||
let mut allow_http = false;
|
|
||||||
let mut timeout = Duration::from_secs(30);
|
let mut timeout = Duration::from_secs(30);
|
||||||
let mut security_context = security_context_env.unwrap_or_else(|| "anonymous".into());
|
let mut security_context = security_context_env.unwrap_or_else(|| "anonymous".into());
|
||||||
let mut authorization_env = "WIP_AUTHORIZATION".to_owned();
|
let mut authorization_env = "WIP_AUTHORIZATION".to_owned();
|
||||||
@@ -123,7 +104,6 @@ impl Config {
|
|||||||
while let Some(argument) = iter.next() {
|
while let Some(argument) = iter.next() {
|
||||||
match argument.as_str() {
|
match argument.as_str() {
|
||||||
"--endpoint" => endpoint = Some(next_value(&mut iter, "--endpoint")?),
|
"--endpoint" => endpoint = Some(next_value(&mut iter, "--endpoint")?),
|
||||||
"--allow-http" => allow_http = true,
|
|
||||||
"--security-context" => {
|
"--security-context" => {
|
||||||
security_context = next_value(&mut iter, "--security-context")?;
|
security_context = next_value(&mut iter, "--security-context")?;
|
||||||
}
|
}
|
||||||
@@ -149,52 +129,22 @@ impl Config {
|
|||||||
_ => return Err(ConfigError::Invalid("multiple endpoints supplied".into())),
|
_ => return Err(ConfigError::Invalid("multiple endpoints supplied".into())),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let endpoint = endpoint
|
let supplied = endpoint
|
||||||
.or(endpoint_env)
|
.or(endpoint_env)
|
||||||
.ok_or_else(|| ConfigError::Invalid("endpoint is required".into()))?;
|
.ok_or_else(|| ConfigError::Invalid("endpoint is required".into()))?;
|
||||||
let mut actual = Url::parse(&endpoint)
|
let endpoint =
|
||||||
.map_err(|_| ConfigError::Invalid("endpoint is not a valid absolute URL".into()))?;
|
Endpoint::parse(&supplied).map_err(|error| ConfigError::Invalid(error.to_string()))?;
|
||||||
if actual.query().is_some()
|
if !endpoint.as_url().username().is_empty() || endpoint.as_url().password().is_some() {
|
||||||
|| actual.fragment().is_some()
|
|
||||||
|| actual.host_str().is_none()
|
|
||||||
|| !actual.username().is_empty()
|
|
||||||
|| actual.password().is_some()
|
|
||||||
{
|
|
||||||
return Err(ConfigError::Invalid(
|
return Err(ConfigError::Invalid(
|
||||||
"endpoint must be an absolute URL without userinfo, query, or fragment".into(),
|
"endpoint userinfo is not accepted; supply credentials through the configured environment variable"
|
||||||
|
.into(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
if !actual.path().ends_with('/') {
|
if !matches!(endpoint.as_url().scheme(), "http" | "https") {
|
||||||
let path = format!("{}/", actual.path());
|
return Err(ConfigError::Invalid(
|
||||||
actual.set_path(&path);
|
"this HTTP client supports http and https endpoint schemes".into(),
|
||||||
|
));
|
||||||
}
|
}
|
||||||
let development_http = actual.scheme() == "http";
|
|
||||||
match actual.scheme() {
|
|
||||||
"https" => {}
|
|
||||||
"http" if allow_http && loopback_host(&actual) => {}
|
|
||||||
"http" if !allow_http => {
|
|
||||||
return Err(ConfigError::Invalid(
|
|
||||||
"plain HTTP requires the explicit --allow-http development option".into(),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
"http" => {
|
|
||||||
return Err(ConfigError::Invalid(
|
|
||||||
"development HTTP is restricted to loopback endpoints".into(),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
_ => return Err(ConfigError::Invalid("endpoint must use HTTPS".into())),
|
|
||||||
}
|
|
||||||
let transport_endpoint = actual.to_string();
|
|
||||||
let mut logical = actual;
|
|
||||||
if development_http {
|
|
||||||
logical
|
|
||||||
.set_scheme("https")
|
|
||||||
.expect("http and https are interchangeable hierarchical schemes");
|
|
||||||
}
|
|
||||||
// Let the binding enforce all remaining canonical endpoint rules.
|
|
||||||
let logical_endpoint = wip_https::Endpoint::parse(logical.as_str())
|
|
||||||
.map_err(|error| ConfigError::Invalid(error.to_string()))?
|
|
||||||
.to_string();
|
|
||||||
if security_context.is_empty() {
|
if security_context.is_empty() {
|
||||||
return Err(ConfigError::Invalid(
|
return Err(ConfigError::Invalid(
|
||||||
"security context must not be empty".into(),
|
"security context must not be empty".into(),
|
||||||
@@ -204,20 +154,18 @@ impl Config {
|
|||||||
.filter(|value| !value.is_empty())
|
.filter(|value| !value.is_empty())
|
||||||
.map(Secret);
|
.map(Secret);
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
logical_endpoint,
|
endpoint: endpoint.to_string(),
|
||||||
transport_endpoint,
|
|
||||||
security_context,
|
security_context,
|
||||||
timeout,
|
timeout,
|
||||||
authorization,
|
authorization,
|
||||||
development_http,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns concise command usage without mentioning credential values.
|
/// Returns concise command usage without mentioning credential values.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn usage() -> &'static str {
|
pub const fn usage() -> &'static str {
|
||||||
"usage: wip-tui [--endpoint] URL [--allow-http] [--security-context NAME] [--authorization-env VAR] [--timeout SECONDS]\n\
|
"usage: wip-tui [--endpoint] URL [--security-context NAME] [--authorization-env VAR] [--timeout SECONDS]\n\
|
||||||
URL may also be supplied as WIP_ENDPOINT; HTTPS is required unless loopback HTTP is explicitly enabled."
|
URL may also be supplied as WIP_ENDPOINT; the HTTP adapter supports http and https."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -229,15 +177,6 @@ fn next_value(
|
|||||||
.ok_or_else(|| ConfigError::Invalid(format!("{option} requires a value")))
|
.ok_or_else(|| ConfigError::Invalid(format!("{option} requires a value")))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn loopback_host(url: &Url) -> bool {
|
|
||||||
match url.host() {
|
|
||||||
Some(wip_https::url::Host::Ipv4(address)) => address.is_loopback(),
|
|
||||||
Some(wip_https::url::Host::Ipv6(address)) => address.is_loopback(),
|
|
||||||
Some(wip_https::url::Host::Domain(name)) => name.eq_ignore_ascii_case("localhost"),
|
|
||||||
None => false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Startup configuration failure.
|
/// Startup configuration failure.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub enum ConfigError {
|
pub enum ConfigError {
|
||||||
@@ -263,7 +202,7 @@ mod tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn https_is_default_and_secrets_are_redacted() {
|
fn endpoint_is_canonical_and_secrets_are_redacted() {
|
||||||
let config = Config::parse(
|
let config = Config::parse(
|
||||||
["https://example.test/wip", "--authorization-env", "TOKEN"],
|
["https://example.test/wip", "--authorization-env", "TOKEN"],
|
||||||
None,
|
None,
|
||||||
@@ -271,7 +210,7 @@ mod tests {
|
|||||||
|name| (name == "TOKEN").then(|| "Bearer secret-value".into()),
|
|name| (name == "TOKEN").then(|| "Bearer secret-value".into()),
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(config.logical_endpoint(), "https://example.test/wip/");
|
assert_eq!(config.endpoint(), "https://example.test/wip/");
|
||||||
let debug = format!("{config:?}");
|
let debug = format!("{config:?}");
|
||||||
assert!(debug.contains("[REDACTED]"));
|
assert!(debug.contains("[REDACTED]"));
|
||||||
assert!(!debug.contains("secret-value"));
|
assert!(!debug.contains("secret-value"));
|
||||||
@@ -279,37 +218,22 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn endpoint_userinfo_is_rejected_before_it_can_reach_debug_or_render_state() {
|
fn endpoint_userinfo_is_rejected_before_it_can_reach_debug_or_render_state() {
|
||||||
for arguments in [
|
for endpoint in [
|
||||||
vec!["https://user:password@example.test/wip"],
|
"https://user:password@example.test/wip",
|
||||||
vec!["http://user:password@localhost:3000/wip", "--allow-http"],
|
"http://user:password@localhost:3000/wip",
|
||||||
] {
|
] {
|
||||||
let error = Config::parse(arguments, None, None, |_| None).unwrap_err();
|
let error = Config::parse([endpoint], None, None, |_| None).unwrap_err();
|
||||||
assert!(error.to_string().contains("without userinfo"));
|
assert!(error.to_string().contains("userinfo"));
|
||||||
assert!(!error.to_string().contains("password"));
|
assert!(!error.to_string().contains("password"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn http_requires_explicit_loopback_development_mode() {
|
fn http_and_https_are_preserved_as_the_single_endpoint() {
|
||||||
assert!(Config::parse(["http://localhost:3000/wip"], None, None, |_| None).is_err());
|
for expected in ["http://example.test:3000/wip/", "https://example.test/wip/"] {
|
||||||
let config = Config::parse(
|
let supplied = expected.trim_end_matches('/');
|
||||||
["http://127.0.0.1:3000/wip", "--allow-http"],
|
let config = Config::parse([supplied], None, None, |_| None).unwrap();
|
||||||
None,
|
assert_eq!(config.endpoint(), expected);
|
||||||
None,
|
}
|
||||||
|_| None,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(config.logical_endpoint(), "https://127.0.0.1:3000/wip/");
|
|
||||||
assert_eq!(config.transport_endpoint(), "http://127.0.0.1:3000/wip/");
|
|
||||||
assert!(config.development_http());
|
|
||||||
assert!(
|
|
||||||
Config::parse(
|
|
||||||
["http://example.test/wip", "--allow-http"],
|
|
||||||
None,
|
|
||||||
None,
|
|
||||||
|_| None,
|
|
||||||
)
|
|
||||||
.is_err()
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,8 +13,8 @@ use wip_client::{
|
|||||||
DispatchedTransportFailure, OutcomeUnknownReason, PreparedRequest, RequestId, SecurityContext,
|
DispatchedTransportFailure, OutcomeUnknownReason, PreparedRequest, RequestId, SecurityContext,
|
||||||
SessionId,
|
SessionId,
|
||||||
};
|
};
|
||||||
use wip_https::Limits;
|
use wip_http::Limits;
|
||||||
use wip_https::http::{Request, Response};
|
use wip_http::http::{Request, Response};
|
||||||
use wip_protocol::{InterfaceDescriptor, TypeExpr, Value};
|
use wip_protocol::{InterfaceDescriptor, TypeExpr, Value};
|
||||||
|
|
||||||
use crate::app::{
|
use crate::app::{
|
||||||
@@ -68,18 +68,17 @@ pub trait Transport: Send + Sync + 'static {
|
|||||||
fn execute(&self, request: Self::Prepared) -> Result<Response<Vec<u8>>, TransportError>;
|
fn execute(&self, request: Self::Prepared) -> Result<Response<Vec<u8>>, TransportError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// HTTPS transport with redirects disabled and bounded response bodies.
|
/// HTTP transport with redirects disabled and bounded response bodies.
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct HttpTransport {
|
pub struct HttpTransport {
|
||||||
agent: ureq::Agent,
|
agent: ureq::Agent,
|
||||||
logical_endpoint: wip_https::Endpoint,
|
endpoint: wip_http::Endpoint,
|
||||||
transport_endpoint: wip_https::url::Url,
|
authorization: Option<wip_http::http::HeaderValue>,
|
||||||
authorization: Option<wip_https::http::HeaderValue>,
|
|
||||||
max_response_bytes: usize,
|
max_response_bytes: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl HttpTransport {
|
impl HttpTransport {
|
||||||
/// Builds the default TLS transport and revalidates its immutable origins.
|
/// Builds the HTTP transport and revalidates its immutable endpoint.
|
||||||
pub fn new(config: &Config, max_response_bytes: usize) -> Result<Self, TransportError> {
|
pub fn new(config: &Config, max_response_bytes: usize) -> Result<Self, TransportError> {
|
||||||
if max_response_bytes == 0 {
|
if max_response_bytes == 0 {
|
||||||
return Err(TransportError {
|
return Err(TransportError {
|
||||||
@@ -87,29 +86,18 @@ impl HttpTransport {
|
|||||||
detail: "transport response limit must be nonzero".into(),
|
detail: "transport response limit must be nonzero".into(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
let logical_endpoint =
|
let endpoint =
|
||||||
wip_https::Endpoint::parse(config.logical_endpoint()).map_err(|_| TransportError {
|
wip_http::Endpoint::parse(config.endpoint()).map_err(|_| TransportError {
|
||||||
kind: TransportErrorKind::Disconnect,
|
kind: TransportErrorKind::Disconnect,
|
||||||
detail: "logical endpoint failed transport validation".into(),
|
detail: "endpoint failed transport validation".into(),
|
||||||
})?;
|
})?;
|
||||||
let transport_endpoint =
|
|
||||||
wip_https::url::Url::parse(config.transport_endpoint()).map_err(|_| {
|
|
||||||
TransportError {
|
|
||||||
kind: TransportErrorKind::Disconnect,
|
|
||||||
detail: "transport endpoint failed validation".into(),
|
|
||||||
}
|
|
||||||
})?;
|
|
||||||
validate_transport_origin(config, &logical_endpoint, &transport_endpoint)?;
|
|
||||||
let authorization = config
|
let authorization = config
|
||||||
.authorization()
|
.authorization()
|
||||||
.map(|secret| {
|
.map(|secret| {
|
||||||
wip_https::http::HeaderValue::from_str(secret.expose()).map_err(|_| {
|
wip_http::http::HeaderValue::from_str(secret.expose()).map_err(|_| TransportError {
|
||||||
TransportError {
|
kind: TransportErrorKind::Disconnect,
|
||||||
kind: TransportErrorKind::Disconnect,
|
detail: "authorization environment variable is not a valid HTTP header value"
|
||||||
detail:
|
.into(),
|
||||||
"authorization environment variable is not a valid HTTP header value"
|
|
||||||
.into(),
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.transpose()?;
|
.transpose()?;
|
||||||
@@ -121,67 +109,24 @@ impl HttpTransport {
|
|||||||
.into();
|
.into();
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
agent,
|
agent,
|
||||||
logical_endpoint,
|
endpoint,
|
||||||
transport_endpoint,
|
|
||||||
authorization,
|
authorization,
|
||||||
max_response_bytes,
|
max_response_bytes,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn effective_uri(&self, uri: &str) -> Result<String, TransportError> {
|
fn effective_uri(&self, uri: &str) -> Result<String, TransportError> {
|
||||||
let candidate = wip_https::url::Url::parse(uri).map_err(|_| TransportError {
|
let candidate = wip_http::url::Url::parse(uri).map_err(|_| TransportError {
|
||||||
kind: TransportErrorKind::Disconnect,
|
kind: TransportErrorKind::Disconnect,
|
||||||
detail: "refused a request with an invalid absolute URI".into(),
|
detail: "refused a request with an invalid absolute URI".into(),
|
||||||
})?;
|
})?;
|
||||||
let route = self
|
self.endpoint
|
||||||
.logical_endpoint
|
|
||||||
.recognize(&candidate)
|
.recognize(&candidate)
|
||||||
.ok_or_else(|| TransportError {
|
.ok_or_else(|| TransportError {
|
||||||
kind: TransportErrorKind::Disconnect,
|
kind: TransportErrorKind::Disconnect,
|
||||||
detail: "refused a request outside the configured WIP origin and routes".into(),
|
detail: "refused a request outside the configured WIP origin and routes".into(),
|
||||||
})?;
|
})?;
|
||||||
Ok(self
|
Ok(candidate.to_string())
|
||||||
.transport_endpoint
|
|
||||||
.join(route.relative_reference())
|
|
||||||
.expect("validated endpoint joins a fixed route")
|
|
||||||
.to_string())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn validate_transport_origin(
|
|
||||||
config: &Config,
|
|
||||||
logical: &wip_https::Endpoint,
|
|
||||||
transport: &wip_https::url::Url,
|
|
||||||
) -> Result<(), TransportError> {
|
|
||||||
let common_invalid = transport.query().is_some()
|
|
||||||
|| transport.fragment().is_some()
|
|
||||||
|| transport.host_str().is_none()
|
|
||||||
|| !transport.username().is_empty()
|
|
||||||
|| transport.password().is_some();
|
|
||||||
let valid = if config.development_http() {
|
|
||||||
let loopback = match transport.host() {
|
|
||||||
Some(wip_https::url::Host::Ipv4(address)) => address.is_loopback(),
|
|
||||||
Some(wip_https::url::Host::Ipv6(address)) => address.is_loopback(),
|
|
||||||
Some(wip_https::url::Host::Domain(name)) => name.eq_ignore_ascii_case("localhost"),
|
|
||||||
None => false,
|
|
||||||
};
|
|
||||||
let mut upgraded = transport.clone();
|
|
||||||
let changed = upgraded.set_scheme("https").is_ok();
|
|
||||||
!common_invalid
|
|
||||||
&& transport.scheme() == "http"
|
|
||||||
&& loopback
|
|
||||||
&& changed
|
|
||||||
&& &upgraded == logical.as_url()
|
|
||||||
} else {
|
|
||||||
!common_invalid && transport == logical.as_url()
|
|
||||||
};
|
|
||||||
if valid {
|
|
||||||
Ok(())
|
|
||||||
} else {
|
|
||||||
Err(TransportError {
|
|
||||||
kind: TransportErrorKind::Disconnect,
|
|
||||||
detail: "transport endpoint does not match the validated logical origin".into(),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -196,10 +141,9 @@ impl Transport for HttpTransport {
|
|||||||
detail: "transport could not construct the configured request URI".into(),
|
detail: "transport could not construct the configured request URI".into(),
|
||||||
})?;
|
})?;
|
||||||
if let Some(authorization) = &self.authorization {
|
if let Some(authorization) = &self.authorization {
|
||||||
parts.headers.insert(
|
parts
|
||||||
wip_https::http::header::AUTHORIZATION,
|
.headers
|
||||||
authorization.clone(),
|
.insert(wip_http::http::header::AUTHORIZATION, authorization.clone());
|
||||||
);
|
|
||||||
}
|
}
|
||||||
Ok(Request::from_parts(parts, body))
|
Ok(Request::from_parts(parts, body))
|
||||||
}
|
}
|
||||||
@@ -242,7 +186,7 @@ fn classify_ureq_error(error: ureq::Error) -> TransportError {
|
|||||||
},
|
},
|
||||||
_ => TransportError {
|
_ => TransportError {
|
||||||
kind: TransportErrorKind::Disconnect,
|
kind: TransportErrorKind::Disconnect,
|
||||||
detail: "HTTP/TLS transport failed".into(),
|
detail: "HTTP transport failed".into(),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -274,7 +218,7 @@ impl<T: Transport> Runtime<T> {
|
|||||||
);
|
);
|
||||||
let session = client
|
let session = client
|
||||||
.open_session(
|
.open_session(
|
||||||
config.logical_endpoint(),
|
config.endpoint(),
|
||||||
SecurityContext::new(config.security_context()),
|
SecurityContext::new(config.security_context()),
|
||||||
)
|
)
|
||||||
.map_err(|error| RuntimeError(error.to_string()))?;
|
.map_err(|error| RuntimeError(error.to_string()))?;
|
||||||
@@ -282,7 +226,7 @@ impl<T: Transport> Runtime<T> {
|
|||||||
Ok(Self {
|
Ok(Self {
|
||||||
client,
|
client,
|
||||||
session,
|
session,
|
||||||
app: App::new(config.transport_endpoint()),
|
app: App::new(config.endpoint()),
|
||||||
transport: Arc::new(transport),
|
transport: Arc::new(transport),
|
||||||
sender,
|
sender,
|
||||||
receiver,
|
receiver,
|
||||||
@@ -918,8 +862,7 @@ fn collect_entries_at(
|
|||||||
/// Standard bounded wire policy used by the executable and integration tests.
|
/// Standard bounded wire policy used by the executable and integration tests.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn default_wire_limits() -> Limits {
|
pub fn default_wire_limits() -> Limits {
|
||||||
Limits::new(256 * 1024, 2 * 1024 * 1024, 64, 64)
|
Limits::new(256 * 1024, 2 * 1024 * 1024, 64).expect("static runtime wire limits are nonzero")
|
||||||
.expect("static runtime wire limits are nonzero")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Runs the interactive executable using process configuration.
|
/// Runs the interactive executable using process configuration.
|
||||||
@@ -1046,6 +989,26 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn transport_preserves_the_configured_endpoint_scheme_for_requests() {
|
||||||
|
for scheme in ["http", "https"] {
|
||||||
|
let configured = format!("{scheme}://example.test/wip");
|
||||||
|
let config = Config::parse([configured], None, None, |_| None).unwrap();
|
||||||
|
let transport = HttpTransport::new(&config, 1024).unwrap();
|
||||||
|
let endpoint = wip_http::Endpoint::parse(config.endpoint()).unwrap();
|
||||||
|
let expected = endpoint.route(wip_http::Route::Observe).to_string();
|
||||||
|
let request = Request::builder()
|
||||||
|
.method("POST")
|
||||||
|
.uri(&expected)
|
||||||
|
.body(Vec::new())
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let prepared = transport.prepare(request).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(prepared.uri().to_string(), expected);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn authorization_is_attached_only_after_exact_origin_and_route_validation() {
|
fn authorization_is_attached_only_after_exact_origin_and_route_validation() {
|
||||||
let config = Config::parse(
|
let config = Config::parse(
|
||||||
@@ -1065,15 +1028,15 @@ mod tests {
|
|||||||
assert!(error.detail.contains("outside"));
|
assert!(error.detail.contains("outside"));
|
||||||
assert!(!error.detail.contains("sensitive"));
|
assert!(!error.detail.contains("sensitive"));
|
||||||
|
|
||||||
let endpoint = wip_https::Endpoint::parse(config.logical_endpoint()).unwrap();
|
let endpoint = wip_http::Endpoint::parse(config.endpoint()).unwrap();
|
||||||
let valid = Request::builder()
|
let valid = Request::builder()
|
||||||
.method("POST")
|
.method("POST")
|
||||||
.uri(endpoint.route(wip_https::Route::Observe).as_str())
|
.uri(endpoint.route(wip_http::Route::Observe).as_str())
|
||||||
.body(Vec::new())
|
.body(Vec::new())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let prepared = transport.prepare(valid).unwrap();
|
let prepared = transport.prepare(valid).unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
prepared.headers()[wip_https::http::header::AUTHORIZATION],
|
prepared.headers()[wip_http::http::header::AUTHORIZATION],
|
||||||
"Bearer sensitive"
|
"Bearer sensitive"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1081,7 +1044,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn transport_error_messages_do_not_echo_underlying_data() {
|
fn transport_error_messages_do_not_echo_underlying_data() {
|
||||||
let error = classify_ureq_error(ureq::Error::BadUri("secret-token".into()));
|
let error = classify_ureq_error(ureq::Error::BadUri("secret-token".into()));
|
||||||
assert_eq!(error.detail, "HTTP/TLS transport failed");
|
assert_eq!(error.detail, "HTTP transport failed");
|
||||||
assert!(!error.detail.contains("secret-token"));
|
assert!(!error.detail.contains("secret-token"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ use std::thread;
|
|||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
use tempfile::tempdir;
|
use tempfile::tempdir;
|
||||||
use wip_fs_server::{AccessMode, ServerConfig, TransportSecurity, WipFsServer};
|
use wip_fs_server::{AccessMode, ServerConfig, WipFsServer};
|
||||||
use wip_tui::app::{Focus, HistoryKind, InputKey, Modal, ViewState};
|
use wip_tui::app::{Focus, HistoryKind, InputKey, Modal, ViewState};
|
||||||
use wip_tui::config::Config;
|
use wip_tui::config::Config;
|
||||||
use wip_tui::runtime::{HttpTransport, Runtime, default_wire_limits};
|
use wip_tui::runtime::{HttpTransport, Runtime, default_wire_limits};
|
||||||
@@ -22,7 +22,6 @@ fn real_http_filesystem_workflow_is_lazy_validator_safe_and_symlink_confined() {
|
|||||||
|
|
||||||
let mut server_config = ServerConfig::for_root(temporary.path());
|
let mut server_config = ServerConfig::for_root(temporary.path());
|
||||||
server_config.access = AccessMode::ReadWrite;
|
server_config.access = AccessMode::ReadWrite;
|
||||||
server_config.transport_security = TransportSecurity::DevelopmentHttp;
|
|
||||||
let bound = Arc::new(
|
let bound = Arc::new(
|
||||||
WipFsServer::new(server_config)
|
WipFsServer::new(server_config)
|
||||||
.expect("build filesystem server")
|
.expect("build filesystem server")
|
||||||
@@ -36,13 +35,8 @@ fn real_http_filesystem_workflow_is_lazy_validator_safe_and_symlink_confined() {
|
|||||||
thread::spawn(move || bound.serve_until(shutdown))
|
thread::spawn(move || bound.serve_until(shutdown))
|
||||||
};
|
};
|
||||||
let endpoint = format!("http://127.0.0.1:{}/wip", bound.local_addr().port());
|
let endpoint = format!("http://127.0.0.1:{}/wip", bound.local_addr().port());
|
||||||
let config = Config::parse(
|
let config = Config::parse([endpoint], None, Some("filesystem-test".into()), |_| None)
|
||||||
[endpoint, "--allow-http".into()],
|
.expect("development config");
|
||||||
None,
|
|
||||||
Some("filesystem-test".into()),
|
|
||||||
|_| None,
|
|
||||||
)
|
|
||||||
.expect("development config");
|
|
||||||
let transport = HttpTransport::new(&config, default_wire_limits().max_response_bytes())
|
let transport = HttpTransport::new(&config, default_wire_limits().max_response_bytes())
|
||||||
.expect("HTTP transport");
|
.expect("HTTP transport");
|
||||||
let mut runtime = Runtime::new(&config, transport).expect("runtime");
|
let mut runtime = Runtime::new(&config, transport).expect("runtime");
|
||||||
|
|||||||
@@ -5,8 +5,8 @@ use std::time::{Duration, Instant};
|
|||||||
|
|
||||||
use tempfile::tempdir;
|
use tempfile::tempdir;
|
||||||
use wip_fs_server::{ServerConfig, WipFsServer};
|
use wip_fs_server::{ServerConfig, WipFsServer};
|
||||||
use wip_https::encode_protocol_error_response;
|
use wip_http::encode_protocol_error_response;
|
||||||
use wip_https::http::{Request, Response};
|
use wip_http::http::{Request, Response};
|
||||||
use wip_protocol::{ProtocolError, ProtocolErrorCode, ProtocolInteraction};
|
use wip_protocol::{ProtocolError, ProtocolErrorCode, ProtocolInteraction};
|
||||||
use wip_tui::app::{ConnectionState, Focus, HistoryKind, InputKey, Modal, ViewState};
|
use wip_tui::app::{ConnectionState, Focus, HistoryKind, InputKey, Modal, ViewState};
|
||||||
use wip_tui::config::Config;
|
use wip_tui::config::Config;
|
||||||
|
|||||||
Reference in New Issue
Block a user