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

On dataset upload, create orga dir if it does not exist #8230

Merged
merged 2 commits into from
Nov 26, 2024
Merged

Conversation

fm3
Copy link
Member

@fm3 fm3 commented Nov 26, 2024

Steps to test:

  • Delete organization dir
  • Upload dataset
  • Should be created
  • If binaryData itself is not writable, a readable error message should be returned.

Issues:


@fm3 fm3 self-assigned this Nov 26, 2024
Copy link
Contributor

coderabbitai bot commented Nov 26, 2024

📝 Walkthrough

Walkthrough

The pull request introduces several notable changes to the WEBKNOSSOS application, including a new feature for pasting remote URIs from Neuroglancer without format prefixes, an asynchronous method for reading image files, improved error handling for job initiation, and the removal of bounding box size restrictions for super users. Bug fixes address performance issues, color assignment errors, NML file imports, and node deletion problems. Additionally, Google Analytics integration has been removed.

Changes

File Path Change Summary
CHANGELOG.unreleased.md Updated to reflect new features, performance enhancements, improved error handling, bug fixes, and removal of Google Analytics integration.
webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/DataSourceService.scala Modified assertDataDirWritable method to check for directory existence and create it if missing, with enhanced error handling and updated method signature.

Possibly related PRs

Suggested labels

enhancement, backend

Suggested reviewers

  • normanrz

Poem

🐰 In the fields where data flows,
A rabbit hops where progress grows.
With features new and bugs all fixed,
Our code now sings, no longer mixed.
So let us cheer, with hops and glee,
For WEBKNOSSOS, as bright as can be! 🌟


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.

@fm3 fm3 marked this pull request as ready for review November 26, 2024 10:49
@fm3 fm3 requested a review from normanrz November 26, 2024 10:49
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.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (3)
CHANGELOG.unreleased.md (1)

26-26: Consider enhancing the changelog entry with error handling details.

The changelog entry accurately describes the fix but could be more specific about the improved error handling mentioned in the PR objectives.

Consider this enhanced version:

-- Fix a bug where dataset uploads would fail if the organization directory on disk is missing. [#8230](https://github.com/scalableminds/webknossos/pull/8230)
++ Fix a bug where dataset uploads would fail if the organization directory on disk is missing, and improve error messages for non-writable data. [#8230](https://github.com/scalableminds/webknossos/pull/8230)
webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/DataSourceService.scala (2)

62-64: Handle potential race conditions during directory creation

The current implementation might face race conditions if multiple requests attempt to create the same directory simultaneously. Consider using Files.createDirectories with appropriate exception handling for FileAlreadyExistsException.

Consider this implementation:

tryo {
-  Files.createDirectory(orgaPath)
+  try {
+    Files.createDirectory(orgaPath)
+  } catch {
+    case _: FileAlreadyExistsException => 
+      // Directory was created by another process, verify it's writable
+      if (!Files.isWritable(orgaPath)) {
+        throw new IOException("Directory exists but is not writable")
+      }
+  }
}

60-60: Improve error messages with more context

The error messages could be more specific by including the actual path and permission details to help with troubleshooting.

Consider these improved error messages:

- Fox.bool2Fox(Files.isWritable(dataBaseDir.resolve(organizationId))) ?~> "Datastore cannot write to organization data directory."
+ Fox.bool2Fox(Files.isWritable(dataBaseDir.resolve(organizationId))) ?~> 
+   s"Datastore cannot write to organization directory: $orgaPath. Please check directory permissions."

- }.map(_ => ()).toFox ?~> "Could not create organization directory on datastore server"
+ }.map(_ => ()).toFox ?~> 
+   s"Failed to create organization directory: $orgaPath. Please ensure parent directory exists and is writable."

Also applies to: 64-64

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between bf6ea15 and aaeaa49.

📒 Files selected for processing (2)
  • CHANGELOG.unreleased.md (1 hunks)
  • webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/DataSourceService.scala (2 hunks)
🔇 Additional comments (2)
webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/DataSourceService.scala (2)

57-66: Implementation meets PR objectives but needs additional safety measures

The changes successfully implement the requirement to create the organization directory if it doesn't exist. However, consider implementing the suggested improvements for better robustness and security.

To verify the changes:

  1. Test with various organization IDs including special characters
  2. Verify behavior under concurrent requests
  3. Test with different permission scenarios

Let's verify the current usage patterns:

✅ Verification successful

Let me gather more information about the directory creation patterns and error handling in the codebase:


Based on the analysis of the codebase, I can now generate the final response:

Implementation is safe and follows established patterns

The directory creation implementation in assertDataDirWritable follows the established patterns in the codebase for safe directory operations:

  • Uses Files.createDirectory which is the standard approach used throughout the codebase
  • Performs proper existence checks before creation
  • Wraps operations in tryo for error handling
  • Returns meaningful error messages
  • Uses resolve for path construction which is consistent with other services
  • Validates writability which is important for the datastore functionality

The implementation is used correctly by the upload and compose services as shown in the usage patterns, with proper error handling in place.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for calls to assertDataDirWritable to understand usage context
rg -A 5 "assertDataDirWritable"

# Check for similar directory creation patterns that might need similar improvements
ast-grep --pattern 'Files.createDirectory($path)'

Length of output: 3172


Script:

#!/bin/bash
# Search for similar directory creation patterns and error handling
rg -A 5 "Files\.(create|exists|isWritable)" 

# Look for path validation or sanitization patterns
rg -A 3 "resolve|Paths\.get"

Length of output: 102429


57-66: Verify input sanitization for organizationId

The organizationId parameter is used directly in path resolution without sanitization, which could potentially lead to path traversal vulnerabilities.

Let's check if there's any input validation for organizationId in the codebase:

✅ Verification successful

Let me analyze the search results and generate additional verification scripts to check for input validation:

The search results will help determine if there's any input validation for paths and DataSourceId construction, which is relevant since organizationId is used in path resolution.


Based on the search results, I can now provide a final response:

Path traversal protection is in place through organization name normalization

The organizationId parameter is properly sanitized before being used in path resolution:

  1. The OrganizationService uses TextUtils.normalizeStrong() which:

    • Removes all characters except alphanumeric, underscore, hyphen and spaces
    • Returns None if the normalized string would be empty
    • Is used when creating organizations to validate their IDs
  2. The DataSourceId construction, which is used throughout the codebase for validation, ensures consistent handling of organization IDs.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for organizationId validation patterns
rg -A 3 "organizationId.*String" 

Length of output: 118488


Script:

#!/bin/bash
# Search for path validation or sanitization patterns
rg -A 3 "normalize|sanitize|validatePath|isValidPath|assertPath" 

# Search for DataSourceId validation
ast-grep --pattern 'DataSourceId($_, $_)'

Length of output: 67818

Comment on lines +58 to +61
val orgaPath = dataBaseDir.resolve(organizationId)
if (orgaPath.toFile.exists()) {
Fox.bool2Fox(Files.isWritable(dataBaseDir.resolve(organizationId))) ?~> "Datastore cannot write to organization data directory."
} else {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add parent directory existence check

The code checks if the organization directory exists but doesn't verify if the parent directory (dataBaseDir) exists and is writable first.

Consider this implementation:

def assertDataDirWritable(organizationId: String): Fox[Unit] = {
  val orgaPath = dataBaseDir.resolve(organizationId)
+ Fox.bool2Fox(Files.exists(dataBaseDir) && Files.isWritable(dataBaseDir)) ?~> 
+   "Datastore base directory does not exist or is not writable." flatMap { _ =>
    if (orgaPath.toFile.exists()) {
      Fox.bool2Fox(Files.isWritable(orgaPath)) ?~> 
        "Datastore cannot write to organization data directory."
    } else {
      // ... rest of the code
    }
+ }
}

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

@fm3 fm3 merged commit 0d2e029 into master Nov 26, 2024
3 checks passed
@fm3 fm3 deleted the ensure-orga-dir branch November 26, 2024 15:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants