1use 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
25pub const DEFAULT_PORT: u16 = 8_787;
27
28#[derive(Clone)]
30pub struct BearerToken {
31 digest: [u8; 32],
32}
33
34impl BearerToken {
35 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#[derive(Clone, Debug, Eq, PartialEq)]
76pub struct ServerLimits {
77 pub request_body_bytes: usize,
79 pub json_depth: usize,
81 pub json_nodes: usize,
83 pub request_body_timeout: Duration,
85 pub batch_items: usize,
87 pub concurrent_operations: usize,
89 pub response_bytes: usize,
91 pub proof_bytes: usize,
93 pub witness_bytes: u64,
95 pub query: ExecutionLimits,
97 pub exact_retrieval: ExactRetrievalLimits,
99 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#[derive(Clone, Debug)]
220pub struct ServerConfig {
221 pub data_dir: PathBuf,
223 pub bind: SocketAddr,
225 pub bearer_token: Option<BearerToken>,
227 pub limits: ServerLimits,
229}
230
231impl ServerConfig {
232 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#[derive(Clone, Debug, Error, Eq, PartialEq)]
259pub enum ServerConfigError {
260 #[error("server data-directory path must not be empty")]
262 EmptyDataDirectory,
263 #[error("non-loopback bind {bind} requires a bearer token")]
265 RemoteBindRequiresAuthentication {
266 bind: SocketAddr,
268 },
269 #[error("bearer token is {actual} bytes; required range is {minimum}..={maximum}")]
271 InvalidBearerTokenLength {
272 minimum: usize,
274 maximum: usize,
276 actual: usize,
278 },
279 #[error("bearer token must contain only visible ASCII without whitespace")]
281 InvalidBearerTokenCharacter,
282 #[error("server resource limits must be nonzero")]
284 ZeroLimit,
285 #[error("JSON depth limit {actual} exceeds canonical maximum {maximum}")]
287 JsonDepthTooLarge {
288 maximum: usize,
290 actual: usize,
292 },
293 #[error("JSON node limit {actual} exceeds canonical maximum {maximum}")]
295 JsonNodesTooLarge {
296 maximum: usize,
298 actual: usize,
300 },
301 #[error("proof limit {actual} exceeds canonical maximum {maximum}")]
303 ProofLimitTooLarge {
304 maximum: u64,
306 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}