Skip to content

cwe: remove prohibited vulnerability-mapping entries on refresh - #992

Open
Bornunique911 wants to merge 3 commits into
OWASP:mainfrom
Bornunique911:fix/cwe-prohibited-mapping-filter-main
Open

cwe: remove prohibited vulnerability-mapping entries on refresh#992
Bornunique911 wants to merge 3 commits into
OWASP:mainfrom
Bornunique911:fix/cwe-prohibited-mapping-filter-main

Conversation

@Bornunique911

Copy link
Copy Markdown
Contributor

Summary

Follow-up to merged PR #939.

This PR fixes the remaining prohibited-CWE import gap by filtering against the upstream CWE vulnerability-mapping field (Mapping_Notes -> Usage = Prohibited) and removing stale prohibited CWE entries that may already exist in the local database.

A concrete example is CWE-16, which is still reachable on OpenCRE even though the upstream CWE entry marks its vulnerability mapping as Prohibited.

Problem

PR #939 improved CWE filtering, but the current logic is still incomplete.

The merged code filters primarily from the XML @Status field on imported weaknesses. That misses entries whose import exclusion is driven by the CWE vulnerability-mapping metadata instead, especially:

  • prohibited entries with Mapping_Notes -> Usage = Prohibited
  • prohibited category entries such as CWE-16
  • stale prohibited CWE rows already present in the database from earlier imports

As a result, prohibited CWE entries can remain visible after refresh.

Fix

This PR updates the CWE parser to:

  • treat Mapping_Notes -> Usage = Prohibited as the authoritative exclusion signal
  • still skip explicitly prohibited status entries
  • inspect both Weaknesses and Categories
  • delete stale prohibited CWE rows already stored in the local database before completing the refresh

It also adds regression coverage for both:

  • prohibited weakness entries
  • stale prohibited category entries such as CWE-16

The refresh script message is updated as well so it reflects the actual filtering rule.

Review Note For Maintainer

This is a small corrective follow-up to merged PR #939.

I verified that prohibited CWE entries can still remain visible after refresh because the current filter does not fully honor the upstream vulnerability-mapping field (Mapping_Notes -> Usage = Prohibited) and does not remove stale prohibited rows already present in the DB.

CWE-16 is a concrete live example of that gap.

This PR keeps the scope narrow:

  • filter prohibited entries using upstream mapping metadata
  • remove stale prohibited CWE rows on refresh
  • add regression coverage

Tested locally with:

/home/born/Important_Stuff/OpenCRE/venv/bin/python -m pytest application/tests/cwe_parser_test.py -k 'prohibited or register_CWE' -q

@coderabbitai

coderabbitai Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Summary by CodeRabbit

  • Bug Fixes
    • CWE imports now detect and remove prohibited or stale entries, including associated relationships and generated data.
    • Prohibited weaknesses and categories are skipped based on catalog status or usage notes.
  • Tests
    • Added coverage confirming prohibited category entries are removed.
  • Chores
    • Improved CWE update setup to install required runtime dependencies automatically when needed.
    • Clarified importer messaging for skipped prohibited entries.

Walkthrough

The CWE parser detects prohibited weaknesses and categories, removes matching stale database entries, skips prohibited weaknesses during registration, and preserves allowed-entry processing. Tests and the update script reflect the new behavior.

Changes

CWE prohibited-entry handling

Layer / File(s) Summary
Prohibited-entry detection and deletion
application/utils/external_project_parsers/parsers/cwe.py
Adds catalog flattening, mapping-usage normalization, prohibited-entry detection, prohibited-ID collection, and deletion of matching CWE nodes with linked records and embeddings.
Registration filtering and cleanup
application/utils/external_project_parsers/parsers/cwe.py
Removes prohibited IDs before registration and skips prohibited weaknesses while continuing allowed-entry updates and relationship handling.
Parser validation and update command
application/tests/cwe_parser_test.py, scripts/update-cwe.sh
Tests prohibited weaknesses and stale categories. The update script checks runtime dependencies and reports both prohibited-entry detection sources.

Estimated code review effort: 4 (Complex) | ~40 minutes

Possibly related PRs

  • OWASP/OpenCRE#939: Related CWE import filtering for prohibited weaknesses, categories, and stale-entry cleanup.

Suggested reviewers: northdpole, pa04rth, paoga87

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: removing prohibited CWE mapping entries during refresh.
Description check ✅ Passed The description directly explains the prohibited-entry filtering, stale database cleanup, affected categories, and regression tests.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@application/utils/external_project_parsers/parsers/cwe.py`:
- Around line 133-138: Update delete_cwe_entries so its final
cache.session.commit() is wrapped in the same IntegrityError handling pattern
used by add_node: catch the commit failure, roll back the session, and handle
the error without aborting the surrounding register_cwe/parse flow. Keep the
successful deletion log unchanged.
- Around line 107-139: Update delete_cwe_entries to remove every embedding
associated with each entry, rather than deleting only the single result returned
by cache.get_embeddings_for_doc. Iterate through all matching embeddings and
delete each one before deleting the node, preserving the existing link cleanup
and commit flow.

In `@scripts/update-cwe.sh`:
- Around line 18-21: Update the dependency bootstrap in update-cwe.sh to install
the repository’s existing requirements.txt when pytest is unavailable, replacing
the nonexistent requirements-dev.txt reference; preserve the current pytest
check and installation flow.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro Plus

Run ID: 6d5333a1-abeb-4b7c-9b3f-b966a3517b86

📥 Commits

Reviewing files that changed from the base of the PR and between a55e380 and 06a5c64.

📒 Files selected for processing (3)
  • application/tests/cwe_parser_test.py
  • application/utils/external_project_parsers/parsers/cwe.py
  • scripts/update-cwe.sh

Comment thread application/utils/external_project_parsers/parsers/cwe.py
Comment thread application/utils/external_project_parsers/parsers/cwe.py Outdated
Comment thread scripts/update-cwe.sh Outdated

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@scripts/update-cwe.sh`:
- Around line 32-33: Update the status message before the cre.py invocation to
state that entries marked PROHIBITED by either `@Status` or Mapping_Notes -> Usage
are skipped, covering both weaknesses and categories.
- Around line 18-20: Update the dependency bootstrap sentinel in the script’s
Python import check to use an explicit marker or a runtime dependency required
by cre.py, rather than pytest from requirements-dev.txt. Ensure the check
succeeds after installing requirements.txt and prevents repeated installation
attempts before the parser runs.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro Plus

Run ID: 14db9b6a-9e48-45c0-b13d-aa066c96d1ca

📥 Commits

Reviewing files that changed from the base of the PR and between 06a5c64 and 07cb4c2.

📒 Files selected for processing (2)
  • application/utils/external_project_parsers/parsers/cwe.py
  • scripts/update-cwe.sh
🚧 Files skipped from review as they are similar to previous changes (1)
  • application/utils/external_project_parsers/parsers/cwe.py

Comment thread scripts/update-cwe.sh Outdated
Comment thread scripts/update-cwe.sh Outdated
@Bornunique911
Bornunique911 force-pushed the fix/cwe-prohibited-mapping-filter-main branch from e6c3f13 to 06a5c64 Compare July 23, 2026 18:28
@Bornunique911
Bornunique911 force-pushed the fix/cwe-prohibited-mapping-filter-main branch 2 times, most recently from b252a5b to c5a348b Compare July 30, 2026 17:57
@Bornunique911
Bornunique911 force-pushed the fix/cwe-prohibited-mapping-filter-main branch from c5a348b to 55dad3d Compare July 31, 2026 18:15

@coderabbitai coderabbitai Bot left a comment

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.

♻️ Duplicate comments (1)
application/utils/external_project_parsers/parsers/cwe.py (1)

142-151: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Catch all commit failures, not only IntegrityError.

If the commit fails with another SQLAlchemyError (for example OperationalError), the session stays in a failed state. Every later cache.add_node call in register_cwe then fails. Roll back on any commit error, and keep the log.

🛡️ Proposed fix
         try:
             cache.session.commit()
             logger.info(
                 "Deleted %s prohibited CWE entries from the local database",
                 len(entries),
             )
-        except IntegrityError as e:
+        except SQLAlchemyError as e:
             cache.session.rollback()
             logger.error("Failed to delete prohibited CWE entries: %s", e)

Update the import accordingly:

from sqlalchemy.exc import SQLAlchemyError
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@application/utils/external_project_parsers/parsers/cwe.py` around lines 142 -
151, Update the exception handling around cache.session.commit in the CWE
deletion flow to catch SQLAlchemyError instead of only IntegrityError, while
preserving the rollback and existing error log. Adjust the sqlalchemy.exc import
accordingly so register_cwe can continue using the session after any commit
failure.
🧹 Nitpick comments (2)
application/utils/external_project_parsers/parsers/cwe.py (1)

311-315: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Rename the local id variable.

Ruff reports A001 on Line 312. id shadows the builtin. Rename it to capec_id_value.

♻️ Proposed fix
                             else:
-                                id = lst["`@CAPEC_ID`"]
+                                capec_id_value = lst["`@CAPEC_ID`"]
                                 cwe = self.link_cwe_to_capec_cre(
-                                    cwe=cwe, cache=cache, capec_id=id
+                                    cwe=cwe, cache=cache, capec_id=capec_id_value
                                 )
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@application/utils/external_project_parsers/parsers/cwe.py` around lines 311 -
315, Rename the local id variable in the CAPEC linking branch to capec_id_value,
and update the capec_id argument in self.link_cwe_to_capec_cre accordingly.

Source: Linters/SAST tools

application/tests/cwe_parser_test.py (1)

299-308: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove the redundant session write.

Node_collection.add_node inserts and commits the node already. The extra session.add(stale_category) and session.commit() add no state.

♻️ Proposed simplification
         stale_category = self.collection.add_node(
             defs.Standard(
                 name="CWE",
                 sectionID="16",
                 section="Configuration",
                 hyperlink="https://cwe.mitre.org/data/definitions/16.html",
             )
         )
-        self.collection.session.add(stale_category)
-        self.collection.session.commit()
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@application/tests/cwe_parser_test.py` around lines 299 - 308, Remove the
redundant self.collection.session.add(stale_category) and
self.collection.session.commit() calls after Node_collection.add_node; retain
the add_node invocation so it remains responsible for inserting and committing
stale_category.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Duplicate comments:
In `@application/utils/external_project_parsers/parsers/cwe.py`:
- Around line 142-151: Update the exception handling around cache.session.commit
in the CWE deletion flow to catch SQLAlchemyError instead of only
IntegrityError, while preserving the rollback and existing error log. Adjust the
sqlalchemy.exc import accordingly so register_cwe can continue using the session
after any commit failure.

---

Nitpick comments:
In `@application/tests/cwe_parser_test.py`:
- Around line 299-308: Remove the redundant
self.collection.session.add(stale_category) and self.collection.session.commit()
calls after Node_collection.add_node; retain the add_node invocation so it
remains responsible for inserting and committing stale_category.

In `@application/utils/external_project_parsers/parsers/cwe.py`:
- Around line 311-315: Rename the local id variable in the CAPEC linking branch
to capec_id_value, and update the capec_id argument in
self.link_cwe_to_capec_cre accordingly.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro Plus

Run ID: 02913147-ee8b-4333-9ab0-a12dc25b074b

📥 Commits

Reviewing files that changed from the base of the PR and between b252a5b and 55dad3d.

📒 Files selected for processing (3)
  • application/tests/cwe_parser_test.py
  • application/utils/external_project_parsers/parsers/cwe.py
  • scripts/update-cwe.sh
🚧 Files skipped from review as they are similar to previous changes (1)
  • scripts/update-cwe.sh

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.

1 participant