Repository navigation
refactor: enhance getBaseModelList to include model_id for credential restoration and add corresponding tests #8289
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
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -190,6 +190,28 @@ def cache_base_model_list(provider, model_type, api_key, api_base, credential, m | |
| ) | ||
|
|
||
|
|
||
| def restore_model_credential(provider, model_type, model_id, credential, provider_handler=None): | ||
| """用已保存模型的真实凭证替换编辑表单中未改动的脱敏字段。""" | ||
| if not model_id or not isinstance(credential, dict): | ||
| return credential | ||
| model = QuerySet(Model).filter(id=model_id, provider=provider, model_type=model_type).first() | ||
| if model is None: | ||
| return credential | ||
| try: | ||
| source_credential = json.loads(rsa_long_decrypt(model.credential)) | ||
| provider_handler = provider_handler or ModelProvideConstants[provider] | ||
| encrypted_credential = provider_handler.get_model_credential(model_type, model.model_name).encryption_dict( | ||
| source_credential | ||
| ) | ||
| restored = dict(credential) | ||
| for key, encrypted_value in encrypted_credential.items(): | ||
| if key in restored and restored[key] == encrypted_value: | ||
| restored[key] = source_credential.get(key) | ||
| return restored | ||
| except Exception: | ||
| return credential | ||
|
|
||
|
|
||
| def get_cached_base_model_list(provider, model_type, model_id=None, credential=None): | ||
| """按 url+key 读取缓存的官方模型列表,未命中返回空列表。 | ||
|
|
||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Here are the issues and suggestions: Correctness / Logic
Optimization / Style
Highest priority: #1 and #2 (the function likely doesn't do what the docstring claims, and can null out secrets), then #5 (security) and #3 (silent failures). |
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| import assert from 'node:assert/strict' | ||
| import { readFileSync } from 'node:fs' | ||
| import { test } from 'node:test' | ||
| import { compileFunction } from 'node:vm' | ||
| import ts from 'typescript' | ||
|
|
||
| function loadModelProviderApi(request) { | ||
| const { outputText } = ts.transpileModule(readFileSync(new URL('../src/api/admin/model-provider.ts', import.meta.url), 'utf8'), { | ||
| compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 }, | ||
| }) | ||
| const exports = {} | ||
| compileFunction(outputText, ['require', 'exports'])((id) => { | ||
| assert.equal(id, './core/request') | ||
| return request | ||
| }, exports) | ||
| return exports.default | ||
| } | ||
|
|
||
| test('编辑模型获取基础模型列表时提交 model_id', async () => { | ||
| let requestPayload | ||
| const providerApi = loadModelProviderApi({ | ||
| get: () => Promise.resolve([]), | ||
| post: (_path, payload) => { | ||
| requestPayload = payload | ||
| return Promise.resolve([]) | ||
| }, | ||
| }) | ||
| const credential = { api_key: '[API_KEY]' } | ||
|
|
||
| await providerApi.getBaseModelList('test_provider', 'LLM', undefined, credential, 'model-id') | ||
|
|
||
| assert.equal(requestPayload.model_id, 'model-id') | ||
| assert.deepEqual(requestPayload.credential, credential) | ||
| }) | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I can only see the test helper, not Potential functional issues
Optimization / robustness suggestions
Overall: no security issue in this test code, but the module mock shape and same-reference credential assertion are the main correctness risks. |
||
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.
Code Review:
Provide.ModelListTest Patch🔴 Critical Issues
1. Test will fail — hard-coded expected value mismatch
The saved credential contains
"api_key": "[API_KEY]"(masked), and the test never injects"sk-live-secret"anywhere. Unlessrsa_long_encrypt/the view magic replaces it, this assertion cannot pass. Compare the first test which uses"[API_KEY]"as the expected value consistently.2.
cache_model_list.call_args.args[2]is brittleIndex-based access into positional args breaks silently if the signature changes. Use:
Better yet, assert on explicit named params.
3.
.side_effect = lambda credential: {...}ignores its inputIf the view calls this to decrypt/mask, returning a fixed mask means the test never verifies the real save/resolve path. This setup effectively fabricates the outcome you then assert. Consider using the real utility or asserting the mock was called with the decrypted credential.
🟠 Potential Issues
4. Mixing
SimpleTestCase→TestCaseAdding
TestCasefor DB access is correct, but check transactional side effects: ifrsa_long_encrypt/Model.objects.createtouches other tables or relies on migrations, ensure the test app is inINSTALLED_APPSand migrations are applied for the test DB.5. Missing
assign_role/ workspace permissions fixtureThe new test creates a
Modelwithworkspace_id="workspace-id"but sets no user/permission context. If the view enforces workspace membership, this test may pass only becauseProvide.ModelList()bypasses auth. Add a comment documenting that assumption, or wire auth consistently with the other tests.6.
request.datamutated after constructionDuplicating top-level
api_keyfromcredentialmirrors production behavior, but mutating a dict insideSimpleNamespaceinline is easy to miss. Build the dict in one literal:7.
model_idvsproviderconsistency not validatedThe test supplies
model_idand a full credential. Make explicit which source wins (saved DB row vs. request body). If the feature is "use saved credential when edit values are masked," assert that the request's masked fields were actually replaced — currently only the final result is checked, not that the DB value was read.🟡 Optimizations / Style
8. Unused import risk
You added
import json,TestCase,rsa_long_encrypt,Model. Verify all are used; otherwise linters (flake8/ruff) will flag them.jsonand the others do appear used here — good.9. Large multi-context
withblockPython 3.10+ parenthesized
withis fine, but patch targets are only scoped over the.post()call. Any downstream lazy import ofModelProvideConstantsoutside that scope won't be patched. Prefer@patch(...)decorators at method level for clarity and to ensure coverage of the whole call chain.10. Assert call count on
get_model_credentialAdd:
to detect redundant lookups or regressions.
11.
[API_KEY]masking string should be a constantReplace literals with a shared constant (e.g.,
MASKED_API_KEY = "[API_KEY]") to avoid typos across both tests.12. First test change — verify intentional
Changing from a list (
[API_KEY]) to a string is a behavioral change. Confirm the provider now expects a scalar. If[API_KEY]was a variable (not a list), note the diff is misleading — consider renaming the constant so the diff is unambiguous.✅ Suggested Fix Skelton
Bottom line: the second assertion set (
"sk-live-secret") contradicts the fixture data and will fail; theencryption_dictstub masks the logic under test; and index-basedcall_argsaccess is fragile. Fix these three before merging.