Skip to content

Custom android mdm commands - #50728

Merged
ksykulev merged 18 commits into
mainfrom
50447-android-command-poc
Aug 17, 2026
Merged

Custom android mdm commands#50728
ksykulev merged 18 commits into
mainfrom
50447-android-command-poc

Conversation

@ksykulev

@ksykulev ksykulev commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Related issue: Resolves #50447, #23232

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.

Testing

Database migrations

  • Checked schema for all modified table for columns that will auto-update timestamps during migration.
  • Confirmed that updating the timestamps is acceptable, and will not cause unwanted side effects.
  • Ensured the correct collation is explicitly set for character columns (COLLATE utf8mb4_unicode_ci).

Summary by CodeRabbit

  • New Features
    • Added Android MDM command execution for custom commands and lock, reboot, reset-password, and wipe actions.
    • Android commands now retain raw command and result details for improved visibility and troubleshooting.
    • Added licensing checks for premium Android actions.
  • Bug Fixes
    • Improved Android enrollment connectivity detection.
    • Added validation for Android MDM configuration, command payloads, and supported host targeting.
    • Improved handling and reporting of completed and failed Android command operations.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Adds first-pass support for issuing custom Android (AMAPI) device commands through Fleet’s existing “run MDM command” pathway, including persistence of the original Android JSON payload and the eventual AMAPI Operation result for retrieval.

Changes:

  • Extend RunMDMCommand to accept Android targets and enqueue AMAPI “custom commands” (currently limited to single-host targeting).
  • Persist Android command payload (raw_command) on issue and store AMAPI Operation JSON (raw_result) on Pub/Sub ack/error.
  • Add datastore interfaces + migration for new mdm_android_commands columns (raw_command, raw_result).

Reviewed changes

Copilot reviewed 12 out of 13 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
server/service/mdm.go Adds Android as a supported platform for RunMDMCommand and enqueues AMAPI custom commands.
server/service/client_mdm.go Allows fleetctl/client to submit Android JSON payloads without XML preparation.
server/mock/datastore_mock.go Updates Android datastore mocks for new methods/signatures.
server/mdm/android/service/service.go Implements IssueCustomCommand to issue AMAPI commands and persist a command row (with raw payload).
server/mdm/android/service/pubsub.go Stores raw AMAPI Operation JSON into raw_result when updating command status from Pub/Sub.
server/mdm/android/service.go Adds IssueCustomCommand to the Android MDM service interface.
server/mdm/android/android.go Extends Android command model with raw_command and raw_result.
server/fleet/datastore.go Extends AndroidDatastore interface to support inserting custom commands and storing raw results.
server/datastore/mysql/migrations/tables/20260805155427_AddRawCommandAndResultToAndroidCommands.go Migration adding raw_command and raw_result columns to mdm_android_commands.
server/datastore/mysql/migrations/tables/20260805155427_AddRawCommandAndResultToAndroidCommands_test.go Migration test verifying new columns default NULL for existing rows and are insertable.
server/datastore/mysql/mdm.go Treats Android hosts as “connected to Fleet MDM” based on host_mdm.enrolled.
server/datastore/mysql/android.go Adds insert helper for custom commands and stores raw_result when updating status.
server/datastore/mysql/schema.sql.backup Adds a full schema dump/backup file (appears accidental).

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

Comment thread server/service/mdm.go
Comment thread server/mdm/android/service/service.go
Comment thread server/datastore/mysql/schema.sql.backup Outdated
Comment thread server/datastore/mysql/mdm.go
@codecov

codecov Bot commented Aug 11, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 63.57143% with 51 lines in your changes missing coverage. Please review.
✅ Project coverage is 68.77%. Comparing base (97685e0) to head (fe43709).
⚠️ Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
server/mdm/android/service/service.go 17.07% 33 Missing and 1 partial ⚠️
server/service/mdm.go 80.00% 4 Missing and 4 partials ⚠️
...4183816_AddRawCommandAndResultToAndroidCommands.go 69.23% 3 Missing and 1 partial ⚠️
server/datastore/mysql/android.go 90.00% 1 Missing and 1 partial ⚠️
server/datastore/mysql/mdm.go 85.71% 1 Missing and 1 partial ⚠️
server/mdm/android/service/reconcile_commands.go 83.33% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@           Coverage Diff            @@
##             main   #50728    +/-   ##
========================================
  Coverage   68.77%   68.77%            
========================================
  Files        4001     4002     +1     
  Lines      258512   258630   +118     
  Branches    13860    13860            
========================================
+ Hits       177792   177874    +82     
- Misses      64922    64955    +33     
- Partials    15798    15801     +3     
Flag Coverage Δ
backend 69.88% <63.57%> (-0.01%) ⬇️

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

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@ksykulev ksykulev changed the title POC custom android mdm commands Custom android mdm commands Aug 12, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 20 out of 20 changed files in this pull request and generated 1 comment.

Suppressed comments (1)

server/mdm/android/service/reconcile_commands.go:161

  • The reconciler path transitions commands to a terminal state without persisting raw_result even though it has the full Operation object available. If Pub/Sub is missed and the cron reconciler resolves the command, raw_result will stay NULL, which breaks the goal of retrieving raw custom command results via the API. Consider marshalling op to JSON (same as the Pub/Sub handler) and passing it as rawResult to setAndroidCommandTerminalState.
		default:
			status, errCode, errMsg := androidOperationTerminalState(op)
			if err := setAndroidCommandTerminalState(ctx, ds, newActivityFn, cmd, status, errCode, errMsg, nil, nil); err != nil {
				logger.ErrorContext(ctx, "failed to apply reconciled android command status",

Comment thread server/service/mdm.go Outdated

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 20 out of 20 changed files in this pull request and generated no new comments.

Suppressed comments (3)

server/service/mdm.go:666

  • Premium-gated Android commands currently return fleet.ErrMissingLicense without a cause, which surfaces the generic message "Requires Fleet Premium license". The linked issue explicitly calls for an error message that identifies the gated command/feature (e.g. LOCK / RESET_PASSWORD) so users understand what is premium-only.
	if androidMDMPremiumCommands[cmdType] {
		lic, err := svc.License(ctx)
		if err != nil {
			return nil, ctxerr.Wrap(ctx, err, "get license")
		}
		if !lic.IsPremium() {
			return nil, fleet.ErrMissingLicense
		}

server/service/mdm.go:640

  • Android custom commands reject requests targeting more than one host (len(hosts) != 1). This conflicts with the intended API/CLI behavior described in the linked issue (examples show multiple hosts and engineering notes suggest serial per-host issuance). If multi-host is intentionally unsupported for now, the public API/docs/CLI should be updated to reflect that constraint; otherwise, this needs a batching strategy (serial loop + aggregated response).
// enqueueAndroidMDMCommand issues an AMAPI custom command for each targeted Android host.
// rawJSON is the base64-decoded JSON bytes of the AMAPI Command object.
// For now, only single-host targeting is supported.
func (svc *Service) enqueueAndroidMDMCommand(ctx context.Context, rawJSON []byte, hosts []*fleet.Host) (*fleet.CommandEnqueueResult, error) {
	if len(hosts) != 1 {
		return nil, fleet.NewInvalidArgumentError("host_uuids",
			"Android custom commands can only target a single host at a time.").WithStatus(http.StatusBadRequest)
	}

server/mdm/android/service/service.go:1137

  • When the AMAPI command type is omitted (relying on parameter inference like clearAppsDataParams → CLEAR_APP_DATA), IssueCustomCommand persists and returns RequestType as "CUSTOM". This prevents clients from seeing the real inferred type and doesn’t meet the linked issue’s acceptance criteria (expects inferred type in results/response). Consider extracting the inferred type from Operation metadata or implementing a deterministic inference from the request payload so the stored/returned command_type matches what was actually executed.
	// Determine the command type from the AMAPI response metadata or the request.
	cmdType := amapiCmd.Type
	if cmdType == "" {
		// AMAPI infers the type from params fields (e.g. clearAppsDataParams → CLEAR_APP_DATA).
		// The type is reflected back in the Operation metadata but not trivially accessible here,
		// so fall back to "CUSTOM" for now.
		cmdType = "CUSTOM"
	}

@ksykulev
ksykulev marked this pull request as ready for review August 12, 2026 16:55
@ksykulev
ksykulev requested a review from a team as a code owner August 12, 2026 16:55
@coderabbitai

coderabbitai Bot commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

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 Plus

Run ID: b5116054-6594-4492-9841-3a96e131e6a4

📥 Commits

Reviewing files that changed from the base of the PR and between 74751aa and 21c1d0f.

📒 Files selected for processing (1)
  • server/mock/datastore_mock.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • server/mock/datastore_mock.go

Walkthrough

The change adds Android command execution to RunMDMCommand. It supports custom AMAPI commands, command-type inference, duration defaults, Android MDM validation, host limits, and license checks. Android commands now persist raw request and result payloads. Pub/Sub and reconciliation flows store completed operations. MySQL migrations and tests cover the new fields. Android connectivity now requires an enrolled host_mdm record.

Possibly related issues

Possibly related PRs

  • fleetdm/fleet#50177: Updates the Android command reconciliation and terminal-result handling paths extended by this change.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% 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 clearly identifies the main change: support for custom Android MDM commands.
Description check ✅ Passed The description includes related issues and covers the required testing, validation, changes-file, and migration checklist items.
Linked Issues check ✅ Passed The implementation provides Android command dispatch plus persistence and retrieval of raw command and result payloads, satisfying the proof-of-concept objective in [#50447].
Out of Scope Changes check ✅ Passed All reviewed changes support Android MDM command dispatch, persistence, status capture, connectivity checks, or tests, so no unrelated scope is evident.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch 50447-android-command-poc

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 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/android.go`:
- Around line 1234-1246: Update the SELECT list used by getMDMAndroidCommand to
include both raw_command and raw_result, ensuring the returned command preserves
payloads written by InsertMDMAndroidCommand and UpdateMDMAndroidCommandStatus.
Add a round-trip test covering both fields after insertion and status update.

In `@server/mdm/android/service/reconcile_commands.go`:
- Line 160: In the completed-operation branch of the reconciliation flow,
marshal the AMAPI operation value op and pass the resulting raw payload instead
of nil to setAndroidCommandTerminalState. Update TestReconcileAndroidCommands to
assert that the completed-operation callback receives this raw result while
preserving the existing terminal status handling.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 87ef3f27-31d8-418f-b23f-505e581c7023

📥 Commits

Reviewing files that changed from the base of the PR and between 4fa2352 and 3f91af5.

⛔ Files ignored due to path filters (1)
  • changes/android-custom-commands.md is excluded by !**/*.md
📒 Files selected for processing (21)
  • server/datastore/mysql/android.go
  • server/datastore/mysql/android_test.go
  • server/datastore/mysql/hosts_test.go
  • server/datastore/mysql/mdm.go
  • server/datastore/mysql/mdm_test.go
  • server/datastore/mysql/migrations/tables/20260812165318_AddRawCommandAndResultToAndroidCommands.go
  • server/datastore/mysql/migrations/tables/20260812165318_AddRawCommandAndResultToAndroidCommands_test.go
  • server/datastore/mysql/schema.sql
  • server/fleet/datastore.go
  • server/mdm/android/android.go
  • server/mdm/android/service.go
  • server/mdm/android/service/pubsub.go
  • server/mdm/android/service/pubsub_dedup_test.go
  • server/mdm/android/service/pubsub_test.go
  • server/mdm/android/service/reconcile_commands.go
  • server/mdm/android/service/reconcile_commands_test.go
  • server/mdm/android/service/service.go
  • server/mock/datastore_mock.go
  • server/service/client_mdm.go
  • server/service/mdm.go
  • server/service/mdm_test.go

Comment thread server/datastore/mysql/android.go
Comment thread server/mdm/android/service/reconcile_commands.go Outdated
Comment thread server/service/client_mdm.go Outdated
Comment thread server/mdm/android/service/service.go
Comment thread server/service/mdm.go
// enqueueAndroidMDMCommand issues an AMAPI custom command for each targeted Android host.
// rawJSON is the base64-decoded JSON bytes of the AMAPI Command object.
// For now, only single-host targeting is supported.
func (svc *Service) enqueueAndroidMDMCommand(ctx context.Context, rawJSON []byte, hosts []*fleet.Host) (*fleet.CommandEnqueueResult, error) {

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.

/commands/results 404s for Android custom commands — GetMDMCommandPlatform (datastore/mysql/mdm.go:37) never checks mdm_android_commands, and the case "android" branch in getMDMCommandResults (mdm.go:992) returns empty even once it does, so the new raw_command/raw_result columns are write-only.

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.

GetMDMCommandResults for Android is part of #50733. The columns are write-only for now until that ticket wires up the read path.

Comment thread server/mdm/android/service/pubsub.go
Comment thread server/mdm/android/service/service.go

@dantecatalfamo dantecatalfamo left a comment

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.

🥬 (L)ettuce
🧄 (G)arlic
🍅 (T)omato
🥩 (M)eat

@ksykulev
ksykulev merged commit a7e4a5b into main Aug 17, 2026
45 checks passed
@ksykulev
ksykulev deleted the 50447-android-command-poc branch August 17, 2026 19:44
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.

POC Device Commands to android

3 participants