Skip to content

feature(url-analysis): add domain utility functions and update analysis logic#153

Closed
OrenIntezer wants to merge 1 commit intomasterfrom
feat/improve-url-analysis-search-TKT-6787
Closed

feature(url-analysis): add domain utility functions and update analysis logic#153
OrenIntezer wants to merge 1 commit intomasterfrom
feat/improve-url-analysis-search-TKT-6787

Conversation

@OrenIntezer
Copy link
Copy Markdown
Contributor

@OrenIntezer OrenIntezer commented Feb 23, 2025

Summary by CodeRabbit

  • New Features
    • Enhanced URL analysis for more accurate domain extraction and validation.
    • Improved handling of URL inputs by automatically correcting missing protocol prefixes.
  • Chores
    • Updated the SDK version to 1.21.12.
  • Tests
    • Added tests to validate the functionality of domain checking within URL analysis.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Feb 23, 2025

Walkthrough

This pull request updates the SDK version and enhances URL analysis capabilities. It introduces two private functions for domain extraction and checking, modifies the logic in an existing analysis method, and adds a new test to validate the functionality of the domain checking utility.

Changes

File(s) Change Summary
intezer_sdk/init.py Updated __version__ from '1.21.11' to '1.21.12'.
intezer_sdk/analysis.py Added _get_domain and _domain_contains functions; modified logic in from_latest_analysis.
tests/unit/test_url_analysis.py Added test_domain_contains_util method and imported _domain_contains for unit testing.
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

@OrenIntezer OrenIntezer force-pushed the feat/improve-url-analysis-search-TKT-6787 branch 2 times, most recently from d8555cc to a5aa056 Compare February 23, 2025 16:54
Copy link
Copy Markdown

@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. If you are seeing this consistently, please check "Code review limits" under "Moderation" settings.

Actionable comments posted: 1

🧹 Nitpick comments (4)
intezer_sdk/analysis.py (3)

341-344: Consider handling edge cases in URL parsing.

The function should handle edge cases like invalid URLs or empty strings.

 def _get_domain(url: str) -> str:
+    if not url or not isinstance(url, str):
+        raise ValueError("URL must be a non-empty string")
     if not url.startswith(('http://', 'https://')):
         url = 'http://' + url
     return urlparse(url).netloc

415-416: Consider documenting the date range change.

The date range has been increased from 1 day to 10 days. This should be documented in the function's docstring.


491-492: Enhance the main block example.

Consider adding more examples to demonstrate different URL formats and edge cases.

 if __name__ == '__main__':
-    print(_clean_url("https://www.google.com/fdsjklfdjs/fdsjklfdsjklfk/"))
+    examples = [
+        "https://www.google.com/path/",
+        "http://example.com",
+        "www.test.com/",
+        "https://sub.domain.com/path?query=1"
+    ]
+    for url in examples:
+        print(f"Original: {url}")
+        print(f"Cleaned:  {_clean_url(url)}\n")
tests/unit/test_url_analysis.py (1)

268-281: LGTM!

The test covers various URL formats and domain variations.

Consider adding more test cases:

     def test_domain_contains_util(self):
         # Arrange
         url1 = 'http://google.com/scans?email=orenk@intezer.com'
         url2 = 'http://intezer.com/scans?email=someone@example.com'
         url3 = 'https://www.intezer.com/scans?email=someone@example.com'
         url4 = 'https://www.analyze.intezer.com/scans?email=someone@example.com'
+        url5 = 'http://myintezer.com/scans'  # Should return False
+        url6 = ''  # Should handle empty string
+        url7 = 'invalid-url'  # Should handle invalid URL
 
         url_to_search = 'intezer.com'
 
         # Act + Assert
         self.assertFalse(_domain_contains(url1, url_to_search))
         self.assertTrue(_domain_contains(url2, url_to_search))
         self.assertTrue(_domain_contains(url3, url_to_search))
         self.assertTrue(_domain_contains(url4, url_to_search))
+        self.assertFalse(_domain_contains(url5, url_to_search))
+        with self.assertRaises(ValueError):
+            _domain_contains(url6, url_to_search)
+        with self.assertRaises(ValueError):
+            _domain_contains(url7, url_to_search)
🛑 Comments failed to post (1)
intezer_sdk/analysis.py (1)

347-348: 🛠️ Refactor suggestion

Improve domain matching logic.

The current implementation might match substrings incorrectly. For example, 'example.com' would match 'myexample.com'.

 def _domain_contains(url: str, search_domain: str) -> bool:
-    return search_domain in _get_domain(url)
+    domain = _get_domain(url)
+    return domain == search_domain or domain.endswith('.' + search_domain)
📝 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.

def _domain_contains(url: str, search_domain: str) -> bool:
    domain = _get_domain(url)
    return domain == search_domain or domain.endswith('.' + search_domain)

@OrenIntezer OrenIntezer force-pushed the feat/improve-url-analysis-search-TKT-6787 branch from a5aa056 to 92cdbc4 Compare February 23, 2025 16:56
@OrenIntezer OrenIntezer force-pushed the feat/improve-url-analysis-search-TKT-6787 branch from 92cdbc4 to a59b82f Compare February 23, 2025 16:57
Copy link
Copy Markdown

@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: 2

🧹 Nitpick comments (1)
intezer_sdk/analysis.py (1)

423-427: Consider moving domain filtering to the query level.

While the current implementation is correct, filtering analysis IDs after fetching all results could be inefficient for large datasets. Consider adding domain filtering parameters to the query_url_analyses_history function.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a5aa056 and a59b82f.

📒 Files selected for processing (3)
  • intezer_sdk/__init__.py (1 hunks)
  • intezer_sdk/analysis.py (3 hunks)
  • tests/unit/test_url_analysis.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • intezer_sdk/init.py
  • tests/unit/test_url_analysis.py
🔇 Additional comments (1)
intezer_sdk/analysis.py (1)

11-11: LGTM!

The urlparse import is correctly placed with other standard library imports and is necessary for the new domain utility functions.

Comment on lines +340 to +343
def _get_domain(url: str) -> str:
if not url.startswith(('http://', 'https://')):
url = 'http://' + url
return urlparse(url).netloc
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add type hints and improve error handling.

The function should include type hints and handle invalid URLs gracefully.

-def _get_domain(url: str) -> str:
+def _get_domain(url: str) -> str:
+    """Extract domain from URL, prefixing with http:// if protocol is missing.
+
+    Args:
+        url: URL string to parse
+
+    Returns:
+        str: Domain extracted from URL
+
+    Raises:
+        ValueError: If URL is invalid
+    """
     if not url.startswith(('http://', 'https://')):
         url = 'http://' + url
-    return urlparse(url).netloc
+    try:
+        return urlparse(url).netloc
+    except Exception as e:
+        raise ValueError(f"Invalid URL format: {url}") from e
📝 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.

Suggested change
def _get_domain(url: str) -> str:
if not url.startswith(('http://', 'https://')):
url = 'http://' + url
return urlparse(url).netloc
def _get_domain(url: str) -> str:
"""Extract domain from URL, prefixing with http:// if protocol is missing.
Args:
url: URL string to parse
Returns:
str: Domain extracted from URL
Raises:
ValueError: If URL is invalid
"""
if not url.startswith(('http://', 'https://')):
url = 'http://' + url
try:
return urlparse(url).netloc
except Exception as e:
raise ValueError(f"Invalid URL format: {url}") from e

@intezer intezer deleted a comment from notion-workspace bot Feb 23, 2025
@intezer intezer deleted a comment from OrenIntezer Feb 23, 2025


def _get_domain(url: str) -> str:
if not url.startswith(('http://', 'https://')):
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Ignore case


analyses_ids = [
report['analysis_id'] for report in analysis_history_url_result.all()
if _domain_contains(report['submitted_url'], url)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Let's talk, not sure i understand why we need the fix here and not in the actual search

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.

2 participants