Closes #45024 ## Summary - Fixed the MDM SSO callback handler returning a `"missing profile: missing profile"` error when an Android device enrolls via SSO (OTA enrollment) on a Fleet instance that does **not** have Apple MDM configured. - Refactored all MDM SSO initiator magic strings (`"ota_enroll"`, `"setup_experience"`, `"account_driven_enroll"`) into named constants (`fleet.SSOInitiatorOTAEnroll`, etc.) to prevent typos and missed cases — which is the class of bug that caused this issue. ## Code walkthrough ### The bug The bug is in `ee/server/service/mdm.go` in `mdmSSOHandleCallbackAuth()`. **The flow:** 1. Android enrollment hits `/enroll?enroll_secret=xxx` → frontend calls `InitiateMDMSSO` with initiator `"ota_enroll"` (`server/service/frontend.go:248`) 2. User authenticates at the SAML IdP 3. The SSO callback arrives at `MDMSSOCallback` → calls `mdmSSOHandleCallbackAuth` 4. After successful SAML auth, the function checks early-exit conditions: - Line 1133: account-driven enrollment (`originalURL == appleMDMAccountDrivenEnrollmentUrl`) → **no match** for OTA - Line 1139: `Initiator != "setup_experience"` → **true** for `"ota_enroll"` → enters the block 5. Line 1140: calls `getAutomaticEnrollmentProfile()` → returns `nil` because **no Apple MDM is configured** 6. Line 1144–1146: `depProf == nil` → **returns `"missing profile"` error** Note that `MDMSSOCallback` (the caller) already has a guard at line 931 that correctly skips the Apple MDM verification for `/enroll?` paths: ```go if !strings.HasPrefix(originalURL, "/enroll?") && ssoRequestData.Initiator != "setup_experience" { if err := svc.VerifyMDMAppleConfigured(ctx); err != nil { ... } } ``` But `mdmSSOHandleCallbackAuth` was missing the equivalent guard — it unconditionally tried to fetch the Apple DEP profile for any non-`setup_experience` initiator. ### The fix Adds an early return for OTA enrollments (where `originalURL` starts with `/enroll?`), matching the existing pattern for account-driven enrollments right above it. OTA enrollments don't use the Apple DEP profile token. ### The refactor Replaced all raw initiator string literals across the backend with named constants defined in `server/fleet/app.go`: | Constant | Value | Used by | |---|---|---| | `fleet.SSOInitiatorOTAEnroll` | `"ota_enroll"` | `/enroll` page (Android, BYOD iPhone/iPad) | | `fleet.SSOInitiatorSetupExperience` | `"setup_experience"` | Orbit agent (macOS Setup Assistant) | | `fleet.SSOInitiatorAccountDrivenEnroll` | `"account_driven_enroll"` | Apple account-driven MDM enrollment | Constants are in `server/fleet/` (not `server/sso/`) so orbit can import them without pulling in Redis dependencies. **Files changed:** - `ee/server/service/mdm.go` — 6 string replacements (switch cases + comparisons) - `server/service/frontend.go` — 1 replacement - `orbit/cmd/orbit/orbit.go` — 1 replacement - `server/service/testing_client.go` — 1 replacement - `server/service/integration_mdm_test.go` — 1 replacement ## Local reproduction ### Setup 1. Started dev server: `build/fleet serve --dev --dev_license` 2. Infrastructure: MySQL, Redis, SimpleSAML IdP via `docker compose up` 3. Created admin user and enroll secret 4. Configured MDM SSO (`entity_id: mdm.test.com`, SimpleSAML IdP at `localhost:9080`) 5. Set `enable_end_user_authentication: true` directly in DB (API blocks this without Apple MDM — matches customer state) 6. **Did NOT configure Apple MDM** — only SSO + EUA, simulating Android-only instance ### Steps 1. `GET https://localhost:8080/enroll?enroll_secret=test_enroll_secret` → 303 redirect to SimpleSAML IdP 2. Completed SAML login programmatically (user: `sso_user`, pass: `user123#`) 3. `POST https://localhost:8080/api/v1/fleet/mdm/sso/callback` with the SAMLResponse ### Before fix ``` === CALLBACK RESULT === Status: HTTP/2 303 Location: /mdm/sso/callback?error=true === SERVER LOGS === ts=2026-05-08T16:53:49Z level=error component=http method=POST uri=/api/v1/fleet/mdm/sso/callback took=12.148708ms err="missing profile: missing profile" ``` ### After fix ``` === CALLBACK RESULT === Status: HTTP/2 303 Location: /enroll?enroll_secret=test_enroll_secret&enrollment_reference=7c67326c-...&initiator=ota_enroll&profile_token= === SERVER LOGS === ts=2026-05-08T17:27:54Z level=info component=http method=POST uri=/api/v1/fleet/mdm/sso/callback took=15.973ms ``` No errors. Successful redirect back to the enrollment page with the enrollment reference. ## Integration test Added `TestOTAEnrollSSOWithoutAppleDEPProfile` which: 1. Configures SSO and creates a team with IdP enabled 2. **Deletes all Apple DEP enrollment profiles** to simulate an Android-only instance 3. Runs the full OTA enrollment SSO flow (GET `/enroll` → SAML IdP login → callback) 4. Verifies the callback redirects to `/enroll?...` with `enrollment_reference` and `initiator=ota_enroll` (not `?error=true`) Confirmed the test **fails without the fix** (`err="missing profile: missing profile"`) and **passes with the fix**. Also added a `LoginOTAEnrollSSOUser` test helper that drives the complete OTA SSO flow starting from `GET /enroll` through SAML IdP login to the callback, using a single cookie jar. ## Test plan - [ ] Verify Android SSO enrollment works on an instance with **only** Android MDM configured (no Apple MDM) - [ ] Verify Apple DEP enrollment with SSO still works (the DEP profile path is unchanged) - [ ] Verify Apple OTA enrollment with SSO still works (also uses `/enroll?` path) - [ ] Verify account-driven enrollment with SSO still works (has its own early return) - [ ] Verify setup experience SSO still works (uses `Initiator == "setup_experience"`) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Resolved a regression where OTA enrollment via SSO could return a "missing profile" error on Android when Apple MDM is not configured; OTA SSO now redirects correctly to the enrollment flow. [](https://app.coderabbit.ai/change-stack/fleetdm/fleet/pull/45046) <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Magnus Jensen <magnus@fleetdm.com>
269 lines
8.2 KiB
Go
269 lines
8.2 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"html/template"
|
|
"io"
|
|
"log/slog"
|
|
"net/http"
|
|
"net/url"
|
|
|
|
assetfs "github.com/elazarl/go-bindata-assetfs"
|
|
shared_mdm "github.com/fleetdm/fleet/v4/pkg/mdm"
|
|
"github.com/fleetdm/fleet/v4/server/bindata"
|
|
"github.com/fleetdm/fleet/v4/server/fleet"
|
|
"github.com/fleetdm/fleet/v4/server/platform/endpointer"
|
|
"github.com/klauspost/compress/gzhttp"
|
|
)
|
|
|
|
func newBinaryFileSystem(root string) *assetfs.AssetFS {
|
|
return &assetfs.AssetFS{
|
|
Asset: bindata.Asset,
|
|
AssetDir: bindata.AssetDir,
|
|
AssetInfo: bindata.AssetInfo,
|
|
Prefix: root,
|
|
}
|
|
}
|
|
|
|
func ServeFrontend(urlPrefix string, sandbox bool, logger *slog.Logger, serveCSP bool) http.Handler {
|
|
herr := func(ctx context.Context, w http.ResponseWriter, err string) {
|
|
logger.ErrorContext(ctx, err)
|
|
http.Error(w, err, http.StatusInternalServerError)
|
|
}
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
ctx := r.Context()
|
|
nonce, err := endpointer.WriteBrowserSecurityHeaders(w, serveCSP, serveCSP)
|
|
if err != nil {
|
|
herr(ctx, w, "write browser security headers err: "+err.Error())
|
|
return
|
|
}
|
|
|
|
// The following check is to prevent a misconfigured osquery from submitting
|
|
// data to the root endpoint (the osquery remote API uses POST for all its endpoints).
|
|
// See https://github.com/fleetdm/fleet/issues/16182.
|
|
if r.Method == "POST" {
|
|
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
|
|
fs := newBinaryFileSystem("/frontend")
|
|
file, err := fs.Open("templates/react.tmpl")
|
|
if err != nil {
|
|
herr(ctx, w, "load react template: "+err.Error())
|
|
return
|
|
}
|
|
data, err := io.ReadAll(file)
|
|
if err != nil {
|
|
herr(ctx, w, "read bindata file: "+err.Error())
|
|
return
|
|
}
|
|
t, err := template.New("react").Parse(string(data))
|
|
if err != nil {
|
|
herr(ctx, w, "create react template: "+err.Error())
|
|
return
|
|
}
|
|
serverType := "on-premise"
|
|
if sandbox {
|
|
serverType = "sandbox"
|
|
}
|
|
if err := t.Execute(w, struct {
|
|
URLPrefix string
|
|
ServerType string
|
|
CSPNonce string
|
|
}{
|
|
URLPrefix: urlPrefix,
|
|
ServerType: serverType,
|
|
CSPNonce: nonce,
|
|
}); err != nil {
|
|
herr(ctx, w, "execute react template: "+err.Error())
|
|
return
|
|
}
|
|
})
|
|
}
|
|
|
|
// ServeEndUserEnrollOTA implements the entrypoint handler for the /enroll
|
|
// path, used to add hosts in "BYOD" mode (currently, iPhone/iPad/Android).
|
|
func ServeEndUserEnrollOTA(
|
|
svc fleet.Service,
|
|
urlPrefix string,
|
|
ds fleet.Datastore,
|
|
logger *slog.Logger,
|
|
serveCSP bool,
|
|
) http.Handler {
|
|
herr := func(ctx context.Context, w http.ResponseWriter, err string) {
|
|
logger.ErrorContext(ctx, err)
|
|
http.Error(w, err, http.StatusInternalServerError)
|
|
}
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
nonce, err := endpointer.WriteBrowserSecurityHeaders(w, serveCSP, serveCSP)
|
|
if err != nil {
|
|
herr(r.Context(), w, "write browser security headers err: "+err.Error())
|
|
return
|
|
}
|
|
ctx := r.Context()
|
|
setupRequired, err := svc.SetupRequired(ctx)
|
|
if err != nil {
|
|
herr(ctx, w, "setup required err: "+err.Error())
|
|
return
|
|
}
|
|
if setupRequired {
|
|
herr(ctx, w, "fleet instance not setup")
|
|
return
|
|
}
|
|
|
|
appCfg, err := ds.AppConfig(r.Context())
|
|
if err != nil {
|
|
herr(ctx, w, "load appconfig err: "+err.Error())
|
|
return
|
|
}
|
|
|
|
errorMsg := r.URL.Query().Get("error")
|
|
if errorMsg != "" {
|
|
if err := renderEnrollPage(w, appCfg, urlPrefix, "", errorMsg, nonce); err != nil {
|
|
herr(ctx, w, err.Error())
|
|
}
|
|
return
|
|
}
|
|
|
|
enrollSecret := r.URL.Query().Get("enroll_secret")
|
|
if enrollSecret == "" {
|
|
if err := renderEnrollPage(w, appCfg, urlPrefix, "", "This URL is invalid. : Enroll secret is invalid. Please contact your IT admin.", nonce); err != nil {
|
|
herr(ctx, w, err.Error())
|
|
}
|
|
return
|
|
}
|
|
|
|
authRequired, err := shared_mdm.RequiresEnrollOTAAuthentication(r.Context(), ds,
|
|
enrollSecret, appCfg.MDM.MacOSSetup.EnableEndUserAuthentication)
|
|
if err != nil {
|
|
herr(ctx, w, "check if authentication is required err: "+err.Error())
|
|
return
|
|
}
|
|
|
|
if authRequired {
|
|
// check if authentication cookie is present, in which case we go ahead with
|
|
// offering the enrollment profile to download.
|
|
var cookieIdPRef string
|
|
if byodCookie, _ := r.Cookie(shared_mdm.BYODIdpCookieName); byodCookie != nil {
|
|
cookieIdPRef = byodCookie.Value
|
|
|
|
// if the cookie is present, we should also receive a (matching) enroll reference
|
|
if cookieIdPRef != "" {
|
|
enrollRef := r.URL.Query().Get("enrollment_reference")
|
|
if cookieIdPRef != enrollRef {
|
|
cookieIdPRef = "" // cookie does not match the enroll reference, so we ignore it and require authentication
|
|
}
|
|
}
|
|
}
|
|
|
|
if cookieIdPRef == "" {
|
|
// IdP authentication has not been completed yet, initiate it by
|
|
// redirecting to the configured IdP provider.
|
|
if err := initiateOTAEnrollSSO(svc, w, r, enrollSecret); err != nil {
|
|
herr(ctx, w, "initiate IdP SSO authentication err: "+err.Error())
|
|
return
|
|
}
|
|
return
|
|
}
|
|
}
|
|
|
|
// if we get here, IdP SSO authentication is either not required, or has
|
|
// been successfully completed (we have a cookie with the IdP account
|
|
// reference).
|
|
if err := renderEnrollPage(w, appCfg, urlPrefix, enrollSecret, "", nonce); err != nil {
|
|
herr(ctx, w, err.Error())
|
|
return
|
|
}
|
|
})
|
|
}
|
|
|
|
func generateEnrollOTAURL(fleetURL string, enrollSecret string) (string, error) {
|
|
path, err := url.JoinPath(fleetURL, "/api/v1/fleet/enrollment_profiles/ota")
|
|
if err != nil {
|
|
return "", fmt.Errorf("creating path for end user ota enrollment url: %w", err)
|
|
}
|
|
|
|
enrollURL, err := url.Parse(path)
|
|
if err != nil {
|
|
return "", fmt.Errorf("parsing end user ota enrollment url: %w", err)
|
|
}
|
|
|
|
q := enrollURL.Query()
|
|
q.Set("enroll_secret", enrollSecret)
|
|
enrollURL.RawQuery = q.Encode()
|
|
return enrollURL.String(), nil
|
|
}
|
|
|
|
func renderEnrollPage(w io.Writer, appCfg *fleet.AppConfig, urlPrefix, enrollSecret, errorMessage, nonce string) error {
|
|
fs := newBinaryFileSystem("/frontend")
|
|
file, err := fs.Open("templates/enroll-ota.html")
|
|
if err != nil {
|
|
return fmt.Errorf("load enroll ota template: %w", err)
|
|
}
|
|
|
|
data, err := io.ReadAll(file)
|
|
if err != nil {
|
|
return fmt.Errorf("read bindata file: %w", err)
|
|
}
|
|
|
|
t, err := template.New("enroll-ota").Parse(string(data))
|
|
if err != nil {
|
|
return fmt.Errorf("create react template: %w", err)
|
|
}
|
|
|
|
enrollURL, err := generateEnrollOTAURL(urlPrefix, enrollSecret)
|
|
if err != nil {
|
|
return fmt.Errorf("generate enroll ota url: %w", err)
|
|
}
|
|
if err := t.Execute(w, struct {
|
|
EnrollURL string
|
|
URLPrefix string
|
|
ErrorMessage string
|
|
AndroidMDMEnabled bool
|
|
MacMDMEnabled bool
|
|
AndroidFeatureEnabled bool
|
|
CSPNonce string
|
|
}{
|
|
URLPrefix: urlPrefix,
|
|
EnrollURL: enrollURL,
|
|
ErrorMessage: errorMessage,
|
|
AndroidMDMEnabled: appCfg.MDM.AndroidEnabledAndConfigured,
|
|
MacMDMEnabled: appCfg.MDM.EnabledAndConfigured,
|
|
AndroidFeatureEnabled: true,
|
|
CSPNonce: nonce,
|
|
}); err != nil {
|
|
return fmt.Errorf("execute react template: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func initiateOTAEnrollSSO(svc fleet.Service, w http.ResponseWriter, r *http.Request, enrollSecret string) error {
|
|
requestURL := "/enroll?enroll_secret=" + url.QueryEscape(enrollSecret)
|
|
// pass the fully_managed parameter for Android enrollments so that it is returned after the callback, else the
|
|
// user won't get the android fully managed page
|
|
if r.URL.Query().Get("fully_managed") == "true" {
|
|
requestURL += "&fully_managed=true"
|
|
}
|
|
ssnID, ssnDurationSecs, idpURL, err := svc.InitiateMDMSSO(r.Context(), fleet.SSOInitiatorOTAEnroll, requestURL, "")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
setSSOCookie(w, ssnID, ssnDurationSecs)
|
|
http.Redirect(w, r, idpURL, http.StatusSeeOther)
|
|
return nil
|
|
}
|
|
|
|
func ServeStaticAssets(path string, serveCSP bool) http.Handler {
|
|
contentTypes := []string{"text/javascript", "text/css"}
|
|
staticAssetsServer := endpointer.BrowserSecurityHeadersHandler(serveCSP, http.FileServer(newBinaryFileSystem("/assets")))
|
|
withoutGzip := http.StripPrefix(path, staticAssetsServer)
|
|
|
|
withOpts, err := gzhttp.NewWrapper(gzhttp.ContentTypes(contentTypes))
|
|
if err != nil { // fall back to serving without gzip if serving with gzip somehow fails
|
|
return withoutGzip
|
|
}
|
|
|
|
return withOpts(withoutGzip)
|
|
}
|