Skip to content

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

fix: feishu_project_auth_refresh (#5350)

zihenglif6f8d42a5b10
diff --git a/openviking/connector/auth.py b/openviking/connector/auth.py
index 77296b39f..77e54e3b0 100644
--- a/openviking/connector/auth.py
+++ b/openviking/connector/auth.py
@@ -100,7 +100,9 @@ async def restore_feishu_request(
return api_key, {OAUTH_REF_ARG: reference}
-def validate_oauth_ref(value: Any, ov_user_id: str) -> Dict[str, str]:
+def validate_oauth_ref(
+ value: Any, ov_user_id: str, *, platform: str = "feishu_doc"
+) -> Dict[str, str]:
keys = {"account_id", "user_id", "ov_user_id", "platform", "type"}
if (
not isinstance(value, dict)
@@ -109,8 +111,8 @@ def validate_oauth_ref(value: Any, ov_user_id: str) -> Dict[str, str]:
):
raise InvalidArgumentError("args.openviking_oauth_ref contains an invalid OAuth reference.")
ref = {key: value[key].strip() for key in keys}
- if ref["type"] != "oauth" or ref["platform"] != "feishu_doc":
- raise InvalidArgumentError("Native Feishu imports require a feishu_doc OAuth reference.")
+ if ref["type"] != "oauth" or ref["platform"] != platform:
+ raise InvalidArgumentError(f"This import requires a {platform} OAuth reference.")
if ref["ov_user_id"] != ov_user_id:
raise InvalidArgumentError(
"OAuth reference does not belong to the current OpenViking user."
@@ -118,12 +120,31 @@ def validate_oauth_ref(value: Any, ov_user_id: str) -> Dict[str, str]:
return ref
+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)
+ if args.get("auth_config") or any(
+ key in args for key in ("user_access_token", "user_key", "plugin_id", "plugin_secret")
+ ):
+ raise InvalidArgumentError(
+ "OAuth references cannot be combined with explicit project credentials."
+ )
+ reference = validate_oauth_ref(args[OAUTH_REF_ARG], ctx.user.user_id, platform="feishu_project")
+ provider = ExternalFeishuToken(reference, ctx.api_key or "")
+ credentials = await asyncio.to_thread(provider.get_credentials)
+ account = credentials.get("account")
+ user_key = account.get("id") if isinstance(account, dict) else None
+ if not isinstance(user_key, str) or not user_key.strip():
+ raise InternalError("External OAuth returned no project user key.")
+ return {"user_access_token": credentials["access_token"], "user_key": user_key.strip()}
+
+
def is_external_feishu_auth(state: Optional[Dict[str, Any]]) -> bool:
return isinstance(state, dict) and state.get("provider") == EXTERNAL_FEISHU_PROVIDER
class ExternalFeishuToken:
- """Cache only access tokens, within one execution; never refresh OAuth locally."""
+ """Cache access credentials within one execution; never refresh OAuth locally."""
def __init__(self, reference: Dict[str, str], api_key: str):
self._url = external_auth_url()
@@ -137,16 +158,19 @@ class ExternalFeishuToken:
self._api_key = api_key
self._client = ConnectorClient("", "", account_id=reference["account_id"])
self._lock = Lock()
- self._token = ""
+ self._credentials: Dict[str, Any] = {}
self._valid_until = 0.0
self._error: Optional[InternalError] = None
def get_token(self) -> str:
+ return self.get_credentials()["access_token"]
+
+ def get_credentials(self) -> Dict[str, Any]:
with self._lock:
if self._error is not None:
raise self._error
- if self._token and time.time() < self._valid_until:
- return self._token
+ if self._credentials and time.time() < self._valid_until:
+ return self._credentials
try:
data = self._client.get_oauth_access_token(
self._url, self._api_key, self._reference
@@ -169,9 +193,9 @@ class ExternalFeishuToken:
"External OAuth returned an invalid or expired access token."
)
raise self._error
- self._token = token.strip()
+ self._credentials = {**data, "access_token": token.strip()}
self._valid_until = min(now + 60, expires_at - 30) if expires_at else now + 60
- return self._token
+ return self._credentials
def check_feishu_auth(resource: "LocalResource") -> "LocalResource":
diff --git a/openviking/connector/delegate.py b/openviking/connector/delegate.py
index b60a8337a..7fce0deb2 100644
--- a/openviking/connector/delegate.py
+++ b/openviking/connector/delegate.py
@@ -26,6 +26,7 @@ from urllib.parse import urlsplit
import httpx
+from openviking.connector.auth import OAUTH_REF_ARG, project_auth_config
from openviking.connector.client import ConnectorClient
from openviking.connector.routing import (
CONNECTOR_ARGS_AUTH_CONFIG_KEY,
@@ -566,6 +567,10 @@ class ConnectorDelegate:
str(key): str(value) for key, value in (declared_auth or {}).items() if value
}
+ if add_type in {"meego", "feishu_project"} and OAUTH_REF_ARG in (connector_args or {}):
+ auth_config = await project_auth_config(connector_args or {}, ctx)
+ forwarded_args.pop(OAUTH_REF_ARG, None)
+
tos_path: Optional[str] = None
param_config: Optional[Dict[str, Any]] = None
if add_type == "tos":
diff --git a/tests/connector/test_auth.py b/tests/connector/test_auth.py
index 84926debc..acb6f54eb 100644
--- a/tests/connector/test_auth.py
+++ b/tests/connector/test_auth.py
@@ -260,3 +260,30 @@ async def test_queue_auth_failure_cleanup_and_prepared_results(
ctx=ctx,
resource_lock=lock,
)
+
+
+async def test_project_credentials_use_account_identity_and_validate_reference(monkeypatch):
+ ctx = SimpleNamespace(user=SimpleNamespace(user_id="alice"), api_key="caller-key")
+ reference = {**REFERENCE, "platform": "feishu_project"}
+ fetch = Mock(return_value={"access_token": " token ", "account": {"id": " project-user "}})
+ monkeypatch.setattr(ConnectorClient, "get_oauth_access_token", fetch)
+ args = {auth.OAUTH_REF_ARG: reference}
+ assert await auth.project_auth_config(args, ctx) == {
+ "user_access_token": "token", "user_key": "project-user"
+ }
+ fetch.assert_called_once_with(auth.external_auth_url(), "caller-key", reference)
+ assert args == {auth.OAUTH_REF_ARG: reference}
+ with pytest.raises(InvalidArgumentError):
+ auth.validate_oauth_ref(reference, "alice")
+ for invalid in (None, REFERENCE, {**reference, "ov_user_id": "bob"}):
+ with pytest.raises(InvalidArgumentError):
+ await auth.project_auth_config({auth.OAUTH_REF_ARG: invalid}, ctx)
+ for extra in ({"auth_config": {"user_key": "other"}}, {"user_access_token": ""}, {"plugin_id": "id"}):
+ with pytest.raises(InvalidArgumentError):
+ await auth.project_auth_config({**args, **extra}, ctx)
+ assert fetch.call_count == 1
+ for account in (None, {}, {"id": " "}, {"id": 123}):
+ fetch.return_value = {"access_token": "token", "account": account}
+ with pytest.raises(InternalError, match="user key"):
+ await auth.project_auth_config(args, ctx)
diff --git a/tests/service/test_resource_service_connector.py b/tests/service/test_resource_service_connector.py
index 97bd159e7..514f1223d 100644
--- a/tests/service/test_resource_service_connector.py
+++ b/tests/service/test_resource_service_connector.py
@@ -2877,3 +2877,51 @@ def test_declared_git_keeps_args_whitelist(connector_config, ctx, service):
to="viking://resources/x",
connector_args={"depth": 1},
)
+
+
[email protected]("add_type", ["meego", "feishu_project"])
+async def test_project_oauth_dispatch_and_watch_replay(
+ monkeypatch, connector_config, ctx, service, add_type
+):
+ from openviking.connector import auth
+
+ connector_config.allowed_add_types = [add_type]
+ connector_config.auth = "https://connector.example/oauth/access_token"
+ tracker = _task_tracker()
+ client = SimpleNamespace(submit_doc_add=AsyncMock(return_value={"task_key": "connector-1"}))
+ _install_connector_dependencies(monkeypatch, tracker, client)
+ reference = {
+ "account_id": "cloud-account", "user_id": "cloud-user", "ov_user_id": "alice",
+ "platform": "feishu_project", "type": "oauth",
+ }
+ fetch = Mock(side_effect=[
+ {"access_token": token, "account": {"id": "project-user"}} for token in ("first", "second")
+ ])
+ monkeypatch.setattr(auth.ConnectorClient, "get_oauth_access_token", fetch)
+ args = {auth.OAUTH_REF_ARG: reference, "project_keys": ["project"]}
+ path = "https://project.feishu.cn/project"
+ delegate = service._connector
+ state = await delegate.create_watch_auth_state(
+ 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(
+ state, account_id=ctx.account_id, path=path
+ )
+ assert api_key == ctx.api_key
+ await service.add_resource(
+ path=path, ctx=ctx, add_type=restored_type, to="viking://resources/kb/project", args=restored_args
+ )
+ request = client.submit_doc_add.call_args.kwargs
+ assert request["auth_config"] == {"user_access_token": token, "user_key": "project-user"}
+ assert request["param_config"] == {"project_keys": ["project"], "path": path}
+ assert restored_args == args
+ assert fetch.call_count == 2
+ assert "access_token" not in json.dumps(state)
+ fetch.side_effect = InvalidArgumentError("OAuth unavailable")
+ with pytest.raises(InvalidArgumentError, match="OAuth unavailable"):
+ await service.add_resource(
+ path=path, ctx=ctx, add_type=add_type, to="viking://resources/kb/project", args=args
+ )
+ assert client.submit_doc_add.await_count == 2