Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(server): require an API key to serve the Local API beyond 127.0.0.1 (#9505)

Thinh Le7890e4189ad6
diff --git a/docs/src/pages/docs/desktop/api-server.mdx b/docs/src/pages/docs/desktop/api-server.mdx
index 72606fc15..2611a05d1 100644
--- a/docs/src/pages/docs/desktop/api-server.mdx
+++ b/docs/src/pages/docs/desktop/api-server.mdx
@@ -57,7 +57,7 @@ These settings control the network accessibility and basic behavior of your loca
### Server Host
The network address the server listens on.
- **`127.0.0.1`** (Default): The server is only accessible from your own computer. This is the most secure option for personal use.
-- **`0.0.0.0`**: The server is accessible from other devices on your local network (e.g., your phone or another computer). Use this with caution.
+- **`0.0.0.0`**: The server is accessible from other devices on your local network (e.g., your phone or another computer). Jan will not start it on this address unless an [API key](#api-key) is set.
### Server Port
The port number for the API server.
@@ -72,7 +72,7 @@ The base path for all API endpoints.
### API Key
A secret key used to authenticate requests.
- Set any string (e.g., `a-secure-password`). If a key is configured, requests must include it in the `Authorization: Bearer YOUR_API_KEY` header.
-- Leave the field empty to disable authentication (not recommended when binding to `0.0.0.0`).
+- Leave the field empty to disable authentication. This only works with the default `127.0.0.1` host: Jan refuses to start the server on `0.0.0.0` (or any address other than your own computer) without a key.
### Trusted Hosts
A comma-separated list of hostnames allowed to access the server. This provides an additional layer of security when the server is exposed on your network.
diff --git a/src-tauri/src/core/server/proxy.rs b/src-tauri/src/core/server/proxy.rs
index a96d0d458..ae00bd80b 100644
--- a/src-tauri/src/core/server/proxy.rs
+++ b/src-tauri/src/core/server/proxy.rs
@@ -2403,9 +2403,14 @@ async fn proxy_request(
}
/// True when this bind exposes the API to the network with no authentication:
-/// a non-loopback host and an empty API key.
+/// a non-loopback host and an empty API key. Every loopback address is safe
+/// (127.0.0.0/8, ::1, "localhost"): only this machine can reach it.
fn is_insecure_public_bind(host: &str, api_key: &str) -> bool {
- let is_loopback = matches!(host, "127.0.0.1" | "localhost" | "::1");
+ let is_loopback = host == "localhost"
+ || host
+ .trim_matches(['[', ']'])
+ .parse::<std::net::IpAddr>()
+ .is_ok_and(|ip| ip.is_loopback());
!is_loopback && api_key.is_empty()
}
@@ -2545,8 +2550,18 @@ async fn start_server_internal(
// and private-range IP literals, which is safe against DNS rebinding (that sends an
// attacker *hostname*, not an IP). Hostnames still require an explicit allowlist entry.
- // Calculate this before proxy_api_key is moved into ProxyConfig.
- let insecure_public_bind = is_insecure_public_bind(&host, &proxy_api_key);
+ // Security: a non-loopback bind exposes the OpenAI-compatible API on the
+ // network, and with no API key any reachable host could call it
+ // unauthenticated (inference, model enumeration and, when enabled, MCP tool
+ // execution). Refuse before binding rather than serve it open.
+ if is_insecure_public_bind(&host, &proxy_api_key) {
+ return Err(format!(
+ "The API server is set to listen on {host}, which other devices on the network \
+ can reach, but no API key is set. Set an API key in Settings > Local API Server, \
+ or switch the host to 127.0.0.1."
+ )
+ .into());
+ }
let config = ProxyConfig {
prefix,
@@ -2573,19 +2588,6 @@ async fn start_server_internal(
};
log::info!("Jan API server started on http://{addr}");
- // Security: binding to a non-loopback interface exposes the OpenAI-compatible
- // API on the network. With no API key set, any reachable host can call it
- // unauthenticated (model inference, model enumeration, and MCP tool execution
- // when enabled). Warn loudly rather than refuse to start, so existing
- // trusted-LAN setups keep working, but the operator is told.
- if insecure_public_bind {
- log::warn!(
- "Jan API server is bound to a non-loopback address ({host}) with no API key set. \
- The local API is reachable UNAUTHENTICATED by any host that can reach this machine. \
- Set an API key in Settings > Local API Server to require authentication."
- );
- }
-
let server_task = tokio::spawn(async move {
loop {
let (stream, _) = match listener.accept().await {
@@ -3079,17 +3081,18 @@ mod tests {
use std::net::SocketAddr;
#[test]
- fn loopback_never_warns() {
- for host in ["127.0.0.1", "localhost", "::1"] {
+ fn loopback_hosts_need_no_key() {
+ for host in ["127.0.0.1", "127.0.0.2", "localhost", "::1", "[::1]"] {
assert!(!is_insecure_public_bind(host, ""), "{host} should be safe");
assert!(!is_insecure_public_bind(host, "secret"));
}
}
#[test]
- fn public_bind_without_key_warns() {
- assert!(is_insecure_public_bind("0.0.0.0", ""));
- assert!(is_insecure_public_bind("192.168.1.10", ""));
+ fn public_bind_without_key_is_insecure() {
+ for host in ["0.0.0.0", "192.168.1.10", "::", "10.0.0.5"] {
+ assert!(is_insecure_public_bind(host, ""), "{host} should need a key");
+ }
}
#[test]
diff --git a/src-tauri/src/core/server/tests.rs b/src-tauri/src/core/server/tests.rs
index 38a87f783..a40dde81b 100644
--- a/src-tauri/src/core/server/tests.rs
+++ b/src-tauri/src/core/server/tests.rs
@@ -1446,4 +1446,44 @@ mod server_tests {
);
proxy::stop_server(handle).await.unwrap();
}
+
+ #[tokio::test]
+ async fn public_bind_without_api_key_is_refused_before_binding() {
+ use std::collections::HashMap;
+ use std::sync::Arc;
+ use tokio::sync::Mutex;
+
+ let port = std::net::TcpListener::bind("127.0.0.1:0")
+ .unwrap()
+ .local_addr()
+ .unwrap()
+ .port();
+ let handle = Arc::new(Mutex::new(None));
+ let err = proxy::start_server(
+ handle.clone(),
+ Arc::new(tauri_plugin_llamacpp::state::LlamacppState::default()),
+ Arc::new(Mutex::new(HashMap::new())),
+ "0.0.0.0".to_string(),
+ port,
+ "/v1".to_string(),
+ String::new(),
+ vec![vec![]],
+ 30,
+ Arc::new(Mutex::new(HashMap::new())),
+ Arc::new(Mutex::new(HashMap::new())),
+ Arc::new(Mutex::new(HashMap::new())),
+ Arc::new(Mutex::new(crate::core::mcp::models::McpSettings::default())),
+ std::env::temp_dir().to_string_lossy().into_owned(),
+ false,
+ true,
+ )
+ .await
+ .expect_err("an open public bind must be refused");
+
+ let msg = err.to_string();
+ assert!(msg.contains("API key") && msg.contains("127.0.0.1"), "{msg}");
+ // Nothing was started and nothing is listening.
+ assert!(handle.lock().await.is_none());
+ assert!(std::net::TcpListener::bind(("127.0.0.1", port)).is_ok());
+ }
}
diff --git a/web-app/src/routes/settings/__tests__/local-api-server.test.tsx b/web-app/src/routes/settings/__tests__/local-api-server.test.tsx
new file mode 100644
index 000000000..90536b8e3
--- /dev/null
+++ b/web-app/src/routes/settings/__tests__/local-api-server.test.tsx
@@ -0,0 +1,97 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+import { render, screen, fireEvent, waitFor } from '@testing-library/react'
+import { Route as LocalApiServerRoute } from '../local-api-server'
+import { useLocalApiServer } from '@/hooks/useLocalApiServer'
+import { useAppState } from '@/hooks/useAppState'
+import { toast } from 'sonner'
+
+const ensureModelForServer = vi.hoisted(() => vi.fn())
+const startServer = vi.hoisted(() => vi.fn())
+// One stable object: the page re-runs an effect whenever the hub identity changes.
+const hub = vi.hoisted(() => ({
+ models: () => ({ getActiveModels: () => Promise.resolve([]) }),
+ app: () => ({ getServerStatus: () => Promise.resolve(false) }),
+ window: () => ({ openLocalApiServerLogsWindow: () => Promise.resolve() }),
+}))
+
+vi.mock('@/utils/ensureModelForServer', () => ({ ensureModelForServer }))
+
+vi.mock('@/hooks/useServiceHub', () => ({
+ useServiceHub: () => hub,
+}))
+
+vi.mock('@/i18n/react-i18next-compat', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}))
+
+vi.mock('@/containers/SettingsMenu', () => ({ default: () => null }))
+vi.mock('@/containers/HeaderPage', () => ({
+ default: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+}))
+vi.mock('@/containers/ServerHostSwitcher', () => ({ ServerHostSwitcher: () => null }))
+vi.mock('@/containers/PortInput', () => ({ PortInput: () => null }))
+vi.mock('@/containers/ProxyTimeoutInput', () => ({ ProxyTimeoutInput: () => null }))
+vi.mock('@/containers/ApiPrefixInput', () => ({ ApiPrefixInput: () => null }))
+vi.mock('@/containers/TrustedHostsInput', () => ({ TrustedHostsInput: () => null }))
+vi.mock('@/components/LogViewer', () => ({ LogViewer: () => null }))
+vi.mock('@/containers/ApiKeyInput', () => ({ ApiKeyInput: () => null }))
+vi.mock('sonner', () => ({
+ toast: { info: vi.fn(), error: vi.fn(), dismiss: vi.fn() },
+}))
+
+const Page = LocalApiServerRoute.options.component as React.ComponentType
+
+function clickStart() {
+ fireEvent.click(screen.getByText('settings:localApiServer.startServer'))
+}
+
+describe('Local API server page: starting on a public address', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ ensureModelForServer.mockResolvedValue({ status: 'loaded' })
+ startServer.mockResolvedValue(1337)
+ ;(window as unknown as { core: unknown }).core = { api: { startServer } }
+ useAppState.setState({ serverStatus: 'stopped' })
+ })
+
+ it.each(['', ' '])(
+ 'asks for an API key instead of loading a model when the host is 0.0.0.0 and the key is %j',
+ (apiKey) => {
+ useLocalApiServer.setState({ serverHost: '0.0.0.0', apiKey })
+ render(<Page />)
+
+ clickStart()
+
+ expect(toast.error).toHaveBeenCalledTimes(1)
+ expect(vi.mocked(toast.error).mock.calls[0][1]?.description).toContain('0.0.0.0')
+ expect(ensureModelForServer).not.toHaveBeenCalled()
+ expect(startServer).not.toHaveBeenCalled()
+ expect(useAppState.getState().serverStatus).toBe('stopped')
+ }
+ )
+
+ it('starts on 0.0.0.0 once a key is set', async () => {
+ useLocalApiServer.setState({ serverHost: '0.0.0.0', apiKey: 'secret' })
+ render(<Page />)
+
+ clickStart()
+
+ await waitFor(() => expect(startServer).toHaveBeenCalledTimes(1))
+ expect(startServer.mock.calls[0][0]).toMatchObject({
+ host: '0.0.0.0',
+ apiKey: 'secret',
+ })
+ expect(toast.error).not.toHaveBeenCalled()
+ })
+
+ it('still starts on 127.0.0.1 with no key', async () => {
+ useLocalApiServer.setState({ serverHost: '127.0.0.1', apiKey: '' })
+ render(<Page />)
+
+ clickStart()
+
+ await waitFor(() => expect(startServer).toHaveBeenCalledTimes(1))
+ expect(startServer.mock.calls[0][0]).toMatchObject({ host: '127.0.0.1' })
+ expect(toast.error).not.toHaveBeenCalled()
+ })
+})
diff --git a/web-app/src/routes/settings/local-api-server.tsx b/web-app/src/routes/settings/local-api-server.tsx
index e3529c2a3..960006475 100644
--- a/web-app/src/routes/settings/local-api-server.tsx
+++ b/web-app/src/routes/settings/local-api-server.tsx
@@ -114,20 +114,25 @@ function LocalAPIServerContent() {
const [isModelLoading, setIsModelLoading] = useState(false)
const toggleAPIServer = async () => {
- // Validate API key before starting server
if (serverStatus === 'stopped') {
+ // The backend refuses to serve an open API on a non-loopback host, since
+ // any device on the network could use it. Say so here, before a model
+ // starts loading for a server that will not start. The key field lives
+ // in the configuration popover, so a toast carries the message.
+ if (serverHost !== '127.0.0.1' && !apiKey?.toString().trim()) {
+ setShowApiKeyError(true)
+ toast.error(t('common:apiKeyRequired'), {
+ description: `Set an API key in Configuration before listening on ${serverHost}, or switch the host to 127.0.0.1.`,
+ })
+ return
+ }
+ setShowApiKeyError(false)
+
console.log('Starting server with port:', serverPort)
toast.info('Starting server...', {
description: `Attempting to start server on port ${serverPort}`,
})
- // if (!apiKey || apiKey.toString().trim().length === 0) {
- // setShowApiKeyError(true)
- // return
- // }
-
- setShowApiKeyError(false)
-
setServerStatus('pending')
ensureModelForServer({