Skip to content

fix: Code Generation for Basic Auth#6474

Merged
bijin-bruno merged 10 commits intousebruno:fix/oauth-code-genfrom
Cmarvin1:bugfix/fix-code-generation-for-basic-auth
Jan 21, 2026
Merged

fix: Code Generation for Basic Auth#6474
bijin-bruno merged 10 commits intousebruno:fix/oauth-code-genfrom
Cmarvin1:bugfix/fix-code-generation-for-basic-auth

Conversation

@Cmarvin1
Copy link
Contributor

@Cmarvin1 Cmarvin1 commented Dec 21, 2025

Description

Fix basic auth variable interpolation in generated code snippets. Code generation currently mishandles requests that use Basic Auth credentials defined via variables (e.g. {{username}}, {{password}}). The generator base64-encodes the literal variable placeholders instead of interpolating them first. Demo of the issue and the fix has been included below with the current behavior on the left pane and the behavior present in this PR on the right.

Screen Recording 2025-12-21 at 12 57 07 PM (1)

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

    • Unified interpolation across entire request payloads for consistent handling of headers, body, params and auth
    • In-place interpolation now applies to nested objects and arrays, improving complex data support
    • Added detection for circular references to prevent infinite processing
  • Tests

    • Expanded coverage for nested structures, missing variables, nulls and circular refs
    • New test for basic-auth header generation and compact body formatting

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 21, 2025

Walkthrough

Refactors interpolation by replacing interpolateHeaders and interpolateBody with a single recursive interpolateObject(obj, variables) that walks objects/arrays, interpolates strings, and detects circular references. Updates snippet generator to apply interpolation to the full request and adjusts tests accordingly.

Changes

Cohort / File(s) Summary
Interpolation Utility Refactoring
packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/interpolation.js, packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/interpolation.spec.js
Consolidates interpolateHeaders and interpolateBody into a single interpolateObject export. Implements recursive traversal for objects and arrays, string interpolation, and circular-reference detection via WeakSet. Tests updated to cover nested structures, missing variables, nulls, and circular references; imports switched to lodash-es.
Snippet Generator Integration
packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/snippet-generator.js, packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/snippet-generator.spec.js
Replaces per-field interpolation with request = interpolateObject(request, variables) (request now let). Interpolation occurs before header merging; header/body-specific helpers removed. Tests updated for compact JSON output, endpoint resolution, and a new basic-auth header generation test.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Review interpolateObject recursion and circular-reference detection for false positives/negatives.
  • Verify preservation of non-string primitives, arrays, and nulls during traversal.
  • Confirm snippet-generator integration doesn't change auth/header assembly semantics.

Suggested labels

size/S

Suggested reviewers

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

Poem

A pair of helpers, now one to roam,
Walking objects, finding each string home,
WeakSet watches for circles in play,
Variables stitched in a tidy array,
Tests sing approval — compact, steady, and bold.

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main fix: correcting basic auth code generation to interpolate variables before base64 encoding, which aligns with the core changes across interpolation and snippet-generator files.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 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 7492fde and 2f101ab.

📒 Files selected for processing (1)
  • packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/snippet-generator.js (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/snippet-generator.js

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.

@Cmarvin1 Cmarvin1 changed the title Fix Code Generation for Basic Auth fix:Code Generation for Basic Auth Dec 21, 2025
@Cmarvin1 Cmarvin1 changed the title fix:Code Generation for Basic Auth fix: Code Generation for Basic Auth Dec 21, 2025
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: 2

📜 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 41efa85 and 7492fde.

📒 Files selected for processing (4)
  • packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/interpolation.js (1 hunks)
  • packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/interpolation.spec.js (1 hunks)
  • packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/snippet-generator.js (3 hunks)
  • packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/snippet-generator.spec.js (7 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (CODING_STANDARDS.md)

**/*.{js,jsx,ts,tsx}: Use 2 spaces for indentation. No tabs, just spaces
Stick to single quotes for strings. For JSX/TSX attributes, use double quotes (e.g., )
Always add semicolons at the end of statements
No trailing commas
Always use parentheses around parameters in arrow functions, even for single params
For multiline constructs, put opening braces on the same line, and ensure consistency. Minimum 2 elements for multiline
No newlines inside function parentheses
Space before and after the arrow in arrow functions. () => {} is good
No space between function name and parentheses. func() not func ()
Semicolons go at the end of the line, not on a new line
Names for functions need to be concise and descriptive
Add in JSDoc comments to add more details to the abstractions if needed
Add in meaningful comments instead of obvious ones where complex code flow is explained properly

Files:

  • packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/snippet-generator.spec.js
  • packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/interpolation.spec.js
  • packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/interpolation.js
  • packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/snippet-generator.js
🧠 Learnings (4)
📓 Common learnings
Learnt from: bijin-bruno
Repo: usebruno/bruno PR: 6263
File: packages/bruno-requests/src/auth/oauth2-helper.ts:249-249
Timestamp: 2025-12-02T07:24:50.311Z
Learning: In OAuth2 Basic Auth headers for Bruno, clientSecret is optional and can be omitted. When constructing the Authorization header in `packages/bruno-requests/src/auth/oauth2-helper.ts`, use `clientSecret || ''` instead of `clientSecret!` to properly handle cases where only clientId is provided, per community requests.
📚 Learning: 2025-12-16T07:16:08.934Z
Learnt from: sanish-bruno
Repo: usebruno/bruno PR: 6090
File: tests/scripting/hooks/init-user-data/ui-state-snapshot.json:1-8
Timestamp: 2025-12-16T07:16:08.934Z
Learning: For e2e tests in the bruno repository: Collections that are shared between CLI and UI tests (comprehensive test suites testing core functionality) should be placed in `packages/bruno-tests/` to avoid duplication. The `tests/**/fixtures/collection` pattern should be used for test-specific collections that test particular UI behaviors or are specific to a single test file.

Applied to files:

  • packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/snippet-generator.spec.js
  • packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/interpolation.spec.js
📚 Learning: 2025-12-05T20:31:33.005Z
Learnt from: CR
Repo: usebruno/bruno PR: 0
File: CODING_STANDARDS.md:0-0
Timestamp: 2025-12-05T20:31:33.005Z
Learning: Applies to **/*.test.{js,jsx,ts,tsx} : Add tests for any new functionality or meaningful changes. If code is added, removed, or significantly modified, corresponding tests should be updated or created

Applied to files:

  • packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/snippet-generator.spec.js
📚 Learning: 2025-12-17T21:41:24.730Z
Learnt from: naman-bruno
Repo: usebruno/bruno PR: 6407
File: packages/bruno-app/src/components/Environments/ConfirmCloseEnvironment/index.js:5-41
Timestamp: 2025-12-17T21:41:24.730Z
Learning: Do not suggest PropTypes validation for React components in the Bruno codebase. The project does not use PropTypes, so reviews should avoid proposing PropTypes and rely on the existing typing/validation approach (e.g., TypeScript or alternative runtime checks) if applicable. This guideline applies broadly to all JavaScript/JSX components in the repo.

Applied to files:

  • packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/snippet-generator.spec.js
  • packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/interpolation.spec.js
  • packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/interpolation.js
  • packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/snippet-generator.js
🧬 Code graph analysis (2)
packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/snippet-generator.spec.js (1)
packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/snippet-generator.js (3)
  • require (10-10)
  • generateSnippet (7-45)
  • harRequest (32-35)
packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/snippet-generator.js (5)
packages/bruno-app/src/components/FolderSettings/Auth/index.js (2)
  • request (30-30)
  • request (50-50)
packages/bruno-app/src/components/RequestPane/Auth/index.js (4)
  • request (35-37)
  • item (21-21)
  • requestTreePath (32-32)
  • getTreePathFromCollectionToItem (19-27)
packages/bruno-cli/src/utils/collection.js (3)
  • getTreePathFromCollectionToItem (368-376)
  • headers (123-123)
  • mergeHeaders (122-153)
packages/bruno-electron/src/utils/collection.js (3)
  • getTreePathFromCollectionToItem (274-282)
  • mergeHeaders (8-50)
  • variables (586-586)
packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/interpolation.js (2)
  • interpolateObject (7-38)
  • interpolateObject (7-38)
🔇 Additional comments (7)
packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/snippet-generator.spec.js (3)

1-1: LGTM - Import aligns with test requirements.

The import of getAuthHeaders is necessary for the new basic authentication test at line 456 where the actual implementation is used to validate header generation.


61-63: LGTM - Mock variables support the new test.

Adding user and pass variables to the mock getAllVariables output enables the basic authentication test case to function correctly.


153-154: LGTM - Compact JSON aligns with interpolation behavior.

The switch from pretty-printed to compact JSON strings in test expectations correctly reflects the new interpolateObject function's behavior, which performs string interpolation on the JSON without reformatting.

Also applies to: 207-208, 270-270, 370-370, 421-424

packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/interpolation.js (1)

1-38: LGTM - Clean, robust implementation.

The interpolateObject function provides a solid foundation for recursive variable interpolation:

  • Circular reference detection prevents infinite loops
  • Handles all common value types (strings, arrays, plain objects, null, primitives)
  • Uses appropriate lodash-es utilities for object traversal

The WeakSet approach for cycle detection is efficient and memory-safe since it doesn't prevent garbage collection of tracked objects.

packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/snippet-generator.js (2)

14-22: Critical fix correctly applied.

The sequence is now correct for basic auth interpolation:

  1. Line 14: request changed to let to allow reassignment
  2. Lines 20-22: Request interpolation happens before auth header generation
  3. Lines 24-29: Auth headers are generated from the interpolated request

This ensures that {{username}} and {{password}} placeholders in request.auth are replaced with actual values before base64 encoding occurs in getAuthHeaders. This is the core fix described in the PR objectives.


3-3: The shortened import path is valid.

The import from 'utils/collections' correctly resolves to 'utils/collections/index.js'. All three functions (getAllVariables, getTreePathFromCollectionToItem, mergeHeaders) are properly exported as named exports from the module.

packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/interpolation.spec.js (1)

1-95: LGTM - Comprehensive test coverage.

The test suite thoroughly validates the new interpolateObject implementation:

  • Complex nested structures with multiple data types (lines 5-60)
  • Circular reference protection (lines 62-69)
  • Missing variable handling with placeholder preservation (lines 71-82)
  • Edge cases including null inputs (lines 93-95)

The tests are well-structured with clear naming and follow AAA (Arrange-Act-Assert) pattern.

Comment on lines +426 to 476
it('should interpolate basic auth credentials correctly', () => {
const item = {
request: {
method: 'GET',
url: 'https://api.example.com',
auth: {
mode: 'basic',
basic: {
username: '{{user}}',
password: '{{pass}}'
}
}
}
};

const collection = {
root: {
request: {
vars: {
req: [
{ name: 'user', value: 'admin', enabled: true },
{ name: 'pass', value: 'secret123', enabled: true }
]
}
}
}
};

const { HTTPSnippet: mockedHTTPSnippet } = require('httpsnippet');
const { getAuthHeaders: actualGetAuthHeaders } = jest.requireActual('utils/codegenerator/auth');
getAuthHeaders.mockImplementation(actualGetAuthHeaders);

const language = { target: 'shell', client: 'curl' };

generateSnippet({
language,
item,
collection,
shouldInterpolate: true
});

const harRequest = mockedHTTPSnippet.mock.calls[0][0];

// "admin:secret123" encoded is "YWRtaW46c2VjcmV0MTIz"
expect(harRequest.headers).toContainEqual(
expect.objectContaining({
name: 'Authorization',
value: 'Basic YWRtaW46c2VjcmV0MTIz'
})
);
});
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 | 🟡 Minor

The test validates basic auth interpolation correctly, but consider clarifying the data flow.

The test depends on the real getAuthHeaders implementation, which is appropriate since basic auth processing involves interpolating template values from collection vars before encoding. However, the actual interpolation and header generation happen in the request preparation phase (via _interpolate), not within getAuthHeaders itself. The test is correct—interpolated credentials do reach the auth handler with resolved values (e.g., 'admin' and 'secret123' instead of '{{user}}' and '{{pass}}'), and they're properly base64-encoded as shown in the assertion.

@@ -24,14 +28,6 @@ const generateSnippet = ({ language, item, collection, shouldInterpolate = false
headers = [...headers, ...authHeaders];
}

Copy link
Member

Choose a reason for hiding this comment

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

We need to interpolate the merged headers too.

@bijin-bruno bijin-bruno changed the base branch from main to fix/oauth-code-gen January 21, 2026 12:59
@bijin-bruno bijin-bruno merged commit 148d3f0 into usebruno:fix/oauth-code-gen Jan 21, 2026
2 checks passed
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.

3 participants