Skip to content

fix: preserve files when downloads fail or are cancelled - #10796

Open
AIdafashi wants to merge 2 commits into
AstrBotDevs:masterfrom
AIdafashi:fix/atomic-file-downloads
Open

AIdafashi wants to merge 2 commits into
AstrBotDevs:masterfrom
AIdafashi:fix/atomic-file-downloads

Conversation

@AIdafashi

@AIdafashi AIdafashi commented Oct 26, 2026 •

Copy link
Copy Markdown

The shared io.download_file() opened the destination with "wb" before receiving the complete response. A disconnect, timeout, cancellation, or progress callback failure could destroy the previous download and leave a partial file.

Downloads now stage beside the resolved destination and publish only after the response and callbacks finish. Each call owns its temporary directory; errors and cancellation clean up staging without deleting another call's completed result. Destination symlinks retain their existing target behavior.

Review fixes and compatibility

  • Open an existing destination with O_WRONLY without truncation both before transfer and before publication, enforcing file-level write authorization.
  • Clear POSIX setuid/setgid bits and omit content-bound privilege/integrity xattrs (security.capability, security.ima, security.evm).
  • Preserve POSIX ownership and available extended attributes, including Linux POSIX ACLs; abort on metadata-copy errors. On Windows, use ReplaceFileW with merge errors enabled to retain DACLs and alternate streams.
  • Compare the original destination identity, size and timestamps immediately before publication. If another call has already published a result, raise FileExistsError and retain that completed result. This is optimistic conflict detection within the downloader's event loop, not a cross-process atomic compare-and-swap or newest-request-wins queue.
  • The destination directory must permit creating/replacing entries. Updating a writable file inside a non-writable directory is intentionally rejected. A copy-in-place fallback cannot provide this PR's atomic-publication guarantee. This compatibility tradeoff remains for maintainer review.
  • Metadata guarantees are limited to the platform APIs above. Native macOS ACL behavior and differing Windows owner identities have not been validated.

TLS verification and the existing certificate-fallback policy are unchanged. Existing PRs #9459 and #10125 address TLS policy and SSRF separately.

Validation

Latest update, Windows / Python 3.12:

  • python -m pytest tests/unit/test_io_download_file.py -q: 32 passed, 6 skipped. Skips require POSIX permissions or unavailable Windows symlink privileges.
  • Tests include real loopback interrupted/cancelled responses, overlapping downloads, publication failures, read-only destinations, alternate streams, and reversed completion order.
  • Additional Windows fixture: protected DACL/owner SDDL unchanged after replacement.
  • WSL Ubuntu / Python 3.12, using the exact checked-in publication function on its Linux filesystem: 3 checks passed for real POSIX ACL/xattr/ownership preservation with privilege-bit removal, read-only refusal, and stale-publication rejection.
  • Ruff format/check and git diff --check: passed.

The original patch also passed 230 related media/updater/diagnostic regression tests (3 symlink skips). That broader selection has not been rerun for this update. No full repository suite or macOS run is claimed. Upstream Actions still require maintainer approval.

No new dependencies, public function signatures, frontend, or API schemas. Atomic publication introduces the explicit conflict and directory-permission behavior described above.

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

Hey - I've found 5 issues

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

## Individual Comments

### Comment 1
<location path="astrbot/core/utils/io.py" line_range="360" />
<code_context>
+                            show_downloading_label=False,
+                        )
+        if target_path.exists():
+            shutil.copymode(target_path, staging_path)
+        staging_path.replace(target_path)
     if show_progress:
</code_context>
<issue_to_address>
**Downloaded bytes gain elevated privileges**

When a privileged downloader replaces a destination with setuid or setgid bits, `shutil.copymode` copies those bits to the staging file, and `staging_path.replace` publishes the downloaded contents with them, creating a setuid/setgid executable from untrusted bytes.

Clear setuid and setgid bits from the staging file before publishing it.
</issue_to_address>

### Comment 2
<location path="astrbot/core/utils/io.py" line_range="361" />
<code_context>
+                        )
+        if target_path.exists():
+            shutil.copymode(target_path, staging_path)
+        staging_path.replace(target_path)
     if show_progress:
         print()
</code_context>
<issue_to_address>
**Read-only destinations become replaceable**

When the destination is non-writable but its parent directory is writable, `download_file` writes only to the staging file, then replaces the destination using the parent directory's permissions. On POSIX, a caller that cannot write an existing file can still overwrite it when the parent directory is writable, bypassing file-level write protection.

Check and enforce the existing destination's write authorization before publishing, rejecting the download when the caller could not write the destination directly.
</issue_to_address>

### Comment 3
<location path="astrbot/core/utils/io.py" line_range="360" />
<code_context>
+                            show_downloading_label=False,
+                        )
+        if target_path.exists():
+            shutil.copymode(target_path, staging_path)
+        staging_path.replace(target_path)
     if show_progress:
</code_context>
<issue_to_address>
**Existing access metadata is lost**

When the destination relies on ownership, ACLs, or extended attributes beyond its permission bits, `shutil.copymode` copies only mode bits, and `staging_path.replace` installs a new inode without the destination's other access metadata, changing who can access the completed download.

Preserve the destination's ownership, ACLs, and extended attributes when publishing the downloaded file.

Also at `astrbot/core/utils/io.py:361-362`.
</issue_to_address>

### Comment 4
<location path="astrbot/core/utils/io.py" line_range="361" />
<code_context>
+                        )
+        if target_path.exists():
+            shutil.copymode(target_path, staging_path)
+        staging_path.replace(target_path)
     if show_progress:
         print()
</code_context>
<issue_to_address>
**Older download replaces newer result**

When two successful downloads to the same destination finish in the reverse order from their start, the later-finishing call replaces the destination regardless of which download was started most recently, so an older response can overwrite a newer completed file and callers see stale content.

Serialize publication per destination or reject publication from calls superseded by a newer request.
</issue_to_address>

### Comment 5
<location path="astrbot/core/utils/io.py" line_range="304-306" />
<code_context>
+    # Resolve symlinks as open(path, "wb") does, and stage on the same filesystem
+    # so replacement is atomic. Each call owns its own temporary directory.
+    target_path = Path(path).resolve()
+    with tempfile.TemporaryDirectory(
+        prefix=".astrbot-download-", dir=target_path.parent
+    ) as staging_dir:
+        staging_path = Path(staging_dir) / "download.part"
+        try:
</code_context>
<issue_to_address>
**Writable file cannot be updated**

When the destination is writable but its parent directory does not permit creating entries, `TemporaryDirectory` raises `PermissionError` before the download because it must create a sibling entry, so the existing file is not updated.

Use a staging approach that does not require creating an entry in the destination's parent directory.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 5 findings to address first, and a completed download is published by replacing the destination, so if the received file is wrong, the previous file’s contents are no longer available at that path; reverting will not restore them. The damage is bounded and usually repairable by downloading the file again.

Blocking findings: astrbot/core/utils/io.py:360, astrbot/core/utils/io.py:361, astrbot/core/utils/io.py:360, astrbot/core/utils/io.py:361, astrbot/core/utils/io.py:306


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

Comment thread astrbot/core/utils/io.py Resolved
Comment thread astrbot/core/utils/io.py Resolved
Comment thread astrbot/core/utils/io.py Resolved
Comment thread astrbot/core/utils/io.py Outdated
)
if target_path.exists():
shutil.copymode(target_path, staging_path)
staging_path.replace(target_path)

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.

🟡 Medium · Older download replaces newer result

When two successful downloads to the same destination finish in the reverse order from their start, the later-finishing call replaces the destination regardless of which download was started most recently, so an older response can overwrite a newer completed file and callers see stale content.

Serialize publication per destination or reject publication from calls superseded by a newer request.

Prompt for AI agents
In `astrbot/core/utils/io.py` at line 361:

**Older download replaces newer result**

When two successful downloads to the same destination finish in the reverse order from their start, the later-finishing call replaces the destination regardless of which download was started most recently, so an older response can overwrite a newer completed file and callers see stale content.

Serialize publication per destination or reject publication from calls superseded by a newer request.

Comment thread astrbot/core/utils/io.py
Comment on lines +304 to +306
with tempfile.TemporaryDirectory(
prefix=".astrbot-download-", dir=target_path.parent
) as staging_dir:

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.

🟡 Medium · Writable file cannot be updated

When the destination is writable but its parent directory does not permit creating entries, TemporaryDirectory raises PermissionError before the download because it must create a sibling entry, so the existing file is not updated.

Use a staging approach that does not require creating an entry in the destination's parent directory.

Prompt for AI agents
In `astrbot/core/utils/io.py` at lines 304-306:

**Writable file cannot be updated**

When the destination is writable but its parent directory does not permit creating entries, `TemporaryDirectory` raises `PermissionError` before the download because it must create a sibling entry, so the existing file is not updated.

Use a staging approach that does not require creating an entry in the destination's parent directory.

@Soulter Soulter moved this to In Progress in AstrBot Roadmap Nov 2, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: In Progress

Development

Successfully merging this pull request may close these issues.

2 participants