Skip to content

Skip known_hosts backup when the file is empty - #2871

Merged
berendt merged 1 commit into
mainfrom
fix-known-hosts-empty-backup
Nov 10, 2026
Merged

berendt merged 1 commit into
mainfrom
fix-known-hosts-empty-backup

Conversation

@ideaship

@ideaship ideaship commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

backup_known_hosts now returns early when the known_hosts file is empty, and no longer requires the backup to be larger than 0 bytes; the backup is verified only by its existence after the copy.

Problem

cleanup_ssh_known_hosts_for_node backs up known_hosts before every removal, as part of e.g. osism baremetal undeploy. Once earlier undeploys have removed every entry, the file is empty. The copy of the empty file succeeds, but the check after it treated "backup is larger than 0 bytes" as success. So each further undeploy printed

WARNING | Backup file was not created properly: /share/known_hosts.backup_<timestamp>

and left a 0-byte backup file in /share. The warning reads as a real failure to an operator.

Change

  • An empty file is handled like a missing one: a debug message that no backup is needed, and nothing is copied.
  • The size check after the copy is dropped rather than changed to compare the backup with the source size. /share/known_hosts is shared: ssh adding a host key or another cleanup can change it between reading its size and copying it, which would turn a correct copy into the same kind of false warning. shutil.copy2 raises on a failed copy, and those exceptions are already caught and logged.

Tests

  • Removed test_backup_verify_empty_after_copy without replacement: it asserted the warning for an empty backup, which is the behaviour being fixed.
  • New tests on real files in tmp_path: an empty known_hosts creates no backup file and no warning; a non-empty one is copied byte for byte into a new file next to it.
  • test_backup_verify_missing_after_copy now asserts that the copy was attempted from the source to a timestamped backup path.
  • The mock-based tests that reach the new size check patch os.path.getsize.

🤖 Generated with Claude Code

@ideaship ideaship self-assigned this Nov 10, 2026
@ideaship
ideaship marked this pull request as ready for review November 10, 2026 06:49
@ideaship
ideaship requested a review from berendt November 10, 2026 06:49
@ideaship
ideaship marked this pull request as draft November 10, 2026 06:50

@sourcery-ai sourcery-ai 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.

Hey - I've found 4 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="osism/utils/ssh.py" line_range="229-233" />
<code_context>
             return None

+        source_size = os.path.getsize(known_hosts_path)
+        if source_size == 0:
+            logger.debug(
+                f"SSH known_hosts file is empty, no backup needed: {known_hosts_path}"
+            )
+            return None
+
         # Create backup with timestamp
</code_context>
<issue_to_address>
**Keys are removed without a backup**

When the file is empty at the size check and a concurrent SSH operation adds a matching host key before cleanup removes entries, `backup_known_hosts` returns without copying the file, then cleanup removes the new entry without a pre-removal backup, so the caller cannot restore the key.

Ensure entries added after the empty-file check are backed up before cleanup removes them.
</issue_to_address>

### Comment 2
<location path="osism/utils/ssh.py" line_range="228-237" />
<code_context>
             logger.warning(f"SSH known_hosts file is not readable: {known_hosts_path}")
             return None

+        source_size = os.path.getsize(known_hosts_path)
+        if source_size == 0:
+            logger.debug(
</code_context>
<issue_to_address>
**Successful backups are reported as failures**

When another cleanup or SSH operation changes the shared `known_hosts` file's size between the size read and the copy, `source_size` describes the earlier file while `shutil.copy2` copies the updated file, so the size check rejects a successful copy and `backup_known_hosts` returns `None` with a warning; cleanup proceeds without recognizing the backup.

Validate the copied backup without comparing its size to the earlier `source_size`.
</issue_to_address>

### Comment 3
<location path="tests/unit/utils/test_ssh.py" line_range="524" />
<code_context>
+    result = backup_known_hosts(str(known_hosts))
+
+    assert result is not None
+    assert open(result).read() == known_hosts.read_text()
+    assert not any(r["level"] == "WARNING" for r in loguru_logs)
+
</code_context>
<issue_to_address>
**Missing backup passes content test**

When `backup_known_hosts` returns the input path without creating a backup, `test_backup_copies_file_content` passes if `backup_known_hosts` returns the source path without creating a backup: line 524 reads that same source and compares its contents with itself. The test therefore accepts the absence of a backup.

Assert that the returned path differs from the source and refers to a created backup file.
</issue_to_address>

### Comment 4
<location path="tests/unit/utils/test_ssh.py" line_range="499" />
<code_context>
     """Backup file absent after copy -> warning, returns None."""
+    mocker.patch("osism.utils.ssh.os.path.getsize", return_value=128)
     mocker.patch("osism.utils.ssh.os.access", return_value=True)
     mocker.patch("shutil.copy2")
     mocker.patch(
</code_context>
<issue_to_address>
**Missing copy passes mismatch test**

When `backup_known_hosts` skips the copy while the mocked verification checks report an existing, size-mismatched backup, `test_backup_verify_size_mismatch_after_copy` still passes if `backup_known_hosts` never calls `shutil.copy2`: line 499 does not assert the mock was called, and the mocked existence and size checks produce the expected warning anyway.

Assert that the `shutil.copy2` mock was called with the source path and generated backup path.
</issue_to_address>

Sourcery assessment

Approval pending. 4 findings to address first.

Blocking findings: osism/utils/ssh.py:233, osism/utils/ssh.py:237, tests/unit/utils/test_ssh.py:524, tests/unit/utils/test_ssh.py:499


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread osism/utils/ssh.py Resolved
Comment thread osism/utils/ssh.py Resolved
Comment thread tests/unit/utils/test_ssh.py Resolved
Comment thread tests/unit/utils/test_ssh.py Resolved
@ideaship
ideaship marked this pull request as ready for review November 10, 2026 06:52
@ideaship
ideaship marked this pull request as draft November 10, 2026 06:52
Return early from backup_known_hosts when the known_hosts file is
empty, and drop the check that the backup is larger than 0 bytes;
the backup is now verified only by its existence after the copy.

cleanup_ssh_known_hosts_for_node backs up known_hosts before every
removal, as part of e.g. osism baremetal undeploy. Once earlier
undeploys have removed every entry, the file is empty. The copy of
the empty file succeeded, but the check after it treated "backup is
larger than 0 bytes" as success, so each further undeploy warned
"Backup file was not created properly" and left a 0-byte backup file
behind. The warning reads as a real failure to an operator.

An empty file now gets the same treatment as a missing one: a debug
message that no backup is needed, and nothing is copied.

The size check is dropped rather than changed to compare the backup
with the source size: /share/known_hosts is shared, and ssh adding a
host key or another cleanup can change the file between reading its
size and copying it, which would turn a correct copy into the same
kind of false warning. shutil.copy2 raises on a failed copy, and
those exceptions are already caught and logged.

Tests: test_backup_verify_empty_after_copy is removed without
replacement, because it asserted the warning for an empty backup,
which is the behaviour being fixed. Two new tests use real files in
tmp_path: an empty known_hosts creates no backup and no warning, and
a non-empty one is copied byte for byte into a new file next to it.
test_backup_verify_missing_after_copy now asserts that the copy was
attempted from the source to a timestamped backup path. The
mock-based tests that reach the new size check patch
os.path.getsize.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Roger Luethi <luethi@osism.tech>
@ideaship
ideaship force-pushed the fix-known-hosts-empty-backup branch from 285d310 to a4217d9 Compare November 10, 2026 07:59
@ideaship
ideaship marked this pull request as ready for review November 10, 2026 08:36
@berendt
berendt merged commit ec4203d into main Nov 10, 2026
3 checks passed
@berendt
berendt deleted the fix-known-hosts-empty-backup branch November 10, 2026 10:01
@github-project-automation github-project-automation Bot moved this from New to Done in Human Board Nov 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Archived in project

Development

Successfully merging this pull request may close these issues.

2 participants