Skip to content

Writing the configuration atomically - #87

Open
erkin-io wants to merge 2 commits into
OpenIPC:masterfrom
erkin-io:fix/config-atomic-save
Open

erkin-io wants to merge 2 commits into
OpenIPC:masterfrom
erkin-io:fix/config-atomic-save

Conversation

@erkin-io

Copy link
Copy Markdown
Contributor

What was wrong

A save (/api/cmd?save) could leave a truncated or empty divinus.yaml: a power cut, a crash or a full flash in the middle of the write destroys the only copy of the configuration, and Divinus then fails to start on the next boot.

Why

app_config_save() (src/app_config.c) renames divinus.yaml to divinus.yaml.bak, then opens a new divinus.yaml with fopen(..., "w") and writes into it directly. For the whole duration of the write the configuration exists only as a half-written file, and the result of fclose() and of the writes was never checked.

What this changes

The new settings are written to divinus.yaml.new in the same directory, flushed to storage (fflush and fsync), and only then put in place with one rename(), which replaces the old file in a single step. If any write or the flush fails, the .new file is removed, the old configuration stays untouched and app_config_save() returns a failure (the web UI already reports that).

The previous file is still kept as divinus.yaml.bak exactly as before, including everything that depends on it today (app_config_restore() at exit is not touched): the old file is linked (or, where hard links are not available, renamed) to .bak right before the rename.

A new test, tst/config-save, saves twice in a temporary directory and checks the result, the .bak file, the restore, and the failure case.

This does not change the rollback at exit; whether that is intended is a separate question that will be opened as an issue.

How it was checked

  • ./test.sh config-save on a PC passes (before the change its failure case does not pass).
  • Built with ./build.sh fhan-v2, no new warnings.
  • Not tested: an actual power cut. The sequence is the usual write-temporary, flush, rename.

Effect on other platforms

Shared code, compiled for all targets, run on a save. Uses fsync, link, rename, remove and fileno, all available in glibc, musl and uClibc. On file systems without hard links (FAT, some flash file systems), link() fails and the previous file is renamed to .bak instead, which is what the old code did; the save still completes. During a save the directory briefly holds one more file (.new), so a nearly full configuration partition needs room for one extra copy of the file (a few kilobytes).

🤖 Generated with Claude Code

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Summary by Qodo

Save configuration through a flushed temporary file

🐞 Bug fix 🧪 Tests 🕐 20-40 Minutes

Grey Divider

AI Description

• Write and sync a temporary configuration before replacing the live file, avoiding partial saves.
• Preserve the previous configuration as a backup and report save failures.
• Test successive saves, backup restoration, and an unwritable temporary file.
Diagram

graph TD
  UI["Web save"] --> Save["Serialize config"] --> Temp[("YAML new")] --> Sync["Flush and sync"] --> Commit["Backup and rename"] --> Live[("YAML live")]
  Commit --> Backup[("YAML bak")]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Copy the backup when hard links are unavailable
  • ➕ Keeps the live path in place until the final rename, including on filesystems without hard links.
  • ➖ Requires another copy and explicit handling of backup-copy failures.

Recommendation: The temporary-file approach addresses partial writes and preserves existing restore behavior. Before relying on its power-loss guarantee, consider syncing the containing directory after rename; on filesystems without hard links, the rename-to-backup fallback also briefly removes the live path and can leave it absent if the final rename fails.

Files changed (3) +132 / -19

Bug fix (1) +46 / -19
app_config.cCommit configuration saves from a synced temporary file +46/-19

Commit configuration saves from a synced temporary file

• Writes YAML to a .new file, checks write and flush status, then backs up the previous configuration and renames the temporary file into place. Read-path selection and the existing restore function remain unchanged.

src/app_config.c

Tests (2) +86 / -0
config_test.cExercise saves, backups, restore, and open failure +72/-0

Exercise saves, backups, restore, and open failure

• Checks two successive saves, backup contents, and restoration. Tests that an unwritable .new file leaves the live configuration unchanged when run as a non-root user.

tst/config-save/config_test.c

run.shBuild and run the standalone configuration-save test +14/-0

Build and run the standalone configuration-save test

• Compiles the test with the configuration implementation and supporting HAL sources, then runs it through the existing test harness.

tst/config-save/run.sh

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (5) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. A failed save can remove the live config ✓ Resolved

Resolving commit: 748afd2

Resolution reason
Records whether the live file was actually moved to the backup path during the fallback, and on
failure of the final rename moves the backup back to the configuration path, so a failed save no
longer removes the live config.
Description
app_config_commit() moves the live file to .bak when link() fails, but does not move it back
if the subsequent rename of .new fails. On a filesystem without hard links, that second failure
returns an error while leaving no file at the normal configuration path.

2. A save can expose stored passwords 🐞 Bug ⛨ Security
Description
app_config_create() creates a fresh file with default process permissions, and
app_config_commit() replaces the original without copying its mode or ownership. If the existing
configuration is restricted to mode 0600 but the process umask permits 0644, saving makes its
serialized authentication passwords readable to other local users.
Code

src/app_config.c[R14-15]

+    snprintf(new_path, sizeof(new_path), "%s.new", conf_path);
+    return fopen(new_path, "w");
Evidence
The replacement is a newly created inode, with no metadata-copy operation between its creation and
rename. The saved output contains authentication passwords.

src/app_config.c[10-15]
src/app_config.c[25-39]
src/app_config.c[113-117]
src/app_config.c[159-165]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Replacing the existing configuration with a newly created file can weaken access restrictions on saved credentials.
## Fix Focus Areas
- src/app_config.c[10-15]
- src/app_config.c[25-37]
## Recommended Fix
Create the temporary file with restrictive permissions, inspect the original file, and apply its appropriate mode and ownership to the temporary file before syncing and replacing it. Treat metadata failures as save failures.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

3. Saved settings can vanish after power loss 🐞 Bug ☼ Reliability
Description
app_config_commit() syncs the contents of .new but returns success without syncing the directory
after changing its entries. A power cut after the rename can therefore lose the committed filename
changes, despite the successful save response.
Code

src/app_config.c[R37-41]

+    if (rename(new_path, conf_path)) {
+        remove(new_path);
+        return EXIT_FAILURE;
+    }
+    return EXIT_SUCCESS;
Evidence
Only the temporary file descriptor is passed to fsync; removal, linking, and renaming occur
afterward, followed immediately by success.

src/app_config.c[25-41]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Syncing the temporary file does not make the subsequent backup and replacement directory entries durable.
## Fix Focus Areas
- src/app_config.c[25-41]
## Recommended Fix
Open and fsync the containing directory after the required backup and replacement operations, handle sync failures, and account for the fallback sequence when establishing crash-safe ordering.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


4. Saving breaks linked configurations 🐞 Bug ≡ Correctness
Description
app_config_create() writes beside the selected pathname rather than through it, and the final
rename replaces that pathname itself. When the selected divinus.yaml is a symlink, its target
remains unchanged and the link becomes a regular configuration file after saving.
Code

src/app_config.c[37]

+    if (rename(new_path, conf_path)) {
Evidence
Lookup accepts a symlink because access follows it, but creation uses a sibling .new path and
rename replaces the selected directory entry rather than writing its target.

src/app_config.c[53-64]
src/app_config.c[10-15]
src/app_config.c[34-39]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Atomic replacement of the selected symlink changes the link instead of the configuration file it previously addressed.
## Fix Focus Areas
- src/app_config.c[10-15]
- src/app_config.c[53-64]
- src/app_config.c[34-39]
## Recommended Fix
Resolve supported configuration symlinks to their target pathname before selecting the sibling temporary and backup paths, then replace the target while retaining the link.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


5. A planted temporary file redirects saves 🐞 Bug ⛨ Security
Description
app_config_create() opens the predictable .new pathname with fopen("w"), which follows a
pre-existing symlink instead of exclusively creating a temporary file. Where an untrusted local user
can write the selected configuration directory, they can plant that symlink before a save and cause
the daemon to write serialized settings to a file it can access outside that directory.
Code

src/app_config.c[R14-15]

+    snprintf(new_path, sizeof(new_path), "%s.new", conf_path);
+    return fopen(new_path, "w");
Evidence
The selected path can be relative to the process working directory, the fixed sibling pathname is
opened for writing, and credential fields are subsequently written to that stream. This exploit
requires another user to have write access to the selected directory; it is not implied for
protected executable or /etc directories.

src/app_config.c[3-3]
src/app_config.c[53-65]
src/app_config.c[10-15]
src/app_config.c[113-117]
src/app_config.c[159-165]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A pre-existing symlink at the fixed temporary pathname can redirect configuration output during a save.
## Fix Focus Areas
- src/app_config.c[10-15]
- src/app_config.c[22-39]
## Recommended Fix
Create the temporary file exclusively and without following symlinks in the destination directory. Retain its file descriptor through writing and syncing, and remove only the temporary entry owned by this save on failure.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Informational

6. Root runs skip the failed-save check 🐞 Bug ⚙ Maintainability
Description
config_test.c guards both the failure assertion and the unchanged-configuration assertion with
geteuid() != 0. Since test.sh runs tests as the invoking user, a root run can pass without
exercising the new test’s advertised failed-save behavior.
Code

tst/config-save/config_test.c[R62-66]

+    if (geteuid() != 0) {
+        CHECK(app_config_save() == EXIT_FAILURE);
+        CHECK(read_file("divinus.yaml", text, sizeof(text)));
+        CHECK(strstr(text, "web_port: 8081") != NULL);
+    }
Evidence
The test runner does not change privileges, while the test explicitly skips the only failure-path
assertions for root.

test.sh[95-106]
tst/config-save/config_test.c[59-67]


Grey Divider

Tip of the day
💡 Did you know, you can choose which labels appear on a finding, and whether they show icons or text

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@erkin-io

Copy link
Copy Markdown
Contributor Author

Updated after the automatic review.

  • Failed replacement after the fallback: correct. On a file system without hard links the old file is renamed to .bak; if the final rename() then failed, no configuration was left under its name. The old file is now put back in that case.
  • Permissions, symbolic links, a planted .new: these behave as before this change (the old code also renamed the configuration away and created a fresh file with fopen(..., "w")), so I left them out to keep the change small. I can add any of them (keeping the mode of the old file with fchmod, syncing the directory after the rename) if you want them here.

🤖 Generated with Claude Code

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.

1 participant