Skip to content

Added vulnerabilities cleanup cron#41195

Open
getvictor wants to merge 3 commits intomainfrom
victor/28091-vulnerabilities-cleanup
Open

Added vulnerabilities cleanup cron#41195
getvictor wants to merge 3 commits intomainfrom
victor/28091-vulnerabilities-cleanup

Conversation

@getvictor
Copy link
Member

@getvictor getvictor commented Mar 7, 2026

Related issue: Resolves #28091

Checklist for submitter

  • Changes file added for user-visible changes in changes/, orbit/changes/ or ee/fleetd-chrome/changes.

Testing

Summary by CodeRabbit

Bug Fixes

  • Fixed an issue where vulnerability counts would inflate over time due to orphaned vulnerability entries remaining after hosts are removed. Vulnerability cleanup now automatically runs during routine scanning operations.

@getvictor
Copy link
Member Author

@coderabbitai full review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 7, 2026

✅ Actions performed

Full review triggered.

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Adds an orphaned-vulnerability cleanup step to Fleet’s vulnerabilities processing so vulnerability counts don’t grow indefinitely after hosts are removed (e.g., host expiry removing hosts but leaving behind OVAL-related vuln rows).

Changes:

  • Extend fleet.Datastore with two new cleanup methods for orphaned software and OS vulnerability rows.
  • Implement MySQL deletes for orphaned software_cve and operating_system_vulnerabilities, with new unit tests covering the behavior.
  • Invoke both cleanup methods during the vulnerabilities scan cron run.

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
cmd/fleet/cron.go Calls the new orphan-cleanup datastore methods during vulnerability scanning.
server/fleet/datastore.go Adds DeleteOrphanedSoftwareVulnerabilities and DeleteOrphanedOSVulnerabilities to the datastore interface.
server/datastore/mysql/software.go Implements orphan cleanup for software_cve via LEFT JOIN host_software.
server/datastore/mysql/software_test.go Adds coverage verifying orphaned software_cve rows are removed after host deletion.
server/datastore/mysql/operating_system_vulnerabilities.go Implements orphan cleanup for operating_system_vulnerabilities via LEFT JOIN host_operating_system.
server/datastore/mysql/operating_system_vulnerabilities_test.go Adds coverage verifying orphaned OS vuln rows are removed after host deletion.
server/mock/datastore_mock.go Extends mock datastore to support the new interface methods.
changes/28091-vulnerabilities-cleanup Adds release note entry for the bug fix.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 7, 2026

Walkthrough

This pull request adds cleanup operations for orphaned vulnerability records in the database. Two new datastore methods are introduced: DeleteOrphanedSoftwareVulnerabilities and DeleteOrphanedOSVulnerabilities. These methods are called after vulnerability scanning in the cron job to remove vulnerability entries associated with hosts that have been deleted. The changes include implementations for MySQL, interface declarations, mock implementations, and test coverage for both cleanup operations.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

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.
Description check ⚠️ Warning The PR description is incomplete. It covers some checklist items but omits required sections like database migrations, input validation, and endpoint compatibility checks. Complete the missing checklist sections: verify SQL injection prevention with placeholders, confirm database migration safety for timestamp columns, and ensure all applicable checks are addressed or marked as not applicable.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Added vulnerabilities cleanup cron' accurately reflects the main change: adding cleanup operations to the vulnerability scanning cron job to delete orphaned vulnerability records.
Linked Issues check ✅ Passed The PR implementation meets the requirements of issue #28091 by adding cleanup methods (DeleteOrphanedSoftwareVulnerabilities and DeleteOrphanedOSVulnerabilities) that delete orphaned vulnerability records when hosts are removed.
Out of Scope Changes check ✅ Passed All changes are directly related to implementing the vulnerabilities cleanup as specified in issue #28091, including interface methods, implementations, tests, and cron integration.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch victor/28091-vulnerabilities-cleanup

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 and usage tips.

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 (1)
server/datastore/mysql/operating_system_vulnerabilities_test.go (1)

368-431: Add a same-os_id multi-host case.

This proves cleanup removes vulns once an OS loses all hosts, but it won't catch an implementation that accidentally deletes rows when one of several hosts sharing the same os_id is removed. Please add a case with two hosts mapped to the same OS, delete one, and assert the vulnerability remains.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@server/datastore/mysql/operating_system_vulnerabilities_test.go` around lines
368 - 431, In testDeleteOrphanedOSVulnerabilities, add a second host that shares
the same OS as hostWithOS to ensure DeleteOrphanedOSVulnerabilities doesn't
remove vulnerabilities when at least one host still references the OS: create
e.g. hostShared := test.NewHost(t, ds, "host_shared", "", "hsharedkey",
"hshareduuid", time.Now()), insert a host_operating_system row mapping
hostShared.ID to osWithHostID (use the same INSERT INTO host_operating_system
call or an additional ExecContext), then after deleting only hostToRemove call
ds.DeleteOrphanedOSVulnerabilities(ctx) and assert
ListOSVulnerabilitiesByOS(ctx, uint(osWithHostID)) still returns the
vulnerability (CVE-2024-100); optionally then delete hostShared and assert the
orphaned OS vuln is removed to cover full lifecycle.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@cmd/fleet/cron.go`:
- Around line 202-208: The current vuln-cron path calls
ds.DeleteOrphanedSoftwareVulnerabilities and ds.DeleteOrphanedOSVulnerabilities
synchronously in cmd/fleet/cron.go which runs full-table DELETEs and causes long
locks; remove these calls from the hot vulnerability cron and instead either (A)
move invocation to the lower-frequency cleanups/aggregation schedule where other
heavy sweeps run, or (B) change the implementations of
DeleteOrphanedSoftwareVulnerabilities and DeleteOrphanedOSVulnerabilities to
perform batched deletes (looping delete LIMIT N in a transaction until no rows
affected) to cap lock time and return quickly so the vuln cron only triggers a
lightweight operation. Ensure references to
ds.DeleteOrphanedSoftwareVulnerabilities and ds.DeleteOrphanedOSVulnerabilities
are updated accordingly and add logging to indicate batching or the new schedule
trigger.

In `@server/datastore/mysql/operating_system_vulnerabilities.go`:
- Around line 392-394: The DELETE currently only compares operating_system_id
and can remove rows that should remain if another host still uses that OS;
update the join to include the vulnerability row’s host scope by joining
host_operating_system (hos) on both hos.host_id = osv.host_id AND hos.os_id =
osv.operating_system_id, then keep the WHERE hos.host_id IS NULL predicate so
only operating_system_vulnerabilities (osv) whose specific host no longer has
that OS mapping are deleted; reference the osv alias
(operating_system_vulnerabilities), hos alias (host_operating_system), and the
host_id and operating_system_id columns when making this change.

---

Nitpick comments:
In `@server/datastore/mysql/operating_system_vulnerabilities_test.go`:
- Around line 368-431: In testDeleteOrphanedOSVulnerabilities, add a second host
that shares the same OS as hostWithOS to ensure DeleteOrphanedOSVulnerabilities
doesn't remove vulnerabilities when at least one host still references the OS:
create e.g. hostShared := test.NewHost(t, ds, "host_shared", "", "hsharedkey",
"hshareduuid", time.Now()), insert a host_operating_system row mapping
hostShared.ID to osWithHostID (use the same INSERT INTO host_operating_system
call or an additional ExecContext), then after deleting only hostToRemove call
ds.DeleteOrphanedOSVulnerabilities(ctx) and assert
ListOSVulnerabilitiesByOS(ctx, uint(osWithHostID)) still returns the
vulnerability (CVE-2024-100); optionally then delete hostShared and assert the
orphaned OS vuln is removed to cover full lifecycle.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 2be8315d-3048-4fb2-9eab-d0eb62c6a857

📥 Commits

Reviewing files that changed from the base of the PR and between 9df1186 and fee3ad1.

📒 Files selected for processing (8)
  • changes/28091-vulnerabilities-cleanup
  • cmd/fleet/cron.go
  • server/datastore/mysql/operating_system_vulnerabilities.go
  • server/datastore/mysql/operating_system_vulnerabilities_test.go
  • server/datastore/mysql/software.go
  • server/datastore/mysql/software_test.go
  • server/fleet/datastore.go
  • server/mock/datastore_mock.go

@codecov
Copy link

codecov bot commented Mar 7, 2026

Codecov Report

❌ Patch coverage is 60.00000% with 8 lines in your changes missing coverage. Please review.
✅ Project coverage is 66.35%. Comparing base (9df1186) to head (9d51bc9).

Files with missing lines Patch % Lines
cmd/fleet/cron.go 0.00% 2 Missing and 2 partials ⚠️
...atastore/mysql/operating_system_vulnerabilities.go 75.00% 1 Missing and 1 partial ⚠️
server/datastore/mysql/software.go 75.00% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #41195      +/-   ##
==========================================
- Coverage   66.35%   66.35%   -0.01%     
==========================================
  Files        2475     2475              
  Lines      198385   198405      +20     
  Branches     8856     8856              
==========================================
+ Hits       131639   131649      +10     
- Misses      54859    54860       +1     
- Partials    11887    11896       +9     
Flag Coverage Δ
backend 68.14% <60.00%> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@getvictor getvictor marked this pull request as ready for review March 7, 2026 15:10
@getvictor getvictor requested a review from a team as a code owner March 7, 2026 15:10
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.

🪲 Clean up vulnerabilities count increase over time

3 participants