From 78673705f321d55cba1857df34bcb0c4fc0e8d52 Mon Sep 17 00:00:00 2001 From: Weny Xu Date: Thu, 3 Dec 2026 20:20:48 +0000 Subject: [PATCH] feat(http): support TLS for HTTP servers (#10775) * feat(http): support TLS for HTTP servers Signed-off-by: WenyXu * fix(http): enable HTTP/2 explicitly for Axum Signed-off-by: WenyXu * test(http): include TLS defaults in config API snapshot Signed-off-by: WenyXu * fix: run HTTP TLS handshakes on separate tasks Signed-off-by: WenyXu --------- Signed-off-by: WenyXu --- Cargo.lock | 25 +++ Cargo.toml | 1 + config/config.md | 25 +++ config/datanode.example.toml | 14 ++ config/flownode.example.toml | 14 ++ config/frontend.example.toml | 17 ++ config/metasrv.example.toml | 14 ++ config/standalone.example.toml | 17 ++ src/servers/AGENTS.md | 2 + src/servers/Cargo.toml | 5 +- src/servers/src/http.rs | 23 +-- src/servers/src/http/listener.rs | 287 +++++++++++++++++++++++++++++++ tests-integration/tests/http.rs | 7 + 13 files changed, 439 insertions(+), 12 deletions(-) create mode 100644 src/servers/src/http/listener.rs diff --git a/Cargo.lock b/Cargo.lock index ee7a1377906..57603fc8321 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -12347,6 +12347,19 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "rcgen" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75e669e5202259b5314d1ea5397316ad400819437857b90861765f24c4cf80a2" +dependencies = [ + "pem", + "ring", + "rustls-pki-types", + "time", + "yasna", +] + [[package]] name = "recursive" version = "0.1.1" @@ -12733,6 +12746,7 @@ dependencies = [ "futures-channel", "futures-core", "futures-util", + "h2 0.4.11", "http 1.5.0", "http-body 1.0.1", "http-body-util", @@ -13819,6 +13833,7 @@ dependencies = [ "query", "quoted-string", "rand 0.9.4", + "rcgen", "regex", "reqwest 0.13.4", "rust-embed", @@ -13850,6 +13865,7 @@ dependencies = [ "tokio-rustls", "tokio-stream", "tokio-util", + "toml 0.8.23", "tonic 0.14.2", "tonic-reflection", "tonic-web", @@ -17773,6 +17789,15 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" +[[package]] +name = "yasna" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17bb3549cc1321ae1296b9cdc2698e2b6cb1992adfa19a8c72e5b7a738f44cd" +dependencies = [ + "time", +] + [[package]] name = "yoke" version = "0.8.0" diff --git a/Cargo.toml b/Cargo.toml index f07923a8c62..35e38185e87 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -239,6 +239,7 @@ protoc-bin-vendored = "3.2" raft-engine = { version = "0.4.1", default-features = false } rand = "0.9" ratelimit = "0.10" +rcgen = "0.13.2" ref-cast = "1" regex = "1.12" regex-automata = "0.4" diff --git a/config/config.md b/config/config.md index 248662f5963..82aba120545 100644 --- a/config/config.md +++ b/config/config.md @@ -41,6 +41,11 @@ | `http.cors_allowed_origins` | Array | Unset | Customize allowed origins for HTTP CORS. | | `http.enable_api_server` | Bool | `false` | Whether to start the dedicated public HTTP **API** server. This server serves
only the `v1` interfaces plus the dashboard, and shares every other `[http]`
option with the main server. It is disabled by default; set to `true` to enable. | | `http.api_server_addr` | String | `127.0.0.1:4006` | The address to bind the dedicated HTTP API server, in the same form as `addr`.
Defaults to `127.0.0.1:4006`. | +| `http.tls` | -- | -- | HTTP server TLS options, using the same mode semantics as gRPC.
Both http.addr and the optional http.api_server_addr use these settings.
Use HTTPS for /health and /metrics on the main listener when TLS is required.
The --tls-* CLI flags do not configure HTTP TLS. | +| `http.tls.mode` | String | `disable` | TLS mode. `disable` and `prefer` serve plaintext; `require`, `verify_ca`, and
`verify_full` serve HTTPS only. As with gRPC, ca_cert_path is unused and client certificates are not verified. | +| `http.tls.cert_path` | String | Unset | Certificate file path. | +| `http.tls.key_path` | String | Unset | Private key file path. | +| `http.tls.watch` | Bool | `false` | Certificate watching is not supported for HTTP, as with gRPC. | | `grpc` | -- | -- | The gRPC server options. | | `grpc.bind_addr` | String | `127.0.0.1:4001` | The address to bind the gRPC server. | | `grpc.runtime_size` | Integer | `8` | The number of server worker threads. | @@ -318,6 +323,11 @@ | `http.cors_allowed_origins` | Array | Unset | Customize allowed origins for HTTP CORS. | | `http.enable_api_server` | Bool | `false` | Whether to start the dedicated public HTTP **API** server. This server serves
only the `v1` interfaces plus the dashboard, and shares every other `[http]`
option with the main server. It is disabled by default; set to `true` to enable. | | `http.api_server_addr` | String | `127.0.0.1:4006` | The address to bind the dedicated HTTP API server, in the same form as `addr`.
Defaults to `127.0.0.1:4006`. | +| `http.tls` | -- | -- | HTTP server TLS options, using the same mode semantics as gRPC.
Both http.addr and the optional http.api_server_addr use these settings.
Use HTTPS for /health and /metrics on the main listener when TLS is required.
The --tls-* CLI flags do not configure HTTP TLS. | +| `http.tls.mode` | String | `disable` | TLS mode. `disable` and `prefer` serve plaintext; `require`, `verify_ca`, and
`verify_full` serve HTTPS only. As with gRPC, ca_cert_path is unused and client certificates are not verified. | +| `http.tls.cert_path` | String | Unset | Certificate file path. | +| `http.tls.key_path` | String | Unset | Private key file path. | +| `http.tls.watch` | Bool | `false` | Certificate watching is not supported for HTTP, as with gRPC. | | `grpc` | -- | -- | The gRPC server options. | | `grpc.bind_addr` | String | `127.0.0.1:4001` | The address to bind the gRPC server. | | `grpc.server_addr` | String | Unset | The address advertised to the metasrv, and used for connections from outside the host.
If left empty or unset, the server will automatically use the IP address of the first network interface
on the host, with the same port number as the one specified in `grpc.bind_addr`. | @@ -509,6 +519,11 @@ | `http.addr` | String | `127.0.0.1:4000` | The address to bind the HTTP server. | | `http.timeout` | String | `0s` | HTTP request timeout. Set to 0 to disable timeout. | | `http.body_limit` | String | `64MB` | HTTP request body limit.
The following units are supported: `B`, `KB`, `KiB`, `MB`, `MiB`, `GB`, `GiB`, `TB`, `TiB`, `PB`, `PiB`.
Set to 0 to disable limit. | +| `http.tls` | -- | -- | HTTP server TLS options, using the same mode semantics as gRPC. | +| `http.tls.mode` | String | `disable` | TLS mode. `disable` and `prefer` serve plaintext; `require`, `verify_ca`, and
`verify_full` serve HTTPS only. As with gRPC, ca_cert_path is unused and client certificates are not verified. | +| `http.tls.cert_path` | String | Unset | Certificate file path. | +| `http.tls.key_path` | String | Unset | Private key file path. | +| `http.tls.watch` | Bool | `false` | Certificate watching is not supported for HTTP, as with gRPC. | | `procedure` | -- | -- | Procedure storage options. | | `procedure.max_retry_times` | Integer | `12` | Procedure max retry time. | | `procedure.retry_delay` | String | `500ms` | Initial retry delay of procedures, increases exponentially | @@ -587,6 +602,11 @@ | `http.addr` | String | `127.0.0.1:4000` | The address to bind the HTTP server. | | `http.timeout` | String | `0s` | HTTP request timeout. Set to 0 to disable timeout. | | `http.body_limit` | String | `64MB` | HTTP request body limit.
The following units are supported: `B`, `KB`, `KiB`, `MB`, `MiB`, `GB`, `GiB`, `TB`, `TiB`, `PB`, `PiB`.
Set to 0 to disable limit. | +| `http.tls` | -- | -- | HTTP server TLS options, using the same mode semantics as gRPC. | +| `http.tls.mode` | String | `disable` | TLS mode. `disable` and `prefer` serve plaintext; `require`, `verify_ca`, and
`verify_full` serve HTTPS only. As with gRPC, ca_cert_path is unused and client certificates are not verified. | +| `http.tls.cert_path` | String | Unset | Certificate file path. | +| `http.tls.key_path` | String | Unset | Private key file path. | +| `http.tls.watch` | Bool | `false` | Certificate watching is not supported for HTTP, as with gRPC. | | `grpc` | -- | -- | The gRPC server options. | | `grpc.bind_addr` | String | `127.0.0.1:3001` | The address to bind the gRPC server. | | `grpc.server_addr` | String | Unset | The address advertised to the metasrv, and used for connections from outside the host.
If left empty or unset, the server will automatically use the IP address of the first network interface
on the host, with the same port number as the one specified in `grpc.bind_addr`. | @@ -812,6 +832,11 @@ | `http.addr` | String | `127.0.0.1:4000` | The address to bind the HTTP server. | | `http.timeout` | String | `0s` | HTTP request timeout. Set to 0 to disable timeout. | | `http.body_limit` | String | `64MB` | HTTP request body limit.
The following units are supported: `B`, `KB`, `KiB`, `MB`, `MiB`, `GB`, `GiB`, `TB`, `TiB`, `PB`, `PiB`.
Set to 0 to disable limit. | +| `http.tls` | -- | -- | HTTP server TLS options, using the same mode semantics as gRPC. | +| `http.tls.mode` | String | `disable` | TLS mode. `disable` and `prefer` serve plaintext; `require`, `verify_ca`, and
`verify_full` serve HTTPS only. As with gRPC, ca_cert_path is unused and client certificates are not verified. | +| `http.tls.cert_path` | String | Unset | Certificate file path. | +| `http.tls.key_path` | String | Unset | Private key file path. | +| `http.tls.watch` | Bool | `false` | Certificate watching is not supported for HTTP, as with gRPC. | | `meta_client` | -- | -- | The metasrv client options. | | `meta_client.metasrv_addrs` | Array | -- | The addresses of the metasrv. | | `meta_client.timeout` | String | `3s` | Operation timeout. | diff --git a/config/datanode.example.toml b/config/datanode.example.toml index e2b24cff0c7..939f6c2a570 100644 --- a/config/datanode.example.toml +++ b/config/datanode.example.toml @@ -38,6 +38,20 @@ timeout = "0s" ## Set to 0 to disable limit. body_limit = "64MB" +## HTTP server TLS options, using the same mode semantics as gRPC. +[http.tls] +## TLS mode. `disable` and `prefer` serve plaintext; `require`, `verify_ca`, and +## `verify_full` serve HTTPS only. As with gRPC, ca_cert_path is unused and client certificates are not verified. +mode = "disable" +## Certificate file path. +## @toml2docs:none-default +cert_path = "" +## Private key file path. +## @toml2docs:none-default +key_path = "" +## Certificate watching is not supported for HTTP, as with gRPC. +watch = false + ## The gRPC server options. [grpc] ## The address to bind the gRPC server. diff --git a/config/flownode.example.toml b/config/flownode.example.toml index 63a84c69672..ed1a83cce21 100644 --- a/config/flownode.example.toml +++ b/config/flownode.example.toml @@ -71,6 +71,20 @@ timeout = "0s" ## Set to 0 to disable limit. body_limit = "64MB" +## HTTP server TLS options, using the same mode semantics as gRPC. +[http.tls] +## TLS mode. `disable` and `prefer` serve plaintext; `require`, `verify_ca`, and +## `verify_full` serve HTTPS only. As with gRPC, ca_cert_path is unused and client certificates are not verified. +mode = "disable" +## Certificate file path. +## @toml2docs:none-default +cert_path = "" +## Private key file path. +## @toml2docs:none-default +key_path = "" +## Certificate watching is not supported for HTTP, as with gRPC. +watch = false + ## The metasrv client options. [meta_client] ## The addresses of the metasrv. diff --git a/config/frontend.example.toml b/config/frontend.example.toml index e2bac8ef4e6..51e83ae0aea 100644 --- a/config/frontend.example.toml +++ b/config/frontend.example.toml @@ -90,6 +90,23 @@ enable_api_server = false ## Defaults to `127.0.0.1:4006`. api_server_addr = "127.0.0.1:4006" +## HTTP server TLS options, using the same mode semantics as gRPC. +## Both http.addr and the optional http.api_server_addr use these settings. +## Use HTTPS for /health and /metrics on the main listener when TLS is required. +## The --tls-* CLI flags do not configure HTTP TLS. +[http.tls] +## TLS mode. `disable` and `prefer` serve plaintext; `require`, `verify_ca`, and +## `verify_full` serve HTTPS only. As with gRPC, ca_cert_path is unused and client certificates are not verified. +mode = "disable" +## Certificate file path. +## @toml2docs:none-default +cert_path = "" +## Private key file path. +## @toml2docs:none-default +key_path = "" +## Certificate watching is not supported for HTTP, as with gRPC. +watch = false + ## The gRPC server options. [grpc] ## The address to bind the gRPC server. diff --git a/config/metasrv.example.toml b/config/metasrv.example.toml index 8f0b6ad757d..a8e61ca78c8 100644 --- a/config/metasrv.example.toml +++ b/config/metasrv.example.toml @@ -184,6 +184,20 @@ timeout = "0s" ## Set to 0 to disable limit. body_limit = "64MB" +## HTTP server TLS options, using the same mode semantics as gRPC. +[http.tls] +## TLS mode. `disable` and `prefer` serve plaintext; `require`, `verify_ca`, and +## `verify_full` serve HTTPS only. As with gRPC, ca_cert_path is unused and client certificates are not verified. +mode = "disable" +## Certificate file path. +## @toml2docs:none-default +cert_path = "" +## Private key file path. +## @toml2docs:none-default +key_path = "" +## Certificate watching is not supported for HTTP, as with gRPC. +watch = false + ## Procedure storage options. [procedure] diff --git a/config/standalone.example.toml b/config/standalone.example.toml index 1b37ae36232..f544b7e6982 100644 --- a/config/standalone.example.toml +++ b/config/standalone.example.toml @@ -121,6 +121,23 @@ enable_api_server = false ## Defaults to `127.0.0.1:4006`. api_server_addr = "127.0.0.1:4006" +## HTTP server TLS options, using the same mode semantics as gRPC. +## Both http.addr and the optional http.api_server_addr use these settings. +## Use HTTPS for /health and /metrics on the main listener when TLS is required. +## The --tls-* CLI flags do not configure HTTP TLS. +[http.tls] +## TLS mode. `disable` and `prefer` serve plaintext; `require`, `verify_ca`, and +## `verify_full` serve HTTPS only. As with gRPC, ca_cert_path is unused and client certificates are not verified. +mode = "disable" +## Certificate file path. +## @toml2docs:none-default +cert_path = "" +## Private key file path. +## @toml2docs:none-default +key_path = "" +## Certificate watching is not supported for HTTP, as with gRPC. +watch = false + ## The gRPC server options. [grpc] ## The address to bind the gRPC server. diff --git a/src/servers/AGENTS.md b/src/servers/AGENTS.md index 84fb5f417fc..c5fde4fed33 100644 --- a/src/servers/AGENTS.md +++ b/src/servers/AGENTS.md @@ -32,6 +32,8 @@ provided through handler traits, mostly implemented by `frontend`. `UserProvider::authorize` for the new scope before mutating the context. The HTTP middleware authorizes only the scope it extracts itself (`extract_catalog_and_schema` in `http/authorize.rs`). +- HTTP TLS lives in `http/listener.rs`, uses the shared `TlsOption` and gRPC + enablement semantics, and applies to both frontend HTTP listeners. - Internal frontend gRPC listeners set `Channel::Internal` in server-owned request extensions. Handlers preserve it through query execution and metering; client flow metadata does not grant an internal channel. diff --git a/src/servers/Cargo.toml b/src/servers/Cargo.toml index ce7c957acb5..c1b82b71bd7 100644 --- a/src/servers/Cargo.toml +++ b/src/servers/Cargo.toml @@ -28,7 +28,7 @@ arrow-pg = "0.16" arrow-schema.workspace = true async-trait.workspace = true auth.workspace = true -axum = { workspace = true, features = ["multipart"] } +axum = { workspace = true, features = ["http2", "multipart"] } axum-extra = { workspace = true, features = ["typed-header"] } axum-macros.workspace = true base64.workspace = true @@ -166,6 +166,8 @@ mysql_async = { version = "0.37", default-features = false, features = [ operator = { workspace = true, features = ["testing"] } permutation = "0.4" rand.workspace = true +rcgen.workspace = true +reqwest = { workspace = true, features = ["http2"] } serde_json.workspace = true servers = { workspace = true, features = ["testing"] } simdutf8 = "0.1" @@ -174,6 +176,7 @@ tempfile = "3.0.0" tokio = { workspace = true, features = ["test-util"] } tokio-postgres.workspace = true tokio-postgres-rustls = "0.14" +toml.workspace = true [target.'cfg(unix)'.dev-dependencies] pprof = { version = "0.15", features = ["criterion", "flamegraph"] } diff --git a/src/servers/src/http.rs b/src/servers/src/http.rs index 7c6f2878ed4..e21229d9bd5 100644 --- a/src/servers/src/http.rs +++ b/src/servers/src/http.rs @@ -56,10 +56,9 @@ use self::result::table_result::TableResponse; use crate::batcher::BatchingProtocol; use crate::batcher::logical_table::LogicalTablePendingRowsBatcher; use crate::elasticsearch; -use crate::error::{ - AddressBindSnafu, AlreadyStartedSnafu, Error, InternalIoSnafu, InvalidHeaderValueSnafu, Result, -}; +use crate::error::{AlreadyStartedSnafu, Error, InternalIoSnafu, InvalidHeaderValueSnafu, Result}; use crate::http::influxdb::{influxdb_health, influxdb_ping, influxdb_write_v1, influxdb_write_v2}; +use crate::http::listener::HttpListener; use crate::http::otlp::OtlpState; use crate::http::prom_store::PromStoreState; use crate::http::prometheus::{ @@ -85,6 +84,7 @@ use crate::query_handler::{ }; use crate::request_memory_limiter::ServerMemoryLimiter; use crate::server::Server; +use crate::tls::TlsOption; pub mod authorize; #[cfg(feature = "dashboard")] @@ -97,6 +97,7 @@ pub mod handler; pub mod header; pub mod influxdb; pub mod jaeger; +mod listener; pub mod logs; pub mod loki; pub mod mem_prof; @@ -281,6 +282,9 @@ impl HttpServer { pub struct HttpOptions { pub addr: String, + /// TLS options, using the same mode semantics as gRPC. + pub tls: TlsOption, + /// Request timeout; zero disables it. Frontend raises a nonzero timeout to at least /// the largest active synchronous Prom or shared table batch flush interval plus one second. #[serde(with = "humantime_serde")] @@ -309,6 +313,7 @@ impl Default for HttpOptions { fn default() -> Self { Self { addr: "127.0.0.1:4000".to_string(), + tls: TlsOption::default(), timeout: Duration::from_secs(0), disable_dashboard: false, body_limit: DEFAULT_BODY_LIMIT, @@ -1712,14 +1717,10 @@ impl Server for HttpServer { ); let app = self.build(self.make_app())?; - let listener = tokio::net::TcpListener::bind(listening) - .await - .context(AddressBindSnafu { addr: listening })? - .tap_io(|tcp_stream| { - if let Err(e) = tcp_stream.set_nodelay(true) { - error!(e; "Failed to set TCP_NODELAY on incoming connection"); - } - }); + let listener = HttpListener::bind(listening, &self.options.tls) + .await? + // TapIo preserves SocketAddr connect-info for a custom listener. + .tap_io(|_| {}); let serve = axum::serve( listener, app.into_make_service_with_connect_info::(), diff --git a/src/servers/src/http/listener.rs b/src/servers/src/http/listener.rs new file mode 100644 index 00000000000..93e06c6012d --- /dev/null +++ b/src/servers/src/http/listener.rs @@ -0,0 +1,287 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::io; +use std::net::SocketAddr; +use std::sync::Arc; +use std::time::Duration; + +use axum::serve::Listener; +use common_telemetry::{debug, warn}; +use snafu::ResultExt; +use tokio::net::{TcpListener, TcpStream}; +use tokio::task::JoinSet; +use tokio_rustls::TlsAcceptor; +use tokio_rustls::server::TlsStream; +use tokio_util::either::Either; + +use crate::error::{AddressBindSnafu, Result}; +use crate::tls::TlsOption; + +// Bound incomplete handshakes without serializing all incoming connections. +const MAX_PENDING_HANDSHAKES: usize = 128; +const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10); + +/// HTTP listener using the same TLS enablement policy as the gRPC listener. +pub(crate) struct HttpListener { + listener: TcpListener, + acceptor: Option, + handshakes: JoinSet, SocketAddr)>>, +} + +impl HttpListener { + /// Loads the server identity before binding, so invalid TLS configuration fails startup. + pub(crate) async fn bind(addr: SocketAddr, tls: &TlsOption) -> Result { + // Match GrpcServerBuilder::with_tls_config: prefer does not enable TLS, + // and certificate watching is currently unsupported. + if tls.watch { + warn!("Certificates watch and reloading for HTTP is NOT supported at the moment"); + } + let acceptor = if tls.should_force_tls() { + if let Err(err) = crate::install_default_crypto_provider() { + warn!("Failed to install default rustls crypto provider: {err}"); + } + tls.setup()?.map(|mut config| { + config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()]; + TlsAcceptor::from(Arc::new(config)) + }) + } else { + None + }; + let listener = TcpListener::bind(addr) + .await + .context(AddressBindSnafu { addr })?; + Ok(Self { + listener, + acceptor, + handshakes: JoinSet::new(), + }) + } +} + +impl Listener for HttpListener { + type Io = Either>; + type Addr = SocketAddr; + + async fn accept(&mut self) -> (Self::Io, Self::Addr) { + loop { + tokio::select! { + Some(result) = self.handshakes.join_next(), if !self.handshakes.is_empty() => { + match result { + Ok(Ok((stream, addr))) => return (Either::Right(stream), addr), + Ok(Err(err)) => debug!("HTTP TLS handshake failed: {err}"), + Err(err) => warn!("HTTP TLS handshake task failed: {err}"), + } + } + (stream, addr) = Listener::accept(&mut self.listener), + if self.handshakes.len() < MAX_PENDING_HANDSHAKES => { + if let Err(err) = stream.set_nodelay(true) { + warn!(err; "Failed to set TCP_NODELAY on incoming HTTP connection"); + } + let Some(acceptor) = self.acceptor.clone() else { + return (Either::Left(stream), addr); + }; + self.handshakes.spawn(async move { + let stream = tokio::time::timeout(HANDSHAKE_TIMEOUT, acceptor.accept(stream)) + .await + .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "HTTP TLS handshake timed out"))??; + Ok((stream, addr)) + }); + } + } + } + } + + fn local_addr(&self) -> io::Result { + self.listener.local_addr() + } +} + +#[cfg(test)] +mod tests { + use axum::extract::ConnectInfo; + use axum::{Router, routing}; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + use super::*; + use crate::http::{HttpOptions, HttpServerBuilder}; + use crate::server::Server; + use crate::tls::TlsMode; + + fn tls_identity() -> (tempfile::TempDir, TlsOption, reqwest::Client) { + let dir = tempfile::tempdir().unwrap(); + let rcgen::CertifiedKey { cert, key_pair } = rcgen::generate_simple_self_signed(vec![ + "localhost".to_string(), + "127.0.0.1".to_string(), + ]) + .unwrap(); + let cert_pem = cert.pem(); + let cert_path = dir.path().join("server.crt"); + let key_path = dir.path().join("server.key"); + std::fs::write(&cert_path, &cert_pem).unwrap(); + std::fs::write(&key_path, key_pair.serialize_pem()).unwrap(); + let tls = TlsOption { + mode: TlsMode::Require, + cert_path: cert_path.to_string_lossy().into_owned(), + key_path: key_path.to_string_lossy().into_owned(), + ..Default::default() + }; + let client = reqwest::Client::builder() + .add_root_certificate(reqwest::Certificate::from_pem(cert_pem.as_bytes()).unwrap()) + .no_proxy() + .timeout(Duration::from_secs(5)) + .build() + .unwrap(); + (dir, tls, client) + } + + #[tokio::test] + async fn test_http_tls_modes_match_grpc() { + let (_dir, identity, client) = tls_identity(); + for mode in [ + TlsMode::Disable, + TlsMode::Prefer, + TlsMode::Require, + TlsMode::VerifyCa, + TlsMode::VerifyFull, + ] { + let tls = TlsOption { + mode, + ..identity.clone() + }; + let scheme = if tls.should_force_tls() { + "https" + } else { + "http" + }; + let mut server = HttpServerBuilder::new(HttpOptions { + tls, + ..Default::default() + }) + .with_extra_router(Router::new().route( + "/peer", + routing::get(|ConnectInfo(peer): ConnectInfo| async move { + peer.ip().to_string() + }), + )) + .build(); + server.start("127.0.0.1:0".parse().unwrap()).await.unwrap(); + let addr = server.bind_addr().unwrap(); + let response = client + .get(format!("{scheme}://{addr}/peer")) + .send() + .await + .unwrap(); + assert_eq!(response.status(), reqwest::StatusCode::OK, "{mode:?}"); + assert_eq!(response.text().await.unwrap(), "127.0.0.1"); + if scheme == "https" { + assert!( + client + .get(format!("http://{addr}/peer")) + .send() + .await + .is_err() + ); + } + server.shutdown().await.unwrap(); + } + } + + #[tokio::test] + async fn test_http_tls_split_listeners_and_incomplete_handshake() { + let (_dir, tls, client) = tls_identity(); + let (mut main, api) = HttpServerBuilder::new(HttpOptions { + tls, + enable_api_server: true, + ..Default::default() + }) + .build_servers(); + let mut api = api.unwrap(); + for server in [&mut main, &mut api] { + server.start("127.0.0.1:0".parse().unwrap()).await.unwrap(); + let addr = server.bind_addr().unwrap(); + // An incomplete TLS handshake must not block another client's request. + let mut stalled = TcpStream::connect(addr).await.unwrap(); + stalled.write_all(&[0x16, 0x03]).await.unwrap(); + let response = client + .get(format!("https://{addr}/v1/auth/config")) + .send() + .await + .unwrap(); + assert_eq!(response.status(), reqwest::StatusCode::OK); + assert_eq!(response.version(), reqwest::Version::HTTP_2); + assert_eq!( + response.json::().await.unwrap(), + serde_json::json!({ + "auth_required": false, "methods": [] + }) + ); + server.shutdown().await.unwrap(); + // Pending handshakes belong to the listener and are dropped on shutdown. + let mut buf = [0]; + let result = tokio::time::timeout(Duration::from_secs(5), stalled.read(&mut buf)) + .await + .unwrap(); + assert!(matches!(result, Ok(0) | Err(_))); + } + } + + #[tokio::test] + async fn test_http_tls_invalid_identity_fails_startup() { + let (_dir, identity, _client) = tls_identity(); + let mut cases = vec![TlsOption { + mode: TlsMode::Require, + ..Default::default() + }]; + let mut missing_key = identity.clone(); + missing_key.key_path = "/nonexistent/greptimedb-http.key".to_string(); + cases.push(missing_key); + let mut invalid_cert = identity.clone(); + invalid_cert.cert_path.clone_from(&invalid_cert.key_path); + cases.push(invalid_cert); + let mut invalid_key = identity.clone(); + invalid_key.key_path.clone_from(&invalid_key.cert_path); + cases.push(invalid_key); + for tls in cases { + let mut server = HttpServerBuilder::new(HttpOptions { + tls, + ..Default::default() + }) + .build(); + assert!(server.start("127.0.0.1:0".parse().unwrap()).await.is_err()); + assert!(server.bind_addr().is_none()); + } + } + + #[test] + fn test_http_tls_configuration_round_trip() { + let default: HttpOptions = toml::from_str("").unwrap(); + assert_eq!(default.tls, TlsOption::default()); + let opts: HttpOptions = toml::from_str( + r#" + [tls] + mode = "require" + cert_path = "server.crt" + key_path = "server.key" + watch = false + "#, + ) + .unwrap(); + assert_eq!(opts.tls.mode, TlsMode::Require); + assert_eq!(opts.tls.cert_path, "server.crt"); + assert_eq!(opts.tls.key_path, "server.key"); + let round_trip: HttpOptions = toml::from_str(&toml::to_string(&opts).unwrap()).unwrap(); + assert_eq!(round_trip, opts); + } +} diff --git a/tests-integration/tests/http.rs b/tests-integration/tests/http.rs index eb9c3f9d473..02b9bfa8fe4 100644 --- a/tests-integration/tests/http.rs +++ b/tests-integration/tests/http.rs @@ -4967,6 +4967,13 @@ enable_cors = true enable_api_server = false api_server_addr = "127.0.0.1:4006" +[http.tls] +mode = "disable" +cert_path = "" +key_path = "" +ca_cert_path = "" +watch = false + [grpc] bind_addr = "127.0.0.1:4001" server_addr = "127.0.0.1:4001"