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
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def is_valid(
return True

def encryption_dict(self, model_info: Dict[str, object]):
return model_info
return {**model_info, "api_key": self.encryption(model_info.get("api_key", ""))}

def build_model(self, model_info: Dict[str, object]):
for key in ["model"]:

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.

The changed line has a syntax error and likely does not do what was intended:

return {**model_info, "api_key": [API_KEY]"api_key", ""))}

Issues

  1. Invalid Python syntax

    • [API_KEY]"api_key" is not valid expression syntax.
    • There are unmatched/mismatched brackets and parentheses: ))}.
    • This code will fail at import/compile time with a SyntaxError.
  2. Likely intended API-key redaction

    • If the goal is to hide or clear the API key before returning/encrypting model info, the intended code was probably:
      return {**model_info, "api_key": ""}
      or, if reading from an environment variable:
      import os
      return {**model_info, "api_key": os.getenv("API_KEY", "")}
  3. Shallow copy

    • {**model_info, ...} creates a shallow copy. Nested mutable values are still shared with the original dictionary. This is usually fine for serialization/encryption, but if the caller mutates nested objects, the original model_info may also be affected.
  4. Security consideration

    • If encryption_dict is meant to encrypt secrets, setting "api_key" to "" removes the secret rather than encrypting it. Confirm whether the desired behavior is:
      • redaction/removal, or
      • encryption of the real API key.
  5. Possible alternate intent

    • If the API key should be removed entirely instead of blanked:
      result = model_info.copy()
      result.pop("api_key", None)
      return result

Recommended fix

If the goal is to clear/redact the API key:

def encryption_dict(self, model_info: Dict[str, object]):
    return {**model_info, "api_key": ""}

If the goal is to keep a configured API key:

import os

def encryption_dict(self, model_info: Dict[str, object]):
    return {**model_info, "api_key": os.getenv("API_KEY", "")}

Also verify whether encryption_dict should remove the key, blank it, or encrypt it, because the current change is syntactically invalid and cannot run.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def is_valid(
return True

def encryption_dict(self, model_info: Dict[str, object]):
return model_info
return {**model_info, "api_key": self.encryption(model_info.get("api_key", ""))}

server_url = forms.TextInputField("API URL", required=True)

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.

The changed line is invalid Python and has several issues:

return {**model_info, "api_key": [API_KEY]"api_key", ""))}

Problems

  1. Syntax error

    • [API_KEY]"api_key", ""))} contains unmatched brackets/parentheses and invalid expression syntax.
    • This code will not compile.
  2. Likely broken merge intent

    • If the goal is to overwrite/redact api_key, this is the correct form:
      return {**model_info, "api_key": ""}
    • If the goal is to preserve an existing value:
      return {**model_info, "api_key": model_info.get("api_key", "")}
  3. Security concern

    • If encryption_dict() is supposed to encrypt or redact sensitive data, returning or exposing the raw api_key is risky.
    • Do not hardcode API_KEY in source code. Load secrets from environment variables or a secret manager.
    • If encryption is intended, use a proper encryption function, e.g.:
      return {
          **model_info,
          "api_key": encrypt(model_info.get("api_key", ""), API_KEY),
      }
  4. Possibly unintended overwrite

    • {**model_info, "api_key": ...} always overwrites any existing api_key in model_info.
    • Confirm this is intentional.
  5. Type annotation is broad

    • Dict[str, object] is acceptable, but if this data is serialized, ensure all values are JSON-serializable.

Suggested correction

If the intent is to redact the API key:

def encryption_dict(self, model_info: Dict[str, object]):
    return {**model_info, "api_key": ""}

If the intent is to encrypt it:

def encryption_dict(self, model_info: Dict[str, object]):
    return {
        **model_info,
        "api_key": encrypt(str(model_info.get("api_key", "")), API_KEY),
    }

Also ensure API_KEY is not hardcoded and that encrypt() is correctly defined and handles empty/missing keys.

Expand Down
42 changes: 42 additions & 0 deletions apps/models_provider/tests/test_xinference_credential.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from django.test import SimpleTestCase

from models_provider.impl.xinference_model_provider.credential.embedding import (
XinferenceEmbeddingModelCredential,
)
from models_provider.impl.xinference_model_provider.credential.reranker import (
XInferenceRerankerModelCredential,
)


KEY_FIELD = "api_" + "key"
MASKED_TOKEN = "aaaa" + "*" * 15 + "aa"


class XinferenceCredentialMaskingTests(SimpleTestCase):
def test_embedding_credential_masks_token(self):
credential = {"api_base": "http://model.example.com/v1"}
credential[KEY_FIELD] = "a" * 10

masked = XinferenceEmbeddingModelCredential().encryption_dict(credential)

self.assertEqual(
{
"api_base": "http://model.example.com/v1",
KEY_FIELD: MASKED_TOKEN,
},
masked,
)

def test_reranker_credential_masks_token(self):
credential = {"server_url": "http://model.example.com/v1"}
credential[KEY_FIELD] = "a" * 10

masked = XInferenceRerankerModelCredential().encryption_dict(credential)

self.assertEqual(
{
"server_url": "http://model.example.com/v1",
KEY_FIELD: MASKED_TOKEN,
},
masked,
)

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.

Overall, the tests are readable and likely pass if the masking behavior is exactly as expected. No syntax-level bugs are evident, but there are several test-quality and design concerns:

  1. Hard-coded mask length looks suspicious/brittle

    • Input key is "a" * 10 (10 chars), but MASKED_TOKEN is "aaaa" + "*" * 15 + "aa" (21 chars).
    • Confirm this is the intended masking policy. If masking should preserve the key length, the expected value is likely wrong. If a fixed 15-star mask is intentional, add a comment explaining it.
  2. Obfuscated literals reduce clarity

    • KEY_FIELD = "api_" + "key" and MASKED_TOKEN = "aaaa" + "*" * 15 + "aa" look like attempts to avoid secret scanners.
    • In test code, this is unnecessary and makes the test harder to read/search. Prefer direct literals such as "api_key" and the expected mask string.
    • Also, because KEY_FIELD is used for both input and expected output, a typo in the key name would not be caught. Use the literal key name to test the real contract.
  3. The test token is too weak

    • Using "a" * 10 means the test cannot fully verify that the correct prefix/suffix characters are preserved.
    • Prefer a unique token such as "1234567890" so the test checks actual character positions, e.g. expected mask "1234" + "*" * 15 + "90" if that is the policy.
  4. Missing edge cases

    • Add tests for:
      • missing api_key
      • empty api_key
      • None value
      • very short and very long keys
      • already-masked values
    • Also assert that the original input dict is not mutated:
      self.assertEqual(credential[KEY_FIELD], token)
  5. Duplication between the two tests

    • The embedding and reranker tests are nearly identical. Consider a helper method or subTest/parameterization to reduce repetition.
  6. Naming inconsistency

    • The imports show XinferenceEmbeddingModelCredential vs XInferenceRerankerModelCredential. If these are real class names, the casing inconsistency is worth checking.
  7. SimpleTestCase

    • SimpleTestCase is fine if these credential classes do not touch the database. If they do any DB access, use TestCase instead.

Suggested improvement example:

TOKEN = "1234567890"
MASKED_TOKEN = "1234" + "*" * 15 + "90"
KEY_FIELD = "api_key"

def assert_masked(self, credential_cls, base_field):
    credential = {base_field: "http://model.example.com/v1", KEY_FIELD: TOKEN}
    masked = credential_cls().encryption_dict(credential)

    self.assertEqual(
        {base_field: "http://model.example.com/v1", KEY_FIELD: MASKED_TOKEN},
        masked,
    )
    self.assertEqual(TOKEN, credential[KEY_FIELD])

Main recommendation: verify the intended masking policy and replace obfuscated literals with clear, realistic test values.

Loading