Skip to content

Check for empty buffers instead of nil in responsewriter - #4576

Merged
leaanthony merged 3 commits into
wailsapp:v3-alphafrom
jghiloni:fix-empty-response-buffer
Sep 16, 2025
Merged

leaanthony merged 3 commits into
wailsapp:v3-alphafrom
jghiloni:fix-empty-response-buffer

Conversation

@jghiloni

@jghiloni jghiloni commented Sep 10, 2025 •

Copy link
Copy Markdown
Contributor

Description

Use Case:

I am using a service that implements http.Handler to send streaming video to the frontend. Reliably, when sending fragmented MP4 data on MacOS, the app would panic because the buffer being sent through the response passed a not-nil check but would panic when accessing the first byte of the buffer.

This PR addresses that by checking if the buffer is not empty instead of nil, accounting for the case where len(buf) == 0 and cap(buf) > 0, or maybe where buf[0] == '\0' (I'm not sure how the nil checks work for slices)

Fixes # (issue)

Type of change

Please select the option that is relevant.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How Has This Been Tested?

Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration using wails doctor.

  • Windows
  • macOS
  • Linux

If you checked Linux, please specify the distro and version.

Test Configuration

Please paste the output of wails doctor. If you are unable to run this command, please describe your environment in as much detail as possible.

Checklist:

  • I have updated website/src/pages/changelog.mdx with details of this PR
  • My code follows the general coding style of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

Summary by CodeRabbit

  • Bug Fixes
    • Fixed a rare crash in AssetServer on macOS when handling responses with empty data, improving stability and reliability during content loading.
  • Documentation
    • Updated the unreleased changelog to include this fix and credited the contributor.

Use Case:

I am using a service that implements `http.Handler` to send streaming
video to the frontend. Reliably, when sending fragmented MP4 data on
MacOS, the app would panic because the buffer being sent through the
response passed a not-nil check but would panic when accessing the first
byte of the buffer.

This PR addresses that by checking if the buffer is not empty instead of
nil, accounting for the case where len(buf) == 0 and cap(buf) > 0, or
maybe where buf[0] == '\0' (I'm not sure how the nil checks work for
slices)
@coderabbitai

coderabbitai Bot commented Sep 10, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Updates the unreleased changelog with a new Fixed entry. Adjusts responseWriter.Write on macOS to handle zero-length buffers safely by checking len(buf) > 0 before accessing buf[0], ensuring correct pointer/length is passed to URLSchemeTaskDidReceiveData.

Changes

Cohort / File(s) Summary
Changelog
v3/UNRELEASED_CHANGELOG.md
Adds a Fixed entry noting potential AssetServer crash on macOS, referencing PR #4576 and crediting @jghiloni.
Darwin response writer guard
v3/internal/assetserver/webview/responsewriter_darwin.go
Changes guard from buf != nil to len(buf) > 0; sets content pointer/length accordingly to avoid dereferencing empty slices when calling URLSchemeTaskDidReceiveData.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant C as Caller
    participant RW as responseWriter.Write
    participant WB as WebView Bridge (cgo)
    participant UST as macOS URLSchemeTask

    rect rgba(200,230,255,0.25)
    note over RW: Prepare data for URLSchemeTaskDidReceiveData
    C->>RW: Write(buf)
    alt buf length > 0
        RW->>RW: content = &buf[0]\ncontentLen = len(buf)
    else buf length == 0
        RW->>RW: content = nil\ncontentLen = 0
    end
    end

    rect rgba(220,255,220,0.18)
    RW->>WB: URLSchemeTaskDidReceiveData(content, contentLen)
    WB->>UST: Deliver data pointer and length
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • FIX: Address Mac CGO Crash #3590 — Similar edits to responsewriter_darwin.go to safely handle zero-length buffers before passing data to URLSchemeTaskDidReceiveData.

Suggested labels

go

Suggested reviewers

  • makew0rld

Pre-merge checks (3 passed)

✅ Passed checks (3 passed)
Check name Status Explanation
Title Check ✅ Passed The title "Check for empty buffers instead of nil in responsewriter" succinctly and accurately summarizes the primary change (switching the response writer's nil check to a length/empty-buffer check to avoid panics). It is concise, specific to the modified code, and readable for teammates scanning history.
Description Check ✅ Passed The description clearly explains the use case, root cause, and code change and correctly labels this as a bug fix, but it omits the required "Fixes #" linkage, explicit test/reproduction steps or wails doctor output, and several checklist items (changelog/documentation updates and unit tests) called for by the repository template. These missing items are required by the template even though the core fix is well described. Because the main problem and fix are documented, this check is a pass but requires the listed additions before merging.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.

Poem

I nibbled bytes both thin and small,
A zero-slice that stumped us all.
Now pointers hop with careful cheer,
No Cocoa panic, logs are clear.
Hooray — the changelog carrots here! 🐇✨

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between aa1674b and 764dc17.

📒 Files selected for processing (1)
  • v3/internal/assetserver/webview/responsewriter_darwin.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • v3/internal/assetserver/webview/responsewriter_darwin.go
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: Run Go Tests v3 (macos-latest, 1.24)
  • GitHub Check: Run Go Tests v3 (ubuntu-latest, 1.24)
  • GitHub Check: Run Go Tests v3 (windows-latest, 1.24)
  • GitHub Check: semgrep-cloud-platform/scan
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@dosubot dosubot Bot added the size:XS This PR changes 0-9 lines, ignoring generated files. label Sep 10, 2025
@dosubot dosubot Bot added the Bug Something isn't working label Sep 10, 2025
@dosubot

dosubot Bot commented Sep 10, 2025

Copy link
Copy Markdown

Related Documentation

Checked 1 published document(s). No updates required.

How did I do? Any feedback?  Join Discord

@github-actions github-actions Bot added the Documentation Improvements or additions to documentation label Sep 10, 2025

@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: 0

🧹 Nitpick comments (1)
v3/internal/assetserver/webview/responsewriter_darwin.go (1)

130-133: Consider applying the same fix pattern to header data handling.

Similar to the buffer fix above, this code has the same potential vulnerability pattern. While json.Marshal is unlikely to return a zero-length slice with non-zero capacity, applying the same defensive pattern would be consistent and safer.

-	if len(headerData) != 0 {
+	if len(headerData) > 0 {
		headers = unsafe.Pointer(&headerData[0])
		headersLen = len(headerData)
	}
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c567263 and aa1674b.

📒 Files selected for processing (2)
  • v3/UNRELEASED_CHANGELOG.md (1 hunks)
  • v3/internal/assetserver/webview/responsewriter_darwin.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Run Go Tests v3 (macos-latest, 1.24)
  • GitHub Check: Run Go Tests v3 (ubuntu-latest, 1.24)
  • GitHub Check: Run Go Tests v3 (windows-latest, 1.24)
🔇 Additional comments (2)
v3/UNRELEASED_CHANGELOG.md (1)

28-28: LGTM!

The changelog entry accurately describes the fix and follows the project's established format. The description "AssetServer can crash on MacOS" clearly communicates the impact, and the PR reference and credit attribution are properly formatted.

v3/internal/assetserver/webview/responsewriter_darwin.go (1)

104-107: Excellent fix for the panic vulnerability!

This change correctly addresses the root cause of the panic. The previous buf != nil check was insufficient because Go slices can be non-nil but have zero length (e.g., make([]byte, 0, 10)), which would cause a panic when accessing buf[0]. The new len(buf) > 0 check ensures safe array access and proper handling of empty buffers.

The logic correctly handles both cases:

  • Empty buffer: content remains nil, contentLen is 0
  • Non-empty buffer: content points to first byte, contentLen is the buffer length

This preserves the intended behavior while eliminating the crash scenario.

@atterpac atterpac self-assigned this Sep 10, 2025
@sonarqubecloud

Copy link
Copy Markdown

@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Sep 15, 2025
@leaanthony

Copy link
Copy Markdown
Member

Great catch! Thank you! 🙏

@leaanthony
leaanthony enabled auto-merge (squash) September 15, 2025 21:08
@jghiloni
jghiloni requested a review from atterpac September 16, 2025 19:44

@atterpac atterpac left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

lgtm

@leaanthony
leaanthony merged commit afbbcc9 into wailsapp:v3-alpha Sep 16, 2025
Grantmartin2002 pushed a commit to Grantmartin2002/wails that referenced this pull request Apr 29, 2026
* Check for empty buffers instead of nil in responsewriter

Use Case:

I am using a service that implements `http.Handler` to send streaming
video to the frontend. Reliably, when sending fragmented MP4 data on
MacOS, the app would panic because the buffer being sent through the
response passed a not-nil check but would panic when accessing the first
byte of the buffer.

This PR addresses that by checking if the buffer is not empty instead of
nil, accounting for the case where len(buf) == 0 and cap(buf) > 0, or
maybe where buf[0] == '\0' (I'm not sure how the nil checks work for
slices)

* Update UNRELEASED_CHANGELOG

* Update v3/internal/assetserver/webview/responsewriter_darwin.go

nil and len check

---------

Co-authored-by: Atterpac <[email protected]>
@taliesin-ai taliesin-ai added v3 and removed v3-alpha labels Aug 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Bug Something isn't working Documentation Improvements or additions to documentation lgtm This PR has been approved by a maintainer MacOS reviewed ✅ size:XS This PR changes 0-9 lines, ignoring generated files. v3

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants