Skip to content
Closed
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ coordinator/ Go control plane (packages live at top level, not internal
├── env/ shared env-var helpers/constants
├── mdm/ MicroMDM client + webhook handling
├── payments/ ledger + pricing (+ baserewards/)
├── providercontrol/trustreuse/ durable device evidence, revocation journal/replay and continuity (Manager)
├── profilesign/ CMS-signing of .mobileconfig enrollment profiles
├── protocol/ WebSocket message types shared with provider (type_scan.go: single-parse frame decode)
├── ratelimit/ rate limiting
Expand Down
18 changes: 11 additions & 7 deletions coordinator/api/mdm_scheduler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"crypto/sha256"
"fmt"
"github.com/eigeninference/d-inference/coordinator/providercontrol/trustreuse"
"io"
"log/slog"
"strings"
Expand Down Expand Up @@ -364,11 +365,11 @@ func TestContinuityMissPromotesRefreshSubmitToImmediateDue(t *testing.T) {
})
srv.mdmClient = dummyMDMClient()
cur := now
srv.trustReuseCache.now = func() time.Time { return cur }
setTrustReuseClock(t, srv, func() time.Time { return cur })

p := schedulerTestProvider(t, srv, "cont-miss", "se-cont-miss")
// Stale window, continuity-covered 60s ago → a reuse candidate at submit.
srv.trustReuseCache.recordTrust(coveredReuseRecord(
seedTrustReuseRecord(t, srv, coveredReuseRecord(
"se-cont-miss", "serial-cont-miss", trHashA,
cur.Add(-20*time.Minute), cur.Add(-60*time.Second)))
priority := srv.verificationSubmitPriority("se-cont-miss", "serial-cont-miss")
Expand Down Expand Up @@ -1637,20 +1638,23 @@ func TestMDMSchedulerFleet1500LifecycleSimulation(t *testing.T) {
t.Fatalf("restart reset due time for %s", se)
}
}
transitionCache := newTrustReuseCacheWithWindow(time.Hour)
transitionCache.now = func() time.Time { return now }
var transitionRows []store.ProviderTrustReuse
for i := range providers {
transitionRows = append(transitionRows, hardwareReuseRecord(
fmt.Sprintf("fleet-se-%04d", i), fmt.Sprintf("serial-fleet-%04d", i), trHashA, now))
}
transitionCache := trustReuseAssessmentForRecords(t, now, transitionRows)
for i := range providers {
se := fmt.Sprintf("fleet-se-%04d", i)
serial := fmt.Sprintf("serial-fleet-%04d", i)
transitionCache.recordTrust(hardwareReuseRecord(se, serial, trHashA, now))
decision := transitionCache.decideTrustReuse(trustReuseInput{
decision := transitionCache.Assess(trustreuse.Input{
SEPubKey: se, Serial: serial, FreshBinaryHash: trHashB,
ReleaseTransition: approvedReleaseTransitionFact{
Approved: true, BinaryHash: trHashB,
ApprovedFromBinaryHashes: map[string]struct{}{trHashA: {}},
},
})
if decision.Decision != trustReuseDecisionApprovedReleaseTransition {
if decision.Decision != trustreuse.DecisionApprovedReleaseTransition {
t.Fatalf("approved release transition %d required live MDM: %q", i, decision.Decision)
}
}
Expand Down
4 changes: 2 additions & 2 deletions coordinator/api/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ func (s *Server) providerReadLoop(ctx context.Context, conn *websocket.Conn, pro
// observed disconnect time (before registry.Disconnect tears the
// provider down), so the measured reconnect gap starts here rather
// than at the last periodic coverage pass.
s.stopTrustCoverageForProvider(providerID)
s.trustReuse.StopProviderCoverage(providerID)
s.stopCodeAttestCoverageForProvider(providerID)
s.registry.DisconnectWithReason(providerID, registry.ClassifyPeerClose(peerCloseStatus, false))
conn.Close(websocket.StatusNormalClosure, "goodbye")
Expand Down Expand Up @@ -1689,7 +1689,7 @@ func (s *Server) verifyChallengeResponse(providerID string, provider *registry.P
// is optimistic: if the fast-skip later DECLINES despite it, the read path
// promotes the job back to first/expired (PromoteFailedFastSkip).
func (s *Server) verificationSubmitPriority(seKey, serial string) store.VerificationPriority {
if s.trustReuseCache.hasFreshRecord(seKey, serial) {
if s.trustReuse.HasFreshRecord(seKey, serial) {
return store.VerificationPriorityRefresh
}
return store.VerificationPriorityFirstOrExpired
Expand Down
11 changes: 6 additions & 5 deletions coordinator/api/provider_mdm_reliability_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -444,7 +444,7 @@ func TestVerifyProviderViaMDM_SuccessGrantedWithoutBinaryHashOrApplicationEviden
if rows, _ := srv.store.ListProviderTrustReuse(context.Background()); len(rows) != 0 {
t.Fatalf("hashless grant must not persist reuse rows, got %d", len(rows))
}
if srv.trustReuseCache.hasFreshRecord("se-pub-key-bytes", "SERIAL-1") {
if srv.trustReuse.HasFreshRecord("se-pub-key-bytes", "SERIAL-1") {
t.Fatal("hashless grant must not cache an unbindable reuse record")
}
}
Expand Down Expand Up @@ -494,12 +494,13 @@ func TestVerifyProviderViaMDM_HashlessRegistrationUsesBoundApplicationEvidence(t
if rows[0].ApplicationProofVerifiedAt == nil || !rows[0].ApplicationProofVerifiedAt.Equal(verifiedAt) {
t.Fatalf("ApplicationProofVerifiedAt = %v, want %v", rows[0].ApplicationProofVerifiedAt, verifiedAt)
}
cached, ok := srv.trustReuseCache.reuseTrust("se-pub-key-bytes", "SERIAL-1", binaryHash)
if !ok {
if !hasReusableTrust(srv, "se-pub-key-bytes", "SERIAL-1", binaryHash) {
t.Fatal("bound application hash did not cache reusable hardware proof")
}
if cached.lastVerifiedBinaryHash != binaryHash {
t.Fatalf("cached binary hash = %q, want %q", cached.lastVerifiedBinaryHash, binaryHash)
// A same-binary assessment requires the cached binary to equal this hash.
// A different hash without an approved transition must remain rejected.
if hasReusableTrust(srv, "se-pub-key-bytes", "SERIAL-1", trHashA) {
t.Fatal("cached binary accepted a different hash without an approved transition")
}
}

Expand Down
69 changes: 12 additions & 57 deletions coordinator/api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,12 @@ import (
"encoding/json"
"errors"
"fmt"
"github.com/eigeninference/d-inference/coordinator/providercontrol/trustreuse"
"io"
"log/slog"
"net"
"net/http"
"os"

"runtime"
"runtime/debug"
"sort"
Expand Down Expand Up @@ -163,26 +164,7 @@ type Server struct {
codeResumeBeforeIdentityCheck func() // test seam between cache match and challenge record
codeResumeFallbackBeforeAPNs func() // test seam after nonce consume, before ctx recheck
codeAttestThrottle *codeAttestThrottle // per-device APNs push budget + reuse cache (v0.6.0)
trustReuseCache *trustReuseCache // per-device trust-reuse cache: skip a fleet-wide live MDM herd on restart (DAR-326)
trustReuseJournal hardUntrustJournal
trustRevocationMu sync.Mutex
trustSafetyMu sync.RWMutex
trustSafetySticky bool
trustSafetyReplayBlocked bool
pendingHardUntrustKeyHashes map[string]int
trustAuthorityMu sync.Mutex
trustAuthority *trustAuthorityLock
trustReplayCtx context.Context
trustReplayCancel context.CancelFunc
trustReplayMu sync.Mutex
trustReplayInFlight map[string]struct{}
// Connection-continuity coverage tracker: seKey → providerID of the live
// covered connection. Advanced by the batched trustCoverageLoop and the
// disconnect/shutdown sweeps (see trust_reuse.go).
trustCoverageMu sync.Mutex
trustCoverage map[string]string
trustCoverageCtx context.Context
trustCoverageCancel context.CancelFunc
trustReuse *trustreuse.Manager // durable device evidence, revocation, replay and continuity

// Graceful-drain state (DAR-327 Phase 1, zero-downtime upgrades). Set
// coordinatorDraining=true before a restart/swap so the drain gate rejects
Expand Down Expand Up @@ -756,7 +738,6 @@ func NewServer(reg *registry.Registry, st store.Store, cfg ServerConfig, logger
geoResolver: newProviderGeoResolverFromEnv(logger),
apiKeyCache: make(map[string]apiKeyCacheEntry),
codeAttestThrottle: newCodeAttestThrottle(),
trustReuseCache: newTrustReuseCache(),
mdmSchedulerConfig: cfg.MDMScheduler,
settlements: newSettlementHolder(),
zombieCanceller: newZombieStreamCanceller(),
Expand All @@ -767,34 +748,17 @@ func NewServer(reg *registry.Registry, st store.Store, cfg ServerConfig, logger
firstContentDeadlineBase: firstContentDeadlineBase,
routingScanSem: make(chan struct{}, DefaultRoutingConcurrency()),
}
if _, clampedDown := trustReuseReconnectGapFromEnv(); clampedDown {
logger.Warn("EIGENINFERENCE_TRUST_REUSE_RECONNECT_GAP exceeds the 120s security ceiling; clamping DOWN",
"requested", os.Getenv("EIGENINFERENCE_TRUST_REUSE_RECONNECT_GAP"),
"allowance", maxTrustReuseReconnectGap,
"reason", "a contiguous offline gap must stay below the RecoveryOS round-trip floor (Threat-Model T-036)",
)
}

// Registry write-lock wait, by call site. This is the acceptance metric
// for taking the recorders off the request path: today the wait is only
// inferable from goroutine dumps.
reg.SetLockWaitObserver(func(site string, wait time.Duration) {
s.ddHistogram("registry.mu.write_wait_ms", float64(wait.Microseconds())/1000, []string{"site:" + site})
})
s.trustCoverage = make(map[string]string)
s.trustCoverageCtx, s.trustCoverageCancel = context.WithCancel(context.Background())
saferun.Go(logger, "trustCoverageLoop", s.trustCoverageLoop)
if cfg.DurableTrustReuse {
journalPath := cfg.TrustReuseJournalPath
if strings.TrimSpace(journalPath) == "" {
journalPath = resolveTrustReuseRevocationJournalPath()
}
s.trustReuseJournal = newFileHardUntrustJournal(journalPath)
s.pendingHardUntrustKeyHashes = make(map[string]int)
s.trustReplayCtx, s.trustReplayCancel = context.WithCancel(
context.Background(),
)
s.trustReplayInFlight = make(map[string]struct{})
}
s.trustReuse = trustreuse.New(trustreuse.Config{
DurableTrustReuse: cfg.DurableTrustReuse,
TrustReuseJournalPath: cfg.TrustReuseJournalPath,
}, s.trustReuseDependencies())
reg.SetRuntimeCapabilitiesPromotedHook(s.handleRuntimeCapabilitiesPromoted)
// The per-identity gate locks that replaced the request-path registry
// write lock (registry/gate_state.go) report any acquisition wait above
Expand Down Expand Up @@ -871,14 +835,10 @@ func (s *Server) Close() {
// short deploy reconnects into the continuity fast-skip on the next
// coordinator instead of a fleet-wide live MDM herd. A crash skips this —
// the last periodic write stands and the gap is over-estimated (fail-safe).
if s.trustCoverageCancel != nil {
s.trustCoverageCancel()
}
s.finalTrustCoverageSweep()
s.trustReuse.StopCoverage()
s.trustReuse.FinalCoverageSweep()
s.sweepCodeAttestCoverage()
if s.trustReplayCancel != nil {
s.trustReplayCancel()
}
s.trustReuse.StopReplay()
if s.mdmScheduler != nil {
s.mdmScheduler.Close()
}
Expand All @@ -900,12 +860,7 @@ func (s *Server) Close() {
)
}
}
s.trustAuthorityMu.Lock()
if s.trustAuthority != nil {
_ = s.trustAuthority.Close()
s.trustAuthority = nil
}
s.trustAuthorityMu.Unlock()
s.trustReuse.ReleaseAuthority()
if s.requestOutcomes != nil {
s.requestOutcomes.Close()
}
Expand Down
3 changes: 2 additions & 1 deletion coordinator/api/server_config.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package api

import (
"github.com/eigeninference/d-inference/coordinator/providercontrol/trustreuse"
"os"
"strings"
"time"
Expand Down Expand Up @@ -80,7 +81,7 @@ func ReadServerConfig() ServerConfig {
AdminEmails: ParseCommaList(env.EnvOr(env.EnvPrefix+"_ADMIN_EMAILS", "")),
ReleaseKey: os.Getenv(env.EnvPrefix + "_RELEASE_KEY"),
ServiceReservations: env.EnvBool(env.EnvPrefix+"_SERVICE_RESERVATIONS_ENABLED", false),
TrustReuseJournalPath: resolveTrustReuseRevocationJournalPath(),
TrustReuseJournalPath: trustreuse.JournalPathFromEnv(),
MDMScheduler: readMDMSchedulerConfig(),
BaseRewards: BaseRewardsConfig{
Enabled: env.EnvBool(env.EnvPrefix+"_BASE_REWARDS", false),
Expand Down
Loading
Loading