Skip to content

Fix: Don't autostart containers on host network with TS enabled#2043

Merged
limetech merged 3 commits into
unraid:masterfrom
Squidly271:patch-28
Feb 25, 2025
Merged

Fix: Don't autostart containers on host network with TS enabled#2043
limetech merged 3 commits into
unraid:masterfrom
Squidly271:patch-28

Conversation

@Squidly271

@Squidly271 Squidly271 commented Feb 24, 2025

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features

    • Enhanced the container autostart process with improved configuration validation to prevent auto-start of containers with conflicting security settings.
  • Refactor

    • Transitioned the autostart initialization script to a new runtime environment, streamlining control flow and error handling for better system reliability.

@coderabbitai

coderabbitai Bot commented Feb 24, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The Docker initialization script has been rewritten from Bash to PHP. It now reads a list of auto-start containers from /var/lib/docker/unraid-autostart, performs XML template checks for each container, and conditionally excludes containers from autostart if they use host networking with Tailscale enabled. The script updates the list of containers based on these checks and writes the modified list back to the file, enhancing control flow and error handling.

Changes

File(s) Change Summary
emhttp/.../scripts/docker_init Converted from Bash to PHP by updating the shebang; added logic to read /var/lib/docker/unraid-autostart; checks XML templates in /boot/config/.../my-*.xml for conditional autostart handling based on network and Tailscale settings.

Sequence Diagram(s)

sequenceDiagram
    participant S as Script (PHP)
    participant FS as File System
    participant XT as XML Checker

    S->>FS: Read autostart file (/var/lib/docker/unraid-autostart)
    alt File exists and is not empty
        loop For each container entry
            S->>FS: Check for XML template (/boot/config/plugins/dockerMan/templates-user/my-*.xml)
            alt XML exists
                S->>XT: Load XML and evaluate "Network" & "TailscaleEnabled"
                alt Network is host and Tailscale is true
                    XT->>S: Log autostart disabled message
                else
                    XT->>S: Container qualifies for autostart
                end
            else
                S->>S: Add container to autostart list
            end
        end
    else
        S->>S: Exit script
    end
    S->>FS: Write updated autostart list back to file
Loading

Possibly related PRs

  • Disallow TS integration on network types host/container #2024: The changes in the main PR, which involve new logic for handling container autostart based on Tailscale integration, are directly related to the modifications in the retrieved PR that manage Tailscale settings based on network types, specifically addressing the security implications of using Tailscale with certain network configurations.

Poem

I'm a rabbit with a gleeful hop,
Bash to PHP made our script non-stop!
Checking XMLs with a vigilant eye,
Host network with Tailscale? Not gonna fly!
Code leaps ahead like a bunny on a spree 🐇!


📜 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 78decb4 and cc9c032.

📒 Files selected for processing (1)
  • emhttp/plugins/dynamix.docker.manager/scripts/docker_init (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • emhttp/plugins/dynamix.docker.manager/scripts/docker_init

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between baf0b4d and 5503aff.

📒 Files selected for processing (1)
  • emhttp/plugins/dynamix.docker.manager/scripts/docker_init (1 hunks)
🔇 Additional comments (2)
emhttp/plugins/dynamix.docker.manager/scripts/docker_init (2)

1-2: Shebang transition to PHP looks fine.
Switching the script to be executed by PHP is appropriate for XML processing, but ensure that /usr/bin/php is the correct path on the target system.


4-5: Silenced file read may mask I/O errors.
Using @file(...) ignores any warning if the file doesn’t exist or can’t be read. Make sure this is intentional, or consider explicit error handling/logging to simplify troubleshooting.

Comment on lines +17 to +22
$doc = new DOMDocument();
$doc->load("/boot/config/plugins/dockerMan/templates-user/my-{$cont[0]}.xml");
if ( ! $doc ) {
$newAuto[] = $container;
continue;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Load return value check is missing.
$doc is always a valid DOMDocument instance after instantiation, even if $doc->load(...) fails. The condition if (!$doc) won’t catch parse errors.

Here's a suggested fix to assess the load result properly:

 $doc = new DOMDocument();
-$doc->load("/boot/config/plugins/dockerMan/templates-user/my-{$cont[0]}.xml");
-if (!$doc) {
+if (!$doc->load("/boot/config/plugins/dockerMan/templates-user/my-{$cont[0]}.xml")) {
   $newAuto[] = $container;
   continue;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
$doc = new DOMDocument();
$doc->load("/boot/config/plugins/dockerMan/templates-user/my-{$cont[0]}.xml");
if ( ! $doc ) {
$newAuto[] = $container;
continue;
}
$doc = new DOMDocument();
- $doc->load("/boot/config/plugins/dockerMan/templates-user/my-{$cont[0]}.xml");
- if ( ! $doc ) {
+ if (! $doc->load("/boot/config/plugins/dockerMan/templates-user/my-{$cont[0]}.xml")) {
$newAuto[] = $container;
continue;
}

Comment thread emhttp/plugins/dynamix.docker.manager/scripts/docker_init

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

♻️ Duplicate comments (1)
emhttp/plugins/dynamix.docker.manager/scripts/docker_init (1)

22-28: ⚠️ Potential issue

Fix null pointer safety and boolean comparison.

The code has potential null pointer issues when accessing DOM elements and uses loose comparison for boolean values.

-  if ( ($doc->getElementsByTagName("Network")->item(0)->nodeValue ?? false) == "host" ) {
-    if ( ($doc->getElementsByTagName("TailscaleEnabled")->item(0)->nodeValue ?? false) == true ) {
+  $networkNode = $doc->getElementsByTagName("Network")->item(0);
+  $tailscaleNode = $doc->getElementsByTagName("TailscaleEnabled")->item(0);
+  
+  $network = $networkNode ? $networkNode->nodeValue : null;
+  $tailscaleEnabled = $tailscaleNode ? filter_var($tailscaleNode->nodeValue, FILTER_VALIDATE_BOOLEAN) : false;
+  
+  if ($network === "host" && $tailscaleEnabled === true) {
🧹 Nitpick comments (1)
emhttp/plugins/dynamix.docker.manager/scripts/docker_init (1)

4-5: Improve error handling for file operations.

The error suppression operator (@) masks potential file access issues. Consider implementing proper error handling and logging.

-$autostart = @file("/var/lib/docker/unraid-autostart",FILE_IGNORE_NEW_LINES);
-if ( ! $autostart ) exit();
+$autostartFile = "/var/lib/docker/unraid-autostart";
+if (!file_exists($autostartFile)) {
+    exec("logger 'Docker autostart configuration file not found'");
+    exit(1);
+}
+$autostart = file($autostartFile, FILE_IGNORE_NEW_LINES);
+if ($autostart === false) {
+    exec("logger 'Failed to read Docker autostart configuration'");
+    exit(1);
+}
+if (empty($autostart)) {
+    exit(0);
+}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5503aff and 78decb4.

📒 Files selected for processing (1)
  • emhttp/plugins/dynamix.docker.manager/scripts/docker_init (1 hunks)

}
$newAuto[] = $container;
}
file_put_contents("/var/lib/docker/unraid-autostart",implode("\n",$newAuto));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Implement atomic file writing with error handling.

The current file writing implementation could lead to data corruption if the script is interrupted.

-file_put_contents("/var/lib/docker/unraid-autostart",implode("\n",$newAuto));
+$tempFile = "/var/lib/docker/unraid-autostart.tmp";
+if (file_put_contents($tempFile, implode("\n", $newAuto)) === false) {
+    exec("logger 'Failed to write Docker autostart configuration'");
+    exit(1);
+}
+if (!rename($tempFile, "/var/lib/docker/unraid-autostart")) {
+    unlink($tempFile);
+    exec("logger 'Failed to update Docker autostart configuration'");
+    exit(1);
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
file_put_contents("/var/lib/docker/unraid-autostart",implode("\n",$newAuto));
$tempFile = "/var/lib/docker/unraid-autostart.tmp";
if (file_put_contents($tempFile, implode("\n", $newAuto)) === false) {
exec("logger 'Failed to write Docker autostart configuration'");
exit(1);
}
if (!rename($tempFile, "/var/lib/docker/unraid-autostart")) {
unlink($tempFile);
exec("logger 'Failed to update Docker autostart configuration'");
exit(1);
}

Comment on lines +11 to +15
$cont = explode(" ",$container);
if ( ! is_file("/boot/config/plugins/dockerMan/templates-user/my-{$cont[0]}.xml")) {
$newAuto[] = $container;
continue;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add input validation for container names.

The code assumes the container string format is valid and directly uses it in a file path without validation.

-  $cont = explode(" ",$container);
-  if ( ! is_file("/boot/config/plugins/dockerMan/templates-user/my-{$cont[0]}.xml")) {
+  $cont = explode(" ", trim($container));
+  if (empty($cont[0]) || !preg_match('/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/', $cont[0])) {
+    exec("logger 'Invalid container name format: {$container}'");
+    continue;
+  }
+  $templateFile = "/boot/config/plugins/dockerMan/templates-user/my-" . $cont[0] . ".xml";
+  if (!is_file($templateFile)) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
$cont = explode(" ",$container);
if ( ! is_file("/boot/config/plugins/dockerMan/templates-user/my-{$cont[0]}.xml")) {
$newAuto[] = $container;
continue;
}
$cont = explode(" ", trim($container));
if (empty($cont[0]) || !preg_match('/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/', $cont[0])) {
exec("logger 'Invalid container name format: {$container}'");
continue;
}
$templateFile = "/boot/config/plugins/dockerMan/templates-user/my-" . $cont[0] . ".xml";
if (!is_file($templateFile)) {
$newAuto[] = $container;
continue;
}

@limetech limetech merged commit 08c5f66 into unraid:master Feb 25, 2025
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.

2 participants