Skip to content

Fixed Windows config profile not deleted properly - #51005

Merged
getvictor merged 5 commits into
mainfrom
victor/50907-deleting-profiles
Aug 12, 2026
Merged

Fixed Windows config profile not deleted properly#51005
getvictor merged 5 commits into
mainfrom
victor/50907-deleting-profiles

Conversation

@getvictor

@getvictor getvictor commented Aug 11, 2026

Copy link
Copy Markdown
Member

Related issue:
Resolves #50907
Resolves #50698
Resolves #49002

Checklist for submitter

If some of the following don't apply, delete the relevant line.

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

Testing

Summary by CodeRabbit

Bug Fixes

  • Fixed stale Windows configuration profiles remaining in Host details after profile deletion, renaming, or host fleet transfers.
  • Host OS settings now accurately reflect the profiles still enforcing each setting.
  • Host status summaries are recalculated correctly after profile changes.
  • Prevented unnecessary device delete commands when another profile still protects the same settings.
  • Removed obsolete profile entries even when no device command is required.

@getvictor
getvictor requested a balanced review from Copilot August 11, 2026 20:16
@getvictor

Copy link
Copy Markdown
Member Author

@coderabbitai full review

@getvictor

Copy link
Copy Markdown
Member Author

/agentic_review

@coderabbitai

coderabbitai Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Full review finished.

Copilot AI 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.

Warning

  • Copilot's review of this pull request may be incomplete because some of the changed files are excluded by your Copilot content exclusion settings. See Excluding content from Copilot for details.

Pull request overview

Fixes stale Windows configuration profile rows when LocURI protection suppresses all <Delete> commands.

Changes:

  • Deletes fully protected host-profile rows and refreshes status rollups.
  • Adds unit and integration coverage for deletion, team transfer, and batch replacement scenarios.

Reviewed changes

Copilot reviewed 3 out of 4 changed files in this pull request and generated no comments.

File Description
server/service/microsoft_mdm.go Cleans up suppressed removal rows in bulk.
server/service/microsoft_mdm_test.go Adds reconciler regression tests.
server/service/integration_mdm_profiles_test.go Verifies database, API, and rollup behavior.
changes/49002-50698-50907-windows-profile-shared-locuri-row-cleanup Content unavailable under the exclusion policy.
Files excluded by content exclusion policy (1)
  • changes/49002-50698-50907-windows-profile-shared-locuri-row-cleanup

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Aug 11, 2026

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Invalid new(c.Verb) call 🐞 Bug ≡ Correctness
Description
The new integration test builds a SyncML <Status> ack with Cmd: new(c.Verb), but c.Verb is a
string value (not a type), so the test does not compile. This blocks CI/test runs for the PR.
Code

server/service/integration_mdm_profiles_test.go[R5118-5121]

+					MsgRef:  &msgID,
+					CmdRef:  &cmdID.Value,
+					Cmd:     new(c.Verb),
+					Data:    &status,
Evidence
new(c.Verb) is invalid because Verb is a string value, while SyncMLCmd.Cmd requires a
*string; other tests in this repo correctly pass a string pointer (e.g. ptr.String(c.Verb)).

server/service/integration_mdm_profiles_test.go[5113-5123]
server/service/integration_mdm_profiles_test.go[5083-5089]
server/fleet/microsoft_mdm.go[1129-1133]
server/fleet/microsoft_mdm.go[1166-1173]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`server/service/integration_mdm_profiles_test.go` constructs a SyncML `<Status>` response using `Cmd: new(c.Verb)`. In Go, `new(...)` requires a *type*, but `c.Verb` is a `string` value, so the test fails to compile.
### Issue Context
`fleet.ProtoCmdOperation.Verb` is a `string`, and `fleet.SyncMLCmd.Cmd` expects a `*string`. This file already uses the correct pattern elsewhere (`ptr.String(c.Verb)`).
### Fix Focus Areas
- server/service/integration_mdm_profiles_test.go[5113-5123]
### Suggested change
Replace `Cmd: new(c.Verb)` with either:
- `Cmd: ptr.String(c.Verb)` (consistent with earlier code in the same file), or
- `cmdVerb := c.Verb; Cmd: &cmdVerb` (avoids taking addresses of loop variables).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Tip of the day
💡 Did you know, you can enable the Remediation agent and Qodo fixes findings in a dedicated fix PR

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread server/service/integration_mdm_profiles_test.go Outdated
@coderabbitai

coderabbitai Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Windows MDM reconciliation now removes stale host-profile rows when all profile LocURIs remain enforced by another profile and no device delete command is generated. The cleanup uses one batched datastore operation. Tests cover profile replacement, empty profiles, mirrored-team transfers, command output, host/profile deletion keys, and host-detail cleanup. A changelog entry documents the fix.

Possibly related PRs

  • fleetdm/fleet#48873: Both PRs modify Windows MDM profile-status cleanup and per-host profile-row reconciliation.
  • fleetdm/fleet#49141: Both PRs modify Windows configuration-profile update and removal reconciliation.
  • fleetdm/fleet#50493: Both PRs account for existing host-profile rows when Windows profile removals are suppressed.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the primary change: fixing improper deletion of Windows configuration profiles.
Description check ✅ Passed The description links all issues and records the changes file, automated tests, host-isolation tests, and manual QA; omitted sections are not relevant to this backend fix.
Linked Issues check ✅ Passed The implementation and tests address stale-row cleanup for suppressed deletes, mirrored-team transfers, and batch replacements with shared LocURIs [#50907, #50698, #49002].
Out of Scope Changes check ✅ Passed The changes file, reconciliation logic, and focused tests are directly related to Windows profile-row cleanup and the linked issue objectives.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch victor/50907-deleting-profiles

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

🤖 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 `@server/service/integration_mdm_profiles_test.go`:
- Around line 5170-5192: Wrap the rollup query and status comparison currently
inside the mysqltest.ExecAdhocSQL callback in a require.Eventually predicate,
retrying until the asynchronous refresh makes rollupStatus equal
recomputedStatus. Preserve the existing SQL and error handling, and return
whether the comparison succeeds from the predicate.
🪄 Autofix

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.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 83365afd-c40c-48d4-ad63-cdd921e81ce1

📥 Commits

Reviewing files that changed from the base of the PR and between dd1080f and e0df8ad.

📒 Files selected for processing (4)
  • changes/49002-50698-50907-windows-profile-shared-locuri-row-cleanup
  • server/service/integration_mdm_profiles_test.go
  • server/service/microsoft_mdm.go
  • server/service/microsoft_mdm_test.go

Comment thread server/service/integration_mdm_profiles_test.go Outdated
@codecov

codecov Bot commented Aug 11, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 81.81818% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 68.56%. Comparing base (ec8334c) to head (4dd5b21).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
server/service/microsoft_mdm.go 81.81% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main   #51005   +/-   ##
=======================================
  Coverage   68.56%   68.56%           
=======================================
  Files        3985     3985           
  Lines      256692   256703   +11     
  Branches    13793    13793           
=======================================
+ Hits       175992   176006   +14     
+ Misses      65045    65043    -2     
+ Partials    15655    15654    -1     
Flag Coverage Δ
backend 69.66% <81.81%> (+<0.01%) ⬆️

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

☔ View full report in Codecov by Harness.
📢 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 August 11, 2026 21:32
@getvictor
getvictor requested a review from a team as a code owner August 11, 2026 21:32

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
server/service/integration_mdm_profiles_test.go (1)

5108-5116: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Assert that the retained profile remains on the host.

The test only proves that profile A is absent. It also passes if cleanup deletes both A and B rows. Query profile B after the batch replacement, assert that its host row remains, and assert that host details contain only profile B.

🤖 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 `@server/service/integration_mdm_profiles_test.go` around lines 5108 - 5116,
Extend the batch-replacement assertions after the existing profile A checks to
query profile B’s host row and require it remains present. Update the host
details validation to assert that the MDM profile list contains only profile B,
while still confirming deleted profile A is absent.
🤖 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 `@server/service/microsoft_mdm_test.go`:
- Around line 1283-1314: The test
TestReconcileWindowsProfilesDeletesRemoveRowsWithNoLocURIs must also verify that
no delete command is emitted for the removed profile. After asserting
deletedRows, call result.requireNoDeleteCommands while preserving the existing
deleted-pair assertion.

---

Outside diff comments:
In `@server/service/integration_mdm_profiles_test.go`:
- Around line 5108-5116: Extend the batch-replacement assertions after the
existing profile A checks to query profile B’s host row and require it remains
present. Update the host details validation to assert that the MDM profile list
contains only profile B, while still confirming deleted profile A is absent.
🪄 Autofix

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.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 0ca9fc7f-db80-4593-992d-798e4bf7b63c

📥 Commits

Reviewing files that changed from the base of the PR and between e0df8ad and 4dd5b21.

📒 Files selected for processing (3)
  • server/service/integration_mdm_profiles_test.go
  • server/service/microsoft_mdm.go
  • server/service/microsoft_mdm_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • server/service/microsoft_mdm.go

Comment on lines +1283 to +1314
// TestReconcileWindowsProfilesDeletesRemoveRowsWithNoLocURIs covers a removed profile whose content yields no LocURIs, so the
// command comes back nil for a reason other than LocURI protection.
func TestReconcileWindowsProfilesDeletesRemoveRowsWithNoLocURIs(t *testing.T) {
const (
hostUUID = "host-a"
keptProfile = "kept-profile-uuid"
removedProfile = "removed-profile-uuid"
)
teamID := uint(1)

// The kept profile shares no LocURI with the removed one, so protection plays no part: the only reason there is no <Delete>
// is that the removed profile has no LocURIs to target.
result := runWindowsReconcileOnce(t, windowsReconcileSnapshot{
hosts: []*fleet.WindowsHostReconcileInfo{{HostID: 1, UUID: hostUUID, TeamID: &teamID}},
profiles: []*fleet.WindowsProfileForReconcile{
{ProfileUUID: keptProfile, ProfileName: "Kept", TeamID: teamID, Checksum: []byte(windowsReconcileTestChecksum)},
},
current: map[string][]*fleet.MDMWindowsProfilePayload{
hostUUID: {
installedRow(keptProfile, "Kept", hostUUID),
installedRow(removedProfile, "Removed", hostUUID),
},
},
contents: map[string][]byte{
keptProfile: windowsTestProfileSyncML("Camera/AllowCamera"),
removedProfile: []byte(""), // empty (no LocURIs)
},
})

require.Len(t, result.deletedRows, 1, "a profile with no LocURIs must not stay stuck on the host")
require.Contains(t, result.deletedPairs(), hostProfileKey{hostUUID: hostUUID, profileUUID: removedProfile})
}

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert that no delete command is emitted.

The test states that the removed profile has no LocURIs and the delete command is nil. It only asserts row deletion. Add result.requireNoDeleteCommands so a regression that emits an unnecessary <Delete> cannot pass.

🤖 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 `@server/service/microsoft_mdm_test.go` around lines 1283 - 1314, The test
TestReconcileWindowsProfilesDeletesRemoveRowsWithNoLocURIs must also verify that
no delete command is emitted for the removed profile. After asserting
deletedRows, call result.requireNoDeleteCommands while preserving the existing
deleted-pair assertion.

@juan-fdz-hawa juan-fdz-hawa self-assigned this Aug 12, 2026
@getvictor
getvictor merged commit 244262c into main Aug 12, 2026
45 checks passed
@getvictor
getvictor deleted the victor/50907-deleting-profiles branch August 12, 2026 13:05
getvictor added a commit that referenced this pull request Aug 12, 2026
<!-- Add the related story/sub-task/bug number, like Resolves #123, or
remove if NA -->
**Related issue:**
Resolves #50907
Resolves #50698
Resolves #49002

# Checklist for submitter

If some of the following don't apply, delete the relevant line.

- [x] Changes file added for user-visible changes in `changes/`,
`orbit/changes/` or `ee/fleetd-chrome/changes`.
See [Changes

files](https://github.com/fleetdm/fleet/blob/main/docs/Contributing/guides/committing-changes.md#changes-files)
for more information.

## Testing

- [x] Added/updated automated tests
- [x] Where appropriate, [automated tests simulate multiple hosts and
test for host

isolation](https://github.com/fleetdm/fleet/blob/main/docs/Contributing/reference/patterns-backend.md#unit-testing)
(updates to one hosts's records do not affect another)

- [x] QA'd all new/changed functionality manually

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

## Bug Fixes

- Fixed stale Windows configuration profiles remaining in Host details
after profile deletion, renaming, or host fleet transfers.
- Host OS settings now accurately reflect the profiles still enforcing
each setting.
- Host status summaries are recalculated correctly after profile
changes.
- Prevented unnecessary device delete commands when another profile
still protects the same settings.
- Removed obsolete profile entries even when no device command is
required.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

(cherry picked from commit 244262c)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants