Skip to main content

lean_ctx/ipc/
runtime.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Bounded client for an explicitly provisioned local Intelligence session.
3//! This module neither admits policy nor discovers, installs or trusts a peer.
4//! Callers own fresh scoped keys, sequence allocation, revocation and fallback.
5
6use std::fmt;
7use std::time::{Duration, SystemTime, UNIX_EPOCH};
8
9use lean_ctx_protocol::runtime_exchange::{RuntimeRequestV1, RuntimeResponseV1};
10use lean_ctx_protocol::runtime_frame::{
11    RUNTIME_FRAME_HEADER_BYTES, RUNTIME_FRAME_NONCE_BYTES, RUNTIME_FRAME_TAG_BYTES,
12    RuntimeFrameDirection, decode_runtime_frame, encode_runtime_frame, runtime_payload_length,
13};
14use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
15use tokio::time::{Instant, timeout_at};
16
17use super::DaemonAddr;
18
19/// Content-free failures: never expose a key, endpoint or projection in logs.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum RuntimeExchangeError {
22    InvalidRequest,
23    InvalidEndpoint,
24    EntropyUnavailable,
25    DeadlineExceeded,
26    ConnectionUnavailable,
27    Io,
28    InvalidFrame,
29    InvalidResponse,
30    ClockUnavailable,
31}
32
33impl fmt::Display for RuntimeExchangeError {
34    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
35        formatter.write_str(match self {
36            Self::InvalidRequest => "invalid local runtime request",
37            Self::InvalidEndpoint => "invalid local runtime endpoint",
38            Self::EntropyUnavailable => "local runtime randomness unavailable",
39            Self::DeadlineExceeded => "local runtime deadline exceeded",
40            Self::ConnectionUnavailable => "local runtime connection unavailable",
41            Self::Io => "local runtime I/O failed",
42            Self::InvalidFrame => "invalid authenticated runtime frame",
43            Self::InvalidResponse => "invalid local runtime response",
44            Self::ClockUnavailable => "local runtime clock unavailable",
45        })
46    }
47}
48
49impl std::error::Error for RuntimeExchangeError {}
50
51/// Exchange one admitted request over a fresh connection to an explicit endpoint.
52///
53/// The caller must provision and verify the endpoint and peer independently, use
54/// a fresh capability-scoped session key, serialize sequence allocation, and retire
55/// the session on failure/reconnect. A valid MAC is not policy authorization.
56/// No default daemon socket or global HTTP token is used. All connect/write/read
57/// work shares ONE monotonic budget; even Windows connection retries are bounded.
58/// The stream is dropped on every return. The caller alone persists host receipts
59/// and decides whether to use the deterministic public fallback.
60pub async fn exchange(
61    address: &DaemonAddr,
62    key: &[u8; 32],
63    request: &RuntimeRequestV1,
64) -> Result<RuntimeResponseV1, RuntimeExchangeError> {
65    validate_local_address(address)?;
66    let (deadline, frame) = prepare_exchange(key, request)?;
67    let response = timeout_at(deadline, async {
68        let mut stream = super::connect(address)
69            .await
70            .map_err(|_| RuntimeExchangeError::ConnectionUnavailable)?;
71        exchange_connected(&mut stream, key, request, &frame).await
72    })
73    .await
74    .map_err(|_| RuntimeExchangeError::DeadlineExceeded)?;
75    finish_exchange(deadline, response)
76}
77
78/// Exchange over a caller-protected connected stream, including inherited Unix
79/// streams and one-use Windows named pipes. Authentication and deadline checks
80/// are identical to the explicit-endpoint exchange path.
81pub(crate) async fn exchange_inherited<S: AsyncRead + AsyncWrite + Unpin>(
82    stream: &mut S,
83    key: &[u8; 32],
84    request: &RuntimeRequestV1,
85) -> Result<RuntimeResponseV1, RuntimeExchangeError> {
86    let (deadline, frame) = prepare_exchange(key, request)?;
87    let response = timeout_at(deadline, exchange_connected(stream, key, request, &frame))
88        .await
89        .map_err(|_| RuntimeExchangeError::DeadlineExceeded)?;
90    finish_exchange(deadline, response)
91}
92
93fn prepare_exchange(
94    key: &[u8; 32],
95    request: &RuntimeRequestV1,
96) -> Result<(Instant, Vec<u8>), RuntimeExchangeError> {
97    let started = Instant::now();
98    let now = unix_millis()?;
99    request
100        .validate_at(now)
101        .map_err(|_| RuntimeExchangeError::InvalidRequest)?;
102    let deadline = started + Duration::from_millis(request.deadline_unix_ms - now);
103    let payload = request
104        .to_bytes()
105        .map_err(|_| RuntimeExchangeError::InvalidRequest)?;
106    let mut nonce = [0; RUNTIME_FRAME_NONCE_BYTES];
107    getrandom::fill(&mut nonce).map_err(|_| RuntimeExchangeError::EntropyUnavailable)?;
108    let frame = encode_runtime_frame(key, RuntimeFrameDirection::Request, &nonce, &payload)
109        .map_err(|_| RuntimeExchangeError::InvalidFrame)?;
110    ensure_remaining(deadline)?;
111    Ok((deadline, frame))
112}
113
114fn finish_exchange(
115    deadline: Instant,
116    response: Result<RuntimeResponseV1, RuntimeExchangeError>,
117) -> Result<RuntimeResponseV1, RuntimeExchangeError> {
118    // timeout_at can poll a ready future after its deadline; reject that too.
119    ensure_remaining(deadline)?;
120    response
121}
122
123fn validate_local_address(address: &DaemonAddr) -> Result<(), RuntimeExchangeError> {
124    let valid = match address {
125        #[cfg(unix)]
126        DaemonAddr::Unix(path) => path.is_absolute(),
127        #[cfg(windows)]
128        DaemonAddr::NamedPipe(name) => name.strip_prefix(r"\\.\pipe\").is_some_and(|suffix| {
129            !suffix.is_empty()
130                && suffix.len() <= 200
131                && !suffix
132                    .chars()
133                    .any(|ch| ch.is_control() || ch == '\\' || ch == '/')
134        }),
135    };
136    if !valid {
137        return Err(RuntimeExchangeError::InvalidEndpoint);
138    }
139    Ok(())
140}
141
142async fn exchange_connected<S: AsyncRead + AsyncWrite + Unpin>(
143    stream: &mut S,
144    key: &[u8; 32],
145    request: &RuntimeRequestV1,
146    frame: &[u8],
147) -> Result<RuntimeResponseV1, RuntimeExchangeError> {
148    stream
149        .write_all(frame)
150        .await
151        .map_err(|_| RuntimeExchangeError::Io)?;
152    stream.flush().await.map_err(|_| RuntimeExchangeError::Io)?;
153    let response_frame = read_frame(stream).await?;
154    let payload = decode_runtime_frame(key, RuntimeFrameDirection::Response, &response_frame)
155        .map_err(|_| RuntimeExchangeError::InvalidFrame)?;
156    RuntimeResponseV1::from_bytes(&payload, request, unix_millis()?)
157        .map_err(|_| RuntimeExchangeError::InvalidResponse)
158}
159
160async fn read_frame<S: AsyncRead + Unpin>(stream: &mut S) -> Result<Vec<u8>, RuntimeExchangeError> {
161    let mut header = [0_u8; RUNTIME_FRAME_HEADER_BYTES];
162    stream
163        .read_exact(&mut header)
164        .await
165        .map_err(|_| RuntimeExchangeError::Io)?;
166    // Validate magic/version and the length limit before allocation or body reads.
167    let length = runtime_payload_length(&header).map_err(|_| RuntimeExchangeError::InvalidFrame)?;
168    let mut frame = vec![
169        0;
170        RUNTIME_FRAME_HEADER_BYTES
171            + RUNTIME_FRAME_NONCE_BYTES
172            + RUNTIME_FRAME_TAG_BYTES
173            + length
174    ];
175    frame[..RUNTIME_FRAME_HEADER_BYTES].copy_from_slice(&header);
176    stream
177        .read_exact(&mut frame[RUNTIME_FRAME_HEADER_BYTES..])
178        .await
179        .map_err(|_| RuntimeExchangeError::Io)?;
180    Ok(frame)
181}
182
183fn ensure_remaining(deadline: Instant) -> Result<(), RuntimeExchangeError> {
184    if Instant::now() >= deadline {
185        return Err(RuntimeExchangeError::DeadlineExceeded);
186    }
187    Ok(())
188}
189
190fn unix_millis() -> Result<u64, RuntimeExchangeError> {
191    SystemTime::now()
192        .duration_since(UNIX_EPOCH)
193        .ok()
194        .and_then(|duration| u64::try_from(duration.as_millis()).ok())
195        .ok_or(RuntimeExchangeError::ClockUnavailable)
196}
197
198#[cfg(test)]
199mod tests;