Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
74 changes: 74 additions & 0 deletions coordinator/api/mdm_webhook_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package api

import (
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"

"github.com/eigeninference/d-inference/coordinator/registry"
"github.com/eigeninference/d-inference/coordinator/store"
)

func mdmTestServer(t *testing.T) *Server {
t.Helper()
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
st := store.NewMemory(store.Config{AdminKey: "test-key"})
reg := registry.New(logger)
return NewServer(reg, st, ServerConfig{}, logger)
}

// TestMDMWebhookSecretGate verifies the optional shared-secret layer: when a
// secret is configured, callers without it are rejected before the body is read;
// with it, the request is accepted.
func TestMDMWebhookSecretGate(t *testing.T) {
srv := mdmTestServer(t)
srv.SetMDMWebhookSecret("s3cret")

// No token → forbidden.
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/v1/mdm/webhook", strings.NewReader("{}"))
srv.HandleMDMWebhook(rec, req)
if rec.Code != http.StatusForbidden {
t.Fatalf("missing token: want 403, got %d", rec.Code)
}

// Wrong token → forbidden.
rec = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodPost, "/v1/mdm/webhook?token=wrong", strings.NewReader("{}"))
srv.HandleMDMWebhook(rec, req)
if rec.Code != http.StatusForbidden {
t.Fatalf("wrong token: want 403, got %d", rec.Code)
}

// Correct token (query param) → accepted (200; body is empty JSON, no-op).
rec = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodPost, "/v1/mdm/webhook?token=s3cret", strings.NewReader("{}"))
srv.HandleMDMWebhook(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("correct token (query): want 200, got %d", rec.Code)
}

// Correct token (header) → accepted.
rec = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodPost, "/v1/mdm/webhook", strings.NewReader("{}"))
req.Header.Set("X-Webhook-Token", "s3cret")
srv.HandleMDMWebhook(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("correct token (header): want 200, got %d", rec.Code)
}
}

// TestMDMWebhookNoSecretConfigured verifies that when no secret is set, the
// endpoint does not 403 (it relies on the solicited-command gate instead).
func TestMDMWebhookNoSecretConfigured(t *testing.T) {
srv := mdmTestServer(t)
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/v1/mdm/webhook", strings.NewReader("{}"))
srv.HandleMDMWebhook(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("no secret configured: want 200, got %d", rec.Code)
}
}
43 changes: 43 additions & 0 deletions coordinator/api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,7 @@ type Server struct {
adminEmails map[string]bool // emails that have admin access
adminKey string // EIGENINFERENCE_ADMIN_KEY for admin endpoints
mdmClient *mdm.Client // MicroMDM client for provider security verification
mdmWebhookSecret string // optional shared secret MicroMDM must present on the webhook
stepCARootCert *x509.Certificate // step-ca root CA for ACME cert verification
stepCAIntermediateCert *x509.Certificate // step-ca intermediate CA

Expand Down Expand Up @@ -702,6 +703,16 @@ func (s *Server) SetMDMClient(client *mdm.Client) {
s.mdmClient = client
}

// SetMDMWebhookSecret configures an optional shared secret that MicroMDM must
// present (as ?token= or the X-Webhook-Token header) when calling the webhook.
// When empty, the webhook relies solely on the solicited-command (CommandUUID)
// gate in the MDM client; when set, callers lacking the secret are rejected
// before the body is read. MicroMDM is co-located with the coordinator, so this
// secret never traverses the public network.
func (s *Server) SetMDMWebhookSecret(secret string) {
s.mdmWebhookSecret = secret
}

// SyncModelCatalog reads active models from the store and updates the
// registry's model catalog. Call this at startup and after admin catalog changes.
func (s *Server) SyncModelCatalog() {
Expand Down Expand Up @@ -1187,9 +1198,29 @@ func (s *Server) handleRuntimeManifest(w http.ResponseWriter, r *http.Request) {
writeCachedJSON(w, body)
}

// maxMDMWebhookBodyBytes caps the MicroMDM webhook body. SecurityInfo /
// DevicePropertiesAttestation responses are a few KB; 1 MiB is generous headroom
// while preventing an unauthenticated caller from exhausting memory via an
// unbounded body.
const maxMDMWebhookBodyBytes = 1 << 20 // 1 MiB

// HandleMDMWebhook processes a MicroMDM webhook callback.
// Mount this on the webhook URL configured in MicroMDM.
//
// Defense layers (the endpoint is reachable but cannot forge trust):
// 1. Body cap — bounds memory for the unauthenticated path.
// 2. Optional shared secret — when configured, rejects callers without it
// before reading the body.
// 3. Solicited-command gate (in mdm.Client.HandleWebhook) — only responses
// whose CommandUUID matches a command the coordinator actually issued are
// acted on, so a forged SecurityInfo can never drive a trust upgrade.
func (s *Server) HandleMDMWebhook(w http.ResponseWriter, r *http.Request) {
if s.mdmWebhookSecret != "" && !s.mdmWebhookTokenValid(r) {
s.logger.Warn("mdm webhook rejected: missing/invalid shared secret", "remote_addr", r.RemoteAddr)
http.Error(w, "forbidden", http.StatusForbidden)
return
}
r.Body = http.MaxBytesReader(w, r.Body, maxMDMWebhookBodyBytes)
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
Expand All @@ -1202,6 +1233,18 @@ func (s *Server) HandleMDMWebhook(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}

// mdmWebhookTokenValid reports whether the request carries the configured MDM
// webhook secret, via either the X-Webhook-Token header or a ?token= query
// param. Comparison is constant-time. Only called when a secret is configured.
func (s *Server) mdmWebhookTokenValid(r *http.Request) bool {
token := r.Header.Get("X-Webhook-Token")
if token == "" {
token = r.URL.Query().Get("token")
}
return token != "" &&
subtle.ConstantTimeCompare([]byte(token), []byte(s.mdmWebhookSecret)) == 1
}

//go:embed install.sh
var installScript []byte

Expand Down
13 changes: 13 additions & 0 deletions coordinator/cmd/coordinator/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,19 @@ func main() {
})

srv.SetMDMClient(mdmClient)
// Optional shared secret for the MicroMDM webhook. Defense-in-depth on
// top of the mandatory solicited-command (CommandUUID) gate: configure
// MicroMDM's command-webhook-url with ?token=<secret> and set this to
// the same value to reject any caller that lacks it.
if webhookSecret := os.Getenv("EIGENINFERENCE_MDM_WEBHOOK_SECRET"); webhookSecret != "" {
srv.SetMDMWebhookSecret(webhookSecret)
Comment on lines +391 to +392

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Wire the webhook secret into MicroMDM's callback URL

When EIGENINFERENCE_MDM_WEBHOOK_SECRET is set here, the server starts rejecting webhook calls that lack the token, but the repo's MicroMDM launch path still uses coordinator/deploy/start.sh with -command-webhook-url http://localhost:8080/v1/mdm/webhook and does not append ?token=... or set the X-Webhook-Token header. In deployments that follow that script and enable the new recommended secret, every legitimate SecurityInfo/MDA callback will get 403 before the MDM client sees it, so provider hardware trust verification will time out.

Useful? React with 👍 / 👎.

logger.Info("MDM webhook shared-secret auth enabled")
} else {
// The solicited-command (CommandUUID) gate still protects the
// webhook, but the shared secret is the recommended extra layer.
// Warn so a misconfigured deployment is visible at startup.
logger.Warn("EIGENINFERENCE_MDM_WEBHOOK_SECRET not set — MDM webhook relies solely on the CommandUUID gate; set it + keep MicroMDM bound to localhost for defense in depth")
}
logger.Info("MDM verification enabled", "url", mdmCfg.URL)
}

Expand Down
14 changes: 13 additions & 1 deletion coordinator/deploy/start.sh
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,18 @@ if [ -n "$MICROMDM_API_KEY" ]; then
-days 3650 -subj "/CN=localhost" 2>/dev/null
fi

# If the coordinator is configured with EIGENINFERENCE_MDM_WEBHOOK_SECRET it
# rejects any MDM callback that doesn't present that secret. MicroMDM has no
# option to set a header on the command webhook, so the shared secret rides
# as a ?token= query param (the coordinator also accepts the X-Webhook-Token
# header — see HandleMDMWebhook). These MUST stay in sync: setting the secret
# on the coordinator without this token would 403 every legitimate
# SecurityInfo/MDA callback and stall provider hardware-trust verification.
MDM_WEBHOOK_URL="http://localhost:8080/v1/mdm/webhook"
if [ -n "${EIGENINFERENCE_MDM_WEBHOOK_SECRET:-}" ]; then
MDM_WEBHOOK_URL="${MDM_WEBHOOK_URL}?token=${EIGENINFERENCE_MDM_WEBHOOK_SECRET}"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge URL-encode the webhook token parameter

When EIGENINFERENCE_MDM_WEBHOOK_SECRET contains query-significant characters (for example a standard base64 secret with + or &), this constructs a callback URL whose token value is not the same string the coordinator later compares: r.URL.Query().Get("token") decodes + as space and treats & as a separator before the constant-time comparison. In deployments that generate random/base64 secrets, legitimate MicroMDM callbacks can therefore be rejected with 403; encode the value before appending it or require a URL-safe secret alphabet.

Useful? React with 👍 / 👎.

fi

echo "Starting MicroMDM..."
micromdm serve \
-server-url "https://${DOMAIN:-localhost}" \
Expand All @@ -89,7 +101,7 @@ if [ -n "$MICROMDM_API_KEY" ]; then
-tls-key /data/micromdm/server.key \
-http-addr :9002 \
-http-proxy-headers \
-command-webhook-url http://localhost:8080/v1/mdm/webhook \
-command-webhook-url "${MDM_WEBHOOK_URL}" \
>> /data/micromdm.log 2>&1 &

# Wait for MicroMDM to be ready, then import push cert if needed
Expand Down
Loading
Loading