mod database;
mod error;
mod request;
mod response;
mod server;
mod transaction;
mod value;
use std::collections::HashSet;
use std::fmt;
use std::fs;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use sha2::{Digest, Sha256};
use subtle::{Choice, ConstantTimeEq};
pub use error::{QueryApiError, Result};
pub use server::QueryApiServer;
pub use tokio_util::sync::CancellationToken;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct QueryApiLimits {
pub max_concurrent_requests: usize,
pub max_request_bytes: usize,
pub max_result_rows: usize,
pub max_result_bytes: usize,
pub max_open_transactions: usize,
pub transaction_idle_timeout: Duration,
pub transaction_timeout: Duration,
pub max_transaction_workspace_bytes: usize,
pub max_transaction_records: usize,
pub max_transaction_journal_bytes: u64,
pub max_query_memory_bytes: usize,
pub database_command_capacity: usize,
pub tls_handshake_timeout: Duration,
pub shutdown_grace_period: Duration,
}
impl Default for QueryApiLimits {
fn default() -> Self {
Self {
max_concurrent_requests: 64,
max_request_bytes: 8 * 1024 * 1024,
max_result_rows: 100_000,
max_result_bytes: 64 * 1024 * 1024,
max_open_transactions: 64,
transaction_idle_timeout: Duration::from_secs(60),
transaction_timeout: Duration::from_secs(30),
max_transaction_workspace_bytes: 64 * 1024 * 1024,
max_transaction_records: 1_000_000,
max_transaction_journal_bytes: 256 * 1024 * 1024,
max_query_memory_bytes: 64 * 1024 * 1024,
database_command_capacity: 4,
tls_handshake_timeout: Duration::from_secs(5),
shutdown_grace_period: Duration::from_secs(5),
}
}
}
impl QueryApiLimits {
fn validate(&self) -> Result<()> {
if self.max_concurrent_requests == 0
|| self.max_request_bytes == 0
|| self.max_result_rows == 0
|| self.max_result_bytes == 0
|| self.max_open_transactions == 0
|| self.transaction_idle_timeout.is_zero()
|| self.transaction_timeout.is_zero()
|| self.max_transaction_workspace_bytes == 0
|| self.max_transaction_records == 0
|| self.max_transaction_journal_bytes == 0
|| self.max_query_memory_bytes == 0
|| self.database_command_capacity == 0
|| self.tls_handshake_timeout.is_zero()
|| self.shutdown_grace_period.is_zero()
{
return Err(QueryApiError::InvalidConfiguration(
"Query API resource limits must be positive".into(),
));
}
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct QueryApiTlsConfig {
pub certificate_file: PathBuf,
pub ca_file: Option<PathBuf>,
}
#[derive(Clone, PartialEq, Eq)]
pub struct QueryApiAuth(Arc<QueryApiAuthData>);
#[derive(PartialEq, Eq)]
struct QueryApiAuthData {
credentials: Vec<QueryApiCredential>,
}
#[derive(PartialEq, Eq)]
struct QueryApiCredential {
read_only: bool,
username_digest: [u8; 32],
password_digest: [u8; 32],
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct AuthContext {
pub(crate) principal: [u8; 32],
pub(crate) read_only: bool,
}
impl AuthContext {
pub(crate) fn anonymous() -> Self {
Self {
principal: Sha256::digest([]).into(),
read_only: false,
}
}
}
impl QueryApiAuth {
pub fn from_file(path: impl AsRef<Path>) -> Result<Self> {
let path = path.as_ref();
let contents = fs::read_to_string(path).map_err(|error| {
QueryApiError::InvalidConfiguration(format!(
"failed to read Query API auth file {}: {error}",
path.display()
))
})?;
Self::from_lines(
contents
.lines()
.enumerate()
.map(|(index, line)| (index + 1, line)),
)
}
fn from_lines<'a>(lines: impl IntoIterator<Item = (usize, &'a str)>) -> Result<Self> {
let mut credentials = Vec::new();
let mut usernames = HashSet::new();
for (line_number, line) in lines {
let mut fields = line.splitn(3, ':');
let access = fields.next().expect("split returns at least one field");
let Some(username) = fields.next() else {
return Err(invalid_auth_file_line(
line_number,
"must use the format <rw|ro>:<user>:<password>",
));
};
let Some(password) = fields.next() else {
return Err(invalid_auth_file_line(
line_number,
"must use the format <rw|ro>:<user>:<password>",
));
};
let read_only = match access {
"rw" => false,
"ro" => true,
_ => {
return Err(invalid_auth_file_line(
line_number,
"access must be `rw` or `ro`",
));
}
};
if password.is_empty() {
return Err(invalid_auth_file_line(
line_number,
"password must not be empty",
));
}
let username_digest: [u8; 32] = Sha256::digest(username.as_bytes()).into();
if !usernames.insert(username_digest) {
return Err(invalid_auth_file_line(
line_number,
"username is duplicated",
));
}
credentials.push(QueryApiCredential {
read_only,
username_digest,
password_digest: Sha256::digest(password.as_bytes()).into(),
});
}
if credentials.is_empty() {
return Err(QueryApiError::InvalidConfiguration(
"Query API auth file must contain at least one credential".into(),
));
}
Ok(Self(Arc::new(QueryApiAuthData { credentials })))
}
pub(crate) fn authenticate(&self, username: &str, password: &str) -> Option<AuthContext> {
let username_digest: [u8; 32] = Sha256::digest(username.as_bytes()).into();
let password_digest: [u8; 32] = Sha256::digest(password.as_bytes()).into();
let mut read_only_match = Choice::from(0);
let mut read_write_match = Choice::from(0);
for credential in &self.0.credentials {
let matched = credential.username_digest.ct_eq(&username_digest)
& credential.password_digest.ct_eq(&password_digest);
if credential.read_only {
read_only_match |= matched;
} else {
read_write_match |= matched;
}
}
if bool::from(read_only_match) {
Some(AuthContext {
principal: username_digest,
read_only: true,
})
} else if bool::from(read_write_match) {
Some(AuthContext {
principal: username_digest,
read_only: false,
})
} else {
None
}
}
}
fn invalid_auth_file_line(line_number: usize, reason: &str) -> QueryApiError {
QueryApiError::InvalidConfiguration(format!("Query API auth file line {line_number} {reason}"))
}
impl fmt::Debug for QueryApiAuth {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("QueryApiAuth([REDACTED])")
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct QueryApiServerConfig {
pub listen_addr: SocketAddr,
pub database_path: PathBuf,
pub auth: Option<QueryApiAuth>,
pub tls: Option<QueryApiTlsConfig>,
pub limits: QueryApiLimits,
}
impl QueryApiServerConfig {
fn validate(&self) -> Result<()> {
if self.database_path.as_os_str().is_empty() {
return Err(QueryApiError::InvalidConfiguration(
"database_path must not be empty".into(),
));
}
if let Some(tls) = &self.tls {
if tls.certificate_file.as_os_str().is_empty() {
return Err(QueryApiError::InvalidConfiguration(
"TLS certificate file must not be empty".into(),
));
}
if tls
.ca_file
.as_ref()
.is_some_and(|path| path.as_os_str().is_empty())
{
return Err(QueryApiError::InvalidConfiguration(
"TLS CA file must not be empty".into(),
));
}
}
self.limits.validate()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn query_api_auth_file_loads_access_modes_and_empty_username() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("auth.txt");
fs::write(&path, "rw:writer:secret:with:colons\nro::reader-token\n").unwrap();
let auth = QueryApiAuth::from_file(&path).unwrap();
assert_eq!(
auth.authenticate("writer", "secret:with:colons")
.map(|context| context.read_only),
Some(false)
);
assert_eq!(
auth.authenticate("", "reader-token")
.map(|context| context.read_only),
Some(true)
);
assert_eq!(auth.authenticate("writer", "wrong"), None);
assert_eq!(format!("{auth:?}"), "QueryApiAuth([REDACTED])");
for (contents, expected) in [
("", "at least one credential"),
("missing-separator\n", "line 1 must use the format"),
("writer:password\n", "line 1 must use the format"),
("write:writer:password\n", "line 1 access must be"),
("rw:writer:\n", "line 1 password must not be empty"),
(
"rw:writer:one\nro:writer:two\n",
"line 2 username is duplicated",
),
] {
fs::write(&path, contents).unwrap();
assert!(matches!(
QueryApiAuth::from_file(&path),
Err(QueryApiError::InvalidConfiguration(message)) if message.contains(expected)
));
}
}
#[test]
fn rejects_zero_tls_handshake_timeout() {
let limits = QueryApiLimits {
tls_handshake_timeout: Duration::ZERO,
..QueryApiLimits::default()
};
assert!(matches!(
limits.validate(),
Err(QueryApiError::InvalidConfiguration(_))
));
}
}