diff --git a/Cargo.lock b/Cargo.lock
index acdc39ea8cd..254f116ecfd 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2398,6 +2398,7 @@ dependencies = [
"arrow-schema 59.2.0",
"async-compression",
"async-trait",
+ "base64 0.22.1",
"bytes",
"common-base",
"common-error",
@@ -2414,6 +2415,7 @@ dependencies = [
"lazy_static",
"object-store",
"object_store_opendal",
+ "opendal-service-azure-common",
"orc-rust",
"parquet",
"paste",
@@ -9687,6 +9689,7 @@ dependencies = [
"derive_builder 0.20.2",
"futures",
"hdfs-native",
+ "http 1.5.0",
"humantime-serde",
"object-store",
"object_store",
@@ -9700,6 +9703,7 @@ dependencies = [
"tempfile",
"tokio",
"toml 0.8.23",
+ "url",
"uuid",
]
diff --git a/Cargo.toml b/Cargo.toml
index 434803ad872..04579b98b4a 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -199,6 +199,8 @@ num_cpus = "1.16"
# https://github.com/GreptimeTeam/greptimedb/issues/9240
object_store_opendal = { git = "https://github.com/GreptimeTeam/opendal.git", rev = "c03e56802b47de3ccfc8fe028e59a459b278a0d2" }
once_cell = "1.18"
+# Same version as `opendal` in src/object-store/Cargo.toml.
+opendal-service-azure-common = "0.59.4"
opentelemetry-proto = { version = "0.32", features = [
"gen-tonic",
"metrics",
diff --git a/config/config.md b/config/config.md
index 97b4da0908d..fcdf1120fb3 100644
--- a/config/config.md
+++ b/config/config.md
@@ -153,6 +153,8 @@
| `query.experimental_spill_path` | String | Unset | Spill directory path. Ignored unless mode is "custom". |
| `query.experimental_spill_max_temp_directory_size` | String | `1GiB` | Maximum total size of spill directory (default: "1GiB").
Ignored unless mode is "custom". |
| `query.experimental_spill_compression` | String | `uncompressed` | Compression for spilled data files: "uncompressed" (default), "lz4_frame", "zstd".
Ignored unless mode is "custom". |
+| `query.remote_allowed_hosts` | Array | Unset | Hosts that object storage in SQL statements may connect to: `COPY`, `COPY DATABASE`,
`EXPORT/IMPORT DATABASE`, and external tables. Frontends check statements; datanodes check
external table scans. Unset or empty means no restriction.
Entries: `host`, `host:port`, `*.domain` (subdomains only), `*.domain:port`, or `[::1]:9000`.
An entry without a port matches any port.
Every request is checked, including credential requests, and redirects aren't followed.
GCS service account keys also need `oauth2.googleapis.com`; OSS needs `*.oss-.aliyuncs.com`.
Credentials from instance metadata are unavailable while the list is set.
Don't list metadata services, such as `169.254.169.254`, or internal services: request paths
aren't restricted. |
+| `query.allow_server_credentials` | Bool | `true` | Whether object storage in SQL statements may use the server's own credentials (environment
variables, credential files, or instance metadata) when no credentials are given. When false,
statements must provide credentials or use OSS `allow_anonymous`. |
| `storage` | -- | -- | The data storage options. |
| `storage.data_home` | String | `./greptimedb_data` | The working home directory. |
| `storage.copy_root` | String | `./greptimedb_data/copy` | Root directory for standalone SQL access to local files.
Relative SQL paths are resolved below this directory. Absolute paths are accepted only when
they are inside this directory. Defaults to `/copy`.
Distributed deployments always reject SQL access to local files.
Upgrade note: COPY commands and existing external tables that reference paths outside this
directory will fail. Move those files below the copy root, set this option to a dedicated
directory containing them, or migrate the files to object storage before upgrading. |
@@ -408,6 +410,8 @@
| `query.experimental_spill_path` | String | Unset | Spill directory path. Ignored unless mode is "custom". |
| `query.experimental_spill_max_temp_directory_size` | String | `1GiB` | Maximum total size of spill directory (default: "1GiB").
Ignored unless mode is "custom". |
| `query.experimental_spill_compression` | String | `uncompressed` | Compression for spilled data files: "uncompressed" (default), "lz4_frame", "zstd".
Ignored unless mode is "custom". |
+| `query.remote_allowed_hosts` | Array | Unset | Hosts that object storage in SQL statements may connect to: `COPY`, `COPY DATABASE`,
`EXPORT/IMPORT DATABASE`, and external tables. Frontends check statements; datanodes check
external table scans. Unset or empty means no restriction.
Entries: `host`, `host:port`, `*.domain` (subdomains only), `*.domain:port`, or `[::1]:9000`.
An entry without a port matches any port.
Every request is checked, including credential requests, and redirects aren't followed.
GCS service account keys also need `oauth2.googleapis.com`; OSS needs `*.oss-.aliyuncs.com`.
Credentials from instance metadata are unavailable while the list is set.
Don't list metadata services, such as `169.254.169.254`, or internal services: request paths
aren't restricted. |
+| `query.allow_server_credentials` | Bool | `true` | Whether object storage in SQL statements may use the server's own credentials (environment
variables, credential files, or instance metadata) when no credentials are given. When false,
statements must provide credentials or use OSS `allow_anonymous`. |
| `write_retry` | -- | -- | Retry retryable distributed write failures.
Backoff grows exponentially, with jitter to spread concurrent retries. |
| `write_retry.max_retries` | Integer | `3` | Maximum retries after the initial write attempt. Set to 0 to disable retries. |
| `write_retry.initial_backoff` | String | `1500ms` | Initial backoff before jitter is applied. Must be positive. |
@@ -642,6 +646,8 @@
| `query.experimental_spill_path` | String | Unset | Spill directory path. Ignored unless mode is "custom". |
| `query.experimental_spill_max_temp_directory_size` | String | `1GiB` | Maximum total size of spill directory (default: "1GiB").
Ignored unless mode is "custom". |
| `query.experimental_spill_compression` | String | `uncompressed` | Compression for spilled data files: "uncompressed" (default), "lz4_frame", "zstd".
Ignored unless mode is "custom". |
+| `query.remote_allowed_hosts` | Array | Unset | Hosts that object storage in SQL statements may connect to: `COPY`, `COPY DATABASE`,
`EXPORT/IMPORT DATABASE`, and external tables. Frontends check statements; datanodes check
external table scans. Unset or empty means no restriction.
Entries: `host`, `host:port`, `*.domain` (subdomains only), `*.domain:port`, or `[::1]:9000`.
An entry without a port matches any port.
Every request is checked, including credential requests, and redirects aren't followed.
GCS service account keys also need `oauth2.googleapis.com`; OSS needs `*.oss-.aliyuncs.com`.
Credentials from instance metadata are unavailable while the list is set.
Don't list metadata services, such as `169.254.169.254`, or internal services: request paths
aren't restricted. |
+| `query.allow_server_credentials` | Bool | `true` | Whether object storage in SQL statements may use the server's own credentials (environment
variables, credential files, or instance metadata) when no credentials are given. When false,
statements must provide credentials or use OSS `allow_anonymous`. |
| `storage` | -- | -- | The data storage options. |
| `storage.data_home` | String | `./greptimedb_data` | The working home directory. |
| `storage.probe_on_startup` | Bool | `true` | Whether to probe every remote object storage when the datanode starts.
The probe writes, reads, overwrites, lists and deletes an object under
`.greptime_probe/`, and a failure aborts startup. The probe lives at the storage
root, so the credentials must allow writes and deletes below the root. Disable it
when the credentials are scoped to narrower prefixes or when the storage may be
unavailable at startup. |
diff --git a/config/datanode.example.toml b/config/datanode.example.toml
index 6c2b990ba72..08d5ef46e23 100644
--- a/config/datanode.example.toml
+++ b/config/datanode.example.toml
@@ -375,6 +375,23 @@ memory_pool_size = "50%"
#+ experimental_spill_compression = "uncompressed"
# --- End spill-to-disk ---
+## Hosts that object storage in SQL statements may connect to: `COPY`, `COPY DATABASE`,
+## `EXPORT/IMPORT DATABASE`, and external tables. Frontends check statements; datanodes check
+## external table scans. Unset or empty means no restriction.
+## Entries: `host`, `host:port`, `*.domain` (subdomains only), `*.domain:port`, or `[::1]:9000`.
+## An entry without a port matches any port.
+## Every request is checked, including credential requests, and redirects aren't followed.
+## GCS service account keys also need `oauth2.googleapis.com`; OSS needs `*.oss-.aliyuncs.com`.
+## Credentials from instance metadata are unavailable while the list is set.
+## Don't list metadata services, such as `169.254.169.254`, or internal services: request paths
+## aren't restricted.
+## @toml2docs:none-default
+#+ remote_allowed_hosts = ["minio.internal:9000"]
+## Whether object storage in SQL statements may use the server's own credentials (environment
+## variables, credential files, or instance metadata) when no credentials are given. When false,
+## statements must provide credentials or use OSS `allow_anonymous`.
+allow_server_credentials = true
+
## The data storage options.
[storage]
## The working home directory.
diff --git a/config/frontend.example.toml b/config/frontend.example.toml
index fa1a99d185a..e259bd6c32f 100644
--- a/config/frontend.example.toml
+++ b/config/frontend.example.toml
@@ -420,6 +420,23 @@ memory_pool_size = "50%"
#+ experimental_spill_compression = "uncompressed"
# --- End spill-to-disk ---
+## Hosts that object storage in SQL statements may connect to: `COPY`, `COPY DATABASE`,
+## `EXPORT/IMPORT DATABASE`, and external tables. Frontends check statements; datanodes check
+## external table scans. Unset or empty means no restriction.
+## Entries: `host`, `host:port`, `*.domain` (subdomains only), `*.domain:port`, or `[::1]:9000`.
+## An entry without a port matches any port.
+## Every request is checked, including credential requests, and redirects aren't followed.
+## GCS service account keys also need `oauth2.googleapis.com`; OSS needs `*.oss-.aliyuncs.com`.
+## Credentials from instance metadata are unavailable while the list is set.
+## Don't list metadata services, such as `169.254.169.254`, or internal services: request paths
+## aren't restricted.
+## @toml2docs:none-default
+#+ remote_allowed_hosts = ["minio.internal:9000"]
+## Whether object storage in SQL statements may use the server's own credentials (environment
+## variables, credential files, or instance metadata) when no credentials are given. When false,
+## statements must provide credentials or use OSS `allow_anonymous`.
+allow_server_credentials = true
+
## Retry retryable distributed write failures.
## Backoff grows exponentially, with jitter to spread concurrent retries.
[write_retry]
diff --git a/config/standalone.example.toml b/config/standalone.example.toml
index abab13112e2..0e6f2c2301c 100644
--- a/config/standalone.example.toml
+++ b/config/standalone.example.toml
@@ -610,6 +610,23 @@ memory_pool_size = "50%"
#+ experimental_spill_compression = "uncompressed"
# --- End spill-to-disk ---
+## Hosts that object storage in SQL statements may connect to: `COPY`, `COPY DATABASE`,
+## `EXPORT/IMPORT DATABASE`, and external tables. Frontends check statements; datanodes check
+## external table scans. Unset or empty means no restriction.
+## Entries: `host`, `host:port`, `*.domain` (subdomains only), `*.domain:port`, or `[::1]:9000`.
+## An entry without a port matches any port.
+## Every request is checked, including credential requests, and redirects aren't followed.
+## GCS service account keys also need `oauth2.googleapis.com`; OSS needs `*.oss-.aliyuncs.com`.
+## Credentials from instance metadata are unavailable while the list is set.
+## Don't list metadata services, such as `169.254.169.254`, or internal services: request paths
+## aren't restricted.
+## @toml2docs:none-default
+#+ remote_allowed_hosts = ["minio.internal:9000"]
+## Whether object storage in SQL statements may use the server's own credentials (environment
+## variables, credential files, or instance metadata) when no credentials are given. When false,
+## statements must provide credentials or use OSS `allow_anonymous`.
+allow_server_credentials = true
+
## The data storage options.
[storage]
## The working home directory.
diff --git a/src/cmd/tests/load_config_test.rs b/src/cmd/tests/load_config_test.rs
index 639a6af0d73..b67607379e8 100644
--- a/src/cmd/tests/load_config_test.rs
+++ b/src/cmd/tests/load_config_test.rs
@@ -900,6 +900,46 @@ fn test_load_heartbeat_env_vars_from_env() {
});
}
+#[test]
+fn test_load_remote_allowed_hosts_from_env() {
+ let env_prefix = "REMOTE_ALLOWED_HOSTS_UT";
+ let env_key = [env_prefix, "QUERY", "REMOTE_ALLOWED_HOSTS"].join(ENV_VAR_SEP);
+
+ temp_env::with_var(env_key, Some("minio.internal:9000,*.example.com"), || {
+ let expected = vec![
+ "minio.internal:9000".to_string(),
+ "*.example.com".to_string(),
+ ];
+
+ let datanode =
+ GreptimeOptions::::load_layered_options(None, env_prefix).unwrap();
+ similar_asserts::assert_eq!(datanode.component.query.remote_allowed_hosts, expected);
+
+ let frontend =
+ GreptimeOptions::::load_layered_options(None, env_prefix).unwrap();
+ similar_asserts::assert_eq!(frontend.component.query.remote_allowed_hosts, expected);
+
+ let standalone =
+ GreptimeOptions::::load_layered_options(None, env_prefix).unwrap();
+ similar_asserts::assert_eq!(
+ standalone
+ .component
+ .frontend_options()
+ .query
+ .remote_allowed_hosts,
+ expected
+ );
+ similar_asserts::assert_eq!(
+ standalone
+ .component
+ .datanode_options()
+ .query
+ .remote_allowed_hosts,
+ expected
+ );
+ });
+}
+
#[test]
fn test_load_event_types_from_env() {
let env_prefix = "EVENT_TYPES_UT";
diff --git a/src/common/datasource/Cargo.toml b/src/common/datasource/Cargo.toml
index 3953d144bad..2134f0b087d 100644
--- a/src/common/datasource/Cargo.toml
+++ b/src/common/datasource/Cargo.toml
@@ -19,6 +19,7 @@ async-compression = { version = "0.4", features = [
"tokio",
] }
async-trait.workspace = true
+base64.workspace = true
bytes.workspace = true
common-base.workspace = true
common-error.workspace = true
@@ -34,6 +35,7 @@ futures.workspace = true
lazy_static.workspace = true
object-store.workspace = true
object_store_opendal.workspace = true
+opendal-service-azure-common.workspace = true
orc-rust = { version = "0.9", default-features = false, features = ["async"] }
parquet.workspace = true
paste.workspace = true
diff --git a/src/common/datasource/src/error.rs b/src/common/datasource/src/error.rs
index f98b43202f2..a847928e3e8 100644
--- a/src/common/datasource/src/error.rs
+++ b/src/common/datasource/src/error.rs
@@ -99,6 +99,16 @@ pub enum Error {
location: Location,
},
+ #[snafu(display(
+ "{} location has no credentials, and query.allow_server_credentials is false; provide credentials in the connection options",
+ backend
+ ))]
+ ServerCredentialsDisallowed {
+ backend: String,
+ #[snafu(implicit)]
+ location: Location,
+ },
+
#[snafu(display(
"Local filesystem path '{}' does not exist within the configured copy root",
path
@@ -305,6 +315,7 @@ impl ErrorExt for Error {
| InvalidUrl { .. }
| LocalFileAccessDisabled { .. }
| LocalFileAccessDenied { .. }
+ | ServerCredentialsDisallowed { .. }
| LocalFilePathNotFound { .. }
| MissingObjectName { .. }
| InvalidLocalFileRoot { .. }
diff --git a/src/common/datasource/src/object_store.rs b/src/common/datasource/src/object_store.rs
index 2cd4f7193eb..c97169bcda4 100644
--- a/src/common/datasource/src/object_store.rs
+++ b/src/common/datasource/src/object_store.rs
@@ -16,6 +16,8 @@ pub mod azblob;
pub mod fs;
pub mod gcs;
pub mod oss;
+#[cfg(test)]
+mod remote_tests;
pub mod s3;
use std::collections::HashMap;
@@ -24,10 +26,11 @@ use std::sync::Arc;
use common_telemetry::debug;
use lazy_static::lazy_static;
-use object_store::ObjectStore;
use object_store::secure_fs::SecureFsRoot;
+use object_store::util::{with_instrument_layers, with_retry_layers};
+use object_store::{ObjectStore, ObjectStoreBuilder};
use regex::Regex;
-use snafu::{OptionExt, ResultExt};
+use snafu::{OptionExt, ResultExt, ensure};
use url::{ParseError, Url};
use self::azblob::build_azblob_backend;
@@ -38,6 +41,8 @@ use crate::error::{self, Result};
use crate::object_store::oss::build_oss_backend;
use crate::util::find_dir_and_filename;
+pub use object_store::remote_access::RemoteStorageAccess;
+
pub const FS_SCHEMA: &str = "FS";
pub const FILE_SCHEMA: &str = "FILE";
pub const S3_SCHEMA: &str = "S3";
@@ -377,12 +382,18 @@ pub async fn build_backend(
url: &str,
connection: &HashMap,
local_file_access: &LocalFileAccess,
+ remote_storage_access: &RemoteStorageAccess,
) -> Result {
- Ok(
- build_backend_inner(url, connection, local_file_access, false, false)
- .await?
- .object_store,
+ Ok(build_backend_inner(
+ url,
+ connection,
+ local_file_access,
+ remote_storage_access,
+ false,
+ false,
)
+ .await?
+ .object_store)
}
/// Builds a backend and returns the target path relative to the backend root.
@@ -390,8 +401,17 @@ pub async fn build_backend_with_path(
url: &str,
connection: &HashMap,
local_file_access: &LocalFileAccess,
+ remote_storage_access: &RemoteStorageAccess,
) -> Result {
- build_backend_inner(url, connection, local_file_access, false, false).await
+ build_backend_inner(
+ url,
+ connection,
+ local_file_access,
+ remote_storage_access,
+ false,
+ false,
+ )
+ .await
}
/// Builds a backend for an operation that may create the target directory.
@@ -399,12 +419,18 @@ pub async fn build_backend_for_write(
url: &str,
connection: &HashMap,
local_file_access: &LocalFileAccess,
+ remote_storage_access: &RemoteStorageAccess,
) -> Result {
- Ok(
- build_backend_inner(url, connection, local_file_access, true, false)
- .await?
- .object_store,
+ Ok(build_backend_inner(
+ url,
+ connection,
+ local_file_access,
+ remote_storage_access,
+ true,
+ false,
)
+ .await?
+ .object_store)
}
/// Builds a writable backend and returns the target path relative to the backend root.
@@ -412,14 +438,24 @@ pub async fn build_backend_for_write_with_path(
url: &str,
connection: &HashMap,
local_file_access: &LocalFileAccess,
+ remote_storage_access: &RemoteStorageAccess,
) -> Result {
- build_backend_inner(url, connection, local_file_access, true, true).await
+ build_backend_inner(
+ url,
+ connection,
+ local_file_access,
+ remote_storage_access,
+ true,
+ true,
+ )
+ .await
}
async fn build_backend_inner(
url: &str,
connection: &HashMap,
local_file_access: &LocalFileAccess,
+ remote_storage_access: &RemoteStorageAccess,
create_local_root: bool,
require_object_path: bool,
) -> Result {
@@ -468,25 +504,25 @@ async fn build_backend_inner(
let host = host.context(error::EmptyHostPathSnafu {
url: url.to_string(),
})?;
- build_s3_backend(&host, &root, connection)?
+ build_s3_backend(&host, &root, connection, remote_storage_access)?
}
OSS_SCHEMA => {
let host = host.context(error::EmptyHostPathSnafu {
url: url.to_string(),
})?;
- build_oss_backend(&host, &root, connection)?
+ build_oss_backend(&host, &root, connection, remote_storage_access)?
}
GCS_SCHEMA => {
let host = host.context(error::EmptyHostPathSnafu {
url: url.to_string(),
})?;
- build_gcs_backend(&host, &root, connection)?
+ build_gcs_backend(&host, &root, connection, remote_storage_access)?
}
AZBLOB_SCHEMA => {
let host = host.context(error::EmptyHostPathSnafu {
url: url.to_string(),
})?;
- build_azblob_backend(&host, &root, connection)?
+ build_azblob_backend(&host, &root, connection, remote_storage_access)?
}
_ => error::UnsupportedBackendProtocolSnafu {
protocol: schema,
@@ -501,6 +537,36 @@ async fn build_backend_inner(
})
}
+/// Returns a connection option, treating an empty value as unset like the backends do.
+fn connection_value<'a>(connection: &'a HashMap, key: &str) -> Option<&'a str> {
+ connection
+ .get(key)
+ .map(String::as_str)
+ .filter(|value| !value.is_empty())
+}
+
+fn ensure_server_credentials_allowed(
+ remote_storage_access: &RemoteStorageAccess,
+ backend: &str,
+) -> Result<()> {
+ ensure!(
+ remote_storage_access.allow_server_credentials(),
+ error::ServerCredentialsDisallowedSnafu { backend }
+ );
+ Ok(())
+}
+
+fn finish_remote_backend(
+ builder: impl ObjectStoreBuilder,
+ remote_storage_access: &RemoteStorageAccess,
+) -> Result {
+ let object_store = ObjectStore::new(builder).context(error::BuildBackendSnafu)?;
+ Ok(with_instrument_layers(
+ with_retry_layers(remote_storage_access.apply(object_store)),
+ true,
+ ))
+}
+
lazy_static! {
static ref DISK_SYMBOL_PATTERN: Regex = Regex::new(r"^([A-Za-z]:[/\\])").unwrap();
}
@@ -522,8 +588,8 @@ mod tests {
use url::Url;
use super::{
- LocalFileAccess, build_backend, build_backend_for_write, build_backend_for_write_with_path,
- build_backend_with_path, handle_windows_path,
+ LocalFileAccess, RemoteStorageAccess, build_backend, build_backend_for_write,
+ build_backend_for_write_with_path, build_backend_with_path, handle_windows_path,
};
use crate::error::Error;
@@ -600,8 +666,13 @@ mod tests {
Url::from_directory_path(dir.path()).unwrap()
);
for location in [relative, absolute, file_url] {
- let result =
- build_backend_for_write_with_path(&location, &HashMap::new(), &access).await;
+ let result = build_backend_for_write_with_path(
+ &location,
+ &HashMap::new(),
+ &access,
+ &RemoteStorageAccess::unrestricted(),
+ )
+ .await;
assert!(
matches!(result, Err(Error::LocalFileAccessDenied { .. })),
"{location}"
@@ -646,9 +717,14 @@ mod tests {
let access = LocalFileAccess::sandboxed(©_root).unwrap();
let connection = HashMap::new();
- let store = build_backend_for_write("nested/data.txt", &connection, &access)
- .await
- .unwrap();
+ let store = build_backend_for_write(
+ "nested/data.txt",
+ &connection,
+ &access,
+ &RemoteStorageAccess::unrestricted(),
+ )
+ .await
+ .unwrap();
store.write("data.txt", "first").await.unwrap();
store.write("data.txt", "second").await.unwrap();
assert_eq!(
@@ -657,9 +733,14 @@ mod tests {
);
let missing = copy_root.join("missing/directory");
- let error = build_backend("missing/directory/data.txt", &connection, &access)
- .await
- .unwrap_err();
+ let error = build_backend(
+ "missing/directory/data.txt",
+ &connection,
+ &access,
+ &RemoteStorageAccess::unrestricted(),
+ )
+ .await
+ .unwrap_err();
assert!(matches!(&error, Error::LocalFilePathNotFound { .. }));
assert_eq!(error.status_code(), StatusCode::InvalidArguments);
assert_eq!(error.retry_hint(), RetryHint::NonRetryable);
@@ -670,56 +751,105 @@ mod tests {
assert!(!missing.exists());
let absolute = copy_root.join("nested/data.txt");
- let store = build_backend(absolute.to_str().unwrap(), &connection, &access)
- .await
- .unwrap();
+ let store = build_backend(
+ absolute.to_str().unwrap(),
+ &connection,
+ &access,
+ &RemoteStorageAccess::unrestricted(),
+ )
+ .await
+ .unwrap();
assert_eq!(store.read("data.txt").await.unwrap().to_vec(), b"second");
let file_url = Url::from_file_path(&absolute).unwrap().to_string();
- let store = build_backend(&file_url, &connection, &access)
- .await
- .unwrap();
+ let store = build_backend(
+ &file_url,
+ &connection,
+ &access,
+ &RemoteStorageAccess::unrestricted(),
+ )
+ .await
+ .unwrap();
assert_eq!(store.read("data.txt").await.unwrap().to_vec(), b"second");
let internal_file = internal_dir.join("secret");
assert!(matches!(
- build_backend(internal_file.to_str().unwrap(), &connection, &access).await,
+ build_backend(
+ internal_file.to_str().unwrap(),
+ &connection,
+ &access,
+ &RemoteStorageAccess::unrestricted()
+ )
+ .await,
Err(Error::LocalFileAccessDenied { .. })
));
assert!(
- build_backend("../escape/data.txt", &connection, &access)
- .await
- .is_err()
+ build_backend(
+ "../escape/data.txt",
+ &connection,
+ &access,
+ &RemoteStorageAccess::unrestricted()
+ )
+ .await
+ .is_err()
);
let outside = data_home.path().join("outside/new");
assert!(
- build_backend(outside.to_str().unwrap(), &connection, &access)
- .await
- .is_err()
+ build_backend(
+ outside.to_str().unwrap(),
+ &connection,
+ &access,
+ &RemoteStorageAccess::unrestricted()
+ )
+ .await
+ .is_err()
);
assert!(!outside.parent().unwrap().exists());
let prefix_escape = data_home.path().join("copy-not-the-root/new");
assert!(matches!(
- build_backend(prefix_escape.to_str().unwrap(), &connection, &access).await,
+ build_backend(
+ prefix_escape.to_str().unwrap(),
+ &connection,
+ &access,
+ &RemoteStorageAccess::unrestricted()
+ )
+ .await,
Err(Error::LocalFileAccessDenied { .. })
));
assert!(!prefix_escape.parent().unwrap().exists());
let disabled = LocalFileAccess::Disabled;
- let error = build_backend(internal_file.to_str().unwrap(), &connection, &disabled)
- .await
- .unwrap_err();
+ let error = build_backend(
+ internal_file.to_str().unwrap(),
+ &connection,
+ &disabled,
+ &RemoteStorageAccess::unrestricted(),
+ )
+ .await
+ .unwrap_err();
assert!(matches!(&error, Error::LocalFileAccessDisabled { .. }));
assert_eq!(error.status_code(), StatusCode::InvalidArguments);
assert_eq!(error.retry_hint(), RetryHint::NonRetryable);
assert!(matches!(
- build_backend(&file_url, &connection, &disabled).await,
+ build_backend(
+ &file_url,
+ &connection,
+ &disabled,
+ &RemoteStorageAccess::unrestricted()
+ )
+ .await,
Err(Error::LocalFileAccessDisabled { .. })
));
assert!(matches!(
- build_backend(outside.to_str().unwrap(), &connection, &disabled).await,
+ build_backend(
+ outside.to_str().unwrap(),
+ &connection,
+ &disabled,
+ &RemoteStorageAccess::unrestricted()
+ )
+ .await,
Err(Error::LocalFileAccessDisabled { .. })
));
assert!(!outside.parent().unwrap().exists());
@@ -736,9 +866,14 @@ mod tests {
let location = Url::from_file_path(&file).unwrap().to_string();
assert!(location.contains("%20"));
let access = LocalFileAccess::sandboxed(©_root).unwrap();
- let backend = build_backend_with_path(&location, &HashMap::new(), &access)
- .await
- .unwrap();
+ let backend = build_backend_with_path(
+ &location,
+ &HashMap::new(),
+ &access,
+ &RemoteStorageAccess::unrestricted(),
+ )
+ .await
+ .unwrap();
assert_eq!(backend.object_path.as_deref(), Some("data file.txt"));
assert_eq!(
@@ -760,7 +895,13 @@ mod tests {
let location = Url::from_directory_path(&target).unwrap().to_string();
let access = LocalFileAccess::sandboxed(©_root).unwrap();
- let result = build_backend_for_write_with_path(&location, &HashMap::new(), &access).await;
+ let result = build_backend_for_write_with_path(
+ &location,
+ &HashMap::new(),
+ &access,
+ &RemoteStorageAccess::unrestricted(),
+ )
+ .await;
assert!(matches!(result, Err(Error::MissingObjectName { .. })));
assert!(!target.exists());
@@ -769,22 +910,32 @@ mod tests {
&location,
&HashMap::new(),
&LocalFileAccess::Disabled,
+ &RemoteStorageAccess::unrestricted(),
)
.await;
assert!(matches!(result, Err(Error::LocalFileAccessDisabled { .. })));
assert!(!target.exists());
let relative_target = copy_root.join("relative directory");
- let result =
- build_backend_for_write_with_path("relative directory/", &HashMap::new(), &access)
- .await;
+ let result = build_backend_for_write_with_path(
+ "relative directory/",
+ &HashMap::new(),
+ &access,
+ &RemoteStorageAccess::unrestricted(),
+ )
+ .await;
assert!(matches!(result, Err(Error::MissingObjectName { .. })));
assert!(!relative_target.exists());
let allowed_directory = copy_root.join("allowed directory");
- build_backend_for_write("allowed directory/", &HashMap::new(), &access)
- .await
- .unwrap();
+ build_backend_for_write(
+ "allowed directory/",
+ &HashMap::new(),
+ &access,
+ &RemoteStorageAccess::unrestricted(),
+ )
+ .await
+ .unwrap();
assert!(allowed_directory.is_dir());
}
@@ -802,9 +953,14 @@ mod tests {
let connection = HashMap::new();
let file_location = file.to_str().unwrap();
assert!(file_location.contains('\\'));
- let backend = build_backend_with_path(file_location, &connection, &access)
- .await
- .unwrap();
+ let backend = build_backend_with_path(
+ file_location,
+ &connection,
+ &access,
+ &RemoteStorageAccess::unrestricted(),
+ )
+ .await
+ .unwrap();
assert_eq!(backend.object_path.as_deref(), Some("data.txt"));
assert_eq!(
backend
@@ -819,7 +975,13 @@ mod tests {
let new_directory = copy_root.join("new directory");
let directory_location = format!("{}\\", new_directory.display());
assert!(matches!(
- build_backend_for_write_with_path(&directory_location, &connection, &access).await,
+ build_backend_for_write_with_path(
+ &directory_location,
+ &connection,
+ &access,
+ &RemoteStorageAccess::unrestricted()
+ )
+ .await,
Err(Error::MissingObjectName { .. })
));
assert!(!new_directory.exists());
@@ -869,6 +1031,7 @@ mod tests {
location,
&connection,
&LocalFileAccess::Disabled,
+ &RemoteStorageAccess::unrestricted(),
)
.await
.unwrap();
@@ -894,20 +1057,35 @@ mod tests {
let connection = HashMap::new();
assert!(
- build_backend("escape/secret", &connection, &access)
- .await
- .is_err()
+ build_backend(
+ "escape/secret",
+ &connection,
+ &access,
+ &RemoteStorageAccess::unrestricted()
+ )
+ .await
+ .is_err()
);
assert!(
- build_backend_for_write("escape/new", &connection, &access)
- .await
- .is_err()
+ build_backend_for_write(
+ "escape/new",
+ &connection,
+ &access,
+ &RemoteStorageAccess::unrestricted()
+ )
+ .await
+ .is_err()
);
assert!(!outside.join("new").exists());
- let store = build_backend("secret-link", &connection, &access)
- .await
- .unwrap();
+ let store = build_backend(
+ "secret-link",
+ &connection,
+ &access,
+ &RemoteStorageAccess::unrestricted(),
+ )
+ .await
+ .unwrap();
assert!(store.read("secret-link").await.is_err());
assert!(store.write("secret-link", "overwritten").await.is_err());
assert_eq!(
diff --git a/src/common/datasource/src/object_store/azblob.rs b/src/common/datasource/src/object_store/azblob.rs
index 4a24382db4e..1deadbd1e51 100644
--- a/src/common/datasource/src/object_store/azblob.rs
+++ b/src/common/datasource/src/object_store/azblob.rs
@@ -15,11 +15,14 @@
use std::collections::HashMap;
use object_store::ObjectStore;
+use object_store::remote_access::RemoteStorageAccess;
use object_store::services::Azblob;
-use object_store::util::{with_instrument_layers, with_retry_layers};
-use snafu::ResultExt;
+use opendal_service_azure_common::azure_account_name_from_endpoint;
use crate::error::{self, Result};
+use crate::object_store::{
+ connection_value, ensure_server_credentials_allowed, finish_remote_backend,
+};
const ENDPOINT: &str = "endpoint";
const ACCOUNT_NAME: &str = "account_name";
@@ -34,6 +37,7 @@ pub fn build_azblob_backend(
container: &str,
root: &str,
connection: &HashMap,
+ remote_storage_access: &RemoteStorageAccess,
) -> Result {
let mut builder = Azblob::default().root(root).container(container);
@@ -41,23 +45,37 @@ pub fn build_azblob_backend(
builder = builder.account_name(account_name);
}
- if let Some(account_key) = connection.get(ACCOUNT_KEY) {
- builder = builder.account_key(account_key);
- }
-
if let Some(endpoint) = connection.get(ENDPOINT) {
builder = builder.endpoint(endpoint);
}
- if let Some(sas_token) = connection.get(SAS_TOKEN) {
+ let sas_token = connection_value(connection, SAS_TOKEN);
+ let account_key = connection_value(connection, ACCOUNT_KEY);
+ if let Some(account_key) = account_key {
+ // The shared key is only used when the account name is known, the same
+ // way the backend resolves it; otherwise the key would be ignored.
+ let has_account_name = connection_value(connection, ACCOUNT_NAME).is_some()
+ || connection_value(connection, ENDPOINT)
+ .and_then(azure_account_name_from_endpoint)
+ .is_some();
+ if !has_account_name {
+ return error::InvalidConnectionSnafu {
+ msg: format!(
+ "{ACCOUNT_KEY} requires {ACCOUNT_NAME}, or an {ENDPOINT} that contains the account name"
+ ),
+ }
+ .fail();
+ }
+ builder = builder.account_key(account_key);
+ }
+ if let Some(sas_token) = sas_token {
builder = builder.sas_token(sas_token);
}
+ if account_key.is_none() && sas_token.is_none() {
+ ensure_server_credentials_allowed(remote_storage_access, "AzBlob")?;
+ }
- let object_store = ObjectStore::new(builder).context(error::BuildBackendSnafu)?;
- Ok(with_instrument_layers(
- with_retry_layers(object_store),
- true,
- ))
+ finish_remote_backend(builder, remote_storage_access)
}
#[cfg(test)]
diff --git a/src/common/datasource/src/object_store/gcs.rs b/src/common/datasource/src/object_store/gcs.rs
index 406b4ff831c..a881a91e985 100644
--- a/src/common/datasource/src/object_store/gcs.rs
+++ b/src/common/datasource/src/object_store/gcs.rs
@@ -14,12 +14,17 @@
use std::collections::HashMap;
+use base64::Engine;
+use base64::prelude::BASE64_STANDARD;
use object_store::ObjectStore;
+use object_store::remote_access::RemoteStorageAccess;
use object_store::services::Gcs;
-use object_store::util::{with_instrument_layers, with_retry_layers};
-use snafu::ResultExt;
+use serde::Deserialize;
use crate::error::{self, Result};
+use crate::object_store::{
+ connection_value, ensure_server_credentials_allowed, finish_remote_backend,
+};
const ENDPOINT: &str = "endpoint";
const CREDENTIAL: &str = "credential";
@@ -33,6 +38,7 @@ pub fn build_gcs_backend(
bucket: &str,
root: &str,
connection: &HashMap,
+ remote_storage_access: &RemoteStorageAccess,
) -> Result {
let mut builder = Gcs::default().root(root).bucket(bucket);
@@ -40,25 +46,108 @@ pub fn build_gcs_backend(
builder = builder.scope(scope);
}
- if let Some(credential) = connection.get(CREDENTIAL) {
- builder = builder.credential(credential);
+ if let Some(credential) = connection_value(connection, CREDENTIAL) {
+ let credential = service_account_credential(credential)?;
+ // The rebuilt credential always yields a provider. Disabling config
+ // load and VM metadata also empties the default chain behind it, in
+ // case reqsign ever parses the credential differently.
+ builder = builder
+ .credential(&credential)
+ .disable_config_load()
+ .disable_vm_metadata();
+ } else {
+ ensure_server_credentials_allowed(remote_storage_access, "GCS")?;
}
if let Some(endpoint) = connection.get(ENDPOINT) {
builder = builder.endpoint(endpoint);
}
- let object_store = ObjectStore::new(builder).context(error::BuildBackendSnafu)?;
- Ok(with_instrument_layers(
- with_retry_layers(object_store),
- true,
- ))
+ finish_remote_backend(builder, remote_storage_access)
+}
+
+/// The credential file shape reqsign parses, limited to service account keys.
+///
+/// Other credential types make the server read local files, expand environment
+/// variables or call URLs taken from the credential.
+#[derive(Deserialize)]
+#[serde(tag = "type", rename_all = "snake_case")]
+enum CredentialFile {
+ ServiceAccount(ServiceAccountKey),
+}
+
+#[derive(Deserialize)]
+struct ServiceAccountKey {
+ private_key: String,
+ client_email: String,
+}
+
+/// Validates a service account key and rebuilds it with only the fields used
+/// for signing, so other fields such as `token_uri` never reach reqsign.
+fn service_account_credential(credential: &str) -> Result {
+ // Errors must not include the decoded content, which holds a private key.
+ let key = BASE64_STANDARD
+ .decode(credential)
+ .ok()
+ .and_then(|decoded| serde_json::from_slice::(&decoded).ok())
+ .map(|CredentialFile::ServiceAccount(key)| key)
+ .filter(|key| !key.private_key.is_empty() && !key.client_email.is_empty());
+ if let Some(key) = key {
+ let rebuilt = serde_json::json!({
+ "type": "service_account",
+ "private_key": key.private_key,
+ "client_email": key.client_email,
+ });
+ Ok(BASE64_STANDARD.encode(rebuilt.to_string()))
+ } else {
+ error::InvalidConnectionSnafu {
+ msg: format!(
+ "{CREDENTIAL} must be a base64-encoded service_account key with private_key and client_email"
+ ),
+ }
+ .fail()
+ }
}
#[cfg(test)]
mod tests {
use super::*;
+ #[test]
+ fn test_service_account_credential() {
+ let encode = |json: &str| BASE64_STANDARD.encode(json);
+ let rebuilt = service_account_credential(&encode(
+ r#"{"type":"service_account","private_key":"key","client_email":"a@b.iam.gserviceaccount.com","token_uri":"https://example.com"}"#,
+ ))
+ .unwrap();
+ let rebuilt: serde_json::Value =
+ serde_json::from_slice(&BASE64_STANDARD.decode(rebuilt).unwrap()).unwrap();
+ assert_eq!(
+ rebuilt,
+ serde_json::json!({
+ "type": "service_account",
+ "private_key": "key",
+ "client_email": "a@b.iam.gserviceaccount.com",
+ })
+ );
+ for invalid in [
+ "not base64".to_string(),
+ encode("not json"),
+ encode(r#"{"private_key":"key","client_email":"a@b"}"#),
+ encode(r#"{"type":"service_account","private_key":"key"}"#),
+ encode(r#"{"type":"service_account","private_key":"","client_email":"a@b"}"#),
+ encode(
+ r#"{"type":"external_account","audience":"a","subject_token_type":"t","token_url":"http://127.0.0.1/","credential_source":{"file":"/etc/passwd"}}"#,
+ ),
+ encode(
+ r#"{"type":"authorized_user","client_id":"a","client_secret":"b","refresh_token":"c"}"#,
+ ),
+ ] {
+ let err = service_account_credential(&invalid).unwrap_err();
+ assert!(!err.to_string().contains("/etc/passwd"));
+ }
+ }
+
#[test]
fn test_is_supported_in_gcs() {
assert!(is_supported_in_gcs(ENDPOINT));
diff --git a/src/common/datasource/src/object_store/oss.rs b/src/common/datasource/src/object_store/oss.rs
index da651f1f9a8..7c72e2dcf15 100644
--- a/src/common/datasource/src/object_store/oss.rs
+++ b/src/common/datasource/src/object_store/oss.rs
@@ -15,11 +15,13 @@
use std::collections::HashMap;
use object_store::ObjectStore;
+use object_store::remote_access::RemoteStorageAccess;
use object_store::services::Oss;
-use object_store::util::{with_instrument_layers, with_retry_layers};
-use snafu::ResultExt;
use crate::error::{self, Result};
+use crate::object_store::{
+ connection_value, ensure_server_credentials_allowed, finish_remote_backend,
+};
const BUCKET: &str = "bucket";
const ENDPOINT: &str = "endpoint";
@@ -48,6 +50,7 @@ pub fn build_oss_backend(
bucket: &str,
root: &str,
connection: &HashMap,
+ remote_storage_access: &RemoteStorageAccess,
) -> Result {
let mut builder = Oss::default().bucket(bucket).root(root);
@@ -55,14 +58,7 @@ pub fn build_oss_backend(
builder = builder.endpoint(endpoint);
}
- if let Some(access_key_id) = connection.get(ACCESS_KEY_ID) {
- builder = builder.access_key_id(access_key_id);
- }
-
- if let Some(access_key_secret) = connection.get(ACCESS_KEY_SECRET) {
- builder = builder.access_key_secret(access_key_secret);
- }
-
+ let mut skip_signature = false;
if let Some((key, value)) = connection
.get(SKIP_SIGNATURE)
.map(|value| (SKIP_SIGNATURE, value))
@@ -72,7 +68,7 @@ pub fn build_oss_backend(
.map(|value| (ALLOW_ANONYMOUS, value))
})
{
- let skip_signature = value.as_str().parse::().map_err(|e| {
+ skip_signature = value.as_str().parse::().map_err(|e| {
error::InvalidConnectionSnafu {
msg: format!("failed to parse the option {}={}, {}", key, value, e),
}
@@ -83,11 +79,27 @@ pub fn build_oss_backend(
}
}
- let object_store = ObjectStore::new(builder).context(error::BuildBackendSnafu)?;
- Ok(with_instrument_layers(
- with_retry_layers(object_store),
- true,
- ))
+ if !skip_signature {
+ match (
+ connection_value(connection, ACCESS_KEY_ID),
+ connection_value(connection, ACCESS_KEY_SECRET),
+ ) {
+ (Some(access_key_id), Some(access_key_secret)) => {
+ builder = builder
+ .access_key_id(access_key_id)
+ .access_key_secret(access_key_secret);
+ }
+ (None, None) => ensure_server_credentials_allowed(remote_storage_access, "OSS")?,
+ _ => {
+ return error::InvalidConnectionSnafu {
+ msg: format!("{ACCESS_KEY_ID} and {ACCESS_KEY_SECRET} must be set together"),
+ }
+ .fail();
+ }
+ }
+ }
+
+ finish_remote_backend(builder, remote_storage_access)
}
#[cfg(test)]
@@ -118,7 +130,12 @@ mod tests {
connection.insert(ACCESS_KEY_SECRET.to_string(), "key_secret".to_string());
connection.insert(ALLOW_ANONYMOUS.to_string(), "true".to_string());
- let result = build_oss_backend("my-bucket", "my-root", &connection);
+ let result = build_oss_backend(
+ "my-bucket",
+ "my-root",
+ &connection,
+ &RemoteStorageAccess::unrestricted(),
+ );
assert!(result.is_ok());
}
}
diff --git a/src/common/datasource/src/object_store/remote_tests.rs b/src/common/datasource/src/object_store/remote_tests.rs
new file mode 100644
index 00000000000..27cd373238e
--- /dev/null
+++ b/src/common/datasource/src/object_store/remote_tests.rs
@@ -0,0 +1,333 @@
+// 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.
+
+//! Which identity SQL object stores use. These tests plant usable server
+//! credentials in the environment and check that they are only used when the
+//! SQL options carry no credentials and the policy allows it. The credentials
+//! are set on a child process running the ignored `*_in_child` test, so they
+//! never reach other tests in this process.
+
+use std::collections::HashMap;
+use std::process::Command;
+
+use base64::Engine;
+use base64::prelude::BASE64_STANDARD;
+use object_store::test_util::{MockHttpServer, http_response};
+
+use super::*;
+use crate::error::Error;
+
+/// Runs the ignored test `name` of this module in a child process configured by `configure`.
+fn run_in_child(name: &str, configure: impl FnOnce(&mut Command)) {
+ let module = module_path!().split_once("::").unwrap().1;
+ let mut command = Command::new(std::env::current_exe().unwrap());
+ command.args([
+ &format!("{module}::{name}"),
+ "--exact",
+ "--ignored",
+ "--nocapture",
+ ]);
+ configure(&mut command);
+ let output = command.output().unwrap();
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ output.status.success() && stdout.contains("1 passed"),
+ "{stdout}\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+}
+
+fn access(port: u16, allow_server_credentials: bool) -> RemoteStorageAccess {
+ RemoteStorageAccess::new(&[format!("127.0.0.1:{port}")], allow_server_credentials).unwrap()
+}
+
+fn options(pairs: &[(&str, &str)]) -> HashMap {
+ pairs
+ .iter()
+ .map(|(k, v)| (k.to_string(), v.to_string()))
+ .collect()
+}
+
+async fn build(
+ url: &str,
+ connection: &HashMap,
+ access: &RemoteStorageAccess,
+) -> Result {
+ build_backend(url, connection, &LocalFileAccess::Disabled, access).await
+}
+
+#[test]
+fn test_s3_identity_selection() {
+ run_in_child("s3_identity_selection_in_child", |command| {
+ command
+ .env("AWS_ACCESS_KEY_ID", "server-ak")
+ .env("AWS_SECRET_ACCESS_KEY", "server-sk")
+ .env_remove("AWS_SESSION_TOKEN")
+ .env("AWS_EC2_METADATA_DISABLED", "true");
+ });
+}
+
+#[tokio::test]
+#[ignore = "run by test_s3_identity_selection with planted credentials"]
+async fn s3_identity_selection_in_child() {
+ let server = MockHttpServer::start(|head| {
+ if head.contains("Credential=bad-ak/") {
+ http_response("403 Forbidden", &[], "")
+ } else {
+ http_response("200 OK", &[], "data")
+ }
+ })
+ .await;
+ let endpoint = format!("http://127.0.0.1:{}", server.port);
+ let base = [("endpoint", endpoint.as_str()), ("region", "us-east-1")];
+ let with = |extra: &[(&str, &str)]| options(&[&base[..], extra].concat());
+ let strict = access(server.port, false);
+ let permissive = access(server.port, true);
+ let url = "s3://bucket/dir/";
+
+ // The planted server credentials work when the policy allows them.
+ let store = build(url, &with(&[]), &permissive).await.unwrap();
+ store.read("key").await.unwrap();
+ assert!(server.request_heads()[0].contains("Credential=server-ak/"));
+
+ let explicit = with(&[("access_key_id", "sql-ak"), ("secret_access_key", "sql-sk")]);
+ for access in [&strict, &permissive] {
+ let store = build(url, &explicit, access).await.unwrap();
+ store.read("key").await.unwrap();
+ let heads = server.request_heads();
+ assert!(heads.last().unwrap().contains("Credential=sql-ak/"));
+ }
+
+ // Wrong explicit credentials fail without trying the server's.
+ let bad = with(&[("access_key_id", "bad-ak"), ("secret_access_key", "sk")]);
+ let store = build(url, &bad, &permissive).await.unwrap();
+ store.read("key").await.unwrap_err();
+
+ let requests = server.request_count();
+ assert!(
+ server
+ .request_heads()
+ .iter()
+ .skip(1)
+ .all(|head| !head.contains("server-ak"))
+ );
+
+ // Incomplete credentials and missing credentials in strict mode are
+ // rejected before any request.
+ for (connection, access) in [
+ (with(&[("access_key_id", "sql-ak")]), &permissive),
+ (with(&[("session_token", "token")]), &permissive),
+ ] {
+ assert!(matches!(
+ build(url, &connection, access).await,
+ Err(Error::InvalidConnection { .. })
+ ));
+ }
+ assert!(matches!(
+ build(url, &with(&[]), &strict).await,
+ Err(Error::ServerCredentialsDisallowed { .. })
+ ));
+ assert_eq!(server.request_count(), requests);
+}
+
+#[test]
+fn test_gcs_identity_selection() {
+ let dir = common_test_util::temp_dir::create_temp_dir("gcs_identity");
+ run_in_child("gcs_identity_selection_in_child", |command| {
+ command.env(
+ "GOOGLE_APPLICATION_CREDENTIALS",
+ dir.path().join("credential.json"),
+ );
+ });
+}
+
+#[tokio::test]
+#[ignore = "run by test_gcs_identity_selection with planted credentials"]
+async fn gcs_identity_selection_in_child() {
+ let server = MockHttpServer::start(|head| {
+ if head.starts_with("POST /token") {
+ http_response(
+ "200 OK",
+ &[("content-type", "application/json".to_string())],
+ r#"{"access_token":"server-token","expires_in":3600,"token_type":"Bearer","issued_token_type":"urn:ietf:params:oauth:token-type:access_token"}"#,
+ )
+ } else {
+ http_response("200 OK", &[], "data")
+ }
+ })
+ .await;
+ // Server credentials: an external account whose token exchange is served
+ // by the mock, so every use of them is visible.
+ let credential_file =
+ std::path::PathBuf::from(std::env::var_os("GOOGLE_APPLICATION_CREDENTIALS").unwrap());
+ let subject = credential_file.with_file_name("subject");
+ std::fs::write(&subject, "subject-token").unwrap();
+ let server_credential = serde_json::json!({
+ "type": "external_account",
+ "audience": "audience",
+ "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
+ "token_url": format!("http://127.0.0.1:{}/token", server.port),
+ "credential_source": {
+ "file": subject.display().to_string(),
+ "format": { "type": "text" },
+ },
+ });
+ std::fs::write(&credential_file, server_credential.to_string()).unwrap();
+
+ let endpoint = format!("http://127.0.0.1:{}", server.port);
+ let strict = access(server.port, false);
+ let permissive = access(server.port, true);
+ let url = "gcs://bucket/dir/";
+ let with =
+ |extra: &[(&str, &str)]| options(&[&[("endpoint", endpoint.as_str())][..], extra].concat());
+
+ let store = build(url, &with(&[]), &permissive).await.unwrap();
+ store.read("key").await.unwrap();
+ let heads = server.request_heads();
+ assert!(heads[0].starts_with("POST /token"));
+ assert!(heads[1].contains("Bearer server-token"));
+
+ // A service account key that cannot be used fails without trying the
+ // server's credentials.
+ let service_account = BASE64_STANDARD.encode(
+ r#"{"type":"service_account","private_key":"invalid","client_email":"a@b.iam.gserviceaccount.com"}"#,
+ );
+ for access in [&strict, &permissive] {
+ let store = build(url, &with(&[("credential", &service_account)]), access)
+ .await
+ .unwrap();
+ store.read("key").await.unwrap_err();
+ }
+
+ // Credential types other than service accounts are rejected even when they
+ // only point to allowed hosts.
+ let external_account = BASE64_STANDARD.encode(server_credential.to_string());
+ assert!(matches!(
+ build(
+ url,
+ &with(&[("credential", &external_account)]),
+ &permissive
+ )
+ .await,
+ Err(Error::InvalidConnection { .. })
+ ));
+ assert!(matches!(
+ build(url, &with(&[]), &strict).await,
+ Err(Error::ServerCredentialsDisallowed { .. })
+ ));
+
+ // Credential requests go through the same host check as data requests.
+ let other_host = access(server.port.wrapping_add(1), true);
+ let store = build(url, &with(&[]), &other_host).await.unwrap();
+ store.read("key").await.unwrap_err();
+ assert_eq!(server.request_count(), 2);
+}
+
+#[tokio::test]
+async fn test_azblob_and_oss_credential_selection() {
+ let strict = access(1, false);
+
+ // The account key is only used with a known account name.
+ let key_without_name = options(&[("endpoint", "http://127.0.0.1:1"), ("account_key", "a2V5")]);
+ assert!(matches!(
+ build("azblob://container/dir/", &key_without_name, &strict).await,
+ Err(Error::InvalidConnection { .. })
+ ));
+ for connection in [
+ options(&[
+ ("endpoint", "http://127.0.0.1:1"),
+ ("account_name", "account"),
+ ("account_key", "a2V5"),
+ ]),
+ options(&[
+ ("endpoint", "https://account.blob.core.windows.net"),
+ ("account_key", "a2V5"),
+ ]),
+ options(&[("endpoint", "http://127.0.0.1:1"), ("sas_token", "sig")]),
+ ] {
+ build("azblob://container/dir/", &connection, &strict)
+ .await
+ .unwrap();
+ }
+ assert!(matches!(
+ build(
+ "azblob://container/dir/",
+ &options(&[
+ ("endpoint", "http://127.0.0.1:1"),
+ ("account_name", "account")
+ ]),
+ &strict
+ )
+ .await,
+ Err(Error::ServerCredentialsDisallowed { .. })
+ ));
+
+ // Anonymous OSS access needs no credentials.
+ let endpoint = ("endpoint", "http://127.0.0.1:1");
+ build(
+ "oss://bucket/dir/",
+ &options(&[endpoint, ("allow_anonymous", "true")]),
+ &strict,
+ )
+ .await
+ .unwrap();
+ assert!(matches!(
+ build("oss://bucket/dir/", &options(&[endpoint]), &strict).await,
+ Err(Error::ServerCredentialsDisallowed { .. })
+ ));
+ assert!(matches!(
+ build(
+ "oss://bucket/dir/",
+ &options(&[endpoint, ("access_key_id", "ak")]),
+ &strict
+ )
+ .await,
+ Err(Error::InvalidConnection { .. })
+ ));
+}
+
+#[tokio::test]
+async fn test_allowed_hosts_apply_to_every_backend() {
+ let denied = MockHttpServer::start(|_| http_response("200 OK", &[], "data")).await;
+ let endpoint = format!("http://127.0.0.1:{}", denied.port);
+ let access = access(denied.port.wrapping_add(1), true);
+ for (url, connection) in [
+ (
+ "s3://bucket/dir/",
+ options(&[
+ ("endpoint", &endpoint),
+ ("region", "us-east-1"),
+ ("access_key_id", "ak"),
+ ("secret_access_key", "sk"),
+ ]),
+ ),
+ (
+ "oss://bucket/dir/",
+ options(&[("endpoint", &endpoint), ("allow_anonymous", "true")]),
+ ),
+ (
+ "azblob://container/dir/",
+ options(&[("endpoint", &endpoint), ("sas_token", "sig")]),
+ ),
+ ] {
+ let store = build(url, &connection, &access).await.unwrap();
+ let err = store.read("key").await.unwrap_err();
+ assert_eq!(
+ err.kind(),
+ object_store::ErrorKind::PermissionDenied,
+ "{url}: {err}"
+ );
+ }
+ assert_eq!(denied.request_count(), 0);
+}
diff --git a/src/common/datasource/src/object_store/s3.rs b/src/common/datasource/src/object_store/s3.rs
index 0dce07c938c..c1b8b2d8838 100644
--- a/src/common/datasource/src/object_store/s3.rs
+++ b/src/common/datasource/src/object_store/s3.rs
@@ -15,11 +15,13 @@
use std::collections::HashMap;
use object_store::ObjectStore;
+use object_store::remote_access::RemoteStorageAccess;
use object_store::services::S3;
-use object_store::util::{with_instrument_layers, with_retry_layers};
-use snafu::ResultExt;
use crate::error::{self, Result};
+use crate::object_store::{
+ connection_value, ensure_server_credentials_allowed, finish_remote_backend,
+};
const ENDPOINT: &str = "endpoint";
const ACCESS_KEY_ID: &str = "access_key_id";
@@ -46,6 +48,7 @@ pub fn build_s3_backend(
host: &str,
path: &str,
connection: &HashMap,
+ remote_storage_access: &RemoteStorageAccess,
) -> Result {
let mut builder = S3::default().root(path).bucket(host);
@@ -57,16 +60,28 @@ pub fn build_s3_backend(
builder = builder.region(region);
}
- if let Some(key_id) = connection.get(ACCESS_KEY_ID) {
- builder = builder.access_key_id(key_id);
- }
-
- if let Some(key) = connection.get(SECRET_ACCESS_KEY) {
- builder = builder.secret_access_key(key);
- }
-
- if let Some(session_token) = connection.get(SESSION_TOKEN) {
- builder = builder.session_token(session_token);
+ let session_token = connection_value(connection, SESSION_TOKEN);
+ match (
+ connection_value(connection, ACCESS_KEY_ID),
+ connection_value(connection, SECRET_ACCESS_KEY),
+ ) {
+ (Some(key_id), Some(key)) => {
+ builder = builder.access_key_id(key_id).secret_access_key(key);
+ if let Some(session_token) = session_token {
+ builder = builder.session_token(session_token);
+ }
+ }
+ (None, None) if session_token.is_none() => {
+ ensure_server_credentials_allowed(remote_storage_access, "S3")?;
+ }
+ _ => {
+ return error::InvalidConnectionSnafu {
+ msg: format!(
+ "{ACCESS_KEY_ID} and {SECRET_ACCESS_KEY} must be set together, and {SESSION_TOKEN} requires both"
+ ),
+ }
+ .fail();
+ }
}
if let Some(enable_str) = connection.get(ENABLE_VIRTUAL_HOST_STYLE) {
@@ -99,11 +114,7 @@ pub fn build_s3_backend(
}
}
- let object_store = ObjectStore::new(builder).context(error::BuildBackendSnafu)?;
- Ok(with_instrument_layers(
- with_retry_layers(object_store),
- true,
- ))
+ finish_remote_backend(builder, remote_storage_access)
}
#[cfg(test)]
diff --git a/src/common/datasource/src/parquet_writer.rs b/src/common/datasource/src/parquet_writer.rs
index a95cbbeb79e..2be0e9b7443 100644
--- a/src/common/datasource/src/parquet_writer.rs
+++ b/src/common/datasource/src/parquet_writer.rs
@@ -666,6 +666,7 @@ mod tests {
&format!("{}/", directory.path().display()),
&Default::default(),
&access,
+ &crate::object_store::RemoteStorageAccess::unrestricted(),
)
.await
.unwrap();
diff --git a/src/datanode/src/config.rs b/src/datanode/src/config.rs
index cc7ebf8a0ce..dda45573fee 100644
--- a/src/datanode/src/config.rs
+++ b/src/datanode/src/config.rs
@@ -180,6 +180,7 @@ impl Configurable for DatanodeOptions {
"heartbeat_env_vars",
"meta_client.metasrv_addrs",
"wal.broker_endpoints",
+ "query.remote_allowed_hosts",
])
}
diff --git a/src/datanode/src/datanode.rs b/src/datanode/src/datanode.rs
index ca14f6cd823..b84faa24cda 100644
--- a/src/datanode/src/datanode.rs
+++ b/src/datanode/src/datanode.rs
@@ -24,7 +24,7 @@ use catalog::kvbackend::KvBackendCatalogManagerBuilder;
use client::client_manager::NodeClients;
use common_base::Plugins;
use common_catalog::consts::{FILE_ENGINE, METRIC_ENGINE, MITO_ENGINE};
-use common_datasource::object_store::LocalFileAccess;
+use common_datasource::object_store::{LocalFileAccess, RemoteStorageAccess};
use common_error::ext::BoxedError;
use common_greptimedb_telemetry::GreptimeDBTelemetryTask;
use common_grpc::channel_manager::ChannelConfig;
@@ -767,6 +767,11 @@ impl DatanodeBuilder {
file_engine_config,
object_store_manager.default_object_store().clone(), // TODO: implement custom storage for file engine
self.local_file_access.clone(),
+ RemoteStorageAccess::new(
+ &self.opts.query.remote_allowed_hosts,
+ self.opts.query.allow_server_credentials,
+ )
+ .context(error::ObjectStoreSnafu)?,
);
let relational_engine =
diff --git a/src/file-engine/src/engine.rs b/src/file-engine/src/engine.rs
index a49b79fa65e..9cb42950eb1 100644
--- a/src/file-engine/src/engine.rs
+++ b/src/file-engine/src/engine.rs
@@ -20,7 +20,7 @@ use std::time::Instant;
use api::region::RegionResponse;
use async_trait::async_trait;
use common_catalog::consts::FILE_ENGINE;
-use common_datasource::object_store::LocalFileAccess;
+use common_datasource::object_store::{LocalFileAccess, RemoteStorageAccess};
use common_error::ext::BoxedError;
use common_recordbatch::SendableRecordBatchStream;
use common_telemetry::{error, info};
@@ -54,9 +54,14 @@ impl FileRegionEngine {
_config: EngineConfig,
object_store: ObjectStore,
local_file_access: LocalFileAccess,
+ remote_storage_access: RemoteStorageAccess,
) -> Self {
Self {
- inner: Arc::new(EngineInner::new(object_store, local_file_access)),
+ inner: Arc::new(EngineInner::new(
+ object_store,
+ local_file_access,
+ remote_storage_access,
+ )),
}
}
@@ -70,7 +75,11 @@ impl FileRegionEngine {
.await
.context(RegionNotFoundSnafu { region_id })
.map_err(BoxedError::new)?
- .query(request, &self.inner.local_file_access)
+ .query(
+ request,
+ &self.inner.local_file_access,
+ &self.inner.remote_storage_access,
+ )
.await
.map_err(BoxedError::new)
}
@@ -203,6 +212,8 @@ struct EngineInner {
object_store: ObjectStore,
local_file_access: LocalFileAccess,
+
+ remote_storage_access: RemoteStorageAccess,
}
type EngineInnerRef = Arc;
@@ -226,12 +237,17 @@ fn ensure_region_requirements(
}
impl EngineInner {
- fn new(object_store: ObjectStore, local_file_access: LocalFileAccess) -> Self {
+ fn new(
+ object_store: ObjectStore,
+ local_file_access: LocalFileAccess,
+ remote_storage_access: RemoteStorageAccess,
+ ) -> Self {
Self {
regions: RwLock::new(HashMap::new()),
region_mutex: Mutex::new(()),
object_store,
local_file_access,
+ remote_storage_access,
}
}
diff --git a/src/file-engine/src/query.rs b/src/file-engine/src/query.rs
index 0923bf2cfd9..c2138439123 100644
--- a/src/file-engine/src/query.rs
+++ b/src/file-engine/src/query.rs
@@ -19,7 +19,7 @@ use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
-use common_datasource::object_store::{LocalFileAccess, build_backend};
+use common_datasource::object_store::{LocalFileAccess, RemoteStorageAccess, build_backend};
use common_recordbatch::adapter::RecordBatchMetrics;
use common_recordbatch::error::{self as recordbatch_error, Result as RecordBatchResult};
use common_recordbatch::{
@@ -45,10 +45,16 @@ impl FileRegion {
&self,
request: ScanRequest,
local_file_access: &LocalFileAccess,
+ remote_storage_access: &RemoteStorageAccess,
) -> Result {
- let store = build_backend(&self.url, &self.options, local_file_access)
- .await
- .context(BuildBackendSnafu)?;
+ let store = build_backend(
+ &self.url,
+ &self.options,
+ local_file_access,
+ remote_storage_access,
+ )
+ .await
+ .context(BuildBackendSnafu)?;
let projection = request.projection.as_deref();
let file_projection = self.projection_pushdown_to_file(projection)?;
diff --git a/src/file-engine/src/region.rs b/src/file-engine/src/region.rs
index 6f7e4bb668c..9d067f58e92 100644
--- a/src/file-engine/src/region.rs
+++ b/src/file-engine/src/region.rs
@@ -107,7 +107,7 @@ impl FileRegion {
mod tests {
use std::assert_matches;
- use common_datasource::object_store::LocalFileAccess;
+ use common_datasource::object_store::{LocalFileAccess, RemoteStorageAccess};
use common_error::ext::{ErrorExt, RetryHint};
use common_error::status_code::StatusCode;
use store_api::region_request::PathType;
@@ -177,7 +177,11 @@ mod tests {
.unwrap();
let error = match region
- .query(ScanRequest::default(), &LocalFileAccess::Disabled)
+ .query(
+ ScanRequest::default(),
+ &LocalFileAccess::Disabled,
+ &RemoteStorageAccess::unrestricted(),
+ )
.await
{
Ok(_) => panic!("local file query must be rejected"),
diff --git a/src/frontend/src/frontend.rs b/src/frontend/src/frontend.rs
index dc669313a55..af8b63c7b0d 100644
--- a/src/frontend/src/frontend.rs
+++ b/src/frontend/src/frontend.rs
@@ -178,6 +178,7 @@ impl Configurable for FrontendOptions {
"heartbeat_env_vars",
"meta_client.metasrv_addrs",
"event_recorder.event_types",
+ "query.remote_allowed_hosts",
"pending_rows_batcher.protocols",
"pending_rows_batcher.logical_table.protocols",
])
diff --git a/src/frontend/src/instance/builder.rs b/src/frontend/src/instance/builder.rs
index 3703c5bedea..871e9799b7d 100644
--- a/src/frontend/src/instance/builder.rs
+++ b/src/frontend/src/instance/builder.rs
@@ -23,7 +23,8 @@ use catalog::process_manager::ProcessManagerRef;
use catalog::system_schema::semantic_graph::EntityGraphProviderRef;
use common_base::Plugins;
use common_batcher::request_limiter::RequestLimiter;
-use common_datasource::object_store::LocalFileAccess;
+use common_datasource::object_store::{LocalFileAccess, RemoteStorageAccess};
+use common_error::ext::BoxedError;
use common_event_recorder::{EventRecorderImpl, EventRecorderRef};
use common_meta::cache::{LayeredCacheRegistryRef, TableFlownodeSetCacheRef, TableRouteCacheRef};
use common_meta::cache_invalidator::CacheInvalidatorRef;
@@ -365,6 +366,12 @@ impl FrontendBuilder {
Some(process_manager.clone()),
frontend_peer_addr.clone(),
self.local_file_access,
+ RemoteStorageAccess::new(
+ &self.options.query.remote_allowed_hosts,
+ self.options.query.allow_server_credentials,
+ )
+ .map_err(BoxedError::new)
+ .context(ExternalSnafu)?,
);
let statement_executor =
diff --git a/src/object-store/Cargo.toml b/src/object-store/Cargo.toml
index 96785fbf243..aa227c93359 100644
--- a/src/object-store/Cargo.toml
+++ b/src/object-store/Cargo.toml
@@ -23,6 +23,7 @@ common-runtime.workspace = true
common-telemetry.workspace = true
derive_builder = { workspace = true, optional = true }
hdfs-native = { workspace = true, optional = true }
+http.workspace = true
humantime-serde.workspace = true
opendal = { version = "0.59.4", features = [
"layers-tracing",
@@ -40,6 +41,7 @@ reqwest.workspace = true
serde.workspace = true
snafu.workspace = true
tokio.workspace = true
+url.workspace = true
uuid = { workspace = true, optional = true }
[dev-dependencies]
diff --git a/src/object-store/src/error.rs b/src/object-store/src/error.rs
index 14661e261cd..582c722dad7 100644
--- a/src/object-store/src/error.rs
+++ b/src/object-store/src/error.rs
@@ -39,6 +39,14 @@ pub enum Error {
error: reqwest::Error,
},
+ #[snafu(display("Invalid entry `{}` in query.remote_allowed_hosts: {}", entry, reason))]
+ InvalidAllowedHost {
+ entry: String,
+ reason: String,
+ #[snafu(implicit)]
+ location: Location,
+ },
+
#[snafu(display("Failed to create directory {}", dir))]
CreateDir {
dir: String,
@@ -71,6 +79,7 @@ impl ErrorExt for Error {
match self {
InitBackend { .. } => StatusCode::StorageUnavailable,
BuildHttpClient { .. } => StatusCode::Unexpected,
+ InvalidAllowedHost { .. } => StatusCode::InvalidArguments,
CreateDir { .. } | RemoveDir { .. } => StatusCode::Internal,
}
}
diff --git a/src/object-store/src/lib.rs b/src/object-store/src/lib.rs
index 67588538054..bd9f6f3e0f9 100644
--- a/src/object-store/src/lib.rs
+++ b/src/object-store/src/lib.rs
@@ -24,6 +24,7 @@ pub mod error;
pub mod factory;
pub mod layers;
pub mod manager;
+pub mod remote_access;
pub mod secure_fs;
#[cfg(feature = "hdfs-object-store")]
pub mod temp_file;
diff --git a/src/object-store/src/remote_access.rs b/src/object-store/src/remote_access.rs
new file mode 100644
index 00000000000..904d5c69c59
--- /dev/null
+++ b/src/object-store/src/remote_access.rs
@@ -0,0 +1,439 @@
+// 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.
+
+//! Access policy for object storage locations supplied by SQL statements.
+
+use std::sync::Arc;
+
+use common_telemetry::warn;
+use http::{Request, Response};
+use opendal::{
+ Buffer, Error, ErrorKind, HttpBody, HttpRedirect, HttpTransport, HttpTransporter,
+ OperationContext,
+};
+use opendal_http_transport_reqwest::ReqwestTransport;
+use snafu::ResultExt;
+use url::Url;
+
+use crate::ObjectStore;
+use crate::error::{self, Result};
+
+/// How object stores built from SQL statements, such as `COPY`, `COPY DATABASE`,
+/// `EXPORT/IMPORT DATABASE` and external tables, may reach storage.
+#[derive(Clone, Debug)]
+pub struct RemoteStorageAccess {
+ /// Operation context with the restricted HTTP transport, if allowed hosts are set.
+ restricted_context: Option,
+ allow_server_credentials: bool,
+}
+
+impl RemoteStorageAccess {
+ /// No host restriction, and server credentials are allowed.
+ pub fn unrestricted() -> Self {
+ Self {
+ restricted_context: None,
+ allow_server_credentials: true,
+ }
+ }
+
+ /// Creates the access policy. An empty `allowed_hosts` means no host restriction.
+ pub fn new(allowed_hosts: &[String], allow_server_credentials: bool) -> Result {
+ let restricted_context = if allowed_hosts.is_empty() {
+ None
+ } else {
+ let allowlist = HostAllowlist::parse(allowed_hosts)?;
+ // Redirects are not followed, otherwise the client could reach a host
+ // that was never checked. Other settings match the default transport
+ // used for SQL object stores without a restriction.
+ let client = reqwest::Client::builder()
+ .redirect(reqwest::redirect::Policy::none())
+ .build()
+ .context(error::BuildHttpClientSnafu)?;
+ let transport = AllowlistTransport {
+ inner: ReqwestTransport::new(client),
+ allowlist: Arc::new(allowlist),
+ };
+ Some(OperationContext::new().with_http_transport(HttpTransporter::new(transport)))
+ };
+ Ok(Self {
+ restricted_context,
+ allow_server_credentials,
+ })
+ }
+
+ /// Makes `store` send its requests through the restricted transport, if any.
+ pub fn apply(&self, store: ObjectStore) -> ObjectStore {
+ match &self.restricted_context {
+ Some(context) => store.with_context(context.clone()),
+ None => store,
+ }
+ }
+
+ /// Whether a store whose connection options carry no credentials may fall back to the
+ /// server's own credentials.
+ pub fn allow_server_credentials(&self) -> bool {
+ self.allow_server_credentials
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum HostPattern {
+ Exact(String),
+ /// Matches any subdomain of the domain, not the domain itself.
+ Subdomain(String),
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+struct AllowedHost {
+ host: HostPattern,
+ /// `None` matches any port.
+ port: Option,
+}
+
+/// Hosts that SQL object stores may connect to.
+///
+/// Entries are `host`, `host:port`, `*.domain` or `*.domain:port`. IPv6 addresses
+/// are written in brackets, e.g. `[::1]:9000`. Hosts are normalized the same way
+/// as request URLs, so `127.1` and `127.0.0.1` are the same host.
+#[derive(Debug, Clone)]
+pub(crate) struct HostAllowlist {
+ entries: Vec,
+}
+
+impl HostAllowlist {
+ pub(crate) fn parse(entries: &[String]) -> Result {
+ let entries = entries
+ .iter()
+ .map(|entry| {
+ parse_allowed_host(entry).map_err(|reason| {
+ error::InvalidAllowedHostSnafu {
+ entry: entry.clone(),
+ reason,
+ }
+ .build()
+ })
+ })
+ .collect::>>()?;
+ Ok(Self { entries })
+ }
+
+ /// Checks the URL a request is sent to.
+ fn check(&self, target: &str) -> opendal::Result<()> {
+ let url = Url::parse(target).map_err(|err| {
+ Error::new(ErrorKind::PermissionDenied, "request URL is invalid").set_source(err)
+ })?;
+ let (Some(host), Some(port)) = (url.host_str(), url.port_or_known_default()) else {
+ return Err(Error::new(
+ ErrorKind::PermissionDenied,
+ "request URL has no host or port",
+ ));
+ };
+ let is_domain = matches!(url.host(), Some(url::Host::Domain(_)));
+ let allowed = self.entries.iter().any(|entry| {
+ let host_matches = match &entry.host {
+ HostPattern::Exact(expected) => host == expected,
+ HostPattern::Subdomain(domain) => {
+ is_domain
+ && host
+ .strip_suffix(domain.as_str())
+ .is_some_and(|prefix| prefix.len() > 1 && prefix.ends_with('.'))
+ }
+ };
+ host_matches && entry.port.is_none_or(|expected| expected == port)
+ });
+ if allowed {
+ Ok(())
+ } else {
+ // Credential providers swallow this error and try the next one, so
+ // the log is the only trace of a blocked credential request.
+ warn!("Blocked request to {host}:{port}, not in query.remote_allowed_hosts");
+ Err(Error::new(
+ ErrorKind::PermissionDenied,
+ "host is not in query.remote_allowed_hosts",
+ )
+ .with_context("host", format!("{host}:{port}")))
+ }
+ }
+}
+
+fn parse_allowed_host(entry: &str) -> std::result::Result {
+ let entry = entry.trim();
+ let (wildcard, rest) = match entry.strip_prefix("*.") {
+ Some(rest) => (true, rest),
+ None => (false, entry),
+ };
+ if rest.is_empty() || rest.contains(['/', '\\', '@', '*', '?', '#']) {
+ return Err("expected `host`, `host:port` or `*.domain`".to_string());
+ }
+
+ let (host, port) = if rest.starts_with('[') {
+ let end = rest
+ .find(']')
+ .ok_or_else(|| "unterminated IPv6 address".to_string())?;
+ let port = &rest[end + 1..];
+ let port = if port.is_empty() {
+ None
+ } else {
+ Some(
+ port.strip_prefix(':')
+ .ok_or_else(|| "unexpected characters after IPv6 address".to_string())?,
+ )
+ };
+ (&rest[..=end], port)
+ } else {
+ match rest.split_once(':') {
+ Some((host, port)) => (host, Some(port)),
+ None => (rest, None),
+ }
+ };
+ let port = port
+ .map(|port| {
+ port.parse::()
+ .map_err(|_| format!("invalid port `{port}`"))
+ })
+ .transpose()?;
+
+ let url = Url::parse(&format!("http://{host}/")).map_err(|err| err.to_string())?;
+ let normalized = url
+ .host_str()
+ .ok_or_else(|| "missing host".to_string())?
+ .to_string();
+ let host = if wildcard {
+ if !matches!(url.host(), Some(url::Host::Domain(_))) {
+ return Err("wildcard entries must use a domain name".to_string());
+ }
+ HostPattern::Subdomain(normalized)
+ } else {
+ HostPattern::Exact(normalized)
+ };
+ Ok(AllowedHost { host, port })
+}
+
+struct AllowlistTransport {
+ inner: ReqwestTransport,
+ allowlist: Arc,
+}
+
+impl HttpTransport for AllowlistTransport {
+ async fn fetch(&self, req: Request) -> opendal::Result> {
+ self.allowlist.check(&req.uri().to_string())?;
+ // The reqwest transport sends the request to this URL instead of the
+ // request URI when a service attaches the extension.
+ if let Some(redirect) = req.extensions().get::() {
+ self.allowlist.check(redirect.uri().original_uri())?;
+ }
+ self.inner.fetch(req).await
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use opendal::services::{Gcs, S3};
+
+ use super::*;
+ use crate::ObjectStore;
+ use crate::test_util::{MockHttpServer, http_response as response};
+
+ fn allowlist(entries: &[&str]) -> HostAllowlist {
+ HostAllowlist::parse(&entries.iter().map(|s| s.to_string()).collect::>()).unwrap()
+ }
+
+ #[test]
+ fn test_allowlist_matching() {
+ let list = allowlist(&[
+ "S3.US-EAST-1.amazonaws.com",
+ "*.storage.example.com",
+ "minio.internal:9000",
+ "127.1:9000",
+ "[::1]:9001",
+ ]);
+ for allowed in [
+ "https://s3.us-east-1.amazonaws.com/bucket/key",
+ "http://s3.us-east-1.amazonaws.com:8080/",
+ "https://bucket.storage.example.com/key",
+ "https://a.b.storage.example.com/key",
+ "http://minio.internal:9000/bucket",
+ "http://127.0.0.1:9000/bucket",
+ "http://2130706433:9000/bucket",
+ "http://[::1]:9001/bucket",
+ ] {
+ assert!(list.check(allowed).is_ok(), "{allowed}");
+ }
+ for denied in [
+ "https://storage.example.com/key",
+ "https://evilstorage.example.com/key",
+ "https://storage.example.com.evil.com/key",
+ "http://minio.internal/bucket",
+ "http://minio.internal:9001/bucket",
+ "http://127.0.0.1:9001/bucket",
+ "http://169.254.169.254/latest/meta-data/",
+ "http://[::1]:9000/bucket",
+ ] {
+ let err = list.check(denied).unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::PermissionDenied, "{denied}");
+ }
+ }
+
+ #[test]
+ fn test_allowlist_rejects_invalid_entries() {
+ for entry in [
+ "",
+ "http://example.com",
+ "example.com/path",
+ "user@example.com",
+ "*.127.0.0.1",
+ "*.[::1]",
+ "example.com:port",
+ "example.com:70000",
+ "[::1",
+ "[::1]9000",
+ "minio.internal\\evil.com",
+ "a*.example.com",
+ ] {
+ assert!(
+ HostAllowlist::parse(&[entry.to_string()]).is_err(),
+ "{entry}"
+ );
+ }
+ }
+
+ fn restricted(entries: &[String]) -> OperationContext {
+ RemoteStorageAccess::new(entries, true)
+ .unwrap()
+ .restricted_context
+ .unwrap()
+ }
+
+ fn s3_store(endpoint: Option<&str>, region: &str, ctx: OperationContext) -> ObjectStore {
+ let mut builder = S3::default()
+ .bucket("bucket")
+ .region(region)
+ .access_key_id("ak")
+ .secret_access_key("sk");
+ if let Some(endpoint) = endpoint {
+ builder = builder.endpoint(endpoint);
+ }
+ ObjectStore::new(builder).unwrap().with_context(ctx)
+ }
+
+ #[tokio::test]
+ async fn test_restricted_transport_targets() {
+ let allowed = MockHttpServer::start(|head| {
+ if head.starts_with("GET") {
+ response("200 OK", &[], "data")
+ } else {
+ response("200 OK", &[("etag", "\"e\"".to_string())], "")
+ }
+ })
+ .await;
+ let denied = MockHttpServer::start(|_| response("200 OK", &[], "secret")).await;
+ let (allowed_port, denied_port) = (allowed.port, denied.port);
+ let ctx = restricted(&[format!("127.0.0.1:{allowed_port}")]);
+
+ // An allowed target can be written and read.
+ let store = s3_store(
+ Some(&format!("http://127.0.0.1:{allowed_port}")),
+ "us-east-1",
+ ctx.clone(),
+ );
+ store.write("key", "data").await.unwrap();
+ assert_eq!(store.read("key").await.unwrap().to_vec(), b"data");
+ assert_eq!(allowed.request_count(), 2);
+
+ // Endpoint pointing to another port.
+ let store = s3_store(
+ Some(&format!("http://127.0.0.1:{denied_port}")),
+ "us-east-1",
+ ctx.clone(),
+ );
+ let err = store.read("key").await.unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::PermissionDenied);
+
+ // Without an endpoint, the region is substituted into the default endpoint
+ // template, which can change the host.
+ let store = s3_store(None, &format!("x@127.0.0.1:{denied_port}/#"), ctx.clone());
+ let err = store.read("key").await.unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::PermissionDenied);
+ assert_eq!(denied.request_count(), 0);
+ }
+
+ #[tokio::test]
+ async fn test_restricted_transport_checks_redirect_extension() {
+ let denied = MockHttpServer::start(|_| response("200 OK", &[], "secret")).await;
+ let allowed = MockHttpServer::start(|_| response("200 OK", &[], "data")).await;
+ let ctx = restricted(&[format!("127.0.0.1:{}", allowed.port)]);
+ let mut req = Request::get(format!("http://127.0.0.1:{}/key", allowed.port))
+ .body(Buffer::new())
+ .unwrap();
+ req.extensions_mut().insert(HttpRedirect::new(
+ format!("http://127.0.0.1:{}/key", denied.port)
+ .parse()
+ .unwrap(),
+ ));
+ let Err(err) = ctx.http_transport().fetch(req).await else {
+ panic!("the redirect target must be checked");
+ };
+ assert_eq!(err.kind(), ErrorKind::PermissionDenied);
+ assert_eq!(allowed.request_count() + denied.request_count(), 0);
+ }
+
+ #[tokio::test]
+ async fn test_restricted_transport_does_not_follow_redirects() {
+ let denied = MockHttpServer::start(|_| response("200 OK", &[], "secret")).await;
+ let location = format!("http://127.0.0.1:{}/bucket/key", denied.port);
+ let allowed = MockHttpServer::start(move |_| {
+ response("302 Found", &[("location", location.clone())], "")
+ })
+ .await;
+ let allowed_port = allowed.port;
+ let ctx = restricted(&[format!("127.0.0.1:{allowed_port}")]);
+ let store = s3_store(
+ Some(&format!("http://127.0.0.1:{allowed_port}")),
+ "us-east-1",
+ ctx,
+ );
+ assert!(store.read("key").await.is_err());
+ assert_eq!(allowed.request_count(), 1);
+ assert_eq!(denied.request_count(), 0);
+ }
+
+ #[tokio::test]
+ async fn test_restricted_transport_checks_gcs_resumable_upload_session() {
+ let denied = MockHttpServer::start(|_| response("200 OK", &[], "{}")).await;
+ let session = format!("http://127.0.0.1:{}/upload/session", denied.port);
+ let allowed = MockHttpServer::start(move |_| {
+ response("200 OK", &[("location", session.clone())], "")
+ })
+ .await;
+ let allowed_port = allowed.port;
+ let ctx = restricted(&[format!("127.0.0.1:{allowed_port}")]);
+ let builder = Gcs::default()
+ .bucket("bucket")
+ .endpoint(&format!("http://127.0.0.1:{allowed_port}"))
+ .skip_signature();
+ let store = ObjectStore::new(builder).unwrap().with_context(ctx);
+
+ // Conditional writes use resumable uploads, whose later requests go to
+ // the session URL from the `Location` header.
+ let result = store
+ .write_with("key", vec![0u8; 1024])
+ .if_not_exists(true)
+ .await;
+ assert_eq!(result.unwrap_err().kind(), ErrorKind::PermissionDenied);
+ // The upload session was created on the allowed host, but no data was
+ // sent to the session URL it returned.
+ assert_eq!(allowed.request_count(), 1);
+ assert_eq!(denied.request_count(), 0);
+ }
+}
diff --git a/src/object-store/src/test_util.rs b/src/object-store/src/test_util.rs
index 936ecba5bac..5ca82d053e1 100644
--- a/src/object-store/src/test_util.rs
+++ b/src/object-store/src/test_util.rs
@@ -33,3 +33,85 @@ impl TempFolder {
self.store.delete_with(&self.path).recursive(true).await
}
}
+
+/// A minimal HTTP/1.1 server for object storage tests. Every connection serves
+/// one request; the handler builds the raw response from the request head.
+pub struct MockHttpServer {
+ pub port: u16,
+ request_heads: std::sync::Arc>>,
+}
+
+impl MockHttpServer {
+ pub async fn start(handler: impl Fn(&str) -> String + Send + Sync + 'static) -> Self {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let request_heads = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
+ let recorded = request_heads.clone();
+ let handler = std::sync::Arc::new(handler);
+ tokio::spawn(async move {
+ while let Ok((mut stream, _)) = listener.accept().await {
+ let recorded = recorded.clone();
+ let handler = handler.clone();
+ tokio::spawn(async move {
+ let mut buf = Vec::new();
+ let mut chunk = [0u8; 4096];
+ let head_end = loop {
+ let n = stream.read(&mut chunk).await.unwrap_or(0);
+ if n == 0 {
+ return;
+ }
+ buf.extend_from_slice(&chunk[..n]);
+ if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
+ break pos + 4;
+ }
+ };
+ let head = String::from_utf8_lossy(&buf[..head_end]).to_string();
+ let content_length = head
+ .lines()
+ .find_map(|line| {
+ let (name, value) = line.split_once(':')?;
+ name.eq_ignore_ascii_case("content-length")
+ .then(|| value.trim().parse::().ok())?
+ })
+ .unwrap_or(0);
+ while buf.len() < head_end + content_length {
+ let n = stream.read(&mut chunk).await.unwrap_or(0);
+ if n == 0 {
+ break;
+ }
+ buf.extend_from_slice(&chunk[..n]);
+ }
+ recorded.lock().unwrap().push(head.clone());
+ let response = handler(&head);
+ let _ = stream.write_all(response.as_bytes()).await;
+ let _ = stream.shutdown().await;
+ });
+ }
+ });
+ Self {
+ port,
+ request_heads,
+ }
+ }
+
+ /// Request lines and headers of the requests received so far.
+ pub fn request_heads(&self) -> Vec {
+ self.request_heads.lock().unwrap().clone()
+ }
+
+ pub fn request_count(&self) -> usize {
+ self.request_heads.lock().unwrap().len()
+ }
+}
+
+/// Builds a raw HTTP/1.1 response that closes the connection.
+pub fn http_response(status: &str, headers: &[(&str, String)], body: &str) -> String {
+ let mut out = format!("HTTP/1.1 {status}\r\nconnection: close\r\n");
+ for (name, value) in headers {
+ out.push_str(&format!("{name}: {value}\r\n"));
+ }
+ out.push_str(&format!("content-length: {}\r\n\r\n{body}", body.len()));
+ out
+}
diff --git a/src/operator/src/expr_helper.rs b/src/operator/src/expr_helper.rs
index 78ac41d0afe..901f8f9b810 100644
--- a/src/operator/src/expr_helper.rs
+++ b/src/operator/src/expr_helper.rs
@@ -33,7 +33,7 @@ use api::v1::{
set_index, unset_index,
};
use common_catalog::consts::RELATIONAL_ENGINE;
-use common_datasource::object_store::LocalFileAccess;
+use common_datasource::object_store::{LocalFileAccess, RemoteStorageAccess};
use common_error::ext::BoxedError;
use common_grpc_expr::util::ColumnExpr;
use common_query::prelude::greptime_timestamp;
@@ -151,6 +151,7 @@ pub(crate) async fn create_external_expr(
create: CreateExternalTable,
query_ctx: &QueryContextRef,
local_file_access: &LocalFileAccess,
+ remote_storage_access: &RemoteStorageAccess,
) -> Result {
let (catalog_name, schema_name, table_name) =
table_idents_to_full_name(&create.name, query_ctx)
@@ -164,6 +165,7 @@ pub(crate) async fn create_external_expr(
create,
query_ctx,
local_file_access,
+ remote_storage_access,
catalog_name,
schema_name,
table_name,
@@ -334,14 +336,16 @@ async fn create_file_expr(
create: CreateExternalTable,
query_ctx: &QueryContextRef,
local_file_access: &LocalFileAccess,
+ remote_storage_access: &RemoteStorageAccess,
catalog_name: String,
schema_name: String,
table_name: String,
) -> Result {
let mut table_options = create.options.into_map();
- let (object_store, files) = prepare_file_table_files(&table_options, local_file_access)
- .await
- .context(PrepareFileTableSnafu)?;
+ let (object_store, files) =
+ prepare_file_table_files(&table_options, local_file_access, remote_storage_access)
+ .await
+ .context(PrepareFileTableSnafu)?;
let file_column_schemas = infer_file_table_schema(&object_store, &files, &table_options)
.await
diff --git a/src/operator/src/statement.rs b/src/operator/src/statement.rs
index feab3b15cba..97357e1d006 100644
--- a/src/operator/src/statement.rs
+++ b/src/operator/src/statement.rs
@@ -42,7 +42,7 @@ use catalog::process_manager::ProcessManagerRef;
use client::RecordBatches;
use client::error::{ExternalSnafu as ClientExternalSnafu, Result as ClientResult};
use client::inserter::{InsertOptions, Inserter};
-use common_datasource::object_store::LocalFileAccess;
+use common_datasource::object_store::{LocalFileAccess, RemoteStorageAccess};
use common_error::ext::BoxedError;
use common_meta::cache_invalidator::CacheInvalidatorRef;
use common_meta::key::flow::{FlowMetadataManager, FlowMetadataManagerRef};
@@ -150,6 +150,7 @@ pub struct StatementExecutor {
origin_frontend_addr: String,
admin_function_service: AdminFunctionServiceRef,
pub(crate) local_file_access: LocalFileAccess,
+ pub(crate) remote_storage_access: RemoteStorageAccess,
#[cfg(feature = "enterprise")]
create_database_handler: Option,
#[cfg(feature = "enterprise")]
@@ -189,6 +190,7 @@ impl StatementExecutor {
process_manager: Option,
origin_frontend_addr: String,
local_file_access: LocalFileAccess,
+ remote_storage_access: RemoteStorageAccess,
) -> Self {
let admin_function_service = admin::new_admin_function_service(query_engine.clone());
Self {
@@ -205,6 +207,7 @@ impl StatementExecutor {
origin_frontend_addr,
admin_function_service,
local_file_access,
+ remote_storage_access,
#[cfg(feature = "enterprise")]
create_database_handler: None,
#[cfg(feature = "enterprise")]
diff --git a/src/operator/src/statement/copy_database.rs b/src/operator/src/statement/copy_database.rs
index 0b07a314a86..1160b94c642 100644
--- a/src/operator/src/statement/copy_database.rs
+++ b/src/operator/src/statement/copy_database.rs
@@ -19,7 +19,9 @@ use client::{Output, OutputData, OutputMeta};
use common_catalog::format_full_table_name;
use common_datasource::file_format::Format;
use common_datasource::lister::{Lister, Source};
-use common_datasource::object_store::{LocalFileAccess, build_backend, build_backend_for_write};
+use common_datasource::object_store::{
+ LocalFileAccess, RemoteStorageAccess, build_backend, build_backend_for_write,
+};
use common_telemetry::{debug, error, info, tracing};
use futures::future::try_join_all;
use object_store::Entry;
@@ -80,9 +82,14 @@ impl StatementExecutor {
suffix,
false,
)?;
- build_backend_for_write(&req.location, &req.connection, &self.local_file_access)
- .await
- .context(error::BuildBackendSnafu)?;
+ build_backend_for_write(
+ &req.location,
+ &req.connection,
+ &self.local_file_access,
+ &self.remote_storage_access,
+ )
+ .await
+ .context(error::BuildBackendSnafu)?;
let mut tasks = Vec::with_capacity(num_tables);
let semaphore = Arc::new(Semaphore::new(parallelism));
@@ -153,7 +160,13 @@ impl StatementExecutor {
.context(error::ParseFileFormatSnafu)?
.suffix();
- let entries = list_files_to_copy(req, suffix, &self.local_file_access).await?;
+ let entries = list_files_to_copy(
+ req,
+ suffix,
+ &self.local_file_access,
+ &self.remote_storage_access,
+ )
+ .await?;
let continue_on_error = req
.with
@@ -254,10 +267,16 @@ async fn list_files_to_copy(
req: &CopyDatabaseRequest,
suffix: &str,
local_file_access: &LocalFileAccess,
+ remote_storage_access: &RemoteStorageAccess,
) -> error::Result> {
- let object_store = build_backend(&req.location, &req.connection, local_file_access)
- .await
- .context(error::BuildBackendSnafu)?;
+ let object_store = build_backend(
+ &req.location,
+ &req.connection,
+ local_file_access,
+ remote_storage_access,
+ )
+ .await
+ .context(error::BuildBackendSnafu)?;
let pattern = Regex::try_from(format!(".*{}", suffix)).context(error::BuildRegexSnafu)?;
let lister = Lister::new(
@@ -273,7 +292,7 @@ async fn list_files_to_copy(
mod tests {
use std::collections::HashSet;
- use common_datasource::object_store::LocalFileAccess;
+ use common_datasource::object_store::{LocalFileAccess, RemoteStorageAccess};
use object_store::ObjectStore;
use object_store::services::Fs;
use object_store::util::normalize_dir;
@@ -311,16 +330,21 @@ mod tests {
time_range: None,
};
let local_file_access = LocalFileAccess::sandboxed(dir.path()).unwrap();
- let listed = list_files_to_copy(&request, ".parquet", &local_file_access)
- .await
- .unwrap()
- .into_iter()
- .map(|e| {
- database_import_source(&request.location, e.path())
- .unwrap()
- .0
- })
- .collect::>();
+ let listed = list_files_to_copy(
+ &request,
+ ".parquet",
+ &local_file_access,
+ &RemoteStorageAccess::unrestricted(),
+ )
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|e| {
+ database_import_source(&request.location, e.path())
+ .unwrap()
+ .0
+ })
+ .collect::>();
assert_eq!(
["a".to_string(), "b".to_string(), "e.f".to_string()]
diff --git a/src/operator/src/statement/copy_table_from.rs b/src/operator/src/statement/copy_table_from.rs
index 7a7c18ec5d4..1214c354f2e 100644
--- a/src/operator/src/statement/copy_table_from.rs
+++ b/src/operator/src/statement/copy_table_from.rs
@@ -28,7 +28,9 @@ use common_datasource::file_format::json::{JsonFormat, json_text_stream};
use common_datasource::file_format::orc::{ReaderAdapter, infer_orc_schema, new_orc_stream_reader};
use common_datasource::file_format::{FileFormat, Format, file_to_stream};
use common_datasource::lister::{Lister, Source};
-use common_datasource::object_store::{LocalFileAccess, build_backend_with_path};
+use common_datasource::object_store::{
+ LocalFileAccess, RemoteStorageAccess, build_backend_with_path,
+};
use common_query::{OutputCost, OutputRows};
use common_recordbatch::DfSendableRecordBatchStream;
use common_recordbatch::adapter::RecordBatchStreamTypeAdapter;
@@ -96,10 +98,16 @@ impl FileMetadata {
async fn list_copy_from_paths(
req: &CopyTableRequest,
local_file_access: &LocalFileAccess,
+ remote_storage_access: &RemoteStorageAccess,
) -> Result<(ObjectStore, Vec)> {
- let backend = build_backend_with_path(&req.location, &req.connection, local_file_access)
- .await
- .context(error::BuildBackendSnafu)?;
+ let backend = build_backend_with_path(
+ &req.location,
+ &req.connection,
+ local_file_access,
+ remote_storage_access,
+ )
+ .await
+ .context(error::BuildBackendSnafu)?;
let regex = req
.pattern
.as_ref()
@@ -513,7 +521,9 @@ impl StatementExecutor {
};
let table = self.get_table(&table_ref).await?;
let format = Format::try_from(&req.with).context(error::ParseFileFormatSnafu)?;
- let (object_store, paths) = list_copy_from_paths(&req, &self.local_file_access).await?;
+ let (object_store, paths) =
+ list_copy_from_paths(&req, &self.local_file_access, &self.remote_storage_access)
+ .await?;
let mut files = Vec::with_capacity(paths.len());
let table_schema = table.schema().arrow_schema().clone();
let filters = table
@@ -1069,21 +1079,29 @@ mod tests {
] {
// PATTERN applies to directories, not an explicitly selected file.
let req = copy_from_request(&location, Some("does-not-match"));
- let (store, paths) = list_copy_from_paths(&req, &access).await.unwrap();
+ let (store, paths) =
+ list_copy_from_paths(&req, &access, &RemoteStorageAccess::unrestricted())
+ .await
+ .unwrap();
assert_eq!(paths, ["data file.parquet"]);
assert_eq!(store.read(&paths[0]).await.unwrap().to_vec(), b"data");
}
let req = copy_from_request("nested/", Some("^data"));
- let (_, paths) = list_copy_from_paths(&req, &access).await.unwrap();
+ let (_, paths) = list_copy_from_paths(&req, &access, &RemoteStorageAccess::unrestricted())
+ .await
+ .unwrap();
assert_eq!(paths, ["data file.parquet"]);
let req = copy_from_request("nested/", None);
- let (_, mut paths) = list_copy_from_paths(&req, &access).await.unwrap();
+ let (_, mut paths) =
+ list_copy_from_paths(&req, &access, &RemoteStorageAccess::unrestricted())
+ .await
+ .unwrap();
paths.sort();
assert_eq!(paths, ["data file.parquet", "other.csv"]);
let req = copy_from_request("nested/data.dir", None);
assert!(
- list_copy_from_paths(&req, &access)
+ list_copy_from_paths(&req, &access, &RemoteStorageAccess::unrestricted())
.await
.unwrap()
.1
@@ -1091,7 +1109,7 @@ mod tests {
);
let req = copy_from_request("nested/", Some("does-not-match"));
assert!(
- list_copy_from_paths(&req, &access)
+ list_copy_from_paths(&req, &access, &RemoteStorageAccess::unrestricted())
.await
.unwrap()
.1
@@ -1100,19 +1118,24 @@ mod tests {
let req = copy_from_request("nested/missing.parquet", None);
assert!(matches!(
- list_copy_from_paths(&req, &access).await,
+ list_copy_from_paths(&req, &access, &RemoteStorageAccess::unrestricted()).await,
Err(error::Error::ListObjects {
source: common_datasource::error::Error::ListObjects { error, .. }, ..
}) if error.kind() == object_store::ErrorKind::NotFound
));
let req = copy_from_request("nested/data file.parquet", Some("["));
assert!(matches!(
- list_copy_from_paths(&req, &access).await,
+ list_copy_from_paths(&req, &access, &RemoteStorageAccess::unrestricted()).await,
Err(error::Error::BuildRegex { .. })
));
let req = copy_from_request("nested/data file.parquet", None);
assert!(matches!(
- list_copy_from_paths(&req, &LocalFileAccess::Disabled).await,
+ list_copy_from_paths(
+ &req,
+ &LocalFileAccess::Disabled,
+ &RemoteStorageAccess::unrestricted()
+ )
+ .await,
Err(error::Error::BuildBackend {
source: common_datasource::error::Error::LocalFileAccessDisabled { .. },
..
@@ -1120,7 +1143,7 @@ mod tests {
));
let req = copy_from_request("../outside.parquet", None);
assert!(matches!(
- list_copy_from_paths(&req, &access).await,
+ list_copy_from_paths(&req, &access, &RemoteStorageAccess::unrestricted()).await,
Err(error::Error::BuildBackend {
source: common_datasource::error::Error::LocalFileAccessDenied { .. },
..
@@ -1141,18 +1164,20 @@ mod tests {
let req = copy_from_request("link.parquet", None);
assert!(
- list_copy_from_paths(&req, &access)
+ list_copy_from_paths(&req, &access, &RemoteStorageAccess::unrestricted())
.await
.unwrap()
.1
.is_empty()
);
let req = copy_from_request("./", None);
- let (_, paths) = list_copy_from_paths(&req, &access).await.unwrap();
+ let (_, paths) = list_copy_from_paths(&req, &access, &RemoteStorageAccess::unrestricted())
+ .await
+ .unwrap();
assert_eq!(paths, ["data.parquet"]);
let req = copy_from_request("dangling.parquet", None);
assert!(matches!(
- list_copy_from_paths(&req, &access).await,
+ list_copy_from_paths(&req, &access, &RemoteStorageAccess::unrestricted()).await,
Err(error::Error::ListObjects {
source: common_datasource::error::Error::ListObjects { error, .. }, ..
}) if error.kind() == object_store::ErrorKind::NotFound
@@ -1217,9 +1242,13 @@ mod tests {
Some("does-not-match"),
);
req.connection = connection.clone();
- let (_, paths) = list_copy_from_paths(&req, &LocalFileAccess::Disabled)
- .await
- .unwrap();
+ let (_, paths) = list_copy_from_paths(
+ &req,
+ &LocalFileAccess::Disabled,
+ &RemoteStorageAccess::unrestricted(),
+ )
+ .await
+ .unwrap();
assert_eq!(paths, [filename]);
}
{
@@ -1230,9 +1259,13 @@ mod tests {
}
let mut req = copy_from_request("s3://bucket/backup/schema/1/", Some(r"^data\."));
req.connection = connection.clone();
- let (_, mut paths) = list_copy_from_paths(&req, &LocalFileAccess::Disabled)
- .await
- .unwrap();
+ let (_, mut paths) = list_copy_from_paths(
+ &req,
+ &LocalFileAccess::Disabled,
+ &RemoteStorageAccess::unrestricted(),
+ )
+ .await
+ .unwrap();
paths.sort();
let mut expected = (0..16)
.map(|i| format!("data.{i}.parquet"))
@@ -1257,7 +1290,7 @@ mod tests {
copy_from_request(&format!("s3://bucket/backup/schema/1/{name}.parquet"), None);
req.connection = connection.clone();
assert!(matches!(
- list_copy_from_paths(&req, &LocalFileAccess::Disabled).await,
+ list_copy_from_paths(&req, &LocalFileAccess::Disabled, &RemoteStorageAccess::unrestricted()).await,
Err(error::Error::ListObjects {
source: common_datasource::error::Error::ListObjects { error, .. }, ..
}) if error.kind() == kind
diff --git a/src/operator/src/statement/copy_table_to.rs b/src/operator/src/statement/copy_table_to.rs
index 2974d4ac0f4..47475a3ec17 100644
--- a/src/operator/src/statement/copy_table_to.rs
+++ b/src/operator/src/statement/copy_table_to.rs
@@ -23,7 +23,9 @@ use common_datasource::file_format::Format;
use common_datasource::file_format::csv::stream_to_csv;
use common_datasource::file_format::json::stream_to_json;
use common_datasource::file_format::parquet::stream_to_parquet;
-use common_datasource::object_store::{LocalFileAccess, build_backend_for_write_with_path};
+use common_datasource::object_store::{
+ LocalFileAccess, RemoteStorageAccess, build_backend_for_write_with_path,
+};
use common_datasource::packed_writer::PackedTableWriter;
use common_datasource::parquet_writer::ParquetFileWriter;
use common_query::Output;
@@ -195,6 +197,7 @@ impl StatementExecutor {
debug!("Copy table: {table_id} to location: {location}");
Self::copy_to_file_managed(
&self.local_file_access,
+ &self.remote_storage_access,
&format,
output,
location,
@@ -214,6 +217,7 @@ impl StatementExecutor {
) -> Result {
Self::copy_to_file_managed(
&self.local_file_access,
+ &self.remote_storage_access,
format,
output,
location,
@@ -224,8 +228,10 @@ impl StatementExecutor {
.await
}
+ #[allow(clippy::too_many_arguments)]
async fn copy_to_file_managed(
local_file_access: &LocalFileAccess,
+ remote_storage_access: &RemoteStorageAccess,
format: &Format,
output: Output,
location: &str,
@@ -256,9 +262,14 @@ impl StatementExecutor {
.await;
}
- let backend = build_backend_for_write_with_path(location, connection, local_file_access)
- .await
- .context(error::BuildBackendSnafu)?;
+ let backend = build_backend_for_write_with_path(
+ location,
+ connection,
+ local_file_access,
+ remote_storage_access,
+ )
+ .await
+ .context(error::BuildBackendSnafu)?;
let filename = backend
.object_path
.with_context(|| error::UnexpectedSnafu {
@@ -531,6 +542,7 @@ mod tests {
let token = CancellationToken::new();
let result = StatementExecutor::copy_to_file_managed(
&access,
+ &RemoteStorageAccess::unrestricted(),
&format,
output(false),
location.as_str(),
@@ -553,6 +565,7 @@ mod tests {
let token = CancellationToken::new();
let result = StatementExecutor::copy_to_file_managed(
&access,
+ &RemoteStorageAccess::unrestricted(),
&format,
output(invalid_schema),
location.as_str(),
diff --git a/src/operator/src/statement/database_copy.rs b/src/operator/src/statement/database_copy.rs
index 899dfa9b133..39124a9c11d 100644
--- a/src/operator/src/statement/database_copy.rs
+++ b/src/operator/src/statement/database_copy.rs
@@ -344,7 +344,9 @@ mod tests {
#[tokio::test]
async fn output_locations_resolve_to_writer_keys() {
- use common_datasource::object_store::{LocalFileAccess, build_backend_for_write_with_path};
+ use common_datasource::object_store::{
+ LocalFileAccess, RemoteStorageAccess, build_backend_for_write_with_path,
+ };
let dir = common_test_util::temp_dir::create_temp_dir("database_export_paths");
let access = LocalFileAccess::sandboxed(dir.path()).unwrap();
@@ -364,10 +366,14 @@ mod tests {
continue;
}
let file = DatabaseExportFile::new(&directory, name, ".parquet").unwrap();
- let backend =
- build_backend_for_write_with_path(&file.location, &connection, &access)
- .await
- .unwrap();
+ let backend = build_backend_for_write_with_path(
+ &file.location,
+ &connection,
+ &access,
+ &RemoteStorageAccess::unrestricted(),
+ )
+ .await
+ .unwrap();
assert_eq!(backend.object_path.as_deref(), Some(file.path.as_str()));
let (table_name, input_location) =
database_import_source(&directory, &file.path).unwrap();
diff --git a/src/operator/src/statement/ddl.rs b/src/operator/src/statement/ddl.rs
index a717af912e4..f742047ecd7 100644
--- a/src/operator/src/statement/ddl.rs
+++ b/src/operator/src/statement/ddl.rs
@@ -549,9 +549,13 @@ impl StatementExecutor {
}
}
- let create_expr =
- &mut expr_helper::create_external_expr(create_expr, &ctx, &self.local_file_access)
- .await?;
+ let create_expr = &mut expr_helper::create_external_expr(
+ create_expr,
+ &ctx,
+ &self.local_file_access,
+ &self.remote_storage_access,
+ )
+ .await?;
self.create_table_inner(create_expr, None, ctx, TriggerReason::Manual)
.await
}
diff --git a/src/operator/src/statement/export_database.rs b/src/operator/src/statement/export_database.rs
index 16fce1982ce..0f394db7701 100644
--- a/src/operator/src/statement/export_database.rs
+++ b/src/operator/src/statement/export_database.rs
@@ -164,9 +164,14 @@ impl StatementExecutor {
LogicalTableExport::try_new_in_directory(table, &tables, &req.location)?,
));
}
- build_backend_for_write(&req.location, &req.connection, &self.local_file_access)
- .await
- .context(error::BuildBackendSnafu)?;
+ build_backend_for_write(
+ &req.location,
+ &req.connection,
+ &self.local_file_access,
+ &self.remote_storage_access,
+ )
+ .await
+ .context(error::BuildBackendSnafu)?;
Ok(PreparedDatabaseExport { request: req, jobs })
}
}
@@ -204,10 +209,14 @@ impl StatementExecutor {
let parallelism = parse_parallelism_from_option_map(&req.with);
let budget = ExportWriteBudget::new(parallelism);
let packed = if is_packed_export(&req.with) {
- let store =
- build_backend_for_write(&req.location, &req.connection, &self.local_file_access)
- .await
- .context(error::BuildBackendSnafu)?;
+ let store = build_backend_for_write(
+ &req.location,
+ &req.connection,
+ &self.local_file_access,
+ &self.remote_storage_access,
+ )
+ .await
+ .context(error::BuildBackendSnafu)?;
Some(
PackedWriter::new(store).context(error::WriteStreamToFileSnafu {
path: &req.location,
diff --git a/src/operator/src/statement/export_logical_tables.rs b/src/operator/src/statement/export_logical_tables.rs
index 9396d5ed8be..a6f797d9e6e 100644
--- a/src/operator/src/statement/export_logical_tables.rs
+++ b/src/operator/src/statement/export_logical_tables.rs
@@ -30,7 +30,9 @@ use arrow::compute::{cast, take};
use arrow::datatypes::{DataType, SchemaRef};
use arrow::downcast_dictionary_array;
use arrow::record_batch::RecordBatch;
-use common_datasource::object_store::{LocalFileAccess, build_backend_for_write};
+use common_datasource::object_store::{
+ LocalFileAccess, RemoteStorageAccess, build_backend_for_write,
+};
use common_datasource::packed_writer::{PackedTableWriter, PackedWriterRef};
use common_datasource::parquet_writer::{
ParquetCreationPolicy, ParquetFileWriter, ParquetWriterLimits,
@@ -357,7 +359,7 @@ impl StatementExecutor {
_ = cancellation.cancelled() => return error::LogicalTableExportCancelledSnafu.fail(),
result = async {
unit.validate_table_routes(self.table_metadata_manager.table_route_manager()).await?;
- let destination = LogicalExportDestination::new(directory, connection, &self.local_file_access, packed).await?;
+ let destination = LogicalExportDestination::new(directory, connection, &self.local_file_access, &self.remote_storage_access, packed).await?;
let output = self.query_engine.execute(unit.build_plan(time_range)?, query_ctx)
.await.context(error::ExecLogicalPlanSnafu)?;
let stream = match output.data {
@@ -383,6 +385,7 @@ impl LogicalExportDestination {
directory: &str,
connection: &HashMap,
local_file_access: &LocalFileAccess,
+ remote_storage_access: &RemoteStorageAccess,
packed: Option,
) -> Result {
if let Some(packed) = packed {
@@ -392,6 +395,7 @@ impl LogicalExportDestination {
&format!("{}/", directory.trim_end_matches('/')),
connection,
local_file_access,
+ remote_storage_access,
)
.await
.context(error::BuildBackendSnafu)?;
diff --git a/src/operator/src/statement/export_logical_tables/tests.rs b/src/operator/src/statement/export_logical_tables/tests.rs
index 59c9ea00f56..22afb7c9499 100644
--- a/src/operator/src/statement/export_logical_tables/tests.rs
+++ b/src/operator/src/statement/export_logical_tables/tests.rs
@@ -321,7 +321,14 @@ async fn packed_destination_reuses_backend_with_local_access_disabled() {
.build_operator();
let connection = HashMap::new();
let access = LocalFileAccess::Disabled;
- let result = LogicalExportDestination::new(location.as_str(), &connection, &access, None).await;
+ let result = LogicalExportDestination::new(
+ location.as_str(),
+ &connection,
+ &access,
+ &RemoteStorageAccess::unrestricted(),
+ None,
+ )
+ .await;
assert!(matches!(
result,
Err(error::Error::BuildBackend {
@@ -335,6 +342,7 @@ async fn packed_destination_reuses_backend_with_local_access_disabled() {
location.as_str(),
&connection,
&access,
+ &RemoteStorageAccess::unrestricted(),
Some(packed.clone()),
)
.await
@@ -778,6 +786,7 @@ async fn cancellation_drains_storage_and_preserves_committed_files() {
&format!("{}/", directory.path().display()),
&HashMap::new(),
&access,
+ &RemoteStorageAccess::unrestricted(),
)
.await
.unwrap();
diff --git a/src/operator/src/statement/import_packed.rs b/src/operator/src/statement/import_packed.rs
index 7f31804c70b..4fbe1779d7a 100644
--- a/src/operator/src/statement/import_packed.rs
+++ b/src/operator/src/statement/import_packed.rs
@@ -67,10 +67,14 @@ impl StatementExecutor {
}
.fail();
}
- let backend =
- build_backend_with_path(&req.location, &req.connection, &self.local_file_access)
- .await
- .context(error::BuildBackendSnafu)?;
+ let backend = build_backend_with_path(
+ &req.location,
+ &req.connection,
+ &self.local_file_access,
+ &self.remote_storage_access,
+ )
+ .await
+ .context(error::BuildBackendSnafu)?;
if !backend
.is_file(PACK_INDEX_FILE)
.await
diff --git a/src/query/src/options.rs b/src/query/src/options.rs
index a420ebe5d12..fe5ec05a195 100644
--- a/src/query/src/options.rs
+++ b/src/query/src/options.rs
@@ -153,6 +153,12 @@ pub struct QueryOptions {
/// a `true` default routes every query natively and a `false` one still lets one query or one
/// session ask for it. Default: `false`.
pub experimental_native_promql: bool,
+ /// Hosts that object stores built from SQL statements (`COPY`, `COPY DATABASE`,
+ /// `EXPORT/IMPORT DATABASE` and external tables) may connect to. Empty means no restriction.
+ pub remote_allowed_hosts: Vec,
+ /// Whether such an object store without credentials in its connection options may use the
+ /// server's own credentials.
+ pub allow_server_credentials: bool,
}
#[allow(clippy::derivable_impls)]
@@ -170,6 +176,8 @@ impl Default for QueryOptions {
experimental_spill_compression: QuerySpillCompression::Uncompressed,
experimental_memory_pool_policy: QueryMemoryPoolPolicy::Greedy,
experimental_native_promql: false,
+ remote_allowed_hosts: Vec::new(),
+ allow_server_credentials: true,
}
}
}
diff --git a/src/query/src/sql.rs b/src/query/src/sql.rs
index aebb0cb6850..daac3a269e5 100644
--- a/src/query/src/sql.rs
+++ b/src/query/src/sql.rs
@@ -31,7 +31,9 @@ use common_catalog::consts::{
use common_catalog::format_full_table_name;
use common_datasource::file_format::{FileFormat, Format, infer_schemas};
use common_datasource::lister::{Lister, Source};
-use common_datasource::object_store::{LocalFileAccess, build_backend_with_path};
+use common_datasource::object_store::{
+ LocalFileAccess, RemoteStorageAccess, build_backend_with_path,
+};
use common_error::ext::BoxedError;
use common_meta::SchemaOptions;
use common_meta::ddl::create_flow::{FlowType, effective_eval_schedule_from_flow_info};
@@ -1446,6 +1448,7 @@ fn describe_column_semantic_types(
pub async fn prepare_file_table_files(
options: &HashMap,
local_file_access: &LocalFileAccess,
+ remote_storage_access: &RemoteStorageAccess,
) -> Result<(ObjectStore, Vec)> {
let url = options
.get(FILE_TABLE_LOCATION_KEY)
@@ -1458,7 +1461,7 @@ pub async fn prepare_file_table_files(
.map(|x| Regex::new(x))
.transpose()
.context(error::BuildRegexSnafu)?;
- let backend = build_backend_with_path(url, options, local_file_access)
+ let backend = build_backend_with_path(url, options, local_file_access, remote_storage_access)
.await
.context(error::BuildBackendSnafu)?;
let source = if let Some(filename) = backend.object_path {
diff --git a/src/standalone/src/options.rs b/src/standalone/src/options.rs
index 3c7a9e6ce13..a0d622fc907 100644
--- a/src/standalone/src/options.rs
+++ b/src/standalone/src/options.rs
@@ -162,6 +162,7 @@ impl Configurable for StandaloneOptions {
"heartbeat_env_vars",
"wal.broker_endpoints",
"event_recorder.event_types",
+ "query.remote_allowed_hosts",
"pending_rows_batcher.protocols",
"pending_rows_batcher.logical_table.protocols",
])
diff --git a/tests-integration/tests/export_logical_tables.rs b/tests-integration/tests/export_logical_tables.rs
index 4c24b437b5c..7236f60f53d 100644
--- a/tests-integration/tests/export_logical_tables.rs
+++ b/tests-integration/tests/export_logical_tables.rs
@@ -1081,6 +1081,7 @@ async fn packed_copy_standalone_heterogeneous_streams() {
&location,
&connection,
&common_datasource::object_store::LocalFileAccess::Disabled,
+ &common_datasource::object_store::RemoteStorageAccess::unrestricted(),
)
.await
.unwrap();
diff --git a/tests-integration/tests/http.rs b/tests-integration/tests/http.rs
index ca613840e22..7b3e9c44d2d 100644
--- a/tests-integration/tests/http.rs
+++ b/tests-integration/tests/http.rs
@@ -5025,6 +5025,8 @@ experimental_spill_max_temp_directory_size = "1GiB"
experimental_spill_compression = "uncompressed"
experimental_memory_pool_policy = "greedy"
experimental_native_promql = false
+remote_allowed_hosts = []
+allow_server_credentials = true
[memory]
enable_heap_profiling = true