Skip to content

Windows wipe failed acivitiy#43795

Open
ksykulev wants to merge 4 commits intomainfrom
42290-wipe-activity
Open

Windows wipe failed acivitiy#43795
ksykulev wants to merge 4 commits intomainfrom
42290-wipe-activity

Conversation

@ksykulev
Copy link
Copy Markdown
Contributor

@ksykulev ksykulev commented Apr 20, 2026

Related issue: Resolves #42290

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.
  • Input data is properly validated, SELECT * is avoided, SQL injection is prevented (using placeholders for values in statements), JS inline code is prevented especially for url redirects, and untrusted data interpolated into shell scripts/commands is validated against shell metacharacters.
  • Timeouts are implemented and retries are limited to avoid infinite loops

Testing

  • Added/updated automated tests
  • QA'd all new/changed functionality manually

Summary by CodeRabbit

  • New Features

    • Windows MDM wipe failures now create a tracked activity ("wipe_failed_host") showing the affected host ID and display name for better visibility.
  • Bug Fixes

    • Improved wipe-status handling and reporting so genuine failures are surfaced reliably to activity logs.
    • Duplicate failure responses are suppressed to avoid repeated alerts.
  • Tests

    • Added tests covering wipe-failure activity creation and related control-flow.

Copilot AI review requested due to automatic review settings April 20, 2026 18:04
@ksykulev ksykulev requested review from a team and rachaelshaw as code owners April 20, 2026 18:04
Copy link
Copy Markdown

@claude claude bot left a comment

Choose a reason for hiding this comment

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

Claude Code Review

This repository is configured for manual code reviews. Comment @claude review to trigger a review and subscribe this PR to future pushes, or @claude review once for a one-time review.

Tip: disable this comment in your organization's Code Review settings.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Apr 20, 2026

Walkthrough

Adds detection and recording of Windows MDM wipe failures by returning a structured MDMWindowsSaveResponseResult (with WipeFailed data) from MDMWindowsSaveResponse, updating MySQL helpers to report rows-affected, and creating a new ActivityTypeWipeFailedHost activity when a wipe failure is reported. Updates datastore interface and mock signatures, introduces MDMWindowsWipeResult and MDMWindowsSaveResponseResult types, adjusts service flow to look up the host and create the activity, and adds tests and a changelog entry.

Possibly related PRs

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

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.
Title check ❓ Inconclusive Title contains a typo ('acivitiy' instead of 'activity') and is only partially related to the changeset—it mentions Windows wipe failure activity creation but misses that this adds activity logging, datastore enhancements, and comprehensive testing. Fix typo to 'activity' and clarify the title to better reflect key changes, such as: 'Add activity logging for Windows wipe failures' or 'Log Windows MDM wipe failures as activities'.
✅ Passed checks (3 passed)
Check name Status Explanation
Description check ✅ Passed The pull request description follows the template structure and includes checked items for changes file, validation, testing, and QA, meeting the basic requirements despite being concise.
Linked Issues check ✅ Passed Changeset implements core requirements from issue #42290: detects wipe failures via new MDMWindowsSaveResponseResult type, creates ActivityTypeWipeFailedHost for audit logging, persists results via datastore updates, and includes comprehensive backend tests covering detection and activity creation.
Out of Scope Changes check ✅ Passed All changes are in-scope: new activity type, datastore enhancements for wipe-failure detection, test coverage, and supporting type definitions align with #42290 requirements. No unrelated refactoring or feature creep detected.

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

✨ 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 42290-wipe-activity

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
Copy Markdown
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/microsoft_mdm.go (1)

539-720: Consider test coverage for the new wipe-failure branch.

The new WipeFailed result path (prefix‑"2" classification, population of result.WipeFailed, and the early return nil, err paths) has no direct assertions visible in this diff. Given the downstream activity creation depends entirely on this return value, please ensure microsoft_mdm_test.go (or an integration test) covers at least: (a) successful wipe (no WipeFailed), (b) failed wipe with a 4xx/5xx status (WipeFailed populated), and (c) non‑wipe responses (result stays nil).

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

In `@server/datastore/mysql/microsoft_mdm.go` around lines 539 - 720, Add unit
tests in microsoft_mdm_test.go that exercise Datastore.MDMWindowsSaveResponse
for the three cases: (1) successful wipe where the matching command has a status
code starting with "2" and assert result is nil and
updateHostLockWipeStatusFromResultAndHostUUID was called with
wipeSucceeded=true; (2) failed wipe where status starts with "4" or "5" and
assert result.WipeFailed is populated with the expected HostUUID and
updateHostLockWipeStatusFromResultAndHostUUID was called with
wipeSucceeded=false; and (3) a non-wipe response (no TargetLocURI match) where
result remains nil and no wipe-related update is made. Construct test inputs to
create an enrolledDevice and matchingCmds, stub/spy the DB interactions or use
an in-memory test DB, and assert the observed behavior of
MDMWindowsSaveResponse, referencing the MDMWindowsSaveResponse method, the
WipeFailed field on fleet.MDMWindowsSaveResponseResult, and the
updateHostLockWipeStatusFromResultAndHostUUID side-effect to validate correct
branching.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@changes/42290-wipe-activity`:
- Line 1: Update the changelog entry text to use proper product casing and
include the missing article: change the sentence "Generate activity when the
windows mdm wipe command fails." to use "Activity" (product casing), "Windows
MDM" (product casing), and include "the" before the command, e.g. "Generate an
Activity when the Windows MDM wipe command fails." Apply this exact wording
where the changelog entry for changes/42290-wipe-activity is defined.

In `@server/datastore/mysql/microsoft_mdm.go`:
- Around line 685-700: The code treats an empty wipeCmdStatus as a failure;
change the logic in the block that handles wipeCmdUUID so you only interpret a
concrete status when wipeCmdStatus is non-empty: if wipeCmdUUID != "" &&
wipeCmdStatus != "" then compute wipeSucceeded :=
strings.HasPrefix(wipeCmdStatus, "2"), call
updateHostLockWipeStatusFromResultAndHostUUID(...) with that boolean, and only
set result.WipeFailed when wipeSucceeded is false (i.e., a non-2xx concrete
status was returned); if wipeCmdStatus is empty, skip updating host_mdm_actions
and do not set result.WipeFailed. Also review whether status codes 214/215
should be treated as success and adjust the strings.HasPrefix/logic accordingly.

---

Nitpick comments:
In `@server/datastore/mysql/microsoft_mdm.go`:
- Around line 539-720: Add unit tests in microsoft_mdm_test.go that exercise
Datastore.MDMWindowsSaveResponse for the three cases: (1) successful wipe where
the matching command has a status code starting with "2" and assert result is
nil and updateHostLockWipeStatusFromResultAndHostUUID was called with
wipeSucceeded=true; (2) failed wipe where status starts with "4" or "5" and
assert result.WipeFailed is populated with the expected HostUUID and
updateHostLockWipeStatusFromResultAndHostUUID was called with
wipeSucceeded=false; and (3) a non-wipe response (no TargetLocURI match) where
result remains nil and no wipe-related update is made. Construct test inputs to
create an enrolledDevice and matchingCmds, stub/spy the DB interactions or use
an in-memory test DB, and assert the observed behavior of
MDMWindowsSaveResponse, referencing the MDMWindowsSaveResponse method, the
WipeFailed field on fleet.MDMWindowsSaveResponseResult, and the
updateHostLockWipeStatusFromResultAndHostUUID side-effect to validate correct
branching.
🪄 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.yaml

Review profile: CHILL

Plan: Pro

Run ID: d3c7f42c-b4f2-44cf-8b68-89e029378cab

📥 Commits

Reviewing files that changed from the base of the PR and between 39d8c6f and c971629.

⛔ Files ignored due to path filters (1)
  • docs/Contributing/reference/audit-logs.md is excluded by !**/*.md
📒 Files selected for processing (9)
  • changes/42290-wipe-activity
  • server/datastore/mysql/mdm_test.go
  • server/datastore/mysql/microsoft_mdm.go
  • server/datastore/mysql/microsoft_mdm_test.go
  • server/fleet/activities.go
  • server/fleet/datastore.go
  • server/fleet/microsoft_mdm.go
  • server/mock/datastore_mock.go
  • server/service/microsoft_mdm.go

Comment thread changes/42290-wipe-activity Outdated
Comment thread server/datastore/mysql/microsoft_mdm.go
Copy link
Copy Markdown
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 a new audit-log activity for Windows MDM wipe failures so admins can observe failures (and trigger automations via webhooks) when a device reports a non-2xx wipe result.

Changes:

  • Extend Windows MDM response processing to surface “wipe failed” events from the datastore up to the service layer and create a new activity (wipe_failed_host).
  • Update datastore interfaces/mocks to return a result object from MDMWindowsSaveResponse.
  • Document the new activity type and add a release-note entry.

Reviewed changes

Copilot reviewed 8 out of 10 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
server/service/microsoft_mdm.go Creates wipe_failed_host activity when the datastore reports a wipe failure.
server/datastore/mysql/microsoft_mdm.go Returns MDMWindowsSaveResponseResult when a wipe command response indicates failure.
server/fleet/microsoft_mdm.go Defines result structs used to report notable Windows MDM response events.
server/fleet/datastore.go Updates datastore interface signature for MDMWindowsSaveResponse.
server/mock/datastore_mock.go Updates mock datastore function signatures/return types for the new result.
server/fleet/activities.go Registers new ActivityTypeWipeFailedHost and includes it in ActivityDetailsList.
server/datastore/mysql/microsoft_mdm_test.go Updates existing tests to accommodate new return value.
server/datastore/mysql/mdm_test.go Updates existing tests to accommodate new return value.
docs/Contributing/reference/audit-logs.md Documents the new wipe_failed_host audit log entry.
changes/42290-wipe-activity Adds release note entry for wipe-failed activity.

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

Comment thread server/datastore/mysql/microsoft_mdm.go
Comment thread changes/42290-wipe-activity Outdated
Comment thread server/datastore/mysql/microsoft_mdm.go
@codecov
Copy link
Copy Markdown

codecov bot commented Apr 20, 2026

Codecov Report

❌ Patch coverage is 77.27273% with 10 lines in your changes missing coverage. Please review.
✅ Project coverage is 66.92%. Comparing base (744c7a9) to head (18ef69a).
⚠️ Report is 40 commits behind head on main.

Files with missing lines Patch % Lines
server/datastore/mysql/scripts.go 60.00% 2 Missing and 2 partials ⚠️
server/service/microsoft_mdm.go 71.42% 2 Missing and 2 partials ⚠️
server/datastore/mysql/microsoft_mdm.go 90.00% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@           Coverage Diff            @@
##             main   #43795    +/-   ##
========================================
  Coverage   66.91%   66.92%            
========================================
  Files        2600     2600            
  Lines      208713   209017   +304     
  Branches     9188     9188            
========================================
+ Hits       139668   139880   +212     
- Misses      56328    56396    +68     
- Partials    12717    12741    +24     
Flag Coverage Δ
backend 68.70% <77.27%> (+<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.

Copy link
Copy Markdown
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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@server/datastore/mysql/scripts.go`:
- Around line 2328-2333: The code ignores errors from res.RowsAffected() after
tx.ExecContext, which can hide failures used by Windows MDM wipe handling; call
n, err = res.RowsAffected() and if err != nil return 0, ctxerr.Wrap(ctx, err,
"rows affected after update host lock/wipe status via host uuid") so the
RowsAffected error is propagated instead of silently returning 0; update the
return to use that checked n (from RowsAffected) and preserve existing
ctxerr.Wrap usage around the new error path.
🪄 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.yaml

Review profile: CHILL

Plan: Pro

Run ID: 25ec9cd3-dec9-43dd-abb1-c90cac66e458

📥 Commits

Reviewing files that changed from the base of the PR and between c971629 and 0d5b771.

📒 Files selected for processing (4)
  • changes/42290-wipe-activity
  • server/datastore/mysql/microsoft_mdm.go
  • server/datastore/mysql/microsoft_mdm_test.go
  • server/datastore/mysql/scripts.go
✅ Files skipped from review due to trivial changes (1)
  • changes/42290-wipe-activity
🚧 Files skipped from review as they are similar to previous changes (2)
  • server/datastore/mysql/microsoft_mdm_test.go
  • server/datastore/mysql/microsoft_mdm.go

Comment thread server/datastore/mysql/scripts.go
@ksykulev
Copy link
Copy Markdown
Contributor Author

Screenshot 2026-04-20 at 2 19 43 PM

@getvictor
Copy link
Copy Markdown
Member

Screenshot 2026-04-20 at 2 19 43 PM

@marko-lisica Does the frontend copy need some tweaking here?

@getvictor
Copy link
Copy Markdown
Member

@claude review once

Copy link
Copy Markdown
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

Copilot reviewed 9 out of 11 changed files in this pull request and generated 2 comments.


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

Comment thread server/datastore/mysql/microsoft_mdm.go
Comment thread server/service/microsoft_mdm.go
Comment thread server/datastore/mysql/microsoft_mdm.go
Comment thread server/fleet/activities.go
Comment on lines 684 to +701

// if we received a Wipe command result, update the host's status
if wipeCmdUUID != "" {
if err := updateHostLockWipeStatusFromResultAndHostUUID(ctx, tx, enrolledDevice.HostUUID,
"wipe_ref", wipeCmdUUID, strings.HasPrefix(wipeCmdStatus, "2"), false,
); err != nil {
wipeSucceeded := strings.HasPrefix(wipeCmdStatus, "2")
rowsAffected, err := updateHostLockWipeStatusFromResultAndHostUUID(ctx, tx, enrolledDevice.HostUUID,
"wipe_ref", wipeCmdUUID, wipeSucceeded, false,
)
if err != nil {
return ctxerr.Wrap(ctx, err, "updating wipe command result in host_mdm_actions")
}

if wipeCmdStatus != "" && !wipeSucceeded && rowsAffected > 0 {
result = &fleet.MDMWindowsSaveResponseResult{
WipeFailed: &fleet.MDMWindowsWipeResult{
HostUUID: enrolledDevice.HostUUID,
},
}
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟣 This is a pre-existing issue not introduced by this PR. When wipeCmdUUID != "" but wipeCmdStatus == "" (device response references the wipe command UUID but provides no Status element), the call to updateHostLockWipeStatusFromResultAndHostUUID with succeeded=false clears wipe_ref = NULL in host_mdm_actions, silently transitioning the host from 'wipe pending' to no-wipe state — this DB update behavior is structurally identical in both old and new code and predates this PR. The PR correctly guards the new activity-creation logic with wipeCmdStatus != "", so the net change from this PR is correct; the underlying DB-state issue should be tracked as a separate fix.

Extended reasoning...

The bug is real: when a Windows MDM device response includes a wipe command UUID in CmdRefUUIDs but provides no element for it (wipeCmdStatus == ""), the code still calls updateHostLockWipeStatusFromResultAndHostUUID with succeeded=false. Per buildHostLockWipeStatusUpdateStmt in scripts.go, a succeeded=false update for wipe_ref generates SET hma.wipe_ref = NULL, which silently clears the wipe-pending state in host_mdm_actions with no activity record and no user notification.

However, the refuter's analysis is correct: this behavior is pre-existing and was not introduced by this PR. Comparing old and new code shows the DB update call is structurally identical in both versions. Old code: updateHostLockWipeStatusFromResultAndHostUUID(ctx, tx, enrolledDevice.HostUUID, "wipe_ref", wipeCmdUUID, strings.HasPrefix(wipeCmdStatus, "2"), false). New code: wipeSucceeded := strings.HasPrefix(wipeCmdStatus, "2"); rowsAffected, err := updateHostLockWipeStatusFromResultAndHostUUID(ctx, tx, enrolledDevice.HostUUID, "wipe_ref", wipeCmdUUID, wipeSucceeded, false). An empty wipeCmdStatus evaluates to false in both versions, and the UPDATE fires identically.

What this PR added was new activity-creation logic, which is correctly gated: if wipeCmdStatus != "" && !wipeSucceeded && rowsAffected > 0 { result = &fleet.MDMWindowsSaveResponseResult{WipeFailed: ...} }. The test 'empty status does not signal wipe failure' validates this correctly — it checks result.WipeFailed == nil when status is empty, which passes because the activity guard is right.

Step-by-step proof: (1) Device sends a SyncML response with a element referencing wipeCmdUUID but no element for that UUID. (2) NewEnrichedSyncML adds the UUID to CmdRefUUIDs (both Status and Results CmdRefs are appended), so wipeCmdUUID gets assigned at line 661-664. (3) statusCode is never set for this UUID (lines 624-626 only populate CmdRefUUIDToStatus for Status commands), leaving wipeCmdStatus == "". (4) Old code: strings.HasPrefix("", "2") == false → updateHostLockWipeStatusFromResultAndHostUUID with succeeded=false → SET hma.wipe_ref = NULL. (5) New code: same evaluation path, same UPDATE — wipe_ref is cleared. The guard then correctly prevents result.WipeFailed from being set. (6) Net result: both old and new code silently clear wipe_ref; the PR does not make the situation worse.

The fix described by verifiers — wrapping the entire if wipeCmdUUID != "" block with wipeCmdStatus != "" — would address the pre-existing issue, but that is beyond the scope of this PR's intended change (adding the wipe-failed activity). The scenario is also non-standard in practice: Exec commands normally receive responses, not -only responses. The pre-existing nature and low probability of triggering reduce urgency, but the issue warrants a follow-up ticket.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@getvictor do we want to address this feedback in this PR? I typically open up another PR for the "make the camp site better than you left it" feedback.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Another PR makes sense. Thanks.

Copy link
Copy Markdown
Member

@getvictor getvictor left a comment

Choose a reason for hiding this comment

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

Looks good. Please take a look and resolve the remaining AI review comments.

Copy link
Copy Markdown
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

♻️ Duplicate comments (1)
server/datastore/mysql/microsoft_mdm.go (1)

687-697: ⚠️ Potential issue | 🟠 Major

Skip wipe-state updates when the device did not report a concrete status.

Line 689 still treats wipeCmdStatus == "" as failure and Line 690 persists that failed state before Line 697 suppresses the activity. This can leave host_mdm_actions marked failed for an unreported wipe response.

Proposed fix
 		// if we received a Wipe command result, update the host's status
-		if wipeCmdUUID != "" {
+		if wipeCmdUUID != "" && wipeCmdStatus != "" {
 			wipeSucceeded := strings.HasPrefix(wipeCmdStatus, "2")
 			rowsAffected, err := updateHostLockWipeStatusFromResultAndHostUUID(ctx, tx, enrolledDevice.HostUUID,
 				"wipe_ref", wipeCmdUUID, wipeSucceeded, false,
 			)
@@
-			if wipeCmdStatus != "" && !wipeSucceeded && rowsAffected > 0 {
+			if !wipeSucceeded && rowsAffected > 0 {
 				result = &fleet.MDMWindowsSaveResponseResult{
 					WipeFailed: &fleet.MDMWindowsWipeResult{
 						HostUUID: enrolledDevice.HostUUID,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@server/datastore/mysql/microsoft_mdm.go` around lines 687 - 697, The code
currently treats an empty wipeCmdStatus as a failure; change the logic so we
only mark a wipe as failed when the device reported a concrete non-empty status
that does not indicate success. Concretely, in the block handling wipeCmdUUID,
compute wipeSucceeded only when wipeCmdStatus != "" (e.g., wipeSucceeded :=
wipeCmdStatus != "" && strings.HasPrefix(wipeCmdStatus, "2")) and only call
updateHostLockWipeStatusFromResultAndHostUUID or interpret rowsAffected as a
failure if wipeCmdStatus != ""; ensure the later check that logs or persists a
failure uses wipeCmdStatus != "" && !wipeSucceeded && rowsAffected > 0 so
empty/unknown statuses are skipped.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@server/datastore/mysql/microsoft_mdm.go`:
- Around line 697-700: The code currently creates a
fleet.MDMWindowsSaveResponseResult with a fleet.MDMWindowsWipeResult that only
sets HostUUID, which drops the concrete failure status (wipeCmdStatus) needed by
activity/webhook consumers; update the MDMWindowsWipeResult type to add fields
for the command failure details (e.g., WipeCommandStatus string and optionally
RowsAffected or ErrorMessage), then populate those new fields here when
wipeCmdStatus != "" && !wipeSucceeded && rowsAffected > 0 (in addition to
HostUUID), and adjust the activity/webhook payload creation code to include
these new fields so the wipe-failed event carries the actual device status.

---

Duplicate comments:
In `@server/datastore/mysql/microsoft_mdm.go`:
- Around line 687-697: The code currently treats an empty wipeCmdStatus as a
failure; change the logic so we only mark a wipe as failed when the device
reported a concrete non-empty status that does not indicate success. Concretely,
in the block handling wipeCmdUUID, compute wipeSucceeded only when wipeCmdStatus
!= "" (e.g., wipeSucceeded := wipeCmdStatus != "" &&
strings.HasPrefix(wipeCmdStatus, "2")) and only call
updateHostLockWipeStatusFromResultAndHostUUID or interpret rowsAffected as a
failure if wipeCmdStatus != ""; ensure the later check that logs or persists a
failure uses wipeCmdStatus != "" && !wipeSucceeded && rowsAffected > 0 so
empty/unknown statuses are skipped.
🪄 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.yaml

Review profile: CHILL

Plan: Pro

Run ID: 29f5fd57-917a-42d1-9948-8af46d9f8896

📥 Commits

Reviewing files that changed from the base of the PR and between 2bfa0aa and 18ef69a.

📒 Files selected for processing (3)
  • server/datastore/mysql/microsoft_mdm.go
  • server/fleet/activities.go
  • server/service/mdm_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • server/fleet/activities.go

Comment on lines +697 to +700
if wipeCmdStatus != "" && !wipeSucceeded && rowsAffected > 0 {
result = &fleet.MDMWindowsSaveResponseResult{
WipeFailed: &fleet.MDMWindowsWipeResult{
HostUUID: enrolledDevice.HostUUID,
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.

⚠️ Potential issue | 🟠 Major

Preserve the failure status for activity/webhook consumers.

The datastore has wipeCmdStatus here, but the structured result only carries HostUUID. That drops the failure reason/details requested for the wipe-failed event and prevents the service/webhook payload from including the concrete device status.

Proposed direction
 				result = &fleet.MDMWindowsSaveResponseResult{
 					WipeFailed: &fleet.MDMWindowsWipeResult{
-						HostUUID: enrolledDevice.HostUUID,
+						HostUUID:    enrolledDevice.HostUUID,
+						CommandUUID:  wipeCmdUUID,
+						StatusCode:   wipeCmdStatus,
 					},
 				}

Also extend fleet.MDMWindowsWipeResult and the activity payload to expose these fields.

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

In `@server/datastore/mysql/microsoft_mdm.go` around lines 697 - 700, The code
currently creates a fleet.MDMWindowsSaveResponseResult with a
fleet.MDMWindowsWipeResult that only sets HostUUID, which drops the concrete
failure status (wipeCmdStatus) needed by activity/webhook consumers; update the
MDMWindowsWipeResult type to add fields for the command failure details (e.g.,
WipeCommandStatus string and optionally RowsAffected or ErrorMessage), then
populate those new fields here when wipeCmdStatus != "" && !wipeSucceeded &&
rowsAffected > 0 (in addition to HostUUID), and adjust the activity/webhook
payload creation code to include these new fields so the wipe-failed event
carries the actual device status.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The activity struct matches the existing ActivityTypeWipedHost. The webhook consumer just needs to know which host failed, not the specific MDM status code. Would adding a StatusCode really be that much beneficial?

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 wipe failed activity for Windows hosts

3 participants