fleet icon indicating copy to clipboard operation
fleet copied to clipboard

Cancel upcoming Apple MDM commands (excluding configuration profiles)

Open noahtalerman opened this issue 7 months ago • 12 comments

Goal

User story
As an IT admin,
I want to be able to cancel upcoming Apple MDM commands (excluding profiles)
so that I can cancel lock/wipe commands that I sent by mistake.

Use cases:

  • "I've sent a lock command to a device that is still pending, but now I want to cancel that and send a wipe command instead"

  • "I've sent a wipe command to this stolen device, but it's been recovered and I don't want to wipe it anymore" Image

  • https://learn.jamf.com/r/en-US/jamf-pro-documentation-11.17.0/Mass_Actions_for_Mobile_Devices

Changes

Product

  • [x] UI changes: Figma
    • "Allow list" of commands for this v1: lock, wipe, clear passcode, and enable lost mode
  • [x] CLI (fleetctl) usage changes: No changes
  • [x] YAML changes: No changes
  • [x] REST API changes:
    • https://github.com/fleetdm/fleet/pull/51038
  • [x] Fleet's agent (fleetd) changes: No changes
  • [x] Fleet server configuration changes: No changes
  • [x] Exposed, public API endpoint changes: No changes
  • [x] fleetdm.com changes: No changes
  • [x] GitOps mode UI changes: No changes
  • [x] GitOps generation changes: No changes
  • [x] Activity changes:
    • New type: "Canceled activity: MDM command"
    • https://github.com/fleetdm/fleet/pull/50633
  • [x] Permissions changes: No changes
  • [x] Changes to paid features or tiers: No changes
  • [x] My device and fleetdm.com/better changes: No changes
  • [x] Usage statistics: No changes
  • [x] Other reference documentation changes: No changes
  • [x] First draft of test plan added
  • [ ] Once shipped, requester has been notified
  • [ ] Once shipped, dogfooding issue has been filed https://github.com/fleetdm/fleet/issues/53749

Engineering

  • [x] Test plan is finalized
  • [x] Contributor API changes: No changes
  • [x] Feature guide changes: Update articles/lock-wipe-hosts.md
  • [x] This is a premium only feature: Yes

ℹ️  Please read this issue carefully and understand it. Pay special attention to UI wireframes, especially "dev notes".

Risk assessment

  • Risk level: Low in terms of performance/log skew however high in that a cancelled Lock command in particular could be disastrous if it actually runs on a host and gets dropped by Fleet.

Test plan

Make sure to go through the list and consider all events that might be related to this story, so we catch edge cases earlier.

Core flow

Testing new endpoint DELETE /api/v1/fleet/hosts/:id/commands/:command_uuid

  • [x] Cancel pending lock/wipe/clear passcode/enable lost mode on offline host → 204, host_mdm_actions ref cleared, past activity created, UI doesn't show host in locked/wiped or pending states
  • [x] Cancel lock/wipe/clear passcode/enable lost mode that has already run -> 400
  • [x] Cancel non-eligible command (e.g. config profile, refetch, etc) → 400 "Only lock, wipe, and clear passcode commands can be canceled."
  • [x] Cancel command on a host it wasn't sent to → 404
  • [x] Cancel non-existent command or host → 404
  • [x] Re-issue same command type(wipe, lock, enable lost mode) after cancelling one → 200 (new ref set and UI shows correct state)
  • [x] UI does not show cancel button on ineligible commands(past commands or ineligible types in the upcoming list)

Permissions

  • [x] Verify role restrictions are applied correctly for global roles
    • [x] All roles that can lock/wipe should be able to cancel, roles that cannot lock/wipe cannot cancel
  • [x] Verify role restrictions are applied correctly for fleet-level roles
    • [x] All roles that can lock/wipe should be able to cancel, roles that cannot lock/wipe cannot cancel

Edge cases

  • [x] Cancel a lock, wipe or enable lost mode command between the time a host fetches it and actually acks it(engineer implementing backend subtask to provide method for testing). Cancel activity is still created but end-state is host is in the locked/wiped state and user can view PIN or disable lost mode

Supplemental testing

Testing notes

Confirmation

  1. [ ] Engineer: Added comment to user story confirming successful completion of test plan (include any special setup, test data, or configuration used during development/testing if applicable).
  2. [ ] QA: Added comment to user story confirming successful completion of test plan.

noahtalerman avatar Apr 07 '26 20:04 noahtalerman

Hey @georgekarrv when you get the chance, can you please T-shirt size this story? We think it contributes to our goal of being "complete" for Apple device management.

noahtalerman avatar Apr 07 '26 20:04 noahtalerman

FYI @ddribeiro @kitzy added gema to this story.

noahtalerman avatar Apr 07 '26 20:04 noahtalerman

when you get the chance, can you please T-shirt size this story? We think it contributes to our goal of being "complete" for Apple device management.

Hey @georgekarrv justing giving you another ping! as a reminder :)

noahtalerman avatar Apr 08 '26 17:04 noahtalerman

It's a bit complicated since the plan was originally to have mdm commands in the unified queue, they still aren't. The unified queue has the cancel functionality already.

So to bring mdm commands into the unified queue M-L with load tests required.

Today the commands are sent to apple immediately and I'm not sure the effort to modify that after the fact. Could be XS - S

My recommendation is to investigate what the options are once the command is already sent to an offline device first to retract it because it sounds like that's the one that would impact more customers here.

georgekarrv avatar Apr 08 '26 18:04 georgekarrv

@georgekarrv I think we want to go with whatever's simplest for us.

My recommendation is to investigate what the options are once the command is already sent to an offline device first to retract it because it sounds like that's the one that would impact more customers here.

Is this something you can help us with? That way, we can T-shirt size this and find a spot for it on the roadmap.

noahtalerman avatar Apr 09 '26 17:04 noahtalerman

Hey @georgekarrv deciding that we don't want to do the unified queue anymore. That way, we avoid MDM commands getting stuck behind software installs / script runs and vice versa.

So, I gave this one a S and added the 4.91 milestone. Please feel free to update the T-shirt size.

FYI @JordanMontgomery

noahtalerman avatar Apr 13 '26 17:04 noahtalerman

Context an implementer needs first

  • Apple MDM commands are not in the unified queue. upcoming_activities.activity_type only covers scripts and software installs. Lock/wipe/clear passcode go straight into nano_commands + one nano_enrollment_queue row per enrollment (active = 1, PK (id, command_uuid) where id is the host UUID for the device channel), with an immediate APNs push. The existing DELETE /hosts/:id/activities/upcoming/:activity_id flow and its "about to run" guard (server/service/activities.go:145-205) apply only to script-based lock/wipe on Windows/Linux and are untouched by this story.
  • "Pending" for cancellation means active = 1 and no terminal nano_command_results row. A NotNow result doesn't count: the device deferred the command, it gets re-served on the next fresh check-in (RetrieveNextCommand's skipNotNow logic), and the listing layer maps it to command_status = 'pending' anyway (listMDMCommandsByHostIdentifier, server/datastore/mysql/mdm.go:263, NotNow mapping at :357) — so a NotNow'd command is still upcoming and stays cancellable. Setting active = 0 makes a command disappear from every feed with no further work — the pattern has many internal writers (closest: the VPP-install cancel, UPDATE nano_enrollment_queue SET active = 0 WHERE id = ? AND command_uuid = ? at server/datastore/mysql/activities.go:770; also re-enrollment ClearQueue, SCEP renew, profile deletion).
  • There is no "delivered" state. RetrieveNextCommand (server/mdm/nanomdm/storage/mysql/queue.go:193) is a pure SELECT — handing a command to a device writes nothing. A cancel can therefore always race a device that already fetched the command; this is unavoidable (Apple's protocol has no retract-after-deliver) and is why the self-heal below exists.
  • Command types per platform. macOS lock = DeviceLock with a server-generated 6-digit PIN stored in host_mdm_actions.unlock_pin and embedded in the plist persisted in nano_commands.command (server/mdm/apple/commander.go:111-185, PIN in the plist at :131-146). iOS/iPadOS lock = EnableLostMode (commander.go:187), no PIN. Wipe = EraseDevice (commander.go:249); its PIN exists only in the plist. Clear passcode = ClearPasscode (commander.go:685), iOS/iPadOS only, no host_mdm_actions ref (clear_passcode_ref is Android-only today; Apple tracking is #46286) and no result-processing hook.
  • Refs must be cleared on cancel. GetHostLockWipeStatus (server/datastore/mysql/scripts.go:1471) resolves host_mdm_actions.lock_ref/wipe_ref against nano_commands + results without checking active — an uncleared ref shows "Lock pending" forever.
  • Late acks no-op today once refs are cleared. The result hook (server/service/apple_mdm.go:5190 for DeviceLock/EraseDevice, :5231 for EnableLostMode) calls UpdateHostLockWipeStatusFromAppleMDMResult (server/datastore/mysql/scripts.go:2488), whose UPDATE is keyed WHERE hma.<ref_col> = ?. After a cancel clears the ref, a late ack updates nothing: the device is locked/wiped but Fleet shows unlocked. The self-heal in sub-task 1 closes this.
  • Re-lock after cancel already works. EnqueueDeviceLockCommand (server/datastore/mysql/nanomdm_storage.go:235) treats a lock_ref pointing at an active = 0 queue row as an orphan and allows a fresh lock (:248-263).
  • The UI feed already exists. The host Activity card has a "Show MDM commands" toggle (frontend/pages/hosts/details/cards/Activity/Activity.tsx:133); the Upcoming tab queries command_status: "pending" (frontend/pages/hosts/details/HostDetailsPage/HostDetailsPage.tsx:621-651). This story only adds the cancel affordance to eligible rows.
  • BatchCancelAllHostUpcomingActivities after a wipe ack is keyed on result status, not refs (server/service/apple_mdm.go:5201-5208), so it still fires for a late ack of a canceled wipe — no extra work needed there.

Product and design decisions folded into these sub-tasks

  • Allowlist = DeviceLock, EraseDevice, ClearPasscode, EnableLostMode. iOS/iPadOS lock is EnableLostMode, so it must be cancellable; PR #51038 omits it and needs amending. DisableLostMode (pending iOS unlock) is out of scope for v1.
  • Self-heal instead of recording the PIN in the activity. When an Acknowledged result arrives for a canceled lock/wipe, restore host_mdm_actions (PIN parsed from the stored plist) so the host shows locked/wiped and POST /hosts/:id/unlock returns the PIN. This avoids exposing PINs to observers and audit-log streams. Product confirmed, including that the earlier canceled_mdm_command activity stays in the feed as-is when self-heal fires.
  • NotNow'd commands are cancellable. A NotNow result means the device deferred the command; it re-serves on every fresh check-in until acknowledged, still shows as pending in the feed, and is exactly the kind of stuck command an admin wants to retract. The cancel guard blocks only terminal results (Acknowledged, Error, CommandFormatError). Apple shouldn't NotNow these command types, but if it happens the command must remain cancellable.
  • Authorization = MDMCommandAuthz write (global/team admin, maintainer, gitops — server/authz/policy.rego:1031-1045), mirroring LockHost (ee/server/service/hosts.go:46-62): whoever can send a lock can cancel one. Not cancel_host_activity (which excludes gitops and belongs to the unified queue).
  • Activity command_type = raw request type ("DeviceLock", not "lock"), matching the Figma feed strings and toast interpolation. PR #50633's example needs amending.
  • Canceled commands vanish from command listings. No result row means they appear in neither the pending nor the ran/failed feed; the canceled_mdm_command past activity is the only record. Product accepted this.
  • Second cancel of the same command → 404, consistent with the unified queue (whose row is deleted on cancel, so a repeat cancel is a not-found).
  • Clear passcode is queue-deactivation + activity only. No ref to clear, no state to heal. #46286 (Apple clear_passcode_ref) must account for cancellation when it lands.

Feature design

sequenceDiagram
    autonumber
    actor Admin
    participant UI as Host details UI
    participant API as Fleet API
    participant EE as EE service
    participant DB as MySQL (nano_*, host_mdm_actions)
    participant Mac as Device

    note over Admin,Mac: 1. Lock issued (existing flow)
    Admin->>API: POST /hosts/:id/lock
    API->>EE: LockHost
    EE->>DB: EnqueueDeviceLockCommand (queue active=1, lock_ref + unlock_pin)
    EE-->>Mac: APNs push

    note over Admin,Mac: 2. Cancel while pending
    Admin->>UI: Trash icon on pending command → "Cancel upcoming command" modal
    UI->>API: DELETE /hosts/:id/commands/:command_uuid
    API->>EE: CancelHostMDMCommand
    EE->>DB: one tx: eligible type + no result row → active=0, clear matching ref
    EE->>DB: NewActivity(canceled_mdm_command)
    API-->>UI: 204 → success toast

    note over Admin,Mac: 3a. Device never fetched the command
    Mac->>API: Idle check-in
    API->>DB: RetrieveNextCommand (active=1 only) → command never served

    note over Admin,Mac: 3b. Device was already executing (race) → self-heal
    Mac->>API: Acknowledged result for canceled command
    API->>DB: StoreCommandReport (result row stored as today)
    API->>DB: UpdateHostLockWipeStatusFromAppleMDMResult: queue row active=0 + ref NULL → restore ref (+ PIN from stored plist), then normal ack update
    note over UI,DB: Host shows locked/wiped, POST unlock returns the PIN

JordanMontgomery avatar Aug 14 '26 14:08 JordanMontgomery

https://github.com/fleetdm/fleet/pull/51685 branch adds the case to delay the ack to test the edge cases in this task.

QAed the other behaviour too.

raju249 avatar Sep 04 '26 10:09 raju249

Test environment and assets

  • Build 4.92.0-rc.2609100301 (093c8aa47d)
  • MacBook Air macOS 26.6.2, macOS 27.0 (upgraded)
  • MacBook Neo macOS 27.0
  • iPhone on iOS 27.0

Summary

Cancel verified across all four cancelable Apple MDM command types, on both macOS and iOS, at the UI and datastore level. Hardware: a MacBook Air (No team) for lock/wipe, and an ADE-enrolled, supervised iPhone on iOS 27.0 (team-scoped) for clear passcode and lost mode - commands were held pending by putting the device to sleep or into airplane mode, so the cancels raced nothing. A second MacBook was used to let lock and wipe run to completion as controls. Permissions were exercised with purpose-created users at both global and fleet level. No blocking defects.

Cancelling a pending command - all four allowlisted types

  • DeviceLock (macOS, asleep, ×2), EraseDevice (macOS, asleep and awake), ClearPasscode (iOS) and EnableLostMode (iOS, airplane mode) each cancel with 204
  • In every case the queue row goes active = 0 with no result row ever written - the command genuinely never reaches the device
  • Each produces a canceled_mdm_command activity carrying the raw request type - "DeviceLock", "EraseDevice", "ClearPasscode", "EnableLostMode" - not the friendly lock/wipe names
  • host_mdm_actions refs are cleared where they exist: lock_ref for lock, wipe_ref for wipe. Clear passcode and lost mode clear nothing, and nothing is expected - there is no lost_mode_ref column, and clear_passcode_ref is Android-only today (Apple tracking is #46286). A host with no prior row gets one created by the lock attempt, with every ref NULL
  • UI throughout: toast on send, command in the upcoming activity feed, pending badge, payload inspectable via the "i" affordance, cancel via "x" behind a confirmation modal, badge removed on confirm

Commands still run when not cancelled

  • A lock allowed to proceed executes normally: PIN surfaced in the UI, entered on the Mac, device unlocks, Locked badge behaves correctly
  • A wipe allowed to proceed is acknowledged and completes
  • Re-issuing the same command type after a cancel produces a new command that queues cleanly - verified for lock, wipe, and lost mode

Rejections

  • Ineligible command type → 400 Couldn't cancel. Only lock, wipe, and clear passcode commands can be canceled. - confirmed against InstallProfile, DeclarativeManagement and DeviceConfigured on a host that actually held them
  • A command that has already run → 400 Couldn't cancel. The command has already run on the host.
  • Command sent to a different host → 404; non-existent command UUID → 404; non-existent host → 404
  • Second cancel of the same command → 404, consistent with the unified queue
  • Worth noting for anyone automating against this: the specific message is in errors[0].reason. The top-level message is just the generic "Bad request"

NotNow is not terminal

  • A command carrying a NotNow result is still cancellable (204) while the same command type carrying an Acknowledged result is refused with the already-run 400. The guard discriminates on exactly status != 'NotNow', in both the eligibility check and the deactivating update

Permissions

  • Cancel succeeds for global admin, global maintainer and global GitOps (204), and for team admin and team maintainer on their own fleet's host (204)
  • Cancel is refused for global observer, and for team admin and team observer targeting a host outside their scope (403)
  • Denials leave no trace - after three consecutive 403s the command was still active = 1, and only the authorized call deactivated it. A rejected cancel does not half-cancel
  • This matches the existing lock/wipe authorization exactly, as the issue specifies

Fetch-to-ack race

  • Cancelling in the window between the host fetching a command and acknowledging it produces the cancel activity while the device still ends in the locked/wiped state, with the PIN retrievable - verified for lock and wipe

chrstphr84 avatar Sep 10 '26 15:09 chrstphr84

notified customer-juliana!

kellykroening avatar Sep 25 '26 15:09 kellykroening

Notified customer-gema, removing tag and closing issue

shc-sync avatar Sep 29 '26 20:09 shc-sync

A moment of thought before the command takes flight saves device and soul

fleet-release avatar Sep 29 '26 20:09 fleet-release