Skip to main content

hyphae_server/
config.rs

1// SPDX-License-Identifier: Apache-2.0
2
3use std::{
4    fmt,
5    net::{IpAddr, Ipv4Addr, SocketAddr},
6    path::{Path, PathBuf},
7    time::Duration,
8};
9
10use hyphae_contracts::v1::ApiLimitsV1;
11use hyphae_core::MAX_VECTOR_DIMENSIONS;
12use hyphae_engine::{
13    MAX_DOCUMENT_BYTES, MAX_DOCUMENT_DEPTH, MAX_DOCUMENT_NODES, MAX_RESULT_PROOF_BYTES,
14    MAX_RETRIEVAL_PROOF_BYTES,
15};
16use hyphae_query::ExecutionLimits;
17use hyphae_retrieval::{ExactRetrievalLimits, LexicalLimits};
18use hyphae_storage::MAX_KEY_BYTES;
19use subtle::ConstantTimeEq;
20use thiserror::Error;
21
22const MIN_BEARER_TOKEN_BYTES: usize = 32;
23const MAX_BEARER_TOKEN_BYTES: usize = 4_096;
24
25/// Default loopback-only address used by `hyphae serve`.
26pub const DEFAULT_PORT: u16 = 8_787;
27
28/// One bearer credential retained only as a BLAKE3 digest.
29#[derive(Clone)]
30pub struct BearerToken {
31    digest: [u8; 32],
32}
33
34impl BearerToken {
35    /// Hashes a sufficiently strong opaque bearer secret for later
36    /// constant-time verification.
37    ///
38    /// # Errors
39    ///
40    /// Returns an error when the token is shorter than 32 bytes or longer
41    /// than 4096 bytes.
42    pub fn new(secret: impl AsRef<[u8]>) -> Result<Self, ServerConfigError> {
43        let secret = secret.as_ref();
44        if !(MIN_BEARER_TOKEN_BYTES..=MAX_BEARER_TOKEN_BYTES).contains(&secret.len()) {
45            return Err(ServerConfigError::InvalidBearerTokenLength {
46                minimum: MIN_BEARER_TOKEN_BYTES,
47                maximum: MAX_BEARER_TOKEN_BYTES,
48                actual: secret.len(),
49            });
50        }
51        if !secret.iter().all(|byte| (0x21..=0x7e).contains(byte)) {
52            return Err(ServerConfigError::InvalidBearerTokenCharacter);
53        }
54        Ok(Self {
55            digest: *blake3::hash(secret).as_bytes(),
56        })
57    }
58
59    pub(crate) fn verifies(&self, candidate: &[u8]) -> bool {
60        if !(MIN_BEARER_TOKEN_BYTES..=MAX_BEARER_TOKEN_BYTES).contains(&candidate.len()) {
61            return false;
62        }
63        let candidate = *blake3::hash(candidate).as_bytes();
64        bool::from(self.digest.ct_eq(&candidate))
65    }
66}
67
68impl fmt::Debug for BearerToken {
69    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
70        formatter.write_str("BearerToken([REDACTED])")
71    }
72}
73
74/// Complete resource policy enforced by one HTTP server process.
75#[derive(Clone, Debug, Eq, PartialEq)]
76pub struct ServerLimits {
77    /// Maximum complete JSON request bytes.
78    pub request_body_bytes: usize,
79    /// Maximum JSON nesting depth.
80    pub json_depth: usize,
81    /// Maximum JSON scalar, array, and object nodes.
82    pub json_nodes: usize,
83    /// Maximum time allowed to receive one complete JSON request body.
84    pub request_body_timeout: Duration,
85    /// Maximum records or keys in one atomic mutation batch.
86    pub batch_items: usize,
87    /// Maximum admitted concurrent data operations.
88    pub concurrent_operations: usize,
89    /// Maximum serialized JSON response bytes.
90    pub response_bytes: usize,
91    /// Maximum canonical proof bytes before base64 transport.
92    pub proof_bytes: usize,
93    /// Maximum downloadable snapshot witness bytes.
94    pub witness_bytes: u64,
95    /// Deterministic structured-query work, shape, result, and timeout limits.
96    pub query: ExecutionLimits,
97    /// Durable exact-retrieval work, result, byte, and timeout limits.
98    pub exact_retrieval: ExactRetrievalLimits,
99    /// Provider-free lexical work, result, token, and timeout limits.
100    pub lexical_retrieval: LexicalLimits,
101}
102
103impl Default for ServerLimits {
104    fn default() -> Self {
105        Self {
106            request_body_bytes: 4 * 1024 * 1024,
107            json_depth: MAX_DOCUMENT_DEPTH,
108            json_nodes: 100_000,
109            request_body_timeout: Duration::from_secs(10),
110            batch_items: 1_000,
111            concurrent_operations: 16,
112            response_bytes: 32 * 1024 * 1024,
113            proof_bytes: 16 * 1024 * 1024,
114            witness_bytes: 512 * 1024 * 1024,
115            query: ExecutionLimits::default(),
116            exact_retrieval: ExactRetrievalLimits::default(),
117            lexical_retrieval: LexicalLimits::default(),
118        }
119    }
120}
121
122impl ServerLimits {
123    pub(crate) fn validate(&self) -> Result<(), ServerConfigError> {
124        let scalar_limits = [
125            self.request_body_bytes,
126            self.json_depth,
127            self.json_nodes,
128            self.batch_items,
129            self.concurrent_operations,
130            self.response_bytes,
131            self.proof_bytes,
132            self.query.max_returned_records,
133            self.query.max_groups,
134            self.query.max_filter_nodes,
135            self.query.max_filter_depth,
136            self.query.max_sort_fields,
137            self.query.max_group_fields,
138            self.query.max_metrics,
139            self.exact_retrieval.max_returned,
140            self.lexical_retrieval.max_returned,
141        ];
142        if scalar_limits.contains(&0)
143            || self.witness_bytes == 0
144            || self.query.max_scanned_records == 0
145            || self.query.max_matched_records == 0
146            || self.exact_retrieval.max_candidates == 0
147            || self.exact_retrieval.max_candidate_bytes == 0
148            || self.lexical_retrieval.max_documents == 0
149            || self.lexical_retrieval.max_tokens == 0
150            || self.lexical_retrieval.max_candidates == 0
151            || self.request_body_timeout.is_zero()
152            || self.query.timeout.is_zero()
153            || self.exact_retrieval.timeout.is_zero()
154            || self.lexical_retrieval.timeout.is_zero()
155        {
156            return Err(ServerConfigError::ZeroLimit);
157        }
158        if self.json_depth > MAX_DOCUMENT_DEPTH {
159            return Err(ServerConfigError::JsonDepthTooLarge {
160                maximum: MAX_DOCUMENT_DEPTH,
161                actual: self.json_depth,
162            });
163        }
164        if self.json_nodes > MAX_DOCUMENT_NODES {
165            return Err(ServerConfigError::JsonNodesTooLarge {
166                maximum: MAX_DOCUMENT_NODES,
167                actual: self.json_nodes,
168            });
169        }
170        let maximum_proof_bytes = MAX_RESULT_PROOF_BYTES.min(MAX_RETRIEVAL_PROOF_BYTES);
171        if u64::try_from(self.proof_bytes).unwrap_or(u64::MAX) > maximum_proof_bytes {
172            return Err(ServerConfigError::ProofLimitTooLarge {
173                maximum: maximum_proof_bytes,
174                actual: u64::try_from(self.proof_bytes).unwrap_or(u64::MAX),
175            });
176        }
177        Ok(())
178    }
179
180    pub(crate) fn as_contract(&self) -> ApiLimitsV1 {
181        ApiLimitsV1 {
182            key_bytes: usize_to_u64(MAX_KEY_BYTES),
183            document_bytes: usize_to_u64(MAX_DOCUMENT_BYTES),
184            request_body_bytes: usize_to_u64(self.request_body_bytes),
185            json_depth: usize_to_u64(self.json_depth),
186            json_nodes: usize_to_u64(self.json_nodes),
187            request_body_timeout_ms: duration_millis(self.request_body_timeout),
188            batch_items: usize_to_u64(self.batch_items),
189            scanned_records: self.query.max_scanned_records,
190            matched_records: self.query.max_matched_records,
191            result_rows: usize_to_u64(self.query.max_returned_records),
192            aggregation_groups: usize_to_u64(self.query.max_groups),
193            filter_nodes: usize_to_u64(self.query.max_filter_nodes),
194            filter_depth: usize_to_u64(self.query.max_filter_depth),
195            sort_fields: usize_to_u64(self.query.max_sort_fields),
196            group_fields: usize_to_u64(self.query.max_group_fields),
197            metrics: usize_to_u64(self.query.max_metrics),
198            concurrent_operations: usize_to_u64(self.concurrent_operations),
199            query_timeout_ms: duration_millis(self.query.timeout),
200            proof_bytes: usize_to_u64(self.proof_bytes),
201            witness_bytes: self.witness_bytes,
202            response_bytes: usize_to_u64(self.response_bytes),
203            vector_dimensions: usize_to_u64(MAX_VECTOR_DIMENSIONS),
204            retrieval_candidates: self.exact_retrieval.max_candidates,
205            retrieval_candidate_bytes: self.exact_retrieval.max_candidate_bytes,
206            retrieval_results: usize_to_u64(self.exact_retrieval.max_returned),
207            retrieval_timeout_ms: duration_millis(self.exact_retrieval.timeout),
208            retrieval_proof_bytes: usize_to_u64(self.proof_bytes),
209            lexical_documents: self.lexical_retrieval.max_documents,
210            lexical_tokens: self.lexical_retrieval.max_tokens,
211            lexical_candidates: self.lexical_retrieval.max_candidates,
212            lexical_results: usize_to_u64(self.lexical_retrieval.max_returned),
213            lexical_timeout_ms: duration_millis(self.lexical_retrieval.timeout),
214        }
215    }
216}
217
218/// Validated input for one owned loopback-first Hyphae server.
219#[derive(Clone, Debug)]
220pub struct ServerConfig {
221    /// Exclusively owned Hyphae data directory.
222    pub data_dir: PathBuf,
223    /// Listener address; defaults to `127.0.0.1:8787`.
224    pub bind: SocketAddr,
225    /// Optional bearer credential. Mandatory for non-loopback binds.
226    pub bearer_token: Option<BearerToken>,
227    /// Effective bounded-resource policy.
228    pub limits: ServerLimits,
229}
230
231impl ServerConfig {
232    /// Creates the secure loopback default for one data directory.
233    pub fn new(data_dir: impl Into<PathBuf>) -> Self {
234        Self {
235            data_dir: data_dir.into(),
236            bind: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), DEFAULT_PORT),
237            bearer_token: None,
238            limits: ServerLimits::default(),
239        }
240    }
241
242    pub(crate) fn validate(&self) -> Result<(), ServerConfigError> {
243        if self.data_dir.as_os_str().is_empty() {
244            return Err(ServerConfigError::EmptyDataDirectory);
245        }
246        if !self.bind.ip().is_loopback() && self.bearer_token.is_none() {
247            return Err(ServerConfigError::RemoteBindRequiresAuthentication { bind: self.bind });
248        }
249        self.limits.validate()
250    }
251
252    pub(crate) fn data_dir(&self) -> &Path {
253        &self.data_dir
254    }
255}
256
257/// Invalid secure-server configuration rejected before socket bind.
258#[derive(Clone, Debug, Error, Eq, PartialEq)]
259pub enum ServerConfigError {
260    /// The data-directory path is empty.
261    #[error("server data-directory path must not be empty")]
262    EmptyDataDirectory,
263    /// A non-loopback listener was requested without bearer authentication.
264    #[error("non-loopback bind {bind} requires a bearer token")]
265    RemoteBindRequiresAuthentication {
266        /// Rejected listener address.
267        bind: SocketAddr,
268    },
269    /// Bearer token length does not meet the local security policy.
270    #[error("bearer token is {actual} bytes; required range is {minimum}..={maximum}")]
271    InvalidBearerTokenLength {
272        /// Minimum accepted bytes.
273        minimum: usize,
274        /// Maximum accepted bytes.
275        maximum: usize,
276        /// Observed bytes.
277        actual: usize,
278    },
279    /// Bearer tokens must be representable safely in one HTTP header.
280    #[error("bearer token must contain only visible ASCII without whitespace")]
281    InvalidBearerTokenCharacter,
282    /// Every configured budget must be positive.
283    #[error("server resource limits must be nonzero")]
284    ZeroLimit,
285    /// JSON depth policy cannot exceed the canonical document limit.
286    #[error("JSON depth limit {actual} exceeds canonical maximum {maximum}")]
287    JsonDepthTooLarge {
288        /// Canonical maximum.
289        maximum: usize,
290        /// Requested limit.
291        actual: usize,
292    },
293    /// JSON node policy cannot exceed the canonical document limit.
294    #[error("JSON node limit {actual} exceeds canonical maximum {maximum}")]
295    JsonNodesTooLarge {
296        /// Canonical maximum.
297        maximum: usize,
298        /// Requested limit.
299        actual: usize,
300    },
301    /// Proof policy cannot exceed the canonical proof codec hard bound.
302    #[error("proof limit {actual} exceeds canonical maximum {maximum}")]
303    ProofLimitTooLarge {
304        /// Canonical maximum.
305        maximum: u64,
306        /// Requested limit.
307        actual: u64,
308    },
309}
310
311fn usize_to_u64(value: usize) -> u64 {
312    u64::try_from(value).unwrap_or(u64::MAX)
313}
314
315fn duration_millis(value: Duration) -> u64 {
316    u64::try_from(value.as_millis()).unwrap_or(u64::MAX)
317}