#53891·fleet

ODFR: Backend key-rotation API, command and query ingestion adjustments

Author: JordanMontgomeryCreated Sep 23, 2026Updated Sep 23, 2026
Labels#g-apple-at-work~sub-task

Related user story

#50149

Task

Ships the whole backend: the datastore methods around the new column, the RotateFileVaultKey command in the commander with placeholder expansion in nanomdm, the Premium rotate endpoint with its eligibility checks and activity, rotation_pending on the GET encryption key response, the command result handling that stores the new key or falls back to Escrow Buddy, and the plaintext-compare guard in the osquery ingest. Frontend can build against the documented contract while this is in review.

Note that the way this all works is we send a RotateFilevaultKey command which includes the encryption cert for the reply(required - Apple fails the command if we don't include it in my tests) and the old password. When the host processes the command, assuming the password is good and current it rotates and escrows the new one in the command Ack. The tricky part is that it also writes out /var/db/FilevaultPRK.dat and even when the key in the escrow profile is the exact same byte-for-byte as the key on-disk it uses a different PKCS CMS, meaning the key we get back from osquery looks like a different key until we decrypt and validate that it isn't. So rather than update it in the DB and go into the usual verifying loop in the case where we have a current, decryptable key for the host and a new one shows up we'll do a live verification that its plaintext matches the prior and swap out the encrypted portion without writing another entry into the archive, etc. This avoids duplicate rows in the archive, avoids any duplicate activities, avoids the key going verified(command ack)->verifying(osquery)->verified(cron) and means further osquery ingests will see it as unchanged and ultimately leads to a nicer user experience with the caveat that it does increase our work here a bit.

Details below are suggested implementation, as usual code itself is up to implementer

Constants and types

  • server/fleet/apple_mdm.go:1779 block: add RotateFileVaultKeyCmdName = "RotateFileVaultKey".
  • server/fleet/mdm.go:1280: add RotateFileVaultKeyCmdName to AppleMDMStandardRetentionRequestTypes. Do not add it to CancelableAppleMDMRequestTypes at apple_mdm.go:1787.
  • server/fleet/secrets.go, next to HostSecretRecoveryLockPassword at line 23: HostSecretFileVaultKey = "FILEVAULT_KEY".
  • server/fleet/hosts.go:2034, HostDiskEncryptionKey: add
go
RotationCommandUUID *string `json:"-" db:"rotation_command_uuid"`
RotationPending     bool    `json:"rotation_pending" db:"-"`
  • server/fleet/activities.go, after ActivityTypeRotatedHostRecoveryLockPassword at line 1186 and mirroring ActivityTypeFailedToRotateManagedLocalAccountPassword at line 1229:
go
type ActivityTypeRotatedDiskEncryptionKey struct {
	HostID          uint   `json:"host_id"`
	HostDisplayName string `json:"host_display_name"`
}

func (a ActivityTypeRotatedDiskEncryptionKey) ActivityName() string { return "rotated_disk_encryption_key" }
func (a ActivityTypeRotatedDiskEncryptionKey) HostIDs() []uint      { return []uint{a.HostID} }

// ActivityTypeFailedToRotateDiskEncryptionKey is always attributed to Fleet: the
// failure arrives from the device or from delivery, outside any user context.
type ActivityTypeFailedToRotateDiskEncryptionKey struct {
	HostID          uint   `json:"host_id"`
	HostDisplayName string `json:"host_display_name"`
	Detail          string `json:"detail,omitempty"`
}

func (a ActivityTypeFailedToRotateDiskEncryptionKey) ActivityName() string { return "failed_to_rotate_disk_encryption_key" }
func (a ActivityTypeFailedToRotateDiskEncryptionKey) HostIDs() []uint      { return []uint{a.HostID} }
func (a ActivityTypeFailedToRotateDiskEncryptionKey) WasFromAutomation() bool { return true }

There is no registration list for activity types. WasFromAutomation satisfies the optional AutomatableActivity interface in server/activity/internal/types/activity.go:25. Add both to the dibble seed at tools/dibble/pkg/seed/activities.go:380.

Datastore

All in server/datastore/mysql/disk_encryption.go, interface entries in server/fleet/datastore.go next to GetHostDiskEncryptionKey at line 1464. Make sure to update mocks

go
// SetHostDiskEncryptionKeyRotationCommand records a pending rotation. It returns
// false without writing when another rotation is already pending, which makes the
// in-progress check atomic with the write.
SetHostDiskEncryptionKeyRotationCommand(ctx context.Context, hostID uint, cmdUUID string) (bool, error)
sql
UPDATE host_disk_encryption_keys
SET rotation_command_uuid = ?, updated_at = updated_at
WHERE host_id = ? AND rotation_command_uuid IS NULL

Return rowsAffected == 1.

go
// ClearHostDiskEncryptionKeyRotationCommand clears the marker only if it still
// points at cmdUUID, so a late result for a superseded command is a no-op.
ClearHostDiskEncryptionKeyRotationCommand(ctx context.Context, hostID uint, cmdUUID string) error
// ClearHostDiskEncryptionKeyRotationByHostUUID clears whatever is pending. Used by
// ClearQueue on checkout and re-enroll.
ClearHostDiskEncryptionKeyRotationByHostUUID(ctx context.Context, hostUUID string) error
// FailHostDiskEncryptionKeyRotation clears the marker and sets decryptable = 0, which
// is what turns on the Escrow Buddy notification in setDiskEncryptionNotifications.
FailHostDiskEncryptionKeyRotation(ctx context.Context, hostID uint, cmdUUID string) error
// GetHostByDiskEncryptionKeyRotationCommand resolves the pending command back to
// its host via idx_hdek_rotation_command_uuid. Returns *Host, as
// GetManagedLocalAccountByPendingCommandUUID does at datastore.go:2219, because
// SetOrUpdateHostDiskEncryptionKey and DisplayName() need it.
GetHostByDiskEncryptionKeyRotationCommand(ctx context.Context, cmdUUID string) (*Host, error)
// ReplaceHostDiskEncryptionKeyBlob swaps the ciphertext for a key whose plaintext is
// unchanged. Leaves decryptable and updated_at alone and writes no archive row.
ReplaceHostDiskEncryptionKeyBlob(ctx context.Context, hostID uint, base64Encrypted string) error
// IsAppleMDMCommandPending reports whether the command is still active in the nano
// queue with no terminal result. A primary-key lookup, not a scan.
IsAppleMDMCommandPending(ctx context.Context, hostUUID, cmdUUID string) (bool, error)

Every statement that touches only the marker or only decryptable sets updated_at = updated_at. See "Pending state lifecycle" for why.

Update GetHostDiskEncryptionKey at disk_encryption.go:326 to select rotation_command_uuid.

IsAppleMDMCommandPending follows the SELECT at server/datastore/mysql/apple_mdm.go:7660:

sql
SELECT neq.active,
  EXISTS (
    SELECT 1 FROM nano_command_results ncr
    WHERE ncr.id = neq.id AND ncr.command_uuid = neq.command_uuid AND ncr.status != 'NotNow'
  ) AS has_terminal_result
FROM nano_enrollment_queue neq
WHERE neq.id = ? AND neq.command_uuid = ?

Pending means the row exists, active = 1, and has_terminal_result = 0.

Why an atomic UPDATE for the 409, not a read-then-write: two API callers hitting rotate at once would both read "not pending" and both enqueue. The conditional UPDATE makes one of them lose.

Why a column and not a host_mdm_actions-style table: the key row always exists when rotation is allowed, since a decryptable current key is a precondition, and the marker's lifetime is bounded by the row's lifetime, which gives free cleanup on re-enroll and fleet moves.

Placeholder expansion

server/datastore/mysql/secret_variables.go:524, ExpandHostSecrets: add

go
case fleet.HostSecretFileVaultKey:
	key, err := ds.getHostDiskEncryptionKeyDecryptedByHostUUID(ctx, enrollmentID)
	if err != nil {
		return "", ctxerr.Wrapf(ctx, err, "getting disk encryption key for host %s", enrollmentID)
	}
	secretValues[secretType] = key

getHostDiskEncryptionKeyDecryptedByHostUUID joins hosts on uuid to load base64_encrypted, then decrypts with assets.CACertsAndKeyForDecryption(ctx, ds) and mdm.DecryptBase64CMSWithCerts. No import cycle: server/datastore/mysql already imports both server/mdm (apple_mdm.go:26) and server/mdm/assets (nanomdm_storage.go:17, scep.go:16).

server/mdm/nanomdm/service/nanomdm/service.go, after the ClearPasscode block at line 335:

go
// Expand the current FileVault key for RotateFileVaultKey. Device channel only,
// so UDID is the host UUID.
if cmd.Command.Command.RequestType == fleet.RotateFileVaultKeyCmdName {
	hostExpanded, didError := expandHostSecrets(string(cmd.Raw), func(hostUUID string, errorMsg string) {
		if storeErr := s.store.SetDiskEncryptionKeyRotationFailed(r.Context, hostUUID, cmd.CommandUUID, errorMsg); storeErr != nil {
			logger.Info("level", "error", "msg", "setting disk encryption key rotation failed", "err", storeErr)
		}
	})
	if didError {
		return nil, nil
	}
	cmd.Raw = []byte(hostExpanded)
}

Add SetDiskEncryptionKeyRotationFailed(ctx, hostUUID, commandUUID, errorMsg string) error to storage.SecretStore at server/mdm/nanomdm/storage/storage.go:42, next to SetRecoveryLockFailed at line 52. Every implementer needs the method: NanoMDMStorage in server/datastore/mysql/nanomdm_storage.go next to SetRecoveryLockFailed at line 368, server/mdm/nanomdm/storage/allmulti/allmulti.go:113, server/mdm/nanomdm/storage/file/file.go:254, server/mdm/nanomdm/storage/mysql/mysql.go:429, and the generated mock in server/mock/mdm/datastore_mdm_mock.go. The NanoMDMStorage implementation resolves the host by UUID, calls FailHostDiskEncryptionKeyRotation, and emits ActivityTypeFailedToRotateDiskEncryptionKey{Detail: errorMsg} with a nil user through a fleet.NewActivityFunc (server/fleet/activities.go:28).

NanoMDMStorage holds only MySQLStorage, db, logger, and ds (nanomdm_storage.go:55), and fleet.Datastore has no activity writer. Add a newActivityFn fleet.NewActivityFunc field with a SetNewActivityFunc setter, and call the setter from cmd/fleet/serve.go once svc exists, near line 988 where svc.NewActivity is already handed to the result handlers. When the func is nil, log at warn level and skip the activity.

Why the activity is emitted from the storage layer here: the nanomdm Service has no activity writer, and the synthesized Error result that expandHostSecrets stores never reaches CommandAndReportResults. SetRecoveryLockFailed writes no activity for the equivalent Recovery Lock case; this story adds one because the failure activity is part of the agreed design. It fires only when the key changed between enqueue and delivery or the CA assets vanished.

ClearQueue

server/datastore/mysql/nanomdm_storage.go:375: inside the existing transaction that calls ClearMDMUpcomingActivitiesDB, add ClearHostDiskEncryptionKeyRotationByHostUUID(r.Context, r.ID).

Commander

server/mdm/apple/commander.go, next to RotateRecoveryLock at line 916, and add to MDMAppleCommandIssuer at server/fleet/apple_mdm.go:45:

go
// RotateFileVaultKey enqueues Apple's RotateFileVaultKey command for one macOS
// host. The current recovery key travels as a host-scoped placeholder that the
// nanomdm service expands at delivery, so the plaintext never lands in nano_commands.
//
// replyCertDER is the DER encoding of the current MDM CA certificate, the same
// certificate the Disk encryption profile escrows to. Apple documents
// ReplyEncryptionCertificate as optional. On macOS 26 the command fails without
// it, and Fleet relies on the encrypted reply to escrow the new key as soon as the
// host acknowledges instead of waiting for the next osquery report. Always send it.
func (svc *MDMAppleCommander) RotateFileVaultKey(ctx context.Context, hostUUID, cmdUUID string, replyCertDER []byte) error {
	cmdPayload := commandPayload{
		CommandUUID: cmdUUID,
		Command: map[string]any{
			"RequestType": fleet.RotateFileVaultKeyCmdName,
			"KeyType":     "personal",
			"FileVaultUnlock": map[string]any{
				"Password": "$" + fleet.HostSecretPrefix + fleet.HostSecretFileVaultKey,
			},
			"ReplyEncryptionCertificate": replyCertDER,
		},
	}
	rawBytes, err := plist.MarshalIndent(cmdPayload, "    ")
	if err != nil {
		return ctxerr.Wrap(ctx, err, "marshalling RotateFileVaultKey payload")
	}
	if err := svc.EnqueueCommand(ctx, []string{hostUUID}, string(rawBytes)); err != nil {
		return ctxerr.Wrap(ctx, err, "enqueuing RotateFileVaultKey command")
	}
	return nil
}

go build ./... will name any other implementer of MDMAppleCommandIssuer that needs the method.

Service and endpoint

server/fleet/service.go, next to RotateRecoveryLockPassword at line 1518:

go
// RotateDiskEncryptionKey enqueues a FileVault recovery key rotation for a macOS host.
RotateDiskEncryptionKey(ctx context.Context, hostID uint) error

server/service/hosts.go, next to the Recovery Lock endpoint at line 4881: request struct with HostID uint \url:"id"`as at line 4884, a response struct with onlyErr, the endpoint function, and the core stub returning fleet.ErrMissingLicense, all following lines 4881 to 4900. Register in server/service/handler.go` beside the GET at line 850:

go
ue.POST("/api/_version_/fleet/hosts/{id:[0-9]+}/encryption_key/rotate", rotateDiskEncryptionKeyEndpoint, rotateDiskEncryptionKeyRequest{})

Add the server/api_endpoints/api_endpoints.yml entry (method POST, path /api/v1/fleet/hosts/:id/encryption_key/rotate, display name Rotate host's disk encryption key) in this PR. The YAML is embedded and validated against registered routes at startup, so it has to land with the route, not in the docs PR.

ee/server/service/hosts.go, modeled on RotateRecoveryLockPassword at line 591:

go
func (svc *Service) RotateDiskEncryptionKey(ctx context.Context, hostID uint) error {
	if err := svc.authz.Authorize(ctx, &fleet.Host{}, fleet.ActionList); err != nil {
		return err
	}
	host, err := svc.ds.Host(ctx, hostID)
	if err != nil {
		return ctxerr.Wrap(ctx, err, "get host")
	}
	notFoundErr := ctxerr.Wrap(ctx, common_mysql.NotFound("Host").WithID(hostID), "rotate disk encryption key")
	if err := svc.authz.AuthorizeOrNotFound(ctx, fleet.MDMCommandAuthz{TeamID: host.TeamID}, fleet.ActionWrite, notFoundErr); err != nil {
		return err
	}

	if host.FleetPlatform() != "darwin" {
		return &fleet.BadRequestError{Message: "Disk encryption key rotation is only supported on macOS hosts."}
	}
	connected, err := svc.ds.IsHostConnectedToFleetMDM(ctx, host)
	if err != nil {
		return ctxerr.Wrap(ctx, err, "checking if host is connected to Fleet MDM")
	}
	if !connected {
		return &fleet.BadRequestError{Message: "Host must be enrolled in Fleet MDM to rotate the disk encryption key."}
	}

	cfg, err := svc.ds.GetConfigEnableDiskEncryption(ctx, host.TeamID)
	if err != nil {
		return ctxerr.Wrap(ctx, err, "get disk encryption config")
	}
	if !cfg.MacOSEscrowEnabled {
		return fleet.NewUserMessageError(errors.New("Disk encryption key escrow is not turned on for this host's fleet."), http.StatusUnprocessableEntity)
	}

	key, err := svc.ds.GetHostDiskEncryptionKey(ctx, host.ID)
	switch {
	case fleet.IsNotFound(err):
		return fleet.NewUserMessageError(errors.New("Host does not have a disk encryption key to rotate."), http.StatusUnprocessableEntity)
	case err != nil:
		return ctxerr.Wrap(ctx, err, "get host disk encryption key")
	}

	if key.RotationCommandUUID != nil {
		pending, err := svc.ds.IsAppleMDMCommandPending(ctx, host.UUID, *key.RotationCommandUUID)
		if err != nil {
			return ctxerr.Wrap(ctx, err, "check pending rotation command")
		}
		if pending {
			return &fleet.ConflictError{Message: "Disk encryption key rotation is already in progress for this host."}
		}
		// Stale marker: the command is gone or finished without clearing it.
		if err := svc.ds.ClearHostDiskEncryptionKeyRotationCommand(ctx, host.ID, *key.RotationCommandUUID); err != nil {
			return ctxerr.Wrap(ctx, err, "clear stale rotation marker")
		}
	}

	// Fleet supplies the current key as the unlock credential, so it must decrypt now.
	certs, caKey, err := assets.CACertsAndKeyForDecryption(ctx, svc.ds)
	if err != nil {
		return ctxerr.Wrap(ctx, err, "load CA assets")
	}
	if key.Decryptable == nil || !*key.Decryptable || key.Base64Encrypted == "" {
		return fleet.NewUserMessageError(errors.New("Couldn't rotate disk encryption key. The current key is not decryptable."), http.StatusUnprocessableEntity)
	}
	if plain, err := mdm.DecryptBase64CMSWithCerts(key.Base64Encrypted, caKey, certs); err != nil || len(plain) == 0 {
		return fleet.NewUserMessageError(errors.New("Couldn't rotate disk encryption key. The current key is not decryptable."), http.StatusUnprocessableEntity)
	}

	caCert, err := assets.X509Cert(ctx, svc.ds, fleet.MDMAssetCACert)
	if err != nil {
		return ctxerr.Wrap(ctx, err, "load CA certificate for reply encryption")
	}

	cmdUUID := uuid.NewString()
	ok, err := svc.ds.SetHostDiskEncryptionKeyRotationCommand(ctx, host.ID, cmdUUID)
	if err != nil {
		return ctxerr.Wrap(ctx, err, "record pending rotation")
	}
	if !ok {
		return &fleet.ConflictError{Message: "Disk encryption key rotation is already in progress for this host."}
	}

	if err := svc.mdmAppleCommander.RotateFileVaultKey(ctx, host.UUID, cmdUUID, caCert.Raw); err != nil {
		// A push failure leaves the command durably enqueued, so keep the marker.
		// Any other error means nothing was enqueued.
		if _, pushFailed := errors.AsType[*apple_mdm.NotificationFailedError](err); !pushFailed {
			_ = svc.ds.ClearHostDiskEncryptionKeyRotationCommand(ctx, host.ID, cmdUUID)
		}
		return ctxerr.Wrap(ctx, err, "enqueue RotateFileVaultKey command")
	}

	if vc, ok := viewer.FromContext(ctx); ok {
		if err := svc.NewActivity(ctx, vc.User, fleet.ActivityTypeRotatedDiskEncryptionKey{
			HostID: host.ID, HostDisplayName: host.DisplayName(),
		}); err != nil {
			return ctxerr.Wrap(ctx, err, "create activity for rotate disk encryption key")
		}
	}
	return nil
}

Check the order: the decryptable and CMS checks run before the marker is set, so a 422 never leaves a marker behind. Decryptable == nil is treated as not decryptable because the cron has not verified that blob yet; the modal cannot reach this state because encryption_key_available is false while decryptable is NULL.

Why NotificationFailedError and not APNSDeliveryError: enqueueAndNotify at commander.go:737 wraps every push-stage failure in *NotificationFailedError, and not all of them are APNSDeliveryError. Recovery Lock's check is the older pattern. Newer callers such as server/service/hosts.go:1759 use errors.AsType[*apple_mdm.NotificationFailedError], which is the only test that guarantees the command was stored.

Why the endpoint decrypts even though the cron already set decryptable: the flag reflects the cron's last run. The CA assets could have been rotated since. A stale true would enqueue a command that fails at delivery, which is a worse experience than a 422 now.

Why no read_host_disk_encryption_key activity here: Fleet reads the plaintext to validate it, and nobody sees it. The triggered activity already records who initiated the rotation. Decided 2026-09-23.

Why 422 for escrow off rather than 409 or 400: 409 is reserved for the in-progress conflict, matching Recovery Lock. The Recovery Lock endpoint returns 400 for not-enabled and no-password at ee/server/service/hosts.go:645. This endpoint uses 422 for those precondition failures because the API doc and the parent test plan already say so, and keeps 400 for platform and enrollment errors.

rotation_pending on GET

server/service/hosts.go:4050, getHostDiskEncryptionKey: after the current key decrypts successfully, set key.RotationPending = key.RotationCommandUUID != nil before returning. On the archived-key fallback path leave it false. HostDiskEncryptionKey already serializes `rotation_pending