fix: validate index names before building remote routes

This commit is contained in:
Gatefixer
2026-11-12 18:52:23 +00:00
parent 9b13e8f725
commit 121342c6d1
5 changed files with 214 additions and 9 deletions
+4
View File
@@ -250,6 +250,10 @@ impl IndexBuilder {
/// The name of the index. If not set, a default name will be generated.
///
/// Custom names must contain 1 to 128 ASCII alphanumeric characters,
/// dashes, underscores, or periods, and cannot be `.` or `..`.
/// Invalid names are rejected when executing the builder.
///
/// # Examples
///
/// ```
+86 -7
View File
@@ -52,7 +52,7 @@ use crate::utils::background_cache::BackgroundCache;
use crate::utils::{
MaxBatchLengthStream, TimeoutStream, public_fts_field_path_by_id, resolve_arrow_field_path,
resolve_arrow_fts_field_path, supported_btree_data_type, supported_vector_data_type,
validate_fts_field,
validate_fts_field, validate_index_name,
};
use crate::{DistanceType, Error};
use crate::{
@@ -697,6 +697,9 @@ impl<S: HttpSend> RemoteTable<S> {
}
async fn submit_create_index(&self, mut index: IndexBuilder) -> Result<Option<String>> {
if let Some(name) = &index.name {
validate_index_name(name)?;
}
self.check_mutable().await?;
let request = self
.client
@@ -2418,6 +2421,10 @@ impl<S: HttpSend + 'static> RemoteTable<S> {
index_name: &str,
read_snapshot: ReadSnapshot,
) -> Result<Option<IndexStatistics>> {
// Percent-encoding alone leaves dot segments intact, and URL parsing
// would normalize them into a different route. This also guards the
// stats requests made while listing indices on legacy servers.
validate_index_name(index_name)?;
let encoded_name = urlencoding::encode(index_name);
let mut body = serde_json::json!({ "version": read_snapshot.version });
self.apply_branch_body(&mut body);
@@ -4512,6 +4519,7 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
}
async fn drop_index(&self, index_name: &str) -> Result<()> {
validate_index_name(index_name)?;
let encoded_name = urlencoding::encode(index_name);
let request = self.apply_branch_query(self.client.post(&format!(
"/v1/table/{}/index/{encoded_name}/drop/",
@@ -4528,6 +4536,7 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
}
async fn prewarm_index(&self, index_name: &str) -> Result<()> {
validate_index_name(index_name)?;
let encoded_name = urlencoding::encode(index_name);
let request = self.client.post(&format!(
"/v1/table/{}/index/{encoded_name}/prewarm/",
@@ -8861,7 +8870,7 @@ mod tests {
}
#[tokio::test]
async fn test_create_index_forwards_replace_false_on_existing_route() {
async fn test_create_index_forwards_name_and_replace_false_on_existing_route() {
let table = Table::new_with_handler("my_table", move |request| {
assert_eq!(request.method(), "POST");
match request.url().path() {
@@ -8876,6 +8885,7 @@ mod tests {
let body = request.body().unwrap().as_bytes().unwrap();
let body: serde_json::Value = serde_json::from_slice(body).unwrap();
assert_eq!(body["replace"], json!(false));
assert_eq!(body["name"], json!("a_idx-1..v2"));
http::Response::builder()
.status(200)
@@ -8889,6 +8899,7 @@ mod tests {
table
.create_index(&["a"], Index::BTree(Default::default()))
.replace(false)
.name("a_idx-1..v2".to_string())
.execute()
.await
.unwrap();
@@ -12985,12 +12996,80 @@ mod tests {
assert!(matches!(e, Error::IndexNotFound { .. }));
}
/// Index names are unvalidated, so reserved characters must be
/// percent-encoded or they restructure the request path.
#[tokio::test]
async fn test_per_index_paths_encode_reserved_characters() {
const NAME: &str = "my/index?a#b c";
const PREFIX: &str = "/v1/table/my_table/index/my%2Findex%3Fa%23b%20c";
async fn test_invalid_index_names_never_send_requests() {
let table = Table::new_with_handler("my_table", |request| -> http::Response<String> {
panic!("Invalid index name sent a request to {}", request.url());
});
for name in [
"..",
".",
"",
"my/index",
"my\\index",
"%2e%2e",
"my/index?a#b c",
] {
for result in [
table.drop_index(name).await,
table.prewarm_index(name).await,
table.index_stats(name).await.map(|_| ()),
table
.create_index(&["a"], Index::BTree(Default::default()))
.name(name.to_string())
.execute()
.await,
table
.create_index(&["a"], Index::BTree(Default::default()))
.name(name.to_string())
.execute_async()
.await
.map(|_| ()),
] {
assert!(
matches!(result, Err(Error::InvalidInput { .. })),
"Expected invalid input for {name:?}, got {result:?}"
);
}
}
}
#[tokio::test]
async fn test_list_indices_with_legacy_index_name() {
for enriched in [false, true] {
let table = Table::new_with_handler("my_table", move |request| {
let body = match request.url().path() {
"/v1/table/my_table/describe/" => {
let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
describe_response(&schema)
}
"/v1/table/my_table/index/list/" => {
let mut entry = json!({"index_name": "..", "columns": ["a"]});
if enriched {
entry["index_type"] = json!("BTREE");
}
json!({"indexes": [entry]}).to_string()
}
path => panic!("Legacy index name caused an unexpected request to {path}"),
};
http::Response::builder().status(200).body(body).unwrap()
});
let result = table.list_indices().await;
if enriched {
// Names from the server remain discoverable when no per-index
// stats request is needed.
assert_eq!(result.unwrap()[0].name, "..");
} else {
assert!(matches!(result, Err(Error::InvalidInput { .. })));
}
}
}
#[tokio::test]
async fn test_per_index_paths_preserve_valid_names() {
const NAME: &str = "my_index-1..v2";
const PREFIX: &str = "/v1/table/my_table/index/my_index-1..v2";
let table = Table::new_with_handler("my_table", |request| {
assert_eq!(request.url().path(), format!("{PREFIX}/stats/"));
+6 -1
View File
@@ -2915,6 +2915,7 @@ impl Table {
/// Get statistics about an index.
/// Returns None if the index does not exist.
/// Remote tables require a name valid for [`IndexBuilder::name`].
pub async fn index_stats(
&self,
index_name: impl AsRef<str>,
@@ -2924,7 +2925,10 @@ impl Table {
/// Drop an index from the table.
///
/// Note: This is not yet available in LanceDB Enterprise.
/// Remote tables reject names that are not valid for [`IndexBuilder::name`].
/// Legacy indices with such names can still be dropped through a native
/// connection with direct access to the dataset. On managed remote tables,
/// these indices require server-side cleanup.
///
/// This does not delete the index from disk, it just removes it from the table.
/// To delete the index, run [`Self::optimize()`] after dropping the index.
@@ -2948,6 +2952,7 @@ impl Table {
/// indices will silently ignore the request.
///
/// Use [`Self::list_indices()`] to find the names of the indices.
/// Remote tables require a name valid for [`IndexBuilder::name`].
pub async fn prewarm_index(&self, name: &str) -> Result<()> {
self.inner.prewarm_index(name).await
}
+79 -1
View File
@@ -30,7 +30,7 @@ use crate::index::vector::{VectorIndex, suggested_num_sub_vectors};
use crate::utils::{
resolve_lance_fts_field_path, supported_bitmap_data_type, supported_btree_data_type,
supported_fm_data_type, supported_label_list_data_type, supported_vector_data_type,
supported_zonemap_data_type, validate_fts_field,
supported_zonemap_data_type, validate_fts_field, validate_index_name,
};
use super::NativeTable;
@@ -116,6 +116,9 @@ impl NativeTable {
&self,
opts: &crate::index::IndexBuilder,
) -> Result<PreparedIndex> {
if let Some(name) = &opts.name {
validate_index_name(name)?;
}
if opts.columns.len() != 1 {
return Err(Error::Schema {
message: "Multi-column (composite) indices are not yet supported".to_string(),
@@ -1296,6 +1299,81 @@ mod tests {
assert_eq!(stats.distance_type, Some(crate::DistanceType::L2));
}
#[tokio::test]
async fn test_create_index_rejects_invalid_index_names() {
let conn = connect("memory://").execute().await.unwrap();
let batch = record_batch!(("i", Int32, [1])).unwrap();
let table = conn
.create_table("my_table", batch)
.execute()
.await
.unwrap();
for name in ["..", ".", "", "my/index", "my\\index", "%2e%2e"] {
let result = table
.create_index(&["i"], Index::Auto)
.name(name.to_string())
.execute()
.await;
assert!(
matches!(result, Err(crate::Error::InvalidInput { .. })),
"Expected invalid input for {name:?}, got {result:?}"
);
let result = table
.create_index(&["i"], Index::Auto)
.name(name.to_string())
.execute_async()
.await;
assert!(
matches!(result, Err(crate::Error::InvalidInput { .. })),
"Expected invalid input for {name:?}, got {result:?}"
);
}
assert!(table.list_indices().await.unwrap().is_empty());
for name in ["i_idx-1..v2", "..."] {
table
.create_index(&["i"], Index::Auto)
.name(name.to_string())
.execute()
.await
.unwrap();
assert_eq!(table.list_indices().await.unwrap()[0].name, name);
table.drop_index(name).await.unwrap();
}
}
#[tokio::test]
async fn test_drop_index_with_legacy_index_names() {
let conn = connect("memory://").execute().await.unwrap();
let batch = record_batch!(("i", Int32, [1])).unwrap();
let table = conn
.create_table("my_table", batch)
.execute()
.await
.unwrap();
let native = table.as_native().unwrap();
let params = lance_index::scalar::ScalarIndexParams::for_builtin(
lance_index::scalar::BuiltinIndexType::BTree,
);
for name in [".", "..", "old/index", "old\\index"] {
// Simulate an index written before LanceDB validated custom names.
let mut dataset = (*native.dataset.get().await.unwrap()).clone();
dataset
.create_index_builder(&["i"], lance_index::IndexType::Scalar, &params)
.name(name.to_string())
.await
.unwrap();
native.dataset.update(dataset);
assert_eq!(table.list_indices().await.unwrap()[0].name, name);
table.drop_index(name).await.unwrap();
assert!(table.list_indices().await.unwrap().is_empty());
assert_eq!(table.count_rows(None).await.unwrap(), 1);
}
}
#[tokio::test]
async fn test_create_scalar_index() {
let conn = connect("memory://").execute().await.unwrap();
+39
View File
@@ -23,6 +23,9 @@ use datafusion_physical_plan::SendableRecordBatchStream;
/// object store.
const MAX_TABLE_NAME_CHARS: usize = 128;
/// The maximum length of a custom index name, which is also used in remote URLs.
const MAX_INDEX_NAME_CHARS: usize = 128;
/// The maximum length of a component of a namespace.
const MAX_NAMESPACE_NAME_CHARS: usize = 64;
@@ -136,6 +139,11 @@ pub fn validate_table_name(name: &str) -> Result<()> {
Ok(())
}
/// Validate a custom index name before creation or use as a remote path segment.
pub(crate) fn validate_index_name(name: &str) -> Result<()> {
validate_view_or_namespace_or_secret(name, "index name", MAX_INDEX_NAME_CHARS)
}
/// Validate that an input string contains alphanumerics, or dashes, underscores, and periods.
fn validate_view_or_namespace_or_secret(input: &str, kind: &str, max_len: usize) -> Result<()> {
if input.is_empty() || input == "." || input == ".." {
@@ -1092,6 +1100,37 @@ mod tests {
);
}
#[test]
fn test_validate_index_name() {
for name in [
"my_index",
"index-1.2",
"index..v2",
"...",
&"a".repeat(128),
] {
assert!(validate_index_name(name).is_ok(), "rejected {name:?}");
}
for name in [
"",
".",
"..",
"my/index",
"my\\index",
"%2e%2e",
"index?query",
"index#fragment",
"name with space",
"café",
&"a".repeat(129),
] {
assert!(
matches!(validate_index_name(name), Err(Error::InvalidInput { .. })),
"accepted {name:?}"
);
}
}
#[test]
fn test_validate_namespace_component() {
// Valid namespace names