Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix last_enrolled_at for macOS devices when re-enrolling to MDM #20173

Merged
merged 7 commits into from
Jul 11, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/20059-fix-last_enrolled_at
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* Fixed bug that set `Added to Fleet` to `Never` after macOS hosts re-enrolled to Fleet via MDM.
Copy link

Choose a reason for hiding this comment

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

ℹ️ info: Documented the fix for the last_enrolled_at field issue for macOS re-enrollment.

39 changes: 23 additions & 16 deletions server/datastore/mysql/apple_mdm.go
Original file line number Diff line number Diff line change
Expand Up @@ -770,30 +770,37 @@ func updateMDMAppleHostDB(
) error {
refetchRequested, lastEnrolledAt := mdmHostEnrollFields(mdmHost)
Copy link
Contributor

Choose a reason for hiding this comment

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

I wonder if it would make things easier to maintain to split up this abstraction and calculate these two values separately when needed?


updateStmt := `
UPDATE hosts SET
hardware_serial = ?,
uuid = ?,
hardware_model = ?,
platform = ?,
refetch_requested = ?,
last_enrolled_at = ?,
osquery_host_id = COALESCE(NULLIF(osquery_host_id, ''), ?)
WHERE id = ?`

if _, err := tx.ExecContext(
ctx,
updateStmt,
args := []interface{}{
mdmHost.HardwareSerial,
mdmHost.UUID,
mdmHost.HardwareModel,
mdmHost.Platform,
refetchRequested,
lastEnrolledAt,
// Set osquery_host_id to the device UUID only if it is not already set.
mdmHost.UUID,
hostID,
); err != nil {
}

// Only update last_enrolled_at if this is a iOS/iPadOS device.
// macOS should not update last_enrolled_at as it is set when osquery enrolls.
lastEnrolledAtColumn := ""
if mdmHost.Platform == "ios" || mdmHost.Platform == "ipados" {
lastEnrolledAtColumn = "last_enrolled_at = ?,"
args = append([]interface{}{lastEnrolledAt}, args...)
}

updateStmt := fmt.Sprintf(`
UPDATE hosts SET
%s
hardware_serial = ?,
uuid = ?,
hardware_model = ?,
platform = ?,
refetch_requested = ?,
osquery_host_id = COALESCE(NULLIF(osquery_host_id, ''), ?)
WHERE id = ?`, lastEnrolledAtColumn)

if _, err := tx.ExecContext(ctx, updateStmt, args...); err != nil {
return ctxerr.Wrap(ctx, err, "update mdm apple host")
}

Expand Down
81 changes: 76 additions & 5 deletions server/service/integration_mdm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,6 @@ func (s *integrationMDMTestSuite) SetupSuite() {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
require.NoError(s.T(), json.NewEncoder(w).Encode(s.mockedDownloadFleetdmMeta))

}
}))
s.T().Setenv("FLEET_DEV_DOWNLOAD_FLEETDM_URL", downloadFleetdmSrv.URL)
Expand Down Expand Up @@ -2206,8 +2205,7 @@ func (s *integrationMDMTestSuite) TestEnrollOrbitAfterDEPSync() {
ctx := context.Background()

// create a host with minimal information and the serial, no uuid/osquery id
// (as when created via DEP sync). Platform must be "darwin" as this is the
// only supported OS with DEP.
// (as when created via DEP sync).
dbZeroTime := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
h, err := s.ds.NewHost(ctx, &fleet.Host{
HardwareSerial: uuid.New().String(),
Expand All @@ -2217,6 +2215,7 @@ func (s *integrationMDMTestSuite) TestEnrollOrbitAfterDEPSync() {
RefetchRequested: true,
})
require.NoError(t, err)
require.Equal(t, dbZeroTime, h.LastEnrolledAt)

// create an enroll secret
secret := uuid.New().String()
Expand All @@ -2242,6 +2241,7 @@ func (s *integrationMDMTestSuite) TestEnrollOrbitAfterDEPSync() {
var hostResp getHostResponse
s.DoJSON("GET", fmt.Sprintf("/api/latest/fleet/hosts/%d", h.ID), nil, http.StatusOK, &hostResp)
require.Equal(t, h.ID, hostResp.Host.ID)
require.NotEqual(t, dbZeroTime, hostResp.Host.LastEnrolledAt)

got, err := s.ds.LoadHostByOrbitNodeKey(ctx, resp.OrbitNodeKey)
require.NoError(t, err)
Expand Down Expand Up @@ -6402,7 +6402,7 @@ func (s *integrationMDMTestSuite) TestRunMDMCommands() {

// create a Windows host enrolled in MDM
enrolledWindows := createOrbitEnrolledHost(t, "windows", "h1", s.ds)
//deviceID := "DB257C3A08778F4FB61E2749066C1F27"
// deviceID := "DB257C3A08778F4FB61E2749066C1F27"
mdmDevice := mdmtest.NewTestMDMClientWindowsProgramatic(s.server.URL, *enrolledWindows.OrbitNodeKey)
err := mdmDevice.Enroll()
require.NoError(t, err)
Expand Down Expand Up @@ -8245,7 +8245,6 @@ func (s *integrationMDMTestSuite) TestLockUnlockWipeMacOS() {

// lock the host without viewing the PIN
s.Do("POST", fmt.Sprintf("/api/latest/fleet/hosts/%d/lock", host.ID), nil, http.StatusNoContent)

}

func (s *integrationMDMTestSuite) TestZCustomConfigurationWebURL() {
Expand Down Expand Up @@ -9114,3 +9113,75 @@ func (s *integrationMDMTestSuite) TestMDMRequestWithoutCerts() {
res := s.DoRawNoAuth("PUT", "/mdm/apple/mdm", nil, http.StatusBadRequest)
require.NoError(t, res.Body.Close())
}

func (s *integrationMDMTestSuite) TestMDMEnrollDoesntClearLastEnrolledAtForMacOS() {
t := s.T()

// Enroll to Fleet with fleetd first.
desktopToken := uuid.New().String()
lastEnrolledAt := time.Now().UTC()
mdmDevice := mdmtest.NewTestMDMClientAppleDesktopManual(s.server.URL, desktopToken)
fleetHost, err := s.ds.NewHost(context.Background(), &fleet.Host{
DetailUpdatedAt: time.Now(),
LabelUpdatedAt: time.Now(),
PolicyUpdatedAt: time.Now(),
LastEnrolledAt: lastEnrolledAt,
SeenTime: time.Now().Add(-1 * time.Minute),
OsqueryHostID: ptr.String(t.Name() + uuid.New().String()),
NodeKey: ptr.String(t.Name() + uuid.New().String()),
Hostname: fmt.Sprintf("%sfoo.local", t.Name()),
Platform: "darwin",

UUID: mdmDevice.UUID,
HardwareSerial: mdmDevice.SerialNumber,
})
require.NoError(t, err)
err = s.ds.SetOrUpdateDeviceAuthToken(context.Background(), fleetHost.ID, desktopToken)
require.NoError(t, err)

// Enroll with MDM manually after.
err = mdmDevice.Enroll()
require.NoError(t, err)

hostResp := getHostResponse{}
s.DoJSON("GET", fmt.Sprintf("/api/latest/fleet/hosts/%d", fleetHost.ID), nil, http.StatusOK, &hostResp)
require.NotNil(t, hostResp.Host)
require.Equal(t, lastEnrolledAt.Truncate(1*time.Second).UTC(), hostResp.Host.LastEnrolledAt.Truncate(1*time.Second).UTC())
}

func (s *integrationMDMTestSuite) TestEnrollAfterDEPSyncIOSIPadOS() {
t := s.T()
ctx := context.Background()

// create a host with minimal information and the serial, no uuid/osquery id
// (as when created via DEP sync).
dbZeroTime := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
serialNumber := mdmtest.RandSerialNumber()
h, err := s.ds.NewHost(ctx, &fleet.Host{
HardwareSerial: serialNumber,
Platform: "ios",
LastEnrolledAt: dbZeroTime,
DetailUpdatedAt: dbZeroTime,
RefetchRequested: true,
})
require.NoError(t, err)
require.Equal(t, dbZeroTime, h.LastEnrolledAt)

// Perform the MDM enrollment.
mdmEnrollInfo := mdmtest.AppleEnrollInfo{
SCEPChallenge: s.scepChallenge,
SCEPURL: s.server.URL + apple_mdm.SCEPPath,
MDMURL: s.server.URL + apple_mdm.MDMPath,
}
mdmDevice := mdmtest.NewTestMDMClientAppleDirect(mdmEnrollInfo, "iPhone14,6")
mdmDevice.SerialNumber = serialNumber
err = mdmDevice.Enroll()
require.NoError(t, err)

// fetch the host, it will match the one created above
// (NOTE: cannot check the returned OrbitNodeKey, this field is not part of the response)
var hostResp getHostResponse
s.DoJSON("GET", fmt.Sprintf("/api/latest/fleet/hosts/%d", h.ID), nil, http.StatusOK, &hostResp)
require.Equal(t, h.ID, hostResp.Host.ID)
require.NotEqual(t, dbZeroTime, hostResp.Host.LastEnrolledAt)
}
Loading