Skip to content

Conversation

@hajdul88
Copy link
Collaborator

Description

Adds subgraph retriever to graph based completion searches

DCO Affirmation

I affirm that all code in every commit of this pull request conforms to the terms of the Topoteretes Developer Certificate of Origin.

@pull-checklist
Copy link

pull-checklist bot commented May 26, 2025

Please make sure all the checkboxes are checked:

  • I have tested these changes locally.
  • I have reviewed the code changes.
  • I have added end-to-end and unit tests (if applicable).
  • I have updated the documentation and README.md file (if necessary).
  • I have removed unnecessary code and debug statements.
  • PR title is clear and follows the convention.
  • I have tagged reviewers or team members for feedback.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 26, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


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
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

@hajdul88 hajdul88 self-assigned this May 26, 2025
@pensarapp
Copy link
Contributor

pensarapp bot commented May 26, 2025

Cypher Injection in Graph Database Query Filter Construction
Suggested Fix

@@ -652,8 +652,24 @@
             + "}"
         )
         return relationship_types_undirected_str
 
+    @staticmethod
+    def _escape_cypher_identifier(identifier: str) -> str:
+        # Allowed unescaped: simple names with [a-zA-Z0-9_] only, not starting with digit.
+        # Otherwise: surround with backticks and escape inner backticks with double-backtick.
+        import re
+        if not isinstance(identifier, str):
+            raise ValueError("Identifier must be a string")
+        # Disallow control, newline, and quote chars
+        if any(ord(c) < 32 or c in '\'"\\' for c in identifier):
+            raise ValueError("Graph name contains illegal control or quote characters")
+        if re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*', identifier):
+            return identifier
+        # If already surrounded by backticks, don't double-escape
+        escaped = identifier.replace("`", "``")
+        return f"`{escaped}`"
+
     async def project_entire_graph(self, graph_name="myGraph"):
         """
         Projects all node labels and all relationship types into an undirected in-memory GDS graph.
         """
@@ -661,12 +677,13 @@
             return
 
         node_labels_str = await self.get_node_labels_string()
         relationship_types_undirected_str = await self.get_relationship_labels_string()
+        graph_name_escaped = self._escape_cypher_identifier(graph_name)
 
         query = f"""
         CALL gds.graph.project(
-            '{graph_name}',
+            {graph_name_escaped},
             {node_labels_str},
             {relationship_types_undirected_str}
         ) YIELD graphName;
         """
@@ -674,9 +691,10 @@
         await self.query(query)
 
     async def drop_graph(self, graph_name="myGraph"):
         if await self.graph_exists(graph_name):
-            drop_query = f"CALL gds.graph.drop('{graph_name}');"
+            graph_name_escaped = self._escape_cypher_identifier(graph_name)
+            drop_query = f"CALL gds.graph.drop({graph_name_escaped});"
             await self.query(drop_query)
 
     async def get_graph_metrics(self, include_optional=False):
         """For the definition of these metrics, please refer to
@@ -761,5 +779,5 @@
         WHERE COUNT {{ MATCH (n)--() }} = 1
         RETURN n
         """
         result = await self.query(query)
-        return [record["n"] for record in result] if result else []
+        return [record["n"] for record in result] if result else []
\ No newline at end of file
Explanation of Fix

The vulnerability is due to direct f-string interpolation of the graph_name parameter into Cypher queries in the project_entire_graph and drop_graph methods, without any validation or escaping. This allows malicious input to break Cypher queries and inject arbitrary statements, leading to severe security risks.

To fix this, I added a _escape_cypher_identifier static method for safe identifier usage. This method checks for allowed characters (letters, digits, _), rejects control/newline characters, and surrounds unsafe names with backticks and escapes any backticks within the identifier. Before interpolating graph_name in Cypher queries, I now pass it through this sanitizer. This approach follows Cypher's recommendations and is consistent with the handling already in place for node/relationship labels.

Potential impact: If callers provide graph names with truly invalid Cypher identifier characters, these will now be escaped (with backticks), which is harmless in most real-world scenarios but may surprise callers expecting punctuation to be included literally in graph names as interpreted by Neo4j/GDS. Legitimate graph names composed of safe characters are unaffected. There is no new dependency or breaking change to existing users (unless they relied on ability to inject Cypher code, which was a security risk).

Issues
Type Identifier Message Severity Link
Application
CWE-89, CWE-943
The filter builder concatenates raw attribute names and values into the Cypher WHERE clause with no escaping or parameterization. Malicious entries in attribute_filters, such as {"name": ["foo'] MATCH (x) DETACH DELETE x //"]}, can inject arbitrary Cypher code. This compromises confidentiality and integrity of the entire graph store.
critical
Link

Copy link
Collaborator

@lxobr lxobr left a comment

Choose a reason for hiding this comment

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

Looks good, nice work!

@hajdul88 hajdul88 merged commit 965033e into dev May 27, 2025
54 of 57 checks passed
@hajdul88 hajdul88 deleted the feature/cog-1892-add-a-retriever-that-filters-the-data-based-on-nodesets branch May 27, 2025 09:40
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.

3 participants