Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix(personal-context): complete reauthorization

zhaominjun1997941ae8db1de0
diff --git a/jiuwenswarm/server/personal_context/host_api.py b/jiuwenswarm/server/personal_context/host_api.py
index 759408480a..ad8c1a6a45 100644
--- a/jiuwenswarm/server/personal_context/host_api.py
+++ b/jiuwenswarm/server/personal_context/host_api.py
@@ -1429,9 +1429,13 @@ class PersonalContextHostAPI:
self,
provider: str,
credentials: dict[str, object] | None = None,
+ *,
+ reauthorize: bool = False,
) -> dict[str, object]:
"""Check or begin user authorization for a configured provider."""
+ if not isinstance(reauthorize, bool):
+ _raise_host_error("reauthorize must be a boolean")
async with self._operation_lock:
if not isinstance(provider, str) or not provider.strip():
_raise_host_error("provider must be a non-empty string")
@@ -1462,10 +1466,48 @@ class PersonalContextHostAPI:
)
provider_credentials[normalized_provider] = {field: normalized_secret}
stored["provider_credentials"] = provider_credentials
+ matching_service_ids: set[str] = set()
+ if reauthorize:
+ services = cast(list[dict[str, object]], stored["fetch_services"])
+ for service in services:
+ if service.get("provider") == normalized_provider:
+ service["credentials"] = {field: normalized_secret}
+ service_id = service.get("service_id")
+ if isinstance(service_id, str):
+ matching_service_ids.add(service_id)
stored, candidate = _prepare_stored_config(stored)
payload = _serialize_config(stored)
if self._stored_config is None:
await self._apply_configuration_locked(candidate, stored, payload)
+ elif reauthorize and matching_service_ids:
+ current = self._config
+ if current is None:
+ _raise_host_error("PersonalContext is not configured")
+ previous_services = tuple(
+ item
+ for item in current.fetch_services
+ if item.service_id in matching_service_ids
+ )
+ candidate_services = tuple(
+ item
+ for item in candidate.fetch_services
+ if item.service_id in matching_service_ids
+ )
+ await self._apply_live_update_locked(
+ candidate,
+ stored,
+ payload,
+ apply=lambda: (
+ self._personal_context._replace_fetch_service_credentials( # pylint: disable=protected-access
+ candidate_services
+ )
+ ),
+ rollback=lambda: (
+ self._personal_context._replace_fetch_service_credentials( # pylint: disable=protected-access
+ previous_services
+ )
+ ),
+ )
else:
try:
_publish_yaml(self._config_path, payload)
@@ -1491,7 +1533,8 @@ class PersonalContextHostAPI:
)
try:
return await self._personal_context.authorize_provider(
- normalized_provider
+ normalized_provider,
+ reauthorize=reauthorize,
)
except asyncio.CancelledError:
raise
diff --git a/jiuwenswarm/server/personal_context/ws_handler.py b/jiuwenswarm/server/personal_context/ws_handler.py
index cf7902e24d..54148bea50 100644
--- a/jiuwenswarm/server/personal_context/ws_handler.py
+++ b/jiuwenswarm/server/personal_context/ws_handler.py
@@ -293,9 +293,13 @@ async def _execute(
credentials = params.get("credentials")
if credentials is not None and not isinstance(credentials, dict):
raise ValueError("credentials must be an object")
+ reauthorize = params.get("reauthorize", False)
+ if not isinstance(reauthorize, bool):
+ raise ValueError("reauthorize must be a boolean")
return await host.authorize_provider(
_text(params, "provider"),
credentials=cast(dict[str, object] | None, credentials),
+ reauthorize=reauthorize,
)
if method == ReqMethod.PERSONAL_CONTEXT_CONTEXT_SEARCH_PAGES:
return await host.search_graph(_text(params, "query"))
diff --git a/tests/unit_tests/agentserver/test_personal_context_websocket_api.py b/tests/unit_tests/agentserver/test_personal_context_websocket_api.py
index 4583941daf..e62e79842c 100644
--- a/tests/unit_tests/agentserver/test_personal_context_websocket_api.py
+++ b/tests/unit_tests/agentserver/test_personal_context_websocket_api.py
@@ -180,10 +180,12 @@ class _FakeHost:
self,
provider: str,
credentials: dict[str, object] | None = None,
+ *,
+ reauthorize: bool = False,
) -> dict[str, object]:
return self._record(
"authorize_provider",
- (provider, credentials),
+ (provider, credentials, reauthorize),
{
"provider": provider,
"state": "authorized",
@@ -443,7 +445,20 @@ PERSONAL_CONTEXT_HOST_CALLS = [
ReqMethod.PERSONAL_CONTEXT_FETCH_AUTHORIZE_PROVIDER,
{"provider": "feishu"},
"authorize_provider",
- ("feishu", None),
+ ("feishu", None, False),
+ {
+ "provider": "feishu",
+ "state": "authorized",
+ "verification_url": None,
+ "expires_at": None,
+ "error": None,
+ },
+ ),
+ (
+ ReqMethod.PERSONAL_CONTEXT_FETCH_AUTHORIZE_PROVIDER,
+ {"provider": "feishu", "reauthorize": True},
+ "authorize_provider",
+ ("feishu", None, True),
{
"provider": "feishu",
"state": "authorized",
@@ -456,7 +471,7 @@ PERSONAL_CONTEXT_HOST_CALLS = [
ReqMethod.PERSONAL_CONTEXT_FETCH_AUTHORIZE_PROVIDER,
{"provider": "github", "credentials": {"token": "github-canary"}},
"authorize_provider",
- ("github", {"token": "github-canary"}),
+ ("github", {"token": "github-canary"}, False),
{
"provider": "github",
"state": "authorized",
@@ -644,7 +659,13 @@ async def test_runtime_switch_callback_failure_is_fail_open(
ReqMethod.PERSONAL_CONTEXT_FETCH_AUTHORIZE_PROVIDER,
{"provider": "github", "credentials": "not-an-object"},
{"provider": "github", "credentials": {"token": "github-canary"}},
- ("authorize_provider", ("github", {"token": "github-canary"})),
+ ("authorize_provider", ("github", {"token": "github-canary"}, False)),
+ ),
+ (
+ ReqMethod.PERSONAL_CONTEXT_FETCH_AUTHORIZE_PROVIDER,
+ {"provider": "feishu", "reauthorize": "true"},
+ {"provider": "feishu", "reauthorize": True},
+ ("authorize_provider", ("feishu", None, True)),
),
],
)
diff --git a/tests/unit_tests/personal_context/test_host_api.py b/tests/unit_tests/personal_context/test_host_api.py
index 27b06a2e40..16f4278c4c 100644
--- a/tests/unit_tests/personal_context/test_host_api.py
+++ b/tests/unit_tests/personal_context/test_host_api.py
@@ -183,6 +183,7 @@ class FakeCore:
self.deactivate_changes_active_before_error = False
self.set_error: BaseException | None = None
self.append_service_error: BaseException | None = None
+ self.replace_credentials_error: BaseException | None = None
self.activate_error: BaseException | None = None
self.activate_started: asyncio.Event | None = None
self.activate_release: asyncio.Event | None = None
@@ -296,6 +297,26 @@ class FakeCore:
self.append_service_error = None
raise error
+ async def _replace_fetch_service_credentials(
+ self,
+ replacements: tuple[object, ...],
+ ) -> None:
+ self.calls.append(("replace_fetch_service_credentials", replacements))
+ assert self.configured is not None
+ replacement_by_id = {item.service_id: item for item in replacements}
+ self.configured = self.configured.model_copy(
+ update={
+ "fetch_services": tuple(
+ replacement_by_id.get(item.service_id, item)
+ for item in self.configured.fetch_services
+ )
+ }
+ )
+ if self.replace_credentials_error is not None:
+ error = self.replace_credentials_error
+ self.replace_credentials_error = None
+ raise error
+
async def _remove_fetch_service_config(self, service_id: str) -> None:
self.calls.append(("remove_fetch_service_config", service_id))
assert self.configured is not None
@@ -316,8 +337,13 @@ class FakeCore:
raise error
return self.snapshot_result
- async def authorize_provider(self, provider: str) -> dict[str, object]:
- self.calls.append(("authorize_provider", provider))
+ async def authorize_provider(
+ self,
+ provider: str,
+ *,
+ reauthorize: bool = False,
+ ) -> dict[str, object]:
+ self.calls.append(("authorize_provider", (provider, reauthorize)))
return {
"provider": provider,
"state": "authorized",
@@ -850,10 +876,25 @@ async def test_authorize_provider_delegates_to_configured_core(
await host.configure(_config(enabled=False, root_dir=tmp_path))
core.calls.clear()
- result = await host.authorize_provider("feishu")
+ result = await host.authorize_provider("feishu", reauthorize=True)
assert result["state"] == "authorized"
- assert core.calls == [("authorize_provider", "feishu")]
+ assert core.calls == [("authorize_provider", ("feishu", True))]
+
+
+async def test_authorize_provider_rejects_non_boolean_reauthorize_before_core_call(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+) -> None:
+ host, core = fake_host
+
+ with pytest.raises(PersonalContext.Error, match="reauthorize must be a boolean"):
+ await host.authorize_provider( # type: ignore[arg-type]
+ "feishu",
+ reauthorize=1,
+ )
+
+ assert core.calls == []
@pytest.mark.asyncio
@@ -1331,7 +1372,7 @@ async def test_repository_pat_first_authorization_creates_minimal_stopped_config
@pytest.mark.asyncio
-async def test_repository_pat_replacement_only_changes_future_service_snapshots(
+async def test_repository_pat_replacement_without_reauthorize_only_changes_future_snapshots(
fake_host: tuple[PersonalContextHostAPI, FakeCore],
monkeypatch: pytest.MonkeyPatch,
) -> None:
@@ -1370,6 +1411,177 @@ async def test_repository_pat_replacement_only_changes_future_service_snapshots(
assert "credentials" not in new_public
+async def test_repository_reauthorization_updates_all_matching_services_only(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ host, core = fake_host
+
+ async def validate(_provider: str, _secret: str) -> dict[str, str]:
+ return {"login": "account", "display_name": "Account"}
+
+ monkeypatch.setattr(
+ host_module,
+ "_validate_repository_pat",
+ validate,
+ raising=False,
+ )
+ await host.authorize_provider("github", credentials={"token": "old-github"})
+ await host.authorize_provider("gitcode", credentials={"pat": "old-gitcode"})
+ await host.create_fetch_service(_repository_service("github-one", "github"))
+ await host.create_fetch_service(_repository_service("github-two", "github"))
+ await host.create_fetch_service(_repository_service("gitcode-one", "gitcode"))
+ core.calls.clear()
+
+ result = await host.authorize_provider(
+ "github",
+ credentials={"token": "new-github"},
+ reauthorize=True,
+ )
+
+ snapshots = {
+ item["service_id"]: item["credentials"]
+ for item in host._stored_config["fetch_services"]
+ }
+ assert snapshots == {
+ "github-one": {"token": "new-github"},
+ "github-two": {"token": "new-github"},
+ "gitcode-one": {"pat": "old-gitcode"},
+ }
+ assert host._stored_config["provider_credentials"] == {
+ "github": {"token": "new-github"},
+ "gitcode": {"pat": "old-gitcode"},
+ }
+ assert [name for name, _value in core.calls] == [
+ "replace_fetch_service_credentials"
+ ]
+ assert result["state"] == "authorized"
+ assert "new-github" not in repr(result)
+
+
+async def test_repository_reauthorization_without_matching_service_skips_core_update(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ host, core = fake_host
+
+ async def validate(_provider: str, _secret: str) -> dict[str, str]:
+ return {"login": "account", "display_name": "Account"}
+
+ monkeypatch.setattr(
+ host_module,
+ "_validate_repository_pat",
+ validate,
+ raising=False,
+ )
+
+ await host.authorize_provider(
+ "github",
+ credentials={"token": "old-token"},
+ )
+ core.calls.clear()
+
+ result = await host.authorize_provider(
+ "github",
+ credentials={"token": "new-token"},
+ reauthorize=True,
+ )
+
+ assert result["state"] == "authorized"
+ assert core.calls == []
+ assert host._stored_config["fetch_services"] == []
+
+
+ ("injected", "expected_error"),
+ [
+ (RuntimeError("candidate replace failed"), PersonalContext.Error),
+ (asyncio.CancelledError(), asyncio.CancelledError),
+ ],
+)
+async def test_repository_reauthorization_core_failure_restores_every_layer(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ monkeypatch: pytest.MonkeyPatch,
+ injected: BaseException,
+ expected_error: type[BaseException],
+) -> None:
+ host, core = fake_host
+
+ async def validate(_provider: str, _secret: str) -> dict[str, str]:
+ return {"login": "account", "display_name": "Account"}
+
+ monkeypatch.setattr(
+ host_module,
+ "_validate_repository_pat",
+ validate,
+ raising=False,
+ )
+ await host.authorize_provider("github", credentials={"token": "old-token"})
+ await host.create_fetch_service(_repository_service("github-one", "github"))
+ old_yaml = host._config_path.read_bytes()
+ old_stored = deepcopy(host._stored_config)
+ old_config = host._config
+ old_core_config = core.configured
+ core.replace_credentials_error = injected
+
+ with pytest.raises(expected_error):
+ await host.authorize_provider(
+ "github",
+ credentials={"token": "new-token"},
+ reauthorize=True,
+ )
+
+ assert host._config is old_config
+ assert host._stored_config == old_stored
+ assert host._config_path.read_bytes() == old_yaml
+ assert core.configured == old_core_config
+ assert list(host._home.glob(".*.tmp")) == []
+
+
+async def test_repository_reauthorization_yaml_failure_restores_core_and_memory(
+ fake_host: tuple[PersonalContextHostAPI, FakeCore],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ host, core = fake_host
+
+ async def validate(_provider: str, _secret: str) -> dict[str, str]:
+ return {"login": "account", "display_name": "Account"}
+
+ monkeypatch.setattr(
+ host_module,
+ "_validate_repository_pat",
+ validate,
+ raising=False,
+ )
+ await host.authorize_provider("github", credentials={"token": "old-token"})
+ await host.create_fetch_service(_repository_service("github-one", "github"))
+ old_yaml = host._config_path.read_bytes()
+ old_stored = deepcopy(host._stored_config)
+ old_config = host._config
+ old_core_config = core.configured
+
+ def fail_replace(_temporary: Path, _path: Path) -> None:
+ raise OSError("replace failed")
+
+ monkeypatch.setattr(host_module, "_replace_yaml", fail_replace)
+ with pytest.raises(PersonalContext.Error):
+ await host.authorize_provider(
+ "github",
+ credentials={"token": "new-token"},
+ reauthorize=True,
+ )
+
+ assert host._config is old_config
+ assert host._stored_config == old_stored
+ assert host._config_path.read_bytes() == old_yaml
+ assert core.configured == old_core_config
+ assert list(host._home.glob(".*.tmp")) == []
+
+
@pytest.mark.asyncio
async def test_repository_authorization_and_creation_reject_unsafe_credentials(
fake_host: tuple[PersonalContextHostAPI, FakeCore],