Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@cicada0007
Copy link
Contributor

@cicada0007 cicada0007 commented Mar 23, 2025

closes #2471

Screenshot 2025-03-23 021246

Summary by CodeRabbit

  • New Features
    • Introduced a Threat Intelligence Section to the organization analytics dashboard, featuring a security risk score with color-coded indicators, top issue categories, and recent security alerts.
    • Improved data retrieval for threat intelligence, including trending attack types and severity classification of recent alerts.
    • Implemented a responsive grid layout for optimal viewing across devices.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 23, 2025

Walkthrough

This pull request adds threat intelligence components to the company cyber dashboard. It introduces a new section in the analytics HTML template with displays for security risk scores, top issue categories, and recent security alerts. In parallel, it enhances the backend view by adding methods to compute threat intelligence data, including risk scoring, recent alerts, and label conversion. Minor adjustments for unauthenticated user handling were also applied.

Changes

File(s) Change Summary
website/templates/.../organization_analytics.html Added a new Threat Intelligence section with components for displaying a color-coded Security Risk Score, Top Issue Categories based on attack vectors, and Recent Security Alerts with severity indicators.
website/views/company.py Introduced get_threat_intelligence and a helper method get_label_name in OrganizationDashboardAnalyticsView to retrieve and process threat intelligence data. Updated the dashboard context and adjusted user handling logic.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant AnalyticsView as OrganizationDashboardAnalyticsView
    participant Template as organization_analytics.html

    Client->>AnalyticsView: Send GET request for dashboard data
    AnalyticsView->>AnalyticsView: Execute get_threat_intelligence(organization)
    AnalyticsView->>AnalyticsView: Process risk score, issue categories, and recent alerts
    AnalyticsView->>Template: Render updated dashboard with threat intelligence context
    Template->>Client: Return dashboard page with new threat intelligence section
Loading

Assessment against linked issues

Objective Addressed Explanation
Add Threat Intelligence data to company cyber dashboard (#2471)

Possibly related PRs

Suggested reviewers

  • DonnieBLT

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 15f454c and 88b74d4.

📒 Files selected for processing (1)
  • website/views/company.py (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run Tests
  • GitHub Check: docker-test
🔇 Additional comments (3)
website/views/company.py (3)

228-261: Well-structured implementation of threat intelligence data collection.

The method successfully gathers security issues, calculates risk scores, and identifies recent alerts. The implementation includes good practices like:

  • Protection against division by zero in the risk score calculation
  • Capping the risk score at 100
  • Using a 90-day window for attack trend analysis
  • Proper filtering for security-related issues

263-265: Good reuse of existing label definitions.

Your implementation correctly leverages the existing labels class attribute defined on line 171 rather than creating a duplicate mapping. This maintains consistency and reduces duplication.


455-455: Clean addition of threat intelligence data to the context.

Using context.update() is a clean way to add the new threat intelligence data to the existing context dictionary.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

Actionable comments posted: 2

🧹 Nitpick comments (4)
website/templates/organization/organization_analytics.html (2)

342-346: Consider adding ARIA attributes for accessibility.

The color-coding for risk scores improves visual understanding, but users with visual impairments might miss this information. Consider adding appropriate ARIA attributes or additional text indicators to ensure the severity level is accessible to all users.

<span class="text-3xl font-bold inline-block py-1 px-2 rounded-full
     {% if threat_intelligence.risk_score >= 75 %}text-red-600
     {% elif threat_intelligence.risk_score >= 50 %}text-yellow-600
     {% else %}text-green-600{% endif %}"
+    aria-label="Risk score: {{ threat_intelligence.risk_score }} out of 100, {% if threat_intelligence.risk_score >= 75 %}High risk{% elif threat_intelligence.risk_score >= 50 %}Medium risk{% else %}Low risk{% endif %}"
>
    {{ threat_intelligence.risk_score }}/100
</span>

372-373: Add tooltips for truncated alert descriptions.

Since you're using truncate class on alert descriptions, some text might be cut off. Consider adding tooltips to show the full description on hover.

<span class="w-2 h-2 rounded-full {% if alert.cve_score >= 8 %}bg-red-500{% elif alert.cve_score >= 5 %}bg-yellow-500{% else %}bg-orange-500{% endif %}"></span>
-<span class="text-sm text-gray-600 truncate">{{ alert.description }}</span>
+<span class="text-sm text-gray-600 truncate" title="{{ alert.description }}">{{ alert.description }}</span>
website/views/company.py (2)

246-246: Risk score calculation could be more robust.

The current risk score calculation uses a simple ratio of critical issues to total issues. Consider implementing a weighted calculation that factors in multiple severity levels.

-risk_score = min(100, (critical_issues / total_issues * 100) if total_issues > 0 else 0)
+# Calculate weighted risk score factoring in multiple severity levels
+high_severity = security_issues.filter(cve_score__gte=8).count()
+medium_severity = security_issues.filter(cve_score__gte=5, cve_score__lt=8).count()
+low_severity = security_issues.filter(cve_score__gt=0, cve_score__lt=5).count()
+
+# Apply weights: high=1.0, medium=0.5, low=0.25
+weighted_score = (high_severity * 1.0 + medium_severity * 0.5 + low_severity * 0.25)
+weighted_total = total_issues if total_issues > 0 else 1
+risk_score = min(100, int((weighted_score / weighted_total) * 100))

462-462: Consider using context.update with multiple key-value pairs.

For better readability when adding multiple context variables, consider using the update() method with a dictionary containing all new entries rather than updating with a single item.

-context.update({"threat_intelligence": self.get_threat_intelligence(id)})
+context.update({
+    "threat_intelligence": self.get_threat_intelligence(id),
+    # Add other future context variables here
+})
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b7d0fff and f7f31ee.

📒 Files selected for processing (2)
  • website/templates/organization/organization_analytics.html (1 hunks)
  • website/views/company.py (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run Tests
  • GitHub Check: docker-test
🔇 Additional comments (2)
website/templates/organization/organization_analytics.html (1)

330-381: Well-structured Threat Intelligence section implementation!

The new Threat Intelligence section follows the established design patterns of the dashboard, maintaining consistency with other sections. The implementation includes three well-organized components: Security Risk Score, Top Issue Categories, and Recent Security Alerts, each with appropriate visual indicators.

The conditional styling for risk scores and alerts based on severity levels is a nice touch for visual clarity.

website/views/company.py (1)

228-262: Well-implemented threat intelligence data gathering.

The get_threat_intelligence method effectively collects and processes security-related data, including:

  • Attack vectors from security issues over the past 90 days
  • Risk score calculation based on critical issues proportion
  • Recent alerts from the past 7 days with severity filtering

The method handles edge cases by checking for zero division and applying maximum limits to the risk score.

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

🧹 Nitpick comments (3)
website/templates/organization/organization_analytics.html (2)

363-363: Minor typo in class name attribute.

There's a typo in the class name where "semibold" is misspelled as "semibold".

-    <h3 class="text-lg font-semibold text-gray-800 mb-2">Recent Security Alerts</h3>
+    <h3 class="text-lg font-semibold text-gray-800 mb-2">Recent Security Alerts</h3>

350-350: Same typo in another class name attribute.

The same "semibold" typo appears in this heading as well.

-    <h3 class="text-lg font-semibold text-gray-800 mb-2">Top Issue Categories</h3>
+    <h3 class="text-lg font-semibold text-gray-800 mb-2">Top Issue Categories</h3>
website/views/company.py (1)

455-455: Consider initializing the context with all values.

Instead of updating the context after initialization, consider including the threat intelligence data directly in the initial context dictionary for better readability.

        context = {
            "organization": id,
            "organizations": organizations,
            "organization_obj": organization_obj,
            "total_info": self.get_general_info(id),
            "bug_report_type_piechart_data": self.get_bug_report_type_piechart_data(id),
            "reports_on_domain_piechart_data": self.get_reports_on_domain_piechart_data(id),
            "get_current_year_monthly_reported_bar_data": self.get_current_year_monthly_reported_bar_data(id),
            "bug_rate_increase_descrease_weekly": self.bug_rate_increase_descrease_weekly(id),
            "accepted_bug_rate_increase_descrease_weekly": self.bug_rate_increase_descrease_weekly(id, True),
            "spent_on_bugtypes": self.get_spent_on_bugtypes(id),
            "security_incidents_summary": self.get_security_incidents_summary(id),
+           "threat_intelligence": self.get_threat_intelligence(id),
        }
-       context.update({"threat_intelligence": self.get_threat_intelligence(id)})
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f7f31ee and 6024fb3.

📒 Files selected for processing (2)
  • website/templates/organization/organization_analytics.html (1 hunks)
  • website/views/company.py (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run Tests
  • GitHub Check: docker-test
🔇 Additional comments (3)
website/templates/organization/organization_analytics.html (1)

330-374: Well-structured implementation of the Threat Intelligence section.

The new section follows the same design patterns as existing sections in the dashboard, with responsive grid layouts and appropriate conditional formatting for risk indicators.

website/views/company.py (2)

228-262: Good implementation of the threat intelligence method.

The method properly filters security issues, calculates risk scores, and retrieves recent alerts. The risk score calculation safely handles division by zero cases.


263-266: Good reuse of existing label mapping.

The get_label_name method properly reuses the existing labels class attribute to maintain consistency across the codebase, as suggested in a previous review comment.

coderabbitai[bot]
coderabbitai bot previously approved these changes Mar 23, 2025
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

🧹 Nitpick comments (2)
website/views/company.py (2)

245-246: Consider adding comments explaining score calculation.

The risk score calculation logic could benefit from additional comments explaining why cve_score >= 8 is chosen as the threshold for critical issues and how the score formula was determined.

# Calculate risk score (0-100)
total_issues = security_issues.count()
critical_issues = security_issues.filter(cve_score__gte=8).count()  # Use cve_score instead of severity
+ # Calculate risk score as percentage of critical issues (CVE score ≥ 8), capped at 100
risk_score = min(100, (critical_issues / total_issues * 100) if total_issues > 0 else 0)

228-262: Consider optimizing database queries.

The method makes multiple database queries to fetch security issues. Consider retrieving the data once and reusing it to improve performance.

def get_threat_intelligence(self, organization):
    """Gets threat intelligence data for the organization."""
    security_issues = Issue.objects.filter(
        domain__organization__id=organization,
        label=4,  # Security label
    )
+    
+    # Calculate counts once to avoid multiple queries
+    total_issues = security_issues.count()
+    critical_issues = security_issues.filter(cve_score__gte=8).count()
+    
+    # Pre-fetch recent alerts in a single query
+    recent_alerts = security_issues.filter(
+        created__gte=timezone.now() - timedelta(days=7),
+        cve_score__gte=7,  # Use cve_score for severity
+    ).order_by("-created")[:5]

    # Get trending attack types based on issue labels/tags instead
    attack_vectors = (
        security_issues.filter(created__gte=timezone.now() - timedelta(days=90))
        .values("label")  # Use label instead of vulnerability_type
        .annotate(count=Count("id"))
        .order_by("-count")[:5]
    )

    # Calculate risk score (0-100)
-    total_issues = security_issues.count()
-    critical_issues = security_issues.filter(cve_score__gte=8).count()  # Use cve_score instead of severity
    risk_score = min(100, (critical_issues / total_issues * 100) if total_issues > 0 else 0)

    return {
        "attack_vectors": [
            {
                "vulnerability_type": self.get_label_name(vector["label"]),  # Convert label to readable name
                "count": vector["count"],
            }
            for vector in attack_vectors
        ],
        "risk_score": int(risk_score),
-        "recent_alerts": security_issues.filter(
-            created__gte=timezone.now() - timedelta(days=7),
-            cve_score__gte=7,  # Use cve_score for severity
-        ).order_by("-created")[:5],
+        "recent_alerts": recent_alerts,
    }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6024fb3 and 15f454c.

📒 Files selected for processing (1)
  • website/views/company.py (2 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
website/views/company.py

265-266: SyntaxError: Expected ')', found newline

⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Run Tests
  • GitHub Check: docker-test
  • GitHub Check: Analyze (python)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (2)
website/views/company.py (2)

228-262: Well-implemented threat intelligence method.

The get_threat_intelligence method effectively collects security insights by:

  1. Filtering security issues by organization and label
  2. Calculating trending attack vectors from the last 90 days
  3. Computing a risk score based on critical issue ratio
  4. Gathering recent high-severity alerts

The implementation properly handles edge cases like division by zero when calculating the risk score.


455-455: Good addition to the context dictionary.

The threat intelligence data is properly added to the context dictionary for rendering in the template.

@cicada0007
Copy link
Contributor Author

Hello sir , please review this PR @DonnieBLT

@DonnieBLT DonnieBLT enabled auto-merge April 5, 2025 02:50
@DonnieBLT DonnieBLT added this pull request to the merge queue Apr 5, 2025
Merged via the queue into OWASP-BLT:main with commit de13b0b Apr 5, 2025
11 checks passed
rahulnegi20 pushed a commit to rahulnegi20/BLT that referenced this pull request Apr 5, 2025
…P-BLT#4036)

* added Threat Intelligence

* fix

* fix

* fix

---------

Co-authored-by: DonnieBLT <[email protected]>
github-merge-queue bot pushed a commit that referenced this pull request Apr 15, 2025
* mentor changes

* chore(deps): Bump aiohttp from 3.11.14 to 3.11.15

Bumps [aiohttp](https://github.com/aio-libs/aiohttp) from 3.11.14 to 3.11.15.
- [Release notes](https://github.com/aio-libs/aiohttp/releases)
- [Changelog](https://github.com/aio-libs/aiohttp/blob/master/CHANGES.rst)
- [Commits](aio-libs/aiohttp@v3.11.14...v3.11.15)

---
updated-dependencies:
- dependency-name: aiohttp
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <[email protected]>

* chore(deps): Bump openai from 1.69.0 to 1.70.0

Bumps [openai](https://github.com/openai/openai-python) from 1.69.0 to 1.70.0.
- [Release notes](https://github.com/openai/openai-python/releases)
- [Changelog](https://github.com/openai/openai-python/blob/main/CHANGELOG.md)
- [Commits](openai/openai-python@v1.69.0...v1.70.0)

---
updated-dependencies:
- dependency-name: openai
  dependency-version: 1.70.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <[email protected]>

* chore(deps): Bump sentry-sdk from 2.24.1 to 2.25.0

Bumps [sentry-sdk](https://github.com/getsentry/sentry-python) from 2.24.1 to 2.25.0.
- [Release notes](https://github.com/getsentry/sentry-python/releases)
- [Changelog](https://github.com/getsentry/sentry-python/blob/master/CHANGELOG.md)
- [Commits](getsentry/sentry-python@2.24.1...2.25.0)

---
updated-dependencies:
- dependency-name: sentry-sdk
  dependency-version: 2.25.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <[email protected]>

* reminder-settings logic done

* UI done for remdiner-settings

* debug statement removed

* chore(deps): Bump django from 5.1.7 to 5.1.8

Bumps [django](https://github.com/django/django) from 5.1.7 to 5.1.8.
- [Commits](django/django@5.1.7...5.1.8)

---
updated-dependencies:
- dependency-name: django
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <[email protected]>

* chore(deps): Bump aiohttp from 3.11.15 to 3.11.16

---
updated-dependencies:
- dependency-name: aiohttp
  dependency-version: 3.11.16
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <[email protected]>

* chore(deps): Bump django-storages from 1.14.5 to 1.14.6

Bumps [django-storages](https://github.com/jschneier/django-storages) from 1.14.5 to 1.14.6.
- [Changelog](https://github.com/jschneier/django-storages/blob/master/CHANGELOG.rst)
- [Commits](jschneier/django-storages@1.14.5...1.14.6)

---
updated-dependencies:
- dependency-name: django-storages
  dependency-version: 1.14.6
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <[email protected]>

* chore(deps): Bump sentry-sdk from 2.25.0 to 2.25.1

Bumps [sentry-sdk](https://github.com/getsentry/sentry-python) from 2.25.0 to 2.25.1.
- [Release notes](https://github.com/getsentry/sentry-python/releases)
- [Changelog](https://github.com/getsentry/sentry-python/blob/master/CHANGELOG.md)
- [Commits](getsentry/sentry-python@2.25.0...2.25.1)

---
updated-dependencies:
- dependency-name: sentry-sdk
  dependency-version: 2.25.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <[email protected]>

* Shifted Kudos view to the api (#4083)

* shifted to api

* pre commit changes

* pre-commit migration'

* made rabbit changes

* Verifying kudos sender through github login.  (#4089)

* shifted to api

* pre commit changes

* pre-commit migration'

* made rabbit changes

* verifying sender by github profile

* pre commit fix

* fixes ssrf in OWASP compliance check (#4091)

* fixes ssrf in OWASP compliance check

* isort

* try block

* Implemented change provided by coderabbitai -Voidoid (#4098)

* Implemented change provided by coderabbitai -Voidoid

* Update website/templates/hackathons/detail.html

---------

Co-authored-by: Voidoid1977 <[email protected]>
Co-authored-by: DonnieBLT <[email protected]>

* done (#4101)

* Fix: Fixed the queue page. (#4075)

* side navbar fixed

* launched_at added and conditions added for it

* transaction fixed

* paid field added

* view queue feature added

* pre-commit error

* improved UI/UX of whole page

* changes in the UI

* removed discord and slack options

* post on launch added

* pre-commit error

* pre-commit error fixed

* added h and w to all img tags

* coderabit changes

* Delete_Page UI Fixed (#4100)

* done

* done

* chat-bot fixed (#4052)

Co-authored-by: DonnieBLT <[email protected]>

* added a close button to delete the message chat in messages (#4032)

* added a close button to delete the message chat in messages

* removed all console logs

---------

Co-authored-by: DonnieBLT <[email protected]>

* Added Threat Intelligence section to the Organization dashboard (#4036)

* added Threat Intelligence

* fix

* fix

* fix

---------

Co-authored-by: DonnieBLT <[email protected]>

* done (#4048)

Co-authored-by: DonnieBLT <[email protected]>

* number updated for django migrations

* deleted old file

* extra line added

* extra line added

* code fix

* pre-commit check

* pre-commit run

* pre-commit run

* migration fix

* optimized logic to send mails

* migration

* precommit

* pre-commit run

* pre-commit

* pre-commit run

* cron changes

* migration fixes

* migration fix

* removed extra urls: code clean

* import correction

* using get_or_create now

* code refactor and bug fix

---------

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Krrish Sehgal <[email protected]>
Co-authored-by: Abhishek Kumar <[email protected]>
Co-authored-by: Voidoid1977 <[email protected]>
Co-authored-by: Voidoid1977 <[email protected]>
Co-authored-by: DonnieBLT <[email protected]>
Co-authored-by: Lucky negi <[email protected]>
Co-authored-by: Rinkit Adhana <[email protected]>
Co-authored-by: Swaparup Mukherjee <[email protected]>
Co-authored-by: sath000007 <[email protected]>
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.

Add to company cyber dashboard: Threat intelligence

2 participants