Skip to content

web : fix filters#11

Open
surajmn1 wants to merge 2 commits intomainfrom
fix/web/filters
Open

web : fix filters#11
surajmn1 wants to merge 2 commits intomainfrom
fix/web/filters

Conversation

@surajmn1
Copy link
Copy Markdown
Contributor

@surajmn1 surajmn1 commented Oct 1, 2025

Summary by CodeRabbit

  • Bug Fixes
    • Improved stability of the dataset preview by safely handling missing data, preventing runtime errors and ensuring pagination states reflect empty or unavailable data correctly.
    • Enhanced dataset table queries by properly quoting and escaping string filter values, preventing malformed requests and ensuring filters with special characters work reliably.
  • Accessibility
    • Pagination controls now more accurately reflect disabled states when data is unavailable or empty, improving clarity for assistive technologies.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Oct 1, 2025

Walkthrough

Updates add null-safe rendering in the dataset preview component using optional chaining and adjust query construction to quote and escape string filter values before requesting table data.

Changes

Cohort / File(s) Summary
UI null-safety in data preview
web/src/components/dataset/data-preview.tsx
Replaced direct accesses with optional chaining for dataset length checks, table mapping, and pagination aria-disabled states to avoid runtime errors when data is undefined.
Filter serialization in table query
web/src/lib/queries/dataset/get-table.ts
Modified filter value serialization: string values are now single-quoted and internal quotes escaped (' -> ''); non-strings remain unchanged. Search params structure preserved with adjusted value formatting.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant UI as DataPreview Component
  participant QB as Query Builder (get-table)
  participant API as Dataset API

  UI->>QB: buildRequest(filters)
  Note right of QB: If filter value is string<br/>→ wrap in single quotes<br/>→ escape internal ' as '' 
  QB->>API: GET /table?filters=...
  API-->>QB: JSON { data: [...] }
  QB-->>UI: data or undefined (pending)
  UI->>UI: Render with optional chaining<br/>data?.data?.map(...) and guards
  Note over UI: Prevents runtime errors when data is undefined
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

I twitch my whiskers at quotes made neat,
Two ticks for one—an escaping treat!
I hop through tables, guards in view,
No crashes now, just data true.
With queries crisp and renders light,
This bunny ships the bytes just right. 🥕✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Title Check ❓ Inconclusive The title “web : fix filters” briefly references one subset of the changes (filter handling) but is vague and does not capture the full scope of this PR, which also introduces optional chaining guards in the DataPreview component. It lacks specificity about what filters are being fixed and omits the data-preview updates. Consider revising the title to clearly reflect both key changes, for example “Guard against undefined data in DataPreview and escape string values in filter queries,” to ensure it accurately and comprehensively conveys the PR’s intent.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/web/filters

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.

@claude
Copy link
Copy Markdown

claude Bot commented Oct 1, 2025

Claude finished @surajmn1's task —— View job


PR Review Analysis

Todo List:

  • Read and analyze changed files
  • Review code quality and best practices
  • Check for potential bugs or issues
  • Assess performance considerations
  • Identify security concerns
  • Evaluate test coverage needs
  • Provide comprehensive feedback

📋 Review Summary

This PR implements important fixes for the filter functionality in the data preview component. The changes address both null safety issues and string escaping for SQL injection prevention.

✅ Positive Changes

1. Null Safety Improvements (web/src/components/dataset/data-preview.tsx:584, 617, 670, 672)

  • Added optional chaining (?.) to prevent runtime errors when data is undefined
  • Consistent pattern applied across all data access points
  • Prevents crashes during loading states or API failures

2. SQL Injection Protection (web/src/lib/queries/dataset/get-table.ts:37-44)

  • Implemented proper string escaping for filter values
  • Single quotes are escaped by doubling them (''')
  • Only applies escaping to string values (type checking with typeof)

🔍 Code Quality Assessment

Good Practices:

  • Type-safe implementation with proper TypeScript usage
  • Defensive programming with null checks
  • Security-conscious string handling

Minor Issues:

  1. File Ending (data-preview.tsx:683): Missing newline at end of file
  2. Complex Logic: The filter mapping logic could benefit from extraction to a helper function for better readability

🛡️ Security Analysis

✅ Security Improvements:

  • SQL Injection Prevention: The string escaping in get-table.ts:39 properly handles single quotes
  • Input Sanitization: Filter values are sanitized before being sent to the API

⚠️ Security Considerations:

  • The escaping logic assumes SQL context - ensure backend expects this format
  • Consider additional validation for filter operators (e, gt, lt) to prevent injection through operator field

🚀 Performance Impact

  • Minimal Performance Impact: Changes are lightweight and don't affect rendering performance
  • API Efficiency: No changes to API call frequency or payload size
  • Memory Usage: Optional chaining adds negligible overhead

🧪 Test Coverage Recommendations

The following areas should have test coverage:

  1. Null Safety Tests:

    // Test data preview with undefined/null data
    it('should handle undefined data gracefully', () => {
      // Test optional chaining behavior
    });
  2. Filter Escaping Tests:

    // Test SQL injection prevention
    it('should escape single quotes in filter values', () => {
      const filterValue = "O'Reilly";
      // Verify escaping produces "O''Reilly"
    });
  3. Edge Cases:

    • Empty filter arrays
    • Special characters in column names
    • Non-string filter values

📝 Recommendations

  1. Extract Helper Function: Consider extracting the filter formatting logic to improve readability:

    const formatFilterValue = (value: string): string => {
      const needsQuotes = typeof value === "string";
      return needsQuotes ? `'${value.replace(/'/g, "''")}'` : value;
    };
  2. Add Input Validation: Consider validating filter operators on the client side

  3. Documentation: Add JSDoc comments explaining the escaping strategy

🎯 Overall Assessment

Score: 8/10

This is a solid PR that addresses critical null safety and security concerns. The changes are focused, well-implemented, and follow TypeScript best practices. The SQL injection prevention is particularly important for a data filtering feature.

Approval Recommendation: ✅ Approve after addressing the minor file ending issue


Copy link
Copy Markdown
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

Caution

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

⚠️ Outside diff range comments (1)
web/src/components/dataset/data-preview.tsx (1)

584-591: Simplify empty‐state condition

The useGetTable fetcher always returns an object with a data array on success, and React Query’s data is only undefined during loading (already gated by the isLoading check). The !data guard is therefore redundant. Replace

!data || data?.data?.length === 0

with

data.data.length === 0

—or, to preserve null‐safety, data?.data.length === 0.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d42cdfb and d25b958.

📒 Files selected for processing (2)
  • web/src/components/dataset/data-preview.tsx (4 hunks)
  • web/src/lib/queries/dataset/get-table.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
web/src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (web/CLAUDE.md)

Use TypeScript throughout the web frontend (no plain .js for app code)

Files:

  • web/src/components/dataset/data-preview.tsx
  • web/src/lib/queries/dataset/get-table.ts
web/src/components/**/*.tsx

📄 CodeRabbit inference engine (web/CLAUDE.md)

web/src/components/**/*.tsx: Prefer Radix UI components with TailwindCSS for styling in React components
Use React Hook Form with Zod validation for forms

Files:

  • web/src/components/dataset/data-preview.tsx
web/src/components/dataset/data-preview.tsx

📄 CodeRabbit inference engine (web/CLAUDE.md)

Load DuckDB WASM on demand (lazy/dynamic load) to minimize initial bundle

Files:

  • web/src/components/dataset/data-preview.tsx
web/src/{app,components}/**/*.tsx

📄 CodeRabbit inference engine (web/CLAUDE.md)

Use Next.js Image component for images to enable optimization instead of plain img for local assets

Files:

  • web/src/components/dataset/data-preview.tsx
web/src/lib/queries/**/*.ts

📄 CodeRabbit inference engine (web/CLAUDE.md)

Implement data fetching with React Query in src/lib/queries (queries only)

Files:

  • web/src/lib/queries/dataset/get-table.ts
web/src/lib/{queries,mutations}/**/*.ts

📄 CodeRabbit inference engine (web/CLAUDE.md)

web/src/lib/{queries,mutations}/**/*.ts: Use the pre-configured Ky client from src/lib/api-client when making API calls in queries/mutations
Use generated API response types for type safety in queries and mutations

Files:

  • web/src/lib/queries/dataset/get-table.ts
🔇 Additional comments (3)
web/src/components/dataset/data-preview.tsx (2)

617-631: LGTM - consistent null-safe access pattern.

The optional chaining on data is consistent with the check at line 584. While technically redundant (since this branch is only reached when data exists), it's good defensive programming and won't cause issues.


670-675: Correct pagination disable logic.

The added !data check ensures the Next button is properly disabled when data hasn't loaded yet, preventing incorrect button states. The logic correctly identifies the last page by checking if fewer rows than rowsPerPage were returned.

web/src/lib/queries/dataset/get-table.ts (1)

38-39: Verify if manual SQL escaping is necessary or appropriate.

The single-quote doubling pattern ('') is standard SQL string escaping, but this raises questions:

  1. Is the backend using parameterized queries? If yes, this manual escaping is unnecessary and the backend should handle it. Parameterized queries are the correct defense against SQL injection.

  2. Is this escaping compatible with the API's query parameter format? Query parameters might expect URL encoding or JSON encoding rather than SQL-escaped strings.

  3. Does this actually prevent injection? If filter values are interpolated directly into SQL on the backend (which would be a backend security issue), this escaping might help but is not a complete solution—other characters like --, ;, \ etc. might still be exploitable.

Check the backend implementation to confirm:

  • Whether it uses parameterized queries (recommended)
  • What format it expects for filter values in query parameters

Comment thread web/src/lib/queries/dataset/get-table.ts Outdated
@claude
Copy link
Copy Markdown

claude Bot commented Oct 1, 2025

Claude finished @surajmn1's task —— View job


PR Review Analysis

Todo List:

  • Read and analyze changed files
  • Review code quality and best practices
  • Check for potential bugs or issues
  • Assess performance considerations
  • Identify security concerns
  • Evaluate test coverage needs
  • Provide comprehensive feedback

📋 Review Summary

This PR implements important fixes for the filter functionality in the data preview component. The changes address both null safety issues and proper handling of undefined data states.

✅ Positive Changes

1. Null Safety Improvements (web/src/components/dataset/data-preview.tsx:584, 617, 670, 672)

  • Added optional chaining (?.) to prevent runtime errors when data is undefined
  • Consistent pattern applied across all data access points
  • Prevents crashes during loading states or API failures

2. Defensive Programming

  • Proper guards against undefined data in pagination logic
  • Safe access to nested data properties throughout the component

🔍 Code Quality Assessment

Good Practices:

  • Type-safe implementation with proper TypeScript usage
  • Defensive programming with null checks
  • Consistent use of optional chaining patterns

Areas for Improvement:

  1. File Ending (data-preview.tsx:683): Missing newline at end of file
  2. Redundant Checks: The condition !data || data?.data?.length === 0 could be simplified since the loading state is already handled
  3. Consistency: Some areas use optional chaining while others rely on explicit null checks

🚨 Critical Issue Found

⚠️ IMPORTANT: Based on the CodeRabbit review comments, there appears to be a critical issue with the filter implementation in get-table.ts. The current code shows:

filter.map((f) => [
  `filter[${f.column}]${f.operator === "e" ? "" : f.operator}`,
  f.value,
])

However, according to the CodeRabbit analysis, there was supposed to be string escaping logic that was incorrectly implemented and then removed. If string values are being passed directly to SQL queries without proper parameterization, this could create SQL injection vulnerabilities.

🛡️ Security Analysis

⚠️ Security Concerns:

  • Potential SQL Injection: Filter values appear to be passed directly without escaping or parameterization
  • Input Validation: No client-side validation of filter operators
  • Type Safety: Filter values are typed as string but may contain various data types

Recommendations:

  1. Ensure the backend uses parameterized queries for filter values
  2. Add input validation for filter operators and values
  3. Consider server-side sanitization if not already implemented

🚀 Performance Impact

  • Minimal Performance Impact: Changes are lightweight and don't affect rendering performance
  • API Efficiency: No changes to API call frequency or payload size
  • Memory Usage: Optional chaining adds negligible overhead

🧪 Test Coverage Recommendations

The following areas need test coverage:

  1. Null Safety Tests:

    it('should handle undefined data gracefully', () => {
      // Test component behavior when data is undefined
    });
  2. Edge Cases:

    • Empty data arrays
    • Pagination with undefined data
    • Filter validation and escaping
  3. Security Tests:

    it('should safely handle special characters in filter values', () => {
      // Test with various input including SQL injection attempts
    });

📝 Critical Recommendations

  1. Security Review: Immediately verify that the backend properly handles filter values with parameterized queries
  2. Add Input Validation: Implement client-side validation for filter inputs
  3. Documentation: Add JSDoc comments explaining the security model
  4. Testing: Add comprehensive tests for filter handling and edge cases

🎯 Overall Assessment

Score: 6/10 (downgraded due to potential security concerns)

While the null safety improvements are excellent, the potential SQL injection vulnerability in the filter system is a serious concern that needs immediate attention. The PR addresses important stability issues but may have introduced or exposed security risks.

Recommendation: ⚠️ Request Security Review - Verify backend filter handling before merging

🔧 Required Actions Before Merge

  1. Security audit of backend filter parameter handling
  2. Add input validation for filter values
  3. Fix missing newline at end of data-preview.tsx
  4. Add comprehensive tests for filter functionality

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant