Skip to main content

ocp_host/
http.rs

1//! Streamable-HTTP transport: a remote OCP provider reached by POSTing the
2//! envelope to its URL (`06-context-protocol.md` §3.2 "remote providers:
3//! streamable HTTP"). The reference host uses request/response JSON — the
4//! [`Envelope`] as the POST body, one [`Envelope`] back as the response body
5//! — which any streamable-HTTP server satisfies; chunked frame streaming is
6//! a documented forward extension, not needed for the v1 shape.
7//!
8//! Unlike stdio's process isolation, an HTTP provider is remote by nature, so
9//! its `egress` posture is decided by the URL host and gated through the same
10//! [`crate::consent`] store at the [`crate::host::Host`] layer.
11
12use std::time::Duration;
13
14use async_trait::async_trait;
15use ocp_types::{Capabilities, ContextQuery, ContextQueryResult, PROTOCOL_VERSION, ProviderInfo};
16
17use crate::error::HostError;
18use crate::provider::ContextProvider;
19use crate::wire::{Envelope, envelope_kind, versions_compatible};
20
21/// Total per-request budget for an HTTP exchange (handshake or query).
22const HTTP_TIMEOUT: Duration = Duration::from_secs(30);
23
24/// A [`ContextProvider`] backed by a remote HTTP endpoint. Handshakes once on
25/// [`HttpProvider::connect`] and caches the negotiated identity + capabilities.
26pub struct HttpProvider {
27    id: String,
28    url: String,
29    client: reqwest::Client,
30    info: ProviderInfo,
31    capabilities: Capabilities,
32}
33
34impl HttpProvider {
35    /// Connect to a remote provider: POST a `handshake`, expect a compatible
36    /// `handshake_ack`, and cache its identity + capabilities. `id` is the
37    /// host-facing routing/consent key.
38    pub async fn connect(id: impl Into<String>, url: impl Into<String>) -> Result<Self, HostError> {
39        let id = id.into();
40        let url = url.into();
41        let client = reqwest::Client::builder()
42            .timeout(HTTP_TIMEOUT)
43            .build()
44            .map_err(|e| HostError::Transport {
45                id: id.clone(),
46                message: format!("building HTTP client: {e}"),
47            })?;
48
49        let ack = post_envelope(
50            &client,
51            &url,
52            &Envelope::Handshake {
53                protocol_version: PROTOCOL_VERSION.to_string(),
54            },
55            &id,
56        )
57        .await?;
58
59        match ack {
60            Envelope::HandshakeAck {
61                protocol_version,
62                provider,
63                capabilities,
64            } => {
65                if !versions_compatible(PROTOCOL_VERSION, &protocol_version) {
66                    return Err(HostError::VersionMismatch {
67                        host: PROTOCOL_VERSION.to_string(),
68                        provider: provider.name,
69                        provider_version: protocol_version,
70                    });
71                }
72                // An HTTP transport is egress by definition: every query is
73                // POSTed off-box to a remote URL. So the consent gate must key
74                // off transport, not the remote's self-report — a remote that
75                // handshakes `egress:false` would otherwise be queried with no
76                // consent. Force it on here regardless of what it declared.
77                // (The stdio path keeps its declared posture; a local child
78                // that doesn't reach the network genuinely may not be egress.)
79                let mut info = provider;
80                info.data_flow.egress = true;
81                Ok(Self {
82                    id,
83                    url,
84                    client,
85                    info,
86                    capabilities,
87                })
88            }
89            other => Err(HostError::UnexpectedEnvelope {
90                id,
91                expected: "handshake_ack".into(),
92                got: envelope_kind(&other).into(),
93            }),
94        }
95    }
96}
97
98/// POST one envelope to the provider URL and decode the response as one
99/// envelope. A non-2xx status or a non-envelope body is a clean named error,
100/// never a panic (task deliverable 5).
101async fn post_envelope(
102    client: &reqwest::Client,
103    url: &str,
104    env: &Envelope,
105    id: &str,
106) -> Result<Envelope, HostError> {
107    let response = client
108        .post(url)
109        .json(env)
110        .send()
111        .await
112        .map_err(|e| HostError::Transport {
113            id: id.to_string(),
114            message: e.to_string(),
115        })?;
116
117    if !response.status().is_success() {
118        let status = response.status();
119        let body = response.text().await.unwrap_or_default();
120        return Err(HostError::Transport {
121            id: id.to_string(),
122            message: format!("HTTP {status}: {body}"),
123        });
124    }
125
126    response.json::<Envelope>().await.map_err(|e| {
127        HostError::Wire(format!(
128            "provider {id} returned a non-envelope HTTP body: {e}"
129        ))
130    })
131}
132
133#[async_trait]
134impl ContextProvider for HttpProvider {
135    fn id(&self) -> &str {
136        &self.id
137    }
138
139    fn info(&self) -> &ProviderInfo {
140        &self.info
141    }
142
143    fn capabilities(&self) -> &Capabilities {
144        &self.capabilities
145    }
146
147    async fn query(&self, query: &ContextQuery) -> Result<ContextQueryResult, HostError> {
148        let reply = post_envelope(
149            &self.client,
150            &self.url,
151            &Envelope::Query {
152                query: query.clone(),
153            },
154            &self.id,
155        )
156        .await?;
157        match reply {
158            Envelope::Frames { result } => Ok(result),
159            Envelope::Error { message } => Err(HostError::Provider {
160                id: self.id.clone(),
161                message,
162            }),
163            other => Err(HostError::UnexpectedEnvelope {
164                id: self.id.clone(),
165                expected: "frames".into(),
166                got: envelope_kind(&other).into(),
167            }),
168        }
169    }
170
171    async fn shutdown(&self) -> Result<(), HostError> {
172        // Best-effort teardown notice; a remote endpoint is not ours to reap.
173        let _ = post_envelope(&self.client, &self.url, &Envelope::Shutdown, &self.id).await;
174        Ok(())
175    }
176}
177
178#[cfg(test)]
179mod tests {
180    use super::*;
181    use ocp_types::capability::QueryCapability;
182    use ocp_types::{ContextFrame, DataFlow, FrameKind};
183    use wiremock::matchers::method;
184    use wiremock::{Mock, MockServer, ResponseTemplate};
185
186    fn ack_body(version: &str) -> serde_json::Value {
187        serde_json::to_value(Envelope::HandshakeAck {
188            protocol_version: version.to_string(),
189            provider: ProviderInfo {
190                name: "remote-docs".into(),
191                version: "0.1.0".into(),
192                data_flow: DataFlow {
193                    reads: true,
194                    writes: false,
195                    egress: true,
196                },
197            },
198            capabilities: Capabilities {
199                query: QueryCapability {
200                    kinds: vec!["doc".into()],
201                    filters: vec![],
202                },
203                ..Capabilities::default()
204            },
205        })
206        .unwrap()
207    }
208
209    fn frames_body() -> serde_json::Value {
210        serde_json::to_value(Envelope::Frames {
211            result: ContextQueryResult {
212                frames: vec![ContextFrame {
213                    id: "frm_h".into(),
214                    kind: FrameKind::Doc,
215                    title: "remote doc".into(),
216                    content: "remote content".into(),
217                    uri: Some("https://example.test/doc".into()),
218                    score: 0.6,
219                    token_cost: 20,
220                    valid_from: None,
221                    valid_to: None,
222                    recorded_at: None,
223                    provenance: vec![],
224                    citation_label: Some("remote doc".into()),
225                    embedding: None,
226                    relations: vec![],
227                }],
228                truncated: false,
229                dropped_estimate: None,
230            },
231        })
232        .unwrap()
233    }
234
235    fn sample_query() -> ContextQuery {
236        ContextQuery {
237            goal: "g".into(),
238            query_text: None,
239            embedding: None,
240            kinds: vec![],
241            anchors: vec![],
242            max_frames: 5,
243            max_tokens: 4000,
244            as_of: None,
245        }
246    }
247
248    #[tokio::test]
249    async fn http_handshake_then_query_round_trips_via_wiremock() {
250        let server = MockServer::start().await;
251        // Both the handshake and the query POST to the same URL; the responder
252        // dispatches on the request envelope's `type`.
253        Mock::given(method("POST"))
254            .respond_with(|req: &wiremock::Request| {
255                let body = match serde_json::from_slice::<Envelope>(&req.body) {
256                    Ok(Envelope::Handshake { .. }) => ack_body(PROTOCOL_VERSION),
257                    Ok(Envelope::Query { .. }) => frames_body(),
258                    _ => serde_json::to_value(Envelope::Error {
259                        message: "unexpected request".into(),
260                    })
261                    .unwrap(),
262                };
263                ResponseTemplate::new(200).set_body_json(body)
264            })
265            .mount(&server)
266            .await;
267
268        let provider = HttpProvider::connect("remote", server.uri())
269            .await
270            .expect("handshake ok");
271        assert_eq!(provider.info().name, "remote-docs");
272        assert!(provider.info().data_flow.egress);
273
274        let result = provider.query(&sample_query()).await.expect("query ok");
275        assert_eq!(result.frames.len(), 1);
276        assert_eq!(result.frames[0].title, "remote doc");
277    }
278
279    #[tokio::test]
280    async fn http_version_mismatch_rejects_the_provider() {
281        let server = MockServer::start().await;
282        Mock::given(method("POST"))
283            .respond_with(ResponseTemplate::new(200).set_body_json(ack_body("ocp/2.0")))
284            .mount(&server)
285            .await;
286
287        let err = match HttpProvider::connect("remote", server.uri()).await {
288            Ok(_) => panic!("incompatible version must reject"),
289            Err(e) => e,
290        };
291        assert!(matches!(err, HostError::VersionMismatch { .. }));
292    }
293
294    #[tokio::test]
295    async fn a_non_envelope_http_body_is_a_clean_wire_error() {
296        let server = MockServer::start().await;
297        Mock::given(method("POST"))
298            .respond_with(ResponseTemplate::new(200).set_body_string("<html>not ocp</html>"))
299            .mount(&server)
300            .await;
301
302        let err = match HttpProvider::connect("remote", server.uri()).await {
303            Ok(_) => panic!("garbage body must not panic the host"),
304            Err(e) => e,
305        };
306        assert!(matches!(err, HostError::Wire(_)));
307    }
308
309    #[tokio::test]
310    async fn http_transport_forces_egress_even_when_the_remote_claims_local() {
311        // A remote self-declares `egress:false` in its handshake. Using an HTTP
312        // transport IS egress (the query is POSTed off-box), so the host must
313        // override the claim and still gate consent — otherwise a remote could
314        // opt itself out of the consent gate by lying.
315        let server = MockServer::start().await;
316        let sneaky_ack = serde_json::to_value(Envelope::HandshakeAck {
317            protocol_version: PROTOCOL_VERSION.to_string(),
318            provider: ProviderInfo {
319                name: "sneaky-remote".into(),
320                version: "0.1.0".into(),
321                data_flow: DataFlow {
322                    reads: true,
323                    writes: false,
324                    egress: false, // the lie the host must not trust
325                },
326            },
327            capabilities: Capabilities {
328                query: QueryCapability {
329                    kinds: vec!["doc".into()],
330                    filters: vec![],
331                },
332                ..Capabilities::default()
333            },
334        })
335        .unwrap();
336        Mock::given(method("POST"))
337            .respond_with(ResponseTemplate::new(200).set_body_json(sneaky_ack))
338            .mount(&server)
339            .await;
340
341        let provider = HttpProvider::connect("remote", server.uri())
342            .await
343            .expect("handshake ok");
344
345        assert!(
346            provider.info().data_flow.egress,
347            "an HTTP transport must be treated as egress regardless of the remote's claim"
348        );
349        assert!(
350            crate::consent::ConsentStore::requires_consent(provider.info()),
351            "an HTTP provider must always require consent, even claiming egress:false"
352        );
353    }
354}