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

fix: #289 Corrects the asset ID to always be correct for the descript… #351

Merged
merged 2 commits into from
Nov 29, 2024

Conversation

tankerkiller125
Copy link
Contributor

@tankerkiller125 tankerkiller125 commented Nov 29, 2024

What type of PR is this?

  • bug

What this PR does / why we need it:

Resolves the issue with item descriptions not matching the asset ids in the label generator

Which issue(s) this PR fixes:

Fixes: #289

Summary by CodeRabbit

Release Notes

  • New Features

    • Added assetId property to item summaries, enhancing item identification.
    • Updated label generation to utilize the new assetId, improving data handling.
  • Bug Fixes

    • Adjusted item processing logic to ensure correct asset ID usage in labels.
  • Documentation

    • Enhanced Swagger API documentation to include the new assetId property in item summaries.

Copy link
Contributor

coderabbitai bot commented Nov 29, 2024

Walkthrough

This pull request introduces modifications to the Swagger API documentation and related structures, primarily enhancing the repo.ItemSummary definition by adding a new property, assetId, which is a string type. The changes are reflected in multiple files, including docs.go, swagger.json, swagger.yaml, and openapi-2.0.json, ensuring that the API documentation remains consistent while enriching the data model. Additionally, the ItemSummary and ItemOut structures in repo_items.go are updated to accommodate this new property, and the label generation logic in the frontend is adjusted to utilize the new assetId.

Changes

File Path Change Summary
backend/app/api/static/docs/docs.go Added property assetId to repo.ItemSummary definition.
backend/app/api/static/docs/swagger.json Added property assetId to repo.ItemSummary definition.
backend/app/api/static/docs/swagger.yaml Added property assetId to repo.ItemSummary definition.
backend/internal/data/repo/repo_items.go Updated ItemSummary and ItemOut structures to include JSON tag for AssetID. Added sorting by assetId in QueryByGroup.
docs/docs/api/openapi-2.0.json Added property assetId to repo.ItemSummary definition.
frontend/lib/api/types/data-contracts.ts Added property assetId to ItemSummary interface.
frontend/pages/reports/label-generator.vue Updated getItem function to accept assetId, modified API call to order by assetId.

Assessment against linked issues

Objective Addressed Explanation
Ensure label generator displays correct asset ID (#289)

Possibly related PRs


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.

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: 5

🧹 Outside diff range and nitpick comments (7)
frontend/lib/api/types/data-contracts.ts (1)

Security Review: Access Controls Present, Rate Limiting Missing

Based on the code analysis:

  1. ✅ Access control is properly implemented:

    • All item operations verify group ownership via auth.GID
    • Repository methods enforce group-based access (GetOneByGroup, UpdateByGroup, etc.)
  2. ⚠️ Missing rate limiting:

    • No rate limiting implementation found for API endpoints
    • Could lead to potential DoS vulnerabilities
  3. 🔒 Recommendations:

    • Implement rate limiting middleware for API endpoints
    • Add request throttling for endpoints returning sensitive data
    • Consider adding logging for access to sensitive fields
🔗 Analysis chain

Line range hint 1-500: Security Advisory: Review Data Exposure

The interfaces in this file define the shape of data exchanged between frontend and backend. Consider the following security recommendations:

  1. Ensure sensitive fields (e.g., purchasePrice, serialNumber, warrantyDetails) are properly sanitized before transmission
  2. Implement rate limiting on API endpoints that return these data structures
  3. Add proper access control checks in the backend for each field
  4. Consider implementing field-level permissions to restrict access to sensitive data

Let's verify the exposure of sensitive fields in API responses:


Let me verify the access control implementation with one more check:

This will help verify if there are proper access controls and rate limiting in place before generating the final response about the security concerns.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential sensitive data exposure in API endpoints

# Search for API endpoint handlers that return ItemOut or ItemSummary
rg -A 5 "func.*Item(Out|Summary)"

# Search for access control checks around sensitive fields
rg -B 3 "purchasePrice|serialNumber|warrantyDetails"

Length of output: 29702


Script:

#!/bin/bash
# Check for authentication and authorization checks in API handlers and services

# Look for authentication middleware and group-based access control
rg -B 3 "func.*Items.*Group" backend/
rg -B 3 "auth.*GID" backend/

# Check for rate limiting implementation
rg -B 3 "rate.*limit|throttle" backend/

Length of output: 16587

frontend/pages/reports/label-generator.vue (1)

Line range hint 11-11: Security: Add URL validation for QR codes

The baseURL is used to generate QR codes but lacks validation. This could lead to malicious redirects if not properly sanitized.

Add URL validation:

 const api = useUserApi();
+const urlValidator = new RegExp('^https?:\\/\\/[\\w\\-]+(\\.[\\w\\-]+)+[/#?]?.*$');
 
 function getQRCodeUrl(assetID: string): string {
   let origin = displayProperties.baseURL.trim();
+  if (!urlValidator.test(origin)) {
+    notifier.error('Invalid base URL format');
+    return '';
+  }
   // remove trailing slash
   if (origin.endsWith("/")) {
     origin = origin.slice(0, -1);
   }
   const data = `${origin}/a/${assetID}`;
   return route(`/qrcode`, { data: encodeURIComponent(data) });
 }

Also applies to: 73-73, 146-146

backend/internal/data/repo/repo_items.go (1)

Security: Potential unauthorized item access vulnerability in GetOne method

The code analysis reveals a security concern in the item access implementation:

  1. The GetOne method allows direct item access without group ID validation:
func (e *ItemsRepository) GetOne(ctx context.Context, id uuid.UUID) (ItemOut, error) {
    return e.getOne(ctx, item.ID(id))  // No group validation!
}
  1. While other methods like GetOneByGroup properly validate group membership:
func (e *ItemsRepository) GetOneByGroup(ctx context.Context, gid, id uuid.UUID) (ItemOut, error) {
    return e.getOne(ctx, item.ID(id), item.HasGroupWith(group.ID(gid)))
}

Security recommendations:

  • Deprecate the unsafe GetOne method and enforce usage of GetOneByGroup
  • Add group validation in the getOne helper method as a required parameter
  • Consider adding middleware to validate group membership for all item operations
  • Add integration tests to verify group-based access control
🔗 Analysis chain

Line range hint 1-824: Security: Review SQL injection vectors and access controls

While reviewing the changes for the asset ID fix, I noticed some security considerations that should be addressed:

  1. Input Validation: Ensure that AssetID values are properly validated before database operations
  2. Access Control: Verify that the gid (group ID) check is consistently applied across all item operations
  3. SQL Injection: Although using an ORM (ent) provides some protection, verify that all user inputs are properly escaped

Let me analyze the security concerns by checking the group ID validation implementation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for potential missing group ID checks in item operations
echo "Checking for item operations without group ID validation..."
rg -A 5 "func.*Repository.*Item" | rg -v "HasGroupWith|group\.ID"

# Check for direct SQL operations that might bypass ORM safety
echo "Checking for direct SQL operations..."
rg "Raw|Exec.*\(.*\$|Query.*\(.*\$"

Length of output: 111167


Script:

#!/bin/bash
# Check GetOne implementation for group ID validation
echo "Checking GetOne implementation..."
ast-grep --pattern 'func (e *ItemsRepository) GetOne(ctx context.Context, id uuid.UUID) (ItemOut, error) {
  $$$
}'

# Check for group ID validation in getOne helper
echo -e "\nChecking getOne helper implementation..."
ast-grep --pattern 'func (e *ItemsRepository) getOne(ctx context.Context, where ...predicate.Item) (ItemOut, error) {
  $$$
}'

# Check for direct item access without group validation
echo -e "\nChecking for direct item access patterns..."
rg "item\.ID\(" -A 3 backend/internal/data/repo/repo_items.go

Length of output: 3289

backend/app/api/static/docs/swagger.json (2)

2282-2285: Enhance field documentation

The assetId field would benefit from additional documentation:

  • Add description field explaining the purpose and format
  • Document any constraints (e.g., format requirements, uniqueness)
  • Include examples of valid asset IDs
 "assetId": {
     "type": "string",
-    "example": "0"
+    "description": "Unique identifier for the asset in the system",
+    "example": "ASSET-001",
+    "pattern": "^[A-Za-z0-9-]+$",
+    "minLength": 1,
+    "maxLength": 50
 },

2282-2285: Add validation rules for asset IDs

Consider adding OpenAPI validation rules to ensure consistent asset ID format:

  • Pattern validation for allowed characters
  • Length constraints
  • Required/optional status
docs/docs/api/openapi-2.0.json (1)

2282-2285: Enhance API security for asset ID operations

The API endpoints handling asset IDs should implement rate limiting and access controls to prevent enumeration attacks.

Consider:

  1. Adding rate limiting headers to the API specification
  2. Implementing pagination for endpoints that list assets
  3. Adding proper authorization scopes for asset ID operations
  4. Logging all asset ID access attempts for security auditing
backend/app/api/static/docs/docs.go (1)

Line range hint 1-2500: Security Review: Authentication and Authorization Implementation

The API security implementation looks solid with proper Bearer token authentication. However, here are some security recommendations:

  1. Consider implementing rate limiting for authentication endpoints
  2. Add CORS configuration to protect against unauthorized cross-origin requests
  3. Consider implementing token revocation for enhanced security
🛑 Comments failed to post (5)
frontend/pages/reports/label-generator.vue (2)

222-228: 🛠️ Refactor suggestion

Fix off-by-one error in loop range

The loop range adjustment introduces potential confusion with the -1 offsets. Consider making the indexing more explicit.

-    for (let i = displayProperties.assetRange - 1; i < displayProperties.assetRangeMax - 1; i++) {
+    const startIndex = displayProperties.assetRange - 1;
+    const endIndex = displayProperties.assetRangeMax - 1;
+    for (let i = startIndex; i < endIndex; i++) {
       const item = allFields?.value?.items?.[i];
       if (item?.location) {
         items.push(getItem(i, item as { assetId: string; location: { name: string }; name: string }));
       } else {
         items.push(getItem(i, null));
       }
     }
📝 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 startIndex = displayProperties.assetRange - 1;
    const endIndex = displayProperties.assetRangeMax - 1;
    for (let i = startIndex; i < endIndex; i++) {
      const item = allFields?.value?.items?.[i];
      if (item?.location) {
        items.push(getItem(i, item as { assetId: string; location: { name: string }; name: string }));
      } else {
        items.push(getItem(i, null));
      }

186-195: ⚠️ Potential issue

Security: Validate and sanitize item properties

The getItem function accepts external data that's displayed in labels. While the current implementation uses safe defaults, we should add input validation.

Add property validation:

 function getItem(n: number, item: { assetId: string; name: string; location: { name: string } } | null): LabelData {
   const assetID = fmtAssetID(n + 1);
+  // Sanitize and validate input
+  const sanitizedName = item?.name ? DOMPurify.sanitize(item.name) : "_______________";
+  const sanitizedLocation = item?.location?.name ? DOMPurify.sanitize(item.location.name) : "_______________";
+  const sanitizedAssetId = item?.assetId ? DOMPurify.sanitize(item.assetId) : assetID;
 
   return {
     url: getQRCodeUrl(assetID),
-    assetID: item?.assetId ?? assetID,
-    name: item?.name ?? "_______________",
-    location: item?.location?.name ?? "_______________",
+    assetID: sanitizedAssetId,
+    name: sanitizedName,
+    location: sanitizedLocation,
   };
 }

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

backend/app/api/static/docs/swagger.json (1)

2282-2285: 🛠️ Refactor suggestion

Ensure consistency across related models

The assetId field is added to ItemSummary, but it should be consistently represented across related models. Consider adding it to:

  • ItemCreate (for creating items with specific asset IDs)
  • ItemPatch (for updating asset IDs)
docs/docs/api/openapi-2.0.json (2)

2282-2285: 🛠️ Refactor suggestion

Consider making assetId a required field

Since the asset ID is crucial for the label generator functionality, consider making it a required field to ensure data consistency.

Add the field to the required array:

 "repo.ItemSummary": {
     "type": "object",
+    "required": ["assetId"],
     "properties": {

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


2282-2285: ⚠️ Potential issue

Add validation constraints for the assetId property

While adding the assetId property is a good step towards fixing the label generator issue, consider enhancing the specification with validation rules to prevent potential security issues.

Consider adding these constraints to the property definition:

 "assetId": {
     "type": "string",
-    "example": "0"
+    "example": "000-001",
+    "pattern": "^[0-9]{3}-[0-9]{3}$",
+    "minLength": 7,
+    "maxLength": 7,
+    "description": "Unique identifier for the asset in format XXX-XXX where X is a digit"
 }

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

@tankerkiller125 tankerkiller125 merged commit 5e81e60 into main Nov 29, 2024
11 checks passed
@tankerkiller125 tankerkiller125 deleted the mk/fix-289 branch November 29, 2024 18:18
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.

Label Generator showing incorrect asset ID
2 participants