Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 57 additions & 3 deletions apps/models_provider/tests/test_provide_validation.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import json
from types import SimpleNamespace
from unittest.mock import MagicMock, patch

from django.http import QueryDict
from django.test import SimpleTestCase
from django.test import SimpleTestCase, TestCase

from common.exception.app_exception import BadRequest400
from common.utils.rsa_util import rsa_long_encrypt
from models_provider.models import Model
from models_provider.views.provide import Provide


Expand Down Expand Up @@ -146,9 +149,60 @@ def test_model_list_post_queries_with_provider_credential_fields(self):
self.assertEqual(200, response.status_code)
provider.get_model_list.assert_called_once_with(
"EMBEDDING",
api_key=None,
api_base=None,
api_key="secret",
api_base="https://api.example.com/v1",
credential={"api_base": "https://api.example.com/v1", "api_key": "secret"},
allow_builtin_fallback=False,
)
cache_model_list.assert_called_once()


class ProvideModelListCredentialTests(TestCase):
def test_model_list_post_uses_saved_credential_for_masked_edit_values(self):
saved_credential = {
"api_base": "https://dashscope.aliyuncs.com/compatible-mode/v1",
"api_key": "sk-live-secret",
}
model = Model.objects.create(
workspace_id="workspace-id",
name="Qwen",
model_type="LLM",
model_name="qwen-plus",
provider="test_provider",
credential=rsa_long_encrypt(json.dumps(saved_credential)),
)
provider = MagicMock()
provider.get_model_type_list.return_value = [{"value": "LLM"}]
provider.get_model_credential.return_value.to_form_list.return_value = [
{"field": "api_base", "label": "API URL", "required": True},
{"field": "api_key", "label": "API Key", "required": True},
]
provider.get_model_credential.return_value.encryption_dict.side_effect = lambda credential: {
**credential,
"api_key": "sk-li***************et",
}
provider.get_model_list.return_value = [{"name": "qwen-plus"}]
request = SimpleNamespace(
data={
"model_id": str(model.id),
"provider": "test_provider",
"model_type": "LLM",
"credential": {
"api_base": "https://dashscope.aliyuncs.com/compatible-mode/v1",
"api_key": "sk-li***************et",
},
}
)
request.data["api_key"] = request.data["credential"]["api_key"]

with (
patch("models_provider.views.provide.ModelProvideConstants", {"test_provider": provider}),
patch("models_provider.views.provide.cache_base_model_list") as cache_model_list,
):
response = Provide.ModelList().post(request)

self.assertEqual(200, response.status_code)
queried_credential = provider.get_model_list.call_args.kwargs["credential"]
self.assertEqual("sk-live-secret", queried_credential["api_key"])
self.assertEqual("sk-live-secret", provider.get_model_list.call_args.kwargs["api_key"])
self.assertEqual("sk-live-secret", cache_model_list.call_args.args[2])

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review: Provide.ModelList Test Patch

🔴 Critical Issues

1. Test will fail — hard-coded expected value mismatch

self.assertEqual("sk-live-secret", queried_credential["api_key"])

The saved credential contains "api_key": "[API_KEY]" (masked), and the test never injects "sk-live-secret" anywhere. Unless rsa_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 brittle

Index-based access into positional args breaks silently if the signature changes. Use:

cache_model_list.assert_called_once()
args, kwargs = cache_model_list.call_args
self.assertEqual("sk-live-secret", kwargs.get("api_key") or args[2])

Better yet, assert on explicit named params.

3. .side_effect = lambda credential: {...} ignores its input

provider.get_model_credential.return_value.encryption_dict.side_effect = lambda credential: {
    **credential, "api_key": "[API_KEY]"
}

If 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 → TestCase

Adding TestCase for DB access is correct, but check transactional side effects: if rsa_long_encrypt / Model.objects.create touches other tables or relies on migrations, ensure the test app is in INSTALLED_APPS and migrations are applied for the test DB.

5. Missing assign_role / workspace permissions fixture

The new test creates a Model with workspace_id="workspace-id" but sets no user/permission context. If the view enforces workspace membership, this test may pass only because Provide.ModelList() bypasses auth. Add a comment documenting that assumption, or wire auth consistently with the other tests.

6. request.data mutated after construction

request.data["api_key"] = request.data["credential"]["api_key"]

Duplicating top-level api_key from credential mirrors production behavior, but mutating a dict inside SimpleNamespace inline is easy to miss. Build the dict in one literal:

payload = {...}
payload["api_key"] = payload["credential"]["api_key"]
request = SimpleNamespace(data=payload)

7. model_id vs provider consistency not validated

The test supplies model_id and 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. json and the others do appear used here — good.

9. Large multi-context with block

Python 3.10+ parenthesized with is fine, but patch targets are only scoped over the .post() call. Any downstream lazy import of ModelProvideConstants outside 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_credential

Add:

provider.get_model_credential.assert_called_once()
provider.get_model_credential.return_value.to_form_list.assert_called_once()

to detect redundant lookups or regressions.

11. [API_KEY] masking string should be a constant

Replace literals with a shared constant (e.g., MASKED_API_KEY = "[API_KEY]") to avoid typos across both tests.

12. First test change — verify intentional

- api_key=[API_KEY],
+ api_key="[API_KEY]",

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

MASKED = "[API_KEY]"
REAL_KEY = "sk-live-secret"

def setUp(self):
    self.model = Model.objects.create(
        ...,
        credential=rsa_long_encrypt(json.dumps({
            "api_base": "...",
            "api_key": REAL_KEY,   # store real, not masked
        })),
    )

def test_...(self):
    payload = {...}  # masked values in request
    ...
    self.assertEqual(REAL_KEY, queried_credential["api_key"])

Bottom line: the second assertion set ("sk-live-secret") contradicts the fixture data and will fail; the encryption_dict stub masks the logic under test; and index-based call_args access is fragile. Fix these three before merging.

22 changes: 22 additions & 0 deletions apps/models_provider/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 读取缓存的官方模型列表,未命中返回空列表。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here are the issues and suggestions:

Correctness / Logic

  1. Wrong-merging direction of trust. The loop compares restored[key] == encrypted_value (the re-encrypted real value). But the form's untouched masked field likely holds the masked/display value sent to the frontend, not the encrypted value. That means the comparison will rarely match, so restoration silently does nothing. You should compare against the actual value the form would have received — i.e., whatever get_model_credential(...).encryption_dict(...) outputs for display, or against a mask constant. Verify which representation the UI echoes back.

  2. Overwriting with None. source_credential.get(key) returns None if the key is missing from the stored credential. Since you only enter this branch when the keys matched, an absent key would replace a previously valid value with None. Guard with if key in source_credential.

  3. Broad except Exception: return credential swallows decryption errors, bad provider lookups (ModelProvideConstants[provider] raises KeyError), and programming bugs alike. Narrow the exceptions (e.g. JSONDecodeError, decryption errors, KeyError) and log them; otherwise you'll never diagnose silent failures in production.

  4. provider_handler or ModelProvideConstants[provider] — if provider_handler is passed but incomplete/mismatched, no validation. Also ModelProvideConstants[provider] is evaluated lazily (good), but ensure provider is always a valid constant here.

  5. Security: restoring credentials for any model_id. There's no check that the caller is allowed to edit/view that model's credential. Filtering by provider/model_type helps but doesn't tie the lookup to the requesting user/tenant. If this runs on user-supplied input, it can be used to exfiltrate other models' secrets (IDOR). Add an ownership/permission check.

Optimization / Style

  1. Query efficiency. Model(id, provider, model_type).first() is fine, but ensure there's an index covering (id, provider, model_type)—the PK alone is enough since it's unique; the extra filters just add safety. Consider .only("credential", "model_name") to avoid loading all columns.

  2. Unnecessary copy. restored = dict(credential) then mutate — fine, but if nothing is restored you return a copy rather than the original. Minor; consider tracking whether any restoration happened and returning credential untouched otherwise (avoids surprising identity changes for callers).

  3. Repeated re-encryption cost. Calling encryption_dict on every edit request re-does RSA/encryption work merely to compare strings. If possible, compare against a cheaper canonical form (e.g., a hash) or a stored "is-masked" flag/sentinel instead.

  4. Docstring/comment is Chinese while the rest of the codebase may be English — consistency nit. Also the return type/contract (may return the same object, a copy, or original) should be documented.

  5. Naming. encrypted_value is misleading — it's the re-encrypted version of the stored secret, being compared to a possibly-masked form input. Rename to expected_masked/real_encrypted to clarify intent.

  6. Testability. No unit-test-friendly seam for decryption/handler; consider injecting these or at least testing the no-match, missing-key, and decrypt-failure paths.

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).

Expand Down
8 changes: 7 additions & 1 deletion apps/models_provider/views/provide.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from models_provider.api.provide import ProvideApi
from models_provider.constants.model_provider_constants import ModelProvideConstants
from models_provider.serializers.model_serializer import get_default_model_params_setting
from models_provider.tools import cache_base_model_list, get_cached_base_model_list
from models_provider.tools import cache_base_model_list, get_cached_base_model_list, restore_model_credential
from rest_framework.request import Request
from rest_framework.views import APIView

Expand Down Expand Up @@ -182,6 +182,7 @@ def post(self, request: Request):
data = request.data or {}
provider = data.get("provider")
model_type = data.get("model_type")
model_id = data.get("model_id")
api_key = data.get("api_key")
api_base = data.get("api_base")
credential = data.get("credential")
Expand All @@ -194,6 +195,11 @@ def post(self, request: Request):
if api_base and not credential.get("api_base"):
credential["api_base"] = api_base
_validate_model_type(provider_handler, model_type)
credential = restore_model_credential(provider, model_type, model_id, credential, provider_handler)
if credential.get("api_key"):
api_key = credential["api_key"]
if credential.get("api_base"):
api_base = credential["api_base"]
_validate_required_credential(provider_handler, model_type, credential)

if not (api_key or credential):
Expand Down
2 changes: 2 additions & 0 deletions ui/src/api/API_README.md
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,8 @@ Action、Drawer 或 Dialog。复用方直接使用 `typeof XxxApi` 约束完整

`model-provider.ts` 的 `getProviderList(query?)` 统一查询 `GET /provider`;不传参数获取全部供应商,
传入 `{ model_type }` 筛选支持指定模型类型的供应商,不单独封装按类型查询方法。
`getBaseModelList` 携带凭证时通过 POST 请求 `/provider/model_list`;编辑场景传 `modelId`,
由后端使用已保存模型的真实凭证替换表单中未改动的脱敏字段。

`workspace/model.ts` 的 `getModelListWithShared(query)` 请求
`/workspace/<workspaceId>/model_list`,支持 `name`、`model_type`、`model_name` 筛选。
Expand Down
10 changes: 3 additions & 7 deletions ui/src/api/admin/model-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,14 @@ const getModelTypeList = (provider: string) => {
}

/** 获取供应商指定类型下的基础模型,可携带 search 远程筛选;提供凭证时后端实时查询官方模型列表。 */
const getBaseModelList = (provider: string, modelType: string, search?: string, credential?: Record<string, unknown>) => {
const getBaseModelList = (provider: string, modelType: string, search?: string, credential?: Record<string, unknown>, modelId?: string) => {
// 携带凭证时走 POST body,避免 api_key 泄露到 URL/访问日志。
if (credential && Object.keys(credential).length > 0) {
return post<Record<string, unknown>, BaseModelOption[]>(`${prefix}/model_list`, {
model_type: modelType,
provider,
search,
model_id: modelId,
...credential,
credential,
})
Expand All @@ -39,12 +40,7 @@ const getBaseModelList = (provider: string, modelType: string, search?: string,
}

/** 按「url + key」读取后端缓存的基础模型列表,未命中返回空数组;编辑时传 modelId,由后端用真实凭证取缓存。 */
const getBaseModelListCache = (
provider: string,
modelType: string,
credential: Record<string, unknown>,
modelId?: string,
) => {
const getBaseModelListCache = (provider: string, modelType: string, credential: Record<string, unknown>, modelId?: string) => {
return post<Record<string, unknown>, BaseModelOption[]>(`${prefix}/model_list_cache`, {
model_type: modelType,
model_id: modelId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ async function fetchBaseModelOptions() {
applyBaseModelOptions(requestProvider, requestModelType, requestCredentialSnapshot, options)
MsgWarning(t('model.messages.baseModelsFallback'))
})
ProviderApi.getBaseModelList(requestProvider, requestModelType, undefined, modelForm.credential as Record<string, unknown>)
ProviderApi.getBaseModelList(requestProvider, requestModelType, undefined, modelForm.credential as Record<string, unknown>, currentModelId.value)
.then((options) => {
if (options?.length) {
if (applyBaseModelOptions(requestProvider, requestModelType, requestCredentialSnapshot, options)) {
Expand Down
34 changes: 34 additions & 0 deletions ui/tests/model-provider-model-list.test.mjs
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)
})

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can only see the test helper, not model-provider.ts, so a few points depend on that file’s import/export style. Main observations:

Potential functional issues

  1. The mocked require('./core/request') shape may not match the transpiled import.

    • The mock returns the request object directly:
      (id) => { ... return request }
    • That works only if the source uses a namespace/CommonJS-style import.
    • If model-provider.ts uses import request from './core/request', TypeScript with module: CommonJS and no esModuleInterop will emit request_1.default, so the mock should return { default: request } (or you should enable esModuleInterop).
    • If it uses a named import such as import { request } from './core/request', the mock should return { request }.
    • This is the most likely cause of a confusing test failure.
  2. requestPayload may be undefined.

    assert.equal(requestPayload.model_id, 'model-id')

    If post is never called, this throws TypeError instead of giving a clear assertion failure. Add:

    assert.ok(requestPayload, 'expected request.post to be called')
  3. credential can produce a false-positive deep-equal assertion.

    const credential = { api_key: '[API_KEY]' }
    ...
    assert.deepEqual(requestPayload.credential, credential)

    Since both references point to the same object, if the code mutates credential, the assertion still passes. Use a separate expected object or freeze the credential:

    const credential = Object.freeze({ api_key: '[API_KEY]' })
    ...
    assert.deepEqual(requestPayload.credential, { api_key: '[API_KEY]' })
  4. The test does not verify the request path or call count.
    It captures only the payload. A wrong post URL would still pass. Consider capturing both:

    let requestPath
    let requestPayload
    post: (path, payload) => {
      requestPath = path
      requestPayload = payload
      return Promise.resolve([])
    }

    Then assert requestPath and that post was called once.

  5. The custom require only supports ./core/request.
    Any other runtime import, including Node built-ins, will fail. That is acceptable for a very isolated test, but it is brittle. If the source grows, the mock must be updated.

  6. compileFunction lacks module, __dirname, __filename, and a filename option.
    If the transpiled source references module.exports, __dirname, etc., the test will fail. At minimum, add a filename for better stack traces:

    compileFunction(outputText, ['require', 'exports'], {
      filename: 'model-provider.ts',
    })
  7. Transpile diagnostics are ignored.
    ts.transpileModule can return diagnostics. You may want to assert none exist, or the test can fail later with a less clear error.

Optimization / robustness suggestions

  • Cache the transpiled module if more tests are added; do not read and transpile the source repeatedly.
  • Ensure the relative path ../src/api/admin/model-provider.ts is correct for the actual test file location.
  • Prefer the project’s existing TypeScript test runner/build setup over runtime transpileModule + vm.compileFunction if available; this custom loader is fragile.
  • Consider asserting that getBaseModelList does not mutate the passed credential, especially if credentials are sensitive.
  • The Chinese test name is not a problem, but using English may improve consistency if the rest of the suite is English.

Overall: no security issue in this test code, but the module mock shape and same-reference credential assertion are the main correctness risks.

Loading