Skip to main content

agentos_client/
net.rs

1//! Port-based virtual networking (`fetch`).
2//!
3//! Ported from `packages/core/src/agent-os.ts` `fetch`. Dispatches to a guest server on `port`
4//! inside the kernel, never the host. The request URL host is discarded (only `pathname`+`search`
5//! are used); the body is only attached for non-GET/HEAD methods; the response body is base64-decoded.
6//! Fully buffered both directions. Wire path is the existing `VmFetch` request/response.
7
8use std::collections::BTreeMap;
9
10use anyhow::{Context, Result};
11use base64::engine::general_purpose::STANDARD as BASE64;
12use base64::Engine as _;
13use serde::{Deserialize, Serialize};
14
15use agentos_sidecar_client::wire;
16
17use crate::agent_os::AgentOs;
18use crate::error::ClientError;
19
20/// Maximum fully buffered fetch component size. `VmFetch` is a single request/response frame, so
21/// keeping this at the default frame size prevents fetch-specific buffers from growing just because
22/// a sidecar was configured with a larger transport frame limit for another API.
23const VM_FETCH_BUFFER_LIMIT_BYTES: usize = agentos_sidecar_client::wire::DEFAULT_MAX_FRAME_BYTES;
24
25/// The shape of the JSON string returned in [`VmFetchResponse::response_json`], mirroring the TS
26/// `{ status, statusText?, headers?: [k,v][], body?: base64 }` payload.
27#[derive(Debug, Deserialize)]
28struct VmFetchResponsePayload {
29    status: u16,
30    #[serde(rename = "statusText", default)]
31    status_text: Option<String>,
32    #[serde(default)]
33    headers: Option<Vec<(String, String)>>,
34    /// Base64-encoded response body.
35    #[serde(default)]
36    body: Option<String>,
37}
38
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40pub struct HttpRequest {
41    pub port: u16,
42    pub path: String,
43    #[serde(default = "default_http_method")]
44    pub method: String,
45    #[serde(default)]
46    pub headers: BTreeMap<String, String>,
47    #[serde(default, skip_serializing_if = "Option::is_none")]
48    pub body: Option<Vec<u8>>,
49}
50
51fn default_http_method() -> String {
52    "GET".to_string()
53}
54
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
56pub struct HttpResponse {
57    pub status: u16,
58    #[serde(rename = "statusText")]
59    pub status_text: String,
60    pub headers: BTreeMap<String, String>,
61    pub body: Vec<u8>,
62}
63
64impl AgentOs {
65    /// Fetch from a guest server listening on `port` inside the VM.
66    ///
67    /// `path` is derived from the request URI's `pathname`+`search`; the host is ignored. The body
68    /// is only sent for methods other than GET/HEAD. The response body is base64-decoded.
69    pub async fn http_request(&self, request: HttpRequest) -> Result<HttpResponse> {
70        let buffer_limit = self.fetch_buffer_limit();
71        let HttpRequest {
72            port,
73            path,
74            method,
75            headers: header_map,
76            body,
77        } = request;
78        if !path.starts_with('/') {
79            return Err(ClientError::Sidecar(format!(
80                "HTTP request path must be absolute: {path}"
81            ))
82            .into());
83        }
84        ensure_fetch_component_within_limit("HTTP request path", path.len(), buffer_limit)?;
85        let method = method.to_uppercase();
86        let raw_header_bytes = header_map.iter().fold(0usize, |size, (name, value)| {
87            size.saturating_add(name.len()).saturating_add(value.len())
88        });
89        ensure_fetch_component_within_limit(
90            "fetch request headers",
91            raw_header_bytes,
92            buffer_limit,
93        )?;
94        let headers_json =
95            serde_json::to_string(&header_map).context("serializing fetch request headers")?;
96        ensure_fetch_component_within_limit(
97            "fetch request headers json",
98            headers_json.len(),
99            buffer_limit,
100        )?;
101
102        // Body is only attached for methods other than GET/HEAD (TS `request.method !== "GET" && ...`).
103        let wire_body = if method == "GET" || method == "HEAD" {
104            None
105        } else {
106            body.map(|body| String::from_utf8_lossy(&body).into_owned())
107        };
108        if let Some(body) = &wire_body {
109            ensure_fetch_component_within_limit("HTTP request body", body.len(), buffer_limit)?;
110        }
111        ensure_fetch_request_payload_within_limit(
112            &method,
113            &path,
114            &headers_json,
115            wire_body.as_deref(),
116            buffer_limit,
117        )?;
118
119        let response = self
120            .transport()
121            .request_wire_bounded(
122                self.vm_fetch_ownership(),
123                wire::RequestPayload::VmFetchRequest(wire::VmFetchRequest {
124                    port,
125                    method,
126                    path,
127                    headers_json,
128                    body: wire_body,
129                }),
130                buffer_limit,
131            )
132            .await?;
133
134        let response_json = match response {
135            wire::ResponsePayload::VmFetchResponse(result) => result.response_json,
136            wire::ResponsePayload::RejectedResponse(rejected) => {
137                return Err(ClientError::from_rejection(rejected).into());
138            }
139            other => {
140                return Err(
141                    ClientError::Sidecar(format!("fetch: unexpected response {other:?}")).into(),
142                );
143            }
144        };
145        ensure_fetch_component_within_limit(
146            "fetch response json",
147            response_json.len(),
148            buffer_limit,
149        )?;
150
151        let payload: VmFetchResponsePayload =
152            serde_json::from_str(&response_json).context("parsing vm_fetch response json")?;
153        if !(100..=599).contains(&payload.status) {
154            return Err(ClientError::Sidecar(format!(
155                "HTTP response has invalid status {}",
156                payload.status
157            ))
158            .into());
159        }
160
161        // Base64-decode the response body (TS `Buffer.from(body ?? "", "base64")`). An absent body is
162        // an empty body.
163        let decoded_body = match payload.body {
164            Some(encoded) => {
165                ensure_fetch_base64_body_within_limit(&encoded, buffer_limit)?;
166                BASE64
167                    .decode(encoded.as_bytes())
168                    .context("decoding base64 fetch response body")?
169            }
170            None => Vec::new(),
171        };
172        Ok(HttpResponse {
173            status: payload.status,
174            status_text: payload.status_text.unwrap_or_default(),
175            headers: payload.headers.unwrap_or_default().into_iter().collect(),
176            body: decoded_body,
177        })
178    }
179
180    /// The VM-scoped ownership used for the `VmFetch` wire request.
181    fn vm_fetch_ownership(&self) -> wire::OwnershipScope {
182        wire::OwnershipScope::VmOwnership(wire::VmOwnership {
183            connection_id: self.connection_id().to_string(),
184            session_id: self.wire_session_id().to_string(),
185            vm_id: self.vm_id().to_string(),
186        })
187    }
188
189    fn fetch_buffer_limit(&self) -> usize {
190        self.transport()
191            .max_frame_bytes()
192            .min(VM_FETCH_BUFFER_LIMIT_BYTES)
193    }
194}
195
196fn ensure_fetch_component_within_limit(
197    component: &str,
198    size: usize,
199    limit: usize,
200) -> Result<(), ClientError> {
201    if size > limit {
202        return Err(ClientError::Sidecar(format!(
203            "{component} is {size} bytes, limit is {limit}"
204        )));
205    }
206    Ok(())
207}
208
209fn ensure_fetch_base64_body_within_limit(encoded: &str, limit: usize) -> Result<(), ClientError> {
210    ensure_fetch_component_within_limit("fetch response body base64", encoded.len(), limit)?;
211    ensure_fetch_component_within_limit(
212        "fetch response body",
213        base64_decoded_upper_bound(encoded.len()),
214        limit,
215    )
216}
217
218fn ensure_fetch_request_payload_within_limit(
219    method: &str,
220    path: &str,
221    headers_json: &str,
222    body: Option<&str>,
223    limit: usize,
224) -> Result<(), ClientError> {
225    let size = method
226        .len()
227        .saturating_add(path.len())
228        .saturating_add(headers_json.len())
229        .saturating_add(body.map(str::len).unwrap_or_default());
230    ensure_fetch_component_within_limit("fetch request payload", size, limit)
231}
232
233fn base64_decoded_upper_bound(encoded_len: usize) -> usize {
234    encoded_len.saturating_add(3) / 4 * 3
235}
236
237#[cfg(test)]
238mod tests {
239    use super::{
240        base64_decoded_upper_bound, ensure_fetch_base64_body_within_limit,
241        ensure_fetch_component_within_limit, ensure_fetch_request_payload_within_limit,
242        VM_FETCH_BUFFER_LIMIT_BYTES,
243    };
244
245    #[test]
246    fn fetch_component_limit_rejects_oversized_buffers() {
247        assert!(ensure_fetch_component_within_limit("component", 8, 8).is_ok());
248
249        let error =
250            ensure_fetch_component_within_limit("component", 9, 8).expect_err("limit violation");
251        assert!(
252            error.to_string().contains("component is 9 bytes"),
253            "unexpected error: {error}"
254        );
255    }
256
257    #[test]
258    fn fetch_component_limit_rejects_expanded_request_text() {
259        let replacement = String::from_utf8_lossy(&[0xff]).into_owned();
260        assert_eq!(replacement.len(), 3);
261
262        let error = ensure_fetch_component_within_limit("fetch request body text", 3, 2)
263            .expect_err("expanded body text should exceed limit");
264        assert!(
265            error
266                .to_string()
267                .contains("fetch request body text is 3 bytes"),
268            "unexpected error: {error}"
269        );
270    }
271
272    #[test]
273    fn fetch_request_payload_limit_rejects_aggregate_oversize() {
274        let error =
275            ensure_fetch_request_payload_within_limit("POST", "/abc", "{}", Some("body"), 8)
276                .expect_err("aggregate request payload should exceed limit");
277        assert!(
278            error
279                .to_string()
280                .contains("fetch request payload is 14 bytes"),
281            "unexpected error: {error}"
282        );
283    }
284
285    #[test]
286    fn fetch_base64_guard_bounds_decoded_response_size() {
287        assert_eq!(base64_decoded_upper_bound(4), 3);
288        assert!(ensure_fetch_base64_body_within_limit("AAAA", 4).is_ok());
289
290        let error = ensure_fetch_base64_body_within_limit("AAAA", 2)
291            .expect_err("encoded body should exceed limit");
292        assert!(
293            error
294                .to_string()
295                .contains("fetch response body base64 is 4 bytes"),
296            "unexpected error: {error}"
297        );
298    }
299
300    #[test]
301    fn fetch_buffer_limit_is_fixed_to_default_frame_size() {
302        assert_eq!(
303            VM_FETCH_BUFFER_LIMIT_BYTES,
304            agentos_sidecar_client::wire::DEFAULT_MAX_FRAME_BYTES
305        );
306    }
307
308    // ── Security: AOSCLIENT-P3-fetch (N-010 guest-server VmFetch response) ───────────────────────
309    //
310    // Threat: a guest server controls the `VmFetch` RESPONSE JSON that the client parses. A hostile
311    // server returns an out-of-range status (70000 / 0), a malformed base64 body ("!!!"), or an
312    // over-limit base64 body. Each must be handled as a clean `Err` on the client — never a panic
313    // (a panic in the shared host process is cross-tenant DoS, F.4). This is a regression guard for
314    // the parse path in `AgentOs::fetch`: `serde_json::from_str` -> `StatusCode::from_u16` ->
315    // `ensure_fetch_base64_body_within_limit` -> `BASE64.decode`.
316    use super::{VmFetchResponsePayload, BASE64};
317    use base64::Engine as _;
318
319    /// A status that overflows u16 (70000) must fail JSON deserialization of the response payload,
320    /// not panic. `status` is typed `u16`, so serde rejects the out-of-range value.
321    #[test]
322    fn vm_fetch_response_overflowing_status_fails_deserialization_without_panic() {
323        let json = r#"{"status":70000}"#;
324        let parsed: Result<VmFetchResponsePayload, _> = serde_json::from_str(json);
325        assert!(
326            parsed.is_err(),
327            "AOSCLIENT-P3-fetch: status 70000 overflows u16 and must fail to deserialize, not panic"
328        );
329    }
330
331    /// A status of 0 deserializes (it is a valid u16) but must be rejected by
332    /// `http::StatusCode::from_u16`, mirroring the `fetch` status construction, without panic.
333    #[test]
334    fn vm_fetch_response_zero_status_is_rejected_by_status_code_without_panic() {
335        let json = r#"{"status":0}"#;
336        let payload: VmFetchResponsePayload =
337            serde_json::from_str(json).expect("status 0 is a valid u16 and should deserialize");
338        let status = http::StatusCode::from_u16(payload.status);
339        assert!(
340            status.is_err(),
341            "AOSCLIENT-P3-fetch: status code 0 must be rejected by StatusCode::from_u16, not panic"
342        );
343    }
344
345    /// A malformed base64 body ("!!!") must produce a decode `Err`, never a panic.
346    #[test]
347    fn vm_fetch_response_malformed_base64_body_errors_without_panic() {
348        // First the size guard passes for a tiny body, so we reach the decode step the way
349        // `fetch` does.
350        ensure_fetch_base64_body_within_limit("!!!", VM_FETCH_BUFFER_LIMIT_BYTES)
351            .expect("tiny body is within the limit");
352        let decoded = BASE64.decode("!!!".as_bytes());
353        assert!(
354            decoded.is_err(),
355            "AOSCLIENT-P3-fetch: malformed base64 response body \"!!!\" must error on decode, not panic"
356        );
357    }
358
359    /// An over-limit base64 body must be rejected by the size guard BEFORE any allocation/decode,
360    /// without panic.
361    #[test]
362    fn vm_fetch_response_over_limit_base64_body_is_rejected_before_decode() {
363        // An encoded length strictly greater than the limit trips the guard on the encoded size.
364        let oversized = "A".repeat(VM_FETCH_BUFFER_LIMIT_BYTES + 4);
365        let result = ensure_fetch_base64_body_within_limit(&oversized, VM_FETCH_BUFFER_LIMIT_BYTES);
366        let error = result.expect_err(
367            "AOSCLIENT-P3-fetch: an over-limit base64 body must be rejected before decode",
368        );
369        assert!(
370            error.to_string().contains("fetch response body base64"),
371            "AOSCLIENT-P3-fetch: over-limit base64 body must be rejected by the size guard, got: {error}"
372        );
373    }
374}