Skip to content

fix: quote values containing hash (#) in .env file serialization#7380

Open
chirag-bruno wants to merge 1 commit intousebruno:mainfrom
chirag-bruno:fix/env-hash-character-escaping
Open

fix: quote values containing hash (#) in .env file serialization#7380
chirag-bruno wants to merge 1 commit intousebruno:mainfrom
chirag-bruno:fix/env-hash-character-escaping

Conversation

@chirag-bruno
Copy link
Collaborator

@chirag-bruno chirag-bruno commented Mar 5, 2026

Description

Values containing # characters were being truncated when saved to .env files because the dotenv parser interprets # as a comment character.

This fix adds a shared jsonToDotenv utility in bruno-common that properly quotes values containing special characters (#, \n, ", ', ) to ensure they are preserved through serialization and parsing.

  • Add jsonToDotenv utility with comprehensive test coverage
  • Update bruno-electron and bruno-app to use shared utility
  • Remove duplicate serialization logic from multiple locations

Fixes #7375 and #7327

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.

Note: Keeping the PR small and focused helps make it easier to review and merge. If you have multiple changes you want to make, please consider submitting them as separate pull requests.

Publishing to New Package Managers

Please see here for more information.

Summary by CodeRabbit

  • Refactor

    • Consolidated dotenv serialization logic into a shared utility for improved consistency and maintainability across environment and workspace variable handling.
  • Tests

    • Added comprehensive test coverage for dotenv variable serialization, including special character handling and round-trip verification.

Values containing # characters were being truncated when saved to .env
files because the dotenv parser interprets # as a comment character.

This fix adds a shared jsonToDotenv utility in bruno-common that properly
quotes values containing special characters (#, \n, ", ', \) to ensure
they are preserved through serialization and parsing.

- Add jsonToDotenv utility with comprehensive test coverage
- Update bruno-electron and bruno-app to use shared utility
- Remove duplicate serialization logic from multiple locations

Fixes usebruno#7375
Fixes usebruno#7327
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 5, 2026

Walkthrough

The PR introduces a new jsonToDotenv utility function to serialize environment variables into dotenv format with proper handling of special characters (hash, quotes, newlines, backslashes). Three existing files are refactored to delegate dotenv serialization to this shared utility, replacing manual formatting logic and addressing a bug where hash-containing values were incorrectly parsed.

Changes

Cohort / File(s) Summary
New Dotenv Utility
packages/bruno-common/src/utils/jsonToDotenv.ts, packages/bruno-common/src/utils/jsonToDotenv.spec.ts, packages/bruno-common/src/utils/index.ts
Introduces jsonToDotenv() function and DotenvVariable interface with comprehensive test coverage. Handles character escaping for special characters and filters invalid variables. Re-exported from utils module.
Electron IPC Integration
packages/bruno-electron/src/ipc/collection.js, packages/bruno-electron/src/ipc/global-environments.js
Replaces manual .env content construction with calls to jsonToDotenv(). Maintains existing validation and error handling.
Bruno App Integration
packages/bruno-app/src/components/Environments/DotEnvFileEditor/utils.js
Replaces inline serialization logic in variablesToRaw() with jsonToDotenv() call from @usebruno/common.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested labels

size/M

Suggested reviewers

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

Poem

\# symbols once vanished in the .env night,
Now escaped and quoted, shining bright! ✨
From scattered code to commons we go,
One utility reigns, let serialization flow. 🌊

🚥 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 accurately reflects the main change: introducing a utility to quote values containing hash (#) characters in .env file serialization.
Linked Issues check ✅ Passed The PR fulfills all coding requirements from issue #7375: it adds special character handling (hash, quotes, newlines, backslashes) via a shared jsonToDotenv utility and updates bruno-app and bruno-electron to use it.
Out of Scope Changes check ✅ Passed All changes are directly scoped to the stated objective: introducing a shared jsonToDotenv utility, adding comprehensive tests, and refactoring duplicate serialization logic in bruno-app and bruno-electron.
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
  • 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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/bruno-common/src/utils/jsonToDotenv.spec.ts (1)

50-83: Add a CRLF (\r\n) serialization test case.

The suite covers \n, but not Windows-style CRLF input, which is the key cross-platform edge here.

Suggested test addition
   describe('special character handling', () => {
+    test('it should quote values containing CRLF newlines and escape them', () => {
+      const variables = [{ name: 'MULTILINE_CRLF', value: 'line1\r\nline2' }];
+      const output = jsonToDotenv(variables);
+      expect(output).toBe('MULTILINE_CRLF="line1\\r\\nline2"');
+    });
+
     test('it should quote values containing hash (#)', () => {
       const variables = [
         { name: 'PASSWORD', value: 'ABC#DEF' },

Based on learnings "Cover both the 'happy path' and the realistically problematic paths. Validate expected success behaviour, but also validate error handling, edge cases, and degraded-mode behaviour".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bruno-common/src/utils/jsonToDotenv.spec.ts` around lines 50 - 83,
Add a test to the special character handling suite that passes a variable with a
CRLF line break to jsonToDotenv and asserts it is serialized with escaped CR and
LF sequences; e.g. create variables = [{ name: 'MULTILINE_CRLF', value:
'line1\r\nline2' }], call jsonToDotenv(variables) and expect the output
toBe('MULTILINE_CRLF="line1\\r\\nline2"') so CRLF inputs are correctly escaped
to "\\r\\n".
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/bruno-common/src/utils/jsonToDotenv.ts`:
- Around line 29-32: The serializer currently escapes backslashes, double
quotes, and newlines but leaves carriage returns raw, which breaks Windows CRLF
handling; update the escaping in the jsonToDotenv serialization (where `value`
is transformed into `escapedValue` and used to build `${v.name}="..."`) to also
replace `\r` (e.g., add a replace for `\r` that yields `\\r`) and perform it
after escaping backslashes but before escaping `\n` so CRLF (`\r\n`) becomes
`\\r\\n`, ensuring consistent cross-platform line ending serialization.

---

Nitpick comments:
In `@packages/bruno-common/src/utils/jsonToDotenv.spec.ts`:
- Around line 50-83: Add a test to the special character handling suite that
passes a variable with a CRLF line break to jsonToDotenv and asserts it is
serialized with escaped CR and LF sequences; e.g. create variables = [{ name:
'MULTILINE_CRLF', value: 'line1\r\nline2' }], call jsonToDotenv(variables) and
expect the output toBe('MULTILINE_CRLF="line1\\r\\nline2"') so CRLF inputs are
correctly escaped to "\\r\\n".

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 5f67422b-099e-4c1c-b3dc-6b709e56c5bc

📥 Commits

Reviewing files that changed from the base of the PR and between 1748741 and 5d5e7dd.

📒 Files selected for processing (6)
  • packages/bruno-app/src/components/Environments/DotEnvFileEditor/utils.js
  • packages/bruno-common/src/utils/index.ts
  • packages/bruno-common/src/utils/jsonToDotenv.spec.ts
  • packages/bruno-common/src/utils/jsonToDotenv.ts
  • packages/bruno-electron/src/ipc/collection.js
  • packages/bruno-electron/src/ipc/global-environments.js

Comment on lines +29 to +32
if (value.includes('\n') || value.includes('"') || value.includes('\'') || value.includes('\\') || value.includes('#')) {
// Escape backslashes first, then double quotes, then newlines
const escapedValue = value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n');
return `${v.name}="${escapedValue}"`;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Handle CRLF safely in serialization.

At Line 31, \n is escaped but \r is left raw. Values containing Windows line endings (\r\n) can be serialized inconsistently across platforms.

Proposed fix
-      if (value.includes('\n') || value.includes('"') || value.includes('\'') || value.includes('\\') || value.includes('#')) {
+      if (value.includes('\n') || value.includes('\r') || value.includes('"') || value.includes('\'') || value.includes('\\') || value.includes('#')) {
         // Escape backslashes first, then double quotes, then newlines
-        const escapedValue = value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n');
+        const escapedValue = value
+          .replace(/\\/g, '\\\\')
+          .replace(/"/g, '\\"')
+          .replace(/\r/g, '\\r')
+          .replace(/\n/g, '\\n');
         return `${v.name}="${escapedValue}"`;
       }

As per coding guidelines "Line endings should be handled consistently (be aware of CRLF vs LF issues)".

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (value.includes('\n') || value.includes('"') || value.includes('\'') || value.includes('\\') || value.includes('#')) {
// Escape backslashes first, then double quotes, then newlines
const escapedValue = value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n');
return `${v.name}="${escapedValue}"`;
if (value.includes('\n') || value.includes('\r') || value.includes('"') || value.includes('\'') || value.includes('\\') || value.includes('#')) {
// Escape backslashes first, then double quotes, then newlines
const escapedValue = value
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n');
return `${v.name}="${escapedValue}"`;
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bruno-common/src/utils/jsonToDotenv.ts` around lines 29 - 32, The
serializer currently escapes backslashes, double quotes, and newlines but leaves
carriage returns raw, which breaks Windows CRLF handling; update the escaping in
the jsonToDotenv serialization (where `value` is transformed into `escapedValue`
and used to build `${v.name}="..."`) to also replace `\r` (e.g., add a replace
for `\r` that yields `\\r`) and perform it after escaping backslashes but before
escaping `\n` so CRLF (`\r\n`) becomes `\\r\\n`, ensuring consistent
cross-platform line ending serialization.

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.

.env files feature does not support values with hash

2 participants