Skip to content

fix(cli): skip headers with empty name when building request - #7869

Merged
bijin-bruno merged 1 commit into
usebruno:mainfrom
Pragadesh-45:fix/allow-empty-header-on-cli
May 6, 2026
Merged

bijin-bruno merged 1 commit into
usebruno:mainfrom
Pragadesh-45:fix/allow-empty-header-on-cli

Conversation

@Pragadesh-45

@Pragadesh-45 Pragadesh-45 commented Apr 27, 2026 •

Copy link
Copy Markdown
Contributor

Fixes: #7868
Partially fixes: #7720
https://usebruno.atlassian.net/browse/BRU-3419

Description

This PR is implemented to skip empty headers ({:}) on CLI runs, similar to how we handle them in the Bruno client.

Contribution Checklist:

  • I've used AI significantly to create this pull request
  • The pull request only addresses one issue or adds one feature.
  • The pull request does not introduce any breaking changes
  • I have added screenshots or gifs to help explain the change if applicable.
  • I have read the contribution guidelines.
  • Create an issue and link to the pull request.

Summary by CodeRabbit

  • Bug Fixes
    • Fixed header processing to properly handle headers with empty names. Empty header names are now skipped during request preparation, preventing invalid header assignments.

@coderabbitai

coderabbitai Bot commented Apr 27, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

The PR fixes a CLI crash that occurs when request headers have empty names. The fix modifies the header preparation logic to skip headers with blank name values, ensuring alignment with the GUI behavior which silently excludes such headers. Comprehensive test coverage validates the filtering behavior.

Changes

Cohort / File(s) Summary
Header filtering logic
packages/bruno-cli/src/runner/prepare-request.js
Added condition to skip headers with empty name values during preparation, preventing invalid header assignments and content-type detection errors.
Header processing tests
packages/bruno-cli/tests/runner/prepare-request.spec.js
Added test suite validating that headers with empty names are excluded from results, disabled headers are filtered out, and enabled headers with non-empty names are retained with their values.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Possibly related PRs

Suggested labels

size/XS

Suggested reviewers

  • helloanoop
  • lohit-bruno
  • naman-bruno
  • bijin-bruno

Poem

Headers with empty names now gracefully fade away,
No more crashes to ruin the CLI's day,
App and CLI dance in harmony at last,
Silent filtering of blanks—bug squashed in the past! 🎉

🚥 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 'fix(cli): skip headers with empty name when building request' directly and accurately describes the main change: filtering out headers with empty names in the CLI request builder.
Linked Issues check ✅ Passed The PR implementation addresses both linked issues by skipping empty-name headers in CLI request construction, matching app behavior and preventing TypeError crashes reported in #7868 and #7720.
Out of Scope Changes check ✅ Passed All changes are scoped to the header validation logic and corresponding tests; no unrelated modifications to other components or functionality.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/bruno-cli/src/runner/prepare-request.js (1)

31-38: ⚠️ Potential issue | 🟡 Minor

Guard against non-string name to avoid a fresh TypeError.

The new h.name.length > 0 check fixes the empty-string case from #7868, but it shifts the failure mode: if h.name is undefined or null (which can happen with malformed/partially-parsed .bru entries — same general territory as the original bug), this line will now throw Cannot read properties of undefined (reading 'length') instead of axios's "header name must be a non-empty string". Cheap to make truly defensive:

🛡️ Proposed fix
-    if (h.enabled && h.name.length > 0) {
+    if (h.enabled && h.name && h.name.length > 0) {
       headers[h.name] = h.value;
       if (h.name.toLowerCase() === 'content-type') {
         contentTypeDefined = true;
       }
     }

Or, equivalently and a touch more thorough (also drops whitespace-only names which axios would also reject):

-    if (h.enabled && h.name.length > 0) {
+    if (h.enabled && typeof h.name === 'string' && h.name.trim().length > 0) {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bruno-cli/src/runner/prepare-request.js` around lines 31 - 38, The
header loop in prepare-request.js currently checks h.name.length which throws if
h.name is null/undefined; update the each(get(request, 'headers', []), (h) => {
... }) block to first ensure h && typeof h.name === 'string' and that
h.name.trim().length > 0 before using it as a key or comparing to
'content-type', then proceed to assign headers[h.name] = h.value and set
contentTypeDefined when h.name.toLowerCase().trim() === 'content-type'; this
defends the headers handling against non-string or whitespace-only names while
preserving existing behavior.
🧹 Nitpick comments (2)
packages/bruno-cli/tests/runner/prepare-request.spec.js (2)

653-666: Tighten the empty-keys assertion.

The filter-and-length dance reads a bit cryptically for what's effectively "no empty-string key on the result". Same intent, less ceremony:

♻️ Proposed refactor
       const result = await prepareRequest(item);
-      expect(Object.keys(result.headers).filter((k) => k === '')).toHaveLength(0);
+      expect(result.headers).not.toHaveProperty('');
+      expect(result.headers).toEqual({});
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bruno-cli/tests/runner/prepare-request.spec.js` around lines 653 -
666, The test's assertion for empty-string header keys in the prepareRequest
result is verbose; change the assertion to directly assert absence of the empty
key (e.g., use expect(result.headers).not.toHaveProperty('') or expect('' in
result.headers).toBe(false)) inside the same test ('produces no headers when all
have empty names') to make the intent clearer and more readable while keeping
the rest of the test and the prepareRequest invocation unchanged.

604-667: Consider adding a case for missing/undefined name.

Tied to the guard suggestion on prepare-request.js Line 32: a header entry like { value: 'x', enabled: true } (no name field) currently slips through to h.name.length and would throw. A small additional case here would lock in the fix and prevent regressions:

it('skips enabled headers with missing/undefined name', async () => {
  const item = {
    request: {
      method: 'GET',
      url: 'https://example.com',
      headers: [
        { value: 'no-name', enabled: true },
        { name: 'X-Valid', value: 'yes', enabled: true }
      ]
    }
  };
  const result = await prepareRequest(item);
  expect(result.headers).toHaveProperty('X-Valid', 'yes');
  expect(Object.keys(result.headers)).toHaveLength(1);
});
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bruno-cli/tests/runner/prepare-request.spec.js` around lines 604 -
667, Add a test that ensures headers missing a name are skipped: create an
it('skips enabled headers with missing/undefined name') case that passes an
item.request.headers array containing an entry without a name (e.g. { value:
'no-name', enabled: true }) alongside a valid header, calls
prepareRequest(item), then asserts only the valid header is present
(expect(result.headers).toHaveProperty('X-Valid','yes') and
expect(Object.keys(result.headers)).toHaveLength(1)). This locks in the guard
you added in prepare-request.js / prepareRequest so undefined/missing h.name
won't cause h.name.length to throw.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@packages/bruno-cli/src/runner/prepare-request.js`:
- Around line 31-38: The header loop in prepare-request.js currently checks
h.name.length which throws if h.name is null/undefined; update the
each(get(request, 'headers', []), (h) => { ... }) block to first ensure h &&
typeof h.name === 'string' and that h.name.trim().length > 0 before using it as
a key or comparing to 'content-type', then proceed to assign headers[h.name] =
h.value and set contentTypeDefined when h.name.toLowerCase().trim() ===
'content-type'; this defends the headers handling against non-string or
whitespace-only names while preserving existing behavior.

---

Nitpick comments:
In `@packages/bruno-cli/tests/runner/prepare-request.spec.js`:
- Around line 653-666: The test's assertion for empty-string header keys in the
prepareRequest result is verbose; change the assertion to directly assert
absence of the empty key (e.g., use
expect(result.headers).not.toHaveProperty('') or expect('' in
result.headers).toBe(false)) inside the same test ('produces no headers when all
have empty names') to make the intent clearer and more readable while keeping
the rest of the test and the prepareRequest invocation unchanged.
- Around line 604-667: Add a test that ensures headers missing a name are
skipped: create an it('skips enabled headers with missing/undefined name') case
that passes an item.request.headers array containing an entry without a name
(e.g. { value: 'no-name', enabled: true }) alongside a valid header, calls
prepareRequest(item), then asserts only the valid header is present
(expect(result.headers).toHaveProperty('X-Valid','yes') and
expect(Object.keys(result.headers)).toHaveLength(1)). This locks in the guard
you added in prepare-request.js / prepareRequest so undefined/missing h.name
won't cause h.name.length to throw.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 1740b925-c264-415f-ad67-50e44c59a726

📥 Commits

Reviewing files that changed from the base of the PR and between 87aefe9 and c0fca85.

📒 Files selected for processing (2)
  • packages/bruno-cli/src/runner/prepare-request.js
  • packages/bruno-cli/tests/runner/prepare-request.spec.js

@prateek-bruno prateek-bruno left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM!

@bijin-bruno
bijin-bruno merged commit e92131f into usebruno:main May 6, 2026
10 checks passed
sharan-bruno pushed a commit to sharan-bruno/bruno that referenced this pull request Jun 4, 2026
@coderabbitai coderabbitai Bot mentioned this pull request Jun 28, 2026
2 of 4 tasks
sid-bruno added a commit to sid-bruno/bruno that referenced this pull request Aug 21, 2026
* feat: implement proxy-aware API fetching using axios instance (usebruno#7767)

* fix(cli): skip headers with empty name when building request (usebruno#7869)

* Revert "feat: ws multi message (usebruno#7719)" (usebruno#7921)

This reverts commit a305b41.

* fix: remove dragbar z-index that was bleeding through modals (usebruno#7924)

* feat: ui state snapshots (usebruno#7794)

* feat(snapshot): add session snapshot persistence and restoration

- Add snapshot middleware to persist UI state (tabs, workspaces, environments)
- Add SnapshotManager service in electron for atomic snapshot storage
- Add accessor-based tab serialization using pathname for reliable restoration
- Add loading states for tabs while collections are mounting
- Add hydrateTabs to restore tabs from snapshots on app load
- Add devTools state persistence (console open/height/tab)

* fix(snapshot): preserve unloaded collections and fix async serialization

Make serializeSnapshot async to fetch existing snapshot before saving,
ensuring collections not currently loaded in Redux are preserved. Fix
activeTab serialization to pass collection object instead of just UID.

* refactor(snapshot): rewrite storage to map-based schema with granular IPC

Replace array-based snapshot storage with key-value maps keyed by pathname
for O(1) lookups. Separate tabs into their own top-level map, decoupled
from collections.

- Rewrite SnapshotManager with map-based schema and granular read/write
  methods (getWorkspace, getTabs, setCollection, removeWorkspace, etc.)
- Add 12 granular IPC handlers (renderer:snapshot:*) replacing 4 coarse ones
- Update middleware serialization to produce maps; remove activeCollectionUidCache
  in favor of lastActiveCollectionPathname on workspace objects
- Fix mountCollection passing collectionUid instead of collection to restoreTabs
- Preserve non-active workspace state from existing snapshot on save

* wip

* refactor: allow migration of old snapshot

* refactor: trim down redundancy

* fix: for workspace state

* feat: fix for finalised schema

* fix: schema cleanup

* chore: simplify

* chore: wait on hydration to finish

* chore: snapshot changes to schema

* chore: fix typo

* fix: switch schema for saving and restoring extras

* chore: correctness changes

* chore: add active in the schema check

* chore: fix lint

* chore: comments

* chore: make writes async

* fix: sorting and cross workspace shared collection fixes

* chore: add version

* fix: wait on hydration

* chore: fix backward compat for ui-snapshots

* chore: dead code removal

* Fix optional chaining in snapshot lookup

---------

Co-authored-by: Chirag Chandrashekhar <[email protected]>

* fix: scrollbar restoration (usebruno#7926)

* fix: restore scrollbar

* chore: remove comments

---------

Co-authored-by: shubh-bruno <[email protected]>

* fix: message in ConnectGitRemote and RemoveGitRemote (usebruno#7929)

* fix: allow empty header names in CLI and gRPC request preparation (usebruno#7925)

* refactor: remove idx from HeaderList, extend ReadOnlyPropertyList, add positional method translations (usebruno#7917)

* refactor: remove 'idx' method from headerList and update related tests

- Eliminated the 'idx' method from both req.headerList and res.headerList to streamline header management.
- Updated associated tests and documentation to reflect the removal, ensuring clarity in the API usage and maintaining consistency across the header management system.

* refactor: block unimplemented HeaderList methods with error messages

- Added error handling for unimplemented methods in HeaderList, including idx, add, upsert, remove, each, prepend, insert, and insertAfter.
- Each method now throws a descriptive error indicating the appropriate alternative methods to use, enhancing clarity in the API and guiding users towards correct usage.

* refactor: update error message in idx() method of HeaderList for clarity

- Modified the error message in the idx() method to guide users towards using all()[index] or get(name) instead of the unsupported idx() method, enhancing the clarity of the API documentation.

* refactor: update HeaderList to extend ReadOnlyPropertyList and remove unimplemented methods

- Changed HeaderList to extend ReadOnlyPropertyList instead of PropertyList, streamlining its functionality.
- Removed unimplemented methods (prepend, insert, insertAfter) from HeaderList, clarifying the API and guiding users towards using supported methods.
- Updated related tests to reflect these changes, ensuring consistency and accuracy in header management.

* test: add translations for pm.request.headers methods in request tests

- Introduced new tests to validate the translation of pm.request.headers methods (prepend, insert, insertAfter) to their corresponding req.headerList.append method.
- Enhanced existing tests to ensure accurate conversion and functionality of header management in the Bruno converters.

* feat: enhance header translation methods for pm.request.headers

- Added translations for additional pm.request.headers methods (get, has, one, all, count, indexOf, find, filter, each, map, reduce, toObject, clear) to their corresponding req.headerList methods.
- Updated tests to validate the new translations and ensure accurate header management functionality in the Bruno converters.

---------

Co-authored-by: Pragadesh-45 <[email protected]>
Co-authored-by: Sid <[email protected]>
Co-authored-by: gopu-bruno <[email protected]>
Co-authored-by: Chirag Chandrashekhar <[email protected]>
Co-authored-by: shubh-bruno <[email protected]>
Co-authored-by: shubh-bruno <[email protected]>
Co-authored-by: naman-bruno <[email protected]>
Co-authored-by: sanish chirayath <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CLI crashes with "header name must be a non-empty string" when request has empty header Bug: removed header on client remains with empty

3 participants