Skip to content

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

Open
chirag-bruno wants to merge 2 commits 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 2 commits 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 into a shared utility, standardizing how environment and workspace variables are formatted and saved across the app.
  • Tests

    • Added comprehensive tests for dotenv serialization, covering empty inputs, special-character escaping/quoting, and round-trip parse/serialize validation.

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

Replaces ad-hoc .env serialization with a new shared jsonToDotenv utility and updates renderer and electron IPC code to delegate dotenv formatting to that utility; adds tests and re-exports the utility from bruno-common.

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
Adds jsonToDotenv(variables: DotenvVariable[]) and DotenvVariable interface; implements escaping/quoting rules and includes comprehensive tests; re-exports from utils index.
Electron IPC Integration
packages/bruno-electron/src/ipc/collection.js, packages/bruno-electron/src/ipc/global-environments.js
Replaces inline .env string construction with calls to jsonToDotenv() when saving variables; preserves validation, write, and error handling flows.
Bruno App Integration
packages/bruno-app/src/components/Environments/DotEnvFileEditor/utils.js
Replaces manual serialization in variablesToRaw() with utils.jsonToDotenv(variables) import from @usebruno/common.

Sequence Diagram(s)

sequenceDiagram
  participant UI as Renderer (App)
  participant IPC as Electron IPC
  participant Util as `@usebruno/common.jsonToDotenv`
  participant FS as Filesystem

  UI->>IPC: save-dotenv-variables(variables)
  IPC->>Util: jsonToDotenv(variables)
  Util-->>IPC: dotenvContent
  IPC->>FS: writeFile(path, dotenvContent)
  FS-->>IPC: writeResult
  IPC-->>UI: result / error
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested labels

size/M

Suggested reviewers

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

Poem

hashes once split at the save's first light,

Now quoted and escaped, they stand upright. ✨
A common util stitches threads anew,
One serializer to keep values true. 🌱

🚥 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: adding proper quoting of .env values containing hash characters to fix serialization issues.
Linked Issues check ✅ Passed The PR successfully addresses issue #7375 by implementing a shared jsonToDotenv utility that quotes and escapes values containing special characters including hash (#), preventing truncation during .env serialization.
Out of Scope Changes check ✅ Passed All changes are directly scoped to the stated objectives: new jsonToDotenv utility, test coverage, and refactoring existing serialization logic in bruno-app and bruno-electron to use the shared utility.
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

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.

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

28-35: Consider quoting values with leading/trailing whitespace.

Values with leading or trailing whitespace (e.g., " password ") will serialize as KEY= password and round-trip back as "password" (stripped by dotenv parser). This is an edge case but could cause data loss.

♻️ Proposed fix
       const value = v.value || '';
       // If value contains special characters, wrap in quotes
-      if (value.includes('\n') || value.includes('\r') || value.includes('"') || value.includes('\'') || value.includes('\\') || value.includes('#')) {
+      const needsQuoting = value.includes('\n') || value.includes('\r') || value.includes('"') || value.includes('\'') || value.includes('\\') || value.includes('#') || value !== value.trim();
+      if (needsQuoting) {
🤖 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 28 - 35, The
serializer in jsonToDotenv.ts uses the local variable value (from v.value) and
currently only quotes when it contains special chars; extend the quoting
condition to also quote when value has leading or trailing whitespace (e.g.,
detect with value.startsWith(' ') || value.endsWith(' ') or a regex /^\s|\s$/)
so such values are wrapped in quotes and escaped the same way as other quoted
values; update the conditional that builds escapedValue (the block referencing
v.name and escapedValue) to trigger for this new whitespace case so
round-tripping via dotenv preserves leading/trailing spaces.

16-16: Minor documentation inaccuracy.

Single quotes don't actually get escaped in the implementation (line 32) — they just trigger double-quoting of the value. Consider rewording to "single quotes ('): must be enclosed in double quotes" for accuracy.

📝 Suggested doc fix
- * - single quotes ('): need escaping
+ * - single quotes ('): must be enclosed in double quotes
🤖 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` at line 16, Update the
documentation string in the jsonToDotenv implementation to accurately describe
handling of single quotes: change the phrase "single quotes ('): need escaping"
to "single quotes ('): must be enclosed in double quotes" (or similar) so it
reflects that the code double-quotes values containing single quotes rather than
escaping them; locate the comment near the jsonToDotenv function/implementation
and adjust the wording accordingly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/bruno-common/src/utils/jsonToDotenv.ts`:
- Around line 28-35: The serializer in jsonToDotenv.ts uses the local variable
value (from v.value) and currently only quotes when it contains special chars;
extend the quoting condition to also quote when value has leading or trailing
whitespace (e.g., detect with value.startsWith(' ') || value.endsWith(' ') or a
regex /^\s|\s$/) so such values are wrapped in quotes and escaped the same way
as other quoted values; update the conditional that builds escapedValue (the
block referencing v.name and escapedValue) to trigger for this new whitespace
case so round-tripping via dotenv preserves leading/trailing spaces.
- Line 16: Update the documentation string in the jsonToDotenv implementation to
accurately describe handling of single quotes: change the phrase "single quotes
('): need escaping" to "single quotes ('): must be enclosed in double quotes"
(or similar) so it reflects that the code double-quotes values containing single
quotes rather than escaping them; locate the comment near the jsonToDotenv
function/implementation and adjust the wording accordingly.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 2d5d4f6e-c2dc-4ee9-a4d6-015663f587cc

📥 Commits

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

📒 Files selected for processing (2)
  • packages/bruno-common/src/utils/jsonToDotenv.spec.ts
  • packages/bruno-common/src/utils/jsonToDotenv.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/bruno-common/src/utils/jsonToDotenv.spec.ts

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