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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## Unreleased — reconnect reputation keyed to Secure Enclave identity

- Restore a reconnecting provider's reputation and account linkage from a live store lookup keyed to the attested Secure Enclave public key, excluding the registering session's own row, so a restart, lid-close, or reconnect no longer resets standing to the 0.60 cold-start default. Device metadata comes from the newest row and reputation from the newest row that earned it, with a deterministic `last_seen`/`id` tie-break shared by the memory and PostgreSQL stores. Hardware trust is still re-earned live on every connection.

## Unreleased — provider console entry

- Open the provider workspace directly from the console home page, removing the Consumer/Provider selection page. Keep chat and API access in workspace navigation.
Expand Down
55 changes: 31 additions & 24 deletions coordinator/api/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -3167,35 +3167,42 @@ func (s *Server) verifyProviderAttestation(providerID string, provider *registry
"trust_level", registry.TrustSelfSigned,
)

// Restore persisted state: if this provider was previously known (by serial
// number or SE key), restore trust level, reputation, and account linkage.
// Fresh attestation verification still runs (above), but stored reputation
// is preserved so routing quality is maintained across coordinator restarts.
if s.storedProviders != nil {
var storedRec *store.ProviderRecord
if result.SerialNumber != "" {
storedRec = s.storedProviders[result.SerialNumber]
}
if storedRec == nil && result.PublicKey != "" {
storedRec = s.storedProviders["sekey:"+result.PublicKey]
}
if storedRec != nil {
// Restore persisted state: if this provider was previously known, restore
// trust level, reputation, and account linkage. State is keyed to the
// attested Secure Enclave public key ALONE (never the serial number, which is
// shareable across a re-image / key rotation, and never the per-connection
// session id). Fresh attestation verification still runs (above); trust above
// self_signed is re-earned live and is capped away in RestoreProviderState.
//
// The lookup is a LIVE store read against the durable store (Postgres in dev
// and prod), keyed to the SE key. State a machine earns AFTER coordinator
// startup — the 123/123 and 52/52 clean records in the reset report — lands in
// the store on the earning session's row, so only a live read recovers it; a
// one-time startup snapshot never would. The registering session (providerID)
// is excluded so its own just-persisted row cannot shadow the prior history.
if s.store != nil && result.PublicKey != "" {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
storedRec, err := s.store.GetProviderBySEKey(ctx, result.PublicKey, providerID)
cancel()
if err != nil {
s.logger.Warn("failed to look up persisted provider state by SE key",
"provider_id", providerID, "error", err)
} else if storedRec != nil {
s.registry.RestoreProviderState(provider, storedRec)
s.logger.Info("restored persisted provider state",
"provider_id", providerID,
"stored_id", storedRec.ID,
"stored_serial", storedRec.SerialNumber,
"stored_trust", storedRec.TrustLevel,
)
}
}

// Stage the durable Apple MDA cert chain from a LIVE store read. storedProviders
// above is a one-time startup snapshot — empty for the coordinator's whole life
// under the in-memory store used in prod — so it cannot surface a chain earned
// during this coordinator's lifetime. The store record survives provider
// disconnect, so a serial lookup recovers a chain a previous connection earned,
// letting attachCachedMDAProof reuse it (re-verified + SE-key-bound) instead of
// forcing a fresh, Apple-rate-limited DevicePropertiesAttestation round-trip.
// Stage the durable Apple MDA cert chain from a LIVE store read. The store
// record survives provider disconnect, so a serial lookup recovers a chain a
// previous connection earned during this coordinator's lifetime, letting
// attachCachedMDAProof reuse it (re-verified + SE-key-bound) instead of forcing
// a fresh, Apple-rate-limited DevicePropertiesAttestation round-trip.
s.stageDurableMDAChain(provider, result.SerialNumber)

// Deduplicate: if another provider connection exists from the same physical
Expand Down Expand Up @@ -3438,10 +3445,10 @@ func (s *Server) ApplyLateSecurityInfo(

// stageDurableMDAChain recovers a previously-earned Apple MDA cert chain from the
// store (by serial) and stages it on the provider as a reuse candidate for this
// reconnect. The store record survives provider disconnect, so this works under
// the in-memory store used in prod — where the startup storedProviders snapshot is
// empty — as well as a durable store. Best-effort: a missing record / chain or a
// read error simply stages nothing, and a fresh attestation is requested.
// reconnect. The store record survives provider disconnect, so a chain earned by
// an earlier connection is recovered by this live read. Best-effort: a missing
// record / chain or a read error simply stages nothing, and a fresh attestation
// is requested.
func (s *Server) stageDurableMDAChain(provider *registry.Provider, serial string) {
if s.store == nil || serial == "" {
return
Expand Down
75 changes: 75 additions & 0 deletions coordinator/api/provider_reputation_metadata_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package api

import (
"context"
"io"
"log/slog"
"testing"
"time"

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

// TestProviderReconnectRestoresMetadataAndReputationIndependently is the
// regression for the review finding that a reputation-bearing OLD row was
// selected for ALL restored state, discarding a newer session's fresh device
// metadata. Device metadata (account linkage) must come from the newest row;
// reputation must come from the newest row that actually earned it. A reconnect
// therefore keeps its fresh account AND recovers the standing under its SE key.
func TestProviderReconnectRestoresMetadataAndReputationIndependently(t *testing.T) {
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
st := store.NewMemory(store.Config{})
publicKey := testPublicKeyB64()
blob := createTestAttestationJSONWithSerial(t, "meta-device", publicKey)
identity, err := attestation.VerifyJSON(blob)
if err != nil || !identity.Valid {
t.Fatalf("invalid test attestation: %v, %+v", err, identity)
}
ctx := context.Background()

// Older session earned standing under the account it was linked to then.
if err := st.UpsertProvider(ctx, store.ProviderRecord{
ID: "old-session", SerialNumber: "meta-device", SEPublicKey: identity.PublicKey,
AccountID: "old-account", TrustLevel: "hardware", Attested: true,
LastSeen: time.Now().Add(-2 * time.Hour),
}); err != nil {
t.Fatal(err)
}
if err := st.UpsertReputation(ctx, "old-session", store.ReputationRecord{
TotalJobs: 60, SuccessfulJobs: 58, FailedJobs: 2,
}); err != nil {
t.Fatal(err)
}
// Newer session re-linked the machine to a fresh account but has not yet
// flushed a reputation row (bare metadata row).
if err := st.UpsertProvider(ctx, store.ProviderRecord{
ID: "new-session", SerialNumber: "meta-device", SEPublicKey: identity.PublicKey,
AccountID: "new-account", TrustLevel: "hardware", Attested: true,
LastSeen: time.Now().Add(-30 * time.Minute),
}); err != nil {
t.Fatal(err)
}

reg := registry.New(logger)
srv := NewServer(reg, st, ServerConfig{}, logger)
t.Cleanup(srv.Close)
p := registerReconnectSession(t, reg, srv, "reconnect", publicKey, blob)

p.Mu().Lock()
defer p.Mu().Unlock()
// Reputation is recovered from the earned (older) row...
if p.Reputation.TotalJobs != 60 || p.Reputation.SuccessfulJobs != 58 || p.Reputation.FailedJobs != 2 {
t.Fatalf("reputation should come from the earned row, got %+v", p.Reputation)
}
// ...while account linkage reflects the NEWEST device metadata, not the old
// reputation-bearing row.
if p.AccountID != "new-account" {
t.Fatalf("account linkage should track newest metadata row, got %q", p.AccountID)
}
// Hardware trust is still re-earned live.
if p.TrustLevel != registry.TrustSelfSigned || p.MDAVerified {
t.Fatalf("reconnect must re-earn hardware trust: trust=%s mda=%v", p.TrustLevel, p.MDAVerified)
}
}
135 changes: 135 additions & 0 deletions coordinator/api/provider_reputation_reconnect_edge_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
package api

import (
"context"
"io"
"log/slog"
"testing"
"time"

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

// registerReconnectSession drives one registration + attestation verification
// against an already-populated store, mirroring the reconnect hot path without a
// live WebSocket. It returns the freshly registered provider.
func registerReconnectSession(t *testing.T, reg *registry.Registry, srv *Server, sessionID, publicKey string, blob []byte) *registry.Provider {
t.Helper()
msg := &protocol.RegisterMessage{Type: protocol.TypeRegister, PublicKey: publicKey,
Attestation: blob, Version: minProviderVersionForReconnectAttestation}
p := reg.Register(sessionID, nil, msg)
srv.verifyProviderAttestation(sessionID, p, msg)
return p
}

// TestProviderReconnectWithMissingReputationRow covers a provider whose prior
// record is present and SE-key-matched but has NO persisted reputation row (the
// row was pruned, or the machine never accumulated one). Restoration must not
// invent counters or fail — it recovers account linkage from the matched record
// and leaves reputation at the neutral cold-start default. Trust is still
// re-earned live.
func TestProviderReconnectWithMissingReputationRow(t *testing.T) {
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
st := store.NewMemory(store.Config{})
publicKey := testPublicKeyB64()
blob := createTestAttestationJSONWithSerial(t, "missing-rep-device", publicKey)
identity, err := attestation.VerifyJSON(blob)
if err != nil || !identity.Valid {
t.Fatalf("invalid test attestation: %v, %+v", err, identity)
}
ctx := context.Background()
// Prior session known by the attested SE key, with account linkage but no
// reputation row.
if err := st.UpsertProvider(ctx, store.ProviderRecord{
ID: "prior-session", SerialNumber: "missing-rep-device",
SEPublicKey: identity.PublicKey, AccountID: "owner-account",
TrustLevel: "hardware", Attested: true, LastSeen: time.Now(),
}); err != nil {
t.Fatal(err)
}

reg := registry.New(logger)
srv := NewServer(reg, st, ServerConfig{}, logger)
t.Cleanup(srv.Close)
p := registerReconnectSession(t, reg, srv, "new-session", publicKey, blob)

p.Mu().Lock()
defer p.Mu().Unlock()
if p.Reputation.TotalJobs != 0 || p.Reputation.SuccessfulJobs != 0 || p.Reputation.ChallengesPassed != 0 {
t.Fatalf("missing reputation row should leave neutral defaults, got %+v", p.Reputation)
}
if p.AccountID != "owner-account" {
t.Fatalf("account linkage not restored from SE-key match: %q", p.AccountID)
}
if p.TrustLevel != registry.TrustSelfSigned || p.MDAVerified {
t.Fatalf("reconnect must re-earn hardware trust: trust=%s mda=%v", p.TrustLevel, p.MDAVerified)
}
}

// TestProviderReconnectRepeatedRestoresLatestBySEKey covers a laptop that
// reconnects several times: each reconnect must recover the most recent standing
// bound to the attested SE key, and must ignore the currently registering
// session's own row so a just-persisted empty row cannot shadow the earned
// history.
func TestProviderReconnectRepeatedRestoresLatestBySEKey(t *testing.T) {
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
st := store.NewMemory(store.Config{})
publicKey := testPublicKeyB64()
blob := createTestAttestationJSONWithSerial(t, "repeat-device", publicKey)
identity, err := attestation.VerifyJSON(blob)
if err != nil || !identity.Valid {
t.Fatalf("invalid test attestation: %v, %+v", err, identity)
}
ctx := context.Background()

seed := func(id string, seenAgo time.Duration, jobs int) {
if err := st.UpsertProvider(ctx, store.ProviderRecord{
ID: id, SerialNumber: "repeat-device", SEPublicKey: identity.PublicKey,
TrustLevel: "hardware", Attested: true, LastSeen: time.Now().Add(-seenAgo),
}); err != nil {
t.Fatal(err)
}
if err := st.UpsertReputation(ctx, id, store.ReputationRecord{
TotalJobs: jobs, SuccessfulJobs: jobs,
}); err != nil {
t.Fatal(err)
}
}

// Two prior connections; the newer (session-2) carries the higher standing.
seed("session-1", 2*time.Hour, 10)
seed("session-2", 1*time.Hour, 40)

reg := registry.New(logger)
srv := NewServer(reg, st, ServerConfig{}, logger)
t.Cleanup(srv.Close)

// First reconnect: restores the latest-by-last_seen prior standing (40), not
// the stale session-1 (10).
p := registerReconnectSession(t, reg, srv, "reconnect-a", publicKey, blob)
p.Mu().Lock()
got := p.Reputation.TotalJobs
p.Mu().Unlock()
if got != 40 {
t.Fatalf("first reconnect should restore latest standing 40, got %d", got)
}

// A newer prior session appears (the machine served more), plus a decoy row
// under the very id the next registration will use — carrying an absurd
// counter. The registering session must be excluded from its own lookup, so
// the decoy must never win.
seed("session-3", 30*time.Minute, 75)
seed("reconnect-b", 0, 999)

// Second reconnect: restores session-3 (75), excluding reconnect-b's own row.
p2 := registerReconnectSession(t, reg, srv, "reconnect-b", publicKey, blob)
p2.Mu().Lock()
got2 := p2.Reputation.TotalJobs
p2.Mu().Unlock()
if got2 != 75 {
t.Fatalf("second reconnect should restore latest prior standing 75 (excluding own row), got %d", got2)
}
}
Loading
Loading