Repository navigation
refactor: add client parameter handling to prevent sending sensitive config in request body #7875
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 |
|---|---|---|
|
|
@@ -70,7 +70,16 @@ def is_valid( | |
| model.invoke([HumanMessage(content="1")]) | ||
| except Exception as e: | ||
| maxkb_logger.error(f"Exception: {e}", exc_info=True) | ||
| raise e | ||
| if isinstance(e, AppApiException): | ||
| raise e | ||
| if raise_exception: | ||
| raise AppApiException( | ||
| ValidCode.valid_error.value, | ||
| gettext("Verification failed, please check whether the parameters are correct: {error}").format( | ||
| error=str(e) | ||
| ), | ||
| ) | ||
| return False | ||
| return True | ||
|
|
||
| def encryption_dict(self, model_info: Dict[str, object]): | ||
|
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 for the code: Potential Issues:
Optimization Suggestions:
Summary: Main fix is adding |
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| # coding=utf-8 | ||
| from unittest.mock import MagicMock | ||
|
|
||
| from django.test import SimpleTestCase | ||
| from langchain_core.messages import HumanMessage | ||
|
|
||
| from common.exception.app_exception import AppApiException | ||
| from models_provider.impl.qianfan_model_provider.credential.llm import QianfanLLMModelCredential | ||
| from models_provider.impl.qianfan_model_provider.model.image import QianfanVisionModel | ||
| from models_provider.impl.qianfan_model_provider.model.llm import QianfanChatModel | ||
|
|
||
| CRED = {"api_base": "https://qianfan.baidubce.com/v2", "api_key": "sk-test"} | ||
|
|
||
|
|
||
| class QianfanModelConstructionTests(SimpleTestCase): | ||
| def test_client_params_are_not_sent_in_request_body(self): | ||
| for model_class in (QianfanChatModel, QianfanVisionModel): | ||
| with self.subTest(model=model_class.__name__): | ||
| model = model_class.new_instance( | ||
| "LLM", | ||
| "ernie-5.1", | ||
| CRED, | ||
| temperature=0.95, | ||
| max_tokens=1, | ||
| request_timeout=5.0, | ||
| max_retries=0, | ||
| ) | ||
|
|
||
| # 客户端配置项应真正作用于 OpenAI 客户端 | ||
| self.assertEqual(5.0, model.request_timeout) | ||
| self.assertEqual(0, model.max_retries) | ||
|
|
||
| # 且不应混入接口请求体 | ||
| self.assertNotIn("request_timeout", model.extra_body) | ||
| self.assertNotIn("max_retries", model.extra_body) | ||
|
|
||
| payload = model._get_request_payload([HumanMessage(content="1")]) | ||
| self.assertNotIn("request_timeout", payload) | ||
| self.assertNotIn("max_retries", payload) | ||
|
|
||
|
|
||
| class QianfanLLMCredentialTests(SimpleTestCase): | ||
| def _mock_provider(self, model): | ||
| provider = MagicMock() | ||
| provider.get_model.return_value = model | ||
| return provider | ||
|
|
||
| def test_validation_propagates_provider_error_message(self): | ||
| model = MagicMock() | ||
| model.invoke.side_effect = RuntimeError("Error code: 500 - {'error': {'code': 'internal_error'}}") | ||
|
|
||
| credential = QianfanLLMModelCredential() | ||
| with self.assertRaises(AppApiException) as raised: | ||
| credential.is_valid( | ||
| "LLM", | ||
| "ernie-5.1", | ||
| CRED, | ||
| {"temperature": 0.95}, | ||
| self._mock_provider(model), | ||
| raise_exception=True, | ||
| ) | ||
|
|
||
| self.assertIn("Error code: 500 - {'error': {'code': 'internal_error'}}", raised.exception.message) | ||
|
|
||
| def test_validation_returns_false_when_not_raising(self): | ||
| model = MagicMock() | ||
| model.invoke.side_effect = RuntimeError("boom") | ||
|
|
||
| credential = QianfanLLMModelCredential() | ||
| result = credential.is_valid( | ||
| "LLM", | ||
| "ernie-5.1", | ||
| CRED, | ||
| {"temperature": 0.95}, | ||
| self._mock_provider(model), | ||
| raise_exception=False, | ||
| ) | ||
|
|
||
| self.assertFalse(result) | ||
|
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's my review of the code: Irregularities / Potential Issues
Optimization Suggestions
Overall the tests are reasonable and focused; main gaps are the missing success case and over-specific error-message assertions. |
||
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.
Review of the Diff
1.
__contains→__icontains(lines ~245, ~400, ~533)Good change.
icontainson large tables can be slower and may bypass certain DB indexes (e.g., PostgreSQLLIKEindex only helps withtext_pattern_ops/pg_trgm). If these querysets are large or hit hot paths, consider a trigram index or full-text search.2. Removing redundant f-string (
f'attachment; filename="data.xlsx"'→ plain string)Correct. There were no interpolation placeholders, so the
fprefix was dead code. No behavior change.3.
is_resource_filter = Falseadded afterworkspace_managebranch (line ~409)Potentially behavior-changing — verify intended semantics.
Compare with the sibling method around line ~533:
The patched block now also sets
is_resource_filter = Falsefor the workspace-manager path. Two concerns:is_resource_filtercontrols whether further permission filtering is applied downstream, setting it toFalsemeans workspace managers now skip that extra filtering. That is likely the intent (managers shouldn't be restricted by per-resource permissions), but it should be confirmed against tests.is_extends_workspace_manage) missing the same treatment.is_resource_filteris ambiguous. Consider something likeskip_resource_permission_filter.4. Other observations (not in diff but visible)
Content-Type mismatch:
content_type="application/vnd.ms-excel"is the MIME type for.xls, but the file is written asdata.xlsx. For modern Excel use:Also add UTF-8 filename encoding via
filename*=UTF-8''...if non-ASCII names may be used later.Duplication: The
exportmethod is copy-pasted three times. Extract a shared helper like_build_excel_response(rows).QuerySet(Application)— assuming this is a custom wrapper; fine, just noting.5. Minor
workbook.save(response)is unchanged — fine.get_queryset, sinceicontainsrelies on DB collation and can differ across backends (SQLite vs MySQL vs Postgres).Summary
icontainsfprefixis_resource_filter = False