Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat: OIDC and LDAP as new auth mode for OpenViking (#3708)

MaojiaSheng444cc87bf840
diff --git a/README.md b/README.md
index c3d7be301..fa63495b2 100644
--- a/README.md
+++ b/README.md
@@ -211,7 +211,6 @@ OpenViking welcomes collaboration with other open-source projects to build the c
- [NoKV](https://github.com/NoKV-Lab/NoKV) - AI native distributed file system
- [loopx](https://github.com/huangruiteng/loopx) - Lightweight loop engineering state kernel
- [Hermes Agent](https://github.com/NousResearch/hermes-agent) - The agent that grows with you
-- [heima](https://github.com/litentry/heima) - Substrate-based EVM-compatible L1 chain
Interested in joining our partner list? Please submit an issue to our community to apply.
diff --git a/README_CN.md b/README_CN.md
index 842c4d7f3..a2a87bcef 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -220,7 +220,6 @@ OpenViking 欢迎与其他开源项目合作建设上下文数据生态。目前
- [NoKV](https://github.com/NoKV-Lab/NoKV) - AI 原生的分布式文件系统
- [loopx](https://github.com/huangruiteng/loopx) - 轻量级循环工程状态内核
- [Hermes Agent](https://github.com/NousResearch/hermes-agent) - 与用户共同成长的智能体
-- [heima](https://github.com/litentry/heima) - 基于 Substrate 的 EVM 兼容 L1 链
有兴趣加入我们的合作伙伴列表?请在社区提交 issue 来申请加入。
diff --git a/README_JA.md b/README_JA.md
index 05271c301..1677f1647 100644
--- a/README_JA.md
+++ b/README_JA.md
@@ -220,7 +220,6 @@ OpenViking は、コンテキストデータエコシステムを構築するた
- [NoKV](https://github.com/NoKV-Lab/NoKV) - AI ネイティブの分散ファイルシステム
- [loopx](https://github.com/huangruiteng/loopx) - 軽量なループエンジニアリング状態カーネル
- [Hermes Agent](https://github.com/NousResearch/hermes-agent) - あなたと共に成長するエージェント
-- [heima](https://github.com/litentry/heima) - Substrate ベースの EVM 互換 L1 チェーン
パートナーリストへの参加に興味がありますか?コミュニティに issue を提出して申請してください。
diff --git a/bot/vikingbot/config/loader.py b/bot/vikingbot/config/loader.py
index a201de1a1..e268ad910 100644
--- a/bot/vikingbot/config/loader.py
+++ b/bot/vikingbot/config/loader.py
@@ -302,12 +302,17 @@ def _bot_auth_mode_from_api_key_type(api_key_type: str, server_auth_mode: str) -
return "trusted"
if server_auth_mode == "dev":
return "dev"
+ # Preserve external-auth modes inherited from the server config so that
+ # downstream code can produce a clear "unsupported with bot" error instead
+ # of silently treating them as api_key.
+ if server_auth_mode in {"oidc", "ldap"}:
+ return server_auth_mode
return "api_key"
def _ov_server_auth_mode(ov_server: Any) -> str:
effective_auth_mode = str(getattr(ov_server, "effective_auth_mode", "") or "").strip().lower()
- if effective_auth_mode in {"trusted", "api_key", "dev"}:
+ if effective_auth_mode in {"trusted", "api_key", "dev", "oidc", "ldap"}:
return effective_auth_mode
api_key_type = _normalize_api_key_type(getattr(ov_server, "api_key_type", "user"))
@@ -746,6 +751,20 @@ def validate_openviking_auth(config: Config) -> None:
if auth_mode == "dev":
_validate_dev_boundary(config, server_url)
return
+ if auth_mode in {"oidc", "ldap"}:
+ # External-auth modes are not yet wired through VikingBot's tool
+ # credential propagation. Fail fast with an actionable message
+ # instead of silently defaulting to api_key and then 401-ing.
+ print(
+ f"Error: OpenViking server at {server_url} is running in "
+ f"'{auth_mode}' auth mode, which is not supported by "
+ "VikingBot yet.\n"
+ f"Either switch the server to a supported auth mode "
+ "(trusted, api_key, dev) or start openviking-server without "
+ "the --with-bot flag.",
+ file=sys.stderr,
+ )
+ raise SystemExit(1)
return
diff --git a/crates/ov_cli/src/base_client.rs b/crates/ov_cli/src/base_client.rs
index 1ec99b733..5110c9708 100644
--- a/crates/ov_cli/src/base_client.rs
+++ b/crates/ov_cli/src/base_client.rs
@@ -189,6 +189,10 @@ pub struct BaseClient {
pub(crate) profile_enabled: bool,
pub(crate) extra_headers: Option<std::collections::HashMap<String, String>>,
gateway_token: Option<String>,
+ auth_mode: Option<String>,
+ ldap_username: Option<String>,
+ ldap_password: Option<String>,
+ oidc_token: Option<String>,
}
impl BaseClient {
@@ -217,9 +221,35 @@ impl BaseClient {
profile_enabled,
extra_headers,
gateway_token: None,
+ auth_mode: None,
+ ldap_username: None,
+ ldap_password: None,
+ oidc_token: None,
}
}
+ pub fn with_auth_mode(mut self, auth_mode: Option<String>) -> Self {
+ self.auth_mode = auth_mode;
+ self
+ }
+
+ pub fn with_ldap_username(mut self, username: Option<String>) -> Self {
+ self.ldap_username = username;
+ self
+ }
+
+ pub fn with_ldap_password(mut self, password: Option<String>) -> Self {
+ self.ldap_password = password;
+ self
+ }
+
+ pub fn with_oidc_token(mut self, token: Option<String>) -> Self {
+ self.oidc_token = token
+ .map(|t| t.trim().to_string())
+ .filter(|t| !t.is_empty());
+ self
+ }
+
pub fn with_gateway_token(mut self, gateway_token: Option<String>) -> Self {
self.gateway_token = gateway_token
.map(|token| token.trim().to_string())
@@ -273,6 +303,53 @@ impl BaseClient {
headers.insert("X-OpenViking-Actor-Peer", value);
}
}
+
+ // LDAP Basic Auth support
+ if let (Some(auth_mode), Some(username), Some(password)) =
+ (&self.auth_mode, &self.ldap_username, &self.ldap_password)
+ {
+ if auth_mode == "ldap" {
+ let credentials = format!("{}:{}", username, password);
+ use base64::engine::Engine;
+ use base64::engine::general_purpose;
+ let encoded = general_purpose::STANDARD.encode(credentials);
+ if let Ok(value) =
+ reqwest::header::HeaderValue::from_str(&format!("Basic {}", encoded))
+ {
+ headers.insert(reqwest::header::AUTHORIZATION, value);
+ }
+ }
+ }
+
+ // OIDC Bearer Token support
+ if let (Some(auth_mode), Some(token)) = (&self.auth_mode, &self.oidc_token) {
+ if auth_mode == "oidc" {
+ if let Ok(value) =
+ reqwest::header::HeaderValue::from_str(&format!("Bearer {}", token))
+ {
+ headers.insert(reqwest::header::AUTHORIZATION, value);
+ }
+ }
+ }
+
+ // Also support OIDC token when api_key looks like a JWT (for backwards compatibility)
+ if self
+ .api_key
+ .as_ref()
+ .map_or(false, |k| k.contains('.') && k.matches('.').count() >= 2)
+ {
+ if let Some(token) = &self.api_key {
+ if let Ok(value) =
+ reqwest::header::HeaderValue::from_str(&format!("Bearer {}", token))
+ {
+ // Only insert if not already set by explicit OIDC
+ if !headers.contains_key(reqwest::header::AUTHORIZATION) {
+ headers.insert(reqwest::header::AUTHORIZATION, value);
+ }
+ }
+ }
+ }
+
if let Some(extra_headers) = &self.extra_headers {
for (key, value) in extra_headers {
if let Ok(header_name) = reqwest::header::HeaderName::from_str(key) {
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rs
index 084518a9f..e14a39f6c 100644
--- a/crates/ov_cli/src/client.rs
+++ b/crates/ov_cli/src/client.rs
@@ -204,6 +204,26 @@ impl HttpClient {
self
}
+ pub fn with_auth_mode(mut self, auth_mode: Option<String>) -> Self {
+ self.base = self.base.with_auth_mode(auth_mode);
+ self
+ }
+
+ pub fn with_ldap_username(mut self, username: Option<String>) -> Self {
+ self.base = self.base.with_ldap_username(username);
+ self
+ }
+
+ pub fn with_ldap_password(mut self, password: Option<String>) -> Self {
+ self.base = self.base.with_ldap_password(password);
+ self
+ }
+
+ pub fn with_oidc_token(mut self, token: Option<String>) -> Self {
+ self.base = self.base.with_oidc_token(token);
+ self
+ }
+
pub fn user_id(&self) -> Option<&str> {
self.base.user_id()
}
diff --git a/crates/ov_cli/src/config.rs b/crates/ov_cli/src/config.rs
index 7c3545613..1503e3ef6 100644
--- a/crates/ov_cli/src/config.rs
+++ b/crates/ov_cli/src/config.rs
@@ -88,6 +88,16 @@ pub struct Config {
pub extra_headers: Option<HashMap<String, String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub gateway_token: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub auth_mode: Option<String>,
+ /// LDAP username for authentication.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub ldap_username: Option<String>,
+ /// LDAP password for authentication.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub ldap_password: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub oidc_token: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -185,6 +195,10 @@ impl Default for Config {
upload: UploadConfig::default(),
extra_headers: None,
gateway_token: None,
+ auth_mode: None,
+ ldap_username: None,
+ ldap_password: None,
+ oidc_token: None,
}
}
}
diff --git a/crates/ov_cli/src/health_ui.rs b/crates/ov_cli/src/health_ui.rs
index a3727d83e..9e954060f 100644
--- a/crates/ov_cli/src/health_ui.rs
+++ b/crates/ov_cli/src/health_ui.rs
@@ -173,6 +173,13 @@ fn identity_field<'a>(
fn format_auth_mode(value: Option<&str>, language: Language) -> String {
match value {
Some("api_key") => "API key".to_string(),
+ Some("oidc") => "OIDC".to_string(),
+ Some("ldap") => "LDAP".to_string(),
+ Some("trusted") => "Trusted".to_string(),
+ Some("dev") => match language {
+ Language::En => "Dev".to_string(),
+ Language::ZhCn => "开发模式".to_string(),
+ },
Some("none") => match language {
Language::En => "None".to_string(),
Language::ZhCn => "无".to_string(),
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs
index 126b5610d..35a6a6ad8 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -94,7 +94,7 @@ impl CliContext {
pub fn get_client_with_timeout(&self, timeout_secs: Option<f64>) -> client::HttpClient {
let auth = self.config.effective_auth(self.sudo);
- client::HttpClient::new(
+ let mut client = client::HttpClient::new(
&self.config.url,
auth.api_key,
auth.account,
@@ -104,7 +104,34 @@ impl CliContext {
self.profile.unwrap_or(self.config.profile),
self.config.effective_extra_headers(),
)
- .with_gateway_token(self.config.effective_gateway_token())
+ .with_gateway_token(self.config.effective_gateway_token());
+
+ // Add LDAP or OIDC authentication if configured
+ if let Some(auth_mode) = &self.config.auth_mode {
+ match auth_mode.as_str() {
+ "ldap" => {
+ client = client.with_auth_mode(Some("ldap".to_string()));
+ if let Some(ldap_username) = &self.config.ldap_username {
+ client = client.with_ldap_username(Some(ldap_username.clone()));
+ }
+ if let Some(ldap_password) = &self.config.ldap_password {
+ client = client.with_ldap_password(Some(ldap_password.clone()));
+ }
+ }
+ "oidc" => {
+ client = client.with_auth_mode(Some("oidc".to_string()));
+ if let Some(token) = &self.config.oidc_token {
+ client = client.with_oidc_token(Some(token.clone()));
+ } else if let Some(api_key) = &self.config.api_key {
+ // Fallback: use api_key as OIDC token if it looks like a JWT
+ client = client.with_oidc_token(Some(api_key.clone()));
+ }
+ }
+ _ => {}
+ }
+ }
+
+ client
}
}
diff --git a/docs/en/guides/04-authentication.md b/docs/en/guides/04-authentication.md
index b89a767b1..c95c9adde 100644
--- a/docs/en/guides/04-authentication.md
+++ b/docs/en/guides/04-authentication.md
@@ -1,28 +1,18 @@
# Authentication
-OpenViking Server supports three built-in authentication modes with role-based access control: `api_key`, `trusted`, and `dev`. The mode is auto-detected if not explicitly configured. In addition, custom authentication plugins can be registered to support arbitrary identity sources (e.g., LDAP, OIDC, mTLS).
+OpenViking Server supports multiple built-in authentication modes with role-based access control. The mode is auto-detected if not explicitly configured. In addition, custom authentication plugins can be registered to support arbitrary identity sources.
-## Overview
+> **Recommended:** API Key mode is the most common and secure default choice, suitable for most deployment scenarios.
-OpenViking uses a two-layer API key system:
+## Authentication Modes Overview
-| Key Type | Created By | Role | Purpose |
-|----------|-----------|------|---------|
-| Root Key | Server config (`root_api_key`) | ROOT | Account management + selected system/monitoring operations |
-| User Key | Admin API | ADMIN or USER | Per-account data access; ADMIN can also manage users in its account |
-
-User keys are generated by the Admin API. By default they use random secret
-material; Admin API callers may also provide a `seed` to derive a predictable
-key secret from `sha256(user_id + "\0" + seed)`. The server still verifies the
-resulting key against the stored key or key hash.
-
-## Authentication Modes
-
-| Mode | `server.auth_mode` | Identity Source | Typical Use |
-|------|--------------------|-----------------|-------------|
-| API key mode | `"api_key"` | API key. Data ownership is resolved from the user/admin key. | Standard multi-tenant deployment |
-| Trusted mode | `"trusted"` | `X-OpenViking-Account` / `X-OpenViking-User`, plus `root_api_key` on non-localhost deployments. Role is looked up from APIKeyManager if the user exists. | Behind a trusted gateway or internal network boundary |
-| Dev mode | `"dev"` | No authentication, always ROOT | Local development only |
+| Mode | `server.auth_mode` | Identity Source | Typical Use | Recommendation |
+|------|--------------------|-----------------|-------------|----------------|
+| **API Key Mode** ⭐ | `api_key` | API key. Data ownership is resolved from the user/admin key. | Standard multi-tenant deployment | ⭐⭐⭐⭐⭐ |
+| **OIDC Mode** | `oidc` | JWT tokens from external identity providers | Enterprise SSO integration with Okta/Auth0/Keycloak | ⭐⭐⭐⭐ |
+| **LDAP Mode** | `ldap` | Enterprise LDAP/AD directory services | Integrate with existing enterprise user directory | ⭐⭐⭐⭐ |
+| **Trusted Mode** | `trusted` | `X-OpenViking-Account` / `X-OpenViking-User`, plus `root_api_key` on non-localhost deployments. Role is looked up from APIKeyManager if the user exists. | Behind a trusted gateway or internal network boundary | ⭐⭐⭐ |
+| **Dev Mode** | `dev` | No authentication, always ROOT | Local development only | ⭐⭐ |
If `auth_mode` is not explicitly configured:
- If `root_api_key` is set (non-empty): auto-selects `api_key` mode
@@ -30,7 +20,11 @@ If `auth_mode` is not explicitly configured:
> **Note:** Setting `root_api_key` to an empty string `""` is invalid. Either set a non-empty value or remove the setting entirely.
-## Setting Up (Server Side)
+## Quick Start: API Key Mode (Recommended)
+
+API Key mode is the most secure and easiest default choice.
+
+### Configuration
Configure the authentication mode in the `server` section of `ov.conf`:
@@ -43,66 +37,22 @@ Configure the authentication mode in the `server` section of `ov.conf`:
}
```
-Start the server:
+### Start the Server
```bash
openviking-server
```
-### Custom Authentication Plugins
-
-The server uses a plugin-based auth architecture. Each `auth_mode` maps to an `AuthPlugin` implementation. Built-in plugins (`dev`, `api_key`, `trusted`) are auto-registered; third-party plugins can be added by subclassing `AuthPlugin` and registering it before startup.
-
-**Plugin interface (`openviking.server.auth.plugin.AuthPlugin`)**
-
-| Method | Purpose |
-|--------|---------|
-| `resolve_identity(request, api_key, x_openviking_account, x_openviking_user)` | Resolve credentials to a `ResolvedIdentity`. |
-| `validate_config(config)` | Validate `ServerConfig` at startup; should `sys.exit(1)` on fatal misconfiguration. |
-| `initialize(app, service, config)` | Initialize runtime state (e.g., `APIKeyManager`) on `app.state`. |
-| `get_request_context_checks(path, identity)` | Optional post-auth path/identity checks. |
-| `requires_api_key_manager()` | Whether Admin API routes need an `APIKeyManager`. |
-| `can_skip_api_key_for_bot_proxy()` | Whether the bot proxy may skip API key validation (e.g., `dev` mode). |
-
-**Register a custom plugin**
+### Two-Layer API Key System
-```python
-from openviking.server.auth.plugin import AuthPlugin
-from openviking.server.auth.registry import register_auth_plugin
-from openviking.server.identity import ResolvedIdentity, Role
-
-@register_auth_plugin
-class LDAPAuthPlugin(AuthPlugin):
- auth_mode = "ldap"
-
- async def resolve_identity(self, request, *, api_key=None, x_openviking_account=None, x_openviking_user=None):
- # ... LDAP bind and identity resolution ...
- return ResolvedIdentity(role=Role.USER, account_id="...", user_id="...")
-
- def validate_config(self, config):
- pass
-
- async def initialize(self, app, service, config):
- pass
-```
-
-Then set `server.auth_mode = "ldap"` in `ov.conf`.
-
-**Custom roles**
-
-The built-in `Role` class supports dynamic registration of custom roles with privilege ranks:
-
-```python
-from openviking.server.identity import Role
-
-Role.register("operator", rank=1) # Between USER (0) and ADMIN (1)
-```
-
-Custom roles work with `require_role()` and `require_auth_role()` decorators out of the box.
+| Key Type | Created By | Role | Purpose |
+|----------|-----------|------|---------|
+| Root Key | Server config (`root_api_key`) | ROOT | Account management + selected system/monitoring operations |
+| User Key | Admin API | ADMIN or USER | Per-account data access; ADMIN can also manage users in its account |
-## Managing Accounts and Users
+User keys are generated by the Admin API. By default they use random secret material; Admin API callers may also provide a `seed` to derive a predictable key secret from `sha256(user_id + "\0" + seed)`. The server still verifies the resulting key against the stored key or key hash.
-Normal requests in both `api_key` and `trusted` modes do not need Admin API as a prerequisite for ordinary reads, writes, search, or session access. Admin API is still the place to create accounts, register users, promote users to admin, and issue or regenerate user keys.
+### Managing Accounts and Users
Use the root key to create accounts (workspaces) and users via the Admin API:
@@ -122,33 +72,7 @@ curl -X POST http://localhost:1933/api/v1/admin/accounts/acme/users \
# Returns: {"result": {"account_id": "acme", "user_id": "bob", "user_key": "..."}}
```
-Trusted deployments can also call Admin API through a trusted gateway. There are two supported patterns:
-
-- Present the trusted deployment's `root_api_key`. For `/api/v1/admin/*`, the server treats the request as ROOT after validating that key.
-- Optionally also present `X-OpenViking-Account` + `X-OpenViking-User` when the admin route targets a specific account/user. Those headers must match the target URL and are kept as the request identity, but authorization still comes from the trusted `root_api_key`.
-
-Example using a trusted upstream identity:
-
-```bash
-# First, register the gateway admin (do this once in api_key mode)
-curl -X POST http://localhost:1933/api/v1/admin/accounts \
- -H "X-API-Key: your-secret-root-key" \
- -H "Content-Type: application/json" \
- -d '{"account_id": "platform", "admin_user_id": "gateway-admin"}'
-
-# Then use that identity in trusted mode; admin authorization comes from root_api_key
-curl -X POST http://localhost:1933/api/v1/admin/accounts \
- -H "X-API-Key: your-secret-root-key" \
- -H "X-OpenViking-Account: platform" \
- -H "X-OpenViking-User: gateway-admin" \
- -H "Content-Type: application/json" \
- -d '{
- "account_id": "acme",
- "admin_user_id": "alice"
- }'
-```
-
-## Using API Keys (Client Side)
+### Client Usage
OpenViking accepts API keys via two headers:
@@ -159,7 +83,7 @@ curl http://localhost:1933/api/v1/fs/ls?uri=viking:// \
-H "X-API-Key: <user-key>"
```
-**Authorization: Bearer header**
+**Authorization: Bearer ***
```bash
curl http://localhost:1933/api/v1/fs/ls?uri=viking:// \
@@ -186,9 +110,7 @@ client = ov.SyncHTTPClient(
}
```
-When you use a user key or admin key, the server derives `account` and `user`
-from the key. Do not send `X-OpenViking-Account` / `X-OpenViking-User` in
-`api_key` mode; those identity headers are accepted only in `trusted` mode.
+When you use a user key or admin key, the server derives `account` and `user` from the key. Do not send `X-OpenViking-Account` / `X-OpenViking-User` in `api_key` mode; those identity headers are accepted only in `trusted` mode.
**CLI override flags**
@@ -214,40 +136,365 @@ When you need to perform admin commands (`admin`, `system`, `reindex`), use the
# List all accounts (requires root privileges)
ov --sudo admin list-accounts
+# Reindex content
+ov --sudo reindex viking://
+
# System commands
ov --sudo system status
```
The `--sudo` flag:
-- Only works with management/system commands: `admin`, `system`
+- Only works with management/system commands: `admin`, `system`, `reindex`
- Will error if used with non-admin commands
- Will error if `root_api_key` is not configured in `ovcli.conf`
- Uses `root_api_key` instead of `api_key` for the request
### Tenant Data Access
-Tenant-scoped data APIs (for example `ls`, `find`, resources, and sessions)
-must use a key that is bound to an account/user in `api_key` mode. That can be
-a `USER` key or an `ADMIN` key; an `ADMIN` key accesses data as its own user and
-cannot switch identity with `X-OpenViking-Account` / `X-OpenViking-User`.
+Tenant-scoped data APIs (for example `ls`, `find`, resources, and sessions) must use a key that is bound to an account/user in `api_key` mode. That can be a `USER` key or an `ADMIN` key; an `ADMIN` key accesses data as its own user and cannot switch identity with `X-OpenViking-Account` / `X-OpenViking-User`.
-A `ROOT` key is not bound to a tenant user, so it cannot access tenant-scoped
-data APIs in `api_key` mode. If a deployment needs an upstream gateway to assert
-`account` / `user`, use `trusted` mode instead of passing identity headers with a
-root key.
+A `ROOT` key is not bound to a tenant user, so it cannot access tenant-scoped data APIs in `api_key` mode. If a deployment needs an upstream gateway to assert `account` / `user`, use `trusted` mode instead of passing identity headers with a root key.
-**ovcli.conf**
+## OIDC Authentication
+
+OIDC (OpenID Connect) authentication allows using JWT tokens from external identity providers (Okta, Auth0, Keycloak, Azure AD, etc.) for authentication.
+
+### Install Dependencies
+
+OIDC and LDAP authentication require optional dependencies. You can install them as:
+
+```bash
+# Install auth features only
+uv pip install openviking[auth]
+
+# Or install with all features (including bot)
+uv pip install openviking[bot]
+```
+
+### Configure OIDC
+
+Configure OIDC in `ov.conf`:
```json
{
- "url": "http://localhost:1933",
- "auth_mode": "trusted",
- "api_key": "your-trusted-server-key",
- "account": "acme",
- "user": "alice"
+ "server": {
+ "auth_mode": "oidc",
+ "oidc": {
+ "issuer": "https://your-oidc-provider.com/",
+ "client_id": "your-client-id",
+ "audience": "openviking",
+ "jwks_uri": "https://your-oidc-provider.com/.well-known/jwks.json",
+ "identity": {
+ "account_id": {
+ "mode": "organization",
+ "source": "claim",
+ "claim": "tenant_id",
+ "prefix": "org-",
+ "fallback": "default-org"
+ },
+ "user_id": {
+ "source": "claim",
+ "claim": "sub",
+ "prefix": "user-",
+ "normalize": "lowercase"
+ },
+ "role": {
+ "source": "claim",
+ "claim": "openviking_role",
+ "mapping": {
+ "admin": "admin",
+ "developer": "user"
+ },
+ "default": "user"
+ }
+ }
+ }
+ }
+}
+```
+
+### OIDC Configuration Options
+
+| Option | Description |
+|--------|-------------|
+| `issuer` | OIDC provider issuer URL (required) |
+| `client_id` | OIDC client ID (optional) |
+| `client_secret` | OIDC client secret (optional) |
+| `audience` | Audience to validate (optional) |
+| `jwks_uri` | JWKS URL, auto-discovered from issuer by default |
+| `token_location` | Token location: `header` (default) or `query` |
+| `token_header_name` | Header name, default `Authorization` |
+| `token_header_prefix` | Header prefix, default `Bearer ` |
+
+### Identity Mapping Configuration
+
+#### Account ID Mapping
+
+Two modes are supported:
+
+1. **Organization mode** (`mode: "organization"`) - entire organization shares one account
+
+```json
+{
+ "account_id": {
+ "mode": "organization",
+ "source": "claim",
+ "claim": "tenant_id"
+ }
+}
+```
+
+2. **Team mode** (`mode: "team"`) - isolation by team
+
+```json
+{
+ "account_id": {
+ "mode": "team",
+ "source": "claim",
+ "claim": "department",
+ "prefix": "team-"
+ }
+}
+```
+
+#### User ID Mapping
+
+```json
+{
+ "user_id": {
+ "source": "claim",
+ "claim": "sub",
+ "prefix": "user-",
+ "normalize": "lowercase"
+ }
+}
+```
+
+#### Role Mapping
+
+```json
+{
+ "role": {
+ "source": "claim",
+ "claim": "role",
+ "mapping": {
+ "administrator": "admin",
+ "developer": "user",
+ "viewer": "user"
+ },
+ "default": "user"
+ }
+}
+```
+
+### Advanced Mapping Features
+
+#### Composite Mapping
+
+```json
+{
+ "account_id": {
+ "source": "composite",
+ "parts": [
+ {"source": "claim", "claim": "tenant_id"},
+ {"literal": "-"},
+ {"source": "claim", "claim": "department"}
+ ]
+ }
+}
+```
+
+#### Regex Extraction
+
+```json
+{
+ "user_id": {
+ "source": "claim",
+ "claim": "email",
+ "regex": "^([^@]+)@",
+ "regex_group": 1
+ }
+}
+```
+
+#### Multiple Field Fallback
+
+```json
+{
+ "account_id": {
+ "source": "claim",
+ "claim": ["department", "team", "organization"],
+ "fallback": "default"
+ }
+}
+```
+
+### Using OIDC Authentication
+
+Clients carry the JWT token in requests:
+
+```bash
+curl https://openviking.example.com/api/v1/fs/ls?uri=viking:// \
+ -H "Authorization: Bearer eyJhbGciOiJSUzI1NiIs..."
+```
+
+## LDAP Authentication
+
+LDAP authentication allows using enterprise LDAP servers (Active Directory, OpenLDAP, etc.) for authentication.
+
+### Configure LDAP
+
+#### Using Search Bind (Recommended)
+
+```json
+{
+ "server": {
+ "auth_mode": "ldap",
+ "ldap": {
+ "host": "ldap.example.com",
+ "port": 636,
+ "use_ssl": true,
+ "use_starttls": false,
+ "bind_dn": "cn=openviking,dc=example,dc=com",
+ "bind_password": "${LDAP_BIND_PASSWORD}",
+ "base_dn": "dc=example,dc=com",
+ "user_search_filter": "(uid=%s)",
+ "username_attribute": "uid",
+ "email_attribute": "mail",
+ "name_attribute": "cn",
+ "identity": {
+ "account_id": {
+ "mode": "team",
+ "source": "dn_attribute",
+ "attribute": "ou",
+ "prefix": "team-",
+ "fallback": "default"
+ },
+ "user_id": {
+ "source": "attribute",
+ "attribute": "uid",
+ "normalize": "lowercase"
+ },
+ "role": {
+ "source": "group_membership",
+ "group_mapping": {
+ "cn=openviking-admins,ou=groups,dc=example,dc=com": "admin",
+ "cn=openviking-users,ou=groups,dc=example,dc=com": "user"
+ },
+ "default": "user"
+ }
+ }
+ }
+ }
}
```
+#### Using Direct Bind
+
+```json
+{
+ "server": {
+ "auth_mode": "ldap",
+ "ldap": {
+ "host": "ldap.example.com",
+ "port": 389,
+ "use_ssl": false,
+ "use_starttls": true,
+ "base_dn": "dc=example,dc=com",
+ "user_dn_pattern": "uid=%s,ou=users,dc=example,dc=com",
+ "identity": {
+ "account_id": {
+ "mode": "organization",
+ "source": "fixed",
+ "value": "my-company"
+ },
+ "user_id": {
+ "source": "attribute",
+ "attribute": "uid"
+ },
+ "role": {
+ "source": "fixed",
+ "value": "user"
+ }
+ }
+ }
+ }
+}
+```
+
+### LDAP Configuration Options
+
+| Option | Description |
+|--------|-------------|
+| `host` | LDAP server address (required) |
+| `port` | LDAP server port, default 389 |
+| `use_ssl` | Whether to use LDAPS (SSL), default false |
+| `use_starttls` | Whether to use StartTLS, default false |
+| `bind_dn` | Bind DN for user searches (recommended) |
+| `bind_password` | Bind password, supports environment variables |
+| `base_dn` | Base DN for searches (required) |
+| `user_search_filter` | User search filter, default `(uid=%s)` |
+| `user_search_base` | User search base DN, defaults to `base_dn` |
+| `username_attribute` | Username attribute, default `uid` |
+| `email_attribute` | Email attribute, default `mail` |
+| `name_attribute` | Name attribute, default `cn` |
+| `user_dn_pattern` | User DN pattern for direct bind |
+
+### LDAP Identity Mapping
+
+#### Extract Organizational Unit from DN
+
+```json
+{
+ "account_id": {
+ "mode": "team",
+ "source": "dn_attribute",
+ "attribute": "ou",
+ "prefix": "team-"
+ }
+}
+```
+
+#### Map from Attribute
+
+```json
+{
+ "account_id": {
+ "mode": "team",
+ "source": "attribute",
+ "attribute": "department",
+ "mapping": {
+ "Engineering": "eng-team",
+ "Sales": "sales-team"
+ }
+ }
+}
+```
+
+#### Role Mapping based on Group Membership
+
+```json
+{
+ "role": {
+ "source": "group_membership",
+ "group_mapping": {
+ "cn=admins,ou=groups,dc=example,dc=com": "admin",
+ "cn=users,ou=groups,dc=example,dc=com": "user"
+ },
+ "default": "user"
+ }
+}
+```
+
+### Using LDAP Authentication
+
+Clients submit credentials using Basic Auth:
+
+```bash
+curl https://openviking.example.com/api/v1/fs/ls?uri=viking:// \
+ -u alice:password123
+```
+
## Trusted Mode
Trusted mode skips user-key lookup and instead trusts explicit identity headers on each request:
@@ -261,28 +508,60 @@ Trusted mode skips user-key lookup and instead trusts explicit identity headers
}
```
-Rules in trusted mode:
+### Rules in Trusted Mode
- Normal data access does not require user registration or user-key provisioning first.
- `X-OpenViking-Account` and `X-OpenViking-User` are required on tenant-scoped requests.
- A trusted upstream may also send `X-OpenViking-Role: user` or `X-OpenViking-Role: admin` to assert the request role. This header is accepted only when `root_api_key` is configured and the request presents the matching API key. `root` is not an allowed asserted value; ROOT is reserved for validated Admin API fallback.
-- Use `peer_id` in session-message bodies for stable speaker attribution. Use `X-OpenViking-Actor-Peer` to filter the current user's peer collection for filesystem and retrieval operations.
- `/api/v1/admin/*` is special: when a configured `root_api_key` is presented, trusted mode treats the request as ROOT. Explicit account/user headers are allowed only when they are complete and match the target URL.
- For ordinary trusted data APIs, role is determined by `X-OpenViking-Role` when present and authorized; otherwise by looking up the account/user in APIKeyManager. If the user exists, their configured role is used; otherwise it defaults to `USER`.
- Trusted identity comes from the headers, not from a user key. If `root_api_key` is configured, it acts as proof that the caller is an approved trusted upstream.
- If `root_api_key` is also configured, every request must still provide a matching API key.
- Only expose this mode behind a trusted network boundary or an identity-injecting gateway.
-Implications:
+### Trusted Deployment Admin API
+
+Trusted deployments can also call Admin API through a trusted gateway. There are two supported patterns:
+
+1. Present the trusted deployment's `root_api_key`. For `/api/v1/admin/*`, the server treats the request as ROOT after validating that key.
+2. Optionally also present `X-OpenViking-Account` + `X-OpenViking-User` when the admin route targets a specific account/user. Those headers must match the target URL and are kept as the request identity, but authorization still comes from the trusted `root_api_key`.
+
+Example using a trusted upstream identity:
+
+```bash
+# First, register the gateway admin (do this once in api_key mode)
+curl -X POST http://localhost:1933/api/v1/admin/accounts \
+ -H "X-API-Key: your-secret-root-key" \
+ -H "Content-Type: application/json" \
+ -d '{"account_id": "platform", "admin_user_id": "gateway-admin"}'
+
+# Then use that identity in trusted mode; admin authorization comes from root_api_key
+curl -X POST http://localhost:1933/api/v1/admin/accounts \
+ -H "X-API-Key: your-secret-root-key" \
+ -H "X-OpenViking-Account: platform" \
+ -H "X-OpenViking-User: gateway-admin" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "account_id": "acme",
+ "admin_user_id": "alice"
+ }'
+```
+
+### Trusted Mode Client Configuration
+
+**ovcli.conf**
-- Trusted mode is not development mode.
-- Trusted mode does not use the Admin API as a prerequisite for ordinary reads, writes, search, or session access.
-- Admin API remains available in trusted mode to upstreams authenticated with the configured `root_api_key`.
-- Trusted Admin API responses omit `user_key` from account creation and user registration results.
-- `root` can create/delete accounts and promote users to admin; `admin` can manage and promote users inside its own account; `user` cannot call Admin API.
-- To use Admin API in trusted mode on non-localhost deployments, configure `root_api_key` and pass it with each admin request.
+```json
+{
+ "url": "http://localhost:1933",
+ "auth_mode": "trusted",
+ "api_key": "your-trusted-server-key",
+ "account": "acme",
+ "user": "alice"
+}
+```
-**curl**
+**curl Example**
```bash
curl http://localhost:1933/api/v1/fs/ls?uri=viking:// \
@@ -360,9 +639,159 @@ curl http://localhost:1933/health
| PUT | `/api/v1/admin/accounts/{id}/users/{uid}/role` | ROOT, ADMIN | Promote a user to ADMIN; ADMIN is limited to its own account |
| POST | `/api/v1/admin/accounts/{id}/users/{uid}/key` | ROOT, ADMIN | Regenerate user key |
+## Custom Authentication Plugins
+
+The server uses a plugin-based auth architecture. Each `auth_mode` maps to an `AuthPlugin` implementation. Built-in plugins (`dev`, `api_key`, `trusted`, `oidc`, `ldap`) are auto-registered; third-party plugins can be added by subclassing `AuthPlugin` and registering it before startup.
+
+### Plugin Interface (`openviking.server.auth.plugin.AuthPlugin`)
+
+| Method | Purpose |
+|--------|---------|
+| `resolve_identity(request, api_key, x_openviking_account, x_openviking_user)` | Resolve credentials to a `ResolvedIdentity`. |
+| `validate_config(config)` | Validate `ServerConfig` at startup; should `sys.exit(1)` on fatal misconfiguration. |
+| `initialize(app, service, config)` | Initialize runtime state (e.g., `APIKeyManager`) on `app.state`. |
+| `get_request_context_checks(path, identity)` | Optional post-auth path/identity checks. |
+| `requires_api_key_manager()` | Whether Admin API routes need an `APIKeyManager`. |
+| `can_skip_api_key_for_bot_proxy()` | Whether the bot proxy may skip API key validation (e.g., `dev` mode). |
+
+### Register a Custom Plugin
+
+```python
+from openviking.server.auth.plugin import AuthPlugin
+from openviking.server.auth.registry import register_auth_plugin
+from openviking.server.identity import ResolvedIdentity, Role
+
+@register_auth_plugin
+class CustomAuthPlugin(AuthPlugin):
+ auth_mode = "custom"
+
+ async def resolve_identity(self, request, *, api_key=None, x_openviking_account=None, x_openviking_user=None):
+ # ... Custom identity resolution logic ...
+ return ResolvedIdentity(role=Role.USER, account_id="...", user_id="...")
+
+ def validate_config(self, config):
+ pass
+
+ async def initialize(self, app, service, config):
+ pass
+```
+
+Then set `server.auth_mode = "custom"` in `ov.conf`.
+
+### Custom Roles
+
+The built-in `Role` class supports dynamic registration of custom roles with privilege ranks:
+
+```python
+from openviking.server.identity import Role
+
+Role.register("operator", rank=1) # Between USER (0) and ADMIN (1)
+```
+
+Custom roles work with `require_role()` and `require_auth_role()` decorators out of the box.
+
+---
+
+## CLI LDAP Authentication Configuration
+
+The OpenViking CLI (`ov`) supports LDAP authentication. Once configured, all CLI commands automatically use LDAP credentials.
+
+### Configuration Methods
+
+#### 1. Config File (Recommended)
+
+Edit `~/.openviking/ovcli.conf` to add LDAP authentication settings:
+
+```json
+{
+ "url": "http://localhost:1933",
+ "auth_mode": "ldap",
+ "ldap_username": "alice",
+ "ldap_password": "password123",
+ "account": "default"
+}
+```
+
+**Configuration Fields:**
+
+| Field | Required | Description |
+|-------|----------|-------------|
+| `url` | Yes | OpenViking server URL |
+| `auth_mode` | Yes | Authentication mode, set to `"ldap"` to enable LDAP |
+| `ldap_username` | Yes | LDAP username (UID) |
+| `ldap_password` | No | LDAP password (omit to skip password in CLI) |
+| `account` | No | OpenViking account ID (defaults to `"default"`) |
+
+#### 2. Mixed Configuration
+
+You can configure some settings in the file and override others with environment variables (e.g. `OPENVIKING_URL`, `OPENVIKING_ACCOUNT`).
+
+### Using the CLI
+
+Once configured, all CLI commands automatically use LDAP authentication:
+
+```bash
+# List resources
+ov ls viking://
+
+# Read a resource
+ov read viking://resources/example.md
+
+# Write a resource
+ov write viking://resources/test.md --content "Hello LDAP!"
+```
+
+### Building the Rust CLI (if updated)
+
+If you modify the Rust CLI source code, rebuild it:
+
+```bash
+make build-cli
+```
+
+The built binary is located at `openviking/bin/ov`.
+
+### Switching Authentication Modes
+
+You can switch between LDAP and API Key authentication by editing `~/.openviking/ovcli.conf` and changing `auth_mode` to `"api_key"` or removing the field.
+
+### Security Recommendations
+
+1. **Avoid storing plaintext passwords**: Prefer environment variables or secret managers over hardcoding in config files
+2. **Use HTTPS**: Always use HTTPS in production environments
+3. **Least privilege**: Use regular user accounts for daily operations, admin accounts only for management tasks
+4. **Rotate passwords regularly**: Follow your organization's password security policy
+
+### Troubleshooting
+
+**"Missing LDAP credentials" error:**
+- Check that `auth_mode` is set to `"ldap"`
+- Verify `username` and `password` are configured correctly
+
+**"LDAP authentication failed" error:**
+- Verify LDAP username and password are correct
+- Check that the LDAP server is reachable
+- Review server logs for detailed error messages
+
+**"Permission denied" error:**
+- Confirm the user's LDAP groups map to the correct OpenViking role
+- Check if the operation requires admin privileges
+- Contact your system administrator to verify permissions
+
+**Debug mode:**
+```bash
+# Enable verbose logging
+RUST_LOG=debug ov ls viking://
+
+# Check configuration
+ov doctor
+```
+
+---
+
## Related Documentation
-- [Multi-Tenant](../concepts/11-multi-tenant.md) - Capabilities, sharing boundaries, and integration patterns
-- [Configuration](01-configuration.md) - Config file reference
-- [Deployment](03-deployment.md) - Server setup
+- [Multi-Tenant](../concepts/11-multi-tenant.md) - Multi-tenant capabilities, sharing boundaries, and integration patterns
+- [Configuration](01-configuration.md) - Configuration file reference
+- [Deployment](03-deployment.md) - Server deployment
- [API Overview](../api/01-overview.md) - API reference
diff --git a/docs/zh/guides/04-authentication.md b/docs/zh/guides/04-authentication.md
index 454f1726b..13ce09833 100644
--- a/docs/zh/guides/04-authentication.md
+++ b/docs/zh/guides/04-authentication.md
@@ -1,351 +1,590 @@
# 认证
-OpenViking Server 支持三种内置认证模式,并带有基于角色的访问控制:`api_key`、`trusted` 和 `dev`。如果未显式配置,模式会自动推导。此外,系统支持自定义认证插件,可对接任意身份源(如 LDAP、OIDC、mTLS 等)。
+> **先看这里:选择适合你的认证模式**
-## 概述
+## 📚 前置知识 - 我该用哪个?
-OpenViking 使用两层 API Key 体系:
+| 认证模式 | 是什么? | 适合谁? | **推荐度** |
+|---------|----------|---------|------------|
+| **API Key** (默认) | OpenViking 自己管理用户和密钥 | 小团队、独立部署 | ⭐⭐⭐⭐⭐ |
+| **OIDC** | 对接企业单点登录(Okta/Auth0/Keycloak/Azure AD 等) | 企业 SSO 集成 | ⭐⭐⭐⭐ |
+| **LDAP** | 对接企业用户目录(Windows AD/OpenLDAP) | 已有企业目录服务 | ⭐⭐⭐⭐ |
+| **Trusted** | 上游网关/反向代理断言身份 | 部署在受信任内网/网关后 | ⭐⭐⭐ |
+| **Dev** | 无认证,仅本地开发 | **只用于本地开发!** | ⭐⭐ |
-| Key 类型 | 创建方式 | 角色 | 用途 |
-|----------|---------|------|------|
-| Root Key | 服务端配置(`root_api_key`) | ROOT | 账户管理 + 少量 system/monitoring 操作 |
-| User Key | Admin API | ADMIN 或 USER | 租户内数据访问;ADMIN 还可管理本 account 下的用户 |
+### 🔍 决策树
-User key 由 Admin API 生成。默认使用随机 secret;Admin API 调用方也可以传入
-`seed`,用 `sha256(user_id + "\0" + seed)` 生成可预测的 key secret。服务端仍然
-会用存储的 key 或 key hash 校验最终 API Key。
-
-## 认证模式
-
-| 模式 | `server.auth_mode` | 身份来源 | 典型使用场景 |
-|------|--------------------|----------|--------------|
-| API Key 模式 | `"api_key"` | API Key;数据归属从 user/admin key 解析 | 标准多租户部署 |
-| Trusted 模式 | `"trusted"` | `X-OpenViking-Account` / `X-OpenViking-User`;非 localhost 部署还必须配置 `root_api_key`。角色会从 APIKeyManager 查询(如果用户存在) | 部署在受信网关或内网边界之后 |
-| Dev 模式 | `"dev"` | 无认证,始终为 ROOT | 仅限本地开发 |
+```
+┌─────────────────────────────────────────────────────┐
+│ 企业里有现成的身份系统? │
+├─────────────────────────────────────────────────────┤
+│ 是 SaaS 身份?(Okta/Auth0/Keycloak) │
+│ → 用 **OIDC** ✅ │
+│ │
+│ 是本地目录?(Windows AD/OpenLDAP) │
+│ → 用 **LDAP** ✅ │
+├─────────────────────────────────────────────────────┤
+│ 没有身份系统? │
+│ → 用 **API Key**(默认)✅ │
+├─────────────────────────────────────────────────────┤
+│ 部署在内部网关后面? │
+│ → 用 **Trusted** ✅ │
+└─────────────────────────────────────────────────────┘
+```
-如果未显式配置 `auth_mode`:
-- 如果设置了 `root_api_key`(非空):自动选择 `api_key` 模式
-- 如果未设置 `root_api_key`:自动选择 `dev` 模式
+---
-> **注意:** 将 `root_api_key` 设置为空字符串 `""` 是非法的。请要么设置一个非空值,要么完全移除该配置项。
+## 🏁 快速开始 - 3分钟跑起来
-## 服务端配置
+### 方案一:API Key(最简单)
-在 `ov.conf` 的 `server` 段配置认证模式:
+只需要配置 `root_api_key`,剩下的默认就好!
```json
{
"server": {
"auth_mode": "api_key",
- "root_api_key": "your-secret-root-key"
+ "root_api_key": "your-secret-root-key-here"
}
}
```
-启动服务:
-
+启动服务器:
```bash
openviking-server
```
-### 自定义认证插件
+用 API 管理用户:
+```bash
+# 创建账号 + 管理员
+curl -X POST http://localhost:1933/api/v1/admin/accounts \
+ -H "X-API-Key: your-secret-root-key" \
+ -H "Content-Type: application/json" \
+ -d '{"account_id": "my-team", "admin_user_id": "alice"}'
+```
-服务端采用插件化认证架构。每种 `auth_mode` 对应一个 `AuthPlugin` 实现。内置插件(`dev`、`api_key`、`trusted`)会自动注册;第三方插件可通过继承 `AuthPlugin` 并在启动前注册来扩展。
+### 方案二:OIDC(企业 SSO)
-**插件接口(`openviking.server.auth.plugin.AuthPlugin`)**
+**最小配置(不需要 mapping):**
-| 方法 | 用途 |
-|------|------|
-| `resolve_identity(request, api_key, x_openviking_account, x_openviking_user)` | 将凭据解析为 `ResolvedIdentity`。 |
-| `validate_config(config)` | 在启动时校验 `ServerConfig`;遇到致命错误应调用 `sys.exit(1)`。 |
-| `initialize(app, service, config)` | 在 `app.state` 上初始化运行时状态(如 `APIKeyManager`)。 |
-| `get_request_context_checks(path, identity)` | 可选的认证后路径/身份检查。 |
-| `requires_api_key_manager()` | Admin API 路由是否需要 `APIKeyManager`。 |
-| `can_skip_api_key_for_bot_proxy()` | Bot 代理是否可以跳过 API Key 校验(如 `dev` 模式)。 |
+```json
+{
+ "server": {
+ "auth_mode": "oidc",
+ "oidc": {
+ "issuer": "https://your-company.okta.com"
+ }
+ }
+}
+```
-**注册自定义插件**
+默认自动使用:
+- `account_id` → 所有用户在同一组织("default")
+- `user_id` → 使用 OIDC 标准字段 `sub`
+- `role` → 默认为 `user`
-```python
-from openviking.server.auth.plugin import AuthPlugin
-from openviking.server.auth.registry import register_auth_plugin
-from openviking.server.identity import ResolvedIdentity, Role
+启动后健康检查会自动验证是否连接成功!
-@register_auth_plugin
-class LDAPAuthPlugin(AuthPlugin):
- auth_mode = "ldap"
+**进阶配置(需要隔离团队时):**
+参考下方「🔧 Identity Mapping 详解」章节。
- async def resolve_identity(self, request, *, api_key=None, x_openviking_account=None, x_openviking_user=None):
- # ... LDAP 绑定与身份解析 ...
- return ResolvedIdentity(role=Role.USER, account_id="...", user_id="...")
+### 方案三:LDAP(企业目录)
- def validate_config(self, config):
- pass
+**最小配置(搜索绑定模式):**
- async def initialize(self, app, service, config):
- pass
+```json
+{
+ "server": {
+ "auth_mode": "ldap",
+ "ldap": {
+ "host": "ldap.your-company.com",
+ "port": 636,
+ "use_ssl": true,
+ "bind_dn": "cn=openviking,dc=your-company,dc=com",
+ "bind_password": "${LDAP_PASSWORD}",
+ "base_dn": "dc=your-company,dc=com",
+ "user_search_filter": "(uid=%s)"
+ }
+ }
+}
```
-然后在 `ov.conf` 中设置 `server.auth_mode = "ldap"`。
+默认自动使用:
+- `account_id` → 所有用户在同一组织("default")
+- `user_id` → 使用 LDAP 字段 `uid`
+- `role` → 默认为 `user`
-**自定义角色**
+---
-内置的 `Role` 类支持动态注册自定义角色及权限等级:
+## 📚 概念详解
-```python
-from openviking.server.identity import Role
+### OIDC 是什么?
-Role.register("operator", rank=1) # 权限介于 USER (0) 与 ADMIN (1) 之间
-```
+OIDC (OpenID Connect) 是业界标准的单点登录协议。
-自定义角色可直接用于 `require_role()` 和 `require_auth_role()` 装饰器。
+| 术语 | 说明 |
+|------|------|
+| **Issuer** | OIDC 提供商的 URL(如 `https://your-company.okta.com`) |
+| **Claims** | Token 里包含的用户信息(如 `sub` = 用户ID,`email` = 邮箱) |
+| **JWKS** | 用于验证 Token 签名的密钥集(自动从 Issuer 发现) |
+| **Audience** | 可选,验证 Token 是发给谁的 |
-## 管理账户和用户
+### LDAP 是什么?
-普通读写、检索、会话等数据请求在 `api_key` 和 `trusted` 两种模式下都不依赖 Admin API 预注册。Admin API 仍然负责创建 account、注册用户、将用户提升为 admin,以及签发或重新生成 user key。
+LDAP (Lightweight Directory Access Protocol) 是企业用户目录的标准协议。
-使用 root key 通过 Admin API 创建工作区和用户:
+| 术语 | 说明 |
+|------|------|
+| **DN** | 唯一标识对象的路径(如 `uid=alice,ou=users,dc=example,dc=com`) |
+| **Base DN** | 搜索用户的根节点(如 `dc=example,dc=com`) |
+| **Bind DN** | 连接 LDAP 用的服务账号 |
+| **Attribute** | 用户属性(如 `uid`, `email`, `memberOf`) |
-```bash
-# 创建工作区 + 首个 admin
-curl -X POST http://localhost:1933/api/v1/admin/accounts \
- -H "X-API-Key: your-secret-root-key" \
- -H "Content-Type: application/json" \
- -d '{"account_id": "acme", "admin_user_id": "alice"}'
-# 返回: {"result": {"account_id": "acme", "admin_user_id": "alice", "user_key": "..."}}
+### Identity Mapping 是什么?
+
+简单说:**把外部身份源的字段映射到 OpenViking 的身份上。**
-# 注册普通用户(ROOT 或 ADMIN 均可)
-curl -X POST http://localhost:1933/api/v1/admin/accounts/acme/users \
- -H "X-API-Key: your-secret-root-key" \
- -H "Content-Type: application/json" \
- -d '{"user_id": "bob", "role": "user"}'
-# 返回: {"result": {"account_id": "acme", "user_id": "bob", "user_key": "..."}}
+```
+外部身份源 → Mapping 规则 → OpenViking 身份
+─────────────────────────────────────────────────────────────────────
+OIDC Claims: {
+ "sub": "user123", → claim="sub" → user_id = "user123"
+ "department": "eng", → claim="department" → account_id = "eng"
+ "role": "admin" → mapping={"admin":"admin"} → role = "admin"
+}
```
-受信部署也可以通过受信网关调用 Admin API,目前支持两种方式:
+支持的模式:
+- **Organization**:所有用户在同一组织(默认)
+- **Team**:按部门/团队隔离(从外部字段提取)
-- 携带受信部署自身的 `root_api_key`。对于 `/api/v1/admin/*`,服务端校验该 key 后会将请求视为 ROOT。
-- 如果 Admin 路由指向具体 account/user,也可以同时携带 `X-OpenViking-Account` + `X-OpenViking-User`。这些 header 必须与目标 URL 匹配,并会保留为请求身份;授权仍来自受信 `root_api_key`。
+---
-下面是“受信上游身份”这种方式的示例:
+## ⚙️ 完整配置参考
-```bash
-# 首先,注册网关管理员(在 api_key 模式下执行一次)
-curl -X POST http://localhost:1933/api/v1/admin/accounts \
- -H "X-API-Key: your-secret-root-key" \
- -H "Content-Type: application/json" \
- -d '{"account_id": "platform", "admin_user_id": "gateway-admin"}'
+### OIDC 完整配置
-# 然后,在 trusted 模式下使用该身份调用 Admin API;管理权限来自 root_api_key
-curl -X POST http://localhost:1933/api/v1/admin/accounts \
- -H "X-API-Key: your-secret-root-key" \
- -H "X-OpenViking-Account: platform" \
- -H "X-OpenViking-User: gateway-admin" \
- -H "Content-Type: application/json" \
- -d '{
- "account_id": "acme",
- "admin_user_id": "alice"
- }'
+```json
+{
+ "server": {
+ "auth_mode": "oidc",
+ "oidc": {
+ "issuer": "https://your-company.okta.com",
+ "client_id": "0oabc123def456",
+ "client_secret": "${OIDC_CLIENT_SECRET}",
+ "audience": "openviking",
+ "jwks_uri": "https://your-company.okta.com/oauth2/v1/keys",
+ "token_location": "header",
+ "token_header_name": "Authorization",
+ "token_header_prefix": "Bearer ",
+ "identity": {
+ "account_id": {
+ "mode": "organization",
+ "source": "claim",
+ "claim": "tenant_id",
+ "prefix": "org-",
+ "fallback": "default-org"
+ },
+ "user_id": {
+ "source": "claim",
+ "claim": "sub",
+ "prefix": "user-",
+ "normalize": "lowercase"
+ },
+ "role": {
+ "source": "claim",
+ "claim": "role",
+ "mapping": {
+ "administrator": "admin",
+ "developer": "user",
+ "viewer": "user"
+ },
+ "default": "user"
+ }
+ }
+ }
+ }
+}
```
-## 客户端使用
-
-OpenViking 支持两种方式传递 API Key:
+### LDAP 完整配置
-**X-API-Key 请求头**
-
-```bash
-curl http://localhost:1933/api/v1/fs/ls?uri=viking:// \
- -H "X-API-Key: <user-key>"
+```json
+{
+ "server": {
+ "auth_mode": "ldap",
+ "ldap": {
+ "host": "ldap.your-company.com",
+ "port": 636,
+ "use_ssl": true,
+ "use_starttls": false,
+ "bind_dn": "cn=openviking,dc=your-company,dc=com",
+ "bind_password": "${LDAP_PASSWORD}",
+ "base_dn": "dc=your-company,dc=com",
+ "user_search_filter": "(uid=%s)",
+ "user_search_base": "ou=users,dc=your-company,dc=com",
+ "username_attribute": "uid",
+ "email_attribute": "mail",
+ "name_attribute": "cn",
+ "user_dn_pattern": "uid=%s,ou=users,dc=your-company,dc=com",
+ "identity": {
+ "account_id": {
+ "mode": "team",
+ "source": "dn_attribute",
+ "attribute": "ou",
+ "prefix": "team-",
+ "fallback": "default"
+ },
+ "user_id": {
+ "source": "attribute",
+ "attribute": "uid",
+ "normalize": "lowercase"
+ },
+ "role": {
+ "source": "group_membership",
+ "group_mapping": {
+ "cn=openviking-admins,ou=groups,dc=your-company,dc=com": "admin",
+ "cn=openviking-users,ou=groups,dc=your-company,dc=com": "user"
+ },
+ "default": "user"
+ }
+ }
+ }
+ }
+}
```
-**Authorization: Bearer 请求头**
+### 高级 Mapping 示例
-```bash
-curl http://localhost:1933/api/v1/fs/ls?uri=viking:// \
- -H "Authorization: Bearer <user-key>"
-```
+#### 1. 正则提取
-**Python SDK(HTTP)**
+从邮箱里提取用户名:
+```json
+{
+ "user_id": {
+ "source": "claim",
+ "claim": "email",
+ "regex": "^([^@]+)@",
+ "regex_group": 1
+ }
+}
+```
+输入:`[email protected]` → 输出:`alice`
-```python
-import openviking as ov
+#### 2. 多字段回退
-client = ov.SyncHTTPClient(
- url="http://localhost:1933",
- api_key="<user-key>",
-)
+尝试多个字段,第一个有值的生效:
+```json
+{
+ "user_id": {
+ "source": "claim",
+ "claims": ["username", "email", "sub"],
+ "fallback": "guest"
+ }
+}
```
-**CLI(通过 ovcli.conf)**
+#### 3. 组合字段
+把 Tenant ID 和 Department 拼起来:
```json
{
- "url": "http://localhost:1933",
- "api_key": "<user-key>"
+ "account_id": {
+ "source": "composite",
+ "parts": [
+ {"source": "claim", "claim": "tenant_id"},
+ {"literal": "-"},
+ {"source": "claim", "claim": "department"}
+ ]
+ }
}
```
+输入:`tenant_id="acme"`, `department="eng"` → 输出:`acme-eng`
-如果使用普通 `user key` 或 `admin key`,`account` 和 `user` 可以省略,因为服务端可以从 key 反查出来;如果使用 `trusted` 模式,则建议明确配置。
+---
-**CLI 覆盖参数**
+## 🐛 故障排除
-```bash
-openviking --account acme --user alice ls viking://
+### OIDC 常见问题
+
+#### 问题 1:「找不到 issuer」
+
+```
+❌ oidc_issuer_configured: Issuer is not configured
```
-### 使用 --sudo 和 Root API Key
+**解决方法:**
+- 检查 URL 是否有协议(`https://`)
+- 确认 URL 是否可以访问:
+ ```bash
+ curl https://your-company.okta.com/.well-known/openid-configuration
+ ```
-CLI 支持在 `ovcli.conf` 中同时配置 `api_key`(用于普通用户操作)和 `root_api_key`(用于管理员操作):
+#### 问题 2:「无法获取 JWKS」
-```json
-{
- "url": "http://localhost:1933",
- "api_key": "<user-key>",
- "root_api_key": "<root-key>"
-}
+```
+⚠️ oidc_jwks_accessible: Failed to fetch JWKS: ...
```
-当需要执行管理员命令(`admin`、`system`、`reindex`)时,使用 `--sudo` 标志提升权限:
+**解决方法:**
+- 检查网络连接
+- 可能是防火墙问题,尝试手动配置 `jwks_uri`
-```bash
-# 列出所有账户(需要 root 权限)
-ov --sudo admin list-accounts
+#### 问题 3:「Token 验证失败」
-# 重新索引内容
-ov --sudo reindex viking://
+**诊断步骤:**
+1. 检查 Token 格式是否正确
+2. 查看日志,确认 `iss` 匹配配置
+3. 如果是过期 Token,这是正常的,需要重新登录
-# 系统命令
-ov --sudo system status
-```
+---
-`--sudo` 标志:
-- 仅适用于管理员命令:`admin`、`system`、`reindex`
-- 用于非管理员命令时会报错
-- `ovcli.conf` 中未配置 `root_api_key` 时会报错
-- 请求时使用 `root_api_key` 替代 `api_key`
+### LDAP 常见问题
-### 租户数据访问
+#### 问题 1:「无法连接 LDAP」
-租户级数据 API(如 `ls`、`find`、resources、sessions 等)在 `api_key`
-模式下必须使用绑定了 account/user 的 key。这个 key 可以是 `USER` key,也可以是
-`ADMIN` key;`ADMIN` key 会以它自己的 user 身份访问数据,不能通过
-`X-OpenViking-Account` / `X-OpenViking-User` 切换身份。
+```
+⚠️ ldap_connection: Failed to connect to LDAP: Connect timeout
+```
-`ROOT` key 没有绑定租户 user,因此在 `api_key` 模式下不能访问租户级数据 API。
-如果部署需要由上游网关断言 `account` / `user`,请使用 `trusted` 模式,而不是在
-root key 请求上携带身份 header。
+**解决方法:**
+- 检查服务器地址和端口
+- 确认 `use_ssl` 设置正确:
+ - LDAPS (SSL) 通常端口 636
+ - 普通 LDAP 通常端口 389
+ - 可以用 `ldapsearch` 测试:
+ ```bash
+ ldapsearch -x -H ldaps://ldap.your-company.com:636 -b "dc=your-company,dc=com"
+ ```
-**ovcli.conf**
+#### 问题 2:「Bind 失败」
-```json
-{
- "url": "http://localhost:1933",
- "auth_mode": "trusted",
- "api_key": "your-trusted-server-key",
- "account": "acme",
- "user": "alice"
-}
+```
+⚠️ ldap_connection: Bind failed: Invalid credentials
```
-## Trusted 模式
+**解决方法:**
+- 检查 `bind_dn` 和 `bind_password`
+- 确认 Bind 账号在 LDAP 中存在
-Trusted 模式不会查 user key,而是直接信任每个请求显式携带的身份请求头:
+#### 问题 3:「找不到用户」
-```json
-{
- "server": {
- "auth_mode": "trusted",
- "host": "127.0.0.1"
- }
-}
+```
+❌ 搜索结果为空
```
-Trusted 模式规则:
+**解决方法:**
+- 检查 `user_search_filter` 是否正确
+- 检查 `base_dn` 是否正确
+- 尝试用 `ldapsearch` 手动测试:
+ ```bash
+ ldapsearch -x -H ldaps://ldap.your-company.com:636 -D "cn=openviking,dc=your-company,dc=com" -W -b "dc=your-company,dc=com" "(uid=alice)"
+ ```
-- 普通数据访问不需要先注册 user key,也不依赖 user key 分发流程
-- 租户级请求必须包含 `X-OpenViking-Account` 和 `X-OpenViking-User`
-- 受信上游也可以发送 `X-OpenViking-Role: user` 或 `X-OpenViking-Role: admin` 断言请求角色。该请求头只有在配置了 `root_api_key` 且请求携带匹配 API Key 时才会生效。`root` 不是允许的断言值;ROOT 只保留给已校验的 Admin API 回退路径
-- `/api/v1/admin/*` 是特例:当请求携带已配置的 `root_api_key` 时,trusted 模式会将请求视为 ROOT。显式 account/user header 只有在完整且与目标 URL 匹配时才允许
-- 普通 trusted 数据 API 的角色优先使用经过授权的 `X-OpenViking-Role`;未提供该请求头时,通过在 APIKeyManager 中查找 account/user 确定。如果用户存在,使用其配置的角色;否则默认为 `USER`
-- trusted 身份完全来自请求头,而不是 user key;如果同时配置了 `root_api_key`,它表示“这个上游是被允许的 trusted 调用方”
-- 如果同时配置了 `root_api_key`,每个请求仍然必须带匹配的 API Key
-- 只应部署在受信网络边界之后,或由身份注入网关统一转发
+---
-这意味着:
+### 通用调试技巧
-- `trusted` 不是开发模式
-- `trusted` 下的普通读写、检索、会话访问不需要先走 Admin API 注册流程
-- `trusted` 模式下,携带已配置 `root_api_key` 的受信上游可以调用 Admin API
-- `trusted` 模式下,创建 account 或注册用户的 Admin API 响应不会返回 `user_key`
-- `root` 可以创建/删除 account 并提升用户为 admin;`admin` 可以管理自己 account 下的用户并将其提升为 admin;`user` 不能调用 Admin API
-- 非 localhost 部署要在 trusted 模式下使用 Admin API,需要配置 `root_api_key`,并在每个管理请求中携带它
+1. **启用 Debug 日志**(启动时看到更多细节)
+2. **先看健康检查**(启动时自动运行)
+3. **检查配置格式**(JSON 是否有效)
+4. **查看日志**(重点看错误信息前面的内容)
-**curl**
+---
-```bash
-curl http://localhost:1933/api/v1/fs/ls?uri=viking:// \
- -H "X-OpenViking-Account: acme" \
- -H "X-OpenViking-User: alice"
+## 🔧 自定义认证插件(高级)
+
+如果内置的模式不够用,可以自己开发!
+
+服务端采用插件化认证架构。每种 `auth_mode` 对应一个 `AuthPlugin` 实现。内置插件(`dev`, `api_key`, `trusted`, `oidc`, `ldap`)会自动注册;第三方插件可通过继承 `AuthPlugin` 并在启动前注册来扩展。
+
+### 插件接口(`openviking.server.auth.plugin.AuthPlugin`)
+
+| 方法 | 用途 |
+|------|------|
+| `resolve_identity(request, api_key, x_openviking_account, x_openviking_user)` | 将凭据解析为 `ResolvedIdentity` |
+| `validate_config(config)` | 在启动时校验 `ServerConfig`;遇到致命错误应调用 `sys.exit(1)` |
+| `initialize(app, service, config)` | 在 `app.state` 上初始化运行时状态(如 `APIKeyManager`) |
+| `get_request_context_checks(path, identity)` | 可选的认证后路径/身份检查 |
+| `requires_api_key_manager()` | Admin API 路由是否需要 `APIKeyManager` |
+| `can_skip_api_key_for_bot_proxy()` | Bot 代理是否可以跳过 API Key 校验(如 `dev` 模式) |
+
+### 注册自定义插件示例
+
+```python
+from openviking.server.auth.plugin import AuthPlugin
+from openviking.server.auth.registry import register_auth_plugin
+from openviking.server.identity import ResolvedIdentity, Role
+
+@register_auth_plugin
+class CustomAuthPlugin(AuthPlugin):
+ auth_mode = "custom"
+
+ async def resolve_identity(self, request, *, api_key=None, x_openviking_account=None, x_openviking_user=None):
+ # 自定义认证逻辑...
+ return ResolvedIdentity(role=Role.USER, account_id="...", user_id="...")
+
+ def validate_config(self, config):
+ pass
+
+ async def initialize(self, app, service, config):
+ pass
```
-**Python SDK**
+然后在 `ov.conf` 中设置 `server.auth_mode = "custom"`。
+
+### 自定义角色
+
+内置的 `Role` 类支持动态注册自定义角色及权限等级:
```python
-import openviking as ov
+from openviking.server.identity import Role
-client = ov.SyncHTTPClient(
- url="http://localhost:1933",
- account="acme",
- user="alice",
-)
+Role.register("operator", rank=1) # 权限介于 USER (0) 与 ADMIN (1) 之间
```
-## Dev 模式
+自定义角色可直接用于 `require_role()` 和 `require_auth_role()` 装饰器。
+
+---
-当 `auth_mode = "dev"`(或未配置 `root_api_key` 时自动推导)时,认证禁用,所有请求以 ROOT 身份访问 default account。**此模式仅允许在服务器绑定 localhost 时使用**(`127.0.0.1`、`localhost` 或 `::1`)。如果 `host` 设置为非回环地址(如 `0.0.0.0`)且使用 `dev` 模式,服务器将拒绝启动。
+## 内置认证模式详情
+
+### Trusted 模式
+
+Trusted 模式不会查询 user key,而是直接信任每个请求显式携带的身份请求头:
```json
{
"server": {
- "host": "127.0.0.1",
- "port": 1933
+ "auth_mode": "trusted",
+ "host": "127.0.0.1"
}
}
```
-或显式配置:
+### Dev 模式
+
+当 `auth_mode = "dev"`(或未配置 `root_api_key` 时自动推导)时,认证禁用,所有请求以 ROOT 身份访问 default account。
```json
{
"server": {
- "auth_mode": "dev",
- "host": "127.0.0.1",
- "port": 1933
+ "host": "127.0.0.1"
}
}
```
-> **安全提示:** 默认 `host` 为 `127.0.0.1`。如需将服务暴露到网络,**必须**配置 `root_api_key`。
+> **安全提示:** 默认 `host` 为 `127.0.0.1`。如果需要将服务暴露到网络,**必须**配置 `root_api_key`。
-## 角色与权限
+---
-| 角色 | 作用域 | 能力 |
-|------|--------|------|
-| ROOT | 全局 | 全部操作 + Admin API(创建/删除工作区、管理用户) |
-| ADMIN | 所属 account | 常规操作 + 管理所属 account 的用户 |
-| USER | 所属 account | 常规操作(ls、read、find、sessions 等) |
+## CLI 配置 LDAP 认证
-在 `trusted` 模式下,普通租户请求默认会解析为 `USER`;如果该 account/user 已注册更高角色,或网关在携带已配置 root API key 的请求中断言 `X-OpenViking-Role: admin`,则使用更高角色。`X-OpenViking-Role: root` 会被拒绝。对于 Admin 路由,在没有显式身份时还支持 trusted ROOT 回退。
+OpenViking CLI (`ov`) 支持通过 LDAP 进行认证。配置完成后,所有 CLI 命令会自动使用 LDAP 凭据。
-## 无需认证的端点
+### 配置方式
-`/health` 端点始终不需要认证,用于负载均衡器和监控工具检查服务健康状态。
+#### 1. 配置文件方式(推荐)
+编辑 `~/.openviking/ovcli.conf` 文件,添加 LDAP 认证配置:
+
+```json
+{
+ "url": "http://localhost:1933",
+ "auth_mode": "ldap",
+ "ldap_username": "alice",
+ "ldap_password": "password123",
+ "account": "default"
+}
+```
+
+**配置项说明:**
+
+| 配置项 | 必需 | 说明 |
+|--------|------|------|
+| `url` | 是 | OpenViking 服务器地址 |
+| `auth_mode` | 是 | 认证模式,设置为 `"ldap"` 启用 LDAP |
+| `ldap_username` | 是 | LDAP 用户名(UID) |
+| `ldap_password` | 否 | LDAP 密码(不提供时 CLI 不发送密码) |
+| `account` | 否 | OpenViking 账户 ID(默认为 `"default"`) |
+
+#### 2. 混合配置
+
+可以部分配置在文件中,部分通过环境变量(如 `OPENVIKING_URL`、`OPENVIKING_ACCOUNT`)覆盖。
+
+### 使用 CLI
+
+配置完成后,所有 CLI 命令会自动使用 LDAP 认证:
+
+```bash
+# 列出资源
+ov ls viking://
+
+# 读取资源
+ov read viking://resources/example.md
+
+# 写入资源
+ov write viking://resources/test.md --content "Hello LDAP!"
+```
+
+### 构建 Rust CLI(如需更新)
+
+如果修改了 Rust CLI 源码,需要重新构建:
+
+```bash
+make build-cli
+```
+
+构建后的二进制文件位于 `openviking/bin/ov`。
+
+### 切换认证模式
+
+编辑 `~/.openviking/ovcli.conf`,修改 `auth_mode` 为 `"api_key"` 或删除该字段即可切换认证模式。
+
+### 安全建议
+
+1. **避免明文存储密码**:推荐使用环境变量或密钥管理工具,而非在配置文件中硬编码密码
+2. **使用 HTTPS**:生产环境中确保服务器使用 HTTPS 连接
+3. **最小权限**:使用普通用户账户进行日常操作,管理员账户仅用于管理任务
+4. **定期轮换密码**:遵循组织的密码安全策略
+
+### 故障排查
+
+**"Missing LDAP credentials" 错误:**
+- 检查 `auth_mode` 是否设置为 `"ldap"`
+- 确认 `username` 和 `password` 配置正确
+
+**"LDAP authentication failed" 错误:**
+- 验证 LDAP 用户名和密码是否正确
+- 检查 LDAP 服务器是否可访问
+- 查看服务器端日志获取详细错误信息
+
+**"Permission denied" 错误:**
+- 确认用户 LDAP 组是否映射到正确的 OpenViking 角色
+- 检查操作是否需要管理员权限
+- 联系系统管理员确认权限配置
+
+**调试模式:**
```bash
-curl http://localhost:1933/health
+# 启用详细日志
+RUST_LOG=debug ov ls viking://
+
+# 检查配置
+ov doctor
```
-## Admin API 参考
+---
+
+## 相关文档
+
+- [多租户](../concepts/11-multi-tenant.md) - 多租户能力、共享边界与接入实践
+- [配置](01-configuration.md) - 配置文件说明
+- [服务部署](03-deployment.md) - 服务部署
+- [API 概览](../api/01-overview.md) - API 参考
+
+---
+
+## 📝 附录:Admin API 参考
| 方法 | 端点 | 角色 | 说明 |
|------|------|------|------|
@@ -357,10 +596,3 @@ curl http://localhost:1933/health
| DELETE | `/api/v1/admin/accounts/{id}/users/{uid}` | ROOT, ADMIN | 移除用户 |
| PUT | `/api/v1/admin/accounts/{id}/users/{uid}/role` | ROOT, ADMIN | 将用户提升为 ADMIN;ADMIN 仅限本账户 |
| POST | `/api/v1/admin/accounts/{id}/users/{uid}/key` | ROOT, ADMIN | 重新生成 user key |
-
-## 相关文档
-
-- [多租户](../concepts/11-multi-tenant.md) - 多租户能力、共享边界与接入实践
-- [配置](01-configuration.md) - 配置文件说明
-- [服务部署](03-deployment.md) - 服务部署
-- [API 概览](../api/01-overview.md) - API 参考
diff --git a/openviking/server/auth/health_check.py b/openviking/server/auth/health_check.py
new file mode 100644
index 000000000..2b664e8bc
--- /dev/null
+++ b/openviking/server/auth/health_check.py
@@ -0,0 +1,548 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Authentication health check module for OIDC and LDAP auth modes.
+
+This module provides startup self-check capabilities to validate authentication
+configurations are working before the server starts accepting traffic.
+"""
+
+from __future__ import annotations
+
+import logging
+import sys
+from abc import ABC, abstractmethod
+from dataclasses import dataclass
+from enum import Enum
+from typing import Any, Dict, List, Optional
+
+from openviking.server.config import ServerConfig
+
+logger = logging.getLogger(__name__)
+
+
+class HealthStatus(str, Enum):
+ """Health check status."""
+ PASS = "pass"
+ WARN = "warn"
+ FAIL = "fail"
+
+
+@dataclass
+class HealthCheckResult:
+ """Result of a single health check."""
+ name: str
+ status: HealthStatus
+ message: str
+ error: Optional[Exception] = None
+ duration_seconds: Optional[float] = None
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "name": self.name,
+ "status": self.status.value,
+ "message": self.message,
+ "error": str(self.error) if self.error else None,
+ "duration_seconds": self.duration_seconds,
+ }
+
+
+@dataclass
+class HealthCheckReport:
+ """Complete health check report."""
+ overall_status: HealthStatus
+ checks: List[HealthCheckResult]
+ auth_mode: str
+ summary: str
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "overall_status": self.overall_status.value,
+ "auth_mode": self.auth_mode,
+ "checks": [c.to_dict() for c in self.checks],
+ "summary": self.summary,
+ }
+
+
+class AuthHealthChecker(ABC):
+ """Abstract base class for auth mode health checkers."""
+
+ @abstractmethod
+ def name(self) -> str:
+ """Name of this checker."""
+ pass
+
+ @abstractmethod
+ async def run_checks(self, config: ServerConfig) -> List[HealthCheckResult]:
+ """Run all health checks for this auth mode."""
+ pass
+
+
+class OIDCAuthChecker(AuthHealthChecker):
+ """Health checker for OIDC auth mode."""
+
+ def name(self) -> str:
+ return "oidc"
+
+ async def run_checks(self, config: ServerConfig) -> List[HealthCheckResult]:
+ from time import time
+ results: List[HealthCheckResult] = []
+
+ if config.oidc is None:
+ results.append(HealthCheckResult(
+ name="OIDC config present",
+ status=HealthStatus.FAIL,
+ message="OIDC config missing, please add server.oidc to your ov.conf",
+ ))
+ return results
+
+ # Check 1: Issuer is present
+ start_time = time()
+ if not config.oidc.issuer:
+ results.append(HealthCheckResult(
+ name="OIDC Issuer configured",
+ status=HealthStatus.FAIL,
+ message="OIDC issuer not configured, please set server.oidc.issuer",
+ duration_seconds=time() - start_time,
+ ))
+ else:
+ results.append(HealthCheckResult(
+ name="OIDC Issuer configured",
+ status=HealthStatus.PASS,
+ message=f"Issuer configured successfully: {config.oidc.issuer}",
+ duration_seconds=time() - start_time,
+ ))
+
+ # Check 2: JWKS endpoint is accessible via OIDC Discovery.
+ # Per OpenID Connect Discovery 1.0 we must fetch
+ # {issuer}/.well-known/openid-configuration and use the returned
+ # jwks_uri, not assume a hardcoded /.well-known/jwks.json path.
+ start_time = time()
+ try:
+ import httpx
+
+ if config.oidc.jwks_uri:
+ jwks_uri = config.oidc.jwks_uri
+ else:
+ discovery_url = (
+ f"{config.oidc.issuer.rstrip('/')}/.well-known/openid-configuration"
+ )
+ async with httpx.AsyncClient(timeout=10.0) as client:
+ disc_response = await client.get(discovery_url)
+ disc_response.raise_for_status()
+ metadata = disc_response.json()
+ jwks_uri = metadata.get("jwks_uri")
+ if not jwks_uri:
+ raise RuntimeError(
+ f"OIDC discovery document at {discovery_url} "
+ "did not contain a jwks_uri"
+ )
+
+ async with httpx.AsyncClient(timeout=10.0) as client:
+ response = await client.get(jwks_uri)
+ response.raise_for_status()
+ jwks = response.json()
+ keys = jwks.get("keys", [])
+ if not keys:
+ results.append(HealthCheckResult(
+ name="OIDC provider connection",
+ status=HealthStatus.WARN,
+ message="Connected to OIDC provider but no signing keys found",
+ duration_seconds=time() - start_time,
+ ))
+ else:
+ results.append(HealthCheckResult(
+ name="OIDC provider connection",
+ status=HealthStatus.PASS,
+ message=(
+ f"Successfully connected to OIDC provider via {jwks_uri}, "
+ f"found {len(keys)} signing keys"
+ ),
+ duration_seconds=time() - start_time,
+ ))
+ except Exception as e:
+ results.append(HealthCheckResult(
+ name="OIDC provider connection",
+ status=HealthStatus.WARN,
+ message=f"Could not connect to OIDC provider: {str(e)[:200]}",
+ error=e,
+ duration_seconds=time() - start_time,
+ ))
+
+ # Check 3: Identity mapping defaults are reasonable
+ start_time = time()
+ try:
+ from openviking.server.auth.identity_mapping import IdentityMapper
+ IdentityMapper(config.oidc.identity)
+ results.append(HealthCheckResult(
+ name="OIDC identity mapping config",
+ status=HealthStatus.PASS,
+ message="Identity mapping configuration is valid",
+ duration_seconds=time() - start_time,
+ ))
+ except Exception as e:
+ results.append(HealthCheckResult(
+ name="OIDC identity mapping config",
+ status=HealthStatus.WARN,
+ message=f"Identity mapping configuration has an issue: {str(e)}",
+ error=e,
+ duration_seconds=time() - start_time,
+ ))
+
+ return results
+
+
+class LDAPAuthChecker(AuthHealthChecker):
+ """Health checker for LDAP auth mode."""
+
+ def name(self) -> str:
+ return "ldap"
+
+ async def run_checks(self, config: ServerConfig) -> List[HealthCheckResult]:
+ from time import time
+ results: List[HealthCheckResult] = []
+
+ if config.ldap is None:
+ results.append(HealthCheckResult(
+ name="ldap_config_present",
+ status=HealthStatus.FAIL,
+ message="LDAP config is missing",
+ ))
+ return results
+
+ # Check 1: Host is configured
+ start_time = time()
+ if not config.ldap.host:
+ results.append(HealthCheckResult(
+ name="ldap_host_configured",
+ status=HealthStatus.FAIL,
+ message="LDAP host is not configured",
+ duration_seconds=time() - start_time,
+ ))
+ else:
+ results.append(HealthCheckResult(
+ name="ldap_host_configured",
+ status=HealthStatus.PASS,
+ message=f"LDAP host configured: {config.ldap.host}:{config.ldap.port}",
+ duration_seconds=time() - start_time,
+ ))
+
+ # Check 2: Can connect and bind
+ start_time = time()
+ try:
+ import ldap
+ protocol = "ldaps" if config.ldap.use_ssl else "ldap"
+ ldap_url = f"{protocol}://{config.ldap.host}:{config.ldap.port}"
+
+ conn = ldap.initialize(ldap_url)
+ conn.set_option(ldap.OPT_REFERRALS, 0)
+ conn.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
+ conn.set_option(ldap.OPT_NETWORK_TIMEOUT, 10)
+ conn.set_option(ldap.OPT_TIMEOUT, 10)
+
+ if config.ldap.use_starttls and not config.ldap.use_ssl:
+ conn.start_tls_s()
+
+ if config.ldap.bind_dn and config.ldap.bind_password:
+ conn.simple_bind_s(config.ldap.bind_dn, config.ldap.bind_password)
+ results.append(HealthCheckResult(
+ name="ldap_connection",
+ status=HealthStatus.PASS,
+ message=f"Successfully connected and bound as {config.ldap.bind_dn}",
+ duration_seconds=time() - start_time,
+ ))
+ else:
+ # Just test anonymous bind if no bind dn configured
+ conn.simple_bind_s("", "")
+ results.append(HealthCheckResult(
+ name="ldap_connection",
+ status=HealthStatus.PASS,
+ message="Successfully connected anonymously (no bind dn configured)",
+ duration_seconds=time() - start_time,
+ ))
+
+ try:
+ conn.unbind()
+ except Exception:
+ pass
+
+ except ImportError:
+ results.append(HealthCheckResult(
+ name="ldap_connection",
+ status=HealthStatus.FAIL,
+ message="python-ldap not installed, cannot test connection",
+ duration_seconds=time() - start_time,
+ ))
+ except Exception as e:
+ results.append(HealthCheckResult(
+ name="ldap_connection",
+ status=HealthStatus.WARN,
+ message=f"Failed to connect to LDAP: {str(e)[:200]}",
+ error=e,
+ duration_seconds=time() - start_time,
+ ))
+
+ # Check 3: Base DN is configured
+ start_time = time()
+ if config.ldap.base_dn:
+ results.append(HealthCheckResult(
+ name="ldap_base_dn_configured",
+ status=HealthStatus.PASS,
+ message=f"Base DN configured: {config.ldap.base_dn}",
+ duration_seconds=time() - start_time,
+ ))
+ else:
+ results.append(HealthCheckResult(
+ name="ldap_base_dn_configured",
+ status=HealthStatus.FAIL,
+ message="Base DN is not configured",
+ duration_seconds=time() - start_time,
+ ))
+
+ # Check 4: Identity mapping is valid
+ start_time = time()
+ try:
+ from openviking.server.auth.identity_mapping import IdentityMapper
+ # Just initialize the mapper
+ IdentityMapper(config.ldap.identity)
+ results.append(HealthCheckResult(
+ name="ldap_mapping_config_valid",
+ status=HealthStatus.PASS,
+ message="Identity mapping configuration is valid",
+ duration_seconds=time() - start_time,
+ ))
+ except Exception as e:
+ results.append(HealthCheckResult(
+ name="ldap_mapping_config_valid",
+ status=HealthStatus.WARN,
+ message=f"Identity mapping configuration check failed: {str(e)}",
+ error=e,
+ duration_seconds=time() - start_time,
+ ))
+
+ return results
+
+
+class ApiKeyAuthChecker(AuthHealthChecker):
+ """Health checker for API key auth mode."""
+
+ def name(self) -> str:
+ return "api_key"
+
+ async def run_checks(self, config: ServerConfig) -> List[HealthCheckResult]:
+ from time import time
+ results: List[HealthCheckResult] = []
+
+ # Check: Root API key is configured
+ start_time = time()
+ if config.root_api_key:
+ results.append(HealthCheckResult(
+ name="api_key_root_key_configured",
+ status=HealthStatus.PASS,
+ message="Root API key is configured",
+ duration_seconds=time() - start_time,
+ ))
+ else:
+ results.append(HealthCheckResult(
+ name="api_key_root_key_configured",
+ status=HealthStatus.WARN,
+ message="Root API key is not configured (will auto-select dev mode)",
+ duration_seconds=time() - start_time,
+ ))
+
+ return results
+
+
+class TrustedAuthChecker(AuthHealthChecker):
+ """Health checker for trusted auth mode."""
+
+ def name(self) -> str:
+ return "trusted"
+
+ async def run_checks(self, config: ServerConfig) -> List[HealthCheckResult]:
+ from time import time
+ results: List[HealthCheckResult] = []
+
+ # Basic config check
+ start_time = time()
+ results.append(HealthCheckResult(
+ name="trusted_config_valid",
+ status=HealthStatus.PASS,
+ message="Trusted mode configuration is valid",
+ duration_seconds=time() - start_time,
+ ))
+
+ return results
+
+
+class DevAuthChecker(AuthHealthChecker):
+ """Health checker for dev auth mode."""
+
+ def name(self) -> str:
+ return "dev"
+
+ async def run_checks(self, config: ServerConfig) -> List[HealthCheckResult]:
+ from time import time
+ results: List[HealthCheckResult] = []
+
+ # Check host is localhost
+ start_time = time()
+ if config.host in ["localhost", "127.0.0.1", "::1"]:
+ results.append(HealthCheckResult(
+ name="dev_host_local",
+ status=HealthStatus.PASS,
+ message=f"Host is set to loopback: {config.host}",
+ duration_seconds=time() - start_time,
+ ))
+ else:
+ results.append(HealthCheckResult(
+ name="dev_host_local",
+ status=HealthStatus.WARN,
+ message=f"Dev mode should be used with localhost only, current host: {config.host}",
+ duration_seconds=time() - start_time,
+ ))
+
+ return results
+
+
+# Registry of health checkers
+_AUTH_CHECKERS: Dict[str, AuthHealthChecker] = {}
+
+
+def register_checker(auth_mode: str, checker: AuthHealthChecker) -> None:
+ """Register an auth health checker for a mode."""
+ _AUTH_CHECKERS[auth_mode] = checker
+
+
+def get_checker(auth_mode: str) -> Optional[AuthHealthChecker]:
+ """Get the health checker for an auth mode."""
+ return _AUTH_CHECKERS.get(auth_mode)
+
+
+# Register default checkers
+register_checker("oidc", OIDCAuthChecker())
+register_checker("ldap", LDAPAuthChecker())
+register_checker("api_key", ApiKeyAuthChecker())
+register_checker("trusted", TrustedAuthChecker())
+register_checker("dev", DevAuthChecker())
+
+
+async def run_health_check(config: ServerConfig, fail_on_warn: bool = False) -> HealthCheckReport:
+ """Run health checks for the configured auth mode.
+
+ Args:
+ config: Server configuration.
+ fail_on_warn: If True, treat WARN as FAIL for overall status.
+
+ Returns:
+ HealthCheckReport with the results.
+ """
+ auth_mode = config.get_effective_auth_mode()
+ checker = get_checker(auth_mode)
+
+ if not checker:
+ logger.warning("No health checker registered for auth mode: %s", auth_mode)
+ return HealthCheckReport(
+ overall_status=HealthStatus.PASS,
+ checks=[HealthCheckResult(
+ name="no_checker",
+ status=HealthStatus.PASS,
+ message=f"No health checker available for mode: {auth_mode}",
+ )],
+ auth_mode=auth_mode,
+ summary=f"No health checks available for auth mode: {auth_mode}",
+ )
+
+ checks = await checker.run_checks(config)
+
+ # Determine overall status
+ has_fail = any(c.status == HealthStatus.FAIL for c in checks)
+ has_warn = any(c.status == HealthStatus.WARN for c in checks)
+
+ if has_fail:
+ overall_status = HealthStatus.FAIL
+ elif has_warn and fail_on_warn:
+ overall_status = HealthStatus.FAIL
+ elif has_warn:
+ overall_status = HealthStatus.WARN
+ else:
+ overall_status = HealthStatus.PASS
+
+ # Generate summary
+ fail_count = sum(1 for c in checks if c.status == HealthStatus.FAIL)
+ warn_count = sum(1 for c in checks if c.status == HealthStatus.WARN)
+ pass_count = sum(1 for c in checks if c.status == HealthStatus.PASS)
+
+ summary = f"Health check: {pass_count} passed, {warn_count} warnings, {fail_count} failed"
+
+ report = HealthCheckReport(
+ overall_status=overall_status,
+ checks=checks,
+ auth_mode=auth_mode,
+ summary=summary,
+ )
+
+ # Log results
+ logger.info("=" * 60)
+ logger.info("AUTHENTICATION HEALTH CHECK")
+ logger.info("=" * 60)
+ logger.info("Auth mode: %s", auth_mode)
+ logger.info("Overall: %s", overall_status.value.upper())
+ logger.info("-" * 60)
+
+ for check in checks:
+ icon = {
+ HealthStatus.PASS: "✅",
+ HealthStatus.WARN: "⚠️",
+ HealthStatus.FAIL: "❌",
+ }.get(check.status, "?")
+ log_func = {
+ HealthStatus.PASS: logger.info,
+ HealthStatus.WARN: logger.warning,
+ HealthStatus.FAIL: logger.error,
+ }.get(check.status, logger.info)
+
+ duration_str = f" ({check.duration_seconds:.2f}s)" if check.duration_seconds else ""
+ log_func("%s %s: %s%s", icon, check.name, check.message, duration_str)
+
+ if check.error:
+ logger.debug("Error detail: %r", check.error)
+
+ logger.info("-" * 60)
+ logger.info(summary)
+ logger.info("=" * 60)
+
+ return report
+
+
+async def run_startup_health_check_or_exit(config: ServerConfig) -> None:
+ """Run health check and exit with error if critical checks fail.
+
+ This function is used during server bootstrap to ensure authentication
+ configuration is valid before starting the server.
+ """
+ auth_mode = config.get_effective_auth_mode()
+ logger.info(f"[AUTH] Running authentication health check for auth_mode={auth_mode}")
+ report = await run_health_check(config, fail_on_warn=False)
+
+ for check in report.checks:
+ if check.status == HealthStatus.PASS:
+ logger.info(f"[AUTH] {check.name}: PASS - {check.message}")
+ elif check.status == HealthStatus.WARN:
+ logger.warning(f"[AUTH] {check.name}: WARN - {check.message}")
+ else:
+ logger.error(f"[AUTH] {check.name}: FAIL - {check.message}")
+
+ if report.overall_status == HealthStatus.FAIL:
+ logger.error("[AUTH] Authentication health check failed, aborting startup")
+ print("\n" + "=" * 60, file=sys.stderr)
+ print("FATAL: AUTHENTICATION HEALTH CHECK FAILED", file=sys.stderr)
+ print("=" * 60, file=sys.stderr)
+ for check in report.checks:
+ if check.status == HealthStatus.FAIL:
+ print(f" ❌ {check.name}: {check.message}", file=sys.stderr)
+ print("\nPlease fix the configuration issues above and try again.", file=sys.stderr)
+ sys.exit(1)
+ elif report.overall_status == HealthStatus.WARN:
+ logger.warning("[AUTH] Authentication health check passed with warnings")
+ else:
+ logger.info("[AUTH] Authentication health check passed")
diff --git a/openviking/server/auth/identity_mapping.py b/openviking/server/auth/identity_mapping.py
new file mode 100644
index 000000000..215a51829
--- /dev/null
+++ b/openviking/server/auth/identity_mapping.py
@@ -0,0 +1,334 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Identity mapping configuration for external auth providers (OIDC, LDAP)."""
+
+from __future__ import annotations
+
+import logging
+import re
+from typing import Any, Dict, List, Literal, Optional, Union
+
+from pydantic import BaseModel, Field, field_validator
+
+from openviking.server.identity import Role
+
+logger = logging.getLogger(__name__)
+
+# Mapping source types
+SourceType = Literal["claim", "attribute", "dn_attribute", "fixed", "composite"]
+
+# Account mode types
+AccountMode = Literal["team", "organization"]
+
+
+class MappingSource(BaseModel):
+ """Source configuration for identity mapping."""
+
+ source: SourceType
+ # For claim/attribute/dn_attribute
+ claim: Optional[str] = None
+ attribute: Optional[str] = None
+ # For fixed
+ value: Optional[str] = None
+ # For composite
+ parts: Optional[List[Union["MappingSource", Dict[str, Any]]]] = None
+ # Optional prefix
+ prefix: Optional[str] = None
+ # Optional regex extraction
+ regex: Optional[str] = None
+ regex_group: int = 1
+ # Optional value mapping
+ mapping: Optional[Dict[str, str]] = None
+ # Optional fallback
+ fallback: Optional[str] = None
+ # Optional normalization (lowercase, etc.)
+ normalize: Optional[Literal["lowercase", "uppercase", "trim"]] = None
+ # For list sources (try claims in order)
+ claims: Optional[List[str]] = None
+
+ model_config = {"extra": "forbid"}
+
+
+# Forward reference update
+MappingSource.model_rebuild()
+
+
+class AccountMappingConfig(BaseModel):
+ """Account ID mapping configuration."""
+
+ mode: AccountMode = "organization"
+ # Delegate all other fields to MappingSource
+ source: SourceType = "fixed"
+ claim: Optional[str] = None
+ attribute: Optional[str] = None
+ value: Optional[str] = "default"
+ parts: Optional[List[Union[MappingSource, Dict[str, Any]]]] = None
+ prefix: Optional[str] = None
+ regex: Optional[str] = None
+ regex_group: int = 1
+ mapping: Optional[Dict[str, str]] = None
+ fallback: Optional[str] = "default"
+ normalize: Optional[Literal["lowercase", "uppercase", "trim"]] = None
+ claims: Optional[List[str]] = None
+
+ model_config = {"extra": "forbid"}
+
+
+class UserMappingConfig(BaseModel):
+ """User ID mapping configuration."""
+
+ source: SourceType = "claim"
+ claim: Optional[str] = "sub"
+ attribute: Optional[str] = "uid"
+ value: Optional[str] = None
+ parts: Optional[List[Union[MappingSource, Dict[str, Any]]]] = None
+ prefix: Optional[str] = None
+ regex: Optional[str] = None
+ regex_group: int = 1
+ mapping: Optional[Dict[str, str]] = None
+ fallback: Optional[str] = None
+ normalize: Optional[Literal["lowercase", "uppercase", "trim"]] = None
+ claims: Optional[List[str]] = None
+
+ model_config = {"extra": "forbid"}
+
+
+class RoleMappingConfig(BaseModel):
+ """Role mapping configuration."""
+
+ source: Literal["claim", "attribute", "group_membership", "fixed"] = "claim"
+ # For claim/attribute
+ claim: Optional[str] = None
+ attribute: Optional[str] = None
+ # For fixed
+ value: Optional[str] = Role.USER
+ # For group_membership
+ group_mapping: Optional[Dict[str, str]] = None
+ # Value mapping
+ mapping: Optional[Dict[str, str]] = None
+ # Fallback
+ default: str = Role.USER
+
+ model_config = {"extra": "forbid"}
+
+
+class IdentityMappingConfig(BaseModel):
+ """Complete identity mapping configuration."""
+
+ account_id: AccountMappingConfig = Field(default_factory=AccountMappingConfig)
+ user_id: UserMappingConfig = Field(default_factory=UserMappingConfig)
+ role: RoleMappingConfig = Field(default_factory=RoleMappingConfig)
+
+ model_config = {"extra": "forbid"}
+
+
+class IdentityMapper:
+ """Identity mapper that applies mapping rules to external identities."""
+
+ def __init__(self, config: IdentityMappingConfig):
+ self.config = config
+
+ def _extract_value(
+ self,
+ source: Union[MappingSource, AccountMappingConfig, UserMappingConfig],
+ claims: Dict[str, Any],
+ attributes: Optional[Dict[str, str]] = None,
+ dn: Optional[str] = None,
+ groups: Optional[List[str]] = None,
+ ) -> Optional[str]:
+ """Extract value from source configuration."""
+ # Handle different source types
+ value: Optional[str] = None
+
+ if source.source == "fixed":
+ value = source.value if hasattr(source, "value") and source.value else None
+ elif source.source == "claim":
+ # Try multiple claims if provided
+ if hasattr(source, "claims") and source.claims:
+ for claim in source.claims:
+ if claim in claims:
+ v = claims.get(claim)
+ if v is not None:
+ value = str(v)
+ logger.debug("Found value from claim '%s': %s", claim, value[:50] if len(value) > 50 else value)
+ break
+ elif hasattr(source, "claim") and source.claim:
+ v = claims.get(source.claim)
+ if v is not None:
+ value = str(v)
+ logger.debug("Found value from claim '%s': %s", source.claim, value[:50] if len(value) > 50 else value)
+ elif source.source == "attribute" and attributes is not None:
+ if hasattr(source, "attribute") and source.attribute:
+ value = attributes.get(source.attribute)
+ if value:
+ logger.debug("Found value from attribute '%s': %s", source.attribute, value[:50] if len(value) > 50 else value)
+ elif source.source == "dn_attribute" and dn is not None:
+ # Extract attribute from DN (e.g., "ou=engineering,dc=example,dc=com" -> "engineering")
+ if hasattr(source, "attribute") and source.attribute:
+ attr = source.attribute.lower()
+ pattern = rf"{attr}=([^,]+)"
+ match = re.search(pattern, dn, re.IGNORECASE)
+ if match:
+ value = match.group(1)
+ logger.debug("Found value from DN attribute '%s': %s", source.attribute, value)
+ elif source.source == "composite" and hasattr(source, "parts") and source.parts:
+ # Build composite value from parts
+ parts: List[str] = []
+ for part in source.parts:
+ if isinstance(part, dict) and "literal" in part:
+ parts.append(str(part["literal"]))
+ else:
+ part_source = MappingSource.model_validate(part) if isinstance(part, dict) else part
+ part_value = self._extract_value(part_source, claims, attributes, dn, groups)
+ if part_value is not None:
+ parts.append(part_value)
+ value = "".join(parts) if parts else None
+ if value:
+ logger.debug("Composite value: %s", value[:50] if len(value) > 50 else value)
+
+ # Apply fallback if needed
+ if value is None and hasattr(source, "fallback"):
+ value = source.fallback
+ if value:
+ logger.debug("Using fallback value: %s", value)
+
+ if value is None:
+ logger.debug("No value extracted from source: %s", source.source)
+ return None
+
+ # Apply regex extraction
+ if hasattr(source, "regex") and source.regex:
+ try:
+ match = re.search(source.regex, value)
+ if match:
+ group_idx = source.regex_group if hasattr(source, "regex_group") else 1
+ if len(match.groups()) >= group_idx:
+ value = match.group(group_idx)
+ logger.debug("Applied regex, extracted: %s", value)
+ except re.error as e:
+ logger.warning("Invalid regex pattern '%s': %s", source.regex, e)
+
+ # Apply value mapping
+ if hasattr(source, "mapping") and source.mapping and value in source.mapping:
+ old_value = value
+ value = source.mapping[value]
+ logger.debug("Mapped value '%s' to '%s'", old_value, value)
+
+ # Apply prefix
+ if hasattr(source, "prefix") and source.prefix:
+ value = f"{source.prefix}{value}"
+
+ # Apply normalization
+ if hasattr(source, "normalize") and source.normalize and value:
+ if source.normalize == "lowercase":
+ value = value.lower()
+ elif source.normalize == "uppercase":
+ value = value.upper()
+ elif source.normalize == "trim":
+ value = value.strip()
+
+ return value
+
+ def map_account_id(
+ self,
+ claims: Dict[str, Any],
+ attributes: Optional[Dict[str, str]] = None,
+ dn: Optional[str] = None,
+ groups: Optional[List[str]] = None,
+ ) -> str:
+ """Map account ID from external identity."""
+ # Log available data for debugging
+ if claims:
+ logger.debug("Available claims for account_id mapping: %s", list(claims.keys()))
+ if attributes:
+ logger.debug("Available attributes for account_id mapping: %s", list(attributes.keys()))
+ if dn:
+ logger.debug("DN available for account_id mapping: %s", dn)
+
+ value = self._extract_value(
+ self.config.account_id, claims, attributes, dn, groups
+ )
+ if value is None:
+ raise ValueError(
+ f"Could not map account_id from external identity. "
+ f"Available claims: {list(claims.keys()) if claims else []}, "
+ f"Available attributes: {list(attributes.keys()) if attributes else []}"
+ )
+ logger.debug("Mapped account_id: %s", value)
+ return value
+
+ def map_user_id(
+ self,
+ claims: Dict[str, Any],
+ attributes: Optional[Dict[str, str]] = None,
+ dn: Optional[str] = None,
+ groups: Optional[List[str]] = None,
+ ) -> str:
+ """Map user ID from external identity."""
+ # Log available data for debugging
+ if claims:
+ logger.debug("Available claims for user_id mapping: %s", list(claims.keys()))
+ if attributes:
+ logger.debug("Available attributes for user_id mapping: %s", list(attributes.keys()))
+
+ value = self._extract_value(
+ self.config.user_id, claims, attributes, dn, groups
+ )
+ if value is None:
+ raise ValueError(
+ f"Could not map user_id from external identity. "
+ f"Available claims: {list(claims.keys()) if claims else []}, "
+ f"Available attributes: {list(attributes.keys()) if attributes else []}"
+ )
+ logger.debug("Mapped user_id: %s", value)
+ return value
+
+ def map_role(
+ self,
+ claims: Dict[str, Any],
+ attributes: Optional[Dict[str, str]] = None,
+ dn: Optional[str] = None,
+ groups: Optional[List[str]] = None,
+ ) -> Role:
+ """Map role from external identity."""
+ role_config = self.config.role
+
+ if role_config.source == "fixed" and role_config.value:
+ logger.debug("Using fixed role: %s", role_config.value)
+ return Role(role_config.value)
+
+ if groups:
+ logger.debug("Available groups for role mapping: %s", groups[:5]) # Log first 5 groups
+
+ value: Optional[str] = None
+ if role_config.source in ("claim", "attribute"):
+ if role_config.source == "claim" and role_config.claim:
+ v = claims.get(role_config.claim)
+ if v is not None:
+ value = str(v)
+ elif role_config.source == "attribute" and attributes and role_config.attribute:
+ value = attributes.get(role_config.attribute)
+
+ if value is not None:
+ if role_config.mapping and value in role_config.mapping:
+ role_str = role_config.mapping[value]
+ logger.debug("Mapped role from value '%s': %s", value, role_str)
+ return Role(role_str)
+ # Try direct role name
+ try:
+ logger.debug("Trying direct role name: %s", value.lower())
+ return Role(value.lower())
+ except (ValueError, AttributeError):
+ logger.debug("Direct role mapping failed for value '%s'", value)
+ pass
+
+ if role_config.source == "group_membership" and groups and role_config.group_mapping:
+ # Check group membership in order
+ logger.debug("Checking group membership for role mapping")
+ for group, role_str in role_config.group_mapping.items():
+ if group in groups:
+ logger.debug("Found role '%s' from group membership: %s", role_str, group)
+ return Role(role_str)
+
+ logger.debug("Using default role: %s", role_config.default)
+ return Role(role_config.default)
diff --git a/openviking/server/auth/ldap_config.py b/openviking/server/auth/ldap_config.py
new file mode 100644
index 000000000..d9bb34ec2
--- /dev/null
+++ b/openviking/server/auth/ldap_config.py
@@ -0,0 +1,82 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""LDAP authentication plugin configuration."""
+
+from __future__ import annotations
+
+from typing import Optional
+
+from pydantic import BaseModel, Field, field_validator
+
+from openviking.server.auth.identity_mapping import (
+ IdentityMappingConfig,
+ UserMappingConfig,
+)
+
+
+def _ldap_default_identity() -> IdentityMappingConfig:
+ """LDAP-specific default identity mapping.
+
+ LDAP entries carry directory attributes rather than JWT claims, so the
+ generic ``IdentityMappingConfig`` defaults (``user_id <- claim:sub``)
+ cannot work. The documented out-of-the-box contract is:
+
+ * ``account_id`` -> fixed "default"
+ * ``user_id`` -> LDAP attribute ``uid``
+
+ Operators can override any field via the ``identity`` config block.
+ """
+ return IdentityMappingConfig(
+ user_id=UserMappingConfig(
+ source="attribute",
+ claim=None,
+ attribute="uid",
+ ),
+ )
+
+
+class LDAPConfig(BaseModel):
+ """LDAP authentication plugin configuration."""
+
+ # LDAP server configuration
+ host: str
+ port: int = 389
+ use_ssl: bool = False
+ use_starttls: bool = False
+ # Bind credentials for searching users
+ bind_dn: Optional[str] = None
+ bind_password: Optional[str] = None
+ # User search configuration
+ base_dn: str
+ user_search_filter: str = "(uid=%s)"
+ user_search_base: Optional[str] = None
+ # Attribute mapping for user info
+ username_attribute: str = "uid"
+ email_attribute: str = "mail"
+ name_attribute: str = "cn"
+ # Direct bind pattern (alternative to search+bind)
+ user_dn_pattern: Optional[str] = None
+ # Identity mapping (LDAP-specific defaults: user_id <- uid, role=user)
+ identity: IdentityMappingConfig = Field(
+ default_factory=_ldap_default_identity
+ )
+
+ model_config = {"extra": "forbid"}
+
+ @field_validator("host")
+ @classmethod
+ def validate_host(cls, v: str) -> str:
+ """Validate host."""
+ v = v.strip()
+ if not v:
+ raise ValueError("host cannot be empty")
+ return v
+
+ @field_validator("base_dn")
+ @classmethod
+ def validate_base_dn(cls, v: str) -> str:
+ """Validate base DN."""
+ v = v.strip()
+ if not v:
+ raise ValueError("base_dn cannot be empty")
+ return v
diff --git a/openviking/server/auth/oidc_config.py b/openviking/server/auth/oidc_config.py
new file mode 100644
index 000000000..82a44a7f4
--- /dev/null
+++ b/openviking/server/auth/oidc_config.py
@@ -0,0 +1,41 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""OIDC (OpenID Connect) authentication plugin configuration."""
+
+from __future__ import annotations
+
+from typing import Dict, List, Literal, Optional
+
+from pydantic import BaseModel, Field, field_validator
+
+from openviking.server.auth.identity_mapping import IdentityMappingConfig
+
+
+class OIDCConfig(BaseModel):
+ """OIDC authentication plugin configuration."""
+
+ # Basic OIDC configuration
+ issuer: str
+ client_id: Optional[str] = None
+ client_secret: Optional[str] = None
+ # Token validation
+ audience: Optional[str] = None
+ # JWKS configuration (auto-discovery from .well-known/openid-configuration if not set)
+ jwks_uri: Optional[str] = None
+ # Token location
+ token_location: Literal["header", "query"] = "header"
+ token_header_name: str = "Authorization"
+ token_header_prefix: str = "Bearer "
+ # Identity mapping
+ identity: IdentityMappingConfig = Field(default_factory=IdentityMappingConfig)
+
+ model_config = {"extra": "forbid"}
+
+ @field_validator("issuer")
+ @classmethod
+ def validate_issuer(cls, v: str) -> str:
+ """Validate issuer URL."""
+ v = v.rstrip("/")
+ if not v:
+ raise ValueError("issuer cannot be empty")
+ return v
diff --git a/openviking/server/auth/plugins/__init__.py b/openviking/server/auth/plugins/__init__.py
index c2cb7b915..4ec2155fe 100644
--- a/openviking/server/auth/plugins/__init__.py
+++ b/openviking/server/auth/plugins/__init__.py
@@ -13,8 +13,28 @@ _registry.register(DevAuthPlugin)
_registry.register(ApiKeyAuthPlugin)
_registry.register(TrustedAuthPlugin)
+# Try to register OIDC and LDAP plugins if dependencies are available
+try:
+ from openviking.server.auth.plugins.oidc import OIDCAuthPlugin
+ _registry.register(OIDCAuthPlugin)
+ _has_oidc = True
+except ImportError:
+ _has_oidc = False
+
+try:
+ from openviking.server.auth.plugins.ldap import LDAPAuthPlugin
+ _registry.register(LDAPAuthPlugin)
+ _has_ldap = True
+except ImportError:
+ _has_ldap = False
+
__all__ = [
"DevAuthPlugin",
"ApiKeyAuthPlugin",
"TrustedAuthPlugin",
]
+
+if _has_oidc:
+ __all__.append("OIDCAuthPlugin")
+if _has_ldap:
+ __all__.append("LDAPAuthPlugin")
diff --git a/openviking/server/auth/plugins/ldap.py b/openviking/server/auth/plugins/ldap.py
new file mode 100644
index 000000000..3efe5d66c
--- /dev/null
+++ b/openviking/server/auth/plugins/ldap.py
@@ -0,0 +1,467 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""LDAP authentication plugin.
+
+Supports authenticating users against an LDAP server (Active Directory, OpenLDAP, etc.)
+and mapping LDAP attributes to OpenViking identities.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import sys
+from typing import Any, Dict, List, Optional, Tuple
+
+from fastapi import Request
+
+from openviking.server.auth.identity_mapping import IdentityMapper
+from openviking.server.auth.ldap_config import LDAPConfig
+from openviking.server.auth.plugin import AuthPlugin
+from openviking.server.identity import ResolvedIdentity, Role
+from openviking_cli.exceptions import UnauthenticatedError
+
+logger = logging.getLogger(__name__)
+
+# Try to import LDAP library, provide helpful error if missing
+try:
+ import ldap
+ import ldap.filter
+
+ LDAP_AVAILABLE = True
+except ImportError:
+ LDAP_AVAILABLE = False
+ logger.warning(
+ "LDAP library not available. LDAP authentication will not work. "
+ "Install with: uv pip install python-ldap"
+ )
+
+
+# Network/operation timeout (seconds) for synchronous LDAP calls. The calls
+# are offloaded to a thread executor (see _authenticate_ldap), but a hung LDAP
+# server must not be allowed to tie up a thread indefinitely.
+_LDAP_NETWORK_TIMEOUT = 10.0
+_LDAP_OPERATION_TIMEOUT = 10.0
+
+
+def _apply_ldap_connection_options(conn: Any) -> None:
+ """Apply standard connection options including network timeouts."""
+ conn.set_option(ldap.OPT_REFERRALS, 0) # Disable chasing referrals
+ conn.set_option(ldap.OPT_PROTOCOL_VERSION, 3) # LDAPv3
+ # Bound blocking I/O — without these a dead LDAP server can hang the
+ # worker thread for the OS default (often minutes).
+ conn.set_option(ldap.OPT_NETWORK_TIMEOUT, _LDAP_NETWORK_TIMEOUT)
+ conn.set_option(ldap.OPT_TIMEOUT, _LDAP_OPERATION_TIMEOUT)
+
+
+def _format_user_dn(pattern: str, username: str) -> str:
+ """Render a user DN pattern.
+
+ Supports two idioms:
+
+ * ``"%s"`` positional substitution, the classic LDAP template style
+ (``uid=%s,ou=users,dc=example,dc=com``).
+ * ``"%(username)s"`` / ``"%(user)s"`` mapping substitution.
+ """
+ if "%(" in pattern:
+ return pattern % {"username": username, "user": username}
+ # Only substitute a single %s; treat %% as an escaped %.
+ return pattern % (username,)
+
+
+class LDAPAuthPlugin(AuthPlugin):
+ """LDAP authentication plugin.
+
+ Authenticates users against an LDAP server and maps attributes
+ to OpenViking account/user identities.
+ """
+
+ auth_mode = "ldap"
+
+ def __init__(self) -> None:
+ self._config: Optional[LDAPConfig] = None
+ self._mapper: Optional[IdentityMapper] = None
+
+ async def resolve_identity(
+ self,
+ request: Request,
+ *,
+ api_key: Optional[str] = None,
+ x_openviking_account: Optional[str] = None,
+ x_openviking_user: Optional[str] = None,
+ ) -> ResolvedIdentity:
+ """Resolve identity from LDAP authentication."""
+ if not LDAP_AVAILABLE:
+ raise UnauthenticatedError(
+ "LDAP authentication not available: missing python-ldap"
+ )
+ if self._config is None:
+ raise RuntimeError("LDAP config not initialized")
+ if self._mapper is None:
+ raise RuntimeError("Identity mapper not initialized")
+
+ # Extract credentials from request
+ username, password = await self._extract_credentials(
+ request,
+ api_key,
+ x_openviking_user,
+ )
+ if not username or not password:
+ raise UnauthenticatedError("Missing LDAP credentials (username/password)")
+
+ # Authenticate against LDAP server and return attributes.
+ # python-ldap is a synchronous binding to OpenLDAP's libldap; every
+ # network call blocks. Offload to the default thread executor so a
+ # slow/unreachable directory cannot stall the event loop (and thus
+ # unrelated requests on the same worker).
+ try:
+ attributes = await asyncio.to_thread(
+ self._authenticate_ldap, username, password
+ )
+ logger.debug("Successfully authenticated LDAP user: %s", username)
+ # Log available attributes for debugging
+ if attributes:
+ logger.debug(
+ "Available LDAP attributes: %s", list(attributes.keys())
+ )
+ except ldap.LDAPError as e:
+ error_code = getattr(e, "args", [None])[0] if e.args else None
+ logger.debug(
+ "LDAP authentication failed for user %s - Error: %s, Code: %s",
+ username,
+ str(e),
+ error_code,
+ )
+ raise UnauthenticatedError(f"LDAP authentication failed: {e}") from e
+
+ # Map LDAP attributes to OpenViking identity.
+ # Role is always USER for LDAP-authenticated identities. This is by
+ # design: LDAP authenticates directory users, and their role in the
+ # directory (e.g., membership in an "admins" group) should not
+ # automatically grant OpenViking admin privileges. Operators who
+ # need admin access should use the root API key mechanism.
+ try:
+ normalized_attrs = self._normalize_attributes(attributes)
+ dn_bytes = attributes.get("dn", [None])[0] if attributes else None
+ dn = dn_bytes.decode("utf-8") if dn_bytes else None
+
+ account_id = self._mapper.map_account_id(
+ claims={}, attributes=normalized_attrs, dn=dn
+ )
+ user_id = self._mapper.map_user_id(
+ claims={}, attributes=normalized_attrs, dn=dn
+ )
+ except ValueError as e:
+ logger.error("Failed to map LDAP attributes: %s", e)
+ raise UnauthenticatedError(f"Failed to map attributes: {e}") from e
+
+ logger.debug(
+ "Successfully authenticated LDAP user: account=%s, user=%s, role=%s",
+ account_id,
+ user_id,
+ Role.USER,
+ )
+
+ return ResolvedIdentity(role=Role.USER, account_id=account_id, user_id=user_id)
+
+ async def _extract_credentials(
+ self,
+ request: Request,
+ api_key: Optional[str] = None,
+ x_openviking_user: Optional[str] = None,
+ ) -> Tuple[Optional[str], Optional[str]]:
+ """Extract username and password from request."""
+ # Try Basic Auth first
+ auth_header = request.headers.get("Authorization")
+ if auth_header and auth_header.lower().startswith("basic "):
+ import base64
+
+ try:
+ encoded = auth_header.split(" ", 1)[1]
+ decoded = base64.b64decode(encoded).decode("utf-8")
+ username, password = decoded.split(":", 1)
+ return username, password
+ except Exception: # noqa: BLE001
+ pass
+
+ # Try form data
+ try:
+ form = await request.form()
+ username = form.get("username")
+ password = form.get("password")
+ if username and password:
+ return str(username), str(password)
+ except Exception: # noqa: BLE001
+ pass
+
+ # Fallback: use api_key as password if x_openviking_user is present
+ if x_openviking_user and api_key:
+ return x_openviking_user, api_key
+
+ return None, None
+
+ def _new_connection(self, ldap_url: str) -> Any:
+ conn = ldap.initialize(ldap_url)
+ _apply_ldap_connection_options(conn)
+ if self._config.use_starttls and not self._config.use_ssl:
+ conn.start_tls_s()
+ return conn
+
+ def _search_user_attributes(
+ self,
+ conn: Any,
+ username: str,
+ ) -> Tuple[Optional[str], Dict[str, List[bytes]]]:
+ """Search for a user's DN and attributes using the bound connection.
+
+ Used both by the search+bind flow (with the service account) and the
+ direct-bind flow (where the bound user typically has read access to
+ their own entry).
+ """
+ assert self._config is not None
+ safe_username = ldap.filter.escape_filter_chars(username)
+ search_filter = self._config.user_search_filter % safe_username
+ search_base = (
+ self._config.user_search_base or self._config.base_dn
+ )
+ logger.debug(
+ "Searching for user with filter: %s, base: %s",
+ search_filter,
+ search_base,
+ )
+
+ result = conn.search_s(
+ search_base,
+ ldap.SCOPE_SUBTREE,
+ search_filter,
+ ["*"],
+ )
+
+ for dn, attrs in result:
+ if dn: # Skip referrals / continuation references
+ return dn, attrs
+ return None, {}
+
+ def _authenticate_ldap(
+ self, username: str, password: str
+ ) -> Dict[str, List[bytes]]:
+ """Authenticate user against LDAP server and return attributes.
+
+ This is a synchronous method; callers must run it in a worker thread.
+ """
+ if self._config is None:
+ raise RuntimeError("LDAP config not initialized")
+
+ protocol = "ldaps" if self._config.use_ssl else "ldap"
+ ldap_url = f"{protocol}://{self._config.host}:{self._config.port}"
+
+ user_dn: Optional[str] = None
+ user_attrs: Dict[str, List[bytes]] = {}
+
+ if self._config.bind_dn and self._config.bind_password:
+ # --- Search + Bind flow -----------------------------------------
+ # 1. Bind as a service account, search for the user entry.
+ # 2. Rebind as the user to verify the supplied password.
+ # 3. Re-bind as the service account to read attributes (the user
+ # bind may not have read access to its own object in some
+ # deployments).
+ search_conn = self._new_connection(ldap_url)
+ try:
+ search_conn.simple_bind_s(
+ self._config.bind_dn, self._config.bind_password
+ )
+ user_dn, user_attrs = self._search_user_attributes(
+ search_conn, username
+ )
+ finally:
+ try:
+ search_conn.unbind()
+ except Exception: # noqa: BLE001
+ pass
+
+ if not user_dn:
+ raise UnauthenticatedError(f"User {username} not found")
+
+ # Validate the user's credentials.
+ user_conn = self._new_connection(ldap_url)
+ try:
+ user_conn.simple_bind_s(user_dn, password)
+ finally:
+ try:
+ user_conn.unbind()
+ except Exception: # noqa: BLE001
+ pass
+
+ # Re-bind as the service account to fetch attributes if the first
+ # search didn't return them (shouldn't normally happen).
+ if not user_attrs:
+ attr_conn = self._new_connection(ldap_url)
+ try:
+ attr_conn.simple_bind_s(
+ self._config.bind_dn, self._config.bind_password
+ )
+ user_dn, user_attrs = self._search_user_attributes(
+ attr_conn, username
+ )
+ finally:
+ try:
+ attr_conn.unbind()
+ except Exception: # noqa: BLE001
+ pass
+
+ elif self._config.user_dn_pattern:
+ # --- Direct Bind flow -------------------------------------------
+ # No service account: construct the user's DN from the pattern,
+ # bind as the user directly, then attempt to read their own
+ # attributes using the bound connection.
+ user_dn = _format_user_dn(self._config.user_dn_pattern, username)
+
+ conn = self._new_connection(ldap_url)
+ try:
+ conn.simple_bind_s(user_dn, password)
+ # Best-effort attribute read: most directory ACLs permit a
+ # user to read their own entry. If the server forbids it, we
+ # fall back to synthesizing attributes from the DN so that
+ # the documented ``user_id <- uid`` default still works for
+ # ``uid=<username>,...`` patterns.
+ try:
+ _, found_attrs = self._search_user_attributes(conn, username)
+ if found_attrs:
+ user_attrs = found_attrs
+ except ldap.LDAPError as e:
+ logger.debug(
+ "Direct bind: unable to read own attributes for %s: %s",
+ username,
+ e,
+ )
+ finally:
+ try:
+ conn.unbind()
+ except Exception: # noqa: BLE001
+ pass
+
+ if not user_attrs:
+ # Fallback: derive the RDN attribute/value pair from the DN.
+ # For ``uid=alice,ou=users,...`` this yields {"uid": [b"alice"]}.
+ user_attrs = self._attrs_from_dn(user_dn)
+ else:
+ raise UnauthenticatedError(
+ "LDAP config requires either bind_dn/bind_password or "
+ "user_dn_pattern"
+ )
+
+ # Ensure DN is present in attributes for identity mapping.
+ if user_dn:
+ user_attrs.setdefault("dn", [user_dn.encode("utf-8")])
+ # Always make the DN RDN value available under its attribute name
+ # so the default user_id <- uid mapping works even if the server
+ # returned no attributes.
+ rdn_attr, rdn_value = self._parse_first_rdn(user_dn)
+ if rdn_attr and rdn_value:
+ user_attrs.setdefault(
+ rdn_attr.lower(), [rdn_value.encode("utf-8")]
+ )
+
+ return user_attrs
+
+ @staticmethod
+ def _parse_first_rdn(dn: str) -> Tuple[Optional[str], Optional[str]]:
+ """Parse the first RDN of a DN, returning (attr_name, value)."""
+ if not dn:
+ return None, None
+ first = dn.split(",", 1)[0]
+ if "=" not in first:
+ return None, None
+ attr, _, value = first.partition("=")
+ return attr.strip(), value.strip()
+
+ @classmethod
+ def _attrs_from_dn(cls, dn: str) -> Dict[str, List[bytes]]:
+ """Build a minimal attribute dict from a DN.
+
+ Used as a fallback when a direct-bind user cannot read their own
+ entry. Extracts the first RDN pair (e.g. ``uid=alice``).
+ """
+ attr, value = cls._parse_first_rdn(dn)
+ if not attr or not value:
+ return {}
+ return {attr.lower(): [value.encode("utf-8")]}
+
+ def _normalize_attributes(
+ self, attributes: Dict[str, List[bytes]]
+ ) -> Dict[str, str]:
+ """Normalize LDAP attributes from bytes to strings."""
+ normalized: Dict[str, str] = {}
+ for key, values in attributes.items():
+ if values:
+ try:
+ normalized[key.lower()] = values[0].decode("utf-8")
+ except UnicodeDecodeError:
+ try:
+ normalized[key.lower()] = values[0].decode("latin-1")
+ except UnicodeDecodeError:
+ normalized[key.lower()] = ""
+ return normalized
+
+ def validate_config(self, config) -> None:
+ """Validate LDAP configuration."""
+ if config.ldap is None:
+ logger.error(
+ "auth_mode=ldap but 'ldap' section missing in config. "
+ "Please configure the LDAP server settings."
+ )
+ sys.exit(1)
+
+ if not config.ldap.host:
+ logger.error("LDAP config missing 'host'")
+ sys.exit(1)
+
+ if not config.ldap.base_dn:
+ logger.error("LDAP config missing 'base_dn'")
+ sys.exit(1)
+
+ if not config.ldap.bind_dn and not config.ldap.user_dn_pattern:
+ logger.error(
+ "LDAP config requires either 'bind_dn'/'bind_password' or "
+ "'user_dn_pattern'"
+ )
+ sys.exit(1)
+
+ if config.ldap.bind_dn and not config.ldap.bind_password:
+ logger.warning(
+ "LDAP config has 'bind_dn' but missing 'bind_password' — "
+ "searches may fail"
+ )
+
+ logger.info("LDAP config validated successfully")
+
+ async def initialize(self, app, service, config) -> None:
+ """Initialize LDAP plugin."""
+ if config.ldap is None:
+ raise RuntimeError("LDAP config missing")
+
+ self._config = config.ldap
+
+ # LDAPConfig supplies LDAP-specific defaults (user_id <- uid,
+ # fixed USER role) via default_factory, so no fallback is needed
+ # here. Operators can still override via the `identity` config block.
+ self._mapper = IdentityMapper(self._config.identity)
+
+ logger.info(
+ "LDAP auth plugin initialized with host=%s", self._config.host
+ )
+
+ def requires_api_key_manager(self) -> bool:
+ """LDAP does not map external identities to admin roles, so no
+ APIKeyManager is needed. Admin API access is gated by role checks."""
+ return False
+
+ def can_skip_api_key_for_bot_proxy(self) -> bool:
+ """LDAP does not declare bot-proxy compatibility until VikingBot
+ natively understands the ``ldap`` auth mode (mode inference, Basic
+ Auth credential propagation, and identity forwarding to bot tools).
+
+ Returning False here makes ``--with-bot`` fail fast with a clear
+ error instead of producing a silent auth-mode mismatch at runtime.
+ """
+ return False
diff --git a/openviking/server/auth/plugins/oidc.py b/openviking/server/auth/plugins/oidc.py
new file mode 100644
index 000000000..3fb152356
--- /dev/null
+++ b/openviking/server/auth/plugins/oidc.py
@@ -0,0 +1,368 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""OIDC (OpenID Connect) authentication plugin.
+
+Supports validating JWT tokens from external OIDC providers (Okta, Auth0, Keycloak, etc.)
+and mapping claims to OpenViking identities.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import re
+import sys
+from typing import Any, Dict, Optional, TYPE_CHECKING
+
+from fastapi import Request
+
+from openviking.server.auth.identity_mapping import IdentityMapper
+from openviking.server.auth.oidc_config import OIDCConfig
+from openviking.server.auth.plugin import AuthPlugin
+from openviking.server.identity import ResolvedIdentity, Role
+from openviking_cli.exceptions import UnauthenticatedError
+
+if TYPE_CHECKING:
+ from jose.backends.base import Key
+
+logger = logging.getLogger(__name__)
+
+# Characters allowed in OpenViking user/account identifiers. Any character
+# not in this set (e.g. Auth0's "|" in sub="auth0|123456") is replaced with
+# "_" during identity mapping.
+_ALLOWED_IDENTIFIER_CHARS = re.compile(r"[^a-zA-Z0-9_.@-]")
+
+def _check_jwt_available() -> bool:
+ """Lazy check for JWT library availability (cached after first call)."""
+ global httpx, JWTError, jwk, jwt, Key, ExpiredSignatureError, JWTClaimsError
+
+ if not hasattr(_check_jwt_available, "_cached"):
+ try:
+ import httpx # noqa: F401
+ from jose import JWTError, jwk, jwt # noqa: F401
+ from jose.backends.base import Key # noqa: F401
+ from jose.exceptions import ExpiredSignatureError, JWTClaimsError # noqa: F401
+ _check_jwt_available._cached = True
+ except ImportError:
+ logger.warning(
+ "JWT libraries not available. OIDC authentication will not work. "
+ "Install with: uv pip install python-jose[cryptography] httpx"
+ )
+ _check_jwt_available._cached = False
+ return _check_jwt_available._cached
+
+
+# Supported signing algorithms. Asymmetric algorithms are preferred for OIDC;
+# HMAC algorithms are included for completeness but require a shared secret.
+_SUPPORTED_ALGORITHMS = [
+ "RS256", "RS384", "RS512",
+ "ES256", "ES384", "ES512",
+ "PS256", "PS384", "PS512",
+ "HS256", "HS384", "HS512",
+]
+
+_DISCOVERY_PATH = "/.well-known/openid-configuration"
+_DISCOVERY_TIMEOUT = 10.0
+
+
+class OIDCAuthPlugin(AuthPlugin):
+ """OIDC authentication plugin.
+
+ Validates JWT tokens from an external OIDC provider and maps claims
+ to OpenViking account/user identities.
+ """
+
+ auth_mode = "oidc"
+
+ def __init__(self) -> None:
+ self._config: Optional[OIDCConfig] = None
+ self._jwks: Dict[str, Key] = {}
+ self._mapper: Optional[IdentityMapper] = None
+ self._jwks_uri: Optional[str] = None
+ self._discovery_lock = asyncio.Lock()
+
+ async def resolve_identity(
+ self,
+ request: Request,
+ *,
+ api_key: Optional[str] = None,
+ x_openviking_account: Optional[str] = None,
+ x_openviking_user: Optional[str] = None,
+ ) -> ResolvedIdentity:
+ """Resolve identity from OIDC JWT token."""
+ if not _check_jwt_available():
+ raise UnauthenticatedError(
+ "OIDC authentication not available: missing python-jose and httpx"
+ )
+ if self._config is None:
+ raise RuntimeError("OIDC config not initialized")
+ if self._mapper is None:
+ raise RuntimeError("Identity mapper not initialized")
+
+ # Extract token from request
+ token = self._extract_token(request, api_key)
+ if not token:
+ raise UnauthenticatedError("Missing OIDC JWT token")
+
+ # Validate token and get claims
+ try:
+ claims = await self._validate_token(token)
+ # Log available claims (safely - don't log sensitive values)
+ logger.debug("Available claims from token: %s", list(claims.keys()))
+ # Log a safe subset of claims for debugging
+ safe_claims = ["iss", "sub", "aud", "exp", "iat", "azp", "kid"]
+ for claim in safe_claims:
+ if claim in claims:
+ logger.debug("Claim '%s': %s", claim, claims[claim])
+ except (JWTError, UnauthenticatedError) as e:
+ logger.debug("Token validation failed: %s", e)
+ raise UnauthenticatedError(f"Invalid OIDC token: {e}") from e
+
+ # Map claims to OpenViking identity.
+ # Role is always USER for OIDC-authenticated identities. External
+ # identity providers determine authentication, not authorization;
+ # operators who need admin access should use the root API key mechanism.
+ try:
+ account_id = self._mapper.map_account_id(claims=claims)
+ user_id = self._mapper.map_user_id(claims=claims)
+ # Sanitize: replace characters not allowed in OpenViking identifiers
+ # (e.g. Auth0's "|" in sub="auth0|123456") so that valid OIDC
+ # tokens from supported providers always produce a usable identity.
+ user_id = _ALLOWED_IDENTIFIER_CHARS.sub("_", user_id)
+ account_id = _ALLOWED_IDENTIFIER_CHARS.sub("_", account_id)
+ except ValueError as e:
+ logger.error("Failed to map claims: %s", e)
+ raise UnauthenticatedError(f"Failed to map claims: {e}") from e
+
+ logger.debug(
+ "Successfully authenticated OIDC user: account=%s, user=%s, role=%s",
+ account_id,
+ user_id,
+ Role.USER,
+ )
+
+ return ResolvedIdentity(role=Role.USER, account_id=account_id, user_id=user_id)
+
+ def _extract_token(
+ self, request: Request, api_key: Optional[str] = None
+ ) -> Optional[str]:
+ """Extract JWT token from request."""
+ if self._config is None:
+ return None
+
+ # Try Authorization header first
+ if self._config.token_location == "header":
+ auth_header = request.headers.get(self._config.token_header_name)
+ if auth_header:
+ prefix = self._config.token_header_prefix
+ if prefix and auth_header.startswith(prefix):
+ return auth_header[len(prefix):].strip()
+ # Without a configured prefix, accept raw bearer token
+ return auth_header.strip()
+
+ # Try query parameter
+ if self._config.token_location == "query":
+ query_params = request.query_params
+ token = query_params.get("access_token")
+ if token:
+ return token
+
+ # Fallback: check if api_key is a JWT (to support SDK use)
+ if api_key and api_key.count(".") == 2:
+ # Looks like a JWT (header.payload.signature)
+ return api_key
+
+ return None
+
+ async def _validate_token(self, token: str) -> Dict[str, Any]:
+ """Validate JWT token and return claims."""
+ if self._config is None:
+ raise RuntimeError("OIDC config not initialized")
+
+ # Get key ID from token header
+ try:
+ header = jwt.get_unverified_header(token)
+ except JWTError as e:
+ raise UnauthenticatedError("Invalid token format") from e
+
+ kid = header.get("kid")
+ if not kid:
+ raise UnauthenticatedError("Token header missing 'kid'")
+
+ # Get key for validation
+ key = await self._get_key(kid)
+
+ # audience is guaranteed non-None after validate_config() — either the
+ # operator configured it explicitly or we fell back to client_id.
+ # Audience validation must NEVER be skipped: an IdP commonly issues
+ # tokens for many audiences, and accepting a token intended for another
+ # application would be a cross-client trust violation.
+ assert self._effective_audience is not None
+
+ # Validate token
+ try:
+ claims = jwt.decode(
+ token,
+ key,
+ algorithms=_SUPPORTED_ALGORITHMS,
+ options={
+ "verify_aud": True,
+ "verify_exp": True,
+ "verify_iss": True,
+ },
+ issuer=self._config.issuer,
+ audience=self._effective_audience,
+ )
+ return claims
+ except ExpiredSignatureError:
+ raise UnauthenticatedError("Token expired")
+ except JWTClaimsError as e:
+ raise UnauthenticatedError(f"Invalid claims: {e}")
+ except JWTError as e:
+ raise UnauthenticatedError(f"Token validation failed: {e}")
+
+ async def _discover_jwks_uri(self) -> str:
+ """Perform OIDC Discovery to locate the JWKS endpoint.
+
+ Standard flow (per OpenID Connect Discovery 1.0):
+ 1. GET ``{issuer}/.well-known/openid-configuration``
+ 2. Read the ``jwks_uri`` field from the returned metadata.
+
+ If an explicit ``jwks_uri`` is configured, it takes precedence and
+ no discovery request is made.
+ """
+ if self._config is None:
+ raise RuntimeError("OIDC config not initialized")
+
+ if self._config.jwks_uri:
+ return self._config.jwks_uri
+
+ async with self._discovery_lock:
+ # Re-check after acquiring the lock to avoid redundant fetches.
+ if self._jwks_uri:
+ return self._jwks_uri
+
+ discovery_url = f"{self._config.issuer}{_DISCOVERY_PATH}"
+ logger.info("Performing OIDC discovery at %s", discovery_url)
+ try:
+ async with httpx.AsyncClient(timeout=_DISCOVERY_TIMEOUT) as client:
+ response = await client.get(discovery_url)
+ response.raise_for_status()
+ metadata = response.json()
+ except (httpx.HTTPError, ValueError) as e:
+ logger.error("OIDC discovery failed for %s: %s", discovery_url, e)
+ raise UnauthenticatedError(
+ f"Failed to fetch OIDC discovery document from {discovery_url}: {e}"
+ ) from e
+
+ jwks_uri = metadata.get("jwks_uri")
+ if not jwks_uri or not isinstance(jwks_uri, str):
+ logger.error(
+ "OIDC discovery document at %s did not contain a jwks_uri",
+ discovery_url,
+ )
+ raise UnauthenticatedError(
+ "OIDC discovery document is missing 'jwks_uri'"
+ )
+
+ logger.info("OIDC discovery resolved jwks_uri=%s", jwks_uri)
+ self._jwks_uri = jwks_uri
+ return jwks_uri
+
+ async def _get_key(self, kid: str) -> Key:
+ """Get JWK key for signature validation."""
+ if self._config is None:
+ raise RuntimeError("OIDC config not initialized")
+
+ # Return cached key if available
+ if kid in self._jwks:
+ return self._jwks[kid]
+
+ jwks_uri = await self._discover_jwks_uri()
+
+ try:
+ async with httpx.AsyncClient(timeout=10.0) as client:
+ response = await client.get(jwks_uri)
+ response.raise_for_status()
+ jwks = response.json()
+ except (httpx.HTTPError, ValueError) as e:
+ logger.error("Failed to fetch JWKS from %s: %s", jwks_uri, e)
+ raise UnauthenticatedError("Failed to fetch JWKS") from e
+
+ # Process keys and cache them
+ for key_dict in jwks.get("keys", []):
+ key_kid = key_dict.get("kid")
+ if key_kid:
+ try:
+ self._jwks[key_kid] = jwk.construct(key_dict)
+ except Exception as e: # noqa: BLE001
+ logger.warning(
+ "Failed to construct key for kid=%s: %s", key_kid, e
+ )
+
+ if kid not in self._jwks:
+ raise UnauthenticatedError(f"Unknown key ID: {kid}")
+
+ return self._jwks[kid]
+
+ def validate_config(self, config) -> None:
+ """Validate OIDC configuration.
+
+ Enforces that an audience can be resolved (explicit ``audience`` or
+ ``client_id``) so that tokens issued for other clients are rejected.
+ """
+ if config.oidc is None:
+ logger.error(
+ "auth_mode=oidc but 'oidc' section missing in config. "
+ "Please configure the OIDC provider settings."
+ )
+ sys.exit(1)
+
+ if not config.oidc.issuer:
+ logger.error("OIDC config missing 'issuer'")
+ sys.exit(1)
+
+ if not config.oidc.audience and not config.oidc.client_id:
+ logger.error(
+ "OIDC config requires either 'audience' or 'client_id' to "
+ "validate the token's 'aud' claim. Refusing to start without "
+ "audience validation."
+ )
+ sys.exit(1)
+
+ logger.info("OIDC config validated successfully")
+
+ async def initialize(self, app, service, config) -> None:
+ """Initialize OIDC plugin."""
+ if config.oidc is None:
+ raise RuntimeError("OIDC config missing")
+
+ self._config = config.oidc
+ self._mapper = IdentityMapper(self._config.identity)
+
+ # Resolve the effective audience once. Explicit audience wins;
+ # otherwise fall back to client_id (standard OIDC ID token contract).
+ self._effective_audience: Optional[str] = (
+ self._config.audience or self._config.client_id
+ )
+
+ logger.info(
+ "OIDC auth plugin initialized with issuer=%s, audience=%s",
+ self._config.issuer,
+ self._effective_audience,
+ )
+
+ def requires_api_key_manager(self) -> bool:
+ """OIDC does not map external identities to admin roles, so no
+ APIKeyManager is needed. Admin API access is gated by role checks."""
+ return False
+
+ def can_skip_api_key_for_bot_proxy(self) -> bool:
+ """OIDC does not declare bot-proxy compatibility until VikingBot
+ natively understands the ``oidc`` auth mode and can propagate the
+ bearer token to downstream tool calls.
+
+ Returning False here makes ``--with-bot`` fail fast with a clear
+ error instead of producing a silent auth-mode mismatch at runtime.
+ """
+ return False
diff --git a/openviking/server/bootstrap.py b/openviking/server/bootstrap.py
index 4a35548e7..cc50f180e 100644
--- a/openviking/server/bootstrap.py
+++ b/openviking/server/bootstrap.py
@@ -2,6 +2,7 @@
# SPDX-License-Identifier: AGPL-3.0
"""Bootstrap script for OpenViking HTTP Server."""
+import asyncio
import argparse
import json
import os
@@ -218,6 +219,18 @@ def main():
print(e, file=sys.stderr)
sys.exit(1)
+ # Configure logging early so that all subsequent steps have proper logging
+ configure_uvicorn_logging()
+
+ # 🔍 Authentication health check - CRITICAL: will exit if check fails
+ try:
+ from openviking.server.auth.health_check import run_startup_health_check_or_exit
+ asyncio.run(run_startup_health_check_or_exit(config))
+ except Exception as e:
+ # Don't fail startup if health check itself has issues
+ print(f"Warning: Authentication health check failed to run: {e}", file=sys.stderr)
+ print("Continuing startup anyway...", file=sys.stderr)
+
# Ensure Ollama is running if configured
try:
from openviking_cli.utils.ollama import detect_ollama_in_config, ensure_ollama_for_server
@@ -249,9 +262,6 @@ def main():
if args.with_bot:
config.with_bot = True
- # Configure logging for Uvicorn
- configure_uvicorn_logging()
-
bot_process: Optional[BotProcess] = None
if config.with_bot:
bot_port = args.bot_port
diff --git a/openviking/server/config.py b/openviking/server/config.py
index 2eb47ea96..121c8328b 100644
--- a/openviking/server/config.py
+++ b/openviking/server/config.py
@@ -8,6 +8,8 @@ from typing import Dict, List, Literal, Optional
from pydantic import BaseModel, Field, ValidationError, field_validator
# Import auth plugin registry for config validation
+from openviking.server.auth.ldap_config import LDAPConfig
+from openviking.server.auth.oidc_config import OIDCConfig
from openviking.server.auth.registry import get_registry
from openviking.server.identity import AuthMode
from openviking_cli.utils import get_logger
@@ -270,6 +272,9 @@ class ServerConfig(BaseModel):
workers: int = 1
auth_mode: Optional[str] = None # If None, auto-detect based on root_api_key
root_api_key: Optional[str] = None
+ # OIDC/LDAP authentication configuration
+ oidc: Optional[OIDCConfig] = None
+ ldap: Optional[LDAPConfig] = None
profile_enabled: bool = False
cors_origins: List[str] = Field(default_factory=lambda: ["*"])
with_bot: bool = False # Enable Bot API proxy to Vikingbot
diff --git a/openviking_cli/doctor.py b/openviking_cli/doctor.py
index fa45d02b1..852dadd5a 100644
--- a/openviking_cli/doctor.py
+++ b/openviking_cli/doctor.py
@@ -578,6 +578,62 @@ def check_vikingbot() -> CheckResult:
return "pass", "bot.ov_server.api_key configured for api_key mode", None
+def check_authentication() -> CheckResult:
+ """Check authentication configuration using auth health checks."""
+ config_path = _find_config()
+ if config_path is None:
+ return "warn", "Cannot check (no config file)", None
+
+ data = _load_config_json(config_path)
+ if data is None:
+ return "warn", "Cannot check (config unreadable)", None
+
+ # Load server config
+ try:
+ from openviking.server.auth.health_check import run_health_check
+ from openviking.server.config import ServerConfig
+
+ server_data = data.get("server", {}) if isinstance(data.get("server"), dict) else {}
+ config = ServerConfig(**server_data)
+ except ImportError:
+ return "warn", "Auth health check not available (module missing)", None
+ except Exception as exc:
+ return "warn", f"Could not load server config: {exc}", None
+
+ # Run auth health checks
+ try:
+ report = asyncio.run(run_health_check(config, fail_on_warn=False))
+ except Exception as exc:
+ return "warn", f"Auth health check failed to run: {exc}", None
+
+ # Format results
+ auth_mode = report.auth_mode
+ pass_count = sum(1 for c in report.checks if c.status == "pass")
+ warn_count = sum(1 for c in report.checks if c.status == "warn")
+ fail_count = sum(1 for c in report.checks if c.status == "fail")
+
+ detail = f"{auth_mode}: {pass_count} passed, {warn_count} warned, {fail_count} failed"
+
+ if report.overall_status == "pass":
+ return "pass", detail, None
+ elif report.overall_status == "warn":
+ # Collect warning messages
+ warn_msgs = []
+ for c in report.checks:
+ if c.status == "warn":
+ warn_msgs.append(f" - {c.name}: {c.message}")
+ fix = "\n".join(warn_msgs) if warn_msgs else None
+ return "warn", detail, fix
+ else:
+ # Collect fail messages
+ fail_msgs = []
+ for c in report.checks:
+ if c.status == "fail":
+ fail_msgs.append(f" - {c.name}: {c.message}")
+ fix = "\n".join(fail_msgs) if fail_msgs else None
+ return "fail", detail, fix
+
+
def check_disk() -> tuple[bool, str, Optional[str]]:
"""Check free disk space in the workspace directory."""
config_path = _find_config()
@@ -614,6 +670,7 @@ _CHECKS = [
("Python", check_python),
("Native Engine", check_native_engine),
("AGFS", check_agfs),
+ ("Authentication", check_authentication),
("Embedding", check_embedding),
("VLM", check_vlm),
("Ollama", check_ollama),
diff --git a/openviking_cli/utils/config/ovcli_config.py b/openviking_cli/utils/config/ovcli_config.py
index 9fd7ee1a2..e88a10a3e 100644
--- a/openviking_cli/utils/config/ovcli_config.py
+++ b/openviking_cli/utils/config/ovcli_config.py
@@ -51,6 +51,12 @@ class OVCLIConfig(BaseModel):
# opaque so a harness can add its own knobs without touching this schema.
plugin: Optional[Dict[str, Any]] = None
+ # Authentication mode: "api_key", "ldap", "oidc"
+ auth_mode: Optional[str] = None
+ # LDAP credentials
+ ldap_username: Optional[str] = None
+ ldap_password: Optional[str] = None
+
model_config = {"extra": "forbid"}
@model_validator(mode="before")
@@ -58,7 +64,6 @@ class OVCLIConfig(BaseModel):
def handle_extra_headers_aliases(cls, data: Any) -> Any:
if isinstance(data, dict):
data = dict(data)
- # 支持 extra_header 作为 extra_headers 的别名
extra_header = data.pop("extra_header", None)
if extra_header is not None and "extra_headers" not in data:
data["extra_headers"] = extra_header
@@ -68,6 +73,19 @@ class OVCLIConfig(BaseModel):
def reject_mixed_actor_and_agent_identity(self) -> "OVCLIConfig":
if self.actor_peer_id is not None and self.agent_id is not None:
raise ValueError("actor_peer_id cannot be used with agent_id")
+
+ # auth_mode must be one of the supported types
+ valid_auth_modes = {None, "api_key", "ldap", "oidc"}
+ if self.auth_mode not in valid_auth_modes:
+ raise ValueError(
+ f"auth_mode must be one of: "
+ f"{', '.join(str(m) for m in valid_auth_modes if m is not None)}"
+ )
+
+ # In ldap mode, username is required (user field may serve as an alias)
+ if self.auth_mode == "ldap" and not self.ldap_username and not self.user:
+ pass
+
return self
diff --git a/pyproject.toml b/pyproject.toml
index 2706fde36..cf42fcb27 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -94,19 +94,24 @@ dependencies = [
[project.optional-dependencies]
test = [
- "pytest>=7.0.0",
- "pytest-asyncio>=0.21.0",
- "pytest-xdist>=3.5.0",
- "boto3>=1.42.44",
- "pytest-cov>=4.0.0",
- "ragas>=0.1.0",
- "datasets>=2.0.0",
- "pandas>=2.0.0",
- "diff-match-patch>=20200713",
- "hvac>=2.0.0",
+ "pytest>=7.0.0",
+ "pytest-asyncio>=0.21.0",
+ "pytest-xdist>=3.5.0",
+ "boto3>=1.42.44",
+ "pytest-cov>=4.0.0",
+ "ragas>=0.1.0",
+ "datasets>=2.0.0",
+ "pandas>=2.0.0",
+ "diff-match-patch>=20200713",
+ "hvac>=2.0.0",
+]
+auth = [
+ "python-jose[cryptography]>=3.3.0",
+ "httpx>=0.25.0",
+ "python-ldap>=3.4.0",
]
opengauss = [
- "psycopg2-binary>=2.9",
+ "psycopg2-binary>=2.9",
]
dev = [
"mypy>=1.0.0",
@@ -142,39 +147,41 @@ build = [
]
# vikingbot - all features included
bot = [
- "pydantic-settings>=2.0.0",
- "websockets>=12.0",
- "websocket-client>=1.6.0",
- "httpx[socks]>=0.25.0",
- "readability-lxml>=0.8.0",
- "rich>=13.0.0",
- "croniter>=2.0.0",
- "socksio>=1.0.0",
- "python-socketio>=5.16.2",
- "python-engineio>=4.13.2",
- "msgpack>=1.0.8",
- "python-socks[asyncio]>=2.4.0",
- "prompt-toolkit>=3.0.0",
- "pygments>=2.16.0",
- "html2text>=2020.1.16",
- "beautifulsoup4>=4.12.0",
- "ddgs>=9.0.0",
- "tavily-python>=0.5.0",
- "gradio>=6.6.0",
- "py-machineid>=1.0.0",
- "mcp>=1,<2",
- # All optional features included by default
- "langfuse>=3.0.0",
- "python-telegram-bot[socks]>=21.0",
- "lark-oapi>=1.0.0",
- "dingtalk-stream>=0.4.0",
- "slack-sdk>=3.26.0",
- "qq-botpy>=1.0.0",
- "opensandbox>=0.1.0",
- "opensandbox-server>=0.1.0",
- "agent-sandbox>=0.0.23",
- "fusepy>=3.0.1",
- "opencode-ai>=0.1.0a0",
+ "pydantic-settings>=2.0.0",
+ "websockets>=12.0",
+ "websocket-client>=1.6.0",
+ "httpx[socks]>=0.25.0",
+ "readability-lxml>=0.8.0",
+ "rich>=13.0.0",
+ "croniter>=2.0.0",
+ "socksio>=1.0.0",
+ "python-socketio>=5.16.2",
+ "python-engineio>=4.13.2",
+ "msgpack>=1.0.8",
+ "python-socks[asyncio]>=2.4.0",
+ "prompt-toolkit>=3.0.0",
+ "pygments>=2.16.0",
+ "html2text>=2020.1.16",
+ "beautifulsoup4>=4.12.0",
+ "ddgs>=9.0.0",
+ "tavily-python>=0.5.0",
+ "gradio>=6.6.0",
+ "py-machineid>=1.0.0",
+ "mcp>=1,<2",
+ # All optional features included by default
+ "langfuse>=3.0.0",
+ "python-telegram-bot[socks]>=21.0",
+ "lark-oapi>=1.0.0",
+ "dingtalk-stream>=0.4.0",
+ "slack-sdk>=3.26.0",
+ "qq-botpy>=1.0.0",
+ "opensandbox>=0.1.0",
+ "opensandbox-server>=0.1.0",
+ "agent-sandbox>=0.0.23",
+ "fusepy>=3.0.1",
+ "opencode-ai>=0.1.0a0",
+ # Auth dependencies
+ "python-jose[cryptography]>=3.3.0",
]
benchmark = [
"langchain>=1.0.0",
diff --git a/sdk/python/openviking_sdk/client.py b/sdk/python/openviking_sdk/client.py
index 525fa50c8..eddacc352 100644
--- a/sdk/python/openviking_sdk/client.py
+++ b/sdk/python/openviking_sdk/client.py
@@ -352,6 +352,12 @@ class AsyncHTTPClient:
profile_enabled: Optional[bool] = None,
upload_mode: Optional[str] = None,
event_hooks: Optional[Dict[str, List[Callable[..., Any]]]] = None,
+ # LDAP parameters
+ auth_mode: Optional[str] = None,
+ ldap_username: Optional[str] = None,
+ ldap_password: Optional[str] = None,
+ # OIDC parameters
+ oidc_token: Optional[str] = None,
):
if actor_peer_id and agent_id:
raise ValueError("actor_peer_id cannot be used with agent_id")
@@ -367,6 +373,10 @@ class AsyncHTTPClient:
extra_headers=extra_headers,
profile_enabled=profile_enabled,
upload_mode=upload_mode,
+ auth_mode=auth_mode,
+ ldap_username=ldap_username,
+ ldap_password=ldap_password,
+ oidc_token=oidc_token,
)
self._url = config.url
self._api_key = config.api_key
@@ -378,6 +388,10 @@ class AsyncHTTPClient:
self._extra_headers = config.extra_headers
self._profile_enabled = config.profile_enabled
self._upload_mode = config.upload_mode
+ self._auth_mode = config.auth_mode
+ self._ldap_username = config.ldap_username
+ self._ldap_password = config.ldap_password
+ self._oidc_token = config.oidc_token
self._event_hooks = {
event: list(hooks) for event, hooks in (event_hooks or {}).items()
}
@@ -395,6 +409,23 @@ class AsyncHTTPClient:
headers["X-OpenViking-User"] = self._user_id
if self._actor_peer_id:
headers["X-OpenViking-Actor-Peer"] = self._actor_peer_id
+
+ # LDAP Basic Auth
+ if self._auth_mode == "ldap" and self._ldap_username and self._ldap_password:
+ from .config import get_basic_auth_header
+ headers["Authorization"] = get_basic_auth_header(
+ self._ldap_username, self._ldap_password
+ )
+
+ # OIDC Bearer token. An explicit oidc_token wins; otherwise fall back
+ # to api_key when it looks like a JWT (header.payload.signature).
+ if self._auth_mode == "oidc":
+ token = self._oidc_token
+ if not token and self._api_key and self._api_key.count(".") == 2:
+ token = self._api_key
+ if token:
+ headers["Authorization"] = f"Bearer {token}"
+
headers.update(self._extra_headers)
self._http = httpx.AsyncClient(
base_url=self._url,
diff --git a/sdk/python/openviking_sdk/config.py b/sdk/python/openviking_sdk/config.py
index 6822dda1d..91cae6412 100644
--- a/sdk/python/openviking_sdk/config.py
+++ b/sdk/python/openviking_sdk/config.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import base64
import json
import os
from dataclasses import dataclass
@@ -23,6 +24,12 @@ class ClientConfig:
extra_headers: dict[str, str]
gateway_token: Optional[str]
upload_mode: Optional[str]
+ # LDAP authentication (None when auth mode is not LDAP)
+ auth_mode: Optional[str]
+ ldap_username: Optional[str]
+ ldap_password: Optional[str]
+ # OIDC authentication (None when auth mode is not OIDC)
+ oidc_token: Optional[str]
@dataclass(frozen=True)
@@ -39,6 +46,12 @@ class OVCLIConfig:
gateway_token: Optional[str]
upload_mode: Optional[str]
output: Optional[str]
+ # LDAP authentication
+ auth_mode: Optional[str]
+ ldap_username: Optional[str]
+ ldap_password: Optional[str]
+ # OIDC authentication
+ oidc_token: Optional[str]
def _resolve_ovcli_config_path() -> Optional[Path]:
@@ -139,6 +152,13 @@ def load_ovcli_config(config_path: Optional[str] = None) -> Optional[OVCLIConfig
"root_api_key",
"gateway_token",
"plugin",
+ # Authentication
+ "auth_mode",
+ # LDAP
+ "ldap_username",
+ "ldap_password",
+ # OIDC
+ "oidc_token",
}
unknown_keys = sorted(set(data) - allowed_keys)
if unknown_keys:
@@ -155,9 +175,7 @@ def load_ovcli_config(config_path: Optional[str] = None) -> Optional[OVCLIConfig
unknown_upload_keys = sorted(set(upload) - allowed_upload_keys)
if unknown_upload_keys:
raise _unknown_field_error(
- "ovcli.upload",
- unknown_upload_keys[0],
- allowed_upload_keys,
+ "ovcli.upload", unknown_upload_keys[0], allowed_upload_keys
)
upload_mode = _optional_string(upload.get("mode"), path="ovcli.upload.mode")
@@ -168,6 +186,19 @@ def load_ovcli_config(config_path: Optional[str] = None) -> Optional[OVCLIConfig
timeout = _optional_float(data.get("timeout"), path="ovcli.timeout")
profile = _optional_bool(data.get("profile"), path="ovcli.profile")
+
+ # Parse LDAP config
+ auth_mode = _optional_string(data.get("auth_mode"), path="ovcli.auth_mode")
+ ldap_username = _optional_string(
+ data.get("ldap_username"), path="ovcli.ldap_username"
+ )
+ ldap_password = _optional_string(
+ data.get("ldap_password"), path="ovcli.ldap_password"
+ )
+ oidc_token = _optional_string(
+ data.get("oidc_token"), path="ovcli.oidc_token"
+ )
+
return OVCLIConfig(
url=_optional_string(data.get("url"), path="ovcli.url"),
api_key=_optional_string(data.get("api_key"), path="ovcli.api_key"),
@@ -181,11 +212,25 @@ def load_ovcli_config(config_path: Optional[str] = None) -> Optional[OVCLIConfig
gateway_token=_optional_string(data.get("gateway_token"), path="ovcli.gateway_token"),
upload_mode=upload_mode,
output=_optional_string(data.get("output"), path="ovcli.output"),
+ auth_mode=auth_mode,
+ ldap_username=ldap_username,
+ ldap_password=ldap_password,
+ oidc_token=oidc_token,
)
except ValueError as exc:
raise ValueError(f"Invalid CLI config in {path}: {exc}") from exc
+def _resolve_env_or_config(env_var: str, explicit: Optional[str], config_value: Optional[str]) -> Optional[str]:
+ """Helper to resolve value: explicit arg > env var > config file."""
+ if explicit is not None:
+ return explicit
+ env_value = os.getenv(env_var)
+ if env_value is not None:
+ return env_value
+ return config_value
+
+
def resolve_client_config(
*,
url: Optional[str] = None,
@@ -197,9 +242,36 @@ def resolve_client_config(
extra_headers: Optional[dict[str, str]] = None,
profile_enabled: Optional[bool] = None,
upload_mode: Optional[str] = None,
+ # LDAP parameters
+ auth_mode: Optional[str] = None,
+ ldap_username: Optional[str] = None,
+ ldap_password: Optional[str] = None,
+ # OIDC parameters
+ oidc_token: Optional[str] = None,
) -> ClientConfig:
cli_config = load_ovcli_config()
+ # Resolve LDAP config (explicit arg > env var > config file)
+ resolved_auth_mode = _resolve_env_or_config(
+ "OPENVIKING_AUTH_MODE", auth_mode,
+ cli_config.auth_mode if cli_config else None
+ )
+ resolved_ldap_username = _resolve_env_or_config(
+ "OPENVIKING_USERNAME", ldap_username,
+ cli_config.ldap_username if cli_config else None
+ )
+ resolved_ldap_password = _resolve_env_or_config(
+ "OPENVIKING_PASSWORD", ldap_password,
+ cli_config.ldap_password if cli_config else None
+ )
+ # OIDC token: explicit arg > env var > config file.
+ # When auth_mode is oidc and no token is resolvable, leave it None so
+ # callers can choose to fall back to an api_key that looks like a JWT.
+ resolved_oidc_token = _resolve_env_or_config(
+ "OPENVIKING_OIDC_TOKEN", oidc_token,
+ cli_config.oidc_token if cli_config else None
+ )
+
resolved_url = url or os.getenv("OPENVIKING_URL") or (cli_config.url if cli_config else None)
resolved_api_key = (
api_key or os.getenv("OPENVIKING_API_KEY") or (cli_config.api_key if cli_config else None)
@@ -265,4 +337,15 @@ def resolve_client_config(
extra_headers=resolved_extra_headers,
gateway_token=resolved_gateway_token,
upload_mode=resolved_upload_mode,
+ auth_mode=resolved_auth_mode,
+ ldap_username=resolved_ldap_username,
+ ldap_password=resolved_ldap_password,
+ oidc_token=resolved_oidc_token,
)
+
+
+def get_basic_auth_header(username: str, password: str) -> str:
+ """生成 HTTP Basic Auth header 值."""
+ credentials = f"{username}:{password}".encode("utf-8")
+ encoded = base64.b64encode(credentials).decode("ascii")
+ return f"Basic {encoded}"
diff --git a/sdk/python/tests/test_ldap_auth.py b/sdk/python/tests/test_ldap_auth.py
new file mode 100644
index 000000000..f085e53cb
--- /dev/null
+++ b/sdk/python/tests/test_ldap_auth.py
@@ -0,0 +1,422 @@
+import pytest
+import base64
+import json
+import os
+from pathlib import Path
+
+from openviking_sdk import AsyncHTTPClient
+from openviking_sdk.config import (
+ resolve_client_config,
+ get_basic_auth_header,
+ load_ovcli_config,
+)
+
+
+class TestBasicAuthHeader:
+ """测试 Basic Auth header 生成"""
+
+ def test_get_basic_auth_header(self):
+ """测试 Basic Auth header 编码正确"""
+ header = get_basic_auth_header("alice", "password123")
+ expected = "Basic " + base64.b64encode(b"alice:password123").decode("ascii")
+ assert header == expected
+
+ def test_get_basic_auth_header_special_characters(self):
+ """测试特殊字符的密码"""
+ header = get_basic_auth_header("user", "p@ss:w0rd!")
+ expected = "Basic " + base64.b64encode(b"user:p@ss:w0rd!").decode("ascii")
+ assert header == expected
+
+ def test_get_basic_auth_header_unicode(self):
+ """测试 Unicode 字符"""
+ header = get_basic_auth_header("user", "pässwörd")
+ expected = "Basic " + base64.b64encode("user:pässwörd".encode("utf-8")).decode("ascii")
+ assert header == expected
+
+
+class TestClientConfigLDAP:
+ """测试 LDAP 配置解析"""
+
+ def test_explicit_ldap_arguments(self):
+ """测试显式传递 LDAP 参数"""
+ config = resolve_client_config(
+ url="http://localhost:1933",
+ auth_mode="ldap",
+ ldap_username="alice",
+ ldap_password="password123",
+ )
+ assert config.auth_mode == "ldap"
+ assert config.ldap_username == "alice"
+ assert config.ldap_password == "password123"
+ assert config.api_key is None
+
+ def test_env_ldap_variables(self, monkeypatch):
+ """测试环境变量 LDAP 配置"""
+ # Isolate from the real user config
+ import openviking_sdk.config as config_module
+ original_default = config_module.DEFAULT_OVCLI_CONF
+ config_module.DEFAULT_OVCLI_CONF = Path("/nonexistent/path/ovcli.conf")
+ monkeypatch.delenv("OPENVIKING_CLI_CONFIG_FILE", raising=False)
+ monkeypatch.setenv("OPENVIKING_URL", "http://env-host:1933")
+ monkeypatch.setenv("OPENVIKING_AUTH_MODE", "ldap")
+ monkeypatch.setenv("OPENVIKING_USERNAME", "bob")
+ monkeypatch.setenv("OPENVIKING_PASSWORD", "secret456")
+ monkeypatch.delenv("OPENVIKING_API_KEY", raising=False)
+
+ try:
+ config = resolve_client_config()
+ assert config.auth_mode == "ldap"
+ assert config.ldap_username == "bob"
+ assert config.ldap_password == "secret456"
+ finally:
+ config_module.DEFAULT_OVCLI_CONF = original_default
+
+ def test_explicit_overrides_env(self, monkeypatch):
+ """测试显式参数覆盖环境变量"""
+ import openviking_sdk.config as config_module
+ original_default = config_module.DEFAULT_OVCLI_CONF
+ config_module.DEFAULT_OVCLI_CONF = Path("/nonexistent/path/ovcli.conf")
+ monkeypatch.delenv("OPENVIKING_CLI_CONFIG_FILE", raising=False)
+ monkeypatch.setenv("OPENVIKING_AUTH_MODE", "ldap")
+ monkeypatch.setenv("OPENVIKING_USERNAME", "env-user")
+ monkeypatch.setenv("OPENVIKING_PASSWORD", "env-pass")
+
+ try:
+ config = resolve_client_config(
+ url="http://localhost:1933",
+ auth_mode="ldap",
+ ldap_username="explicit-user",
+ ldap_password="explicit-pass",
+ )
+ assert config.auth_mode == "ldap"
+ assert config.ldap_username == "explicit-user"
+ assert config.ldap_password == "explicit-pass"
+ finally:
+ config_module.DEFAULT_OVCLI_CONF = original_default
+
+ def test_no_ldap_config_defaults(self, monkeypatch):
+ """测试无 LDAP 配置时的默认值"""
+ monkeypatch.delenv("OPENVIKING_AUTH_MODE", raising=False)
+ monkeypatch.delenv("OPENVIKING_USERNAME", raising=False)
+ monkeypatch.delenv("OPENVIKING_PASSWORD", raising=False)
+ monkeypatch.delenv("OPENVIKING_CLI_CONFIG_FILE", raising=False)
+
+ # Need to make sure no user config is loaded
+ # Patch the default config path to not exist
+ import openviking_sdk.config as config_module
+ original_default = config_module.DEFAULT_OVCLI_CONF
+ config_module.DEFAULT_OVCLI_CONF = Path("/nonexistent/path/ovcli.conf")
+ try:
+ config = resolve_client_config(url="http://localhost:1933")
+ assert config.auth_mode is None
+ assert config.ldap_username is None
+ assert config.ldap_password is None
+ finally:
+ config_module.DEFAULT_OVCLI_CONF = original_default
+
+ def test_ldap_partial_config(self, monkeypatch):
+ """测试部分 LDAP 配置"""
+ monkeypatch.delenv("OPENVIKING_AUTH_MODE", raising=False)
+ monkeypatch.delenv("OPENVIKING_USERNAME", raising=False)
+ monkeypatch.delenv("OPENVIKING_PASSWORD", raising=False)
+ monkeypatch.delenv("OPENVIKING_CLI_CONFIG_FILE", raising=False)
+
+ import openviking_sdk.config as config_module
+ original_default = config_module.DEFAULT_OVCLI_CONF
+ config_module.DEFAULT_OVCLI_CONF = Path("/nonexistent/path/ovcli.conf")
+ try:
+ # 只设置 username,不设置 password
+ config = resolve_client_config(
+ url="http://localhost:1933",
+ ldap_username="alice",
+ )
+ assert config.ldap_username == "alice"
+ assert config.ldap_password is None
+ finally:
+ config_module.DEFAULT_OVCLI_CONF = original_default
+
+
+class TestConfigFileLDAP:
+ """测试配置文件中的 LDAP 配置"""
+
+ def test_load_ldap_config_from_file(self, tmp_path, monkeypatch):
+ """测试从配置文件加载 LDAP 配置"""
+ config_data = {
+ "url": "http://file-host:1933",
+ "auth_mode": "ldap",
+ "ldap_username": "config-user",
+ "ldap_password": "config-pass",
+ "account": "default",
+ }
+ config_file = tmp_path / "ovcli.conf"
+ config_file.write_text(json.dumps(config_data))
+
+ # 设置配置文件路径
+ monkeypatch.setenv("OPENVIKING_CLI_CONFIG_FILE", str(config_file))
+ # 清除其他环境变量
+ monkeypatch.delenv("OPENVIKING_AUTH_MODE", raising=False)
+ monkeypatch.delenv("OPENVIKING_USERNAME", raising=False)
+ monkeypatch.delenv("OPENVIKING_PASSWORD", raising=False)
+
+ config = load_ovcli_config()
+ assert config is not None
+ assert config.url == "http://file-host:1933"
+ assert config.auth_mode == "ldap"
+ assert config.ldap_username == "config-user"
+ assert config.ldap_password == "config-pass"
+
+ def test_config_file_ldap_missing_password(self, tmp_path, monkeypatch):
+ """测试配置文件中缺少密码"""
+ config_data = {
+ "url": "http://file-host:1933",
+ "auth_mode": "ldap",
+ "ldap_username": "config-user",
+ # password 缺失
+ }
+ config_file = tmp_path / "ovcli.conf"
+ config_file.write_text(json.dumps(config_data))
+
+ monkeypatch.setenv("OPENVIKING_CLI_CONFIG_FILE", str(config_file))
+
+ config = load_ovcli_config()
+ assert config is not None
+ assert config.ldap_username == "config-user"
+ assert config.ldap_password is None
+
+ def test_config_file_api_key_mode(self, tmp_path, monkeypatch):
+ """测试 API Key 模式(向后兼容)"""
+ config_data = {
+ "url": "http://file-host:1933",
+ "api_key": "sk-test-key",
+ # 没有 auth_mode,默认使用 API Key
+ }
+ config_file = tmp_path / "ovcli.conf"
+ config_file.write_text(json.dumps(config_data))
+
+ monkeypatch.setenv("OPENVIKING_CLI_CONFIG_FILE", str(config_file))
+
+ config = load_ovcli_config()
+ assert config is not None
+ assert config.api_key == "sk-test-key"
+ assert config.auth_mode is None
+
+
+class TestAsyncHTTPClientLDAP:
+ """测试 AsyncHTTPClient 的 LDAP 支持"""
+
+ def test_client_ldap_attributes(self, monkeypatch):
+ """测试客户端存储 LDAP 属性"""
+ monkeypatch.delenv("OPENVIKING_CLI_CONFIG_FILE", raising=False)
+ import openviking_sdk.config as config_module
+ original_default = config_module.DEFAULT_OVCLI_CONF
+ config_module.DEFAULT_OVCLI_CONF = Path("/nonexistent/path/ovcli.conf")
+ try:
+ client = AsyncHTTPClient(
+ url="http://localhost:1933",
+ auth_mode="ldap",
+ ldap_username="alice",
+ ldap_password="password123",
+ )
+ assert client._auth_mode == "ldap"
+ assert client._ldap_username == "alice"
+ assert client._ldap_password == "password123"
+ finally:
+ config_module.DEFAULT_OVCLI_CONF = original_default
+
+ def test_client_no_ldap_by_default(self, monkeypatch):
+ """测试默认不使用 LDAP"""
+ monkeypatch.delenv("OPENVIKING_CLI_CONFIG_FILE", raising=False)
+ import openviking_sdk.config as config_module
+ original_default = config_module.DEFAULT_OVCLI_CONF
+ config_module.DEFAULT_OVCLI_CONF = Path("/nonexistent/path/ovcli.conf")
+ try:
+ client = AsyncHTTPClient(
+ url="http://localhost:1933",
+ api_key="sk-test",
+ )
+ assert client._auth_mode is None
+ assert client._ldap_username is None
+ assert client._ldap_password is None
+ finally:
+ config_module.DEFAULT_OVCLI_CONF = original_default
+
+ @pytest.mark.asyncio
+ async def test_client_initialize_with_ldap(self, monkeypatch):
+ """测试初始化时添加 LDAP header"""
+ monkeypatch.delenv("OPENVIKING_CLI_CONFIG_FILE", raising=False)
+ import openviking_sdk.config as config_module
+ original_default = config_module.DEFAULT_OVCLI_CONF
+ config_module.DEFAULT_OVCLI_CONF = Path("/nonexistent/path/ovcli.conf")
+ try:
+ client = AsyncHTTPClient(
+ url="http://localhost:1933",
+ auth_mode="ldap",
+ ldap_username="alice",
+ ldap_password="password123",
+ )
+ await client.initialize()
+ try:
+ # 检查 HTTP client 的 headers(HTTP headers 是小写的)
+ assert client._http is not None
+ headers = {k.lower(): v for k, v in client._http.headers.items()}
+ assert "authorization" in headers
+ expected_auth = get_basic_auth_header("alice", "password123")
+ assert headers["authorization"] == expected_auth
+ # 确认没有 x-api-key header
+ assert "x-api-key" not in headers
+ finally:
+ await client.close()
+ finally:
+ config_module.DEFAULT_OVCLI_CONF = original_default
+
+ @pytest.mark.asyncio
+ async def test_client_initialize_with_api_key(self, monkeypatch):
+ """测试 API Key 模式不添加 Authorization header"""
+ monkeypatch.delenv("OPENVIKING_CLI_CONFIG_FILE", raising=False)
+ import openviking_sdk.config as config_module
+ original_default = config_module.DEFAULT_OVCLI_CONF
+ config_module.DEFAULT_OVCLI_CONF = Path("/nonexistent/path/ovcli.conf")
+ try:
+ client = AsyncHTTPClient(
+ url="http://localhost:1933",
+ api_key="sk-test-key",
+ )
+ await client.initialize()
+ try:
+ assert client._http is not None
+ headers = {k.lower(): v for k, v in client._http.headers.items()}
+ assert "x-api-key" in headers
+ assert headers["x-api-key"] == "sk-test-key"
+ # 确认没有 authorization header
+ assert "authorization" not in headers
+ finally:
+ await client.close()
+ finally:
+ config_module.DEFAULT_OVCLI_CONF = original_default
+
+ @pytest.mark.asyncio
+ async def test_client_ldap_missing_password(self, monkeypatch):
+ """测试 LDAP 模式但缺少密码时不添加 header"""
+ monkeypatch.delenv("OPENVIKING_CLI_CONFIG_FILE", raising=False)
+ import openviking_sdk.config as config_module
+ original_default = config_module.DEFAULT_OVCLI_CONF
+ config_module.DEFAULT_OVCLI_CONF = Path("/nonexistent/path/ovcli.conf")
+ try:
+ client = AsyncHTTPClient(
+ url="http://localhost:1933",
+ auth_mode="ldap",
+ ldap_username="alice",
+ # password 缺失
+ )
+ await client.initialize()
+ try:
+ assert client._http is not None
+ headers = {k.lower(): v for k, v in client._http.headers.items()}
+ # 不应该添加 authorization header
+ assert "authorization" not in headers
+ finally:
+ await client.close()
+ finally:
+ config_module.DEFAULT_OVCLI_CONF = original_default
+
+ @pytest.mark.asyncio
+ async def test_client_ldap_extra_headers_combined(self, monkeypatch):
+ """测试 LDAP header 与其他自定义 header 共存"""
+ monkeypatch.delenv("OPENVIKING_CLI_CONFIG_FILE", raising=False)
+ import openviking_sdk.config as config_module
+ original_default = config_module.DEFAULT_OVCLI_CONF
+ config_module.DEFAULT_OVCLI_CONF = Path("/nonexistent/path/ovcli.conf")
+ try:
+ client = AsyncHTTPClient(
+ url="http://localhost:1933",
+ auth_mode="ldap",
+ ldap_username="alice",
+ ldap_password="password123",
+ extra_headers={"X-Custom": "value"},
+ )
+ await client.initialize()
+ try:
+ assert client._http is not None
+ headers = {k.lower(): v for k, v in client._http.headers.items()}
+ assert "authorization" in headers
+ assert "x-custom" in headers
+ finally:
+ await client.close()
+ finally:
+ config_module.DEFAULT_OVCLI_CONF = original_default
+
+
+class TestLDAPEdgeCases:
+ """测试 LDAP 边界情况"""
+
+ def test_empty_username_password(self):
+ """测试空用户名和密码"""
+ header = get_basic_auth_header("", "")
+ expected = "Basic " + base64.b64encode(b":").decode("ascii")
+ assert header == expected
+
+ def test_auth_mode_case_sensitive(self, monkeypatch):
+ """测试 auth_mode 大小写(当前实现区分大小写)"""
+ monkeypatch.delenv("OPENVIKING_CLI_CONFIG_FILE", raising=False)
+ monkeypatch.setenv("OPENVIKING_URL", "http://localhost:1933")
+ monkeypatch.setenv("OPENVIKING_AUTH_MODE", "LDAP")
+ monkeypatch.setenv("OPENVIKING_USERNAME", "alice")
+ monkeypatch.setenv("OPENVIKING_PASSWORD", "secret")
+
+ import openviking_sdk.config as config_module
+ original_default = config_module.DEFAULT_OVCLI_CONF
+ config_module.DEFAULT_OVCLI_CONF = Path("/nonexistent/path/ovcli.conf")
+ try:
+ config = resolve_client_config()
+ # 当前实现是区分大小写的,所以 "LDAP" 会被保留但不会触发 Basic Auth
+ assert config.auth_mode == "LDAP"
+ finally:
+ config_module.DEFAULT_OVCLI_CONF = original_default
+
+ def test_mixed_auth_config(self, monkeypatch):
+ """测试同时配置 API Key 和 LDAP"""
+ monkeypatch.delenv("OPENVIKING_CLI_CONFIG_FILE", raising=False)
+ import openviking_sdk.config as config_module
+ original_default = config_module.DEFAULT_OVCLI_CONF
+ config_module.DEFAULT_OVCLI_CONF = Path("/nonexistent/path/ovcli.conf")
+ try:
+ client = AsyncHTTPClient(
+ url="http://localhost:1933",
+ api_key="sk-test",
+ auth_mode="ldap",
+ ldap_username="alice",
+ ldap_password="password123",
+ )
+ # LDAP 配置被存储
+ assert client._auth_mode == "ldap"
+ assert client._api_key == "sk-test"
+ assert client._ldap_username == "alice"
+ finally:
+ config_module.DEFAULT_OVCLI_CONF = original_default
+
+ @pytest.mark.asyncio
+ async def test_mixed_auth_ldap_wins(self, monkeypatch):
+ """测试同时配置时 LDAP 添加 Authorization header"""
+ monkeypatch.delenv("OPENVIKING_CLI_CONFIG_FILE", raising=False)
+ import openviking_sdk.config as config_module
+ original_default = config_module.DEFAULT_OVCLI_CONF
+ config_module.DEFAULT_OVCLI_CONF = Path("/nonexistent/path/ovcli.conf")
+ try:
+ client = AsyncHTTPClient(
+ url="http://localhost:1933",
+ api_key="sk-test",
+ auth_mode="ldap",
+ ldap_username="alice",
+ ldap_password="password123",
+ )
+ await client.initialize()
+ try:
+ headers = {k.lower(): v for k, v in client._http.headers.items()}
+ # LDAP 应该添加 authorization header
+ assert "authorization" in headers
+ # 也可以同时有 x-api-key(两者都会添加)
+ assert "x-api-key" in headers
+ finally:
+ await client.close()
+ finally:
+ config_module.DEFAULT_OVCLI_CONF = original_default
diff --git a/uv.lock b/uv.lock
index 1edc0c7e0..e1f10739d 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1214,6 +1214,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/bf/ee/aa015c5de8b0dc42a8e507eae8c2de5d1c0e068c896858fec6d502402ed6/ebooklib-0.20-py3-none-any.whl", hash = "sha256:fff5322517a37e31c972d27be7d982cc3928c16b3dcc5fd7e8f7c0f5d7bcf42b", size = 40995, upload-time = "2025-10-26T20:56:19.104Z" },
]
+[[package]]
+name = "ecdsa"
+version = "0.19.2"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "six" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/25/ca/8de7744cb3bc966c85430ca2d0fcaeea872507c6a4cf6e007f7fe269ed9d/ecdsa-0.19.2.tar.gz", hash = "sha256:62635b0ac1ca2e027f82122b5b81cb706edc38cd91c63dda28e4f3455a2bf930", size = 202432, upload-time = "2026-03-26T09:58:17.675Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/51/79/119091c98e2bf49e24ed9f3ae69f816d715d2904aefa6a2baa039a2ba0b0/ecdsa-0.19.2-py2.py3-none-any.whl", hash = "sha256:840f5dc5e375c68f36c1a7a5b9caad28f95daa65185c9253c0c08dd952bb7399", size = 150818, upload-time = "2026-03-26T09:58:15.808Z" },
+]
+
[[package]]
name = "et-xmlfile"
version = "2.0.0"
@@ -3684,6 +3696,11 @@ dependencies = [
]
[package.optional-dependencies]
+auth = [
+ { name = "httpx" },
+ { name = "python-jose", extra = ["cryptography"] },
+ { name = "python-ldap" },
+]
benchmark = [
{ name = "datasets" },
{ name = "langchain" },
@@ -3715,6 +3732,7 @@ bot = [
{ name = "pydantic-settings" },
{ name = "pygments" },
{ name = "python-engineio" },
+ { name = "python-jose", extra = ["cryptography"] },
{ name = "python-socketio" },
{ name = "python-socks", extra = ["asyncio"] },
{ name = "python-telegram-bot", extra = ["socks"] },
@@ -3818,6 +3836,7 @@ requires-dist = [
{ name = "grep-ast", specifier = ">=0.9.0" },
{ name = "html2text", marker = "extra == 'bot'", specifier = ">=2020.1.16" },
{ name = "httpx", specifier = ">=0.25.0" },
+ { name = "httpx", marker = "extra == 'auth'", specifier = ">=0.25.0" },
{ name = "httpx", extras = ["socks"], marker = "extra == 'bot'", specifier = ">=0.25.0" },
{ name = "hvac", marker = "extra == 'test'", specifier = ">=2.0.0" },
{ name = "jinja2", specifier = ">=3.1.6" },
@@ -3868,6 +3887,9 @@ requires-dist = [
{ name = "pytest-xdist", marker = "extra == 'test'", specifier = ">=3.5.0" },
{ name = "python-docx", specifier = ">=1.0.0" },
{ name = "python-engineio", marker = "extra == 'bot'", specifier = ">=4.13.2" },
+ { name = "python-jose", extras = ["cryptography"], marker = "extra == 'auth'", specifier = ">=3.3.0" },
+ { name = "python-jose", extras = ["cryptography"], marker = "extra == 'bot'", specifier = ">=3.3.0" },
+ { name = "python-ldap", marker = "extra == 'auth'", specifier = ">=3.4.0" },
{ name = "python-multipart", specifier = ">=0.0.31" },
{ name = "python-pptx", specifier = ">=1.0.0" },
{ name = "python-socketio", marker = "extra == 'bot'", specifier = ">=5.16.2" },
@@ -3917,7 +3939,7 @@ requires-dist = [
{ name = "xlrd", specifier = ">=2.0.1" },
{ name = "xxhash", specifier = ">=3.0.0" },
]
-provides-extras = ["test", "opengauss", "dev", "doc", "eval", "gemini", "gemini-async", "ocr", "build", "bot", "benchmark", "local-embed"]
+provides-extras = ["test", "auth", "opengauss", "dev", "doc", "eval", "gemini", "gemini-async", "ocr", "build", "bot", "benchmark", "langchain", "langgraph", "local-embed"]
[package.metadata.requires-dev]
dev = [{ name = "pytest", specifier = ">=9.0.2" }]
@@ -5137,6 +5159,35 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/5b/96/82f6328e410515fab21d5602ba35b9377a47b5a141a0c1f9efa00ce21eb4/python_engineio-4.13.3-py3-none-any.whl", hash = "sha256:1f60ecaf1358190f0e26c48c578a60428dc02a8f1295bc3dbf53d1b31116821f", size = 59993, upload-time = "2026-06-20T22:53:50.775Z" },
]
+[[package]]
+name = "python-jose"
+version = "3.5.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "ecdsa" },
+ { name = "pyasn1" },
+ { name = "rsa" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/c6/77/3a1c9039db7124eb039772b935f2244fbb73fc8ee65b9acf2375da1c07bf/python_jose-3.5.0.tar.gz", hash = "sha256:fb4eaa44dbeb1c26dcc69e4bd7ec54a1cb8dd64d3b4d81ef08d90ff453f2b01b", size = 92726, upload-time = "2025-05-28T17:31:54.288Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/d9/c3/0bd11992072e6a1c513b16500a5d07f91a24017c5909b02c72c62d7ad024/python_jose-3.5.0-py2.py3-none-any.whl", hash = "sha256:abd1202f23d34dfad2c3d28cb8617b90acf34132c7afd60abd0b0b7d3cb55771", size = 34624, upload-time = "2025-05-28T17:31:52.802Z" },
+]
+
+[package.optional-dependencies]
+cryptography = [
+ { name = "cryptography" },
+]
+
+[[package]]
+name = "python-ldap"
+version = "3.4.7"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "pyasn1" },
+ { name = "pyasn1-modules" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/b2/f4/60edeb794bbc9ed0ff2149bbaeec605f3ed331766459d195832ecbd0ba2d/python_ldap-3.4.7.tar.gz", hash = "sha256:bacd9fb680d20263d8570ade1cf234d90d281149a8beb4f079dd8f33f7613dc8", size = 387477, upload-time = "2026-05-20T13:41:04.358Z" }
+
[[package]]
name = "python-multipart"
version = "0.0.32"
@@ -5709,6 +5760,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/d1/b7/b95708304cd49b7b6f82fdd039f1748b66ec2b21d6a45180910802f1abf1/rpds_py-0.30.0-pp311-pypy311_pp73-musllinux_1_2_x86_64.whl", hash = "sha256:ac37f9f516c51e5753f27dfdef11a88330f04de2d564be3991384b2f3535d02e", size = 562191, upload-time = "2025-11-30T20:24:36.853Z" },
]
+[[package]]
+name = "rsa"
+version = "4.9.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "pyasn1" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/da/8a/22b7beea3ee0d44b1916c0c1cb0ee3af23b700b6da9f04991899d0c555d4/rsa-4.9.1.tar.gz", hash = "sha256:e7bdbfdb5497da4c07dfd35530e1a902659db6ff241e39d9953cad06ebd0ae75", size = 29034, upload-time = "2025-04-16T09:51:18.218Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/64/8d/0133e4eb4beed9e425d9a98ed6e081a55d195481b7632472be1af08d2f6b/rsa-4.9.1-py3-none-any.whl", hash = "sha256:68635866661c6836b8d39430f97a996acbd61bfa49406748ea243539fe239762", size = 34696, upload-time = "2025-04-16T09:51:17.142Z" },
+]
+
[[package]]
name = "ruff"
version = "0.15.5"
diff --git a/web-studio/src/hooks/use-server-mode.ts b/web-studio/src/hooks/use-server-mode.ts
index 5ab1bcbd0..5f657ac44 100644
--- a/web-studio/src/hooks/use-server-mode.ts
+++ b/web-studio/src/hooks/use-server-mode.ts
@@ -1,9 +1,9 @@
import { getHealth } from '#/lib/ov-client'
-export type ServerAuthMode = 'api_key' | 'trusted' | 'dev'
+export type ServerAuthMode = 'api_key' | 'trusted' | 'dev' | 'oidc' | 'ldap'
export type ServerMode = ServerAuthMode | 'checking' | 'offline'
-const SERVER_AUTH_MODES = new Set<ServerAuthMode>(['api_key', 'trusted', 'dev'])
+const SERVER_AUTH_MODES = new Set<ServerAuthMode>(['api_key', 'trusted', 'dev', 'oidc', 'ldap'])
const HEALTH_REQUEST_REUSE_MS = 1_000
let recentHealthRequest:
diff --git a/web-studio/src/i18n/locales/en.ts b/web-studio/src/i18n/locales/en.ts
index eb45114cf..f480dcf01 100644
--- a/web-studio/src/i18n/locales/en.ts
+++ b/web-studio/src/i18n/locales/en.ts
@@ -390,6 +390,12 @@ const en = {
},
rootHint: 'Lists accounts and users, and mints or rotates keys.',
title: 'Connection settings',
+ unsupportedAuthMode: {
+ description:
+ 'Web Studio does not support the {{mode}} authentication mode. Please use the {{ov}} CLI or Python SDK to interact with this server.',
+ primary: 'This server is configured with {{mode}} authentication.',
+ title: 'Unsupported authentication mode',
+ },
userHint: 'Used by the Playground and tenant data APIs.',
},
connectionPage: {
@@ -509,7 +515,9 @@ const en = {
api_key: 'API key mode',
checking: 'Checking...',
dev: 'Development mode',
+ ldap: 'LDAP mode',
offline: 'Offline',
+ oidc: 'OIDC mode',
trusted: 'Trusted mode',
},
stats: {
diff --git a/web-studio/src/i18n/locales/zh-CN.ts b/web-studio/src/i18n/locales/zh-CN.ts
index 9b4a10f1c..6368a9b88 100644
--- a/web-studio/src/i18n/locales/zh-CN.ts
+++ b/web-studio/src/i18n/locales/zh-CN.ts
@@ -376,6 +376,12 @@ const zhCN = {
},
rootHint: '用于列出 account / user,以及生成或轮换 key。',
title: '连接设置',
+ unsupportedAuthMode: {
+ description:
+ 'Web Studio 不支持 {{mode}} 认证模式。请使用 {{ov}} CLI 或 Python SDK 连接此服务器。',
+ primary: '该服务器配置了 {{mode}} 认证。',
+ title: '不支持的认证模式',
+ },
userHint: '供 Playground 和租户数据 API 使用。',
},
connectionPage: {
@@ -491,7 +497,9 @@ const zhCN = {
api_key: 'API key 模式',
checking: '检查中...',
dev: '开发模式',
+ ldap: 'LDAP 模式',
offline: '离线',
+ oidc: 'OIDC 模式',
trusted: 'Trusted 模式',
},
stats: {
diff --git a/web-studio/src/routes/settings/route.tsx b/web-studio/src/routes/settings/route.tsx
index 95453aa66..8c695b5f8 100644
--- a/web-studio/src/routes/settings/route.tsx
+++ b/web-studio/src/routes/settings/route.tsx
@@ -8,6 +8,7 @@ import {
ExternalLinkIcon,
KeyRoundIcon,
ShieldCheckIcon,
+ TriangleAlertIcon,
} from 'lucide-react'
import { useTranslation } from 'react-i18next'
@@ -192,6 +193,7 @@ function ConnectionSettingsRoute() {
staleTime: 15_000,
})
const isDevMode = serverMode === 'dev'
+ const isUnsupportedAuthMode = serverMode === 'oidc' || serverMode === 'ldap'
const rootApiKey = connection.adminApiKey.trim()
const hasControlCredential = Boolean(draft.adminApiKey.trim())
const hasDataCredential = Boolean(draft.apiKey.trim())
@@ -283,6 +285,33 @@ function ConnectionSettingsRoute() {
<p className="rounded-md border border-dashed bg-muted/30 px-3 py-2 text-sm text-muted-foreground">
{t('connection.devMode')}
</p>
+ ) : isUnsupportedAuthMode ? (
+ <Alert variant="destructive" className="border-destructive/50">
+ <TriangleAlertIcon className="size-5" />
+ <AlertTitle>{t('connection.unsupportedAuthMode.title')}</AlertTitle>
+ <AlertDescription className="grid gap-2">
+ <p>
+ {t('connection.unsupportedAuthMode.primary', {
+ mode: serverMode,
+ })}
+ </p>
+ <p>
+ {t('connection.unsupportedAuthMode.description', {
+ mode: serverMode,
+ ov: 'ov',
+ })}
+ </p>
+ <a
+ href={authenticationGuideUrl}
+ target="_blank"
+ rel="noreferrer"
+ className="mt-1 inline-flex w-fit items-center gap-1 font-medium text-foreground underline underline-offset-2"
+ >
+ {t('connection.keyGuide.learnMore')}
+ <ExternalLinkIcon className="size-3.5" />
+ </a>
+ </AlertDescription>
+ </Alert>
) : (
<>
<div className="grid gap-4 md:grid-cols-2">