Skip to content
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

[IMP] cetmix_tower_server: Access to server fields #182

Open
wants to merge 3 commits into
base: 14.0-dev
Choose a base branch
from

Conversation

GabbasovDinar
Copy link
Contributor

@GabbasovDinar GabbasovDinar commented Jan 14, 2025

Limit access to the following fields of the cx.tower.server ​model to Manager and Root:

  • OS
  • IP v4 Address
  • IP v6 Address
  • SSH username
  • SSH Port
  • SSS auth mode
  • SSH key
  • Use sudo

Task: 4116

Summary by CodeRabbit

  • Security Enhancements

    • Added group-based access control for server connection settings
    • Restricted sensitive server configuration fields to manager group
    • Made SSH password field optional
  • User Interface

    • Updated kanban and search views to reflect new access controls
    • Improved field visibility based on user roles
  • Documentation

    • Added note about user access levels in configuration guide
  • Testing

    • Enhanced test coverage for user access and command execution

Copy link

coderabbitai bot commented Jan 14, 2025

Walkthrough

The pull request introduces significant modifications to the Cetmix Tower Server module, focusing on enhancing access control for server connection settings. The changes primarily involve adding group-based restrictions to sensitive server configuration fields, ensuring that only users in the cetmix_tower_server.group_manager group can view and modify critical connection details such as IP addresses, SSH credentials, and authentication modes.

Changes

File Change Summary
cetmix_tower_server/models/cx_tower_server.py Added groups="cetmix_tower_server.group_manager" to multiple fields including IP addresses, SSH credentials, authentication mode, and OS selection
cetmix_tower_server/views/cx_tower_server_view.xml Created new kanban view with group restrictions and updated search view filters
cetmix_tower_server/readme/CONFIGURE.md Added note about field visibility based on user access levels
cetmix_tower_server/wizards/cx_tower_command_execute_wizard.py Added compute_sudo=True to rendered_code field
cetmix_tower_server/tests/test_command.py Added test case to verify user access rules for command execution

Possibly related PRs

Suggested labels

bot is merging ⏳, approved

Suggested reviewers

  • tendil

Finishing Touches

  • 📝 Generate Docstrings (Beta)

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (4)
cetmix_tower_server/models/cx_tower_server.py (2)

743-747: Ensure consistent use of sudo() throughout the method.

While adding sudo() for checking ssh_username and use_sudo attributes is good for security, consider applying it consistently to all attribute accesses in this method for better maintainability.

Consider applying this pattern:

-if self.sudo().ssh_username != "root" and self.sudo().use_sudo:
-    sudo = self.sudo().use_sudo
+self_sudo = self.sudo()
+if self_sudo.ssh_username != "root" and self_sudo.use_sudo:
+    sudo = self_sudo.use_sudo

-elif sudo and self.sudo().ssh_username == "root":
+elif sudo and self_sudo.ssh_username == "root":
    sudo = None

Line range hint 563-574: Enhance error handling in the _connect method.

While adding sudo() for server connection is good, consider improving the error handling to provide more specific error messages based on the type of connection failure (e.g., authentication failure, network unreachable, etc.).

Consider this approach:

 self = self.sudo()
 try:
     client = SSH(
         host=self.ip_v4_address or self.ip_v6_address,
         port=self.ssh_port,
         username=self.ssh_username,
         mode=self.ssh_auth_mode,
         password=self._get_password(),
         ssh_key=self._get_ssh_key(),
     )
 except Exception as e:
+    error_msg = str(e)
+    if "Authentication failed" in error_msg:
+        error_msg = _("SSH authentication failed. Please check your credentials.")
+    elif "Connection refused" in error_msg:
+        error_msg = _("Connection refused. Please check if the server is running and accessible.")
+    elif "Network is unreachable" in error_msg:
+        error_msg = _("Network is unreachable. Please check your network connection.")
     if raise_on_error:
-        raise ValidationError(_("SSH connection error %(err)s", err=e)) from e
+        raise ValidationError(_("SSH connection error: %(err)s", err=error_msg)) from e
     else:
-        return False, e
+        return False, error_msg
cetmix_tower_server/views/cx_tower_server_view.xml (2)

108-135: Consider removing redundant group restriction in view.

Since the fields (os_id, ip_v4_address, ip_v6_address) already have group restrictions defined at the model level, the groups_id field in the view might be unnecessary. The model-level restrictions will automatically handle the access control.

Consider this simplified approach:

 <record id="cx_tower_server_view_kanban_manager" model="ir.ui.view">
     <field name="name">cx.tower.server.view.kanban</field>
     <field name="model">cx.tower.server</field>
     <field
         name="inherit_id"
         ref="cetmix_tower_server.cx_tower_server_view_kanban"
     />
-    <field
-        name="groups_id"
-        eval="[(4, ref('cetmix_tower_server.group_manager'))]"
-    />
     <field name="arch" type="xml">
         <xpath expr="//div[hasclass('o_kanban_primary_right')]" position="inside">
             <!-- ... rest of the view definition ... -->
         </xpath>
     </field>
 </record>

Line range hint 375-399: Optimize group restrictions in search view.

The groups attribute on the os_id field is redundant as it's already restricted at the model level. However, the group restriction on the "Group By OS" filter is correct and necessary as it's a view-specific feature.

Consider this optimization:

-    <field name="os_id" groups="cetmix_tower_server.group_manager" />
+    <field name="os_id" />
     <field name="tag_ids" />
     <!-- ... other fields ... -->
     <filter
         string="OS"
         name="group_by_os"
         domain="[]"
         context="{'group_by': 'os_id'}"
         groups="cetmix_tower_server.group_manager"
     />
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b1e01f1 and 7e6dad2.

📒 Files selected for processing (2)
  • cetmix_tower_server/models/cx_tower_server.py (6 hunks)
  • cetmix_tower_server/views/cx_tower_server_view.xml (3 hunks)
🧰 Additional context used
📓 Learnings (1)
cetmix_tower_server/views/cx_tower_server_view.xml (1)
Learnt from: ivs-cetmix
PR: cetmix/cetmix-tower#147
File: cetmix_tower_server/views/cx_tower_file_view.xml:160-160
Timestamp: 2024-11-24T22:56:35.204Z
Learning: In Odoo, when groups are defined at the model level, it's unnecessary to specify them again in the view fields.
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test with OCB
🔇 Additional comments (1)
cetmix_tower_server/models/cx_tower_server.py (1)

Line range hint 282-340: Well-structured security enhancement for sensitive server fields!

The consistent application of group-based access control (groups="cetmix_tower_server.group_manager") to all sensitive server connection fields is a good security practice. This ensures that only users with appropriate permissions can access critical server details.

@GabbasovDinar GabbasovDinar force-pushed the 14.0-t4116-cetmix_tower_server-access branch from 7e6dad2 to 022d74c Compare January 14, 2025 10:22
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
cetmix_tower_server/views/cx_tower_server_view.xml (1)

375-375: Consider removing redundant group restrictions.

Based on previous feedback, when groups are defined at the model level, it's unnecessary to specify them again in the view fields.

-                <field name="os_id" groups="cetmix_tower_server.group_manager" />
+                <field name="os_id" />
-                        groups="cetmix_tower_server.group_manager"
+                        

Also applies to: 399-399

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7e6dad2 and 022d74c.

📒 Files selected for processing (3)
  • cetmix_tower_server/models/cx_tower_server.py (6 hunks)
  • cetmix_tower_server/readme/CONFIGURE.md (1 hunks)
  • cetmix_tower_server/views/cx_tower_server_view.xml (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • cetmix_tower_server/models/cx_tower_server.py
🧰 Additional context used
📓 Learnings (1)
cetmix_tower_server/views/cx_tower_server_view.xml (1)
Learnt from: ivs-cetmix
PR: cetmix/cetmix-tower#147
File: cetmix_tower_server/views/cx_tower_file_view.xml:160-160
Timestamp: 2024-11-24T22:56:35.204Z
Learning: In Odoo, when groups are defined at the model level, it's unnecessary to specify them again in the view fields.
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test with OCB
🔇 Additional comments (2)
cetmix_tower_server/views/cx_tower_server_view.xml (1)

108-135: LGTM! Well-structured view inheritance for manager-specific fields.

The implementation correctly extends the base kanban view while maintaining proper access control and visibility conditions.

cetmix_tower_server/readme/CONFIGURE.md (1)

43-44: LGTM! Clear documentation update.

The added note effectively communicates the access-level-based field visibility to users.

@GabbasovDinar GabbasovDinar force-pushed the 14.0-t4116-cetmix_tower_server-access branch from 022d74c to da74aec Compare January 14, 2025 10:28
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
cetmix_tower_server/views/cx_tower_server_view.xml (2)

108-135: Consider removing redundant field declarations.

Based on the retrieved learning from PR #147, since these fields (os_id, ip_v4_address, ip_v6_address) are already defined with group restrictions at the model level, it's unnecessary to create a separate inherited view just for managers. The base kanban view can directly use these fields, and Odoo will automatically handle the access control.

Consider removing this entire view and moving the field declarations to the base kanban view's content section. The model-level group restrictions will automatically apply.


375-375: Optimize group restrictions in search view.

  • The group restriction on the os_id field (line 375) is redundant if the field is already restricted at the model level.
  • However, the group restriction on the "Group By OS" filter (line 399) should be retained as it's a view-specific feature.

Remove the redundant group restriction from the os_id field while keeping it for the "Group By OS" filter:

-                <field name="os_id" groups="cetmix_tower_server.group_manager" />
+                <field name="os_id" />

Also applies to: 399-399

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 022d74c and da74aec.

📒 Files selected for processing (3)
  • cetmix_tower_server/models/cx_tower_server.py (6 hunks)
  • cetmix_tower_server/readme/CONFIGURE.md (1 hunks)
  • cetmix_tower_server/views/cx_tower_server_view.xml (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • cetmix_tower_server/readme/CONFIGURE.md
  • cetmix_tower_server/models/cx_tower_server.py
🧰 Additional context used
📓 Learnings (1)
cetmix_tower_server/views/cx_tower_server_view.xml (1)
Learnt from: ivs-cetmix
PR: cetmix/cetmix-tower#147
File: cetmix_tower_server/views/cx_tower_file_view.xml:160-160
Timestamp: 2024-11-24T22:56:35.204Z
Learning: In Odoo, when groups are defined at the model level, it's unnecessary to specify them again in the view fields.
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test with OCB

@GabbasovDinar GabbasovDinar force-pushed the 14.0-t4116-cetmix_tower_server-access branch from da74aec to d04cce2 Compare January 14, 2025 12:32
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
cetmix_tower_server/models/cx_tower_server.py (1)

563-563: Avoid Overwriting self with self.sudo()

Reassigning self with self.sudo() can lead to confusion and unintended side effects. It's clearer and safer to store the result in a new variable or use self.sudo() directly when accessing attributes.

Refactor the code to avoid reassigning self:

 def _connect(self, raise_on_error=True):
     self.ensure_one()
-    self = self.sudo()
     try:
+        sudo_self = self.sudo()
         client = SSH(
-            host=self.ip_v4_address or self.ip_v6_address,
-            port=self.ssh_port,
-            username=self.ssh_username,
-            mode=self.ssh_auth_mode,
-            password=self._get_password(),
-            ssh_key=self._get_ssh_key(),
+            host=sudo_self.ip_v4_address or sudo_self.ip_v6_address,
+            port=sudo_self.ssh_port,
+            username=sudo_self.ssh_username,
+            mode=sudo_self.ssh_auth_mode,
+            password=sudo_self._get_password(),
+            ssh_key=sudo_self._get_ssh_key(),
         )
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between da74aec and d04cce2.

📒 Files selected for processing (4)
  • cetmix_tower_server/models/cetmix_tower.py (1 hunks)
  • cetmix_tower_server/models/cx_tower_server.py (6 hunks)
  • cetmix_tower_server/readme/CONFIGURE.md (1 hunks)
  • cetmix_tower_server/views/cx_tower_server_view.xml (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • cetmix_tower_server/readme/CONFIGURE.md
  • cetmix_tower_server/views/cx_tower_server_view.xml
🧰 Additional context used
📓 Learnings (1)
cetmix_tower_server/models/cetmix_tower.py (1)
Learnt from: ivs-cetmix
PR: cetmix/cetmix-tower#174
File: cetmix_tower_server/models/cetmix_tower.py:130-132
Timestamp: 2025-01-06T12:28:58.379Z
Learning: SSH credentials (username, password, and/or key) are controlled at the server level, so an additional validation in the `server_check_ssh_connection` method is not needed.
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test with OCB
🔇 Additional comments (3)
cetmix_tower_server/models/cx_tower_server.py (2)

677-677: Ensure Elevated Access is Necessary

Using self.sudo() in get_variable_values suggests that elevated permissions are required. Confirm that this is necessary and that it doesn't unintentionally expose sensitive data to unauthorized users.

Please verify that self.sudo() is required here and consider potential security implications.


743-744: Consistent Use of Elevated Permissions

Accessing ssh_username and use_sudo with self.sudo() ensures that fields restricted by groups are accessible. Ensure that this pattern is used consistently where needed and that it complies with your security model.

Also applies to: 747-747

cetmix_tower_server/models/cetmix_tower.py (1)

134-136: Verify Necessity of Elevating server to sudo()

Adding server = server.sudo() elevates access rights to all fields of server. According to previous learnings, SSH credentials are managed at the server level, and additional validation might not be necessary.

Based on retrieved learnings:

Learning: SSH credentials (username, password, and/or key) are controlled at the server level, so an additional validation in the `server_check_ssh_connection` method is not needed.

Please verify if elevating server to sudo() is required in this context, and ensure it aligns with the application's security policies without introducing unintended access.

✅ Verification successful

The sudo() elevation is necessary and correctly implemented

The elevation is required to access sensitive SSH credentials (password, keys) which are protected fields. This follows the application's security model where sensitive fields require elevated access, as evidenced by similar patterns across the codebase for handling SSH credentials and secret values.

🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Get the complete file content
cat cetmix_tower_server/models/cetmix_tower.py

# Look for similar sudo() patterns
rg "sudo\(\)" -A 3 -B 3

# Look for field definitions that might be sensitive
ast-grep --pattern 'fields.$_ = fields.$_($$$)'

Length of output: 20443

Copy link
Contributor

@ivs-cetmix ivs-cetmix left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have changed the flow so need to update the test coverage accordingly.
Eg we need to ensure that user with group "Tower/User" can still run SSH commands with no issues.

cetmix_tower_server/views/cx_tower_server_view.xml Outdated Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
cetmix_tower_server/tests/test_command.py (1)

532-541: Enhance test coverage for SSH command execution.

The test case verifies that a user with "cetmix_tower_server.group_user" can execute SSH commands, but it could be more robust. Consider these improvements:

  1. Verify the command execution result
  2. Add assertions to validate successful execution
  3. Include error handling test cases
  4. Check the command output

Here's a suggested implementation:

         # Check that user with "cetmix_tower_server.group_user" can execute ssh command
         test_command.write(
             {
                 "code": "ls -l",
             }
         )
-        self.server_test_1.with_user(self.user_bob).execute_command(
+        result = self.server_test_1.with_user(self.user_bob).execute_command(
             test_command,
         )
+        self.assertEqual(result['status'], 0, "Command execution should succeed")
+        self.assertIsNotNone(result['response'], "Command should return a response")
+        self.assertIsNone(result['error'], "Command should not return an error")
+
+        # Test error handling
+        test_command.write({'code': 'invalid_command'})
+        result = self.server_test_1.with_user(self.user_bob).execute_command(
+            test_command,
+        )
+        self.assertNotEqual(result['status'], 0, "Invalid command should fail")
+        self.assertIsNotNone(result['error'], "Invalid command should return an error")
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d04cce2 and c428b9e.

📒 Files selected for processing (2)
  • cetmix_tower_server/tests/test_command.py (1 hunks)
  • cetmix_tower_server/views/cx_tower_server_view.xml (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • cetmix_tower_server/views/cx_tower_server_view.xml

Copy link
Contributor

@ivs-cetmix ivs-cetmix left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we need

@@ -529,6 +529,16 @@ def test_user_access_rule(self):
# Ensure that user can access the command
command_name = test_command_1_as_bob.name
self.assertEqual(command_name, "Test command", msg="Must return 'Test command'")
# Check that user with "cetmix_tower_server.group_user" can execute ssh command
test_command.write(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we need to update this method too. And add some read operations to ensure that they don't trigger any access issues.
However let's merge #181 first

@GabbasovDinar GabbasovDinar force-pushed the 14.0-t4116-cetmix_tower_server-access branch from c428b9e to 9246dcd Compare January 16, 2025 08:19
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🔭 Outside diff range comments (1)
cetmix_tower_server/wizards/cx_tower_command_execute_wizard.py (1)

Line range hint 171-186: Add sudo access control check in execute_command_on_server method.

While the method checks for manager group access for the path, it doesn't verify sudo access permissions before passing the sudo parameter to execute_command. This could potentially allow unauthorized users to execute commands with sudo privileges.

Consider adding a sudo access check:

    def execute_command_on_server(self):
        """Render selected command rendered using server method"""

        # Check if command is selected
        if not self.command_id:
            raise ValidationError(_("Please select a command to execute"))

+       # Check sudo access
+       if self.use_sudo and not self.env.user.has_group("cetmix_tower_server.group_manager"):
+           raise AccessError(_("You are not allowed to execute commands with sudo privileges"))

        # Generate custom label. Will be used later to locate the command log
        log_label = generate_random_id(4)
        path_value = (
            self.env.user.has_group("cetmix_tower_server.group_manager") and self.path
        )
🧹 Nitpick comments (3)
cetmix_tower_server/views/cx_tower_server_view.xml (1)

108-118: Remove redundant groups restriction and use unique view name.

Based on the model-level field restrictions, the groups_id field is redundant. Also, the view name should be unique to avoid confusion.

Apply this diff:

     <record id="cx_tower_server_view_kanban_manager" model="ir.ui.view">
-        <field name="name">cx.tower.server.view.kanban</field>
+        <field name="name">cx.tower.server.view.kanban.manager</field>
         <field name="model">cx.tower.server</field>
         <field
             name="inherit_id"
             ref="cetmix_tower_server.cx_tower_server_view_kanban"
         />
-        <field
-            name="groups_id"
-            eval="[(4, ref('cetmix_tower_server.group_manager'))]"
-        />
cetmix_tower_server/wizards/cx_tower_command_execute_wizard.py (2)

Line range hint 102-102: Remove TODO comment and clarify the single-server requirement.

The comment # TODO testing only!!! suggests temporary code. If this is a requirement for production, please remove the TODO comment and add a proper comment explaining why only the first server is used.


Line range hint 171-246: Consider extracting common security checks into a decorator.

The security checks for manager group access and sudo privileges are scattered across methods. Consider extracting these into a decorator for better maintainability and consistency.

Example implementation:

from functools import wraps

def require_manager_for_sudo(method):
    @wraps(method)
    def wrapper(self, *args, **kwargs):
        if self.use_sudo and not self.env.user.has_group("cetmix_tower_server.group_manager"):
            raise AccessError(_("You are not allowed to execute commands with sudo privileges"))
        return method(self, *args, **kwargs)
    return wrapper

# Usage:
@require_manager_for_sudo
def execute_command_on_server(self):
    # Method implementation
    pass
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c428b9e and 9246dcd.

📒 Files selected for processing (6)
  • cetmix_tower_server/models/cetmix_tower.py (1 hunks)
  • cetmix_tower_server/models/cx_tower_server.py (6 hunks)
  • cetmix_tower_server/readme/CONFIGURE.md (1 hunks)
  • cetmix_tower_server/tests/test_command.py (1 hunks)
  • cetmix_tower_server/views/cx_tower_server_view.xml (2 hunks)
  • cetmix_tower_server/wizards/cx_tower_command_execute_wizard.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • cetmix_tower_server/models/cetmix_tower.py
  • cetmix_tower_server/readme/CONFIGURE.md
  • cetmix_tower_server/tests/test_command.py
  • cetmix_tower_server/models/cx_tower_server.py
🧰 Additional context used
📓 Learnings (1)
cetmix_tower_server/views/cx_tower_server_view.xml (1)
Learnt from: ivs-cetmix
PR: cetmix/cetmix-tower#147
File: cetmix_tower_server/views/cx_tower_file_view.xml:160-160
Timestamp: 2024-11-24T22:56:35.204Z
Learning: In Odoo, when groups are defined at the model level, it's unnecessary to specify them again in the view fields.
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test with OCB
🔇 Additional comments (3)
cetmix_tower_server/views/cx_tower_server_view.xml (2)

120-133: LGTM! Clean implementation of manager-specific fields.

The field visibility conditions and structure are well implemented, following Odoo's best practices.


399-399: Remove redundant groups restriction from filter.

Since the OS field is already restricted at the model level, the groups restriction on the filter is redundant.

Apply this diff:

                    <filter
                        string="OS"
                        name="group_by_os"
                        domain="[]"
                        context="{'group_by': 'os_id'}"
-                        groups="cetmix_tower_server.group_manager"
                    />
cetmix_tower_server/wizards/cx_tower_command_execute_wizard.py (1)

56-56: ⚠️ Potential issue

Implement sudo handling in the compute method.

The addition of compute_sudo=True suggests that sudo privileges should affect the rendered code, but the _compute_rendered_code method doesn't utilize the use_sudo field. This could lead to a security gap where sudo privileges aren't properly considered during code rendering.

Consider updating the compute method to handle sudo privileges. Here's a suggested implementation:

@api.depends("code", "server_ids", "action")
def _compute_rendered_code(self):
    for record in self:
        if record.server_ids and len(record.server_ids) == 1:
            server_id = record.server_ids[0]

            # Get variable list
            variables = record.get_variables()

            # Get variable values
            variable_values = server_id.get_variable_values(
                variables.get(str(record.id))
            )

+           # Check sudo access
+           if record.use_sudo and not self.env.user.has_group('cetmix_tower_server.group_manager'):
+               record.rendered_code = False
+               return

            # Render template
            if variable_values:
                record.rendered_code = record.render_code(
                    pythonic_mode=record.action == "python_code",
+                   use_sudo=bool(record.use_sudo),
                    **variable_values.get(server_id.id),
                ).get(self.id)
            else:
                record.rendered_code = record.code
        else:
            record.rendered_code = record.code

Let's verify the sudo-related access controls:

Limit access to the following fields of the cx.tower.server ​odel to Manager and Root:

- OS
- IP v4 Address
- IP v6 Address
- SSH username
- SSH Port
- SSS auth mode
- SSH key
- Use sudo

Task: 4116
- Add test to execute command with user tower access
- Delete group for search view

Task 4116
- Fix access error of code rendering in wizard

Task: 4116
@GabbasovDinar GabbasovDinar force-pushed the 14.0-t4116-cetmix_tower_server-access branch from 9246dcd to 432a175 Compare January 17, 2025 11:51
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
cetmix_tower_server/views/cx_tower_server_view.xml (1)

399-399: Redundant groups attribute on search filter

The groups="cetmix_tower_server.group_manager" attribute on the group_by_os filter in the search view might be redundant if the os_id field is already restricted. Users without access to os_id won't see or be able to use this filter.

Consider removing the groups attribute from the filter or confirm that it serves a necessary purpose.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9246dcd and 432a175.

📒 Files selected for processing (5)
  • cetmix_tower_server/models/cx_tower_server.py (6 hunks)
  • cetmix_tower_server/readme/CONFIGURE.md (1 hunks)
  • cetmix_tower_server/tests/test_command.py (1 hunks)
  • cetmix_tower_server/views/cx_tower_server_view.xml (2 hunks)
  • cetmix_tower_server/wizards/cx_tower_command_execute_wizard.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • cetmix_tower_server/tests/test_command.py
  • cetmix_tower_server/wizards/cx_tower_command_execute_wizard.py
  • cetmix_tower_server/readme/CONFIGURE.md
🧰 Additional context used
📓 Learnings (1)
cetmix_tower_server/views/cx_tower_server_view.xml (1)
Learnt from: ivs-cetmix
PR: cetmix/cetmix-tower#147
File: cetmix_tower_server/views/cx_tower_file_view.xml:160-160
Timestamp: 2024-11-24T22:56:35.204Z
Learning: In Odoo, when groups are defined at the model level, it's unnecessary to specify them again in the view fields.
🔇 Additional comments (7)
cetmix_tower_server/models/cx_tower_server.py (6)

283-288: Access control on IP address fields is appropriate

The addition of group restrictions to ip_v4_address and ip_v6_address fields ensures that sensitive information is only accessible to users in the cetmix_tower_server.group_manager group.


289-300: Access control enhancements on SSH fields are appropriate

Restricting access to SSH-related fields (ssh_port, ssh_username, ssh_password, ssh_key_id, ssh_auth_mode) to the manager group aligns with the security objectives of limiting sensitive configuration details to authorized personnel.


305-305: Consistent application of group restrictions

Applying the groups attribute to additional fields like ssh_key_id, ssh_auth_mode, use_sudo, and os_id ensures a consistent access control policy across all sensitive fields.

Also applies to: 315-315, 321-321, 337-341


572-572: Review the use of self.sudo() in _get_ssh_client

Assigning self = self.sudo() elevates the access rights for the method _get_ssh_client. While this is necessary to access restricted fields, please verify that this elevated privilege is properly managed and does not expose sensitive operations unintentionally.


762-762: Ensure intentional use of self.sudo() in _render_command

Using self.sudo() in the _render_command method could bypass access controls on variables. Confirm that this is deliberate and that it doesn't grant unauthorized access to sensitive data.


828-829: Verify the necessity of self.sudo() when accessing SSH credentials

In the execute_command method, self.sudo() is used to access ssh_username and use_sudo. Please confirm that elevating privileges here is required and that it aligns with access control policies.

Also applies to: 832-832

cetmix_tower_server/views/cx_tower_server_view.xml (1)

108-135: Avoid duplicating group restrictions in views

Defining groups on the view record cx_tower_server_view_kanban_manager might be unnecessary if access control is already enforced at the model level. Since the fields have groups attributes and the model restricts access appropriately, consider removing the groups_id from the view definition to simplify maintenance.

This aligns with the previous feedback and the learning that when groups are defined at the model level, it's unnecessary to specify them again in the view.

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.

3 participants