Skip to content

CSAH: clear state on ABM re-enrollment#44722

Open
MagnusHJensen wants to merge 6 commits intomainfrom
43945-clear-state-on-reenrollment
Open

CSAH: clear state on ABM re-enrollment#44722
MagnusHJensen wants to merge 6 commits intomainfrom
43945-clear-state-on-reenrollment

Conversation

@MagnusHJensen
Copy link
Copy Markdown
Member

@MagnusHJensen MagnusHJensen commented May 5, 2026

Related issue: Resolves #43945

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

  • If paths of existing endpoints are modified without backwards compatibility, checked the frontend/CLI for any necessary changes

Testing

Summary by CodeRabbit

  • New Features

    • Configurable option to preserve past host activity history during Apple Business Manager re-enrollment.
    • Re-enrollment can perform a targeted reset of host MDM state and upcoming activities when preservation is disabled.
    • Token-update flow now conditionally triggers the reenrollment reset based on device/migration state and the preserve flag.
  • Bug Fixes

    • Host vitals and host-scoped data are cleared on ABM re-enrollment when preservation is disabled.
    • Reset is skipped during specific migration scenarios to avoid disruption.
  • Tests

    • Added tests and mocks validating reset behavior, the preservation flag, and migration-based skip logic.

Copilot AI review requested due to automatic review settings May 5, 2026 10:22
@MagnusHJensen MagnusHJensen requested a review from a team as a code owner May 5, 2026 10:22
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.

if err != nil {
return ctxerr.Wrap(ctx, err, "associating host with idp account")
}
} else if idpUUID == "" && len(hosts) > 0 {
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

While this handles OTA enrollment, I found it made sense to keep the parity up between OTA and ADE "in-sync".

This is called via the Install profile from the device on the /ota_enrollment.

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

This PR adds ABM/ADE re-enrollment reset logic to Apple MDM TokenUpdate, plus datastore support and tests, so Fleet can clear more host-scoped state when a device re-enrolls during Setup Assistant.

Changes:

  • Gate a new Apple re-enrollment reset in TokenUpdate on AwaitingConfiguration, TokenUpdateTally == 1, and the existing macOS migration skip.
  • Add MDMAppleResetOnReenrollment in the MySQL datastore, including transactional upcoming-activity cancellation and host-state cleanup.
  • Add service/datastore tests and a changelog entry for the new behavior.

Reviewed changes

Copilot reviewed 7 out of 8 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
server/service/apple_mdm.go Calls the new datastore reset during qualifying Apple TokenUpdate flows.
server/service/apple_mdm_test.go Adds coverage for the new TokenUpdate gating behavior and preserve flag forwarding.
server/mock/datastore_mock.go Extends the datastore mock with the new re-enrollment reset method.
server/fleet/datastore.go Adds the new datastore interface method and its comment.
server/datastore/mysql/apple_mdm.go Implements the new re-enrollment reset and adds IdP-association cleanup in related enrollment paths.
server/datastore/mysql/apple_mdm_test.go Adds datastore tests for host-scoped reset behavior and preserve flag behavior.
server/datastore/mysql/activities.go Extracts a tx-aware batch upcoming-activity cancellation helper for reuse.
changes/37682-clear-state-on-abm-re-enrollment Adds the user-visible changelog entry for the feature.

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

Comment thread server/datastore/mysql/apple_mdm.go
Comment thread server/datastore/mysql/apple_mdm.go Outdated
Comment thread server/service/apple_mdm.go Outdated
Comment thread changes/37682-clear-state-on-abm-re-enrollment Outdated
Comment thread server/fleet/datastore.go Outdated
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 5, 2026

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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: c8cdb99a-f7bc-4d38-a3e7-47c85f0cb29b

📥 Commits

Reviewing files that changed from the base of the PR and between fae0485 and a21f263.

📒 Files selected for processing (1)
  • server/service/integration_mdm_test.go

Walkthrough

Adds Datastore.MDMAppleResetOnReenrollment(ctx, hostUUID, preserveHostActivities) which cancels upcoming host activities, deletes host-scoped Apple MDM rows (label membership, host_mdm_commands, host_mdm_idp_accounts, and a set of host vitals/reference tables), and optionally deletes past activity history and deactivates nano enrollment queue entries. Refactors batch upcoming-activity cancellation into a transaction-aware helper, clears host_mdm_idp_accounts on certain OTA/enroll-ref conditions, and invokes the reset from TokenUpdate when gated by nano-enrollment, TokenUpdateTally, and migration flags. Tests and mock updates for the new method and TokenUpdate behavior were added.

Possibly related PRs

  • fleetdm/fleet#44323: Modifies host upcoming-activity cancellation and introduces/uses batch cancellation helpers used by the reset flow.
  • fleetdm/fleet#43827: Adjusts Apple MDM reenrollment/unenroll reset flows and host-scoped cleanup logic that overlaps with the added reset method.
  • fleetdm/fleet#42421: Also touches Apple MDM checkin/token handling in server/service/apple_mdm.go and may intersect with TokenUpdate gating changes.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.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 'CSAH: clear state on ABM re-enrollment' is directly related to the main objective of clearing host state during ABM re-enrollment, which is the primary focus of the changeset.
Description check ✅ Passed The PR description includes all critical checklist items for submission (changes file, input validation, testing, QA) with boxes checked, references the linked issue #43945, and indicates tests were added/updated and manual QA was completed.
Linked Issues check ✅ Passed The PR implements all major coding requirements from issue #43945: new MDMAppleResetOnReenrollment datastore method, conditional triggering in TokenUpdate with proper gating, clearing of host vitals/activities/memberships, and preserve flag support.
Out of Scope Changes check ✅ Passed All changes are directly scoped to issue #43945: datastore reset method, service layer integration, mock updates, tests for the reset logic, and a changelog entry. Changes to BatchCancelAllHostUpcomingActivities are refactoring to support the new reset functionality.

✏️ 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 43945-clear-state-on-reenrollment

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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

🧹 Nitpick comments (1)
server/datastore/mysql/apple_mdm_test.go (1)

5559-5563: ⚡ Quick win

Add an explicit idempotency assertion for repeated resets.

The method contract is “safe to call multiple times,” but each branch currently validates only a single call. A second call assertion would lock that down and prevent regressions.

Suggested test additions
 		require.NoError(t, ds.MDMAppleResetOnReenrollment(ctx, hostA.UUID, true))

 		// host A: everything cleared
 		assert.Equal(t, counts{label: 0, upcoming: 0}, countRows(t, hostA))
+		// idempotent on repeated execution
+		require.NoError(t, ds.MDMAppleResetOnReenrollment(ctx, hostA.UUID, true))
+		assert.Equal(t, counts{label: 0, upcoming: 0}, countRows(t, hostA))

 		// host B: untouched (control - proves the reset is host-scoped)
 		assert.Equal(t, seeded, countRows(t, hostB))
 		require.NoError(t, ds.MDMAppleResetOnReenrollment(ctx, hostB.UUID, false))
 		assert.Equal(t,
 			activityCounts{pastActivity: 0, activeQueue: 0, inactiveQueue: 2, ackedCommand: 1},
 			countActivityRows(t, hostB))
+		// idempotent on repeated execution
+		require.NoError(t, ds.MDMAppleResetOnReenrollment(ctx, hostB.UUID, false))
+		assert.Equal(t,
+			activityCounts{pastActivity: 0, activeQueue: 0, inactiveQueue: 2, ackedCommand: 1},
+			countActivityRows(t, hostB))
 	})

Also applies to: 5667-5670

🤖 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/datastore/mysql/apple_mdm_test.go` around lines 5559 - 5563, Add an
explicit idempotency assertion by calling ds.MDMAppleResetOnReenrollment(ctx,
hostA.UUID, true) a second time and asserting no error and that counts remain
unchanged via countRows(t, hostA); update both occurrences (the block around
MDMAppleResetOnReenrollment/assert.Equal at the shown location and the similar
block at the other location ~5667-5670) so the test verifies the method is safe
to call repeatedly and the hostA row counts stay the same after the repeated
reset.
🤖 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 `@changes/37682-clear-state-on-abm-re-enrollment`:
- Line 1: Fix the typo in the changelog entry by replacing the misspelled word
"activites" with the correct spelling "activities" in the changelog string (the
text line "Implemented clearing host vitals on AB host re-enrollment, with a
config option to preserve past host activites."); update that exact string to
use "activities".

In `@server/datastore/mysql/apple_mdm.go`:
- Around line 8434-8435: The UPDATE is too broad: in apple_mdm.go the
tx.ExecContext call that deactivates nano_enrollment_queue using "WHERE id IN
(SELECT id FROM nano_enrollments WHERE device_id = ?)" (hostUUID) will cancel
unrelated commands; narrow the WHERE to only the queue rows associated with the
specific execution/activity IDs you are deleting. Modify the query in the same
function to join/filter by the execution IDs (e.g., executionIDs or activityIDs
used in the surrounding cleanup logic) — for example filter
nano_enrollment_queue by execution_id IN (...) or join to
nano_enrollment_commands/nano_activities to match the exact activity-linked
executions rather than all rows for the device UUID.
- Around line 8384-8426: The reset loop in MDMAppleResetOnReenrollment uses
appleHostRefsForMDMReset but omits host_mdm_idp_accounts and
host_maintenance_windows (and contains a duplicate "host_disks"), so add
"host_mdm_idp_accounts" and "host_maintenance_windows" to the
appleHostRefsForMDMReset slice and remove the duplicate "host_disks" entry (or
explicitly execute DELETEs for those two tables before/after the existing loop)
so IdP associations and maintenance windows are removed during reenrollment
reset; verify clearHostActivitiesForAppleMDMReset remains unchanged for
activity-specific cleanup.

---

Nitpick comments:
In `@server/datastore/mysql/apple_mdm_test.go`:
- Around line 5559-5563: Add an explicit idempotency assertion by calling
ds.MDMAppleResetOnReenrollment(ctx, hostA.UUID, true) a second time and
asserting no error and that counts remain unchanged via countRows(t, hostA);
update both occurrences (the block around
MDMAppleResetOnReenrollment/assert.Equal at the shown location and the similar
block at the other location ~5667-5670) so the test verifies the method is safe
to call repeatedly and the hostA row counts stay the same after the repeated
reset.
🪄 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: f6de5ac0-8551-4f1b-82dd-d0c55d9f13ca

📥 Commits

Reviewing files that changed from the base of the PR and between 84b0b15 and 628df80.

📒 Files selected for processing (8)
  • changes/37682-clear-state-on-abm-re-enrollment
  • server/datastore/mysql/activities.go
  • server/datastore/mysql/apple_mdm.go
  • server/datastore/mysql/apple_mdm_test.go
  • server/fleet/datastore.go
  • server/mock/datastore_mock.go
  • server/service/apple_mdm.go
  • server/service/apple_mdm_test.go

Comment thread changes/37682-clear-state-on-abm-re-enrollment Outdated
Comment thread server/datastore/mysql/apple_mdm.go
Comment on lines +8434 to +8435
if _, err := tx.ExecContext(ctx, "UPDATE nano_enrollment_queue SET active = 0 WHERE active = 1 AND id IN (SELECT id FROM nano_enrollments WHERE device_id = ?)", hostUUID); err != nil {
return ctxerr.Wrap(ctx, err, "deactivate nano enrollment queue for mdm reset", "host_uuid", 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 | ⚡ Quick win

The nano queue cleanup is broader than the activities being removed.

This update deactivates every active nano_enrollment_queue row for any enrollment attached to the device ID. When preserveHostActivities is false, that can also cancel unrelated fresh commands from the reenrollment flow, not just commands backed by the host activities you're deleting here. Please scope this to the specific execution IDs / activity-linked commands being cleared.

As per coding guidelines, added SQL queries should apply precise filtering for the specific entity being updated.

🤖 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/datastore/mysql/apple_mdm.go` around lines 8434 - 8435, The UPDATE is
too broad: in apple_mdm.go the tx.ExecContext call that deactivates
nano_enrollment_queue using "WHERE id IN (SELECT id FROM nano_enrollments WHERE
device_id = ?)" (hostUUID) will cancel unrelated commands; narrow the WHERE to
only the queue rows associated with the specific execution/activity IDs you are
deleting. Modify the query in the same function to join/filter by the execution
IDs (e.g., executionIDs or activityIDs used in the surrounding cleanup logic) —
for example filter nano_enrollment_queue by execution_id IN (...) or join to
nano_enrollment_commands/nano_activities to match the exact activity-linked
executions rather than all rows for the device UUID.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This seems like it's technically true, however with the current setup we don't queue any commands before this point (our apple_mdm worker runs after this).

Not sure how we would be able to narrow it down further, but also from my testing, this did not cause any problems.

return "", ctxerr.New(ctx, "machine info is nil")
}

if enrollRef == "" {
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This here handles clearing out the host_mdm_idp_accounts if we enroll without an IDP reference.

Before we upserted with an empty row, which might have mostly behaved the same, but I found it a bit weird.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

It will then later in the Authenticate step, reconciled into the host_emails and host_scim_user tables, or removed if we remove it here.

@codecov
Copy link
Copy Markdown

codecov Bot commented May 5, 2026

Codecov Report

❌ Patch coverage is 57.35294% with 29 lines in your changes missing coverage. Please review.
✅ Project coverage is 66.70%. Comparing base (442f6d0) to head (a21f263).
⚠️ Report is 51 commits behind head on main.

Files with missing lines Patch % Lines
server/datastore/mysql/apple_mdm.go 53.65% 11 Missing and 8 partials ⚠️
server/service/apple_mdm.go 45.45% 3 Missing and 3 partials ⚠️
server/datastore/mysql/activities.go 75.00% 2 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #44722      +/-   ##
==========================================
+ Coverage   66.68%   66.70%   +0.01%     
==========================================
  Files        2651     2651              
  Lines      213440   213568     +128     
  Branches     9638     9638              
==========================================
+ Hits       142327   142454     +127     
+ Misses      58149    58148       -1     
- Partials    12964    12966       +2     
Flag Coverage Δ
backend 68.57% <57.35%> (+0.02%) ⬆️

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

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

8411-8421: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

host_mdm_idp_accounts still survives the reenrollment reset.

This cleanup only deletes host_id-keyed tables, so the stale IdP association keyed by host_uuid is left behind after the first TokenUpdate. That can carry the previous user's identity into the new enrollment.

Suggested fix
 		for _, table := range appleHostRefsForMDMReset {
 			if _, err := tx.ExecContext(ctx, fmt.Sprintf("DELETE FROM %s WHERE host_id = ?", table), hostID); err != nil {
 				return ctxerr.Wrap(ctx, err, fmt.Sprintf("clear %s for mdm reset", table), "host_uuid", hostUUID)
 			}
 		}
+
+		if _, err := tx.ExecContext(ctx, `DELETE FROM host_mdm_idp_accounts WHERE host_uuid = ?`, hostUUID); err != nil {
+			return ctxerr.Wrap(ctx, err, "clear host_mdm_idp_accounts for mdm reset", "host_uuid", hostUUID)
+		}
 
 		if !preserveHostActivities {
 			if err := ds.clearHostActivitiesForAppleMDMReset(ctx, tx, hostUUID, hostID); err != nil {
 				return ctxerr.Wrap(ctx, err, "clear host activities for mdm reset")
 			}
🤖 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/datastore/mysql/apple_mdm.go` around lines 8411 - 8421, The code
currently deletes only host_id-keyed tables in the apple MDM reset loop
(appleHostRefsForMDMReset) but leaves host_mdm_idp_accounts (which is keyed by
host_uuid) intact, so add an explicit deletion of host_mdm_idp_accounts by
host_uuid before/after the existing loop; call tx.ExecContext(ctx, "DELETE FROM
host_mdm_idp_accounts WHERE host_uuid = ?", hostUUID) and wrap errors with
ctxerr.Wrap (matching the style used elsewhere), or alternatively include
host_mdm_idp_accounts in the cleanup using hostUUID and ensure the error context
includes "clear host_mdm_idp_accounts for mdm reset" and the host_uuid value.
🤖 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/datastore/mysql/apple_mdm.go`:
- Around line 8399-8405: The host lookup here uses a non-deterministic SELECT by
uuid; replace it with the same deterministic host-resolution used by
MDMResetEnrollment so both flows pick the same host record. Locate the SQL/logic
in MDMResetEnrollment that resolves a host UUID to a single host id (or extract
it into a helper like resolveHostIDByUUID), and use that exact query/path in
MDMAppleResetOnReenrollment (instead of the current simple `SELECT id FROM hosts
WHERE uuid = ?`), preserving its ordering/joins/limits and error handling so
duplicate-UUID rows are resolved identically.

---

Duplicate comments:
In `@server/datastore/mysql/apple_mdm.go`:
- Around line 8411-8421: The code currently deletes only host_id-keyed tables in
the apple MDM reset loop (appleHostRefsForMDMReset) but leaves
host_mdm_idp_accounts (which is keyed by host_uuid) intact, so add an explicit
deletion of host_mdm_idp_accounts by host_uuid before/after the existing loop;
call tx.ExecContext(ctx, "DELETE FROM host_mdm_idp_accounts WHERE host_uuid =
?", hostUUID) and wrap errors with ctxerr.Wrap (matching the style used
elsewhere), or alternatively include host_mdm_idp_accounts in the cleanup using
hostUUID and ensure the error context includes "clear host_mdm_idp_accounts for
mdm reset" and the host_uuid value.
🪄 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: 8fb63b0f-95b5-41af-92dc-9530eed4a25c

📥 Commits

Reviewing files that changed from the base of the PR and between 628df80 and 2acbf77.

📒 Files selected for processing (5)
  • changes/37682-clear-state-on-abm-re-enrollment
  • server/datastore/mysql/apple_mdm.go
  • server/fleet/datastore.go
  • server/service/apple_mdm.go
  • server/service/apple_mdm_test.go
✅ Files skipped from review due to trivial changes (1)
  • changes/37682-clear-state-on-abm-re-enrollment
🚧 Files skipped from review as they are similar to previous changes (2)
  • server/fleet/datastore.go
  • server/service/apple_mdm_test.go

Comment thread server/datastore/mysql/apple_mdm.go Outdated
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 current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@server/datastore/mysql/apple_mdm.go`:
- Around line 8382-8395: The appleHostRefsForMDMReset slice omits the
"host_device_auth" table causing MDMAppleResetOnReenrollment to leave stale
device-auth state; update the appleHostRefsForMDMReset variable to include
"host_device_auth" so MDMAppleResetOnReenrollment will clear device auth rows
for a host during re-enrollment.
🪄 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: 0632e2bb-37c4-46ae-b4ac-cdc3e953598a

📥 Commits

Reviewing files that changed from the base of the PR and between e41fb4c and fae0485.

📒 Files selected for processing (1)
  • server/datastore/mysql/apple_mdm.go

Comment on lines +8382 to +8395
// appleHostRefsForMDMReset are the tables referenced by host ids.
// These tables are cleared when the host is re-enrolled.
var appleHostRefsForMDMReset = []string{
"label_membership",
"host_disks",
"host_mdm_commands",
"host_batteries",
"host_operating_system",
"host_certificates",
"host_issues",
"host_last_known_locations",
"host_munki_info",
"host_munki_issues",
}
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 | ⚡ Quick win

Reset still leaves host_device_auth behind.

MDMAppleResetOnReenrollment doesn't include host_device_auth in the host-scoped tables it clears, so a wiped/re-enrolled device can retain stale device-auth state after the first TokenUpdate.

🧹 Minimal fix
 var appleHostRefsForMDMReset = []string{
 	"label_membership",
 	"host_disks",
 	"host_mdm_commands",
 	"host_batteries",
 	"host_operating_system",
 	"host_certificates",
 	"host_issues",
+	"host_device_auth",
 	"host_last_known_locations",
 	"host_munki_info",
 	"host_munki_issues",
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// appleHostRefsForMDMReset are the tables referenced by host ids.
// These tables are cleared when the host is re-enrolled.
var appleHostRefsForMDMReset = []string{
"label_membership",
"host_disks",
"host_mdm_commands",
"host_batteries",
"host_operating_system",
"host_certificates",
"host_issues",
"host_last_known_locations",
"host_munki_info",
"host_munki_issues",
}
// appleHostRefsForMDMReset are the tables referenced by host ids.
// These tables are cleared when the host is re-enrolled.
var appleHostRefsForMDMReset = []string{
"label_membership",
"host_disks",
"host_mdm_commands",
"host_batteries",
"host_operating_system",
"host_certificates",
"host_issues",
"host_device_auth",
"host_last_known_locations",
"host_munki_info",
"host_munki_issues",
}
🤖 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/datastore/mysql/apple_mdm.go` around lines 8382 - 8395, The
appleHostRefsForMDMReset slice omits the "host_device_auth" table causing
MDMAppleResetOnReenrollment to leave stale device-auth state; update the
appleHostRefsForMDMReset variable to include "host_device_auth" so
MDMAppleResetOnReenrollment will clear device auth rows for a host during
re-enrollment.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

That should be fine IMO.

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.

CSAH: Expanded re-enrollment reset for ABM-enrolling hosts

2 participants