Skip to content

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

feat: add DingTalk connector OAuth auth (#6609)

leebai22a281010895
diff --git a/openviking/connector/auth.py b/openviking/connector/auth.py
index 01977a4a3..b017cefe2 100644
--- a/openviking/connector/auth.py
+++ b/openviking/connector/auth.py
@@ -18,6 +18,16 @@ if TYPE_CHECKING:
from openviking.parse.accessors.base import LocalResource
OAUTH_REF_ARG = "openviking_oauth_ref"
+CONNECTOR_AUTH_CONFIG_FIELD = "connector_auth_config"
+CREDENTIAL_REF_KEY = "openviking_credential_ref"
+_CREDENTIAL_REF_REQUIRED_KEYS = (
+ "account_id",
+ "resource_id",
+ "user_id",
+ "ov_user_id",
+ "platform",
+ "type",
+)
EXTERNAL_FEISHU_PROVIDER = "feishu_external"
current_feishu_token: ContextVar[Optional["ExternalFeishuToken"]] = ContextVar(
"external_feishu_token", default=None
@@ -30,6 +40,12 @@ def external_auth_url() -> str:
return get_openviking_config().connector.auth
+def credential_resolve_url() -> str:
+ from openviking_cli.utils.config.open_viking_config import get_openviking_config
+
+ return get_openviking_config().connector.credential_resolve_url()
+
+
def validate_feishu_auth_args(args: Dict[str, Any]) -> None:
if OAUTH_REF_ARG in args and any(
key in args
@@ -91,7 +107,7 @@ async def feishu_auth_scope(
async def restore_feishu_request(
connector, state: Dict[str, Any], *, path: str, ctx: RequestContext
) -> tuple[str, Dict[str, Any]]:
- api_key, add_type, args = await connector.restore_watch_request(
+ api_key, add_type, args, _ = await connector.restore_watch_request(
state.get("credentials", {}), account_id=ctx.account_id, path=path
)
if add_type != "feishu_doc":
@@ -120,6 +136,88 @@ def validate_oauth_ref(
return ref
+def extract_credential_reference(
+ connector_auth_config: Optional[Dict[str, Any]],
+) -> Optional[Dict[str, Any]]:
+ """Return the private credential reference, or None when absent.
+
+ The top-level ``connector_auth_config`` is managed by OpenViking and only
+ ever carries one key, ``openviking_credential_ref``. Imports that keep the
+ legacy ``args.openviking_oauth_ref`` channel (Feishu) leave it unset, so a
+ present reference is the single platform-agnostic signal that this import
+ resolves credentials through the unified resolver.
+ """
+ if not connector_auth_config:
+ return None
+ if not isinstance(connector_auth_config, dict):
+ raise InvalidArgumentError("connector_auth_config must be an object.")
+ reference = connector_auth_config.get(CREDENTIAL_REF_KEY)
+ if reference is None:
+ return None
+ if set(connector_auth_config) != {CREDENTIAL_REF_KEY}:
+ raise InvalidArgumentError("connector_auth_config contains unexpected fields.")
+ return validate_credential_reference(reference)
+
+
+def validate_credential_reference(value: Any) -> Dict[str, Any]:
+ """Validate the OpenViking-managed credential reference shape.
+
+ ``binding_version`` is optional (DingTalk sends a positive integer; Feishu
+ omits it). All other fields are non-empty strings and ``type`` is ``oauth``.
+ The reference is forwarded verbatim to the unified resolver, so the kernel
+ never inspects platform-specific credential fields here.
+ """
+ if not isinstance(value, dict):
+ raise InvalidArgumentError("connector_auth_config contains an invalid credential reference.")
+ extra = set(value) - set(_CREDENTIAL_REF_REQUIRED_KEYS) - {"binding_version"}
+ if extra or any(key not in value for key in _CREDENTIAL_REF_REQUIRED_KEYS):
+ raise InvalidArgumentError("connector_auth_config contains an invalid credential reference.")
+ reference: Dict[str, Any] = {}
+ for key in _CREDENTIAL_REF_REQUIRED_KEYS:
+ field = value[key]
+ if not isinstance(field, str) or not field.strip():
+ raise InvalidArgumentError(
+ "connector_auth_config contains an invalid credential reference."
+ )
+ reference[key] = field.strip()
+ if reference["type"] != "oauth":
+ raise InvalidArgumentError("connector_auth_config credential reference must be an OAuth type.")
+ if "binding_version" in value:
+ binding_version = value["binding_version"]
+ if isinstance(binding_version, bool) or not isinstance(binding_version, int):
+ raise InvalidArgumentError("connector_auth_config binding_version must be an integer.")
+ reference["binding_version"] = binding_version
+ return reference
+
+
+async def resolve_connector_auth_config(
+ reference: Dict[str, Any], ctx: RequestContext
+) -> Dict[str, Any]:
+ """Resolve the current Connector ``auth_config`` for a credential reference.
+
+ Each import and each watch round resolves credentials just before use so a
+ refreshed token is always current; the resolver assembles the full
+ ``auth_config`` for the target Connector, and the kernel forwards it
+ verbatim without persisting any token or application secret.
+ """
+ resolve_url = credential_resolve_url()
+ if not resolve_url:
+ raise InvalidArgumentError(
+ "connector.auth is required to resolve external Connector credentials."
+ )
+ api_key = ctx.api_key or ""
+ if not api_key:
+ raise InvalidArgumentError("External Connector authorization requires an API key.")
+ client = ConnectorClient("", "", account_id=reference.get("account_id", ""))
+ data = await asyncio.to_thread(
+ client.resolve_connector_credential, resolve_url, api_key, reference
+ )
+ auth_config = data.get("auth_config")
+ if not isinstance(auth_config, dict) or not auth_config:
+ raise InternalError("External Connector credential resolution returned no auth_config.")
+ return {str(key): value for key, value in auth_config.items()}
+
+
async def project_auth_config(args: Dict[str, Any], ctx: RequestContext) -> Dict[str, str]:
"""Resolve one credential snapshot without changing the stored watch request."""
validate_feishu_auth_args(args)
diff --git a/openviking/connector/client.py b/openviking/connector/client.py
index 991785a7c..a02aaf403 100644
--- a/openviking/connector/client.py
+++ b/openviking/connector/client.py
@@ -67,6 +67,25 @@ class ConnectorClient:
# Neither remote business messages nor response bodies may expose credentials.
raise InternalError("External OAuth access token request failed.") from None
+ def resolve_connector_credential(
+ self, resolve_url: str, api_key: str, reference: Dict[str, Any]
+ ) -> Dict[str, Any]:
+ """Resolve centrally managed Connector credentials for a credential reference.
+
+ Shares the synchronous access-token transport: the unified resolver is
+ reached from both async imports and synchronous watch replays, returns
+ the freshly assembled ``auth_config`` for this call only, and never
+ exposes remote business messages or response bodies that may carry
+ credentials.
+ """
+ try:
+ with httpx.Client(timeout=10.0) as client:
+ rsp = client.post(resolve_url, json=reference, headers={"X-API-Key": api_key})
+ rsp.raise_for_status()
+ return _unwrap_connector_response(rsp.json())
+ except (httpx.HTTPError, ValueError, InternalError):
+ raise InternalError("External connector credential resolution failed.") from None
+
async def submit_doc_add(
self,
add_type: str,
diff --git a/openviking/connector/delegate.py b/openviking/connector/delegate.py
index e9258ef5d..884842a47 100644
--- a/openviking/connector/delegate.py
+++ b/openviking/connector/delegate.py
@@ -30,7 +30,9 @@ from openviking.connector.auth import (
OAUTH_REF_ARG,
confluence_auth_config,
document_auth_config,
+ extract_credential_reference,
project_auth_config,
+ resolve_connector_auth_config,
)
from openviking.connector.client import ConnectorClient
from openviking.connector.routing import (
@@ -174,6 +176,7 @@ class ConnectorDelegate:
add_type: str,
path: str,
connector_args: Optional[Dict[str, Any]],
+ connector_auth_config: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
"""Build the private request state needed to replay a Connector watch."""
if not api_key:
@@ -185,6 +188,10 @@ class ConnectorDelegate:
"path": path,
"connector_args": dict(connector_args or {}),
}
+ # Watches persist only the secret-free credential reference; the actual
+ # auth_config is resolved anew each round so refreshed tokens stay current.
+ if connector_auth_config:
+ payload["connector_auth_config"] = dict(connector_auth_config)
encryptor = getattr(self._viking_fs, "_encryptor", None)
if encryptor is None:
return {
@@ -221,8 +228,13 @@ class ConnectorDelegate:
*,
account_id: str,
path: str,
- ) -> Tuple[str, str, Dict[str, Any]]:
- """Restore and validate a source-bound Connector watch request."""
+ ) -> Tuple[str, str, Dict[str, Any], Optional[Dict[str, Any]]]:
+ """Restore and validate a source-bound Connector watch request.
+
+ Returns ``(api_key, add_type, connector_args, connector_auth_config)``;
+ ``connector_auth_config`` is the secret-free credential reference and is
+ None for watches that predate it or use the legacy args channel.
+ """
try:
provider = auth_state.get("provider")
if provider == self._WATCH_PLAINTEXT_AUTH_PROVIDER:
@@ -247,15 +259,23 @@ class ConnectorDelegate:
api_key = payload.get("api_key")
add_type = payload.get("add_type")
connector_args = payload.get("connector_args")
+ connector_auth_config = payload.get("connector_auth_config")
if (
not isinstance(api_key, str)
or not api_key
or not isinstance(add_type, str)
or not add_type
or not isinstance(connector_args, dict)
+ or (connector_auth_config is not None
+ and not isinstance(connector_auth_config, dict))
):
raise ValueError("invalid watch request")
- return api_key, add_type, dict(connector_args)
+ return (
+ api_key,
+ add_type,
+ dict(connector_args),
+ dict(connector_auth_config) if connector_auth_config else None,
+ )
except InvalidArgumentError:
raise
except Exception as exc:
@@ -502,6 +522,7 @@ class ConnectorDelegate:
reason: str = "",
declared_add_type: Optional[str] = None,
connector_args: Optional[Dict[str, Any]] = None,
+ connector_auth_config: Optional[Dict[str, Any]] = None,
tags: Optional[List[str]] = None,
tag_mode: str = "replace",
wait_for_completion: bool = False,
@@ -591,6 +612,19 @@ class ConnectorDelegate:
auth_config = await confluence_auth_config(connector_args or {}, ctx)
forwarded_args.pop(OAUTH_REF_ARG, None)
+ # Imports carrying an OpenViking-managed credential reference resolve the
+ # full auth_config through the unified resolver just before forwarding,
+ # so a refreshed token is always current. This is platform-agnostic:
+ # the kernel forwards whatever auth_config the resolver assembled for the
+ # target Connector without inspecting its fields.
+ credential_reference = extract_credential_reference(connector_auth_config)
+ if credential_reference is not None:
+ if add_type in CONNECTOR_SUPPORTED_ARGS:
+ raise InvalidArgumentError(
+ f"add_type '{add_type}' does not accept a managed credential reference."
+ )
+ auth_config = await resolve_connector_auth_config(credential_reference, ctx)
+
tos_path: Optional[str] = None
param_config: Optional[Dict[str, Any]] = None
if add_type == "tos":
diff --git a/openviking/resource/watch_scheduler.py b/openviking/resource/watch_scheduler.py
index 364c208ba..74cabf1d5 100644
--- a/openviking/resource/watch_scheduler.py
+++ b/openviking/resource/watch_scheduler.py
@@ -403,6 +403,7 @@ class WatchScheduler:
api_key,
add_type,
connector_args,
+ connector_auth_config,
) = await self._resource_service._connector.restore_watch_request(
auth_state,
account_id=task.account_id,
@@ -416,6 +417,10 @@ class WatchScheduler:
refresh_kwargs = {}
if connector_watch:
refresh_kwargs["connector_states"] = getattr(task, "connector_states", None)
+ # Re-resolve managed credentials every round so refreshed
+ # tokens stay current; watches persist only the reference.
+ if connector_auth_config:
+ refresh_kwargs["connector_auth_config"] = connector_auth_config
result = await self._resource_service.refresh_resource(
path=task.path,
ctx=ctx,
diff --git a/openviking/server/resource_ingest.py b/openviking/server/resource_ingest.py
index ba14d6444..e1366c1fc 100644
--- a/openviking/server/resource_ingest.py
+++ b/openviking/server/resource_ingest.py
@@ -40,6 +40,11 @@ class AddResourceRequest(BaseModel):
and therefore requires both a positive interval and an explicit target.
``wait`` and ``internal_task`` are transport defaults that callers may
override when the resource is imported as part of another operation.
+
+ ``connector_auth_config`` is an OpenViking-managed private credential channel
+ injected by the data plane for saved-credential OAuth imports. It carries only
+ ``openviking_credential_ref``, a secret-free reference resolved into the current
+ Connector ``auth_config`` for each import or watch round.
"""
model_config = ConfigDict(extra="forbid")
@@ -62,6 +67,7 @@ class AddResourceRequest(BaseModel):
directly_upload_media: bool = True
preserve_structure: Optional[bool] = None
args: Dict[str, Any] = Field(default_factory=dict)
+ connector_auth_config: Optional[Dict[str, Any]] = None
telemetry: TelemetryRequest = False
watch_interval: float = 0
is_active: bool = True
@@ -201,6 +207,7 @@ async def ingest_resource_request(
internal_task=internal_task,
is_active=request.is_active,
args=request.args,
+ connector_auth_config=request.connector_auth_config,
shared_source=shared_source_ref,
**kwargs,
)
diff --git a/openviking/service/resource_service.py b/openviking/service/resource_service.py
index aa83c4a0a..b444c3e51 100644
--- a/openviking/service/resource_service.py
+++ b/openviking/service/resource_service.py
@@ -1633,6 +1633,7 @@ class ResourceService:
add_type: Optional[str] = None,
internal_task: bool = False,
args: Optional[Dict[str, Any]] = None,
+ connector_auth_config: Optional[Dict[str, Any]] = None,
shared_source: Optional["SharedSource"] = None,
acl: AclSpec | dict[str, Any] | None = None,
**kwargs,
@@ -1668,6 +1669,7 @@ class ResourceService:
enforce_public_remote_targets=enforce_public_remote_targets,
internal_task=internal_task,
args=args,
+ connector_auth_config=connector_auth_config,
shared_source=shared_source,
**kwargs,
)
@@ -1690,6 +1692,7 @@ class ResourceService:
add_type: Optional[str] = None,
args: Optional[Dict[str, Any]] = None,
connector_states: Optional[Dict[str, Any]] = None,
+ connector_auth_config: Optional[Dict[str, Any]] = None,
**kwargs,
) -> Dict[str, Any]:
"""Submit a scheduled refresh without changing its watch task."""
@@ -1712,6 +1715,7 @@ class ResourceService:
add_type=add_type,
args=args,
connector_states=connector_states,
+ connector_auth_config=connector_auth_config,
**kwargs,
)
@@ -1740,6 +1744,7 @@ class ResourceService:
internal_task: bool = False,
args: Optional[Dict[str, Any]] = None,
connector_states: Optional[Dict[str, Any]] = None,
+ connector_auth_config: Optional[Dict[str, Any]] = None,
shared_source: Optional["SharedSource"] = None,
acl: AclSpec | dict[str, Any] | None = None,
**kwargs,
@@ -1903,6 +1908,17 @@ class ResourceService:
connector_args=normalized_args.processor_kwargs,
kwargs=kwargs,
)
+ if not delegate_to_connector and connector_auth_config:
+ # A managed credential reference only resolves inside Connector
+ # delegation; never drop it and silently degrade to an unauthorized
+ # standard-pipeline import.
+ from openviking.connector.auth import extract_credential_reference
+
+ if extract_credential_reference(connector_auth_config) is not None:
+ raise InvalidArgumentError(
+ "connector_auth_config requires a Connector import; the source or "
+ "parameters did not route to the Connector integration."
+ )
if delegate_to_connector:
resolved = connector.resolve_add_type(path, add_type)
if resolved is None: # pragma: no cover - should_delegate already resolved it
@@ -1924,6 +1940,7 @@ class ResourceService:
add_type=resolved[0],
path=path,
connector_args=connector_watch_auth_args,
+ connector_auth_config=connector_auth_config,
)
connector_watch_processor_kwargs = self._watch_processor_kwargs(
{
@@ -2030,6 +2047,7 @@ class ResourceService:
to=target_to,
reason=reason,
connector_args=normalized_args.processor_kwargs,
+ connector_auth_config=connector_auth_config,
tags=tags,
tag_mode=tag_mode,
wait_for_completion=not manage_watch and watch_interval > 0,
diff --git a/openviking_cli/utils/config/open_viking_config.py b/openviking_cli/utils/config/open_viking_config.py
index dab7c93d8..c5650fd4b 100644
--- a/openviking_cli/utils/config/open_viking_config.py
+++ b/openviking_cli/utils/config/open_viking_config.py
@@ -113,6 +113,27 @@ class ConnectorConfig(BaseModel):
raise ValueError("connector.poll_interval_ms must be > 0")
return self
+ def credential_resolve_url(self) -> str:
+ """Derive the unified credential-resolve endpoint from ``auth``.
+
+ The Feishu compatibility endpoint (``.../oauth/access_token``) and the
+ unified resolver (``.../credential/resolve``) are two fixed paths on the
+ same KernelAPI inner entry, so the resolver URL is derived from the
+ configured ``auth`` rather than adding a second endpoint setting; this
+ keeps existing Feishu deployments unchanged. Returns an empty string
+ when ``auth`` is unset or uses an unrecognized path.
+ """
+ auth = self.auth.strip()
+ if not auth:
+ return ""
+ compat_suffix = "/oauth/access_token"
+ resolve_suffix = "/credential/resolve"
+ if auth.endswith(compat_suffix):
+ return auth[: -len(compat_suffix)] + resolve_suffix
+ if auth.endswith(resolve_suffix):
+ return auth
+ return ""
+
class ParserApiConfig(BaseModel):
"""Configuration for the Understanding files/responses API."""
diff --git a/tests/connector/test_auth.py b/tests/connector/test_auth.py
index 06f695b4e..4eb05a776 100644
--- a/tests/connector/test_auth.py
+++ b/tests/connector/test_auth.py
@@ -19,7 +19,9 @@ from openviking.resource.feishu_watch_auth import (
FeishuOAuthClient,
FeishuRefreshedToken,
)
+from openviking.server.identity import RequestContext, Role
from openviking_cli.exceptions import InternalError, InvalidArgumentError
+from openviking_cli.session.user_id import UserIdentifier
REFERENCE = {
"account_id": "cloud-account",
@@ -218,7 +220,7 @@ async def test_queue_auth_failure_cleanup_and_prepared_results(
service = ResourceService()
service._connector_delegate = SimpleNamespace(
restore_watch_request=AsyncMock(
- return_value=("key", "feishu_doc", {auth.OAUTH_REF_ARG: REFERENCE})
+ return_value=("key", "feishu_doc", {auth.OAUTH_REF_ARG: REFERENCE}, None)
)
)
service._execute_resource_ingestion = AsyncMock(return_value={"status": "success"})
@@ -289,6 +291,100 @@ async def test_project_credentials_use_account_identity_and_validate_reference(m
await auth.project_auth_config(args, ctx)
+def _credential_reference(**changes):
+ return {
+ "account_id": "acct",
+ "resource_id": "ov-resource",
+ "user_id": "cloud-user",
+ "ov_user_id": "ov-user",
+ "type": "oauth",
+ "platform": "dingtalk",
+ "binding_version": 3,
+ **changes,
+ }
+
+
+def test_extract_credential_reference_returns_none_without_reference():
+ assert auth.extract_credential_reference(None) is None
+ assert auth.extract_credential_reference({}) is None
+
+
+def test_extract_credential_reference_normalizes_and_validates():
+ ref = auth.extract_credential_reference(
+ {"openviking_credential_ref": _credential_reference(account_id=" acct ")}
+ )
+ assert ref == _credential_reference()
+ # binding_version is optional (Feishu omits it).
+ feishu_ref = _credential_reference(platform="feishu_doc")
+ feishu_ref.pop("binding_version")
+ resolved = auth.extract_credential_reference({"openviking_credential_ref": feishu_ref})
+ assert "binding_version" not in resolved
+
+
+ "config",
+ [
+ {"openviking_credential_ref": _credential_reference(), "extra": 1},
+ {"openviking_credential_ref": _credential_reference(type="static")},
+ {"openviking_credential_ref": _credential_reference(account_id="")},
+ {"openviking_credential_ref": {**_credential_reference(), "unknown": "x"}},
+ {"openviking_credential_ref": {**_credential_reference(), "binding_version": "3"}},
+ "not-a-dict",
+ ],
+)
+def test_extract_credential_reference_rejects_invalid(config):
+ with pytest.raises(InvalidArgumentError):
+ auth.extract_credential_reference(config)
+
+
+async def test_resolve_connector_auth_config_uses_unified_resolver(monkeypatch):
+ monkeypatch.setattr(
+ auth, "credential_resolve_url", lambda: "https://connector.example/credential/resolve"
+ )
+ captured = {}
+
+ def fake_resolve(_self, url, api_key, reference):
+ captured.update(url=url, api_key=api_key, reference=reference)
+ return {"auth_config": {"user_access_token": "live", "client_id": "c"}}
+
+ monkeypatch.setattr(ConnectorClient, "resolve_connector_credential", fake_resolve)
+ ctx = RequestContext(user=UserIdentifier("acct", "cloud-user"), role=Role.USER, api_key="user-key")
+
+ result = await auth.resolve_connector_auth_config(_credential_reference(), ctx)
+
+ assert result == {"user_access_token": "live", "client_id": "c"}
+ assert captured["url"] == "https://connector.example/credential/resolve"
+ assert captured["api_key"] == "user-key"
+ assert captured["reference"] == _credential_reference()
+
+
+async def test_resolve_connector_auth_config_requires_config_and_key(monkeypatch):
+ ctx = RequestContext(user=UserIdentifier("acct", "cloud-user"), role=Role.USER, api_key="k")
+ monkeypatch.setattr(auth, "credential_resolve_url", lambda: "")
+ with pytest.raises(InvalidArgumentError, match="connector.auth is required"):
+ await auth.resolve_connector_auth_config(_credential_reference(), ctx)
+
+ monkeypatch.setattr(auth, "credential_resolve_url", lambda: "https://connector.example/resolve")
+ no_key = RequestContext(user=UserIdentifier("acct", "cloud-user"), role=Role.USER, api_key="")
+ with pytest.raises(InvalidArgumentError, match="requires an API key"):
+ await auth.resolve_connector_auth_config(_credential_reference(), no_key)
+
+
+async def test_resolve_connector_auth_config_rejects_empty_auth_config(monkeypatch):
+ monkeypatch.setattr(auth, "credential_resolve_url", lambda: "https://connector.example/resolve")
+ monkeypatch.setattr(
+ ConnectorClient,
+ "resolve_connector_credential",
+ lambda *_: {"auth_config": {}},
+ )
+ ctx = RequestContext(user=UserIdentifier("acct", "cloud-user"), role=Role.USER, api_key="k")
+ with pytest.raises(InternalError, match="no auth_config"):
+ await auth.resolve_connector_auth_config(_credential_reference(), ctx)
+
+
@pytest.mark.asyncio
async def test_confluence_credentials_use_bearer_token_and_validate_reference(monkeypatch):
ctx = SimpleNamespace(user=SimpleNamespace(user_id="alice"), api_key="caller-key")
diff --git a/tests/connector/test_client.py b/tests/connector/test_client.py
index 76da6a0c4..3c6a7fe52 100644
--- a/tests/connector/test_client.py
+++ b/tests/connector/test_client.py
@@ -2,8 +2,10 @@
# SPDX-License-Identifier: AGPL-3.0
"""Focused tests for the external Connector HTTP contract."""
+import json
from types import SimpleNamespace
+import httpx
import pytest
from openviking.connector import client as client_module
@@ -185,3 +187,58 @@ async def test_get_task_info_unwraps_task_object():
def test_connector_business_error_is_not_treated_as_success():
with pytest.raises(InternalError, match=r"code=1003.*permission denied"):
_unwrap_connector_response({"code": 1003, "message": "permission denied", "data": {}})
+
+
+def test_resolve_connector_credential_posts_reference_with_api_key(monkeypatch):
+ reference = {
+ "account_id": "acct",
+ "resource_id": "ov-resource",
+ "user_id": "alice",
+ "ov_user_id": "ov-user",
+ "type": "oauth",
+ "platform": "dingtalk",
+ "binding_version": 3,
+ }
+
+ def handle(request):
+ assert request.method == "POST"
+ assert request.headers["x-api-key"] == "user-key"
+ assert "authorization" not in request.headers
+ assert json.loads(request.content) == reference
+ return httpx.Response(
+ 200,
+ json={"code": 0, "data": {"auth_config": {"user_access_token": "live"}}},
+ )
+
+ client_type = httpx.Client
+ monkeypatch.setattr(
+ httpx,
+ "Client",
+ lambda **kwargs: client_type(transport=httpx.MockTransport(handle), **kwargs),
+ )
+ client = ConnectorClient("", "", "acct")
+
+ data = client.resolve_connector_credential(
+ "https://connector.example/api/v1/inner/connector/credential/resolve",
+ "user-key",
+ reference,
+ )
+
+ assert data == {"auth_config": {"user_access_token": "live"}}
+
+
+def test_resolve_connector_credential_hides_remote_error(monkeypatch):
+ def handle(request):
+ return httpx.Response(200, json={"code": 42, "message": "must-not-expose-secret"})
+
+ client_type = httpx.Client
+ monkeypatch.setattr(
+ httpx,
+ "Client",
+ lambda **kwargs: client_type(transport=httpx.MockTransport(handle), **kwargs),
+ )
+ client = ConnectorClient("", "", "acct")
+
+ with pytest.raises(InternalError) as error:
+ client.resolve_connector_credential("https://connector.example/resolve", "k", {})
+ assert "must-not-expose-secret" not in str(error.value)
diff --git a/tests/resource/test_watch_scheduler.py b/tests/resource/test_watch_scheduler.py
index cf0e48f23..9d5b05a9e 100644
--- a/tests/resource/test_watch_scheduler.py
+++ b/tests/resource/test_watch_scheduler.py
@@ -330,7 +330,7 @@ class TestWatchSchedulerResourceExistence:
auth_state={"provider": "connector_encrypted", "ciphertext": "encrypted"},
)
resource_service._connector.restore_watch_request = AsyncMock(
- return_value=("api-key", "tos", {})
+ return_value=("api-key", "tos", {}, None)
)
await scheduler._execute_task(task)
diff --git a/tests/server/test_resource_parse_mode_request.py b/tests/server/test_resource_parse_mode_request.py
index 70c7d6574..8a0be40f2 100644
--- a/tests/server/test_resource_parse_mode_request.py
+++ b/tests/server/test_resource_parse_mode_request.py
@@ -50,6 +50,46 @@ async def test_add_resource_route_forwards_no_split_mode(monkeypatch: pytest.Mon
assert add_resource.await_args.kwargs["args"] == {"parse_mode": "no_split"}
+async def test_add_resource_route_forwards_connector_auth_config(monkeypatch: pytest.MonkeyPatch):
+ add_resource = AsyncMock(
+ return_value={"status": "success", "root_uri": "viking://resources/docs"}
+ )
+ service = SimpleNamespace(resources=SimpleNamespace(add_resource=add_resource))
+ monkeypatch.setattr(resources_router, "get_service", lambda: service)
+ ctx = RequestContext(
+ user=UserIdentifier("test_account", "test_user"),
+ role=Role.USER,
+ )
+ reference = {
+ "openviking_credential_ref": {
+ "account_id": "test_account",
+ "resource_id": "ov-resource",
+ "user_id": "test_user",
+ "ov_user_id": "ov-user",
+ "type": "oauth",
+ "platform": "dingtalk",
+ "binding_version": 3,
+ }
+ }
+
+ # The managed credential channel is accepted despite extra="forbid" and is
+ # forwarded verbatim to the service layer.
+ await resources_router.add_resource(
+ SimpleNamespace(headers={}),
+ AddResourceRequest(
+ path="https://alidocs.dingtalk.com/i/nodes/NODE1",
+ add_type="dingtalk",
+ to="viking://resources/docs",
+ args={"binding_version": 3},
+ connector_auth_config=reference,
+ ),
+ ctx,
+ )
+
+ assert add_resource.await_args.kwargs["connector_auth_config"] == reference
+
+
@pytest.mark.asyncio
async def test_signed_temp_upload_forwards_token_bound_parse_mode(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/service/test_resource_service_connector.py b/tests/service/test_resource_service_connector.py
index 9f6774caa..c32895f1f 100644
--- a/tests/service/test_resource_service_connector.py
+++ b/tests/service/test_resource_service_connector.py
@@ -12,7 +12,8 @@ from unittest.mock import AsyncMock, Mock
import httpx
import pytest
-from openviking.connector import auth, delegate as connector_delegate_module
+from openviking.connector import auth
+from openviking.connector import delegate as connector_delegate_module
from openviking.parse.mode import ParseMode
from openviking.resource.watch_manager import WatchManager
from openviking.resource.watch_scheduler import WatchScheduler
@@ -332,6 +333,7 @@ async def test_connector_watch_stores_only_encrypted_replay_state(
"secret",
"tos",
{"tos_prefix": ["tos://bucket/docs/"]},
+ None,
)
assert connector_client.submit_doc_add.await_args.kwargs["param_config"] == {
"tos_prefix": ["tos://bucket/docs/"]
@@ -820,7 +822,7 @@ async def test_git_connector_watch_keeps_args_only_in_encrypted_state(
task.auth_state,
account_id="acct",
path="https://git.example/org/private.git",
- ) == ("secret", "git", connector_args)
+ ) == ("secret", "git", connector_args, None)
@pytest.mark.asyncio
@@ -868,7 +870,7 @@ async def test_connector_watch_allows_plaintext_private_state_without_encryption
task.auth_state,
account_id="acct",
path="tos://bucket/docs/",
- ) == ("secret", "tos", {})
+ ) == ("secret", "tos", {}, None)
@pytest.mark.asyncio
@@ -1030,7 +1032,7 @@ async def test_connector_watch_keeps_running_when_target_is_missing():
service = ResourceService()
service.refresh_resource = AsyncMock(return_value={"status": "completed"})
- service._connector.restore_watch_request = AsyncMock(return_value=("secret", "tos", {}))
+ service._connector.restore_watch_request = AsyncMock(return_value=("secret", "tos", {}, None))
scheduler = WatchScheduler(resource_service=service, viking_fs=MissingTargetFS())
watch_manager = WatchManager()
scheduler._watch_manager = watch_manager
@@ -3043,7 +3045,7 @@ async def test_project_oauth_dispatch_and_watch_replay(
api_key=ctx.api_key, account_id=ctx.account_id, add_type=add_type, path=path, connector_args=args
)
for token in ("first", "second"):
- api_key, restored_type, restored_args = await delegate.restore_watch_request(
+ api_key, restored_type, restored_args, _ = await delegate.restore_watch_request(
state, account_id=ctx.account_id, path=path
)
assert api_key == ctx.api_key
@@ -3120,3 +3122,147 @@ async def test_document_auth_rejects_ambiguous_or_foreign_credentials(patch, mon
_feishu_request_context(),
)
factory.assert_not_called()
+
+
+_DINGTALK_URL = "https://alidocs.dingtalk.com/i/nodes/NODE1"
+
+
+def _dingtalk_credential_ref(**changes):
+ return {
+ "account_id": "acct",
+ "resource_id": "ov-resource",
+ "user_id": "alice",
+ "ov_user_id": "ov-user",
+ "type": "oauth",
+ "platform": "dingtalk",
+ "binding_version": 3,
+ **changes,
+ }
+
+
+def _dingtalk_auth_config(token):
+ return {
+ "auth_mode": "internal_app",
+ "token_scope": "internal_app",
+ "client_id": "ding-client",
+ "client_secret": "ding-secret",
+ "user_access_token": token,
+ "corp_id": "ding-corp",
+ "user_id": "open-id",
+ "operator_id": "union-id",
+ }
+
+
+async def test_dingtalk_import_resolves_managed_credential_reference(
+ monkeypatch, connector_config, ctx, service
+):
+ connector_config.allowed_add_types.append("dingtalk")
+ client = SimpleNamespace(submit_doc_add=AsyncMock(return_value={"task_key": "C1"}))
+ _install_connector_dependencies(monkeypatch, _task_tracker(), client)
+ resolve = AsyncMock(return_value=_dingtalk_auth_config("live-token"))
+ monkeypatch.setattr(connector_delegate_module, "resolve_connector_auth_config", resolve)
+
+ result = await service.add_resource(
+ path=_DINGTALK_URL,
+ ctx=ctx,
+ add_type="dingtalk",
+ to="viking://resources/docs",
+ args={"binding_version": 3},
+ connector_auth_config={"openviking_credential_ref": _dingtalk_credential_ref()},
+ )
+
+ assert result["task_id"] == "task-1"
+ payload = client.submit_doc_add.await_args.kwargs
+ assert payload["add_type"] == "dingtalk"
+ # The resolver output is forwarded verbatim as the private auth_config and
+ # never leaks into param_config.
+ assert payload["auth_config"] == _dingtalk_auth_config("live-token")
+ assert "user_access_token" not in str(payload["param_config"])
+ assert payload["param_config"]["path"] == _DINGTALK_URL
+ assert payload["param_config"]["binding_version"] == 3
+ resolve.assert_awaited_once()
+ forwarded_reference = resolve.await_args.args[0]
+ assert forwarded_reference == _dingtalk_credential_ref()
+
+
+async def test_dingtalk_watch_replays_reference_and_reresolves_each_round(
+ monkeypatch, connector_config, ctx, service
+):
+ connector_config.allowed_add_types.append("dingtalk")
+ client = SimpleNamespace(submit_doc_add=AsyncMock(return_value={"task_key": "C1"}))
+ _install_connector_dependencies(monkeypatch, _task_tracker(), client)
+ tokens = iter(["round-1", "round-2"])
+ resolve = AsyncMock(side_effect=lambda *_: _dingtalk_auth_config(next(tokens)))
+ monkeypatch.setattr(connector_delegate_module, "resolve_connector_auth_config", resolve)
+
+ delegate = service._connector
+ connector_auth_config = {"openviking_credential_ref": _dingtalk_credential_ref()}
+ state = await delegate.create_watch_auth_state(
+ api_key=ctx.api_key,
+ account_id=ctx.account_id,
+ add_type="dingtalk",
+ path=_DINGTALK_URL,
+ connector_args={"binding_version": 3},
+ connector_auth_config=connector_auth_config,
+ )
+ # Encrypted watch state only persists the secret-free reference.
+ assert "user_access_token" not in json.dumps(state)
+
+ for expected in ("round-1", "round-2"):
+ api_key, add_type, restored_args, restored_ref = await delegate.restore_watch_request(
+ state, account_id=ctx.account_id, path=_DINGTALK_URL
+ )
+ assert api_key == ctx.api_key
+ assert add_type == "dingtalk"
+ assert restored_ref == connector_auth_config
+ await service.refresh_resource(
+ path=_DINGTALK_URL,
+ ctx=ctx,
+ add_type=add_type,
+ to="viking://resources/docs",
+ args=restored_args,
+ connector_auth_config=restored_ref,
+ )
+ assert client.submit_doc_add.await_args.kwargs["auth_config"] == _dingtalk_auth_config(
+ expected
+ )
+ assert resolve.await_count == 2
+
+
+async def test_managed_reference_without_connector_route_is_rejected(
+ monkeypatch, connector_config, ctx, service
+):
+ # A credential reference must resolve inside Connector delegation; a source
+ # that does not route to the Connector must fail instead of silently
+ # degrading to an unauthorized standard-pipeline import.
+ client = SimpleNamespace(submit_doc_add=AsyncMock(return_value={"task_key": "C1"}))
+ _install_connector_dependencies(monkeypatch, _task_tracker(), client)
+ with pytest.raises(InvalidArgumentError, match="requires a Connector import"):
+ await service.add_resource(
+ path="https://example.com/page",
+ ctx=ctx,
+ to="viking://resources/docs",
+ connector_auth_config={"openviking_credential_ref": _dingtalk_credential_ref()},
+ )
+ client.submit_doc_add.assert_not_awaited()
+
+
+async def test_dingtalk_registry_type_rejects_managed_reference(
+ monkeypatch, connector_config, ctx, service
+):
+ # Registry types (tos/git) carry credentials through their own channels, so
+ # a managed reference on such a declared type is rejected.
+ connector_config.allowed_add_types = ["git"]
+ _install_connector_dependencies(monkeypatch, _task_tracker(), SimpleNamespace())
+ with pytest.raises(InvalidArgumentError, match="does not accept a managed credential reference"):
+ await service._connector.submit(
+ path=_GIT_REPO_PREFIX + "org/repo",
+ ctx=ctx,
+ to="viking://resources/repo",
+ declared_add_type="git",
+ connector_auth_config={"openviking_credential_ref": _dingtalk_credential_ref()},
+ )
diff --git a/tests/unit/test_connector_config.py b/tests/unit/test_connector_config.py
index ff096e58d..c00e7b15e 100644
--- a/tests/unit/test_connector_config.py
+++ b/tests/unit/test_connector_config.py
@@ -72,3 +72,22 @@ def test_connector_auth_does_not_enable_ingestion_delegation():
config = ConnectorConfig(auth=" https://connector.example/oauth/access_token ")
assert config.auth == "https://connector.example/oauth/access_token"
assert config.enable is False
+
+
+ ("auth", "expected"),
+ [
+ (
+ "https://connector.example/api/v1/inner/connector/oauth/access_token",
+ "https://connector.example/api/v1/inner/connector/credential/resolve",
+ ),
+ (
+ "https://connector.example/api/v1/inner/connector/credential/resolve",
+ "https://connector.example/api/v1/inner/connector/credential/resolve",
+ ),
+ ("", ""),
+ ("https://connector.example/some/other/path", ""),
+ ],
+)
+def test_credential_resolve_url_is_derived_from_auth(auth, expected):
+ assert ConnectorConfig(auth=auth).credential_resolve_url() == expected