Repository navigation
fix: enhance validation logic to include workspace_id in model checks - #7855
Merged
Merged
Conversation
shaohuzhang1
commented
Nov 12, 2026
| self.is_valid(raise_exception=True, workspace_id=workspace_id) | ||
| except AppApiException as e: | ||
| if e.code == ValidCode.model_not_fount: | ||
| status = Status.DOWNLOAD |
Contributor
Author
There was a problem hiding this comment.
Code Review & Analysis
Here is a concise analysis of the provided code diff, highlighting irregularities, potential issues, and optimization suggestions.
1. Irregularity / Bug: String "None" used as default
if workspace_id is None:
workspace_id = self.data.get("workspace_id", "None")- Issue: Using the string
"None"as a default value forworkspace_idis dangerous and likely incorrect. Ifworkspace_idis meant to beNULLor an empty string in the database, storing or filtering by the literal string"None"will cause logic errors. - Fix: Use
None(Python object) or""(empty string), depending on DB schema. Also,getkey should matchself.fields. Useself.data.get("workspace_id") or None.
2. API Contract Violation: Overriding is_valid() signature
- Issue: Django REST Framework’s
Serializer.is_valid()does not accept aworkspace_idargument. Adding it here breaks polymorphism and can cause unexpected behavior if the serializer is used generically (e.g., by DRF views). - Suggestion: Remove
workspace_idfromis_valid(). Instead, ensureworkspace_idis always available inself.initial_dataor passed explicitly during validation via context (self.context.get('workspace_id')). Alternatively, perform the duplicate check directly invalidate()orcreate().
3. Security & Logic Concern: Trusting User Input for Duplicate Check
provider = self.data.get("provider")
# ... later ...
QuerySet(Model).filter(name=self.data.get("name"), workspace_id=workspace_id).exists()- Issue:
- If
workspace_idfalls back to user-provided data, a user might bypass constraints by providing a specific ID. - If
workspace_idcomes from request context (e.g., authenticated user’s workspace), it should not be optional in the serializer field definition unless you intend to allow cross-workspace operations (which is rare for multi-tenancy).
- If
- Suggestion: Ensure
workspace_idis derived from authentication context, not just client input. If it must come from input, validate its integrity before DB queries.
4. Performance Optimization: Redundant .get() calls
- Current: Repeatedly calls
self.data.get("name"),self.data.get("provider"), etc. - Optimization: Extract values early after validation.
name = self.data.get("name")
provider = self.data.get("provider")
# Use these variables in subsequent checks5. Error Handling: Exception swallowing risk
In insert():
try:
self.is_valid(raise_exception=True, workspace_id=workspace_id)
except AppApiException as e:
if e.code == ValidCode.model_not_fount: # Typo? "found" not "fount"
status = Status.DOWNLOAD- Typo:
model_not_fount→ likelymodel_not_found. - Logic: Catching only one exception type is fine, but ensure other
AppApiExceptions are re-raised or handled appropriately. Otherwise, invalid input (e.g., missing provider) will silently proceed with partial validation failure if not caught.
6. QuerySet Optimization: Avoid .exists() inside loops or heavy conditions
- The duplicate check is outside the loop, so it’s acceptable. However, if this is called per-model in a batch, consider using bulk queries.
✅ Recommended Refactored Approach
Remove workspace_id from is_valid() and rely on context:
class Create(serializers.Serializer):
credential = serializers.DictField(required=True, label=_("certification information"))
name = serializers.CharField(required=True, max_length=256) # Add explicit fields!
provider = serializers.CharField(required=True)
workspace_id = serializers.CharField(required=False, label=_("workspace id"), max_length=128)
def validate(self, attrs):
"""
Custom validation using DRF's built-in validator hook.
"""
name = attrs["name"]
provider = attrs["provider"]
# Prefer workspace_id from context (set in view), fallback to input if needed
workspace_id = self.context.get("workspace_id") or attrs.get("workspace_id")
try:
provider_handler = ModelProvideConstants[provider]
except KeyError:
raise valid.serializers.ValidationError(_("Unsupported provider."))
# Example additional validations...
for index, item in enumerate(attrs.get("fields", [])):
if "field" not in item or "default_value" not in item:
raise valid.serializers.ValidationError(
f"The field and default_value fields are required for the {index + 1}th item"
)
# Duplicate check
if QuerySet(Model).filter(name=name, workspace_id=workspace_id).exists():
raise valid.serializers.ValidationError(
_("Base model 【{model_name}】 already exists.").format(model_name=name)
)
return attrs
def create(self, validated_data):
# Perform insert logic here
passIn the view:
serializer = Create(data=request.data)
serializer.validated_data # Triggers is_valid/validate correctly
model_id = serializer.insert(workspace_id=request.user.workspace_id)Note: Do not override
is_valid()unless absolutely necessary. Use DRF patterns likevalidate()for field validation andcreate()for persistence logic.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
fix: enhance validation logic to include workspace_id in model checks