1#[allow(dead_code)] mod chunk;
7#[allow(dead_code)] mod connection;
9#[allow(dead_code)] mod database;
11mod error;
12#[allow(dead_code)] mod handshake;
14#[allow(dead_code)] mod message;
16#[allow(dead_code)] mod packstream;
18mod server;
19#[allow(dead_code)] mod state;
21#[allow(dead_code)] mod value;
23
24#[cfg(feature = "fuzzing")]
25#[doc(hidden)]
26pub mod fuzzing {
27 use crate::packstream::PackstreamLimits;
28
29 const FUZZ_INPUT_BYTES: usize = 64 * 1024;
30
31 fn limits() -> PackstreamLimits {
32 PackstreamLimits {
33 max_input_bytes: FUZZ_INPUT_BYTES,
34 max_string_bytes: FUZZ_INPUT_BYTES,
35 max_byte_array_bytes: FUZZ_INPUT_BYTES,
36 max_collection_items: 4096,
37 max_nesting_depth: 16,
38 }
39 }
40
41 pub fn handshake(data: &[u8]) {
42 let mut request = [0_u8; 20];
43 let length = request.len().min(data.len());
44 request[..length].copy_from_slice(&data[..length]);
45 let _ = crate::handshake::negotiate_request(&request);
46
47 request[..4].copy_from_slice(&crate::handshake::BOLT_MAGIC_PREAMBLE.to_be_bytes());
48 let _ = crate::handshake::negotiate_request(&request);
49 }
50
51 pub async fn chunk_frames(data: &[u8]) {
52 let mut input = data;
53 while !input.is_empty() {
54 if crate::chunk::read_frame(&mut input, FUZZ_INPUT_BYTES, 4096)
55 .await
56 .is_err()
57 {
58 break;
59 }
60 }
61 }
62
63 pub fn packstream(data: &[u8]) {
64 let _ = crate::packstream::decode(data, limits());
65 }
66
67 pub fn message(data: &[u8]) {
68 let _ = crate::message::decode_request(data, limits());
69 }
70}
71
72use std::collections::HashSet;
73use std::fmt;
74use std::fs;
75use std::net::SocketAddr;
76use std::path::{Path, PathBuf};
77use std::sync::Arc;
78use std::time::Duration;
79
80use sha2::{Digest, Sha256};
81use subtle::{Choice, ConstantTimeEq};
82
83pub use error::{BoltError, Result};
84pub use server::BoltServer;
85pub use tokio_util::sync::CancellationToken;
86
87#[derive(Clone, Debug, PartialEq, Eq)]
89pub struct BoltLimits {
90 pub max_connections: usize,
91 pub handshake_timeout: Duration,
92 pub authentication_timeout: Duration,
93 pub connection_idle_timeout: Duration,
94 pub max_unauthenticated_message_bytes: usize,
95 pub max_unauthenticated_collection_items: usize,
96 pub max_unauthenticated_nesting_depth: usize,
97 pub max_message_bytes: usize,
98 pub max_chunks_per_message: usize,
99 pub outbound_chunk_bytes: usize,
100 pub max_nesting_depth: usize,
101 pub max_collection_items: usize,
102 pub max_string_bytes: usize,
103 pub max_byte_array_bytes: usize,
104 pub database_command_capacity: usize,
105 pub transaction_timeout: Duration,
106 pub max_transaction_workspace_bytes: usize,
107 pub max_transaction_records: usize,
108 pub max_transaction_journal_bytes: u64,
109 pub max_query_memory_bytes: usize,
110 pub max_open_results_per_transaction: usize,
111 pub max_retained_rows: usize,
112 pub max_retained_bytes: usize,
113 pub shutdown_grace_period: Duration,
114}
115
116impl Default for BoltLimits {
117 fn default() -> Self {
118 Self {
119 max_connections: 64,
120 handshake_timeout: Duration::from_secs(5),
121 authentication_timeout: Duration::from_secs(30),
122 connection_idle_timeout: Duration::from_secs(30),
123 max_unauthenticated_message_bytes: 8 * 1024,
124 max_unauthenticated_collection_items: 64,
125 max_unauthenticated_nesting_depth: 4,
126 max_message_bytes: 8 * 1024 * 1024,
127 max_chunks_per_message: 4096,
128 outbound_chunk_bytes: u16::MAX as usize,
129 max_nesting_depth: 64,
130 max_collection_items: 1_000_000,
131 max_string_bytes: 4 * 1024 * 1024,
132 max_byte_array_bytes: 4 * 1024 * 1024,
133 database_command_capacity: 8,
134 transaction_timeout: Duration::from_secs(30),
135 max_transaction_workspace_bytes: 64 * 1024 * 1024,
136 max_transaction_records: 1_000_000,
137 max_transaction_journal_bytes: 256 * 1024 * 1024,
138 max_query_memory_bytes: 64 * 1024 * 1024,
139 max_open_results_per_transaction: 64,
140 max_retained_rows: 100_000,
141 max_retained_bytes: 64 * 1024 * 1024,
142 shutdown_grace_period: Duration::from_secs(5),
143 }
144 }
145}
146
147impl BoltLimits {
148 pub fn validate(&self) -> Result<()> {
149 if self.max_connections == 0 {
150 return Err(BoltError::InvalidConfiguration(
151 "max_connections must be positive".into(),
152 ));
153 }
154 if self.handshake_timeout.is_zero()
155 || self.authentication_timeout.is_zero()
156 || self.connection_idle_timeout.is_zero()
157 {
158 return Err(BoltError::InvalidConfiguration(
159 "connection timeouts must be positive".into(),
160 ));
161 }
162 if self.max_unauthenticated_message_bytes == 0
163 || self.max_unauthenticated_collection_items == 0
164 || self.max_unauthenticated_nesting_depth == 0
165 {
166 return Err(BoltError::InvalidConfiguration(
167 "unauthenticated message limits must be positive".into(),
168 ));
169 }
170 if self.max_message_bytes == 0 {
171 return Err(BoltError::InvalidConfiguration(
172 "max_message_bytes must be positive".into(),
173 ));
174 }
175 if self.max_chunks_per_message == 0 {
176 return Err(BoltError::InvalidConfiguration(
177 "max_chunks_per_message must be positive".into(),
178 ));
179 }
180 if !(1..=u16::MAX as usize).contains(&self.outbound_chunk_bytes) {
181 return Err(BoltError::InvalidConfiguration(
182 "outbound_chunk_bytes must be between 1 and 65535".into(),
183 ));
184 }
185 if self.max_nesting_depth == 0
186 || self.max_collection_items == 0
187 || self.max_string_bytes == 0
188 || self.max_byte_array_bytes == 0
189 {
190 return Err(BoltError::InvalidConfiguration(
191 "PackStream limits must be positive".into(),
192 ));
193 }
194 if self.database_command_capacity == 0
195 || self.transaction_timeout.is_zero()
196 || self.max_transaction_workspace_bytes == 0
197 || self.max_transaction_records == 0
198 || self.max_transaction_journal_bytes == 0
199 || self.max_query_memory_bytes == 0
200 || self.max_open_results_per_transaction == 0
201 || self.max_retained_rows == 0
202 || self.max_retained_bytes == 0
203 || self.shutdown_grace_period.is_zero()
204 {
205 return Err(BoltError::InvalidConfiguration(
206 "database, query, and retained-result limits must be positive".into(),
207 ));
208 }
209 Ok(())
210 }
211
212 fn inbound_message_bytes(&self, authenticated: bool) -> usize {
213 if authenticated {
214 self.max_message_bytes
215 } else {
216 self.max_message_bytes
217 .min(self.max_unauthenticated_message_bytes)
218 }
219 }
220
221 fn packstream_limits(&self, authenticated: bool) -> packstream::PackstreamLimits {
222 let mut limits: packstream::PackstreamLimits = self.into();
223 if !authenticated {
224 limits.max_input_bytes = limits
225 .max_input_bytes
226 .min(self.max_unauthenticated_message_bytes);
227 limits.max_collection_items = limits
228 .max_collection_items
229 .min(self.max_unauthenticated_collection_items);
230 limits.max_nesting_depth = limits
231 .max_nesting_depth
232 .min(self.max_unauthenticated_nesting_depth);
233 limits.max_string_bytes = limits.max_string_bytes.min(limits.max_input_bytes);
234 limits.max_byte_array_bytes = limits.max_byte_array_bytes.min(limits.max_input_bytes);
235 }
236 limits
237 }
238}
239
240impl From<&BoltLimits> for packstream::PackstreamLimits {
241 fn from(limits: &BoltLimits) -> Self {
242 Self {
243 max_input_bytes: limits.max_message_bytes,
244 max_string_bytes: limits.max_string_bytes,
245 max_byte_array_bytes: limits.max_byte_array_bytes,
246 max_collection_items: limits.max_collection_items,
247 max_nesting_depth: limits.max_nesting_depth,
248 }
249 }
250}
251
252#[derive(Clone, Debug, PartialEq, Eq)]
254pub struct BoltServerConfig {
255 pub listen_addr: SocketAddr,
256 pub advertised_addr: SocketAddr,
257 pub database_path: PathBuf,
258 pub auth: Option<BoltAuth>,
260 pub tls: Option<BoltTlsConfig>,
262 pub limits: BoltLimits,
263}
264
265#[derive(Clone, PartialEq, Eq)]
270pub struct BoltAuth(Arc<BoltAuthData>);
271
272#[derive(PartialEq, Eq)]
273struct BoltAuthData {
274 credentials: Vec<BoltCredential>,
275}
276
277#[derive(PartialEq, Eq)]
278struct BoltCredential {
279 read_only: bool,
280 username_digest: [u8; 32],
281 password_digest: [u8; 32],
282}
283
284impl BoltAuth {
285 pub fn new(username: impl AsRef<str>, password: impl AsRef<str>) -> Result<Self> {
286 let username = username.as_ref();
287 let password = password.as_ref();
288 if username
289 .chars()
290 .any(|character| matches!(character, ':' | '\r' | '\n'))
291 {
292 return Err(BoltError::InvalidConfiguration(
293 "Bolt authentication username contains an auth-file delimiter".into(),
294 ));
295 }
296 if password.is_empty() {
297 return Err(BoltError::InvalidConfiguration(
298 "Bolt authentication password must not be empty".into(),
299 ));
300 }
301 if password
302 .chars()
303 .any(|character| matches!(character, '\r' | '\n'))
304 {
305 return Err(BoltError::InvalidConfiguration(
306 "Bolt authentication password contains an auth-file line ending".into(),
307 ));
308 }
309 Ok(Self(Arc::new(BoltAuthData {
310 credentials: vec![BoltCredential {
311 read_only: false,
312 username_digest: Sha256::digest(username.as_bytes()).into(),
313 password_digest: Sha256::digest(password.as_bytes()).into(),
314 }],
315 })))
316 }
317
318 pub fn from_file(path: impl AsRef<Path>) -> Result<Self> {
320 let path = path.as_ref();
321 let contents = fs::read_to_string(path).map_err(|error| {
322 BoltError::InvalidConfiguration(format!(
323 "failed to read Bolt auth file {}: {error}",
324 path.display()
325 ))
326 })?;
327 Self::from_lines(
328 contents
329 .lines()
330 .enumerate()
331 .map(|(index, line)| (index + 1, line)),
332 )
333 }
334
335 fn from_lines<'a>(lines: impl IntoIterator<Item = (usize, &'a str)>) -> Result<Self> {
336 let mut credentials = Vec::new();
337 let mut usernames = HashSet::new();
338 for (line_number, line) in lines {
339 let mut fields = line.splitn(3, ':');
340 let access = fields.next().expect("split returns at least one field");
341 let Some(username) = fields.next() else {
342 return Err(invalid_auth_file_line(
343 line_number,
344 "must use the format <rw|ro>:<user>:<password>",
345 ));
346 };
347 let Some(password) = fields.next() else {
348 return Err(invalid_auth_file_line(
349 line_number,
350 "must use the format <rw|ro>:<user>:<password>",
351 ));
352 };
353 let read_only = match access {
354 "rw" => false,
355 "ro" => true,
356 _ => {
357 return Err(invalid_auth_file_line(
358 line_number,
359 "access must be `rw` or `ro`",
360 ));
361 }
362 };
363 if password.is_empty() {
364 return Err(invalid_auth_file_line(
365 line_number,
366 "password must not be empty",
367 ));
368 }
369 let username_digest: [u8; 32] = Sha256::digest(username.as_bytes()).into();
370 if !usernames.insert(username_digest) {
371 return Err(invalid_auth_file_line(
372 line_number,
373 "username is duplicated",
374 ));
375 }
376 credentials.push(BoltCredential {
377 read_only,
378 username_digest,
379 password_digest: Sha256::digest(password.as_bytes()).into(),
380 });
381 }
382 if credentials.is_empty() {
383 return Err(BoltError::InvalidConfiguration(
384 "Bolt auth file must contain at least one credential".into(),
385 ));
386 }
387 Ok(Self(Arc::new(BoltAuthData { credentials })))
388 }
389
390 pub(crate) fn authenticate(&self, username: &str, password: &str) -> Option<bool> {
391 let username_digest: [u8; 32] = Sha256::digest(username.as_bytes()).into();
392 let password_digest: [u8; 32] = Sha256::digest(password.as_bytes()).into();
393 let mut read_only_match = Choice::from(0);
394 let mut read_write_match = Choice::from(0);
395 for credential in &self.0.credentials {
396 let matched = credential.username_digest.ct_eq(&username_digest)
397 & credential.password_digest.ct_eq(&password_digest);
398 if credential.read_only {
399 read_only_match |= matched;
400 } else {
401 read_write_match |= matched;
402 }
403 }
404 if bool::from(read_only_match) {
405 Some(true)
406 } else if bool::from(read_write_match) {
407 Some(false)
408 } else {
409 None
410 }
411 }
412}
413
414fn invalid_auth_file_line(line_number: usize, reason: &str) -> BoltError {
415 BoltError::InvalidConfiguration(format!("Bolt auth file line {line_number} {reason}"))
416}
417
418impl fmt::Debug for BoltAuth {
419 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
420 formatter.write_str("BoltAuth([REDACTED])")
421 }
422}
423
424#[derive(Clone, Debug, PartialEq, Eq)]
431pub struct BoltTlsConfig {
432 pub certificate_file: PathBuf,
433 pub ca_file: Option<PathBuf>,
434}
435
436impl BoltServerConfig {
437 pub fn validate(&self) -> Result<()> {
438 if self.database_path.as_os_str().is_empty() {
439 return Err(BoltError::InvalidConfiguration(
440 "database_path must not be empty".into(),
441 ));
442 }
443 if let Some(tls) = &self.tls {
444 if tls.certificate_file.as_os_str().is_empty() {
445 return Err(BoltError::InvalidConfiguration(
446 "TLS certificate file must not be empty".into(),
447 ));
448 }
449 if tls
450 .ca_file
451 .as_ref()
452 .is_some_and(|path| path.as_os_str().is_empty())
453 {
454 return Err(BoltError::InvalidConfiguration(
455 "TLS CA file must not be empty".into(),
456 ));
457 }
458 }
459 self.limits.validate()
460 }
461}
462
463#[cfg(test)]
464mod tests {
465 use super::*;
466
467 #[test]
468 fn bolt_auth_validates_hashes_and_redacts_credentials() {
469 let auth = BoltAuth::new("alice", "secret:with:colons").unwrap();
470 assert_eq!(
471 auth.authenticate("alice", "secret:with:colons"),
472 Some(false)
473 );
474 assert_eq!(auth.authenticate("alice", "wrong"), None);
475 assert_eq!(auth.authenticate("bob", "secret:with:colons"), None);
476 let empty_username = BoltAuth::new("", "secret").unwrap();
477 assert_eq!(empty_username.authenticate("", "secret"), Some(false));
478 assert_eq!(format!("{auth:?}"), "BoltAuth([REDACTED])");
479 }
480
481 #[test]
482 fn bolt_auth_file_loads_multiple_credentials_and_rejects_invalid_lines() {
483 let directory = tempfile::tempdir().unwrap();
484 let path = directory.path().join("auth.txt");
485 fs::write(&path, "rw:alice:secret:with:colons\r\nro::password\n").unwrap();
486 let auth = BoltAuth::from_file(&path).unwrap();
487 assert_eq!(
488 auth.authenticate("alice", "secret:with:colons"),
489 Some(false)
490 );
491 assert_eq!(auth.authenticate("", "password"), Some(true));
492 assert_eq!(auth.authenticate("", "wrong"), None);
493 assert_eq!(format!("{auth:?}"), "BoltAuth([REDACTED])");
494
495 for (contents, expected) in [
496 ("", "at least one credential"),
497 ("missing-separator\n", "line 1 must use the format"),
498 ("alice:password\n", "line 1 must use the format"),
499 ("write:alice:password\n", "line 1 access must be"),
500 ("rw:alice:\n", "line 1 password must not be empty"),
501 ("rw:alice:one\n\nro:bob:two\n", "line 2 must use the format"),
502 (
503 "rw:alice:one\nro:alice:two\n",
504 "line 2 username is duplicated",
505 ),
506 ] {
507 fs::write(&path, contents).unwrap();
508 assert!(matches!(
509 BoltAuth::from_file(&path),
510 Err(BoltError::InvalidConfiguration(message)) if message.contains(expected)
511 ));
512 }
513
514 fs::write(&path, [0xff]).unwrap();
515 assert!(matches!(
516 BoltAuth::from_file(&path),
517 Err(BoltError::InvalidConfiguration(message))
518 if message.contains("failed to read Bolt auth file")
519 ));
520 }
521
522 #[test]
523 fn pre_authentication_limits_match_neo4j_defaults() {
524 let limits = BoltLimits::default();
525 let pre_authentication = limits.packstream_limits(false);
526 assert_eq!(limits.inbound_message_bytes(false), 8 * 1024);
527 assert_eq!(pre_authentication.max_input_bytes, 8 * 1024);
528 assert_eq!(pre_authentication.max_collection_items, 64);
529 assert_eq!(pre_authentication.max_nesting_depth, 4);
530
531 let authenticated = limits.packstream_limits(true);
532 assert_eq!(authenticated.max_input_bytes, limits.max_message_bytes);
533 assert_eq!(
534 authenticated.max_collection_items,
535 limits.max_collection_items
536 );
537 assert_eq!(authenticated.max_nesting_depth, limits.max_nesting_depth);
538 }
539
540 #[test]
541 fn pre_authentication_limits_cannot_weaken_general_limits() {
542 let limits = BoltLimits {
543 max_unauthenticated_message_bytes: 2048,
544 max_unauthenticated_collection_items: 20,
545 max_unauthenticated_nesting_depth: 10,
546 max_message_bytes: 1024,
547 max_collection_items: 10,
548 max_nesting_depth: 5,
549 ..BoltLimits::default()
550 };
551 let effective = limits.packstream_limits(false);
552 assert_eq!(limits.inbound_message_bytes(false), 1024);
553 assert_eq!(effective.max_input_bytes, 1024);
554 assert_eq!(effective.max_collection_items, 10);
555 assert_eq!(effective.max_nesting_depth, 5);
556 }
557
558 #[test]
559 fn rejects_disabled_pre_authentication_limits() {
560 for limits in [
561 BoltLimits {
562 max_unauthenticated_message_bytes: 0,
563 ..BoltLimits::default()
564 },
565 BoltLimits {
566 max_unauthenticated_collection_items: 0,
567 ..BoltLimits::default()
568 },
569 BoltLimits {
570 max_unauthenticated_nesting_depth: 0,
571 ..BoltLimits::default()
572 },
573 ] {
574 assert!(matches!(
575 limits.validate(),
576 Err(BoltError::InvalidConfiguration(message))
577 if message.contains("unauthenticated message limits")
578 ));
579 }
580 }
581
582 #[test]
583 fn rejects_disabled_transaction_resource_limits() {
584 for limits in [
585 BoltLimits {
586 max_transaction_records: 0,
587 ..BoltLimits::default()
588 },
589 BoltLimits {
590 max_transaction_journal_bytes: 0,
591 ..BoltLimits::default()
592 },
593 BoltLimits {
594 max_open_results_per_transaction: 0,
595 ..BoltLimits::default()
596 },
597 ] {
598 assert!(matches!(
599 limits.validate(),
600 Err(BoltError::InvalidConfiguration(message))
601 if message.contains("database, query, and retained-result limits")
602 ));
603 }
604 }
605}