Skip to content

fix: salt-fix write fails when wp-config directory is locked (1.0.1) - #12

Closed
r00bbert wants to merge 1 commit into
mainfrom
fix/salt-write-inplace-fallback
Closed

r00bbert wants to merge 1 commit into
mainfrom
fix/salt-write-inplace-fallback

Conversation

@r00bbert

@r00bbert r00bbert commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

Bug

A user hit "Could not write the new configuration. No changes were made." when running the salt-fix wizard on a real install.

Root cause: apply_salt_fix() wrote a sibling temp file in the wp-config.php directory and move()'d it over the original. That requires the directory to be writable — but the precheck (salt_autofix_available) only verified the file (is_writable($path)) was writable. On the common hardening where wp-config.php is writable but its directory is locked, creating the temp failed, so the whole operation aborted even though we could have written the file.

Fix

Keep the atomic temp-swap as the preferred path, but fall back to an in-place put_contents() overwrite of wp-config.php when the temp can't be created. Overwriting an existing writable file needs no directory write access, so it works in the locked-dir setup. The replacement content was already validated by the pre-write safety gate (still valid PHP, no longer weak), so the non-atomic in-place write is sound. Original file mode is preserved on both paths (now passed directly to put_contents, no separate chmod).

This means auto-write now succeeds whenever the file is writable — exactly what the preview check already promised.

Notes

  • Version → 1.0.1.
  • Write path uses WP_Filesystem and isn't unit-testable in the stub harness (consistent with the rest of the I/O layer); pure-logic tests unchanged and green. Verified locally: lint clean, version-consistency matches.
  • A v1.0.1 release with a fresh installable zip will follow the merge.

Summary by CodeRabbit

  • Bug Fixes
    • Enhanced wp-config.php file handling with improved permission preservation and atomic file operations.

Review Change Stack

The salt-fix auto-write created a sibling temp file in the wp-config.php
directory and move()'d it over the original. That requires the
*directory* to be writable, but the precheck only verified the *file*
was writable — so on the common hardening where wp-config.php is
writable yet its directory is locked, the temp creation failed with
"Could not write the new configuration. No changes were made."

Keep the atomic temp-swap as the preferred path, but fall back to an
in-place put_contents() overwrite of wp-config.php when the temp can't
be created. Overwriting an existing writable file needs no directory
write access, and the content was already validated by the safety gate.
Original file mode is preserved on both paths.

Bumps version to 1.0.1.
@coderabbitai

coderabbitai Bot commented May 21, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR improves wp-config.php write reliability in the salt-fix function by computing and preserving original file permissions, implementing an atomic temp-file swap with fallback in-place overwrite, and bumps the plugin version to 1.0.1 to release these changes.

Changes

wp-config write reliability and version 1.0.1 release

Layer / File(s) Summary
wp-config write path with chmod preservation and fallback
includes/Installer.php
The apply_salt_fix() function computes an integer chmod from the existing wp-config.php file using getchmod() with FS_CHMOD_FILE fallback. It writes salts to a sibling temp file with that chmod, attempts an atomic move() to replace the original file, and if that fails, deletes the temp file and falls back to in-place overwrite. If both paths fail, it returns an error message instructing the user to use the manual copy-and-paste option.
Version 1.0.1 release metadata
magicauth.php, readme.txt
The MAGICAUTH_VERSION constant and plugin header Version field are updated to 1.0.1, and the README stable tag is updated to match.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

  • EtticDevelopment/magicauth#10: Both PRs change includes/Installer.php's apply_salt_fix() wp-config write path—preserving original chmod/permissions and handling atomic temp-file/move() failure with appropriate fallbacks—so the changes are directly related at the code level.

Poem

🐰 A rabbit hops through config files with care,
Permissions preserved with chmod so fair,
When atoms align and the swap goes through,
One point zero one—this version is true! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main bug fix (salt-fix write fails when wp-config directory is locked) and includes the version bump (1.0.1), accurately reflecting the primary change.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/salt-write-inplace-fallback

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@includes/Installer.php`:
- Around line 493-495: The chmod parsing uses $filesystem->getchmod($path) and
treats only the empty string as failure, so a returned '0' becomes octdec('0') →
0 and passes a 0000 mode to writes; update the logic around $mode_str and $chmod
to treat '0' (and any non-octal or invalid value) as a failure and fall back to
FS_CHMOD_FILE. Specifically, in the Installer.php code that reads $mode_str and
computes $chmod, validate $mode_str using a check like: ensure it's a non-empty
octal string (e.g., matches /^[0-7]+$/) before calling octdec and casting;
otherwise set $chmod = FS_CHMOD_FILE so put_contents() never receives 0000. Make
the change where $mode_str and $chmod are defined (referencing getchmod,
$mode_str, $chmod, and FS_CHMOD_FILE).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 014d313a-8215-4f1d-b3d8-7bab39bc426f

📥 Commits

Reviewing files that changed from the base of the PR and between 5b15631 and cc5d9ec.

📒 Files selected for processing (3)
  • includes/Installer.php
  • magicauth.php
  • readme.txt

Comment thread includes/Installer.php
Comment on lines +493 to +495
$mode_str = $filesystem->getchmod( $path );
$chmod = '' !== $mode_str ? (int) octdec( $mode_str ) : FS_CHMOD_FILE;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

In current WordPress core, what is the documented/actual return type of WP_Filesystem_Base::getchmod(), and can it return false or non-octal strings?

💡 Result:

In current WordPress core, WP_Filesystem_Base::getchmod is documented to return a string (octal-mode string). The Developer/Trac docs for WP_Filesystem_Base::getchmod state the return type as “string”, i.e., “Mode of the file (the last 3 digits)”[1]. In the upstream code for the base class, getchmod($file) simply returns the string '777' unconditionally[2]. Whether it can return false or non-octal strings: - The method is not documented to return false; the docblock specifies @return string[1]. The base implementation does not return false; it returns '777'[2]. - However, concrete filesystem implementations can differ in behavior. In the direct filesystem implementation (class-wp-filesystem-direct.php), getchmod($file) calls fileperms and returns the string '0' on failure; otherwise it returns substr(decoct(@fileperms($file)),-3), which is an octal-derived string[3]. That means the failure case is still a string and still octal-like ("0"), not false. So, in current core as implemented across at least the base class and the direct filesystem implementation, getchmod returns a string and does not return false; on failure it returns the string '0'. It should not return arbitrary non-octal strings under these implementations (it derives the last 3 digits from decoct(fileperms) or returns a fixed octal string), though the base-class stub itself returns '777' regardless of input[2][3].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate and print the relevant section around includes/Installer.php lines ~470-540
FILE="includes/Installer.php"
if [ -f "$FILE" ]; then
  echo "== $FILE =="
  sed -n '450,540p' "$FILE" | nl -ba | sed -n '1,200p'
else
  echo "File not found: $FILE" >&2
  exit 1
fi

# Show definitions/usage of put_contents call(s) in this region for $chmod
rg -n "put_contents\\(|\\$chmod" "$FILE" | head -n 50

Repository: EtticDevelopment/magicauth

Length of output: 160


🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE="includes/Installer.php"
echo "== $FILE =="
if [ ! -f "$FILE" ]; then
  echo "Missing $FILE" >&2
  exit 1
fi

# print with line numbers around the chmod section
sed -n '470,530p' "$FILE" | nl -ba

echo "== Context: chmod usage =="
rg -n "\\$chmod" "$FILE" | head -n 50

echo "== Context: getchmod usage =="
rg -n "getchmod\\(" "$FILE" | head -n 50

Repository: EtticDevelopment/magicauth

Length of output: 161


🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE="includes/Installer.php"
if [ ! -f "$FILE" ]; then
  echo "Missing $FILE" >&2
  exit 1
fi

sed -n '460,540p' "$FILE" | nl -ba

echo "---- getchmod occurrence ----"
rg -n "getchmod\\(" "$FILE"
echo "---- chmod usage occurrence ----"
rg -n "\\$chmod" "$FILE"

Repository: EtticDevelopment/magicauth

Length of output: 114


🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE="includes/Installer.php"
echo "== Checking file =="
if [ ! -f "$FILE" ]; then
  echo "Missing $FILE" >&2
  exit 1
fi
echo "Size(bytes): $(stat -c %s "$FILE" 2>/dev/null || echo unknown)"

echo "== Snippet around chmod (lines 475-525) =="
# Use cat -n for line numbers (nl not available)
sed -n '475,525p' "$FILE" | cat -n

echo "== Lines containing getchmod() =="
rg -n "getchmod\\(" "$FILE" || true

echo "== Lines containing $chmod =="
rg -n "\\$chmod" "$FILE" || true

echo "== Lines containing put_contents() =="
rg -n "put_contents\\(" "$FILE" || true

Repository: EtticDevelopment/magicauth

Length of output: 3022


🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE="includes/Installer.php"
echo "== Snippet around chmod (lines 485-510) =="
sed -n '485,510p' "$FILE" | cat -n

echo "== Full chmod block context (475-515) =="
sed -n '475,515p' "$FILE" | cat -n

echo "== getchmod() occurrences =="
rg -n "getchmod\\(" "$FILE" || true

echo "== octdec() occurrences =="
rg -n "octdec\\(" "$FILE" || true

echo "== put_contents() occurrences near chmod block =="
rg -n "put_contents\\(.*\\$chmod|put_contents\\(.*?,\\s*\\$updated,\\s*\\$chmod|put_contents\\(\\s*\\$path,\\s*\\$updated,\\s*\\$chmod|put_contents\\(\\s*\\$path,\\s*\\$updated" "$FILE" || true

# Safe check for raw "$chmod" text (no bash $ expansion)
echo "== Lines containing literal '$chmod' =="
grep -nF '$chmod' "$FILE" || true

Repository: EtticDevelopment/magicauth

Length of output: 4161


Harden chmod parsing to avoid applying 0000 when getchmod() fails

WP_Filesystem_*::getchmod() is expected to return an octal-mode string, and WP_Filesystem_Direct::getchmod() returns the string '0' when it can’t read permissions. Current logic only falls back on '', so '0' !== $mode_str and octdec('0') produces $chmod = 0, which is then passed to put_contents() for both the atomic temp swap and the in-place fallback writes.

$mode_str = $filesystem->getchmod( $path );
$chmod    = '' !== $mode_str ? (int) octdec( $mode_str ) : FS_CHMOD_FILE;
Proposed fix
-		$mode_str = $filesystem->getchmod( $path );
-		$chmod    = '' !== $mode_str ? (int) octdec( $mode_str ) : FS_CHMOD_FILE;
+		$mode_raw = $filesystem->getchmod( $path );
+		$mode_str = is_string( $mode_raw ) ? trim( $mode_raw ) : '';
+		$chmod    = preg_match( '/^[0-7]{3,4}$/', $mode_str ) ? (int) octdec( $mode_str ) : FS_CHMOD_FILE;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@includes/Installer.php` around lines 493 - 495, The chmod parsing uses
$filesystem->getchmod($path) and treats only the empty string as failure, so a
returned '0' becomes octdec('0') → 0 and passes a 0000 mode to writes; update
the logic around $mode_str and $chmod to treat '0' (and any non-octal or invalid
value) as a failure and fall back to FS_CHMOD_FILE. Specifically, in the
Installer.php code that reads $mode_str and computes $chmod, validate $mode_str
using a check like: ensure it's a non-empty octal string (e.g., matches
/^[0-7]+$/) before calling octdec and casting; otherwise set $chmod =
FS_CHMOD_FILE so put_contents() never receives 0000. Make the change where
$mode_str and $chmod are defined (referencing getchmod, $mode_str, $chmod, and
FS_CHMOD_FILE).

@r00bbert

Copy link
Copy Markdown
Contributor Author

Superseded by #13 (1.0.1). After security review, we removed the wp-config.php auto-write entirely rather than ship the in-place fallback proposed here — a mid-write failure could truncate wp-config.php and fatal the whole site with no backup. #13 replaces it with a guided copy-and-paste flow plus a docs guide, switches salt generation to local-only, fixes the managed-host false-positive detection, and softens the branded-login gate to informed consent. Closing in favor of #13.

@r00bbert r00bbert closed this May 21, 2026
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