Skip to content

refactor: enhance getBaseModelList to include model_id for credential restoration and add corresponding tests - #8289

Merged
wxg0103 merged 1 commit into
v3from
pr@v3@refactor_model_list
Dec 3, 2026
Merged

wxg0103 merged 1 commit into
v3from
pr@v3@refactor_model_list

Conversation

@shaohuzhang1

Copy link
Copy Markdown
Contributor

refactor: enhance getBaseModelList to include model_id for credential restoration and add corresponding tests

@wxg0103
wxg0103 merged commit b5431a7 into v3 Dec 3, 2026
3 of 4 checks passed
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.

@wxg0103
wxg0103 deleted the pr@v3@refactor_model_list branch December 3, 2026 10:06

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.


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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants