Repository navigation
fix(openapi):validate API spec imports - #8322
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughAdds Electron-side API spec validation and guarded parsing, plus client-side preview parsing, timeout handling, and error-overlay rendering in the spec viewer. ChangesAPI Spec Validation
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (3)
packages/bruno-app/src/components/ApiSpecPanel/SpecViewer.js (2)
144-153: ⚡ Quick winAdd
data-testidto the error overlay for Playwright.Per coding guidelines, testable elements should have
data-testidattributes.♻️ Suggested fix
<div className="absolute inset-0 flex items-center justify-center p-8" style={{ background: theme.bg }} + data-testid="spec-preview-error" > <div className="flex flex-col items-center gap-3 text-center opacity-70"> <IconAlertCircle size={28} strokeWidth={1.5} /> <span className="text-sm">{previewError}</span> </div> </div>Based on learnings: "Add
data-testidto testable elements for Playwright" from the coding guidelines.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-app/src/components/ApiSpecPanel/SpecViewer.js` around lines 144 - 153, The error overlay container in the previewError condition does not have a data-testid attribute required for Playwright testing. Add a data-testid attribute to the outer div element that contains the error message display (the one with className="absolute inset-0 flex items-center justify-center p-8") with an appropriate identifier such as "spec-preview-error" to make the error overlay testable.Source: Coding guidelines
159-168: ⚡ Quick winConsider adding
data-testidto the loader overlay as well.Consistent test IDs help Playwright tests wait for and assert on loading states.
♻️ Suggested addition
{!swaggerReady && ( <div className="absolute inset-0 flex items-center justify-center gap-2" style={{ background: theme.bg }} + data-testid="spec-preview-loading" >🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-app/src/components/ApiSpecPanel/SpecViewer.js` around lines 159 - 168, The loader overlay div in the SpecViewer component that displays when swaggerReady is false is missing a data-testid attribute. Add a descriptive data-testid attribute (such as "spec-loader-overlay" or "swagger-loader-overlay") to the outer div element that has the className "absolute inset-0 flex items-center justify-center gap-2" and the style prop with theme.bg background. This will allow Playwright tests to properly wait for and assert on the loading state.Source: Coding guidelines
packages/bruno-electron/src/app/apiSpecs.js (1)
17-40: ⚡ Quick winValidation logic is sound.
Extension check, JSON/YAML parsing fallback, and OpenAPI/Swagger structure assertion are all correctly implemented. The
yaml.loaddefault in js-yaml v4.x uses the safe schema.One improvement: consider returning the parsed spec from
validateApiSpecto avoid re-parsing the file later (lines 116-124 duplicate this work).♻️ Suggested refactor to return parsed spec
-const validateApiSpec = (filePath) => { +const validateApiSpec = (filePath) => { const ext = path.extname(filePath).toLowerCase(); if (!VALID_API_SPEC_EXTENSIONS.includes(ext)) { throw new Error('Invalid file format. Please select a valid OpenAPI spec in YAML or JSON format.'); } const content = fs.readFileSync(filePath, 'utf8'); let parsed; try { parsed = ext === '.json' ? JSON.parse(content) : yaml.load(content); } catch { throw new Error('Invalid file format. Please select a valid OpenAPI spec in YAML or JSON format.'); } if (!parsed || typeof parsed !== 'object') { throw new Error('Invalid file format. Please select a valid OpenAPI spec in YAML or JSON format.'); } const hasSpecVersion = typeof parsed.openapi === 'string' || typeof parsed.swagger === 'string'; if (!hasSpecVersion || typeof parsed.info !== 'object' || parsed.info === null) { throw new Error('Invalid OpenAPI spec. The file must contain a valid OpenAPI (3.x) or Swagger (2.0) specification.'); } + + return { content, parsed }; };Then update the call site to reuse the parsed result instead of re-reading and re-parsing.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-electron/src/app/apiSpecs.js` around lines 17 - 40, The validateApiSpec function currently only validates and throws errors but doesn't return the parsed spec object, causing the call site to duplicate the parsing work by re-reading and re-parsing the file. Modify validateApiSpec to return the parsed spec object at the end of the function instead of implicitly returning undefined, then update the call site (around lines 116-124 where duplicate parsing occurs) to reuse the returned parsed result from validateApiSpec instead of re-reading and re-parsing the file.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@packages/bruno-app/src/components/ApiSpecPanel/SpecViewer.js`:
- Around line 144-153: The error overlay container in the previewError condition
does not have a data-testid attribute required for Playwright testing. Add a
data-testid attribute to the outer div element that contains the error message
display (the one with className="absolute inset-0 flex items-center
justify-center p-8") with an appropriate identifier such as "spec-preview-error"
to make the error overlay testable.
- Around line 159-168: The loader overlay div in the SpecViewer component that
displays when swaggerReady is false is missing a data-testid attribute. Add a
descriptive data-testid attribute (such as "spec-loader-overlay" or
"swagger-loader-overlay") to the outer div element that has the className
"absolute inset-0 flex items-center justify-center gap-2" and the style prop
with theme.bg background. This will allow Playwright tests to properly wait for
and assert on the loading state.
In `@packages/bruno-electron/src/app/apiSpecs.js`:
- Around line 17-40: The validateApiSpec function currently only validates and
throws errors but doesn't return the parsed spec object, causing the call site
to duplicate the parsing work by re-reading and re-parsing the file. Modify
validateApiSpec to return the parsed spec object at the end of the function
instead of implicitly returning undefined, then update the call site (around
lines 116-124 where duplicate parsing occurs) to reuse the returned parsed
result from validateApiSpec instead of re-reading and re-parsing the file.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 47a2a238-a2f7-4635-99cc-9343ba6a8f63
📒 Files selected for processing (2)
packages/bruno-app/src/components/ApiSpecPanel/SpecViewer.jspackages/bruno-electron/src/app/apiSpecs.js
6d91fed to
8c8181c
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
packages/bruno-app/src/components/ApiSpecPanel/SpecViewer.js (1)
149-175: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd stable test selectors for the new error/loading preview states.
These new user-visible states are core behavior and should expose
data-testidhooks for Playwright assertions.
As per coding guidelines, “Adddata-testidto testable elements for Playwright in React components.”🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-app/src/components/ApiSpecPanel/SpecViewer.js` around lines 149 - 175, Add data-testid attributes to the two new preview state sections in the SpecViewer component to enable Playwright testing. Specifically, add a data-testid attribute to the outer div that displays when previewError is truthy (the error state container) and add another data-testid attribute to the div that displays when swaggerReady is false (the loading state container with the spinner and "Generating preview" text). These test selectors should have descriptive names that clearly identify each state for testing purposes.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/bruno-app/src/components/ApiSpecPanel/SpecViewer.js`:
- Around line 13-29: The getPreviewParseError function accepts any parsed object
without validating required OpenAPI specification fields, allowing structurally
invalid specs like {"foo":1} to bypass validation and cause downstream timeout
errors. After the existing object type check in getPreviewParseError, add
validation to ensure the parsed object contains the required OpenAPI fields:
either an openapi or swagger field, plus an info object. Return an appropriate
error message if these required fields are missing to catch invalid
specifications upfront.
In `@packages/bruno-electron/src/app/apiSpecs.js`:
- Around line 17-22: The validateApiSpec function currently only validates the
file extension but does not validate the actual content of the OpenAPI
specification. To fix this, enhance the validateApiSpec function to not only
check that the file extension is valid (YAML or JSON) but also parse and
validate the actual file content to ensure it is a valid OpenAPI document. If
the file content is malformed, missing required OpenAPI fields, or is not a
valid OpenAPI specification, throw an appropriate error before the workspace is
mutated. This will prevent invalid or malformed specs from being added or opened
downstream.
---
Nitpick comments:
In `@packages/bruno-app/src/components/ApiSpecPanel/SpecViewer.js`:
- Around line 149-175: Add data-testid attributes to the two new preview state
sections in the SpecViewer component to enable Playwright testing. Specifically,
add a data-testid attribute to the outer div that displays when previewError is
truthy (the error state container) and add another data-testid attribute to the
div that displays when swaggerReady is false (the loading state container with
the spinner and "Generating preview" text). These test selectors should have
descriptive names that clearly identify each state for testing purposes.
🪄 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: 6701dc3c-3d8b-42ad-bdaf-25692c3237ae
📒 Files selected for processing (3)
packages/bruno-app/src/components/ApiSpecPanel/SpecViewer.jspackages/bruno-electron/src/app/apiSpecs.jspackages/bruno-electron/src/app/apiSpecsWatcher.js
8c8181c to
080e0f6
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
packages/bruno-app/src/components/ApiSpecPanel/SpecViewer.js (1)
153-179: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd
data-testidhooks to the new preview states.This PR's whole value is the error/timeout/loader states, yet none are addressable by Playwright. Tagging the overlay and loader keeps the new behaviour testable without brittle text selectors.
🧪 Suggested test ids
- {previewError ? ( - <div - className="absolute inset-0 flex items-center justify-center p-8" + {previewError ? ( + <div + data-testid="spec-preview-error" + className="absolute inset-0 flex items-center justify-center p-8" style={{ background: theme.bg }} > @@ - {!swaggerReady && ( - <div - className="absolute inset-0 flex items-center justify-center gap-2" + {!swaggerReady && ( + <div + data-testid="spec-preview-loader" + className="absolute inset-0 flex items-center justify-center gap-2" style={{ background: theme.bg }} >As per coding guidelines: "Add
data-testidto testable elements for Playwright in React components".🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-app/src/components/ApiSpecPanel/SpecViewer.js` around lines 153 - 179, The preview error, loader, and timeout overlay states in SpecViewer are not directly selectable in Playwright. Add stable data-testid hooks to the preview state elements in the preview render branch of SpecViewer (the previewError overlay, the Swagger loading wrapper/overlay, and the “Generating preview…” loader container) so tests can target these states without relying on text or layout selectors.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/bruno-app/src/components/ApiSpecPanel/SpecViewer.js`:
- Line 24: The user-facing error message in SpecViewer should be reworded to
remove the awkward article before “valid YAML or JSON.” Update the return string
in the preview-rendering logic so it reads naturally, keeping the same meaning
but using “valid YAML or JSON” wording without “a” in the message returned by
the SpecViewer component.
---
Nitpick comments:
In `@packages/bruno-app/src/components/ApiSpecPanel/SpecViewer.js`:
- Around line 153-179: The preview error, loader, and timeout overlay states in
SpecViewer are not directly selectable in Playwright. Add stable data-testid
hooks to the preview state elements in the preview render branch of SpecViewer
(the previewError overlay, the Swagger loading wrapper/overlay, and the
“Generating preview…” loader container) so tests can target these states without
relying on text or layout selectors.
🪄 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: f733e2b4-9904-4862-8f8c-977dda123b3a
📒 Files selected for processing (3)
packages/bruno-app/src/components/ApiSpecPanel/SpecViewer.jspackages/bruno-electron/src/app/apiSpecs.jspackages/bruno-electron/src/app/apiSpecsWatcher.js
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/bruno-electron/src/app/apiSpecsWatcher.js
- packages/bruno-electron/src/app/apiSpecs.js
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
tests/import/openapi/api-spec-panel-validation.spec.ts (1)
48-48: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReplace class-based spec item selectors with stable locator variables.
Using
.api-spec-item+ text filters is brittle in E2E; prefer explicitdata-testid/role locators and store them in variables.As per path instructions, “Replace brittle text/index selectors with role, label, test id, or stable user-facing selectors” and “Use locator variables for locators.” As per coding guidelines, “Add
data-testidto testable elements for Playwright in React components.”Also applies to: 65-65, 82-82, 101-101
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/import/openapi/api-spec-panel-validation.spec.ts` at line 48, The Playwright spec currently uses brittle class-based text filters for API spec items, so update the tests to use stable locators instead. In api-spec-panel-validation.spec.ts, replace the .api-spec-item + hasText selectors with explicit role/data-testid-based locators, and store each locator in a variable before interacting with it. If the needed test ids do not exist yet, add data-testid attributes in the relevant React component for the spec items so the tests can target them reliably; apply the same locator refactor to the other affected occurrences in this spec.Sources: Coding guidelines, Path instructions
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@tests/import/openapi/api-spec-panel-validation.spec.ts`:
- Around line 7-19: The `showOpenDialog` save/restore logic is using a test-file
variable outside the Electron context, so `originalShowOpenDialog` is never
reliably preserved. Update the `beforeAll` and `afterAll` logic around
`electronApp.evaluate` to capture and restore the original
`dialog.showOpenDialog` within the same Electron context, or stash it directly
on `dialog`, so later tests don’t inherit the monkey patch.
---
Nitpick comments:
In `@tests/import/openapi/api-spec-panel-validation.spec.ts`:
- Line 48: The Playwright spec currently uses brittle class-based text filters
for API spec items, so update the tests to use stable locators instead. In
api-spec-panel-validation.spec.ts, replace the .api-spec-item + hasText
selectors with explicit role/data-testid-based locators, and store each locator
in a variable before interacting with it. If the needed test ids do not exist
yet, add data-testid attributes in the relevant React component for the spec
items so the tests can target them reliably; apply the same locator refactor to
the other affected occurrences in this spec.
🪄 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: 9bdb1360-1094-4adf-833a-4b0189954932
📒 Files selected for processing (4)
packages/bruno-electron/tests/app/apiSpecs.spec.jstests/import/openapi/api-spec-panel-validation.spec.tstests/import/openapi/fixtures/openapi-empty.yamltests/import/openapi/fixtures/openapi-invalid-extension.txt
✅ Files skipped from review due to trivial changes (1)
- tests/import/openapi/fixtures/openapi-invalid-extension.txt
80851bd to
d8f6a95
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/bruno-app/src/components/ApiSpecPanel/SpecViewer.js (1)
83-115: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoffConsider extracting the preview validation + timeout into a custom hook.
The parse/empty/timeout side-effect plus its ref and
handleSwaggerCompleteare self-contained business logic. Moving them into something likeusePreviewValidation(content)returning{ previewError, swaggerReady, onSwaggerComplete }keepsSpecViewerdeclarative and isolates the effect.As per coding guidelines: "Prefer custom hooks for business logic, data fetching, and side-effects in React" and "Avoid
useEffectunless absolutely needed."🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-app/src/components/ApiSpecPanel/SpecViewer.js` around lines 83 - 115, The preview validation, timeout handling, and Swagger completion logic in SpecViewer are self-contained and should be moved out of the component. Extract the useEffect, previewTimeoutRef, and handleSwaggerComplete behavior into a custom hook such as usePreviewValidation(content) that returns previewError, swaggerReady, and onSwaggerComplete. Keep SpecViewer focused on rendering and wire it to the hook’s returned state and callback.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@packages/bruno-app/src/components/ApiSpecPanel/SpecViewer.js`:
- Around line 83-115: The preview validation, timeout handling, and Swagger
completion logic in SpecViewer are self-contained and should be moved out of the
component. Extract the useEffect, previewTimeoutRef, and handleSwaggerComplete
behavior into a custom hook such as usePreviewValidation(content) that returns
previewError, swaggerReady, and onSwaggerComplete. Keep SpecViewer focused on
rendering and wire it to the hook’s returned state and callback.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 3fa5e075-dac1-43b1-b49f-afdfc47c1a73
📒 Files selected for processing (8)
packages/bruno-app/src/components/ApiSpecPanel/SpecViewer.jspackages/bruno-app/src/components/ApiSpecPanel/constants.tspackages/bruno-electron/src/app/apiSpecs.jspackages/bruno-electron/src/app/apiSpecsWatcher.jspackages/bruno-electron/tests/app/apiSpecs.spec.jstests/import/openapi/api-spec-panel-validation.spec.tstests/import/openapi/fixtures/openapi-empty.yamltests/import/openapi/fixtures/openapi-invalid-extension.txt
✅ Files skipped from review due to trivial changes (2)
- tests/import/openapi/fixtures/openapi-invalid-extension.txt
- packages/bruno-app/src/components/ApiSpecPanel/constants.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- packages/bruno-electron/src/app/apiSpecsWatcher.js
- tests/import/openapi/api-spec-panel-validation.spec.ts
- packages/bruno-electron/src/app/apiSpecs.js
d8f6a95 to
590944f
Compare
arpit-bruno
left a comment
There was a problem hiding this comment.
Few gaps:
- we test malformed YAML files but not broken JSONs
- the happy path is only asserted with openapi-simple.json, can we add one case for a valid yaml too
590944f to
5a2965a
Compare
5a2965a to
37ed729
Compare
…tate instead of hanging
37ed729 to
a1d8944
Compare
* fix(openapi):validate API spec imports and resolve preview to error state instead of hanging * fix(openapi):allows opening of malformed files with correct extension * fix(openapi):reject non-OpenAPI content in spec preview before timeout * test(openapi): add unit + e2e coverage for spec import validation * refactor(openapi):centralise spec error messages and fix dialog restore * fix:removed nested try catch * test:added common locators * refactor:removed repeated lines * refactor:removed redundant file reads --------- Co-authored-by: Adwait Aayush <[email protected]>
Description
JIRA:https://usebruno.atlassian.net/browse/BRU-3622
Earlier, the spec viewer accepted any type of file. To resolve this, the following changes have been made:
1)Added filters so only .json, .yaml, and .yml files can be selected.
2)If a user bypasses the first validation stage, the frontend (SpecViewer.js) also validates the file content.
3)In case of a very large file, a 15-second timeout triggers an error state instead of an infinite loading state.
Contribution Checklist:
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
Release Notes
New Features
Bug Fixes
Tests