Merge pull request 'add advertise_endpoint configuration parameter' (#1563) from config-advertise-endpoint into main-v2

Reviewed-on: https://git.deuxfleurs.fr/Deuxfleurs/garage/pulls/1563
This commit is contained in:
Alex
2026-10-02 12:47:26 +00:00
13 changed files with 327 additions and 38 deletions
+65 -10
View File
@@ -2467,6 +2467,39 @@
}
}
},
"ConnectionParameters": {
"type": "object",
"required": [
"region"
],
"properties": {
"k2vEndpoint": {
"type": [
"string",
"null"
],
"description": "K2V endpoint URL"
},
"region": {
"type": "string",
"description": "Region parameter, put this in `$AWS_DEFAULT_REGION`"
},
"s3Endpoint": {
"type": [
"string",
"null"
],
"description": "S3 endpoint URL"
},
"s3UsePathStyle": {
"type": [
"boolean",
"null"
],
"description": "whether S3 client should use path-style instead of DNS style"
}
}
},
"CreateAdminTokenResponse": {
"allOf": [
{
@@ -3472,6 +3505,17 @@
],
"description": "Socket address used by other nodes to connect to this node for RPC"
},
"connectionParameters": {
"oneOf": [
{
"type": "null"
},
{
"$ref": "#/components/schemas/ConnectionParameters",
"description": "Connection parameters for S3 and K2V clients"
}
]
},
"dataPartition": {
"oneOf": [
{
@@ -3485,7 +3529,7 @@
},
"dbEngine": {
"type": "string",
"description": "database engine used for metadata"
"description": "Database engine used for metadata"
},
"draining": {
"type": [
@@ -3502,18 +3546,18 @@
"items": {
"type": "string"
},
"description": "build-time features enabled for this garage release"
"description": "Build-time features enabled for this garage release"
},
"garageVersion": {
"type": "string",
"description": "garage version running on this node"
"description": "Garage version running on this node"
},
"hostname": {
"type": [
"string",
"null"
],
"description": "hostname of this node"
"description": "Hostname of this node"
},
"isUp": {
"type": [
@@ -3549,7 +3593,7 @@
},
"rustVersion": {
"type": "string",
"description": "rustc version with which this garage release was compiled"
"description": "`rustc` version with which this garage release was compiled"
}
}
},
@@ -3889,6 +3933,17 @@
],
"description": "Socket address used by other nodes to connect to this node for RPC"
},
"connectionParameters": {
"oneOf": [
{
"type": "null"
},
{
"$ref": "#/components/schemas/ConnectionParameters",
"description": "Connection parameters for S3 and K2V clients"
}
]
},
"dataPartition": {
"oneOf": [
{
@@ -3902,7 +3957,7 @@
},
"dbEngine": {
"type": "string",
"description": "database engine used for metadata"
"description": "Database engine used for metadata"
},
"draining": {
"type": [
@@ -3919,18 +3974,18 @@
"items": {
"type": "string"
},
"description": "build-time features enabled for this garage release"
"description": "Build-time features enabled for this garage release"
},
"garageVersion": {
"type": "string",
"description": "garage version running on this node"
"description": "Garage version running on this node"
},
"hostname": {
"type": [
"string",
"null"
],
"description": "hostname of this node"
"description": "Hostname of this node"
},
"isUp": {
"type": [
@@ -3966,7 +4021,7 @@
},
"rustVersion": {
"type": "string",
"description": "rustc version with which this garage release was compiled"
"description": "`rustc` version with which this garage release was compiled"
}
}
},
+1 -2
View File
@@ -139,11 +139,10 @@ rpc_secret = "<RPC secret>"
[s3_api]
s3_region = "garage"
api_bind_addr = "[::]:3900"
root_domain = ".s3.garage"
advertise_endpoint = "http://s3.example.com:3900"
[s3_web]
bind_addr = "[::]:3902"
root_domain = ".web.garage"
index = "index.html"
```
+26
View File
@@ -32,6 +32,32 @@ An example:
mc ls --insecure garage/
```
## Updating your Garage configuration
This section is common to all methods described below.
When configuring a reverse-proxy, you should update your Garage configuration
file with the proper endpoint in `advertise_endpoint`:
```toml
[s3_api]
advertise_endpoint = "https://s3.example.com"
```
If you have a wildcard DNS setup and are able to automatically provision TLS
certificates for subdomains, you can enable vhost-style bucket addressing as
follows:
```toml
[s3_api]
root_domain = ".s3.example.com"
advertise_endpoint = "https://s3.example.com"
```
For example, this will make bucket `my-bucket` accessible either at
`https://my-bucket.s3.example.com` or at `https://s3.example.com/my-bucket`.
## socat (only for testing purposes)
If you want to test Garage with a TLS frontend, socat can do it for you in a single command:
+1
View File
@@ -74,6 +74,7 @@ rpc_secret = "$(openssl rand -hex 32)"
s3_region = "garage"
api_bind_addr = "[::]:3900"
root_domain = ".s3.garage.localhost"
advertise_endpoint = "http://s3.garage.localhost:3900"
[s3_web]
bind_addr = "[::]:3902"
+35 -6
View File
@@ -76,11 +76,13 @@ skip_crd = false
[s3_api]
api_bind_addr = "[::]:3900"
s3_region = "garage"
root_domain = ".s3.garage"
root_domain = ".s3.example.com"
advertise_endpoint = "https://s3.example.com"
advertise_path_style = false
[s3_web]
bind_addr = "[::]:3902"
root_domain = ".web.garage"
root_domain = ".web.example.com"
add_host_to_metrics = true
[admin]
@@ -146,6 +148,8 @@ The `[kubernetes_discovery]` section:
[`skip_crd`](#kube_skip_crd).
The `[s3_api]` section:
[`advertise_endpoint`](#s3_api_advertise_endpoint),
[`advertise_path_style`](#s3_api_advertise_path_style),
[`api_bind_addr`](#s3_api_bind_addr),
[`root_domain`](#s3_root_domain),
[`s3_region`](#s3_region).
@@ -805,9 +809,32 @@ Note path-style requests are always enabled, whether or not vhost-style is confi
Configuring vhost-style S3 required a wildcard DNS entry, and possibly a wildcard TLS certificate,
but might be required by software not supporting path-style requests.
If `root_domain` is `s3.garage.eu`, a bucket called `my-bucket` can be interacted with
using the hostname `my-bucket.s3.garage.eu`.
If `root_domain` is `s3.example.com`, a bucket called `my-bucket` can be interacted with
using the hostname `my-bucket.s3.example.com`.
#### `advertise_endpoint` {#s3_api_advertise_endpoint}
The publicly-advertised endpoint for accessing this Garage cluster. This must
be a full URI specifying the `http://` or `https://` scheme, suitable to be set
directly as the endpoint parameter in client configurations.
By default, this is not specified and Garage will fall back graciously:
- The admin API will not report any specific endpoint value in the connection
parameters returned by `GetNodeInfo`
- When the S3 API needs to return a string corresponding to the public URL of
an object, it will try to guess the URL by using `root_domain` if it is
available.
#### `advertise_path_style` {#s3_api_advertise_path_style}
Whether to advertise clients to use path-style URLs when accessing this Garage cluster.
This will be reported in the connection parameters returned by the `GetNodeInfo` admin API endpoint.
It will also impact the S3 API when it needs to return a string corresponding to the public URL of an object.
If it is not defined and `root_domain` is not set, it will default to `true`.
### The `[s3_web]` section
@@ -827,10 +854,12 @@ Alternatively, since `v0.8.5`, a path can be used to create a unix socket with 0
The optional suffix appended to bucket names for the corresponding HTTP Host.
For instance, if `root_domain` is `web.garage.eu`, a bucket called `deuxfleurs.fr`
will be accessible either with hostname `deuxfleurs.fr.web.garage.eu`
For instance, if `root_domain` is `web.example.com`, a bucket called `deuxfleurs.fr`
will be accessible either with hostname `deuxfleurs.fr.web.example.com`
or with hostname `deuxfleurs.fr`.
If this is not defined, the bucket name must always match the requested hostname.
#### `add_host_to_metrics` {#web_add_host_to_metrics}
Whether to include the requested domain name (HTTP `Host` header) in the
+27 -5
View File
@@ -1215,17 +1215,21 @@ pub struct LocalGetNodeInfoRequest;
pub struct LocalGetNodeInfoResponse {
pub node_id: String,
// FIXME for v3: remove Option<> and serde(default) for field below
/// hostname of this node
/// Hostname of this node
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hostname: Option<String>,
/// garage version running on this node
/// Garage version running on this node
pub garage_version: String,
/// build-time features enabled for this garage release
/// Build-time features enabled for this garage release
pub garage_features: Option<Vec<String>>,
/// rustc version with which this garage release was compiled
/// `rustc` version with which this garage release was compiled
pub rust_version: String,
/// database engine used for metadata
/// Database engine used for metadata
pub db_engine: String,
/// Connection parameters for S3 and K2V clients
#[serde(default, skip_serializing_if = "Option::is_none")]
pub connection_parameters: Option<ConnectionParameters>,
// FIXME for v3: remove Option<> and serde(default) for field below
// FIXME for v3: merge LocalGetNodeInfoResponse and NodeResp
/// Socket address used by other nodes to connect to this node for RPC
@@ -1251,6 +1255,24 @@ pub struct LocalGetNodeInfoResponse {
pub metadata_partition: Option<FreeSpaceResp>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ConnectionParameters {
/// Region parameter, put this in `$AWS_DEFAULT_REGION`
pub region: String,
/// S3 endpoint URL
#[serde(skip_serializing_if = "Option::is_none")]
pub s3_endpoint: Option<String>,
/// whether S3 client should use path-style instead of DNS style
#[serde(skip_serializing_if = "Option::is_none")]
pub s3_use_path_style: Option<bool>,
/// K2V endpoint URL
#[serde(skip_serializing_if = "Option::is_none")]
pub k2v_endpoint: Option<String>,
}
// ---- GetNodeStatistics ----
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
+18
View File
@@ -36,6 +36,24 @@ impl RequestHandler for LocalGetNodeInfoRequest {
.map(|features| features.iter().map(ToString::to_string).collect()),
rust_version: garage_util::version::rust_version().to_string(),
db_engine: garage.db.engine(),
connection_parameters: Some(ConnectionParameters {
region: garage.config.s3_api.s3_region.clone(),
s3_endpoint: garage
.config
.s3_api
.advertise_endpoint
.as_ref()
.map(ToString::to_string),
s3_use_path_style: garage.config.s3_api.advertise_path_style,
k2v_endpoint: garage
.config
.k2v_api
.as_ref()
.and_then(|c| c.advertise_endpoint.as_ref())
.map(ToString::to_string),
}),
is_up: Some(true),
addr: garage
.system
+2 -1
View File
@@ -143,7 +143,8 @@ async fn check_domain(garage: &Arc<Garage>, domain: &str) -> Result<bool, Error>
.config
.s3_web
.as_ref()
.and_then(|sw| host_to_bucket(domain, sw.root_domain.as_str()))
.and_then(|sw| sw.root_domain.as_ref())
.and_then(|rd| host_to_bucket(domain, rd))
{
(bname.to_string(), true)
} else {
+70
View File
@@ -19,3 +19,73 @@ pub mod website;
mod encryption;
mod router;
pub mod xml;
pub fn generate_public_object_url(
config: &garage_util::config::S3ApiConfig,
bucket: &str,
key: &str,
) -> String {
fn inner(
path_style: bool,
public_endpoint: &http::Uri,
bucket: &str,
key: &str,
) -> Option<String> {
use http::Uri;
if path_style {
let mut uri = public_endpoint.clone().into_parts();
uri.path_and_query = Some(
http::uri::PathAndQuery::from_maybe_shared(
format!("/{}/{}", bucket, key).into_bytes(),
)
.ok()?,
);
Some(Uri::from_parts(uri).ok()?.to_string())
} else {
let mut uri = public_endpoint.clone().into_parts();
let au = uri.authority.as_ref().unwrap();
let host = if let Some(port) = au.port() {
format!("{}.{}:{}", bucket, au.host(), port)
} else {
format!("{}.{}", bucket, au.host())
};
uri.authority = Some(http::uri::Authority::from_maybe_shared(host.into_bytes()).ok()?);
uri.path_and_query = Some(
http::uri::PathAndQuery::from_maybe_shared(format!("/{}", key).into_bytes())
.ok()?,
);
Some(Uri::from_parts(uri).ok()?.to_string())
}
}
let key = garage_api_common::encoding::uri_encode(key, false);
if let Some(public_endpoint) = &config.advertise_endpoint {
let path_style = config
.advertise_path_style
.unwrap_or(config.root_domain.is_none());
if let Some(res) = inner(path_style, public_endpoint, bucket, &key) {
return res;
}
}
// Fall back to older method
if let Some(root_domain) = &config.root_domain {
// FIXME: the returned URL uses https, but the client might want http
format!(
"https://{}.{}/{}",
bucket,
root_domain.trim_start_matches('.'),
key
)
} else {
// FIXME: what to return here??
format!("/{}/{}", bucket, key)
}
}
+5 -10
View File
@@ -506,16 +506,11 @@ pub async fn handle_complete_multipart_upload(
// Send response saying ok we're done
let result = s3_xml::CompleteMultipartUploadResult {
xmlns: (),
// FIXME: the location returned is not always correct:
// - we always return https, but maybe some people do http
// - if root_domain is not specified, a full URL is not returned
location: garage
.config
.s3_api
.root_domain
.as_ref()
.map(|rd| s3_xml::Value(format!("https://{}.{}/{}", bucket_name, rd, key)))
.or_else(|| Some(s3_xml::Value(format!("/{}/{}", bucket_name, key)))),
location: Some(s3_xml::Value(crate::generate_public_object_url(
&garage.config.s3_api,
bucket_name,
&key,
))),
bucket: s3_xml::Value(bucket_name.to_string()),
key: s3_xml::Value(key),
etag: s3_xml::Value(format!("\"{}\"", etag)),
+2
View File
@@ -74,9 +74,11 @@ allow_punycode = true
s3_region = "{region}"
api_bind_addr = "127.0.0.1:{s3_port}"
root_domain = ".s3.garage"
advertise_endpoint = "http://s3.garage"
[k2v_api]
api_bind_addr = "127.0.0.1:{k2v_port}"
advertise_endpoint = "http://s3.garage"
[s3_web]
bind_addr = "127.0.0.1:{web_port}"
+69 -2
View File
@@ -183,7 +183,15 @@ pub struct S3ApiConfig {
pub s3_region: String,
/// Suffix to remove from domain name to find bucket. If None,
/// vhost-style S3 request are disabled
#[serde(default)]
pub root_domain: Option<String>,
/// Public endpoint to use in auto-generated client configurations
#[serde(deserialize_with = "deserialize_advertise_endpoint", default)]
pub advertise_endpoint: Option<http::Uri>,
/// Whether the client configurations should use path-style instead of dns-style
#[serde(default)]
pub advertise_path_style: Option<bool>,
}
/// Configuration for K2V api
@@ -191,6 +199,10 @@ pub struct S3ApiConfig {
pub struct K2VApiConfig {
/// Address and port to bind for api serving
pub api_bind_addr: UnixOrTCPSocketAddress,
/// Public endpoint to use in auto-generated client configurations
#[serde(deserialize_with = "deserialize_advertise_endpoint", default)]
pub advertise_endpoint: Option<http::Uri>,
}
/// Configuration for serving files as normal web server
@@ -199,7 +211,8 @@ pub struct WebConfig {
/// Address and port to bind for web serving
pub bind_addr: UnixOrTCPSocketAddress,
/// Suffix to remove from domain name to find bucket
pub root_domain: String,
#[serde(default)]
pub root_domain: Option<String>,
/// Whether to add the requested domain to exported Prometheus metrics
#[serde(default)]
pub add_host_to_metrics: bool,
@@ -321,7 +334,32 @@ pub fn read_config(config_file: PathBuf) -> Result<Config, Error> {
)
})?;
Ok(toml::from_str(&config)?)
let mut config: Config = toml::from_str(&config)?;
// when no root domain is configured, force path style
if config.s3_api.root_domain.is_none() {
if config.s3_api.advertise_path_style == Some(false) {
return Err(Error::Message(
"`advertise_path_style` is `false` but `root_domain` is not configured".to_string(),
));
}
config.s3_api.advertise_path_style = Some(true);
}
// when using vhost-style, check that root_domain and advertised endpoint match
if config.s3_api.advertise_path_style == Some(false) {
if let (Some(rd), Some(ep)) = (
&config.s3_api.root_domain,
&config.s3_api.advertise_endpoint,
) {
if rd.trim_start_matches('.') != ep.authority().unwrap().host() {
warn!("Values of `root_domain` and `advertise_endpoint` do not match in configuration file");
}
}
}
Ok(config)
}
fn default_db_engine() -> String {
@@ -439,6 +477,35 @@ where
deserializer.deserialize_any(CapacityVisitor)
}
fn deserialize_advertise_endpoint<'de, D>(deserializer: D) -> Result<Option<http::Uri>, D::Error>
where
D: de::Deserializer<'de>,
{
struct EndpointVisitor;
impl<'de> serde::de::Visitor<'de> for EndpointVisitor {
type Value = Option<http::Uri>;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("string or null")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
let uri = value
.parse::<http::uri::Uri>()
.map_err(|e| E::custom(format!("invalid url: {}", e)))?;
if uri.authority().is_none() {
return Err(E::custom(format!("endpoint url {} is incomplete", uri)));
}
Ok(Some(uri))
}
}
deserializer.deserialize_any(EndpointVisitor)
}
#[cfg(test)]
mod tests {
use crate::error::Error;
+6 -2
View File
@@ -72,7 +72,7 @@ impl WebMetrics {
pub struct WebServer {
garage: Arc<Garage>,
metrics: Arc<WebMetrics>,
root_domain: String,
root_domain: Option<String>,
add_host_to_metrics: bool,
}
@@ -237,7 +237,11 @@ impl WebServer {
// Get bucket
let host = authority_to_host(authority)?;
let bucket_name = host_to_bucket(&host, &self.root_domain).unwrap_or(&host);
let bucket_name = self
.root_domain
.as_deref()
.and_then(|rd| host_to_bucket(&host, rd))
.unwrap_or(&host);
let bucket_id = self
.garage
.bucket_alias_table