Skip to content

Conversation

@GautierDele
Copy link
Member

@GautierDele GautierDele commented Aug 2, 2025

closes #181

Summary by CodeRabbit

  • Tests

    • Added new tests to verify that batch operations (delete, restore, force delete) fail if any model in the batch is unauthorized, ensuring no changes are made when authorization is denied.
    • Introduced a custom policy for fine-grained authorization in tests.
  • Refactor

    • Improved the handling of batch operations by separating authorization checks from mutation actions for more consistent and predictable behavior.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 2, 2025

Walkthrough

The changes separate authorization checks from mutation operations (destroy, restore, force delete) in batch model operations, ensuring all models are authorized before any mutation occurs. New tests verify that if any model in a batch is unauthorized, the operation is denied for all. A custom policy class is introduced to facilitate fine-grained authorization testing.

Changes

Cohort / File(s) Change Summary
Batch Operation Logic Refactor
src/Concerns/PerformsRestOperations.php
Refactored destroy, restore, and forceDelete methods to first check authorization for all models before performing actions.
Batch Authorization Tests
tests/Feature/Controllers/DeleteOperationsTest.php,
tests/Feature/Controllers/ForceDeleteOperationsTest.php,
tests/Feature/Controllers/RestoreOperationsTest.php
Added tests to verify that batch operations are denied if any model is unauthorized, ensuring no partial mutations occur.
Custom Policy for Model-specific Authorization
tests/Support/Policies/RedPolicyButForModel.php
Introduced a policy class allowing authorization for only a specific model instance, supporting precise test scenarios.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Controller
    participant Authorization
    participant Model

    Client->>Controller: Batch mutation request (delete/restore/forceDelete)
    Controller->>Authorization: Check authorization for all models
    Authorization-->>Controller: Authorization result (all or any unauthorized)
    alt All authorized
        Controller->>Model: Perform mutation on all models
        Model-->>Controller: Mutation results
        Controller-->>Client: Success response
    else Any unauthorized
        Controller-->>Client: 403 Forbidden, no mutations performed
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Assessment against linked issues

Objective Addressed Explanation
Prevent partial deletion: No models should be deleted if any in the batch is unauthorized (#181)
Ensure batch operations (delete/restore/forceDelete) are atomic with respect to authorization (#181)
Add tests to verify batch authorization behavior for deletion, restoration, and force deletion (#181)

Poem

A batch of models, lined in a row,
The rabbit checks if all can go.
If one says "no," then none shall leave—
Atomic rules, so none will grieve.
With policies set and tests in tow,
This patch ensures a fairer flow!
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between aab3ab5 and c55b75e.

📒 Files selected for processing (5)
  • src/Concerns/PerformsRestOperations.php (3 hunks)
  • tests/Feature/Controllers/DeleteOperationsTest.php (2 hunks)
  • tests/Feature/Controllers/ForceDeleteOperationsTest.php (2 hunks)
  • tests/Feature/Controllers/RestoreOperationsTest.php (2 hunks)
  • tests/Support/Policies/RedPolicyButForModel.php (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: in laravel rest api controller generation tests, the resource class assertions are expected to be di...
Learnt from: GautierDele
PR: Lomkit/laravel-rest-api#173
File: tests/Feature/Commands/ControllerMakeCommandTest.php:19-0
Timestamp: 2025-06-02T17:45:40.477Z
Learning: In Laravel REST API controller generation tests, the resource class assertions are expected to be different:
- Without --resource option: expects `\Resource::class` (generic/default)
- With --resource option: expects fully qualified class name like `\App\Rest\Resources\TestResource::class`
This reflects the actual behavior of the command generator and should not be flagged as inconsistent.

Applied to files:

  • tests/Feature/Controllers/DeleteOperationsTest.php
  • tests/Feature/Controllers/ForceDeleteOperationsTest.php
  • tests/Feature/Controllers/RestoreOperationsTest.php
🧬 Code Graph Analysis (1)
tests/Feature/Controllers/DeleteOperationsTest.php (2)
tests/Support/Policies/RedPolicyButForModel.php (3)
  • RedPolicyButForModel (8-107)
  • forModel (14-17)
  • delete (77-80)
tests/Support/Database/Factories/ModelFactory.php (1)
  • ModelFactory (8-29)
🪛 PHPMD (2.15.0)
tests/Support/Policies/RedPolicyButForModel.php

26-26: Avoid unused parameters such as '$user'. (Unused Code Rules)

(UnusedFormalParameter)


39-39: Avoid unused parameters such as '$user'. (Unused Code Rules)

(UnusedFormalParameter)


51-51: Avoid unused parameters such as '$user'. (Unused Code Rules)

(UnusedFormalParameter)


64-64: Avoid unused parameters such as '$user'. (Unused Code Rules)

(UnusedFormalParameter)


77-77: Avoid unused parameters such as '$user'. (Unused Code Rules)

(UnusedFormalParameter)


90-90: Avoid unused parameters such as '$user'. (Unused Code Rules)

(UnusedFormalParameter)


103-103: Avoid unused parameters such as '$user'. (Unused Code Rules)

(UnusedFormalParameter)

🔇 Additional comments (10)
tests/Support/Policies/RedPolicyButForModel.php (1)

1-107: Well-designed test policy for authorization testing.

This policy class effectively implements a pattern where only one specific model instance (set via forModel()) is authorized for operations, while all others are denied. This is perfect for testing mixed authorization scenarios in batch operations.

The static analysis warnings about unused $user parameters are acceptable in test policies where user-specific logic isn't required.

src/Concerns/PerformsRestOperations.php (3)

141-151: Excellent separation of authorization and mutation logic.

The change separates authorization checks from the actual deletion operations, ensuring that all models are authorized before any deletions occur. This prevents the partial deletion issue described in the linked issue where some models would be deleted before authorization failed on subsequent models.


180-190: Consistent pattern applied to restore operations.

The same authorization-before-mutation pattern is correctly applied to restore operations, maintaining consistency across all destructive operations.


220-230: Pattern correctly implemented for force delete operations.

The authorization separation is consistently applied to force delete operations as well, completing the fix for all destructive operations.

tests/Feature/Controllers/DeleteOperationsTest.php (2)

13-13: Good import addition for the new policy.


37-57: Excellent test for atomic batch delete behavior.

This test perfectly validates the fix for issue #181. It creates a mixed authorization scenario (one authorized model, one not) and verifies that:

  1. The entire operation fails with 403 status
  2. Neither model is deleted from the database

This ensures the authorization separation prevents partial deletions.

tests/Feature/Controllers/ForceDeleteOperationsTest.php (2)

11-11: Good import addition for the new policy.


34-54: Comprehensive test for atomic force delete behavior.

This test validates the same atomic behavior for force delete operations, ensuring that mixed authorization scenarios result in complete operation failure rather than partial force deletions. The use of assertSoftDeleted() correctly verifies that both models remain in their soft-deleted state.

tests/Feature/Controllers/RestoreOperationsTest.php (2)

11-11: Good import addition for the new policy.


34-60: Thorough test for atomic restore behavior.

This test completes the coverage by validating atomic behavior for restore operations. The test correctly verifies that both models remain soft-deleted (using deleted_at field checks) when the batch operation fails due to mixed authorization.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/restore-delete-operations

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@GautierDele GautierDele merged commit acf8050 into main Aug 2, 2025
21 checks passed
@GautierDele GautierDele deleted the fix/restore-delete-operations branch August 2, 2025 19:07
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.

Error on multiple deletion when permission does not allow one of it

3 participants