fix: read LANCEDB_API_KEY when connecting to remote without api_key (#5166)

## Summary

- Rust remote connect reads `LANCEDB_API_KEY` when a `db://` connection
has no `api_key` and no `oauth_config`. Python already does this in its
own wrapper; Node and Rust callers did not.
- An explicit API key still wins. An empty `LANCEDB_API_KEY` is treated
as present, matching Python's `is None` check, and the connection sends
no `x-api-key` header.
- OAuth does not read the variable, so an ambient key cannot turn an
OAuth connect into an invalid API-key-plus-OAuth configuration. The
fallback lives in Rust `execute_remote`, so Node does not write the
credential into the caller's options object.

Supersedes #3797, which is stale and conflicting. This addresses the
Gatekeeper requests there: do not apply the environment key when
`oauthConfig` is set, and do not write it into the caller-owned options.

## Test plan

- [x] `cargo test --features remote -p lancedb --lib connection::` (each
env case re-runs the test binary as a child process with
`LANCEDB_API_KEY` set or removed on the child `Command`; no in-process
`set_var`/`remove_var`)
- [x] `cargo clippy -p lancedb --all-targets --features remote -- -D
warnings`
- [x] `cargo fmt --all -- --check`
- [x] `cd nodejs && pnpm build`
- [x] `cd nodejs && pnpm exec jest __test__/remote_api_key_env.test.ts`
(env set only in a child process; missing-key case asserts `connect()`
itself rejects against the loopback endpoint; OAuth case asserts
`x-api-key` is absent)
- [x] `cd nodejs && pnpm lint-ci`; `pnpm run docs` leaves `docs/src/js`
unchanged

Written with Cursor (Grok).

---------

Co-authored-by: Preston Zhao <195942578+canyang25@users.noreply.github.com>
Co-authored-by: Xuanwo <github@xuanwo.io>
This commit is contained in:
Preston Zhao
2026-12-02 13:04:57 +08:00
committed by GitHub
co-authored by Preston Zhao Xuanwo
parent 5373da5760
commit b3a8e6f08d
4 changed files with 500 additions and 7 deletions
@@ -17,6 +17,8 @@ optional apiKey: string;
(For LanceDB Enterprise or LanceDB Cloud only): the API key to use.
Can also be set via the environment variable `LANCEDB_API_KEY`.
An explicit `apiKey` takes precedence. The variable is not read when
`oauthConfig` is set.
***
+295
View File
@@ -0,0 +1,295 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
import * as http from "http";
import { type ChildProcess, spawn } from "node:child_process";
import * as path from "path";
// The child is killed after 20s. Jest's default 5s test timeout would fire
// first, including on macOS CI while the debug addon loads.
jest.setTimeout(60_000);
// Jest replaces process.env with a sandbox. Assigning LANCEDB_API_KEY there
// does not reach Rust's std::env, so these cases run in a child whose real
// environment is set explicitly. See nodejs/jest.config.js.
const CHILD_SOURCE = `
"use strict";
const { connect } = require(process.env.LANCEDB_PACKAGE_ENTRY);
(async () => {
const mode = process.env.LANCEDB_CONNECT_MODE;
const port = process.env.LANCEDB_CONNECT_PORT;
const options = {};
if (port) {
options.hostOverride = "http://127.0.0.1:" + port;
}
if (mode === "explicit") {
options.apiKey = "explicit-key";
} else if (mode === "oauth") {
options.oauthConfig = {
issuerUrl: process.env.LANCEDB_OAUTH_ISSUER,
clientId: "client-id",
clientSecret: "secret",
scopes: ["scope"],
flow: "client_credentials",
};
}
let stage = "connect";
try {
const db = await connect("db://dev", options);
stage = "tableNames";
const names = await db.tableNames();
const body = { ok: true, names };
if (mode === "oauth") {
body.open = db.isOpen();
}
process.stdout.write(JSON.stringify(body));
} catch (error) {
const message = error && error.message ? error.message : String(error);
process.stdout.write(JSON.stringify({ ok: false, stage, message }));
}
})();
`;
const packageRoot = path.resolve(__dirname, "..");
type ConnectResult = {
ok: boolean;
names?: string[];
open?: boolean;
stage?: "connect" | "tableNames";
message?: string;
};
type ChildRun = {
mode: "env" | "explicit" | "oauth";
apiKey?: string;
port?: number;
issuerUrl?: string;
};
function childEnvironment(apiKey: string | undefined): NodeJS.ProcessEnv {
const env: NodeJS.ProcessEnv = {};
for (const [key, value] of Object.entries(process.env)) {
if (typeof value === "string") {
env[key] = value;
}
}
delete env.LANCEDB_API_KEY;
if (apiKey !== undefined) {
env.LANCEDB_API_KEY = apiKey;
}
env.LANCEDB_PACKAGE_ENTRY = path.join(packageRoot, "dist", "index.js");
return env;
}
function runChild(options: ChildRun): Promise<ConnectResult> {
const env = childEnvironment(options.apiKey);
env.LANCEDB_CONNECT_MODE = options.mode;
if (options.port !== undefined) {
env.LANCEDB_CONNECT_PORT = String(options.port);
}
if (options.issuerUrl !== undefined) {
env.LANCEDB_OAUTH_ISSUER = options.issuerUrl;
}
return new Promise((resolve, reject) => {
const child: ChildProcess = spawn(process.execPath, ["-e", CHILD_SOURCE], {
cwd: packageRoot,
env,
});
let stdout = "";
let stderr = "";
const timer = setTimeout(() => {
child.kill("SIGKILL");
reject(new Error(`connect child timed out\nstderr:\n${stderr}`));
}, 20_000);
child.stdout?.setEncoding("utf8");
child.stderr?.setEncoding("utf8");
child.stdout?.on("data", (chunk: string) => {
stdout += chunk;
});
child.stderr?.on("data", (chunk: string) => {
stderr += chunk;
});
child.on("error", (error) => {
clearTimeout(timer);
reject(error);
});
child.on("close", () => {
clearTimeout(timer);
const line = stdout
.trim()
.split("\n")
.filter((entry) => entry.length > 0)
.at(-1);
if (!line) {
reject(
new Error(`connect child produced no output\nstderr:\n${stderr}`),
);
return;
}
try {
resolve(JSON.parse(line) as ConnectResult);
} catch (error) {
reject(
new Error(
`connect child output was not JSON: ${stdout}\nstderr:\n${stderr}\n${String(error)}`,
),
);
}
});
});
}
function headerValue(value: string | string[] | undefined): string | undefined {
return Array.isArray(value) ? value[0] : value;
}
function writeJson(res: http.ServerResponse, body: unknown) {
res
.writeHead(200, { "Content-Type": "application/json" })
.end(JSON.stringify(body));
}
function writeRawJson(res: http.ServerResponse, body: string) {
res.writeHead(200, { "Content-Type": "application/json" }).end(body);
}
async function withApiKeyServer(
onKey: (apiKey: string | undefined) => void,
options?: { oauthIssuer?: boolean },
): Promise<{ port: number; close: () => Promise<void> }> {
const server = http.createServer((req, res) => {
const address = server.address();
const port =
address !== null && typeof address !== "string" ? address.port : 0;
const pathname = new URL(req.url ?? "/", "http://127.0.0.1").pathname;
const respond = () => {
if (
options?.oauthIssuer &&
pathname === "/.well-known/openid-configuration"
) {
writeRawJson(
res,
`{"token_endpoint":"http://127.0.0.1:${port}/token"}`,
);
return;
}
if (options?.oauthIssuer && pathname === "/token") {
writeRawJson(
res,
'{"access_token":"access-token","expires_in":3600,"token_type":"Bearer"}',
);
return;
}
onKey(headerValue(req.headers["x-api-key"]));
writeJson(res, { tables: [] });
};
if (req.method === "POST") {
req.on("data", () => {
// Drain the client-credentials body before responding.
});
req.on("end", respond);
return;
}
respond();
});
const port = await new Promise<number>((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", () => {
const address = server.address();
if (address === null || typeof address === "string") {
reject(new Error("mock server did not bind a TCP port"));
return;
}
resolve(address.port);
});
});
return {
port,
close: () =>
new Promise((resolve) => {
server.closeAllConnections();
server.close(() => resolve());
}),
};
}
describe("LANCEDB_API_KEY remote fallback", () => {
it("uses the env var when apiKey is omitted", async () => {
const seen: Array<string | undefined> = [];
const server = await withApiKeyServer((apiKey) => seen.push(apiKey));
try {
const result = await runChild({
mode: "env",
apiKey: "env-key",
port: server.port,
});
expect(result).toEqual({ ok: true, names: [] });
expect(seen.length).toBeGreaterThan(0);
expect(new Set(seen)).toEqual(new Set(["env-key"]));
} finally {
await server.close();
}
});
it("keeps an explicit apiKey when the env var is set", async () => {
const seen: Array<string | undefined> = [];
const server = await withApiKeyServer((apiKey) => seen.push(apiKey));
try {
const result = await runChild({
mode: "explicit",
apiKey: "env-key",
port: server.port,
});
expect(result).toEqual({ ok: true, names: [] });
expect(seen.length).toBeGreaterThan(0);
expect(new Set(seen)).toEqual(new Set(["explicit-key"]));
} finally {
await server.close();
}
});
it("ignores the env var when oauthConfig is set", async () => {
const seen: Array<string | undefined> = [];
const server = await withApiKeyServer((apiKey) => seen.push(apiKey), {
oauthIssuer: true,
});
try {
const result = await runChild({
mode: "oauth",
apiKey: "env-key",
port: server.port,
issuerUrl: `http://127.0.0.1:${server.port}`,
});
expect(result).toEqual({ ok: true, open: true, names: [] });
expect(seen.length).toBeGreaterThan(0);
expect(seen.every((apiKey) => apiKey === undefined)).toBe(true);
} finally {
await server.close();
}
});
it("still requires an api key when the env var is unset", async () => {
// Loopback hostOverride so a connect() regression cannot reach the
// default service. stage is connect only when connect() itself rejects;
// tableNames() runs after connect() resolves.
const seen: Array<string | undefined> = [];
const server = await withApiKeyServer((apiKey) => {
seen.push(apiKey);
});
try {
const result = await runChild({ mode: "env", port: server.port });
expect(result).toEqual({
ok: false,
stage: "connect",
message: expect.stringContaining(
"Invalid input, An api_key or oauth_config is required when connecting to LanceDB Enterprise or LanceDB Cloud",
),
});
expect(seen).toEqual([]);
} finally {
await server.close();
}
});
});
+2
View File
@@ -74,6 +74,8 @@ pub struct ConnectionOptions {
/// (For LanceDB Enterprise or LanceDB Cloud only): the API key to use.
///
/// Can also be set via the environment variable `LANCEDB_API_KEY`.
/// An explicit `apiKey` takes precedence. The variable is not read when
/// `oauthConfig` is set.
pub api_key: Option<String>,
/// (For LanceDB Cloud only): the region to use for LanceDB Cloud (legacy).
/// Defaults to 'us-east-1'.
+201 -7
View File
@@ -1783,6 +1783,10 @@ impl ConnectBuilder {
/// This option is only used for `db://` URIs
/// and will be ignored for other URIs.
///
/// If omitted, `db://` connections read `LANCEDB_API_KEY`. An explicit key
/// takes precedence. An empty variable is present and sends no `x-api-key`
/// header. The variable is not read when [`Self::oauth_config`] is set.
///
/// # Arguments
///
/// * `api_key` - The API key to use for the connection
@@ -2056,6 +2060,8 @@ impl ConnectBuilder {
let region = options.region.ok_or_else(|| Error::InvalidInput {
message: "A region is required when connecting to LanceDB Cloud".to_string(),
})?;
// Match the Python client: an omitted key falls back to LANCEDB_API_KEY.
// Leave OAuth alone so an ambient key cannot collide with oauth_config.
let api_key = match (&self.oauth_config, &options.api_key) {
(Some(_), None) => String::new(),
(Some(_), Some(_)) => {
@@ -2066,13 +2072,16 @@ impl ConnectBuilder {
});
}
(None, Some(key)) => key.clone(),
(None, None) => {
return Err(Error::InvalidInput {
message:
"An api_key or oauth_config is required when connecting to LanceDB Enterprise or LanceDB Cloud"
.to_string(),
});
}
(None, None) => match std::env::var("LANCEDB_API_KEY") {
Ok(key) => key,
Err(_) => {
return Err(Error::InvalidInput {
message:
"An api_key or oauth_config is required when connecting to LanceDB Enterprise or LanceDB Cloud"
.to_string(),
});
}
},
};
if self.oauth_config.is_some() && self.request.client_config.header_provider.is_some() {
@@ -2418,6 +2427,191 @@ mod tests {
));
}
/// Marker for a re-exec of this test binary. The value is the libtest name.
#[cfg(feature = "remote")]
const LANCEDB_API_KEY_TEST_CHILD: &str = "LANCEDB_API_KEY_TEST_CHILD";
#[cfg(feature = "remote")]
fn lancedb_api_key_libtest_name(function: &str) -> String {
let module_path = module_path!();
let prefix = concat!(env!("CARGO_PKG_NAME"), "::");
let relative = module_path.strip_prefix(prefix).unwrap_or(module_path);
format!("{relative}::{function}")
}
/// Applies `LANCEDB_API_KEY` on a child process, then runs one test case.
///
/// `std::env::set_var` and `remove_var` are unsound once other threads in
/// this process exist. A `serial_test` lock does not cover those threads,
/// and restoring the variable from `Drop` has the same race. The child is
/// this test binary filtered to the one case, with the variable set or
/// removed before spawn.
#[cfg(feature = "remote")]
fn run_lancedb_api_key_child(test_name: &str, api_key: Option<&str>) {
let executable = std::env::current_exe().expect("current test executable");
let mut command = std::process::Command::new(executable);
command
.args(["--exact", test_name, "--nocapture", "--test-threads=1"])
.env(LANCEDB_API_KEY_TEST_CHILD, test_name)
.env("CARGO_TERM_COLOR", "never");
match api_key {
Some(api_key) => {
command.env("LANCEDB_API_KEY", api_key);
}
None => {
command.env_remove("LANCEDB_API_KEY");
}
}
let output = command
.output()
.unwrap_or_else(|error| panic!("failed to spawn {test_name}: {error}"));
let combined = format!(
"{}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
let completed = format!("LANCEDB_API_KEY_CASE_OK {test_name}");
assert!(
output.status.success()
&& combined.contains("test result: ok. 1 passed;")
&& combined.contains(&completed),
"child {test_name} failed ({})\n{combined}",
output.status,
);
}
#[cfg(feature = "remote")]
fn lancedb_api_key_case_entered(function: &str, api_key: Option<&str>) -> bool {
let test_name = lancedb_api_key_libtest_name(function);
if std::env::var(LANCEDB_API_KEY_TEST_CHILD).ok().as_deref() == Some(test_name.as_str()) {
true
} else {
run_lancedb_api_key_child(&test_name, api_key);
false
}
}
#[cfg(feature = "remote")]
fn lancedb_api_key_case_ok(function: &str) {
use std::io::Write;
let test_name = lancedb_api_key_libtest_name(function);
let mut stderr = std::io::stderr().lock();
writeln!(stderr, "LANCEDB_API_KEY_CASE_OK {test_name}")
.expect("write LANCEDB_API_KEY case marker");
stderr.flush().expect("flush LANCEDB_API_KEY case marker");
}
#[cfg(feature = "remote")]
macro_rules! lancedb_api_key_test {
($name:ident, $api_key:expr, $body:block) => {
#[tokio::test]
async fn $name() {
const CASE: &str = stringify!($name);
if !lancedb_api_key_case_entered(CASE, $api_key) {
return;
}
$body
lancedb_api_key_case_ok(CASE);
}
};
}
#[cfg(feature = "remote")]
async fn remote_api_key_header(api_key: Option<&str>) -> Result<Option<String>> {
let mut builder = connect("db://my-db")
.region("us-east-1")
.host_override("https://example.com");
if let Some(api_key) = api_key {
builder = builder.api_key(api_key);
}
let connection = builder.execute().await?;
let (_namespace, properties) = connection.namespace_client_config().await?;
Ok(properties.get("header.x-api-key").cloned())
}
#[cfg(feature = "remote")]
lancedb_api_key_test!(
test_connect_remote_lancedb_api_key_from_env,
Some("env-api-key"),
{
let header = remote_api_key_header(None)
.await
.expect("LANCEDB_API_KEY should satisfy a remote connection");
assert_eq!(header.as_deref(), Some("env-api-key"));
}
);
#[cfg(feature = "remote")]
lancedb_api_key_test!(
test_connect_remote_lancedb_api_key_explicit_wins,
Some("env-api-key"),
{
let header = remote_api_key_header(Some("explicit-api-key"))
.await
.expect("explicit api_key should still connect");
assert_eq!(header.as_deref(), Some("explicit-api-key"));
}
);
#[cfg(feature = "remote")]
lancedb_api_key_test!(
test_connect_remote_empty_lancedb_api_key_sends_no_header,
Some(""),
{
// Python uses `api_key is None`, so an empty LANCEDB_API_KEY is present.
let header = remote_api_key_header(None)
.await
.expect("an empty LANCEDB_API_KEY should still connect");
assert_eq!(header, None);
}
);
#[cfg(feature = "remote")]
lancedb_api_key_test!(
test_connect_remote_lancedb_api_key_required_when_unset,
None,
{
let result = connect("db://my-db").region("us-east-1").execute().await;
match result {
Err(Error::InvalidInput { message })
if message
== "An api_key or oauth_config is required when connecting to LanceDB Enterprise or LanceDB Cloud" =>
{}
Err(err) => panic!("expected missing api key error, got {err:?}"),
Ok(_) => panic!("expected missing api key error, got a connection"),
}
}
);
#[cfg(feature = "remote")]
lancedb_api_key_test!(
test_connect_remote_lancedb_api_key_ignored_for_oauth,
Some("env-api-key"),
{
let oauth_config = crate::remote::OAuthConfig {
issuer_url: "https://issuer.example.com".to_string(),
client_id: "client-id".to_string(),
client_secret: Some("secret".to_string()),
scopes: vec!["scope".to_string()],
flow: crate::remote::OAuthFlow::ClientCredentials,
client_auth_method: None,
refresh_buffer_secs: None,
resource: None,
audience: None,
token_cache: None,
};
connect("db://my-db")
.region("us-east-1")
.host_override("https://example.com")
.oauth_config(oauth_config)
.execute()
.await
.expect("oauth_config should connect without consuming LANCEDB_API_KEY");
}
);
#[cfg(feature = "remote")]
#[test]
fn test_apply_env_defaults() {