1mod database;
9mod error;
10mod request;
11mod response;
12mod server;
13mod transaction;
14mod value;
15
16use std::collections::HashSet;
17use std::fmt;
18use std::fs;
19use std::net::SocketAddr;
20use std::path::{Path, PathBuf};
21use std::sync::Arc;
22use std::time::Duration;
23
24use sha2::{Digest, Sha256};
25use subtle::{Choice, ConstantTimeEq};
26
27pub use error::{QueryApiError, Result};
28pub use server::QueryApiServer;
29pub use tokio_util::sync::CancellationToken;
30
31#[derive(Clone, Debug, PartialEq, Eq)]
33pub struct QueryApiLimits {
34 pub max_concurrent_requests: usize,
35 pub max_request_bytes: usize,
36 pub max_result_rows: usize,
37 pub max_result_bytes: usize,
38 pub max_open_transactions: usize,
39 pub transaction_idle_timeout: Duration,
40 pub transaction_timeout: Duration,
41 pub max_transaction_workspace_bytes: usize,
42 pub max_transaction_records: usize,
43 pub max_transaction_journal_bytes: u64,
44 pub max_query_memory_bytes: usize,
45 pub database_command_capacity: usize,
46 pub tls_handshake_timeout: Duration,
47 pub shutdown_grace_period: Duration,
48}
49
50impl Default for QueryApiLimits {
51 fn default() -> Self {
52 Self {
53 max_concurrent_requests: 64,
54 max_request_bytes: 8 * 1024 * 1024,
55 max_result_rows: 100_000,
56 max_result_bytes: 64 * 1024 * 1024,
57 max_open_transactions: 64,
58 transaction_idle_timeout: Duration::from_secs(60),
59 transaction_timeout: Duration::from_secs(30),
60 max_transaction_workspace_bytes: 64 * 1024 * 1024,
61 max_transaction_records: 1_000_000,
62 max_transaction_journal_bytes: 256 * 1024 * 1024,
63 max_query_memory_bytes: 64 * 1024 * 1024,
64 database_command_capacity: 4,
65 tls_handshake_timeout: Duration::from_secs(5),
66 shutdown_grace_period: Duration::from_secs(5),
67 }
68 }
69}
70
71impl QueryApiLimits {
72 fn validate(&self) -> Result<()> {
73 if self.max_concurrent_requests == 0
74 || self.max_request_bytes == 0
75 || self.max_result_rows == 0
76 || self.max_result_bytes == 0
77 || self.max_open_transactions == 0
78 || self.transaction_idle_timeout.is_zero()
79 || self.transaction_timeout.is_zero()
80 || self.max_transaction_workspace_bytes == 0
81 || self.max_transaction_records == 0
82 || self.max_transaction_journal_bytes == 0
83 || self.max_query_memory_bytes == 0
84 || self.database_command_capacity == 0
85 || self.tls_handshake_timeout.is_zero()
86 || self.shutdown_grace_period.is_zero()
87 {
88 return Err(QueryApiError::InvalidConfiguration(
89 "Query API resource limits must be positive".into(),
90 ));
91 }
92 Ok(())
93 }
94}
95
96#[derive(Clone, Debug, PartialEq, Eq)]
98pub struct QueryApiTlsConfig {
99 pub certificate_file: PathBuf,
100 pub ca_file: Option<PathBuf>,
101}
102
103#[derive(Clone, PartialEq, Eq)]
105pub struct QueryApiAuth(Arc<QueryApiAuthData>);
106
107#[derive(PartialEq, Eq)]
108struct QueryApiAuthData {
109 credentials: Vec<QueryApiCredential>,
110}
111
112#[derive(PartialEq, Eq)]
113struct QueryApiCredential {
114 read_only: bool,
115 username_digest: [u8; 32],
116 password_digest: [u8; 32],
117}
118
119#[derive(Clone, Copy, Debug, PartialEq, Eq)]
120pub(crate) struct AuthContext {
121 pub(crate) principal: [u8; 32],
122 pub(crate) read_only: bool,
123}
124
125impl AuthContext {
126 pub(crate) fn anonymous() -> Self {
127 Self {
128 principal: Sha256::digest([]).into(),
129 read_only: false,
130 }
131 }
132}
133
134impl QueryApiAuth {
135 pub fn from_file(path: impl AsRef<Path>) -> Result<Self> {
137 let path = path.as_ref();
138 let contents = fs::read_to_string(path).map_err(|error| {
139 QueryApiError::InvalidConfiguration(format!(
140 "failed to read Query API auth file {}: {error}",
141 path.display()
142 ))
143 })?;
144 Self::from_lines(
145 contents
146 .lines()
147 .enumerate()
148 .map(|(index, line)| (index + 1, line)),
149 )
150 }
151
152 fn from_lines<'a>(lines: impl IntoIterator<Item = (usize, &'a str)>) -> Result<Self> {
153 let mut credentials = Vec::new();
154 let mut usernames = HashSet::new();
155 for (line_number, line) in lines {
156 let mut fields = line.splitn(3, ':');
157 let access = fields.next().expect("split returns at least one field");
158 let Some(username) = fields.next() else {
159 return Err(invalid_auth_file_line(
160 line_number,
161 "must use the format <rw|ro>:<user>:<password>",
162 ));
163 };
164 let Some(password) = fields.next() else {
165 return Err(invalid_auth_file_line(
166 line_number,
167 "must use the format <rw|ro>:<user>:<password>",
168 ));
169 };
170 let read_only = match access {
171 "rw" => false,
172 "ro" => true,
173 _ => {
174 return Err(invalid_auth_file_line(
175 line_number,
176 "access must be `rw` or `ro`",
177 ));
178 }
179 };
180 if password.is_empty() {
181 return Err(invalid_auth_file_line(
182 line_number,
183 "password must not be empty",
184 ));
185 }
186 let username_digest: [u8; 32] = Sha256::digest(username.as_bytes()).into();
187 if !usernames.insert(username_digest) {
188 return Err(invalid_auth_file_line(
189 line_number,
190 "username is duplicated",
191 ));
192 }
193 credentials.push(QueryApiCredential {
194 read_only,
195 username_digest,
196 password_digest: Sha256::digest(password.as_bytes()).into(),
197 });
198 }
199 if credentials.is_empty() {
200 return Err(QueryApiError::InvalidConfiguration(
201 "Query API auth file must contain at least one credential".into(),
202 ));
203 }
204 Ok(Self(Arc::new(QueryApiAuthData { credentials })))
205 }
206
207 pub(crate) fn authenticate(&self, username: &str, password: &str) -> Option<AuthContext> {
208 let username_digest: [u8; 32] = Sha256::digest(username.as_bytes()).into();
209 let password_digest: [u8; 32] = Sha256::digest(password.as_bytes()).into();
210 let mut read_only_match = Choice::from(0);
211 let mut read_write_match = Choice::from(0);
212 for credential in &self.0.credentials {
213 let matched = credential.username_digest.ct_eq(&username_digest)
214 & credential.password_digest.ct_eq(&password_digest);
215 if credential.read_only {
216 read_only_match |= matched;
217 } else {
218 read_write_match |= matched;
219 }
220 }
221 if bool::from(read_only_match) {
222 Some(AuthContext {
223 principal: username_digest,
224 read_only: true,
225 })
226 } else if bool::from(read_write_match) {
227 Some(AuthContext {
228 principal: username_digest,
229 read_only: false,
230 })
231 } else {
232 None
233 }
234 }
235}
236
237fn invalid_auth_file_line(line_number: usize, reason: &str) -> QueryApiError {
238 QueryApiError::InvalidConfiguration(format!("Query API auth file line {line_number} {reason}"))
239}
240
241impl fmt::Debug for QueryApiAuth {
242 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
243 formatter.write_str("QueryApiAuth([REDACTED])")
244 }
245}
246
247#[derive(Clone, Debug, PartialEq, Eq)]
249pub struct QueryApiServerConfig {
250 pub listen_addr: SocketAddr,
251 pub database_path: PathBuf,
252 pub auth: Option<QueryApiAuth>,
253 pub tls: Option<QueryApiTlsConfig>,
254 pub limits: QueryApiLimits,
255}
256
257impl QueryApiServerConfig {
258 fn validate(&self) -> Result<()> {
259 if self.database_path.as_os_str().is_empty() {
260 return Err(QueryApiError::InvalidConfiguration(
261 "database_path must not be empty".into(),
262 ));
263 }
264 if let Some(tls) = &self.tls {
265 if tls.certificate_file.as_os_str().is_empty() {
266 return Err(QueryApiError::InvalidConfiguration(
267 "TLS certificate file must not be empty".into(),
268 ));
269 }
270 if tls
271 .ca_file
272 .as_ref()
273 .is_some_and(|path| path.as_os_str().is_empty())
274 {
275 return Err(QueryApiError::InvalidConfiguration(
276 "TLS CA file must not be empty".into(),
277 ));
278 }
279 }
280 self.limits.validate()
281 }
282}
283
284#[cfg(test)]
285mod tests {
286 use super::*;
287
288 #[test]
289 fn query_api_auth_file_loads_access_modes_and_empty_username() {
290 let directory = tempfile::tempdir().unwrap();
291 let path = directory.path().join("auth.txt");
292 fs::write(&path, "rw:writer:secret:with:colons\nro::reader-token\n").unwrap();
293 let auth = QueryApiAuth::from_file(&path).unwrap();
294
295 assert_eq!(
296 auth.authenticate("writer", "secret:with:colons")
297 .map(|context| context.read_only),
298 Some(false)
299 );
300 assert_eq!(
301 auth.authenticate("", "reader-token")
302 .map(|context| context.read_only),
303 Some(true)
304 );
305 assert_eq!(auth.authenticate("writer", "wrong"), None);
306 assert_eq!(format!("{auth:?}"), "QueryApiAuth([REDACTED])");
307
308 for (contents, expected) in [
309 ("", "at least one credential"),
310 ("missing-separator\n", "line 1 must use the format"),
311 ("writer:password\n", "line 1 must use the format"),
312 ("write:writer:password\n", "line 1 access must be"),
313 ("rw:writer:\n", "line 1 password must not be empty"),
314 (
315 "rw:writer:one\nro:writer:two\n",
316 "line 2 username is duplicated",
317 ),
318 ] {
319 fs::write(&path, contents).unwrap();
320 assert!(matches!(
321 QueryApiAuth::from_file(&path),
322 Err(QueryApiError::InvalidConfiguration(message)) if message.contains(expected)
323 ));
324 }
325 }
326
327 #[test]
328 fn rejects_zero_tls_handshake_timeout() {
329 let limits = QueryApiLimits {
330 tls_handshake_timeout: Duration::ZERO,
331 ..QueryApiLimits::default()
332 };
333
334 assert!(matches!(
335 limits.validate(),
336 Err(QueryApiError::InvalidConfiguration(_))
337 ));
338 }
339}