Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Show full location (including parents) of items in search results #347

Conversation

Tom-stack3
Copy link
Contributor

@Tom-stack3 Tom-stack3 commented Nov 23, 2024

What type of PR is this?

  • feature

What this PR does / why we need it:

  • Pass locationFlatTree from frontend/pages/items.vue to frontend/components/Item/Card.vue in order to display full location (including parents).
  • Added item.location.name as a fallback in case the location wasn't found in locationFlatTree

Which issue(s) this PR fixes:

Fixes #344

Special notes for your reviewer:

Maybe need to think on limiting the length displayed. If the chain is too long we might consider shortening it in some way, or just show the location without its parents. Wasn't sure what to decide, so left it to review.

Testing

Created items under nested locations, and saw that it looks fine.

Before

Before screenshot

After

Before screenshot

Summary by CodeRabbit

  • New Features

    • Enhanced item card to display location information using a new locationFlatTree prop.
    • Improved item listing component with robust error handling and retry mechanism for loading locations.
  • Bug Fixes

    • Updated search function to reset items and notify users upon search failures.
  • Documentation

    • Updated prop definitions and method signatures for better clarity on component usage.

Copy link
Contributor

coderabbitai bot commented Nov 23, 2024

Walkthrough

The changes in this pull request enhance the Card.vue and items.vue components to better handle and display location data. A new required prop, locationFlatTree, is introduced to Card.vue, allowing for a computed property that generates a location string based on this prop. In items.vue, the ItemCard component is updated to accept this new prop, alongside improvements to the data loading mechanism and error handling in the search functionality.

Changes

File Change Summary
frontend/components/Item/Card.vue Added prop locationFlatTree (required) and computed property locationString for location display.
frontend/pages/items.vue Updated ItemCard to include :location-flat-tree prop; modified onMounted for retry logic and enhanced error handling in search.

Assessment against linked issues

Objective Addressed Explanation
Show parent locations of an item in search results (#344) The changes do not implement the display of parent locations in search results.

Possibly related PRs

Security Recommendations

  • Ensure that any data passed through the locationFlatTree prop is validated and sanitized to prevent potential injection attacks.
  • Implement error handling for API calls to safeguard against unexpected failures that could expose sensitive data or lead to application crashes.

Warning

Rate limit exceeded

@Tom-stack3 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 17 minutes and 6 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 8afa69f and 674cc2b.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8afa69f and 674cc2b.

📒 Files selected for processing (1)
  • frontend/components/Item/Card.vue (2 hunks)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@Tom-stack3 Tom-stack3 force-pushed the enhancement/show-parent-locations branch from 43e9794 to 8afa69f Compare November 23, 2024 14:53
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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (6)
frontend/components/Item/Card.vue (2)

70-74: Add validation for locationFlatTree prop

While the prop is correctly typed, consider adding runtime validation to ensure the array elements contain the expected properties, especially id and treeString which are used in the computed property.

Consider adding a validator:

    locationFlatTree: {
      type: Array as () => FlatTreeItem[],
      required: true,
+     validator: (value: FlatTreeItem[]) => {
+       return value.every(item => 
+         typeof item.id === 'string' && 
+         typeof item.treeString === 'string'
+       );
+     }
    },

Line range hint 46-51: Review security considerations for dynamic URLs

Several security considerations for URL handling:

  1. Image URL construction should validate item.id and item.imageId
  2. Navigation links should validate IDs before routing
  3. Consider implementing Content Security Policy (CSP) headers

Consider implementing URL validation:

  const imageUrl = computed(() => {
    if (!props.item.imageId) {
      return "/no-image.jpg";
    }

+   // Validate IDs to prevent path traversal
+   const itemId = validateId(props.item.id);
+   const imageId = validateId(props.item.imageId);
+   if (!itemId || !imageId) return "/no-image.jpg";

-   return api.authURL(`/items/${props.item.id}/attachments/${props.item.imageId}`);
+   return api.authURL(`/items/${itemId}/attachments/${imageId}`);
  });
frontend/pages/items.vue (4)

Line range hint 63-93: Add input validation for URL parameters

The current implementation directly uses query parameters without proper validation. This could lead to XSS vulnerabilities if malicious data is injected into the URL.

Consider adding validation:

    const qLoc = route.query.loc as string[];
    if (qLoc) {
+     // Validate location IDs format and existence
+     const validLocations = qLoc.every(id => /^[a-zA-Z0-9-]+$/.test(id));
+     if (!validLocations) {
+       console.error('Invalid location IDs detected');
+       return;
+     }
      selectedLocations.value = locations.value.filter(l => qLoc.includes(l.id));
    }

Line range hint 284-331: Enhance search function security

The search function accepts user input without proper sanitization and lacks rate limiting.

Consider implementing:

  1. Input sanitization
  2. Rate limiting
  3. Maximum query length validation
  async function search() {
    if (searchLocked.value) {
      return;
    }

+   // Add rate limiting
+   if (!canMakeRequest()) {
+     toast.error("Too many requests. Please wait.");
+     return;
+   }

+   // Validate query length
+   if (query.value && query.value.length > 100) {
+     toast.error("Search query too long");
+     return;
+   }

    loading.value = true;

Line range hint 333-368: Secure URL parameter handling

The current implementation allows direct manipulation of URL parameters without proper sanitization.

Add validation before pushing to router:

  async function submit() {
    const fields = [];
    for (const t of fieldTuples.value) {
-     if (t[0] && t[1]) {
+     if (t[0] && t[1] && isValidFieldValue(t[0], t[1])) {
        fields.push(`${t[0]}=${t[1]}`);
      }
    }

+   // Sanitize values before pushing to URL
+   const sanitizedQuery = sanitizeInput(query.value);
+   const sanitizedPageSize = Math.min(100, Math.max(1, pageSize.value));

Line range hint 1-585: General Security Recommendations

Consider implementing these security measures across the component:

  1. Add Content Security Policy (CSP) headers
  2. Implement CSRF protection for API calls
  3. Add input length limits for all user inputs
  4. Implement proper error logging
  5. Add rate limiting for search operations
  6. Sanitize all user inputs before processing
  7. Implement proper session handling
  8. Add security headers (X-Frame-Options, X-XSS-Protection, etc.)

Would you like me to provide specific implementation details for any of these security measures?

🛑 Comments failed to post (2)
frontend/components/Item/Card.vue (1)

76-78: 🛠️ Refactor suggestion

Handle missing locations and implement length limiting

Two improvements needed for the locationString computed property:

  1. Add a fallback for when location is not found
  2. Implement length limiting as mentioned in the PR objectives

Consider this implementation:

  const locationString = computed(() => {
-   return props.locationFlatTree.find(l => l.id === props.item.location.id)?.treeString;
+   const location = props.locationFlatTree.find(l => l.id === props.item.location.id);
+   if (!location?.treeString) return 'Unknown location';
+   
+   // Limit to last 3 segments if too long
+   const segments = location.treeString.split(' > ');
+   if (segments.length > 3) {
+     return '... > ' + segments.slice(-3).join(' > ');
+   }
+   return location.treeString;
  });
📝 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.

const locationString = computed(() => {
    const location = props.locationFlatTree.find(l => l.id === props.item.location.id);
    if (!location?.treeString) return 'Unknown location';
    
    // Limit to last 3 segments if too long
    const segments = location.treeString.split(' > ');
    if (segments.length > 3) {
      return '... > ' + segments.slice(-3).join(' > ');
    }
    return location.treeString;
  });
frontend/pages/items.vue (1)

477-477: ⚠️ Potential issue

Protect against XSS in template rendering

When passing the locationFlatTree to ItemCard, ensure proper HTML escaping is in place.

Consider using Vue's built-in XSS protection:

-        <ItemCard v-for="item in items" :key="item.id" :item="item" :location-flat-tree="locationFlatTree" />
+        <ItemCard
+          v-for="item in items"
+          :key="item.id"
+          :item="item"
+          :location-flat-tree="sanitizeLocationTree(locationFlatTree)"
+          v-bind="$attrs"
+        />

Committable suggestion skipped: line range outside the PR's diff.

@Tom-stack3 Tom-stack3 marked this pull request as ready for review November 23, 2024 15:06
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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (2)
frontend/components/Item/Card.vue (2)

70-74: Add type validation for locationFlatTree prop

The prop definition looks good, but consider adding runtime validation to ensure data integrity.

Consider adding validator function:

    locationFlatTree: {
      type: Array as () => FlatTreeItem[],
      required: true,
+     validator: (value: FlatTreeItem[]) => {
+       return value.every(item => 
+         typeof item.id === 'string' && 
+         typeof item.treeString === 'string'
+       );
+     }
    },

Line range hint 1-90: Security Review: URL Construction and Navigation

The component uses several dynamic URLs that could be security-sensitive:

  1. /item/${item.id}
  2. /location/${item.location.id}
  3. Image URL construction in imageUrl computed property

Ensure that:

  1. The IDs are properly validated before being used in URLs
  2. The authURL helper implements proper URL encoding
  3. Consider implementing URL sanitization middleware
🛑 Comments failed to post (2)
frontend/components/Item/Card.vue (2)

76-77: ⚠️ Potential issue

Add null check for item.location

The computed property needs defensive programming to handle cases where item.location might be null.

Apply this fix:

  const locationString = computed(() => {
-   return props.locationFlatTree.find(l => l.id === props.item.location.id)?.treeString || props.item.location.name;
+   if (!props.item.location) return '';
+   return props.locationFlatTree.find(l => l.id === props.item.location.id)?.treeString || props.item.location.name;
  });
📝 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.

  const locationString = computed(() => {
    if (!props.item.location) return '';
    return props.locationFlatTree.find(l => l.id === props.item.location.id)?.treeString || props.item.location.name;

17-17: ⚠️ Potential issue

Ensure XSS protection for location display

While the change from item.location.name to locationString improves functionality, we should ensure proper sanitization of the location string before rendering.

Consider using Vue's built-in escaping or a sanitization library:

-          {{ locationString }}
+          {{ $sanitize(locationString) }}

Committable suggestion skipped: line range outside the PR's diff.

@Tom-stack3
Copy link
Contributor Author

I see that the Lint check has failed in the typecheck stage, but I don't really understand the output of it. So I'm not sure how to fix it :(
Would love the help of someone here 🙃

@tonyaellie
Copy link
Collaborator

Looks like an issue with a typescript update breaking vue-tsc, vuejs/language-tools#5018. I think just ignore it for now @tankerkiller125?

@tankerkiller125 tankerkiller125 merged commit 121d577 into sysadminsmedia:main Nov 27, 2024
7 of 8 checks passed
@adamkleizer
Copy link
Contributor

adamkleizer commented Nov 28, 2024

Well, this seems to have broken all other ItemCard component instances except the search page since locationFlatTree isn't set there.

Need to make locationFlatTree optional in Card.vue and use withDefaults:

  type Props = {
    item: ItemOut | ItemSummary;
    locationFlatTree?: FlatTreeItem[];
  };
 //......
 const props = withDefaults(defineProps<Props>(), {
    locationFlatTree: () => [],
  });

@tankerkiller125
Copy link
Contributor

Somehow, I didn't catch that, and the tests (mostly) all passed. That's for the quick fix I'll get that sorted here in a bit.

tankerkiller125 added a commit that referenced this pull request Nov 29, 2024
Sets the locationFlatTree to be an optional prop for the Card component. With a default of an empty array.
@Tom-stack3
Copy link
Contributor Author

Sadly, I missed it. Sorry for the trouble, and thanks for the fix @adamkleizer @tankerkiller125 :)

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.

Show Parent Locations of an item in search results
4 participants