Skip to content

fix: When other users download the public model, they cannot obtain the download data#2785

Merged
shaohuzhang1 merged 1 commit intomainfrom
pr@main@fix_model_meta
Apr 2, 2025
Merged

fix: When other users download the public model, they cannot obtain the download data#2785
shaohuzhang1 merged 1 commit intomainfrom
pr@main@fix_model_meta

Conversation

@shaohuzhang1
Copy link
Copy Markdown
Contributor

fix: When other users download the public model, they cannot obtain the download data

@f2c-ci-robot
Copy link
Copy Markdown

f2c-ci-robot bot commented Apr 2, 2025

Adding the "do-not-merge/release-note-label-needed" label because no release-note block was detected, please follow our release note process to remove it.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes/test-infra repository.

@f2c-ci-robot
Copy link
Copy Markdown

f2c-ci-robot bot commented Apr 2, 2025

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@shaohuzhang1 shaohuzhang1 merged commit ac5a9d0 into main Apr 2, 2025
4 checks passed
@shaohuzhang1 shaohuzhang1 deleted the pr@main@fix_model_meta branch April 2, 2025 10:29
raise Exception(_('No permission to use this model') + f"{model.name}")
model = QuerySet(Model).get(id=self.data.get('id'), user_id=self.data.get('user_id'))
return {'id': str(model.id), 'provider': model.provider, 'name': model.name, 'model_type': model.model_type,
'model_name': model.model_name,
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 provided code snippet has several issues and opportunities for improvement:

  1. Redundancy: The one_meta method calls self.is_valid() multiple times. This can lead to unnecessary validation checks during each call.
  2. Security Risk: If with_valid=False, there's no safety margin against unauthorized access since the data is directly retrieved from self.data.
  3. Duplicate Code: The if model_permission_type... logic is duplicated at two different points (both checking for existence and permissions).
  4. Error Handling: The error messages are missing when raising exceptions, which could make debugging difficult.
  5. Code Duplication: The retrieval of the model after checking its validity should be moved to a more reusable function.

Here’s a revised version with improvements:

from django.core.exceptions import ObjectDoesNotExist
from .exceptions import AppApiException

class OneMixin:
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def one_meta(self, with_valid=False):
        if with_valid:
            self.check_validity(raise_exception=True)
            
            # Ensure that the model exists first
            try:
                model = Model.objects.filter(id=self.data.get("id")).get()
            except ObjectDoesNotExist:
                raise AppApiException(500, _('Model does not exist'))
                
            # Check permission type
            if model.permission_type == 'PRIVATE':
                current_user_id = str(get_current_user_id())  # Assuming get_current_user_id() returns the authenticated user ID
                if current_user_id != str(model.user_id):
                    raise Exception(_('No permission to use this model') + f" {model.name}")
        
        return self.get_model()

    def check_validity(self, raise_exception=False):
        # Implement your validation logic here
        pass

    def get_model(self):
        try:
            model = Model.objects.get(
                id=int(self.data.get('id')), 
                user_id=get_current_user_id())
        except IntegrityError as e:
            raise AppApiException(500, _('Database integrity error')) from e
        except ValueError as e:
            raise AppApiException(400, _('Invalid input')) from e
        else:
            return {'id': str(model.id), 'provider': model.provider, 'name': model.name,
                        'model_type': model.model_type, 'model_name': model.model_name}

Key Improvements:

  • Simplified Validation Logic: Removed redundant is_valid() calls by delegating validation to a separate check_validity method.
  • Check for Existence Early: Ensured that the model exists before proceeding with the permission check.
  • Reused Functionality: Moved the duplicate code around the model fetching process into the get_model method for better readability and maintainability.
  • Added Error Messages: Included detailed error messages in exception instances where necessary.
  • User Authentication: Used a placeholder function get_current_user_id() assuming it retrieves the currently authenticated user's ID. You need to replace this with an actual implementation based on your authentication system.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant