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
29 changes: 23 additions & 6 deletions coordinator/api/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -484,10 +484,10 @@ func (s *Server) challengeLoop(ctx context.Context, conn *websocket.Conn, provid
case <-ctx.Done():
return
case <-ticker.C:
provider.Mu().Lock()
untrusted := provider.Status == registry.StatusUntrusted
provider.Mu().Unlock()
if untrusted {
// Stop only for a hard (non-recoverable) untrust. A transiently
// untrusted provider (missed-challenge timeouts) keeps being
// challenged so a later passing challenge can restore it.
if provider.ChallengeShouldStop() {
return
}
s.sendChallenge(ctx, conn, providerID, provider, tracker)
Expand Down Expand Up @@ -912,7 +912,17 @@ func (s *Server) verifyChallengeResponse(providerID string, provider *registry.P
provider.Mu().Unlock()

// Challenge passed.
s.registry.RecordChallengeSuccess(providerID)
recovered := s.registry.RecordChallengeSuccess(providerID)
if recovered {
// The provider was transiently untrusted and is now back online. It was
// last told "untrusted" (handleChallengeFailure) and scheduled a 10-min
// diagnostic auto-report; push a fresh "online" trust_status so it clears
// that local state and cancels the report.
provider.Mu().Lock()
trustLevel := provider.TrustLevel
provider.Mu().Unlock()
s.sendTrustStatus(provider, trustLevel, "online", "recovered after transient deroute")
}
s.ddIncr("attestation.challenges", []string{"outcome:passed"})
s.logger.Info("attestation challenge verified",
"provider_id", providerID,
Expand Down Expand Up @@ -964,7 +974,14 @@ func (s *Server) handleChallengeFailure(providerID string, reason string) {
severity := protocol.SeverityWarn
if failures >= registry.MaxFailedChallenges {
severity = protocol.SeverityError
s.registry.MarkUntrusted(providerID)
if transient {
// Missed-challenge timeouts (sleep / network blip) are recoverable:
// keep challenging and let a later passing challenge restore the
// provider without requiring a reconnect.
s.registry.MarkUntrustedTransient(providerID)
} else {
s.registry.MarkUntrusted(providerID)
}
if p := s.registry.GetProvider(providerID); p != nil {
s.sendTrustStatus(p, p.TrustLevel, string(registry.StatusUntrusted), reason)
}
Expand Down
57 changes: 57 additions & 0 deletions coordinator/api/provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2289,6 +2289,63 @@ func TestHandleChunkRejectsMixedPlaintextAndEncryptedTextChunk(t *testing.T) {
}
}

// Issue #239: hitting the failure threshold via missed-challenge timeouts marks
// the provider untrusted but *recoverable* (the challenge loop keeps probing it).
func TestHandleChallengeFailureThresholdTransientIsRecoverable(t *testing.T) {
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
st := store.NewMemory(store.Config{AdminKey: "test-key"})
reg := registry.New(logger)
srv := NewServer(reg, st, ServerConfig{}, logger)

p := reg.Register("p1", nil, &protocol.RegisterMessage{
Type: protocol.TypeRegister,
Hardware: protocol.Hardware{ChipName: "Apple M3 Max", MemoryGB: 64},
Models: []protocol.ModelInfo{{ID: "test-model", ModelType: "chat", Quantization: "4bit"}},
Backend: "mlx-swift",
})

for range registry.MaxFailedChallenges {
srv.handleChallengeFailure("p1", "timeout")
}

if p.Status != registry.StatusUntrusted {
t.Fatalf("status = %q, want %q after %d timeouts", p.Status, registry.StatusUntrusted, registry.MaxFailedChallenges)
}
if p.ChallengeShouldStop() {
t.Error("ChallengeShouldStop = true, want false (timeout-threshold deroute must be recoverable)")
}
if reg.OnlineCount() != 0 {
t.Errorf("OnlineCount = %d, want 0", reg.OnlineCount())
}
}

// Issue #239: a non-transient reason at the threshold is a hard deroute — the
// challenge loop stops and it cannot self-recover.
func TestHandleChallengeFailureThresholdSecurityIsHard(t *testing.T) {
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
st := store.NewMemory(store.Config{AdminKey: "test-key"})
reg := registry.New(logger)
srv := NewServer(reg, st, ServerConfig{}, logger)

p := reg.Register("p1", nil, &protocol.RegisterMessage{
Type: protocol.TypeRegister,
Hardware: protocol.Hardware{ChipName: "Apple M3 Max", MemoryGB: 64},
Models: []protocol.ModelInfo{{ID: "test-model", ModelType: "chat", Quantization: "4bit"}},
Backend: "mlx-swift",
})

for range registry.MaxFailedChallenges {
srv.handleChallengeFailure("p1", "nonce mismatch")
}

if p.Status != registry.StatusUntrusted {
t.Fatalf("status = %q, want %q", p.Status, registry.StatusUntrusted)
}
if !p.ChallengeShouldStop() {
t.Error("ChallengeShouldStop = false, want true (security-threshold deroute must be hard)")
}
}

// Verification: the coordinator's SSE output for a private text request contains
// only the decrypted content — no raw ciphertext, no session keys, no encrypted
// payloads leak into the consumer-visible HTTP response.
Expand Down
132 changes: 124 additions & 8 deletions coordinator/registry/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,13 @@ type Provider struct {
LastChallengeVerified time.Time // last successful challenge verification
FailedChallenges int // consecutive failed challenges

// untrustedRecoverable marks an untrust as a *transient* missed-challenge
// deroute (timeout / no-response) that may self-recover on the next passing
// challenge. It is false for every hard/security deroute. In-memory only —
// never persisted, because recoverability is meaningless without a live
// WebSocket and a running challenge loop.
untrustedRecoverable bool

mu sync.Mutex
pendingReqs map[string]*PendingRequest
}
Expand Down Expand Up @@ -328,6 +335,16 @@ func (p *Provider) Mu() *sync.Mutex {
return &p.mu
}

// ChallengeShouldStop reports whether the attestation challenge loop should
// stop for this provider. It stops only for a *hard* (non-recoverable) untrust;
// a transiently-untrusted provider keeps being challenged so a later passing
// challenge can restore it via RecordChallengeSuccess. Thread-safe.
func (p *Provider) ChallengeShouldStop() bool {
p.mu.Lock()
defer p.mu.Unlock()
return p.Status == StatusUntrusted && !p.untrustedRecoverable
}

// SetAttestationResult stores the parsed attestation result (thread-safe).
func (p *Provider) SetAttestationResult(result *attestation.VerificationResult) {
p.mu.Lock()
Expand Down Expand Up @@ -1661,10 +1678,41 @@ func (r *Registry) GetProvider(id string) *Provider {
return r.providers[id]
}

// MarkUntrusted sets a provider's status to untrusted, preventing it from
// receiving new jobs. This is called when a provider fails too many
// challenge-response verifications.
// MarkUntrusted sets a provider's status to untrusted for a hard/security
// reason (bad encrypted chunk, MDM/MDA failure, SIP disabled, binary or model
// hash mismatch, serial impersonation, attestation failure). The deroute is
// non-recoverable: the provider stays untrusted until it reconnects and
// re-registers. This is the default for every direct deroute call site.
func (r *Registry) MarkUntrusted(providerID string) {
r.markUntrusted(providerID, false)
}

// MarkUntrustedTransient sets a provider's status to untrusted for a *transient*
// reason — MaxFailedChallenges consecutive missed-challenge timeouts (screen
// sleep, network blip, momentary Secure Enclave inaccessibility). Unlike
// MarkUntrusted, the provider remains eligible to self-recover: the challenge
// loop keeps challenging it (see ChallengeShouldStop), and a subsequent fully
// passing challenge (RecordChallengeSuccess) restores it to online.
//
// A passing challenge re-verifies signature, SIP, secure boot, binary hash,
// model hash and runtime before RecordChallengeSuccess is reached, so using it
// as the recovery trigger is safe.
func (r *Registry) MarkUntrustedTransient(providerID string) {
r.markUntrusted(providerID, true)
}

// markUntrusted is the shared implementation. recoverable=true marks the untrust
// as transiently recoverable; recoverable=false is a hard deroute.
//
// Transition rules:
// - not untrusted -> untrusted: decrement online/model counts, set status and
// the recoverable flag.
// - already untrusted + hard (recoverable=false): clear the flag. A hard
// reason always overrides/downgrades a previously-recoverable untrust.
// - already untrusted + transient (recoverable=true): leave the flag as-is, so
// a transient timeout can never *upgrade* a hard deroute to recoverable
// (matters for an in-flight challenge timeout that races a hard deroute).
func (r *Registry) markUntrusted(providerID string, recoverable bool) {
r.mu.Lock()
p, ok := r.providers[providerID]
if !ok {
Expand All @@ -1678,14 +1726,19 @@ func (r *Registry) MarkUntrusted(providerID string) {
for _, m := range p.Models {
r.modelProviderDec(m.ID)
}
p.Status = StatusUntrusted
p.untrustedRecoverable = recoverable
} else if !recoverable {
p.untrustedRecoverable = false
}
p.Status = StatusUntrusted
failed := p.FailedChallenges // read under p.mu (the old code read this unlocked)
p.mu.Unlock()
r.mu.Unlock()

r.logger.Warn("provider marked as untrusted",
"provider_id", providerID,
"failed_challenges", p.FailedChallenges,
"failed_challenges", failed,
"recoverable", recoverable,
)
}

Expand All @@ -1706,14 +1759,25 @@ func (r *Registry) SetTrustLevel(providerID string, level TrustLevel) {
}

// RecordChallengeSuccess records a successful challenge-response verification.
func (r *Registry) RecordChallengeSuccess(providerID string) {
// A fully passing challenge re-verifies signature, SIP, secure boot, binary
// hash, model hash and runtime (see verifyChallengeResponse) before this is
// called, so it doubles as the recovery trigger for a *transiently* untrusted
// provider.
//
// Returns true iff this call recovered a transiently-untrusted provider back to
// online. The caller (verifyChallengeResponse) uses that to push a fresh
// "online" trust_status so the provider clears its local untrusted state and
// cancels the pending diagnostic auto-report it scheduled at deroute time.
func (r *Registry) RecordChallengeSuccess(providerID string) bool {
r.mu.RLock()
p, ok := r.providers[providerID]
r.mu.RUnlock()
if !ok {
return
return false
}

recovered := r.recoverIfTransientlyUntrusted(providerID, p)

p.mu.Lock()
p.LastChallengeVerified = time.Now()
p.FailedChallenges = 0
Expand All @@ -1727,8 +1791,60 @@ func (r *Registry) RecordChallengeSuccess(providerID string) {
r.persistProviderNow(p)
r.persistReputation(p)

// A newly verified provider may unlock queued requests for any model it serves.
if recovered {
r.logger.Info("provider recovered from transient deroute", "provider_id", providerID)
Comment on lines +1794 to +1795

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 Send online trust_status after transient recovery

When recovered is true, the registry has just moved the provider back to online, but the coordinator never tells the provider that its prior trust_status=untrusted has been cleared. The Swift provider only cancels the pending auto-report when it receives a non-untrusted trust status (provider-swift/Sources/ProviderCore/ProviderLoop.swift:1026-1030), so a provider that transiently times out and then recovers will still upload diagnostic logs ten minutes later and keep stale local trust state. Send an online trust_status on this recovery path.

Useful? React with 👍 / 👎.

}

// A newly verified (or newly recovered) provider may unlock queued requests
// for any model it serves.
r.drainQueuedRequestsForModels(providerModelIDs(p))

return recovered
}

// recoverIfTransientlyUntrusted promotes a transiently-untrusted provider back
// to online, mirroring markUntrusted's bookkeeping in reverse. Returns true iff
// a transition occurred. It acquires r.mu (write) then p.mu — the same order as
// markUntrusted/Register/Disconnect — so online/model counts stay consistent and
// the path is deadlock-free.
func (r *Registry) recoverIfTransientlyUntrusted(providerID string, p *Provider) bool {
// Cheap pre-check under p.mu only, so the common (non-recovery) success path
// never contends on the registry write lock.
p.mu.Lock()
eligible := p.Status == StatusUntrusted && p.untrustedRecoverable
p.mu.Unlock()
if !eligible {
return false
}

r.mu.Lock()
// Re-verify membership: RecordChallengeSuccess looked p up under RLock and
// released it, so Disconnect may have removed (or replaced) it since. A
// transiently-untrusted provider was already decremented out of the counts,
// and Disconnect does not decrement an untrusted provider, so incrementing a
// stale/removed pointer here would permanently corrupt onlineCount and
// modelProviders. Only recover the provider still registered under this ID.
if cur, ok := r.providers[providerID]; !ok || cur != p {
r.mu.Unlock()
return false
}
p.mu.Lock()
// Re-check under the write lock: a hard deroute may have intervened and
// cleared the recoverable flag between the pre-check and here.
if p.Status != StatusUntrusted || !p.untrustedRecoverable {
p.mu.Unlock()
r.mu.Unlock()
return false
}
r.onlineCount.Add(1)
for _, m := range p.Models {
r.modelProviderInc(m.ID)
}
p.Status = StatusOnline
p.untrustedRecoverable = false
p.mu.Unlock()
r.mu.Unlock()
return true
}

// RecordChallengeFailure records a failed challenge-response. Returns the
Expand Down
Loading
Loading