Skip to content

SAAD: Support DDM assets in sync + reconciliation - #49016

Merged
MagnusHJensen merged 12 commits into
mainfrom
48568-asset-api-ddm-sync
Jul 10, 2026
Merged

SAAD: Support DDM assets in sync + reconciliation#49016
MagnusHJensen merged 12 commits into
mainfrom
48568-asset-api-ddm-sync

Conversation

@MagnusHJensen

@MagnusHJensen MagnusHJensen commented Jul 9, 2026

Copy link
Copy Markdown
Member

Related issue: Resolves #48568 second part

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

Summary by CodeRabbit

  • New Features

    • Apple declarative management now supports asset-backed declarations, including device delivery of referenced DDM assets.
    • Added a new device-facing endpoint to fetch managed DDM assets by identifier (scoped to the device’s team).
  • Bug Fixes

    • Declaration/profile updates now refresh when referenced assets change (not just variables).
    • Device and host token/declaration matching now accounts for asset update timing to trigger redeploys reliably.
    • Improved validation to detect missing/invalid asset references before saving.
  • Other

    • Updated which configuration declaration types are blocked during user-provided validation.

@MagnusHJensen MagnusHJensen changed the title 48568 asset api ddm sync SAAD: Support DDM assets in sync + reconciliation Jul 9, 2026
@MagnusHJensen
MagnusHJensen requested a review from Copilot July 9, 2026 11:03
@MagnusHJensen

Copy link
Copy Markdown
Member Author

@coderabbitai review once

@coderabbitai

coderabbitai Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

@MagnusHJensen: Sure, I'll review the PR now.

✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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.

Warning

  • Copilot's review of this pull request may be incomplete because some of the changed files are excluded by your Copilot content exclusion settings. See Excluding content from Copilot for details.

Pull request overview

Adds backend support for Apple Declarative Device Management (DDM) assets in the DDM sync/reconciliation flow by tracking declaration→asset references, incorporating assets_updated_at into per-host effective tokens, including assets in the DDM manifest, and serving asset JSON from a new declaration/asset/<identifier> endpoint.

Changes:

  • Extend per-host DDM token computation (EffectiveDDMToken, SQL token calculation, reconciliation delta logic) to incorporate assets_updated_at.
  • Persist and load declaration→asset reference edges, and include referenced assets in the declaration-items response plus a new declaration/asset/<id> handler.
  • Add/adjust unit + integration tests covering reconciliation behavior and token changes when assets are edited.

Reviewed changes

Copilot reviewed 20 out of 21 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
server/service/integration_mdm_ddm_test.go Adds an integration test asserting asset edits trigger a DDM resync and token change.
server/service/integration_core_test.go Updates call sites for the extended declaration creation API.
server/service/apple_mdm.go Adds asset reference extraction/validation, serves assets via DDM endpoints, and incorporates assets_updated_at into effective tokens and manifests.
server/service/apple_mdm_test.go Updates mocks + adds service-level tests for asset reference validation during declaration creation.
server/service/apple_mdm_ddm_test.go Updates datastore declaration creation signature in DDM tests.
server/mock/datastore_mock.go Extends datastore mock surface for new declaration signature and asset lookup/list helpers.
server/mdm/apple/reconcile.go Treats assets_updated_at as a reason to re-deliver an unchanged declaration and stamps it on host rows.
server/mdm/apple/reconcile_test.go Adds unit test coverage for assets_updated_at delta behavior.
server/fleet/datastore.go Extends datastore interface for asset reference persistence and lookups.
server/fleet/apple_mdm.go Adds AssetsUpdatedAt fields and extends EffectiveDDMToken; adjusts declaration type validation copy and forbidden-type set.
server/fleet/apple_mdm_test.go Updates declaration validation tests and adds EffectiveDDMToken tests for vars/assets ordering.
server/datastore/mysql/teams_test.go Updates declaration creation signature in team tests.
server/datastore/mysql/secret_variables_test.go Updates declaration creation signature in secret-variable tests.
server/datastore/mysql/labels_test.go Updates declaration creation signature in label tests.
server/datastore/mysql/hosts_test.go Updates declaration creation signature in host tests.
server/datastore/mysql/apple_mdm.go Persists asset references on declaration insert; extends token SQL and adds asset lookup/query helpers.
server/datastore/mysql/apple_mdm_test.go Updates declaration creation signature in datastore tests.
server/datastore/mysql/apple_mdm_ddm_test.go Adds datastore tests for asset lookup-by-identifier, referenced-asset queries, and token round-trip with assets_updated_at.
server/datastore/mysql/apple_mdm_batched.go Loads assets_updated_at for reconcile inputs and persists it to host declaration rows.
cmd/fleetctl/fleetctl/gitops_test.go Updates GitOps tests for the extended declaration creation signature.
changes/38986-support-ddm-assets User-visible changes entry (content excluded from review).
Files excluded by content exclusion policy (1)
  • changes/38986-support-ddm-assets

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

Comment thread server/service/apple_mdm.go Outdated
Comment thread server/service/apple_mdm.go Outdated
Comment thread server/service/apple_mdm.go
@codecov

codecov Bot commented Jul 9, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 86.01036% with 27 lines in your changes missing coverage. Please review.
✅ Project coverage is 68.03%. Comparing base (a15d58e) to head (1c26c3f).
⚠️ Report is 14 commits behind head on main.

Files with missing lines Patch % Lines
server/service/apple_mdm.go 82.82% 11 Missing and 6 partials ⚠️
server/datastore/mysql/apple_mdm.go 88.46% 3 Missing and 3 partials ⚠️
server/datastore/mysql/apple_mdm_batched.go 83.33% 2 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #49016      +/-   ##
==========================================
- Coverage   68.09%   68.03%   -0.07%     
==========================================
  Files        3732     3743      +11     
  Lines      235783   237392    +1609     
  Branches    12371    12371              
==========================================
+ Hits       160557   161503     +946     
- Misses      60807    61298     +491     
- Partials    14419    14591     +172     
Flag Coverage Δ
backend 69.61% <86.01%> (-0.09%) ⬇️

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.

@coderabbitai

coderabbitai Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

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: c328c95b-f0ef-41cf-ba17-dcfd6202bc04

📥 Commits

Reviewing files that changed from the base of the PR and between 23b69e0 and 1c26c3f.

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

Walkthrough

This PR adds Apple DDM asset support across declaration creation, datastore persistence, reconciliation, and delivery. It introduces AssetsUpdatedAt tracking, persists declaration-to-asset references, adds datastore APIs for asset lookup, updates DDM token generation and host-declaration syncing to account for asset changes, and serves assets through a new declaration asset endpoint. Tests, mocks, and call sites were updated to match the new signatures and behavior.

Possibly related PRs

  • fleetdm/fleet#43222: Extends the same DDM token path that this PR changes with assets_updated_at.
  • fleetdm/fleet#48866: Adds the schema and host-declaration columns consumed by this PR.
  • fleetdm/fleet#49011: Adds related Apple DDM asset service and datastore functionality that this PR builds on.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% 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 is concise and matches the main change: DDM asset support in sync and reconciliation.
Description check ✅ Passed The description includes the related issue, checklist, and testing sections required by the template.
Linked Issues check ✅ Passed The changes cover asset reference handling, DDM token propagation, reconciliation updates, and tests required by #48568.
Out of Scope Changes check ✅ Passed The diff stays focused on DDM assets, datastore updates, and tests, with no obvious unrelated changes.
✨ 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 48568-asset-api-ddm-sync

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
server/datastore/mysql/apple_mdm.go (1)

4924-4964: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Move the aff == 0 exists-check before inserting asset references. mdm_apple_declaration_asset_references.declaration_uuid has a foreign key to mdm_apple_declarations.declaration_uuid, so the duplicate-name path can raise a raw FK error instead of existsError. It also does unnecessary writes on the conflict path.

🤖 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 4924 - 4964, The
exists-check in the declaration insert flow should happen before writing asset
references, because the current order in the new declaration transaction can hit
a foreign key error instead of returning the intended existsError on duplicate
names. Update the apple MDM declaration insert logic in the withTx callback to
check RowsAffected on the ExecContext result immediately after the main
insert/upsert, and only run the mdm_apple_declaration_asset_references insert
when aff is non-zero; keep the existing ctxerr.Wrap and reloadStmt handling
unchanged.
🤖 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/fleet/apple_mdm.go`:
- Around line 895-916: The doc comment for EffectiveDDMToken is stale because it
only describes variablesUpdatedAt and omits the new assetsUpdatedAt input.
Update the comment above EffectiveDDMToken to mention both timestamps and
explain that the returned token combines the static token with any non-nil
host-specific variables_updated_at and assets_updated_at values.

In `@server/service/apple_mdm.go`:
- Around line 6664-6683: The handleDeclarationAsset flow in MDMAppleDDMService
currently scopes only by team, so a host can fetch another host’s asset if it
knows the identifier. Update this path to verify the requested asset is actually
referenced by the requesting host’s DDM declarations—either by adding a
datastore lookup scoped to hostUUID plus assetIdentifier or by checking the
host’s manifest/reference graph before ExpandEmbeddedSecrets runs. If the asset
is not assigned to that host, return a 404 instead of serving it.

---

Outside diff comments:
In `@server/datastore/mysql/apple_mdm.go`:
- Around line 4924-4964: The exists-check in the declaration insert flow should
happen before writing asset references, because the current order in the new
declaration transaction can hit a foreign key error instead of returning the
intended existsError on duplicate names. Update the apple MDM declaration insert
logic in the withTx callback to check RowsAffected on the ExecContext result
immediately after the main insert/upsert, and only run the
mdm_apple_declaration_asset_references insert when aff is non-zero; keep the
existing ctxerr.Wrap and reloadStmt handling unchanged.
🪄 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: 27d9b299-08bd-4740-8713-b91ae78100cc

📥 Commits

Reviewing files that changed from the base of the PR and between a53207a and c3c53c38ec03b68365041555b7d22b49650f5c73.

📒 Files selected for processing (21)
  • changes/38986-support-ddm-assets
  • cmd/fleetctl/fleetctl/gitops_test.go
  • server/datastore/mysql/apple_mdm.go
  • server/datastore/mysql/apple_mdm_batched.go
  • server/datastore/mysql/apple_mdm_ddm_test.go
  • server/datastore/mysql/apple_mdm_test.go
  • server/datastore/mysql/hosts_test.go
  • server/datastore/mysql/labels_test.go
  • server/datastore/mysql/secret_variables_test.go
  • server/datastore/mysql/teams_test.go
  • server/fleet/apple_mdm.go
  • server/fleet/apple_mdm_test.go
  • server/fleet/datastore.go
  • server/mdm/apple/reconcile.go
  • server/mdm/apple/reconcile_test.go
  • server/mock/datastore_mock.go
  • server/service/apple_mdm.go
  • server/service/apple_mdm_ddm_test.go
  • server/service/apple_mdm_test.go
  • server/service/integration_core_test.go
  • server/service/integration_mdm_ddm_test.go

Comment thread server/fleet/apple_mdm.go
Comment thread server/service/apple_mdm.go
Base automatically changed from 48568-asset-api to main July 9, 2026 16:34
@MagnusHJensen
MagnusHJensen marked this pull request as ready for review July 9, 2026 18:02
@MagnusHJensen
MagnusHJensen requested a review from a team as a code owner July 9, 2026 18:02
decoded.TeamID = new(uint(0))
} else {
fleetID, err := strconv.ParseUint(val[0], 10, 32)
fleetID, err := strconv.ParseUint(val[0], 10, 32) // nolint:staticcheck // it's used...

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.

This is very odd. I wonder why staticcheck flagged that?

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.

I honestly have no idea, and I tried multiple times.. :(

@MagnusHJensen
MagnusHJensen merged commit b4ce886 into main Jul 10, 2026
48 checks passed
@MagnusHJensen
MagnusHJensen deleted the 48568-asset-api-ddm-sync branch July 10, 2026 12:47
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.

SAAD Backend: Asset API handlers + DDM Sync

3 participants