use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use axum::body::Bytes;
use axum::extract::{DefaultBodyLimit, Path, State};
use axum::http::{header, HeaderMap, StatusCode};
use axum::middleware::{self, Next};
use axum::response::Response;
use axum::routing::post;
use axum::{extract::Request, Router};
use axum_server::tls_rustls::{RustlsAcceptor, RustlsConfig};
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use base64::Engine;
use littlegraph_core::{CancellationToken as CoreCancellationToken, Graph};
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
use crate::database::auto_commit;
use crate::error::{HttpError, QueryApiError, Result};
use crate::request::QueryRequest;
use crate::response::{QueryResponse, ResponseFormat};
use crate::transaction::TransactionManager;
use crate::{AuthContext, CancellationToken, QueryApiAuth, QueryApiServerConfig};
const ROOT: &str = "/db/self/query/v2";
#[derive(Clone)]
struct AppState {
config: Arc<QueryApiServerConfig>,
transactions: TransactionManager,
requests: Arc<Semaphore>,
query_cancellation: CoreCancellationToken,
}
pub struct QueryApiServer {
listener: std::net::TcpListener,
state: AppState,
tls: Option<RustlsConfig>,
}
impl QueryApiServer {
pub async fn bind(config: QueryApiServerConfig) -> Result<Self> {
config.validate()?;
let database_path = config.database_path.clone();
tokio::task::spawn_blocking(move || Graph::open_neo4j_writable(database_path))
.await
.map_err(|error| QueryApiError::Database(format!("validation task failed: {error}")))?
.map_err(|error| QueryApiError::Database(error.to_string()))?;
let tls = match &config.tls {
Some(tls) => {
let mut certificates =
tokio::fs::read(&tls.certificate_file)
.await
.map_err(|error| {
QueryApiError::InvalidConfiguration(format!(
"failed to read TLS certificate file {}: {error}",
tls.certificate_file.display()
))
})?;
if let Some(ca_file) = &tls.ca_file {
let ca = tokio::fs::read(ca_file).await.map_err(|error| {
QueryApiError::InvalidConfiguration(format!(
"failed to read TLS CA file {}: {error}",
ca_file.display()
))
})?;
certificates.push(b'\n');
certificates.extend(ca);
}
let key = tokio::fs::read(&tls.certificate_file)
.await
.map_err(|error| {
QueryApiError::InvalidConfiguration(format!(
"failed to read TLS private key file {}: {error}",
tls.certificate_file.display()
))
})?;
Some(
RustlsConfig::from_pem(certificates, key)
.await
.map_err(|error| {
QueryApiError::InvalidConfiguration(format!(
"failed to load Query API TLS configuration: {error}"
))
})?,
)
}
None => None,
};
let listener = std::net::TcpListener::bind(config.listen_addr)?;
listener.set_nonblocking(true)?;
let config = Arc::new(config);
let state = AppState {
transactions: TransactionManager::new(
config.database_path.clone(),
config.limits.clone(),
),
requests: Arc::new(Semaphore::new(config.limits.max_concurrent_requests)),
query_cancellation: CoreCancellationToken::new(),
config,
};
Ok(Self {
listener,
state,
tls,
})
}
pub fn local_addr(&self) -> Result<SocketAddr> {
Ok(self.listener.local_addr()?)
}
pub async fn serve(self, shutdown: CancellationToken) -> Result<()> {
let body_limit = self.state.config.limits.max_request_bytes;
let router = Router::new()
.route(ROOT, post(execute))
.route(&format!("{ROOT}/tx"), post(begin_transaction))
.route(
&format!("{ROOT}/tx/:tx_id"),
post(continue_transaction).delete(rollback_transaction),
)
.route(
&format!("{ROOT}/tx/:tx_id/commit"),
post(commit_transaction),
)
.fallback(route_not_found)
.layer(DefaultBodyLimit::max(body_limit))
.layer(middleware::from_fn_with_state(
self.state.clone(),
authenticate_request,
))
.with_state(self.state.clone());
let handle = axum_server::Handle::new();
let shutdown_handle = handle.clone();
let shutdown_signal = shutdown.clone();
let query_cancellation = self.state.query_cancellation.clone();
let grace = self.state.config.limits.shutdown_grace_period;
let shutdown_task = tokio::spawn(async move {
shutdown_signal.cancelled().await;
query_cancellation.cancel();
shutdown_handle.graceful_shutdown(Some(grace));
});
let cleanup_manager = self.state.transactions.clone();
let cleanup_shutdown = shutdown.clone();
let cleanup_task = tokio::spawn(async move {
let mut interval = tokio::time::interval(Duration::from_secs(1));
loop {
tokio::select! {
_ = cleanup_shutdown.cancelled() => break,
_ = interval.tick() => cleanup_manager.expire().await,
}
}
});
let result = if let Some(tls) = self.tls {
let acceptor = RustlsAcceptor::new(tls)
.handshake_timeout(self.state.config.limits.tls_handshake_timeout);
axum_server::from_tcp(self.listener)
.acceptor(acceptor)
.handle(handle)
.serve(router.into_make_service())
.await
} else {
axum_server::from_tcp(self.listener)
.handle(handle)
.serve(router.into_make_service())
.await
};
cleanup_task.abort();
shutdown_task.abort();
self.state.query_cancellation.cancel();
if tokio::time::timeout(grace, self.state.transactions.shutdown())
.await
.is_err()
{
log::warn!("Query API transaction cleanup exceeded the shutdown grace period");
}
result.map_err(|error| QueryApiError::Http(error.to_string()))
}
}
async fn execute(State(state): State<AppState>, headers: HeaderMap, body: Bytes) -> Response {
let error_format = ResponseFormat::for_error(&headers);
handle_execute(state, &headers, &body)
.await
.unwrap_or_else(|error| error_format.render_error(error))
}
async fn handle_execute(
state: AppState,
headers: &HeaderMap,
body: &[u8],
) -> std::result::Result<Response, HttpError> {
let _permit = admit(&state).await?;
let (request, format, auth) = parse_request(&state, headers, body)?;
let statement = request.statement_required()?.to_owned();
let params = request.params()?;
let mut options = request.options(&state.config.limits);
options.read_only |= auth.read_only;
let result = auto_commit(
state.config.database_path.clone(),
statement,
params,
options,
state.query_cancellation.clone(),
state.config.limits.max_result_rows,
state.config.limits.max_result_bytes,
)
.await
.map_err(|error| map_authorization_error(error, auth))?;
format.render(
QueryResponse {
result: Some(result),
transaction: None,
},
StatusCode::ACCEPTED,
state.config.limits.max_result_bytes,
)
}
async fn begin_transaction(
State(state): State<AppState>,
headers: HeaderMap,
body: Bytes,
) -> Response {
let error_format = ResponseFormat::for_error(&headers);
handle_begin(state, &headers, &body)
.await
.unwrap_or_else(|error| error_format.render_error(error))
}
async fn handle_begin(
state: AppState,
headers: &HeaderMap,
body: &[u8],
) -> std::result::Result<Response, HttpError> {
let _permit = admit(&state).await?;
let (request, format, auth) = parse_request(&state, headers, body)?;
let mut options = request.options(&state.config.limits);
options.read_only |= auth.read_only;
let info = state
.transactions
.begin(options, auth.principal)
.await
.map_err(|error| map_authorization_error(error, auth))?;
let (result, transaction) = match request.statement.as_deref() {
Some(statement) if !statement.is_empty() => {
let params = request.params()?;
let (result, info) = state
.transactions
.run(&info.id, auth.principal, statement.to_owned(), params)
.await
.map_err(|error| map_authorization_error(error, auth))?;
(Some(result), Some(info))
}
_ => (None, Some(info)),
};
let rollback_id = transaction.as_ref().map(|info| info.id.clone());
let response = format.render(
QueryResponse {
result,
transaction,
},
StatusCode::ACCEPTED,
state.config.limits.max_result_bytes,
);
if response.is_err() {
if let Some(id) = rollback_id {
let _ = state.transactions.rollback(&id, auth.principal).await;
}
}
response
}
async fn continue_transaction(
State(state): State<AppState>,
Path(tx_id): Path<String>,
headers: HeaderMap,
body: Bytes,
) -> Response {
let error_format = ResponseFormat::for_error(&headers);
handle_continue(state, tx_id, &headers, &body)
.await
.unwrap_or_else(|error| error_format.render_error(error))
}
async fn handle_continue(
state: AppState,
tx_id: String,
headers: &HeaderMap,
body: &[u8],
) -> std::result::Result<Response, HttpError> {
let _permit = admit(&state).await?;
let (request, format, auth) = parse_request(&state, headers, body)?;
let params = request.params()?;
let (result, transaction) = match request.statement {
Some(statement) => {
let (result, info) = state
.transactions
.run(&tx_id, auth.principal, statement, params)
.await
.map_err(|error| map_authorization_error(error, auth))?;
(Some(result), Some(info))
}
None => (
None,
Some(
state
.transactions
.keep_alive(&tx_id, auth.principal)
.await?,
),
),
};
let rollback_id = transaction.as_ref().map(|info| info.id.clone());
let response = format.render(
QueryResponse {
result,
transaction,
},
StatusCode::ACCEPTED,
state.config.limits.max_result_bytes,
);
if response.is_err() {
if let Some(id) = rollback_id {
let _ = state.transactions.rollback(&id, auth.principal).await;
}
}
response
}
async fn commit_transaction(
State(state): State<AppState>,
Path(tx_id): Path<String>,
headers: HeaderMap,
body: Bytes,
) -> Response {
let error_format = ResponseFormat::for_error(&headers);
handle_commit(state, tx_id, &headers, &body)
.await
.unwrap_or_else(|error| error_format.render_error(error))
}
async fn handle_commit(
state: AppState,
tx_id: String,
headers: &HeaderMap,
body: &[u8],
) -> std::result::Result<Response, HttpError> {
let _permit = admit(&state).await?;
let (request, format, auth) = parse_request(&state, headers, body)?;
let params = request.params()?;
let query = request.statement.map(|statement| (statement, params));
let result = state
.transactions
.commit(&tx_id, auth.principal, query)
.await
.map_err(|error| map_authorization_error(error, auth))?;
format.render(
QueryResponse {
result,
transaction: None,
},
StatusCode::ACCEPTED,
state.config.limits.max_result_bytes,
)
}
async fn rollback_transaction(
State(state): State<AppState>,
Path(tx_id): Path<String>,
headers: HeaderMap,
) -> Response {
let error_format = ResponseFormat::for_error(&headers);
async {
let _permit = admit(&state).await?;
let auth = authenticate(&state.config.auth, &headers)?;
let format = ResponseFormat::negotiate(&headers)?;
state.transactions.rollback(&tx_id, auth.principal).await?;
format.render(
QueryResponse {
result: None,
transaction: None,
},
StatusCode::OK,
state.config.limits.max_result_bytes,
)
}
.await
.unwrap_or_else(|error| error_format.render_error(error))
}
fn parse_request(
state: &AppState,
headers: &HeaderMap,
body: &[u8],
) -> std::result::Result<(QueryRequest, ResponseFormat, AuthContext), HttpError> {
let auth = authenticate(&state.config.auth, headers)?;
let typed_parameters = ResponseFormat::validate_content_type(headers)?;
let format = ResponseFormat::negotiate(headers)?;
let mut request = if body.is_empty() {
QueryRequest::default()
} else {
serde_json::from_slice(body).map_err(|_| {
HttpError::new(
StatusCode::BAD_REQUEST,
"Neo.ClientError.Request.Invalid",
"Bad Request",
)
})?
};
request.typed_parameters = typed_parameters;
request.validate_extensions()?;
let _ = request.params()?;
Ok((request, format, auth))
}
async fn authenticate_request(
State(state): State<AppState>,
request: Request,
next: Next,
) -> Response {
let error_format = ResponseFormat::for_error(request.headers());
match authenticate(&state.config.auth, request.headers()) {
Ok(_) => {
let response = next.run(request).await;
if response.status() == StatusCode::PAYLOAD_TOO_LARGE
&& response
.headers()
.get(header::CONTENT_TYPE)
.is_none_or(|value| {
!value
.to_str()
.unwrap_or_default()
.starts_with("application/json")
})
{
error_format.render_error(HttpError::new(
StatusCode::PAYLOAD_TOO_LARGE,
"Neo.ClientError.Request.Invalid",
"request body exceeds the configured limit",
))
} else if response.status() == StatusCode::METHOD_NOT_ALLOWED {
error_format.render_error(HttpError::new(
StatusCode::METHOD_NOT_ALLOWED,
"Neo.ClientError.Request.Invalid",
"Method Not Allowed",
))
} else {
response
}
}
Err(error) => error_format.render_error(error),
}
}
async fn route_not_found(headers: HeaderMap) -> Response {
let error_format = ResponseFormat::for_error(&headers);
error_format.render_error(HttpError::new(
StatusCode::NOT_FOUND,
"Neo.ClientError.Database.DatabaseNotFound",
"The requested Query API database or endpoint was not found.",
))
}
fn authenticate(
expected: &Option<QueryApiAuth>,
headers: &HeaderMap,
) -> std::result::Result<AuthContext, HttpError> {
let Some(expected) = expected else {
return Ok(AuthContext::anonymous());
};
let mut values = headers.get_all(header::AUTHORIZATION).iter();
let Some(value) = values.next() else {
return Err(HttpError::unauthorized(
"No authentication header supplied.",
));
};
if values.next().is_some() {
return Err(HttpError::new(
StatusCode::BAD_REQUEST,
"Neo.ClientError.Request.InvalidFormat",
"Multiple authentication headers supplied.",
));
}
let value = value.to_str().map_err(|_| {
HttpError::new(
StatusCode::BAD_REQUEST,
"Neo.ClientError.Request.InvalidFormat",
"Invalid authentication header.",
)
})?;
let Some((scheme, credential)) = value.trim().split_once(' ') else {
return Err(HttpError::new(
StatusCode::BAD_REQUEST,
"Neo.ClientError.Request.InvalidFormat",
"Invalid authentication header.",
));
};
if credential.is_empty() || credential.contains(' ') {
return Err(HttpError::new(
StatusCode::BAD_REQUEST,
"Neo.ClientError.Request.InvalidFormat",
"Invalid authentication header.",
));
}
let authenticated = if scheme.eq_ignore_ascii_case("Bearer") {
expected.authenticate("", credential)
} else if scheme.eq_ignore_ascii_case("Basic") {
let decoded = BASE64_STANDARD.decode(credential).map_err(|_| {
HttpError::new(
StatusCode::BAD_REQUEST,
"Neo.ClientError.Request.InvalidFormat",
"Invalid authentication header.",
)
})?;
let decoded = std::str::from_utf8(&decoded).map_err(|_| {
HttpError::new(
StatusCode::BAD_REQUEST,
"Neo.ClientError.Request.InvalidFormat",
"Invalid authentication header.",
)
})?;
let (username, password) = decoded.split_once(':').ok_or_else(|| {
HttpError::new(
StatusCode::BAD_REQUEST,
"Neo.ClientError.Request.InvalidFormat",
"Invalid authentication header.",
)
})?;
expected.authenticate(username, password)
} else {
return Err(HttpError::new(
StatusCode::BAD_REQUEST,
"Neo.ClientError.Request.InvalidFormat",
"Invalid authentication header.",
));
};
authenticated.ok_or_else(|| HttpError::unauthorized("Invalid credential."))
}
fn map_authorization_error(error: HttpError, auth: AuthContext) -> HttpError {
if auth.read_only && error.code == "Neo.ClientError.Statement.AccessMode" {
HttpError::new(
StatusCode::FORBIDDEN,
"Neo.ClientError.Security.Forbidden",
"Permission denied.",
)
} else {
error
}
}
async fn admit(state: &AppState) -> std::result::Result<OwnedSemaphorePermit, HttpError> {
state.requests.clone().try_acquire_owned().map_err(|_| {
HttpError::new(
StatusCode::SERVICE_UNAVAILABLE,
"Neo.TransientError.General.DatabaseUnavailable",
"the Query API request limit was reached",
)
})
}
#[cfg(test)]
mod tests {
use std::io::Write;
use std::path::Path;
use std::sync::Arc;
use axum::http::HeaderValue;
use littlegraph_core::Neo4jStorage;
use rcgen::{CertificateParams, KeyPair};
use rustls::pki_types::ServerName;
use serde_json::json;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio_rustls::TlsConnector;
use super::*;
use crate::{QueryApiLimits, QueryApiServerConfig, QueryApiTlsConfig};
async fn start_server(
database: &Path,
auth: Option<QueryApiAuth>,
) -> (
SocketAddr,
CancellationToken,
tokio::task::JoinHandle<Result<()>>,
) {
Neo4jStorage::initialize_if_empty(database).unwrap();
let server = QueryApiServer::bind(QueryApiServerConfig {
listen_addr: "127.0.0.1:0".parse().unwrap(),
database_path: database.to_owned(),
auth,
tls: None,
limits: QueryApiLimits::default(),
})
.await
.unwrap();
let address = server.local_addr().unwrap();
let shutdown = CancellationToken::new();
let serve_shutdown = shutdown.clone();
let task = tokio::spawn(server.serve(serve_shutdown));
(address, shutdown, task)
}
fn auth(contents: &str) -> QueryApiAuth {
let mut file = tempfile::NamedTempFile::new().unwrap();
file.write_all(contents.as_bytes()).unwrap();
QueryApiAuth::from_file(file.path()).unwrap()
}
async fn request(
address: SocketAddr,
method: &str,
path: &str,
body: &str,
authorization: Option<&str>,
) -> (u16, HeaderMap, serde_json::Value) {
let stream = tokio::net::TcpStream::connect(address).await.unwrap();
exchange(stream, address, method, path, body, authorization).await
}
async fn request_with_media_types(
address: SocketAddr,
method: &str,
path: &str,
body: &str,
authorization: Option<&str>,
content_type: &str,
accept: &str,
) -> (u16, HeaderMap, serde_json::Value) {
let stream = tokio::net::TcpStream::connect(address).await.unwrap();
exchange_with_media_types(
stream,
address,
method,
path,
body,
authorization,
content_type,
accept,
)
.await
}
async fn exchange<S>(
stream: S,
address: SocketAddr,
method: &str,
path: &str,
body: &str,
authorization: Option<&str>,
) -> (u16, HeaderMap, serde_json::Value)
where
S: AsyncRead + AsyncWrite + Unpin,
{
exchange_with_media_types(
stream,
address,
method,
path,
body,
authorization,
"application/json",
"application/json",
)
.await
}
#[allow(clippy::too_many_arguments)]
async fn exchange_with_media_types<S>(
mut stream: S,
address: SocketAddr,
method: &str,
path: &str,
body: &str,
authorization: Option<&str>,
content_type: &str,
accept: &str,
) -> (u16, HeaderMap, serde_json::Value)
where
S: AsyncRead + AsyncWrite + Unpin,
{
let authorization = authorization
.map(|value| format!("Authorization: {value}\r\n"))
.unwrap_or_default();
let request = format!(
"{method} {path} HTTP/1.1\r\nHost: {address}\r\nContent-Type: {content_type}\r\nAccept: {accept}\r\n{authorization}Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
stream.write_all(request.as_bytes()).await.unwrap();
let mut response = Vec::new();
stream.read_to_end(&mut response).await.unwrap();
let separator = response
.windows(4)
.position(|window| window == b"\r\n\r\n")
.unwrap();
let head = std::str::from_utf8(&response[..separator]).unwrap();
let status = head
.lines()
.next()
.unwrap()
.split_whitespace()
.nth(1)
.unwrap()
.parse()
.unwrap();
let mut headers = HeaderMap::new();
for line in head.lines().skip(1) {
let (name, value) = line.split_once(':').unwrap();
headers.insert(
axum::http::HeaderName::from_bytes(name.as_bytes()).unwrap(),
HeaderValue::from_str(value.trim()).unwrap(),
);
}
let body = &response[separator + 4..];
let json = if body.is_empty() {
json!({})
} else {
serde_json::from_slice(body).unwrap()
};
(status, headers, json)
}
#[tokio::test]
async fn executes_auto_commit_and_explicit_transactions() {
let directory = tempfile::tempdir().unwrap();
let database = directory.path().join("neo4j");
let (address, shutdown, task) = start_server(&database, None).await;
let (status, _, body) =
request(address, "POST", ROOT, r#"{"statement":"RETURN 1"}"#, None).await;
assert_eq!(status, 202, "unexpected response: {body}");
assert_eq!(body["data"]["values"], json!([[1]]));
let (status, _, body) = request(
address,
"POST",
&format!("{ROOT}/tx"),
r#"{"statement":"CREATE (:QueryApiNode)"}"#,
None,
)
.await;
assert_eq!(status, 202);
let tx_id = body["transaction"]["id"].as_str().unwrap();
assert_eq!(tx_id.len(), 6);
let (status, _, body) = request(
address,
"POST",
&format!("{ROOT}/tx/{tx_id}/commit"),
"{}",
None,
)
.await;
assert_eq!(status, 202);
assert_eq!(body, json!({}));
let (status, _, body) = request(
address,
"POST",
ROOT,
r#"{"statement":"MATCH (n:QueryApiNode) RETURN n"}"#,
None,
)
.await;
assert_eq!(status, 202, "unexpected response: {body}");
assert_eq!(body["data"]["values"].as_array().unwrap().len(), 1);
let (_, _, body) = request(
address,
"POST",
&format!("{ROOT}/tx"),
r#"{"statement":"CREATE (:RolledBackNode)"}"#,
None,
)
.await;
let tx_id = body["transaction"]["id"].as_str().unwrap();
let (status, _, body) =
request(address, "DELETE", &format!("{ROOT}/tx/{tx_id}"), "", None).await;
assert_eq!(status, 200);
assert_eq!(body, json!({}));
let (status, _, body) = request(
address,
"POST",
&format!("{ROOT}/tx/{tx_id}/commit"),
"{}",
None,
)
.await;
assert_eq!(status, 404);
assert_eq!(body["errors"][0]["code"], "Neo.ClientError.Request.Invalid");
assert_eq!(
body["errors"][0]["message"],
format!(
"Transaction with Id: \"{tx_id}\" was not found. It may have timed out and \
therefore rolled back or the routing header 'neo4j-cluster-affinity' was not \
provided."
)
);
let (status, _, body) = request(
address,
"POST",
"/db/other/query/v2",
r#"{"statement":"RETURN 1"}"#,
None,
)
.await;
assert_eq!(status, 404);
assert_eq!(
body["errors"][0]["code"],
"Neo.ClientError.Database.DatabaseNotFound"
);
shutdown.cancel();
task.await.unwrap().unwrap();
}
#[tokio::test]
async fn enforces_bearer_authentication_before_query_handling() {
let directory = tempfile::tempdir().unwrap();
let database = directory.path().join("neo4j");
let auth = auth("rw::test-secret\nro:reader:reader-secret\nrw:writer:writer-secret\n");
let (address, shutdown, task) = start_server(&database, Some(auth)).await;
let (status, headers, body) = request(address, "POST", ROOT, "not-json", None).await;
assert_eq!(status, 401);
assert_eq!(
headers[header::WWW_AUTHENTICATE],
"Basic realm=\"Neo4j\", Bearer realm=\"Neo4j\""
);
assert_eq!(
body["errors"][0]["code"],
"Neo.ClientError.Security.Unauthorized"
);
let (status, _, _) = request(
address,
"POST",
ROOT,
r#"{"statement":"RETURN 1"}"#,
Some("Bearer wrong"),
)
.await;
assert_eq!(status, 401);
let (status, _, body) = request(
address,
"POST",
ROOT,
r#"{"statement":"RETURN 1"}"#,
Some("Bearer test-secret"),
)
.await;
assert_eq!(status, 202);
assert_eq!(body["data"]["values"], json!([[1]]));
let (status, _, body) = request(
address,
"POST",
ROOT,
r#"{"statement":"RETURN 2"}"#,
Some("bearer test-secret"),
)
.await;
assert_eq!(status, 202);
assert_eq!(body["data"]["values"], json!([[2]]));
let reader = format!("Basic {}", BASE64_STANDARD.encode("reader:reader-secret"));
let writer = format!("Basic {}", BASE64_STANDARD.encode("writer:writer-secret"));
let (status, _, body) = request(
address,
"POST",
ROOT,
r#"{"statement":"RETURN 3"}"#,
Some(&reader),
)
.await;
assert_eq!(status, 202);
assert_eq!(body["data"]["values"], json!([[3]]));
let (status, _, body) = request(
address,
"POST",
ROOT,
r#"{"statement":"CREATE (:DeniedReader)"}"#,
Some(&reader),
)
.await;
assert_eq!(status, 403);
assert_eq!(
body["errors"][0]["code"],
"Neo.ClientError.Security.Forbidden"
);
let (status, _, body) = request(
address,
"POST",
&format!("{ROOT}/tx"),
r#"{"statement":"RETURN 4"}"#,
Some(&reader),
)
.await;
assert_eq!(status, 202, "unexpected response: {body}");
let tx_id = body["transaction"]["id"].as_str().unwrap();
let (status, _, _) = request(
address,
"POST",
&format!("{ROOT}/tx/{tx_id}"),
r#"{"statement":"RETURN 5"}"#,
Some(&writer),
)
.await;
assert_eq!(status, 404);
let (status, _, body) = request(
address,
"POST",
&format!("{ROOT}/tx/{tx_id}"),
r#"{"statement":"CREATE (:DeniedExplicitReader)"}"#,
Some(&reader),
)
.await;
assert_eq!(status, 403);
assert_eq!(
body["errors"][0]["code"],
"Neo.ClientError.Security.Forbidden"
);
let (status, _, body) = request(
address,
"POST",
ROOT,
r#"{"statement":"CREATE (:AllowedWriter)"}"#,
Some(&writer),
)
.await;
assert_eq!(status, 202, "unexpected response: {body}");
shutdown.cancel();
task.await.unwrap().unwrap();
}
#[tokio::test]
async fn enforces_case_insensitive_read_access_mode() {
let directory = tempfile::tempdir().unwrap();
let database = directory.path().join("neo4j");
let (address, shutdown, task) = start_server(&database, None).await;
let (status, _, body) = request(
address,
"POST",
ROOT,
r#"{"statement":"RETURN 1","accessMode":"read"}"#,
None,
)
.await;
assert_eq!(status, 202, "unexpected response: {body}");
let (status, _, body) = request(
address,
"POST",
ROOT,
r#"{"statement":"CREATE (:DeniedAutoCommit)","accessMode":"Read"}"#,
None,
)
.await;
assert_eq!(status, 400);
assert_eq!(
body["errors"][0]["code"],
"Neo.ClientError.Statement.AccessMode"
);
let (status, _, body) = request(
address,
"POST",
&format!("{ROOT}/tx"),
r#"{"accessMode":"READ"}"#,
None,
)
.await;
assert_eq!(status, 202);
let tx_id = body["transaction"]["id"].as_str().unwrap();
let (status, _, body) = request(
address,
"POST",
&format!("{ROOT}/tx/{tx_id}"),
r#"{"statement":"CREATE (:DeniedExplicit)"}"#,
None,
)
.await;
assert_eq!(status, 400);
assert_eq!(
body["errors"][0]["code"],
"Neo.ClientError.Statement.AccessMode"
);
let (status, _, _) = request(
address,
"POST",
&format!("{ROOT}/tx/{tx_id}/commit"),
"{}",
None,
)
.await;
assert_eq!(status, 404);
shutdown.cancel();
task.await.unwrap().unwrap();
}
#[tokio::test]
async fn renders_request_and_query_errors_as_json_lines() {
let directory = tempfile::tempdir().unwrap();
let database = directory.path().join("neo4j");
let (address, shutdown, task) = start_server(&database, None).await;
let (status, headers, body) = request_with_media_types(
address,
"POST",
ROOT,
r#"{"statement":"THIS IS NOT CYPHER"}"#,
None,
"application/json",
"application/jsonl",
)
.await;
assert_eq!(status, 400);
assert_eq!(headers[header::CONTENT_TYPE], "application/jsonl");
assert_eq!(body["$event"], "Error");
assert_eq!(
body["_body"]["errors"][0]["code"],
"Neo.ClientError.Statement.SyntaxError"
);
let (status, headers, body) = request_with_media_types(
address,
"POST",
ROOT,
"",
None,
"application/json",
"application/jsonl",
)
.await;
assert_eq!(status, 400);
assert_eq!(headers[header::CONTENT_TYPE], "application/jsonl");
assert_eq!(
body["_body"]["errors"][0],
json!({
"code": "Neo.ClientError.Request.Invalid",
"message": "statement cannot be null or empty"
})
);
let (status, headers, body) = request_with_media_types(
address,
"POST",
ROOT,
"not-json",
None,
"application/json",
"application/jsonl",
)
.await;
assert_eq!(status, 400);
assert_eq!(headers[header::CONTENT_TYPE], "application/jsonl");
assert_eq!(
body["_body"]["errors"][0],
json!({
"code": "Neo.ClientError.Request.Invalid",
"message": "Bad Request"
})
);
let (status, headers, body) = request_with_media_types(
address,
"POST",
ROOT,
"not-json",
None,
"text/csv",
"application/jsonl",
)
.await;
assert_eq!(status, 415);
assert_eq!(headers[header::CONTENT_TYPE], "application/jsonl");
assert_eq!(body["$event"], "Error");
assert_eq!(
body["_body"]["errors"][0]["code"],
"Neo.ClientError.Request.Invalid"
);
let (status, headers, body) = request_with_media_types(
address,
"GET",
ROOT,
"",
None,
"application/json",
"application/jsonl",
)
.await;
assert_eq!(status, 405);
assert_eq!(headers[header::CONTENT_TYPE], "application/jsonl");
assert_eq!(
body["_body"]["errors"][0],
json!({
"code": "Neo.ClientError.Request.Invalid",
"message": "Method Not Allowed"
})
);
shutdown.cancel();
task.await.unwrap().unwrap();
}
#[tokio::test]
async fn enforces_neo4j_max_execution_time_integer_semantics() {
let directory = tempfile::tempdir().unwrap();
let database = directory.path().join("neo4j");
let (address, shutdown, task) = start_server(&database, None).await;
let (status, _, body) = request(
address,
"POST",
ROOT,
r#"{"statement":"RETURN 1","maxExecutionTime":-1}"#,
None,
)
.await;
assert_eq!(status, 202, "unexpected response: {body}");
let (status, _, body) = request(
address,
"POST",
ROOT,
r#"{"statement":"RETURN 1","maxExecutionTime":2147483648}"#,
None,
)
.await;
assert_eq!(status, 400);
assert_eq!(body["errors"][0]["code"], "Neo.ClientError.Request.Invalid");
assert_eq!(body["errors"][0]["message"], "Bad Request");
shutdown.cancel();
task.await.unwrap().unwrap();
}
#[tokio::test]
async fn renders_authentication_errors_as_json_lines() {
let directory = tempfile::tempdir().unwrap();
let database = directory.path().join("neo4j");
let auth = auth("rw::test-secret\n");
let (address, shutdown, task) = start_server(&database, Some(auth)).await;
for authorization in [None, Some("Bearer wrong")] {
let (status, headers, body) = request_with_media_types(
address,
"POST",
ROOT,
r#"{"statement":"RETURN 1"}"#,
authorization,
"application/json",
"application/vnd.neo4j.query.v1.1+jsonl",
)
.await;
assert_eq!(status, 401);
assert_eq!(
headers[header::CONTENT_TYPE],
"application/vnd.neo4j.query.v1.1+jsonl"
);
assert_eq!(
headers[header::WWW_AUTHENTICATE],
"Basic realm=\"Neo4j\", Bearer realm=\"Neo4j\""
);
assert_eq!(body["$event"], "Error");
assert_eq!(
body["_body"]["errors"][0]["code"],
"Neo.ClientError.Security.Unauthorized"
);
}
shutdown.cancel();
task.await.unwrap().unwrap();
}
#[tokio::test]
async fn serves_query_api_over_tls_with_the_combined_pem_bundle() {
let directory = tempfile::tempdir().unwrap();
let database = directory.path().join("neo4j");
Neo4jStorage::initialize_if_empty(&database).unwrap();
let key = KeyPair::generate().unwrap();
let certificate = CertificateParams::new(vec!["localhost".into()])
.unwrap()
.self_signed(&key)
.unwrap();
let pem_path = directory.path().join("server.pem");
let mut pem_file = std::fs::File::create(&pem_path).unwrap();
write!(pem_file, "{}{}", certificate.pem(), key.serialize_pem()).unwrap();
let limits = QueryApiLimits {
tls_handshake_timeout: Duration::from_millis(100),
..QueryApiLimits::default()
};
let server = QueryApiServer::bind(QueryApiServerConfig {
listen_addr: "127.0.0.1:0".parse().unwrap(),
database_path: database,
auth: None,
tls: Some(QueryApiTlsConfig {
certificate_file: pem_path,
ca_file: None,
}),
limits,
})
.await
.unwrap();
let address = server.local_addr().unwrap();
let shutdown = CancellationToken::new();
let serve_shutdown = shutdown.clone();
let task = tokio::spawn(server.serve(serve_shutdown));
let mut stalled = tokio::net::TcpStream::connect(address).await.unwrap();
let mut byte = [0];
let closed = tokio::time::timeout(Duration::from_secs(1), stalled.read(&mut byte))
.await
.expect("stalled TLS handshake was not closed");
assert!(
matches!(closed, Ok(0) | Err(_)),
"stalled TLS connection unexpectedly produced application data"
);
let mut roots = rustls::RootCertStore::empty();
roots.add(certificate.der().clone()).unwrap();
let client = rustls::ClientConfig::builder()
.with_root_certificates(roots)
.with_no_client_auth();
let tcp = tokio::net::TcpStream::connect(address).await.unwrap();
let tls = TlsConnector::from(Arc::new(client))
.connect(ServerName::try_from("localhost").unwrap(), tcp)
.await
.unwrap();
let (status, _, body) = exchange(
tls,
address,
"POST",
ROOT,
r#"{"statement":"RETURN 1"}"#,
None,
)
.await;
assert_eq!(status, 202);
assert_eq!(body["data"]["values"], json!([[1]]));
shutdown.cancel();
task.await.unwrap().unwrap();
}
}