-
Notifications
You must be signed in to change notification settings - Fork 42
Unbind model rules automatically when deleting a bound credential #50
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
ba57ae3
Auto-unbind model rules when deleting a bound credential
maiphucgiang da2418c
Format the new e2e unbind test
maiphucgiang 899d254
Keep model bindings when credential removal fails
maiphucgiang 729567c
Roll back the unbind when credential removal fails
maiphucgiang 47084cc
Keep concurrent binding edits during unbind rollback
maiphucgiang a65a77e
Serialize the confirmed delete with rule edits and sweep racing rebinds
maiphucgiang File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| """Deleting credentials that are still bound by model rules must auto-unbind on confirmation.""" | ||
| import sys | ||
| from pathlib import Path | ||
| sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # Allow direct execution. | ||
|
|
||
| import json | ||
| import os | ||
| import tempfile | ||
| import time | ||
| import unittest | ||
| from types import SimpleNamespace | ||
| from unittest.mock import patch | ||
| import threading | ||
|
|
||
|
|
||
| from fastapi import HTTPException | ||
| from fastapi.testclient import TestClient | ||
|
|
||
| import converter | ||
| from app.control_store import ControlStore | ||
| from app.gateway_management import Management | ||
|
|
||
|
|
||
| class UnbindDeleteTests(unittest.TestCase): | ||
| def setUp(self): | ||
| root = Path(self.enterContext(tempfile.TemporaryDirectory())) | ||
| self.enterContext(patch.dict(os.environ, {"CODEBUDDY_AUTH_DIR": str(root)})) | ||
| self.enterContext(patch.dict(converter.CONFIG, {"log_path": None, "cred_pool": None, "cred": None})) | ||
| self.path = root / "account.info" | ||
| self.path.write_text(json.dumps({"account": {"uid": "synthetic"}, "auth": { | ||
| "accessToken": "old-synthetic-token", "refreshToken": "synthetic-refresh", | ||
| "domain": "www.codebuddy.cn", "expiresAt": (time.time() + 86400) * 1000, | ||
| "lastRefreshTime": time.time() * 1000}}), encoding="utf-8") | ||
| self.pool = converter.CredentialPool([self.path]) | ||
| self.store = ControlStore(root / "control.sqlite3") | ||
| self.addCleanup(self.store.close) | ||
| self.config = {"cred_pool": self.pool, "control_store": self.store, | ||
| "ledger": None, "trial_ledger": None} | ||
| self.management = Management(SimpleNamespace(CONFIG=self.config)) | ||
| self.identity = self.pool.entries()[0]["account_key"] | ||
|
|
||
| def bind(self): | ||
| self.store.update_model("glm-4-flash", {"credential_ids": [self.identity]}, 0) | ||
|
|
||
| def test_bound_delete_is_blocked_without_the_confirmation_flag(self): | ||
| self.bind() | ||
| with self.assertRaises(HTTPException) as ctx: | ||
| self.management.admin_delete_guard("account.info") | ||
| self.assertEqual(ctx.exception.status_code, 409) | ||
| self.assertEqual(ctx.exception.detail["models"], ["glm-4-flash"]) | ||
|
|
||
| def test_confirmed_unbind_rolls_back_when_removal_fails(self): | ||
| self.store.update_model("glm-4-flash", {"public_id": "glm4", "credential_ids": [self.identity, "other"]}, 0) | ||
| identity = self.management.admin_delete_guard("account.info", unbind=True) | ||
| self.assertEqual(identity, self.identity) | ||
| rollback = self.management.admin_unbind_credential(identity) | ||
| self.assertEqual(rollback, {"identity": self.identity, "rules": {"glm-4-flash": [self.identity, "other"]}}) | ||
| self.assertEqual(self.store.snapshot()["models"]["glm-4-flash"]["credential_ids"], ["other"]) | ||
| self.management.admin_restore_bindings(rollback) # A failed removal undoes the unbind. | ||
| rule = self.store.snapshot()["models"]["glm-4-flash"] | ||
| self.assertEqual(rule["credential_ids"], [self.identity, "other"]) | ||
| self.assertEqual(rule["public_id"], "glm4") | ||
| self.assertTrue(self.path.exists()) | ||
|
|
||
| def test_rollback_preserves_concurrent_binding_edits(self): | ||
| self.store.update_model("glm-4-flash", {"credential_ids": [self.identity, "other"]}, 0) | ||
| identity = self.management.admin_delete_guard("account.info", unbind=True) | ||
| rollback = self.management.admin_unbind_credential(identity) | ||
| # Another administrator rebinds the rule between the unbind and the rollback. | ||
| revision = self.store.snapshot()["revision"] | ||
| self.store.update_model("glm-4-flash", {"credential_ids": ["fresh"]}, revision) | ||
| self.management.admin_restore_bindings(rollback) | ||
| self.assertEqual(self.store.snapshot()["models"]["glm-4-flash"]["credential_ids"], ["fresh"]) | ||
|
|
||
| def test_route_keeps_bindings_when_removal_fails(self): | ||
| self.bind() | ||
| config = dict(self.config, api_key="secret", management=self.management) | ||
| self.enterContext(patch.dict(converter.CONFIG, config)) | ||
| client = TestClient(converter.app) | ||
| headers = {"X-Api-Key": "secret"} | ||
| with patch.object(self.pool, "remove_file", return_value=False): | ||
| response = client.delete("/admin/credentials/account.info?unbind=1", headers=headers) | ||
| self.assertEqual(response.status_code, 404, response.text) | ||
| self.assertEqual(self.store.snapshot()["models"]["glm-4-flash"]["credential_ids"], | ||
| [self.identity]) # A failed removal never widens routing to automatic. | ||
| response = client.delete("/admin/credentials/account.info?unbind=1", headers=headers) | ||
| self.assertEqual(response.status_code, 200, response.text) | ||
| self.assertEqual(self.store.snapshot()["models"]["glm-4-flash"]["credential_ids"], []) | ||
| self.assertFalse(self.path.exists()) | ||
|
|
||
| def test_route_sweeps_a_rebind_that_raced_the_removal(self): | ||
| self.bind() | ||
| config = dict(self.config, api_key="secret", management=self.management, | ||
| admin_mutation_lock=threading.RLock()) | ||
| self.enterContext(patch.dict(converter.CONFIG, config)) | ||
| client = TestClient(converter.app) | ||
| headers = {"X-Api-Key": "secret"} | ||
| real_remove = self.pool.remove_file | ||
| def rebind_during_removal(file_name): | ||
| # A writer outside the shared lock rebinds while the credential is pooled. | ||
| revision = self.store.snapshot()["revision"] | ||
| self.store.update_model("glm-4-flash", {"credential_ids": [self.identity]}, revision) | ||
| return real_remove(file_name) | ||
| with patch.object(self.pool, "remove_file", side_effect=rebind_during_removal): | ||
| response = client.delete("/admin/credentials/account.info?unbind=1", headers=headers) | ||
| self.assertEqual(response.status_code, 200, response.text) | ||
| self.assertEqual(self.store.snapshot()["models"]["glm-4-flash"]["credential_ids"], []) | ||
| self.assertFalse(self.path.exists()) | ||
|
|
||
| def test_unbound_and_unknown_credentials_stay_on_the_fast_path(self): | ||
| self.assertIsNone(self.management.admin_delete_guard("account.info")) # No bindings. | ||
| self.assertIsNone(self.management.admin_delete_guard("missing.info", unbind=True)) # Pool reports 404. | ||
| self.assertEqual(self.store.snapshot()["revision"], 0) | ||
|
|
||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main(verbosity=2) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When credential removal raises before unlinking, this expression bypasses the rollback branch and leaves the file present but its model bindings removed. This is reachable because
CredentialPool.remove_file()catches onlyOSError, whilecredential_file_lock()can raiseCredentialFileErrorfor a non-regular lock file (app/credential_io.py:65). Fresh evidence in this revision is that rollback is now confined to the false-result branch; normalize pre-unlink failures toFalseor catch them here and restore the bindings.Useful? React with 👍 / 👎.