Skip to content

Feat: PAC Support - #7633

Closed
Pragadesh-45 wants to merge 6 commits into
usebruno:mainfrom
Pragadesh-45:pull/6056
Closed

Pragadesh-45 wants to merge 6 commits into
usebruno:mainfrom
Pragadesh-45:pull/6056

Conversation

@Pragadesh-45

@Pragadesh-45 Pragadesh-45 commented Mar 31, 2026 •

Copy link
Copy Markdown
Contributor

fixes: #5980

Description

This PR adds support for a new PAC (Proxy Auto-Configuration) mode in Bruno, allowing users to specify a .pac URL that dynamically determines the proxy to use for each request. This PR includes the work of @dbrglc from #6056

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

Summary by CodeRabbit

Release Notes

  • New Features
    • Added PAC (Proxy Auto-Configuration) support—select "PAC" mode in proxy settings and provide a PAC URL to automatically resolve proxy configurations based on target URLs.

@Pragadesh-45
Pragadesh-45 marked this pull request as draft March 31, 2026 08:33
@snyk-io

snyk-io Bot commented Mar 31, 2026 •

Copy link
Copy Markdown

✅ Snyk checks have passed. No issues have been found so far.

Status Scan Engine Critical High Medium Low Total (0)
✅ Open Source Security 0 0 0 0 0 issues

💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse.

@coderabbitai

coderabbitai Bot commented Mar 31, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

This PR introduces PAC (Proxy Auto-Config) support to Bruno. Users can now select a PAC proxy mode, provide a PAC URL, and the application automatically resolves proxy directives per-request using QuickJS-based PAC parsing, with built-in caching and LRU eviction.

Changes

Cohort / File(s) Summary
UI & Preferences
packages/bruno-app/src/components/Preferences/ProxySettings/index.js, packages/bruno-electron/src/store/preferences.js
Added PAC mode selection and pacUrl form field with validation; updated proxy schema to support pacUrl (max 2048 chars, optional).
PAC Resolver Module
packages/bruno-common/src/net/pac-resolver.js, packages/bruno-common/package.json
New PAC resolver module that downloads PAC scripts, uses QuickJS WASM for parsing, and resolves directives per URL with TTL-based LRU caching (5-min default, configurable max size). Exports getPacResolver() and clearCache(); added pac-resolver, @tootallnate/quickjs-emscripten, and node-fetch dependencies.
PAC Resolver Tests
packages/bruno-common/test/pac-resolver.test.js, packages/bruno-common/test/pac-resolver.integration.test.js
Unit tests mock QuickJS and validate resolver caching, fetch, and error handling; integration tests run against live local PAC server, verify directive parsing (DIRECT, PROXY, SOCKS4/5), cache TTL/LRU eviction, PAC built-ins (isPlainHostName, dnsDomainIs, shExpMatch, etc.), and timeout/error scenarios.
Proxy Agent Integration
packages/bruno-electron/src/utils/proxy-util.js, packages/bruno-electron/src/ipc/network/axios-instance.js
Made setupProxyAgents async; added PAC mode branch that resolves directives and applies corresponding proxy/SOCKS/direct agents; updated axios interceptors to await async setupProxyAgents.
Proxy Integration Tests
packages/bruno-electron/test/pac-proxy.integration.test.js, packages/bruno-electron/test/proxy-util.test.js
Integration test runs local PAC server and verifies agent selection per directive; unit test mocks PAC resolver and confirms timeline logging and agent configuration.
Test Data
packages/bruno-tests/collection/environments/Local.bru
Added sample environment variables for testing.

Sequence Diagram

sequenceDiagram
    actor User
    participant UI as ProxySettings UI
    participant AxiosInstance as Axios Instance
    participant ProxyUtil as Proxy Utility
    participant PACResolver as PAC Resolver
    participant QuickJS as QuickJS WASM
    participant HTTPServer as PAC HTTP Server

    User->>UI: Configure PAC URL
    UI->>UI: Validate & Save

    rect rgba(100, 150, 200, 0.5)
    note over AxiosInstance,PACResolver: On Request
    AxiosInstance->>ProxyUtil: setupProxyAgents(mode: 'pac', pacUrl)
    activate ProxyUtil
    ProxyUtil->>PACResolver: getPacResolver({pacUrl})
    activate PACResolver
    PACResolver->>HTTPServer: fetch PAC script
    HTTPServer-->>PACResolver: PAC script content
    PACResolver->>QuickJS: Initialize & Compile
    QuickJS-->>PACResolver: Resolver function
    PACResolver-->>ProxyUtil: Resolver object
    deactivate PACResolver
    
    ProxyUtil->>PACResolver: resolve(requestURL)
    activate PACResolver
    PACResolver->>QuickJS: Execute FindProxyForURL()
    QuickJS-->>PACResolver: Directive string
    PACResolver-->>ProxyUtil: [PROXY/DIRECT/SOCKS...]
    deactivate PACResolver
    
    ProxyUtil->>ProxyUtil: Apply agent (HTTP/HTTPS/SOCKS)
    ProxyUtil-->>AxiosInstance: requestConfig with agents
    deactivate ProxyUtil
    AxiosInstance->>HTTPServer: Send request with agent
    HTTPServer-->>AxiosInstance: Response
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

Suggested reviewers

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

Poem

🔗 A script in the PAC now flows,
QuickJS parses where proxy goes,
DIRECT or SOCKS, the choice is clear—
Auto-resolved, without fear! 🚀

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 26.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Feat: PAC Support' accurately describes the primary change—adding PAC (Proxy Auto-Config) support across the codebase.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ 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.

Actionable comments posted: 4

Caution

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

⚠️ Outside diff range comments (2)
packages/bruno-electron/src/ipc/network/axios-instance.js (2)

395-398: ⚠️ Potential issue | 🔴 Critical

Same const reassignment issue in redirect error handler.

timeline is declared with const at line 248. Reassigning it at line 397 will throw a runtime error.

🐛 Proposed fix
         catch(err) {
-          if (err.timeline) {
-            timeline = err.timeline;
-          }
           timeline.push({
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bruno-electron/src/ipc/network/axios-instance.js` around lines 395 -
398, The catch block in the redirect error handler (catch(err) { if
(err.timeline) { timeline = err.timeline; } }) attempts to reassign timeline
which was declared as const (timeline at its original declaration); change the
original timeline declaration (the variable named timeline where it is
initialized) from const to let so it can be reassigned here, or alternatively
merge err.timeline into the existing timeline object without reassignment—update
the declaration near the timeline initialization and keep the catch block logic
using the same timeline identifier.

188-191: ⚠️ Potential issue | 🔴 Critical

Const reassignment will throw a runtime error.

timeline is declared with const at line 106. Attempting to reassign it here with timeline = err.timeline will cause a TypeError: Assignment to constant variable.

🐛 Proposed fix

If you need to use err.timeline, push its entries onto the existing array or handle differently:

     catch(err) {
       if (err.timeline) {
-        timeline = err.timeline;
+        // Merge error timeline entries if present
+        err.timeline.forEach((entry) => timeline.push(entry));
       }
       timeline.push({

Or simply remove the reassignment if err.timeline is already a reference to the same array:

     catch(err) {
-      if (err.timeline) {
-        timeline = err.timeline;
-      }
       timeline.push({
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bruno-electron/src/ipc/network/axios-instance.js` around lines 188 -
191, The catch block in axios-instance.js attempts to reassign the const
variable timeline inside catch(err) (the line with timeline = err.timeline),
which causes a runtime TypeError; fix it by either merging the error timeline
into the existing const array (e.g., push or spread its items into the existing
timeline) or by removing the reassignment and handling err.timeline separately
(e.g., assign to a new let/const like errTimeline or only read from err.timeline
without reassigning timeline) — update the catch(err) block around the timeline
handling to use timeline.push(...err.timeline) or similar non-reassignment
approach, referencing the catch(err) block and the timeline variable in
axios-instance.js.
🧹 Nitpick comments (4)
packages/bruno-common/src/net/pac-resolver.js (1)

20-30: Abort error could be more descriptive.

When the timeout triggers, the error will be an AbortError without context. Consider wrapping it for better diagnostics in timeline logs.

♻️ Enhanced error handling
 async function downloadPac(pacUrl, timeoutMs = 5000) {
   const controller = new AbortController();
   const id = setTimeout(() => controller.abort(), timeoutMs);
   try {
     const res = await fetch(pacUrl, { signal: controller.signal });
     if (!res.ok) throw new Error(`Failed to fetch PAC (${res.status})`);
     return await res.text();
+  } catch (err) {
+    if (err.name === 'AbortError') {
+      throw new Error(`PAC download timed out after ${timeoutMs}ms`);
+    }
+    throw err;
   } finally {
     clearTimeout(id);
   }
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bruno-common/src/net/pac-resolver.js` around lines 20 - 30, In
downloadPac, improve the AbortError diagnostics by catching errors from the
fetch call (or the AbortController timeout) and rethrowing a more descriptive
error that includes context such as the pacUrl and timeoutMs; specifically,
update the async function downloadPac to wrap the fetch in a try/catch (or add a
catch after await) that detects an AbortError and throws a new Error like "PAC
download aborted (timeoutMs ms) for URL: pacUrl" while preserving the original
error as cause or including its message for timeline logs.
packages/bruno-common/package.json (1)

24-26: Missing ESM import condition in new subpath export.

Other subpath exports (., ./runner, ./utils) define both require and import conditions. This export only provides require, which could cause issues if any ESM consumer attempts to import it.

If this module is intentionally CJS-only (since it's consumed by Electron's main process), consider adding a comment to document that decision. Otherwise, add the import mapping for consistency.

♻️ Suggested fix for consistency
     "./net/pac-resolver": {
-      "require": "./src/net/pac-resolver.js"
+      "require": "./src/net/pac-resolver.js",
+      "import": "./src/net/pac-resolver.js"
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bruno-common/package.json` around lines 24 - 26, The new subpath
export "./net/pac-resolver" in package.json only defines a "require" condition
and lacks an "import" condition; update the package.json export for
"./net/pac-resolver" to include an "import" mapping alongside "require" to
support ESM consumers (or add an inline comment in package.json documenting that
"./net/pac-resolver" is intentionally CJS-only if that is the deliberate
choice). Locate the export entry for "./net/pac-resolver" and either add the
same "import": "./src/net/pac-resolver.js" key as used in the other exports
(e.g., ".", "./runner", "./utils") or add a clear comment explaining CJS-only
intent.
packages/bruno-electron/test/proxy-util.test.js (1)

16-44: Consider adding test coverage for PAC resolution failure.

The happy path is covered, but the error handling branch (lines 434-436 in proxy-util.js) where PAC resolution fails and falls back to direct connection isn't tested here.

📝 Example additional test case
test('setupProxyAgents falls back to direct on PAC resolution error', async () => {
  jest.doMock('@usebruno/common/net/pac-resolver', () => ({
    getPacResolver: async () => { throw new Error('PAC fetch failed'); },
    clearCache: () => {}
  }));

  const { setupProxyAgents } = require('../src/utils/proxy-util');
  const requestConfig = { url: 'http://example.com/resource' };
  const timeline = [];

  await setupProxyAgents({
    requestConfig,
    proxyMode: 'pac',
    proxyConfig: { pacUrl: 'http://bad-pac' },
    httpsAgentRequestFields: {},
    interpolationOptions: {},
    timeline
  });

  expect(requestConfig.httpsAgent).toBeDefined();
  const hasError = timeline.some((t) => t.type === 'error' && /PAC resolution failed/.test(t.message));
  expect(hasError).toBe(true);
});
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bruno-electron/test/proxy-util.test.js` around lines 16 - 44, Add a
new test in packages/bruno-electron/test/proxy-util.test.js that verifies
setupProxyAgents falls back to direct on PAC resolution error: mock the
'@usebruno/common/net/pac-resolver' module so getPacResolver throws (e.g., throw
new Error('PAC fetch failed')), require setupProxyAgents, call it with
proxyMode: 'pac' and a bad pacUrl, then assert requestConfig.httpsAgent is still
set and the timeline contains an error entry indicating PAC resolution failed;
reference the setupProxyAgents function and the mocked
getPacResolver/pac-resolver module so the test targets the error branch in
proxy-util.js.
packages/bruno-electron/src/utils/proxy-util.js (1)

403-410: Consider supporting HTTPS proxy directive type.

Some PAC files return HTTPS host:port for HTTPS-capable proxies. The current regex only matches PROXY and HTTP. If this is intentional, a comment would help future maintainers.

-          if (/^(PROXY|HTTP)\s+\S/i.test(directive)) {
+          if (/^(PROXY|HTTP|HTTPS)\s+\S/i.test(directive)) {
             const hostPort = directive.split(/\s+/)[1];
-            const proxyUri = `http://${hostPort}`;
+            // Use https:// for HTTPS directive, http:// otherwise
+            const isHttps = /^HTTPS\s/i.test(directive);
+            const proxyUri = `${isHttps ? 'https' : 'http'}://${hostPort}`;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bruno-electron/src/utils/proxy-util.js` around lines 403 - 410, The
PAC directive-handling code currently only matches PROXY and HTTP; update the
check in the block that reads directive to also accept HTTPS (e.g. change the
regex to /^(PROXY|HTTP|HTTPS)\s+\S/i) and when the directive is HTTPS set
proxyUri to use the https:// scheme (so proxyUri = `https://${hostPort}`) before
constructing the agents (TimelineHttpsProxyAgent via
createTimelineAgentClass(PatchedHttpsProxyAgent) and the
HttpProxyAgent/httpsAgent assignments on requestConfig). Ensure the rest of the
logic (agentSet = true; break) remains unchanged so HTTPS-capable PAC entries
are honored.
🤖 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-app/src/components/Preferences/ProxySettings/index.js`:
- Line 17: Remove the leftover debug console.log call that prints preferences in
the ProxySettings component (the console.log(preferences) statement); locate it
in the ProxySettings component file and delete the console.log line (or replace
it with a proper logger or conditional debug flag if runtime inspection is
required) so no debug output is emitted in production.

In `@packages/bruno-common/test/pac-resolver.integration.test.js`:
- Around line 181-202: The test asserts LRU behaviour by inspecting _CACHE
internals but only proves FIFO; to fix, after filling to CACHE_MAX_SIZE via
repeated getPacResolver calls, re-request one early URL (e.g., await
getPacResolver({ pacUrl: firstUrl })) to mark it as recently used, then insert
the overflow URL (pac/50) and assert that an untouched entry (not the
re-accessed firstUrl) was evicted; avoid relying on _CACHE internals—use
startPacServer/pacScript request counters or a handler-side hit counter to
detect which URL was re-downloaded (i.e., the evicted URL should trigger a
network request when fetched again), and update assertions to check server hit
counts or observable network requests rather than _CACHE.has/_CACHE.size
directly.
- Around line 128-142: The test's TTL timing is too tight and may flake; in the
block that calls getPacResolver with opts: { cacheTtlMs: 50 } and then awaits
new Promise(r => setTimeout(r, 60)), increase the sleep to a safely larger
margin (for example at least 2x the TTL or a fixed 100–200ms) so the cache entry
reliably expires before the second getPacResolver call; update the timeout
surrounding the downloadCount check to reference the same cacheTtlMs intent and
keep use of getPacResolver, startPacServer and downloadCount unchanged.

In `@packages/bruno-electron/test/pac-proxy.integration.test.js`:
- Around line 112-118: The test currently uses currentScript = pac('DIRECT')
which doesn't exercise multi-directive parsing; change currentScript to a PAC
string that returns a multi-directive response like "DIRECT; PROXY
proxy.example:8080" (or use pac('DIRECT; PROXY "proxy.example:8080"')) so the
code must parse multiple directives and choose DIRECT; then call
runSetup(pacUrl) as before and assert the same expectations
(requestConfig.httpsAgent defined, requestConfig.httpAgent undefined). Update
the test named "DIRECT-only in multi-directive list: sets plain agent" to use
the multi-directive pac value so it validates that the DIRECT choice is honored
when followed by a PROXY directive.

---

Outside diff comments:
In `@packages/bruno-electron/src/ipc/network/axios-instance.js`:
- Around line 395-398: The catch block in the redirect error handler (catch(err)
{ if (err.timeline) { timeline = err.timeline; } }) attempts to reassign
timeline which was declared as const (timeline at its original declaration);
change the original timeline declaration (the variable named timeline where it
is initialized) from const to let so it can be reassigned here, or alternatively
merge err.timeline into the existing timeline object without reassignment—update
the declaration near the timeline initialization and keep the catch block logic
using the same timeline identifier.
- Around line 188-191: The catch block in axios-instance.js attempts to reassign
the const variable timeline inside catch(err) (the line with timeline =
err.timeline), which causes a runtime TypeError; fix it by either merging the
error timeline into the existing const array (e.g., push or spread its items
into the existing timeline) or by removing the reassignment and handling
err.timeline separately (e.g., assign to a new let/const like errTimeline or
only read from err.timeline without reassigning timeline) — update the
catch(err) block around the timeline handling to use
timeline.push(...err.timeline) or similar non-reassignment approach, referencing
the catch(err) block and the timeline variable in axios-instance.js.

---

Nitpick comments:
In `@packages/bruno-common/package.json`:
- Around line 24-26: The new subpath export "./net/pac-resolver" in package.json
only defines a "require" condition and lacks an "import" condition; update the
package.json export for "./net/pac-resolver" to include an "import" mapping
alongside "require" to support ESM consumers (or add an inline comment in
package.json documenting that "./net/pac-resolver" is intentionally CJS-only if
that is the deliberate choice). Locate the export entry for "./net/pac-resolver"
and either add the same "import": "./src/net/pac-resolver.js" key as used in the
other exports (e.g., ".", "./runner", "./utils") or add a clear comment
explaining CJS-only intent.

In `@packages/bruno-common/src/net/pac-resolver.js`:
- Around line 20-30: In downloadPac, improve the AbortError diagnostics by
catching errors from the fetch call (or the AbortController timeout) and
rethrowing a more descriptive error that includes context such as the pacUrl and
timeoutMs; specifically, update the async function downloadPac to wrap the fetch
in a try/catch (or add a catch after await) that detects an AbortError and
throws a new Error like "PAC download aborted (timeoutMs ms) for URL: pacUrl"
while preserving the original error as cause or including its message for
timeline logs.

In `@packages/bruno-electron/src/utils/proxy-util.js`:
- Around line 403-410: The PAC directive-handling code currently only matches
PROXY and HTTP; update the check in the block that reads directive to also
accept HTTPS (e.g. change the regex to /^(PROXY|HTTP|HTTPS)\s+\S/i) and when the
directive is HTTPS set proxyUri to use the https:// scheme (so proxyUri =
`https://${hostPort}`) before constructing the agents (TimelineHttpsProxyAgent
via createTimelineAgentClass(PatchedHttpsProxyAgent) and the
HttpProxyAgent/httpsAgent assignments on requestConfig). Ensure the rest of the
logic (agentSet = true; break) remains unchanged so HTTPS-capable PAC entries
are honored.

In `@packages/bruno-electron/test/proxy-util.test.js`:
- Around line 16-44: Add a new test in
packages/bruno-electron/test/proxy-util.test.js that verifies setupProxyAgents
falls back to direct on PAC resolution error: mock the
'@usebruno/common/net/pac-resolver' module so getPacResolver throws (e.g., throw
new Error('PAC fetch failed')), require setupProxyAgents, call it with
proxyMode: 'pac' and a bad pacUrl, then assert requestConfig.httpsAgent is still
set and the timeline contains an error entry indicating PAC resolution failed;
reference the setupProxyAgents function and the mocked
getPacResolver/pac-resolver module so the test targets the error branch in
proxy-util.js.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: f894f96c-344f-49c1-8b9c-0dff781514e0

📥 Commits

Reviewing files that changed from the base of the PR and between f0866be and 2ffbefc.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (11)
  • packages/bruno-app/src/components/Preferences/ProxySettings/index.js
  • packages/bruno-common/package.json
  • packages/bruno-common/src/net/pac-resolver.js
  • packages/bruno-common/test/pac-resolver.integration.test.js
  • packages/bruno-common/test/pac-resolver.test.js
  • packages/bruno-electron/src/ipc/network/axios-instance.js
  • packages/bruno-electron/src/store/preferences.js
  • packages/bruno-electron/src/utils/proxy-util.js
  • packages/bruno-electron/test/pac-proxy.integration.test.js
  • packages/bruno-electron/test/proxy-util.test.js
  • packages/bruno-tests/collection/environments/Local.bru

@@ -17,7 +17,7 @@ const ProxySettings = ({ close }) => {
console.log(preferences);

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.

⚠️ Potential issue | 🟡 Minor

Remove debug console.log statement.

This appears to be a leftover debug artifact that shouldn't ship to production.

-  console.log(preferences);
📝 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
console.log(preferences);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bruno-app/src/components/Preferences/ProxySettings/index.js` at line
17, Remove the leftover debug console.log call that prints preferences in the
ProxySettings component (the console.log(preferences) statement); locate it in
the ProxySettings component file and delete the console.log line (or replace it
with a proper logger or conditional debug flag if runtime inspection is
required) so no debug output is emitted in production.

Comment on lines +128 to +142
test('stale cache entry is re-fetched after TTL expires', async () => {
let downloadCount = 0;
const { server: s2, port: p2 } = await startPacServer((req, res) => {
downloadCount++;
res.writeHead(200);
res.end(pacScript('DIRECT'));
});
const url2 = `http://127.0.0.1:${p2}/proxy.pac`;

try {
// 50ms TTL so it expires quickly
await getPacResolver({ pacUrl: url2, opts: { cacheTtlMs: 50 } });
await new Promise((r) => setTimeout(r, 60));
await getPacResolver({ pacUrl: url2, opts: { cacheTtlMs: 50 } });
expect(downloadCount).toBe(2);

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.

⚠️ Potential issue | 🟡 Minor

Give the TTL expiry check a larger timing margin.

Sleeping 60ms against a 50ms TTL is close enough to wall-clock jitter that this can flap on busy CI. Waiting comfortably past the TTL keeps the test deterministic without changing what it proves.

🕒 Suggested change
-      // 50ms TTL so it expires quickly
+      // Keep a comfortable margin over the TTL to avoid clock jitter in CI
       await getPacResolver({ pacUrl: url2, opts: { cacheTtlMs: 50 } });
-      await new Promise((r) => setTimeout(r, 60));
+      await new Promise((r) => setTimeout(r, 150));
       await getPacResolver({ pacUrl: url2, opts: { cacheTtlMs: 50 } });

As per coding guidelines, "Ensure tests are deterministic and reproducible. No randomness, timing dependencies, or environment-specific assumptions without explicit control."

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

In `@packages/bruno-common/test/pac-resolver.integration.test.js` around lines 128
- 142, The test's TTL timing is too tight and may flake; in the block that calls
getPacResolver with opts: { cacheTtlMs: 50 } and then awaits new Promise(r =>
setTimeout(r, 60)), increase the sleep to a safely larger margin (for example at
least 2x the TTL or a fixed 100–200ms) so the cache entry reliably expires
before the second getPacResolver call; update the timeout surrounding the
downloadCount check to reference the same cacheTtlMs intent and keep use of
getPacResolver, startPacServer and downloadCount unchanged.

Comment on lines +181 to +202
test('LRU evicts oldest entry when cache reaches max size', async () => {
const { default: CACHE_MAX_SIZE } = { default: 50 };

// Fill up the cache beyond max size using unique URLs on a single server
const { server: s2, port: p2 } = await startPacServer((req, res) => {
res.writeHead(200);
res.end(pacScript('DIRECT'));
});

try {
const firstUrl = `http://127.0.0.1:${p2}/pac/0`;
// Fill to max
for (let i = 0; i < 50; i++) {
await getPacResolver({ pacUrl: `http://127.0.0.1:${p2}/pac/${i}` });
}
expect(_CACHE.has(`url:${firstUrl}`)).toBe(true);
expect(_CACHE.size).toBe(50);

// One more push evicts the oldest
await getPacResolver({ pacUrl: `http://127.0.0.1:${p2}/pac/50` });
expect(_CACHE.size).toBe(50);
expect(_CACHE.has(`url:${firstUrl}`)).toBe(false);

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.

⚠️ Potential issue | 🟡 Minor

This case still passes with a FIFO cache.

Nothing is re-accessed before the overflow insert, so the current assertions only prove "oldest inserted entry gets evicted." If LRU is the contract here, touch one early URL again and assert that an untouched entry is the one that falls out—ideally via a re-download check rather than _CACHE internals.

As per coding guidelines, "Write behaviour-driven tests, not implementation-driven ones. Tests should validate real expected output and observable behaviour, not internal details or mocked-out logic unless absolutely necessary."

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

In `@packages/bruno-common/test/pac-resolver.integration.test.js` around lines 181
- 202, The test asserts LRU behaviour by inspecting _CACHE internals but only
proves FIFO; to fix, after filling to CACHE_MAX_SIZE via repeated getPacResolver
calls, re-request one early URL (e.g., await getPacResolver({ pacUrl: firstUrl
})) to mark it as recently used, then insert the overflow URL (pac/50) and
assert that an untouched entry (not the re-accessed firstUrl) was evicted; avoid
relying on _CACHE internals—use startPacServer/pacScript request counters or a
handler-side hit counter to detect which URL was re-downloaded (i.e., the
evicted URL should trigger a network request when fetched again), and update
assertions to check server hit counts or observable network requests rather than
_CACHE.has/_CACHE.size directly.

Comment on lines +112 to +118
test('DIRECT-only in multi-directive list: sets plain agent', async () => {
currentScript = pac('DIRECT');
const { requestConfig } = await runSetup(pacUrl);

expect(requestConfig.httpsAgent).toBeDefined();
expect(requestConfig.httpAgent).toBeUndefined();
});

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.

⚠️ Potential issue | 🟡 Minor

Make this case actually exercise a multi-directive PAC result.

currentScript = pac('DIRECT') just duplicates the plain DIRECT test above, so a regression in handling DIRECT; PROXY ... would still pass here.

🧪 Suggested change
-  test('DIRECT-only in multi-directive list: sets plain agent', async () => {
-    currentScript = pac('DIRECT');
+  test('DIRECT first in a multi-directive list: keeps direct routing', async () => {
+    currentScript = pac('DIRECT; PROXY 10.0.0.1:3128');
     const { requestConfig } = await runSetup(pacUrl);

     expect(requestConfig.httpsAgent).toBeDefined();
     expect(requestConfig.httpAgent).toBeUndefined();
   });

As per coding guidelines, "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 when appropriate."

📝 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
test('DIRECT-only in multi-directive list: sets plain agent', async () => {
currentScript = pac('DIRECT');
const { requestConfig } = await runSetup(pacUrl);
expect(requestConfig.httpsAgent).toBeDefined();
expect(requestConfig.httpAgent).toBeUndefined();
});
test('DIRECT first in a multi-directive list: keeps direct routing', async () => {
currentScript = pac('DIRECT; PROXY 10.0.0.1:3128');
const { requestConfig } = await runSetup(pacUrl);
expect(requestConfig.httpsAgent).toBeDefined();
expect(requestConfig.httpAgent).toBeUndefined();
});
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bruno-electron/test/pac-proxy.integration.test.js` around lines 112
- 118, The test currently uses currentScript = pac('DIRECT') which doesn't
exercise multi-directive parsing; change currentScript to a PAC string that
returns a multi-directive response like "DIRECT; PROXY proxy.example:8080" (or
use pac('DIRECT; PROXY "proxy.example:8080"')) so the code must parse multiple
directives and choose DIRECT; then call runSetup(pacUrl) as before and assert
the same expectations (requestConfig.httpsAgent defined, requestConfig.httpAgent
undefined). Update the test named "DIRECT-only in multi-directive list: sets
plain agent" to use the multi-directive pac value so it validates that the
DIRECT choice is honored when followed by a PROXY directive.

@Pragadesh-45
Pragadesh-45 force-pushed the pull/6056 branch 2 times, most recently from 3b00354 to 6359164 Compare March 31, 2026 11:23
@Pragadesh-45
Pragadesh-45 marked this pull request as ready for review March 31, 2026 11:26
dbrglc and others added 4 commits April 1, 2026 12:39
chore(dependencies): update package-lock.json with new dependencies and version upgrades

- Added new dependencies: ajv, git-url-parse, @opencollection/types, and storybook packages.
- Updated existing dependencies to their latest versions, including eslint and babel packages.
- Removed deprecated entries and cleaned up the package-lock structure for better maintainability.
@Pragadesh-45

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Apr 1, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@Pragadesh-45 Pragadesh-45 mentioned this pull request Apr 1, 2026
5 tasks done
@Pragadesh-45 Pragadesh-45 mentioned this pull request Apr 1, 2026
6 tasks done
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.

Support for Proxy Auto-Config (.pac) files

2 participants