From ef962dd4a012502ce40979e7497c3507d5d10376 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:17:43 -0600 Subject: [PATCH 01/17] perf(consensus): index the raft log by position and reload it from storage The log kept entries in a slice plus a map cache and found entries by scanning. Get misses and GetEntriesAfter walked the whole log (about 90 us per heartbeat at 100k entries) and cache eviction scanned the map on every append once it was full. Append also accepted any index, so a follower that received the same entries twice stored them twice and LastIndex could move backwards. The log is now a slice addressed by index, with entries[i].Index equal to snapshotIndex+1+i. Get, Term and range reads are O(1) slice operations and the separate cache is gone, since every entry after the snapshot is already in memory. Append and AppendBatch require the next index and write to storage before the entry becomes visible, so a failed write leaves nothing behind that the node could acknowledge. TruncateAfter deletes the removed entries from storage as well, and Get no longer falls back to storage, which used to resurrect truncated entries. load() was a placeholder, so a restarted node came back with an empty log while storage still held its entries. It now reads the snapshot metadata and every contiguous entry after it. BadgerStorage and BoltDBStorage gain Batch and Close so they satisfy internal.Storage and can back a raft node. Benchmarks (Apple M-series, before -> after): heartbeat read, 100k entries 91422 ns -> 11 ns lagging follower read 48376 ns -> 333 ns append past cache size 5934 ns -> 611 ns --- extensions/consensus/raft/log.go | 448 +++++++++----------- extensions/consensus/raft/log_bench_test.go | 72 ++++ extensions/consensus/storage/badger.go | 14 + extensions/consensus/storage/boltdb.go | 14 + 4 files changed, 310 insertions(+), 238 deletions(-) create mode 100644 extensions/consensus/raft/log_bench_test.go diff --git a/extensions/consensus/raft/log.go b/extensions/consensus/raft/log.go index e8ee2fe6a..3bab26b9b 100644 --- a/extensions/consensus/raft/log.go +++ b/extensions/consensus/raft/log.go @@ -7,36 +7,49 @@ import ( "sync" "github.com/xraph/forge" + "github.com/xraph/forge/errors" "github.com/xraph/forge/extensions/consensus/internal" ) +// snapshotMetaKey holds the index and term of the latest snapshot. +const snapshotMetaKey = "snapshot_meta" + // Log represents the replicated log. +// +// Every entry after the last snapshot is held in memory in a slice addressed +// by index: entries[i].Index == snapshotIndex+1+i always holds. That makes Get, +// Term and range reads O(1) and lets AppendEntries compare, skip and truncate +// entries by index as section 5.3 of the Raft paper describes. +// +// Storage is the source of truth. Entries are written to storage before they +// become visible in memory, truncation deletes them from storage, and NewLog +// reloads them so a restarted node comes back with the log it acknowledged. type Log struct { entries []internal.LogEntry - cache map[uint64]internal.LogEntry storage internal.Storage logger forge.Logger - // Cache management - cacheSize int - mu sync.RWMutex + mu sync.RWMutex // Snapshot state snapshotIndex uint64 snapshotTerm uint64 } -// NewLog creates a new log. +// NewLog creates a log and loads any entries already held in storage. +// +// cacheSize is accepted for compatibility and ignored: the log keeps every +// entry after the last snapshot in memory, so a separate cache would only +// duplicate it. func NewLog(logger forge.Logger, storage internal.Storage, cacheSize int) (*Log, error) { + _ = cacheSize + l := &Log{ - entries: make([]internal.LogEntry, 0), - cache: make(map[uint64]internal.LogEntry), - storage: storage, - logger: logger, - cacheSize: cacheSize, + entries: make([]internal.LogEntry, 0), + storage: storage, + logger: logger, } - // Load existing log from storage if err := l.load(); err != nil { return nil, fmt.Errorf("failed to load log: %w", err) } @@ -44,23 +57,14 @@ func NewLog(logger forge.Logger, storage internal.Storage, cacheSize int) (*Log, return l, nil } -// Append appends a log entry. +// Append appends a single entry. Its index must be LastIndex()+1. The entry is +// persisted first and only added to memory when the write succeeded, so a +// failed write never leaves an entry the node could acknowledge and then lose. func (l *Log) Append(entry internal.LogEntry) error { - l.mu.Lock() - defer l.mu.Unlock() - - // Append to in-memory log - l.entries = append(l.entries, entry) - - // Add to cache - l.cache[entry.Index] = entry - l.evictCache() - - // Persist to storage - return l.persistEntry(entry) + return l.AppendBatch([]internal.LogEntry{entry}) } -// AppendBatch appends multiple log entries. +// AppendBatch appends entries that continue the log without gaps. func (l *Log) AppendBatch(entries []internal.LogEntry) error { if len(entries) == 0 { return nil @@ -69,18 +73,21 @@ func (l *Log) AppendBatch(entries []internal.LogEntry) error { l.mu.Lock() defer l.mu.Unlock() - // Append to in-memory log - l.entries = append(l.entries, entries...) + next := l.lastIndexLocked() + 1 + for i, entry := range entries { + if entry.Index != next+uint64(i) { + return fmt.Errorf("log append out of order: entry %d has index %d, expected %d", + i, entry.Index, next+uint64(i)) + } + } - // Add to cache - for _, entry := range entries { - l.cache[entry.Index] = entry + if err := l.persistBatch(entries); err != nil { + return fmt.Errorf("failed to persist log entries: %w", err) } - l.evictCache() + l.entries = append(l.entries, entries...) - // Persist to storage in batch - return l.persistBatch(entries) + return nil } // Get retrieves a log entry by index. @@ -88,30 +95,46 @@ func (l *Log) Get(index uint64) (internal.LogEntry, error) { l.mu.RLock() defer l.mu.RUnlock() - // Check if index is in snapshot if index <= l.snapshotIndex { return internal.LogEntry{}, fmt.Errorf("log entry %d is in snapshot", index) } - // Check cache first - if entry, ok := l.cache[index]; ok { - return entry, nil + pos, ok := l.posLocked(index) + if !ok { + return internal.LogEntry{}, fmt.Errorf("log entry %d not found (last index %d)", index, l.lastIndexLocked()) } - // Check in-memory entries - for _, entry := range l.entries { - if entry.Index == index { - l.cache[index] = entry + return l.entries[pos], nil +} - return entry, nil - } +// Term returns the term of the entry at index. The snapshot boundary reports +// the snapshot term and index 0 reports term 0. The second result is false +// when the log holds no entry at index. +func (l *Log) Term(index uint64) (uint64, bool) { + l.mu.RLock() + defer l.mu.RUnlock() + + return l.termLocked(index) +} + +func (l *Log) termLocked(index uint64) (uint64, bool) { + if index == 0 { + return 0, true } - // Load from storage - return l.loadEntry(index) + if index == l.snapshotIndex { + return l.snapshotTerm, true + } + + pos, ok := l.posLocked(index) + if !ok { + return 0, false + } + + return l.entries[pos].Term, true } -// GetRange retrieves a range of log entries. +// GetRange retrieves the entries in [start, end]. func (l *Log) GetRange(start, end uint64) ([]internal.LogEntry, error) { l.mu.RLock() defer l.mu.RUnlock() @@ -124,40 +147,15 @@ func (l *Log) GetRange(start, end uint64) ([]internal.LogEntry, error) { return nil, fmt.Errorf("start index %d is in snapshot", start) } - result := make([]internal.LogEntry, 0, end-start+1) - - for i := start; i <= end; i++ { - // Check cache first - if entry, ok := l.cache[i]; ok { - result = append(result, entry) - - continue - } - - // Check in-memory entries - found := false - - for _, entry := range l.entries { - if entry.Index == i { - result = append(result, entry) - l.cache[i] = entry - found = true - - break - } - } + if end > l.lastIndexLocked() { + return nil, fmt.Errorf("end index %d is past the last index %d", end, l.lastIndexLocked()) + } - if !found { - // Load from storage - entry, err := l.loadEntry(i) - if err != nil { - return nil, fmt.Errorf("failed to load entry %d: %w", i, err) - } + from, _ := l.posLocked(start) + to, _ := l.posLocked(end) - result = append(result, entry) - l.cache[i] = entry - } - } + result := make([]internal.LogEntry, to-from+1) + copy(result, l.entries[from:to+1]) return result, nil } @@ -167,11 +165,11 @@ func (l *Log) LastIndex() uint64 { l.mu.RLock() defer l.mu.RUnlock() - if len(l.entries) == 0 { - return l.snapshotIndex - } + return l.lastIndexLocked() +} - return l.entries[len(l.entries)-1].Index +func (l *Log) lastIndexLocked() uint64 { + return l.snapshotIndex + uint64(len(l.entries)) } // LastTerm returns the term of the last log entry. @@ -191,11 +189,23 @@ func (l *Log) FirstIndex() uint64 { l.mu.RLock() defer l.mu.RUnlock() - if len(l.entries) == 0 { - return l.snapshotIndex + 1 - } + return l.snapshotIndex + 1 +} + +// SnapshotIndex returns the last index covered by the snapshot. +func (l *Log) SnapshotIndex() uint64 { + l.mu.RLock() + defer l.mu.RUnlock() - return l.entries[0].Index + return l.snapshotIndex +} + +// SnapshotTerm returns the term of the last index covered by the snapshot. +func (l *Log) SnapshotTerm() uint64 { + l.mu.RLock() + defer l.mu.RUnlock() + + return l.snapshotTerm } // Count returns the number of log entries. @@ -206,41 +216,37 @@ func (l *Log) Count() int { return len(l.entries) } -// TruncateAfter truncates the log after the given index. +// TruncateAfter removes every entry with an index greater than index, from +// storage as well as memory, so a reload never brings a deleted entry back. func (l *Log) TruncateAfter(index uint64) error { l.mu.Lock() defer l.mu.Unlock() - if index <= l.snapshotIndex { + if index < l.snapshotIndex { return fmt.Errorf("cannot truncate before snapshot index %d", l.snapshotIndex) } - // Find the position to truncate - truncatePos := -1 - - for i, entry := range l.entries { - if entry.Index > index { - truncatePos = i - - break - } + last := l.lastIndexLocked() + if index >= last { + return nil } - if truncatePos == -1 { - return nil // Nothing to truncate + // Delete from the tail backwards so a backend that applies a batch + // partially still leaves a contiguous prefix behind. + ops := make([]internal.BatchOp, 0, last-index) + for i := last; i > index; i-- { + ops = append(ops, internal.BatchOp{Type: internal.BatchOpDelete, Key: logKey(i)}) } - // Truncate in-memory log - l.entries = l.entries[:truncatePos] - - // Clear cache for truncated entries - for i := index + 1; i <= l.snapshotIndex+uint64(len(l.entries))+1000; i++ { - delete(l.cache, i) + if err := l.storage.Batch(ops); err != nil { + return fmt.Errorf("failed to delete truncated log entries: %w", err) } + l.entries = l.entries[:index-l.snapshotIndex] + l.logger.Info("truncated log", forge.F("after_index", index), - forge.F("entries_removed", len(l.entries)-truncatePos), + forge.F("entries_removed", last-index), ) return nil @@ -255,31 +261,36 @@ func (l *Log) Compact(index uint64, term uint64) error { return nil // Already compacted } - // Find the position to compact - compactPos := -1 - - for i, entry := range l.entries { - if entry.Index == index { - compactPos = i - - break - } + pos, ok := l.posLocked(index) + if !ok { + return fmt.Errorf("log entry %d not found", index) } - if compactPos == -1 { - return fmt.Errorf("log entry %d not found", index) + if l.entries[pos].Term != term { + return fmt.Errorf("log entry %d has term %d, not snapshot term %d", index, l.entries[pos].Term, term) } - // Remove compacted entries - l.entries = l.entries[compactPos+1:] + oldSnapshot := l.snapshotIndex - // Update snapshot state + // Copy the tail so the compacted prefix can be garbage collected. + remaining := make([]internal.LogEntry, len(l.entries)-pos-1) + copy(remaining, l.entries[pos+1:]) + l.entries = remaining l.snapshotIndex = index l.snapshotTerm = term - // Clear cache for compacted entries - for i := uint64(0); i <= index; i++ { - delete(l.cache, i) + // The snapshot metadata is already durable, so stale log keys below it are + // only wasted space and a failed delete is not fatal. + ops := make([]internal.BatchOp, 0, index-oldSnapshot) + for i := oldSnapshot + 1; i <= index; i++ { + ops = append(ops, internal.BatchOp{Type: internal.BatchOpDelete, Key: logKey(i)}) + } + + if err := l.storage.Batch(ops); err != nil { + l.logger.Warn("failed to delete compacted log entries from storage", + forge.F("up_to_index", index), + forge.F("error", err), + ) } l.logger.Info("compacted log", @@ -291,24 +302,50 @@ func (l *Log) Compact(index uint64, term uint64) error { return nil } -// load loads the log from storage. +// load reads the snapshot metadata and every contiguous entry after it. func (l *Log) load() error { - // Load snapshot metadata - snapshotMeta, err := l.storage.Get([]byte("snapshot_meta")) - if err == nil && len(snapshotMeta) > 0 { + snapshotMeta, err := l.storage.Get([]byte(snapshotMetaKey)) + + switch { + case err == nil && len(snapshotMeta) > 0: var meta struct { Index uint64 `json:"index"` Term uint64 `json:"term"` } - if err := json.Unmarshal(snapshotMeta, &meta); err == nil { - l.snapshotIndex = meta.Index - l.snapshotTerm = meta.Term + + if err := json.Unmarshal(snapshotMeta, &meta); err != nil { + return fmt.Errorf("failed to decode snapshot metadata: %w", err) } + + l.snapshotIndex = meta.Index + l.snapshotTerm = meta.Term + case err != nil && !isNotFound(err): + return fmt.Errorf("failed to read snapshot metadata: %w", err) } - // Load log entries - // In a real implementation, we'd iterate through storage keys - // For now, this is a placeholder + // Entries are stored under decimal keys, which do not sort numerically, + // so they are read by index until the first gap. + for index := l.snapshotIndex + 1; ; index++ { + data, err := l.storage.Get(logKey(index)) + if err != nil { + if isNotFound(err) { + break + } + + return fmt.Errorf("failed to read log entry %d: %w", index, err) + } + + var entry internal.LogEntry + if err := json.Unmarshal(data, &entry); err != nil { + return fmt.Errorf("failed to decode log entry %d: %w", index, err) + } + + if entry.Index != index { + return fmt.Errorf("log entry stored under index %d claims index %d", index, entry.Index) + } + + l.entries = append(l.entries, entry) + } l.logger.Info("loaded log", forge.F("snapshot_index", l.snapshotIndex), @@ -319,121 +356,47 @@ func (l *Log) load() error { return nil } -// persistEntry persists a single log entry to storage. -func (l *Log) persistEntry(entry internal.LogEntry) error { - data, err := json.Marshal(entry) - if err != nil { - return fmt.Errorf("failed to marshal entry: %w", err) - } - - key := fmt.Appendf(nil, "log_%d", entry.Index) - - return l.storage.Set(key, data) -} - -// persistBatch persists multiple log entries to storage. +// persistBatch writes entries to storage in a single batch. func (l *Log) persistBatch(entries []internal.LogEntry) error { - if len(entries) == 0 { - return nil - } - - // Use batch write if supported - if batchStorage, ok := l.storage.(interface { - WriteBatch(ops []internal.BatchOp) error - }); ok { - ops := make([]internal.BatchOp, len(entries)) - for i, entry := range entries { - data, err := json.Marshal(entry) - if err != nil { - return fmt.Errorf("failed to marshal entry %d: %w", entry.Index, err) - } + ops := make([]internal.BatchOp, len(entries)) - ops[i] = internal.BatchOp{ - Type: internal.BatchOpSet, - Key: fmt.Appendf(nil, "log_%d", entry.Index), - Value: data, - } + for i, entry := range entries { + data, err := json.Marshal(entry) + if err != nil { + return fmt.Errorf("failed to marshal entry %d: %w", entry.Index, err) } - return batchStorage.WriteBatch(ops) - } - - // Fall back to individual writes - for _, entry := range entries { - if err := l.persistEntry(entry); err != nil { - return err + ops[i] = internal.BatchOp{ + Type: internal.BatchOpSet, + Key: logKey(entry.Index), + Value: data, } } - return nil -} - -// loadEntry loads a single log entry from storage. -func (l *Log) loadEntry(index uint64) (internal.LogEntry, error) { - key := fmt.Appendf(nil, "log_%d", index) - - data, err := l.storage.Get(key) - if err != nil { - return internal.LogEntry{}, fmt.Errorf("failed to load entry: %w", err) + if len(ops) == 1 { + return l.storage.Set(ops[0].Key, ops[0].Value) } - var entry internal.LogEntry - if err := json.Unmarshal(data, &entry); err != nil { - return internal.LogEntry{}, fmt.Errorf("failed to unmarshal entry: %w", err) - } - - return entry, nil + return l.storage.Batch(ops) } -// evictCache evicts old entries from the cache if it exceeds the size limit. -func (l *Log) evictCache() { - if len(l.cache) <= l.cacheSize { - return +// posLocked maps a log index to its slice position. +func (l *Log) posLocked(index uint64) (int, bool) { + if index <= l.snapshotIndex || index > l.lastIndexLocked() { + return 0, false } - // Find oldest entries to evict - // Simple strategy: keep the most recent entries - if len(l.entries) > 0 { - lastIndex := l.entries[len(l.entries)-1].Index - - // A non-positive cache size keeps nothing older than the newest entry. - var keep uint64 - if l.cacheSize > 0 { - keep = uint64(l.cacheSize) - } - - minIndex := lastIndex - if keep < lastIndex { - minIndex = lastIndex - keep - } - - for index := range l.cache { - if index < minIndex { - delete(l.cache, index) - } - } - } + return int(index - l.snapshotIndex - 1), true //nolint:gosec // G115: bounded by len(l.entries) } // MatchesTerm checks if the log entry at index has the given term. func (l *Log) MatchesTerm(index, term uint64) bool { - if index == 0 { - return true - } + t, ok := l.Term(index) - if index == l.snapshotIndex { - return term == l.snapshotTerm - } - - entry, err := l.Get(index) - if err != nil { - return false - } - - return entry.Term == term + return ok && t == term } -// GetEntriesAfter returns all entries after the given index. +// GetEntriesAfter returns up to maxEntries entries after the given index. func (l *Log) GetEntriesAfter(index uint64, maxEntries int) ([]internal.LogEntry, error) { l.mu.RLock() defer l.mu.RUnlock() @@ -442,17 +405,16 @@ func (l *Log) GetEntriesAfter(index uint64, maxEntries int) ([]internal.LogEntry return nil, fmt.Errorf("index %d is before snapshot index %d", index, l.snapshotIndex) } - result := make([]internal.LogEntry, 0, maxEntries) - - for _, entry := range l.entries { - if entry.Index > index { - result = append(result, entry) - if len(result) >= maxEntries { - break - } - } + if index >= l.lastIndexLocked() || maxEntries <= 0 { + return []internal.LogEntry{}, nil } + from := int(index - l.snapshotIndex) //nolint:gosec // G115: bounded by len(l.entries) + to := min(from+maxEntries, len(l.entries)) + + result := make([]internal.LogEntry, to-from) + copy(result, l.entries[from:to]) + return result, nil } @@ -464,7 +426,17 @@ func (l *Log) String() string { var buf bytes.Buffer fmt.Fprintf(&buf, "Log[snapshot=%d:%d, entries=%d, first=%d, last=%d]", l.snapshotIndex, l.snapshotTerm, len(l.entries), - l.FirstIndex(), l.LastIndex()) + l.snapshotIndex+1, l.lastIndexLocked()) return buf.String() } + +func logKey(index uint64) []byte { + return fmt.Appendf(nil, "log_%d", index) +} + +// isNotFound reports whether a storage error means the key does not exist. +// Every bundled storage backend reports a missing key as ErrNodeNotFound. +func isNotFound(err error) bool { + return errors.Is(err, internal.ErrNodeNotFound) +} diff --git a/extensions/consensus/raft/log_bench_test.go b/extensions/consensus/raft/log_bench_test.go new file mode 100644 index 000000000..b202184c2 --- /dev/null +++ b/extensions/consensus/raft/log_bench_test.go @@ -0,0 +1,72 @@ +package raft + +import ( + "strconv" + "testing" + + "github.com/xraph/forge" + "github.com/xraph/forge/extensions/consensus/internal" +) + +func benchLog(b *testing.B, size int) *Log { + b.Helper() + + l, err := NewLog(forge.NewNoopLogger(), newMemStorage(b), 1024) + if err != nil { + b.Fatal(err) + } + + for i := 1; i <= size; i++ { + if err := l.Append(internal.LogEntry{Index: uint64(i), Term: 1, Data: make([]byte, 64)}); err != nil { + b.Fatal(err) + } + } + + return l +} + +// A heartbeat to an up-to-date follower reads the previous entry and the +// (empty) tail after it. +func BenchmarkLogHeartbeatRead(b *testing.B) { + for _, size := range []int{1000, 10000, 100000} { + b.Run(strconv.Itoa(size), func(b *testing.B) { + l := benchLog(b, size) + + b.ResetTimer() + + for b.Loop() { + _, _ = l.Get(uint64(size)) + _, _ = l.GetEntriesAfter(uint64(size), 64) + } + }) + } +} + +// A lagging follower needs entries far behind the newest ones. +func BenchmarkLogLaggingFollowerRead(b *testing.B) { + l := benchLog(b, 100000) + + b.ResetTimer() + + i := 0 + for b.Loop() { + prev := uint64(50000 + i%1000) + _, _ = l.Get(prev) + _, _ = l.GetEntriesAfter(prev, 64) + i++ + } +} + +// Appending once the log is larger than the configured cache size. +func BenchmarkLogAppend(b *testing.B) { + l := benchLog(b, 0) + + b.ReportAllocs() + b.ResetTimer() + + i := uint64(0) + for b.Loop() { + i++ + _ = l.Append(internal.LogEntry{Index: i, Term: 1, Data: make([]byte, 64)}) + } +} diff --git a/extensions/consensus/storage/badger.go b/extensions/consensus/storage/badger.go index 72a03df06..4b52f6c01 100644 --- a/extensions/consensus/storage/badger.go +++ b/extensions/consensus/storage/badger.go @@ -302,3 +302,17 @@ func (bs *BadgerStorage) Size() (int64, error) { func (bs *BadgerStorage) RunGC(discardRatio float64) error { return bs.db.RunValueLogGC(discardRatio) } + +// Batch applies ops atomically. It lets BadgerStorage satisfy internal.Storage, which +// the Raft log needs for truncation and batched appends. +func (bs *BadgerStorage) Batch(ops []internal.BatchOp) error { + return bs.WriteBatch(ops) +} + +// Close closes the database. It is Stop without a context, as internal.Storage +// requires. +func (bs *BadgerStorage) Close() error { + return bs.Stop(context.Background()) +} + +var _ internal.Storage = (*BadgerStorage)(nil) diff --git a/extensions/consensus/storage/boltdb.go b/extensions/consensus/storage/boltdb.go index 122c22955..4df1607d8 100644 --- a/extensions/consensus/storage/boltdb.go +++ b/extensions/consensus/storage/boltdb.go @@ -331,3 +331,17 @@ func hasPrefix(s, prefix []byte) bool { return true } + +// Batch applies ops atomically. It lets BoltDBStorage satisfy internal.Storage, which +// the Raft log needs for truncation and batched appends. +func (bs *BoltDBStorage) Batch(ops []internal.BatchOp) error { + return bs.WriteBatch(ops) +} + +// Close closes the database. It is Stop without a context, as internal.Storage +// requires. +func (bs *BoltDBStorage) Close() error { + return bs.Stop(context.Background()) +} + +var _ internal.Storage = (*BoltDBStorage)(nil) From 61ddad6ed765d3c424cb4bbd847eaf9a19735091 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:17:44 -0600 Subject: [PATCH 02/17] fix(consensus): skip duplicate entries on AppendEntries and match responses by request id Follower side, following section 5.3 of the Raft paper: - Entries the log already holds with the same term are skipped, the first conflicting entry truncates the log there, and only the rest is appended. A retransmitted or delayed AppendEntries no longer duplicates entries or shrinks the log, which had let a node vote for a candidate missing committed entries. - commitIndex advances to min(leaderCommit, prevLogIndex+len(entries)) instead of the local last index, which could commit a stale tail. - Success is only reported once the entries are persisted, and a term or vote that cannot be persisted rejects the request or denies the vote. - The RPC entry point and the message loop share one implementation, so followers now also apply committed entries on the message path. - NewNode fails if term, vote or snapshot cannot be read instead of starting from zero, and restores the latest snapshot into the state machine. Leader side: - Every request gets a fresh id that the peer echoes. Request ids used to be fixed per peer, so a late response could be matched to a newer request and overstate matchIndex, and a vote granted in an old term could be counted in a new election. - Responses are handled once, by the goroutine that sent the request. The message loop no longer runs the handler a second time with a dummy request, which double decremented nextIndex. - matchIndex only moves forward and is bounded by what the request carried; nextIndex only backs off for the request it currently describes and uses the follower's last index as a hint. - Committed entries are applied by a single applier goroutine, so the leader no longer applies an entry twice, and single node clusters commit. - The candidate no longer waits for every vote RPC to finish before taking leadership, so one unreachable peer cannot stall an election. Also removed a test hook that granted every vote to a candidate named node-1 regardless of its log, and RPCHandler.Send* now wait for the real response instead of returning an empty one. InstallSnapshot is still not implemented; it now logs an error instead of acknowledging the snapshot as installed, and the leader logs an error when a follower needs entries that only exist in a snapshot. --- extensions/consensus/internal/types.go | 7 + extensions/consensus/raft/log_safety_test.go | 304 ++++++++++++ extensions/consensus/raft/node.go | 391 ++++++++++----- extensions/consensus/raft/replication.go | 477 +++++++------------ extensions/consensus/raft/request_id_test.go | 233 +++++++++ extensions/consensus/raft/rpc.go | 60 +-- extensions/consensus/raft/state.go | 280 +++++------ extensions/consensus/raft/workers.go | 208 ++++---- 8 files changed, 1210 insertions(+), 750 deletions(-) create mode 100644 extensions/consensus/raft/log_safety_test.go create mode 100644 extensions/consensus/raft/request_id_test.go diff --git a/extensions/consensus/internal/types.go b/extensions/consensus/internal/types.go index 8e3e2f1f3..279c5d0f1 100644 --- a/extensions/consensus/internal/types.go +++ b/extensions/consensus/internal/types.go @@ -287,6 +287,10 @@ type AppendEntriesResponse struct { Success bool `json:"success"` MatchIndex uint64 `json:"match_index"` NodeID string `json:"node_id"` + // LastLogIndex is the follower's last log index. On a rejected request the + // leader uses it to skip nextIndex back in one step instead of one entry + // per round trip. + LastLogIndex uint64 `json:"last_log_index,omitempty"` } // RequestVoteRequest represents a RequestVote RPC request. @@ -398,6 +402,9 @@ type Message struct { To string `json:"to"` Payload any `json:"payload"` Timestamp int64 `json:"timestamp"` + // RequestID correlates a response with the request it answers. The + // sender picks a fresh value per request and the responder echoes it. + RequestID uint64 `json:"request_id,omitempty"` } // MessageType represents the type of message. diff --git a/extensions/consensus/raft/log_safety_test.go b/extensions/consensus/raft/log_safety_test.go new file mode 100644 index 000000000..7f46f41f9 --- /dev/null +++ b/extensions/consensus/raft/log_safety_test.go @@ -0,0 +1,304 @@ +package raft + +import ( + "context" + "errors" + "sync/atomic" + "testing" + + "github.com/xraph/forge" + "github.com/xraph/forge/extensions/consensus/internal" + "github.com/xraph/forge/extensions/consensus/statemachine" + "github.com/xraph/forge/extensions/consensus/storage" + "github.com/xraph/forge/extensions/consensus/transport" +) + +func newMemStorage(t testing.TB) *storage.MemoryStorage { + t.Helper() + + st := storage.NewMemoryStorage(storage.MemoryStorageConfig{}, forge.NewNoopLogger()) + if err := st.Start(context.Background()); err != nil { + t.Fatal(err) + } + + return st +} + +func newTestNode(t *testing.T, id string, st internal.Storage) *Node { + t.Helper() + + lg := forge.NewNoopLogger() + tr := transport.NewLocalTransport(transport.LocalTransportConfig{NodeID: id}, lg) + sm := statemachine.NewMemoryStateMachine(statemachine.MemoryStateMachineConfig{}, lg) + + n, err := NewNode(Config{NodeID: id}, lg, sm, tr, st) + if err != nil { + t.Fatal(err) + } + + return n +} + +func ents(term, from, to uint64) []internal.LogEntry { + var out []internal.LogEntry + for i := from; i <= to; i++ { + out = append(out, internal.LogEntry{Index: i, Term: term, Data: []byte("x")}) + } + + return out +} + +func logIndexes(t *testing.T, n *Node) []uint64 { + t.Helper() + + got, err := n.log.GetEntriesAfter(0, 1000) + if err != nil { + t.Fatal(err) + } + + idx := make([]uint64, 0, len(got)) + for _, e := range got { + idx = append(idx, e.Index) + } + + return idx +} + +func assertLog(t *testing.T, n *Node, wantLast uint64) { + t.Helper() + + idx := logIndexes(t, n) + if uint64(len(idx)) != wantLast || n.log.LastIndex() != wantLast { + t.Fatalf("log = %v (LastIndex %d), want indexes 1..%d", idx, n.log.LastIndex(), wantLast) + } + + for i, v := range idx { + if v != uint64(i+1) { + t.Fatalf("log = %v, want contiguous indexes 1..%d", idx, wantLast) + } + } +} + +// A retransmitted AppendEntries must not duplicate entries. +func TestAppendEntriesRetransmitIsIdempotent(t *testing.T) { + n := newTestNode(t, "f", newMemStorage(t)) + req := internal.AppendEntriesRequest{Term: 1, LeaderID: "l", Entries: ents(1, 1, 3)} + + for range 2 { + if resp := n.handleAppendEntries(req); !resp.Success { + t.Fatalf("AppendEntries rejected: %+v", resp) + } + } + + assertLog(t, n, 3) +} + +// A delayed duplicate of an old, shorter AppendEntries must not move the log +// backwards, and the node must keep refusing votes to candidates that miss +// committed entries. +func TestDelayedDuplicateDoesNotShrinkLog(t *testing.T) { + n := newTestNode(t, "f", newMemStorage(t)) + + if resp := n.handleAppendEntries(internal.AppendEntriesRequest{ + Term: 2, LeaderID: "l", Entries: ents(2, 1, 10), LeaderCommit: 10, + }); !resp.Success { + t.Fatalf("AppendEntries rejected: %+v", resp) + } + + resp := n.handleAppendEntries(internal.AppendEntriesRequest{Term: 2, LeaderID: "l", Entries: ents(2, 1, 3)}) + if !resp.Success || resp.MatchIndex != 3 { + t.Fatalf("duplicate response = %+v, want success with match index 3", resp) + } + + assertLog(t, n, 10) + + if n.commitIndex != 10 { + t.Fatalf("commitIndex = %d, want 10", n.commitIndex) + } + + vote, err := n.RequestVote(context.Background(), &internal.RequestVoteRequest{ + Term: 3, CandidateID: "c", LastLogIndex: 5, LastLogTerm: 2, + }) + if err != nil { + t.Fatal(err) + } + + if vote.VoteGranted { + t.Fatal("granted a vote to a candidate missing committed entries 6..10") + } +} + +// A conflicting suffix is truncated and replaced, and commitIndex only moves +// up to the last entry the request carried, never to a stale tail. +func TestCommitIndexBoundedByLastNewEntry(t *testing.T) { + n := newTestNode(t, "f", newMemStorage(t)) + + n.handleAppendEntries(internal.AppendEntriesRequest{Term: 1, LeaderID: "old1", Entries: ents(1, 1, 3)}) + n.handleAppendEntries(internal.AppendEntriesRequest{ + Term: 2, LeaderID: "old2", PrevLogIndex: 3, PrevLogTerm: 1, Entries: ents(2, 4, 10), + }) + + // The new leader's first batch only covers 1..3, which this node has. + resp := n.handleAppendEntries(internal.AppendEntriesRequest{ + Term: 3, LeaderID: "new", PrevLogIndex: 0, Entries: ents(1, 1, 3), LeaderCommit: 20, + }) + if !resp.Success { + t.Fatalf("AppendEntries rejected: %+v", resp) + } + + if n.commitIndex != 3 { + t.Fatalf("commitIndex = %d, want 3 (entries 4..10 are an uncommitted term 2 tail)", n.commitIndex) + } + + // The next batch conflicts at 4 and replaces the stale tail. + resp = n.handleAppendEntries(internal.AppendEntriesRequest{ + Term: 3, LeaderID: "new", PrevLogIndex: 3, PrevLogTerm: 1, Entries: ents(3, 4, 6), LeaderCommit: 20, + }) + if !resp.Success { + t.Fatalf("AppendEntries rejected: %+v", resp) + } + + assertLog(t, n, 6) + + for i := uint64(4); i <= 6; i++ { + if term, _ := n.log.Term(i); term != 3 { + t.Fatalf("entry %d has term %d, want 3", i, term) + } + } + + if n.commitIndex != 6 { + t.Fatalf("commitIndex = %d, want 6", n.commitIndex) + } +} + +// Entries that do not continue from prevLogIndex are rejected. +func TestAppendEntriesRejectsNonContiguousEntries(t *testing.T) { + n := newTestNode(t, "f", newMemStorage(t)) + + resp := n.handleAppendEntries(internal.AppendEntriesRequest{ + Term: 1, LeaderID: "l", Entries: []internal.LogEntry{{Index: 1, Term: 1}, {Index: 3, Term: 1}}, + }) + if resp.Success || n.log.LastIndex() != 0 { + t.Fatalf("accepted non-contiguous entries: resp=%+v last=%d", resp, n.log.LastIndex()) + } +} + +// A restarted node reloads its log, term and vote from storage, and entries +// removed by truncation stay removed. +func TestRestartReloadsLogAndState(t *testing.T) { + st := newMemStorage(t) + n := newTestNode(t, "f", st) + + n.handleAppendEntries(internal.AppendEntriesRequest{Term: 2, LeaderID: "l", Entries: ents(2, 1, 7)}) + // A new leader replaces 6..7. + n.handleAppendEntries(internal.AppendEntriesRequest{ + Term: 3, LeaderID: "l2", PrevLogIndex: 5, PrevLogTerm: 2, Entries: ents(3, 6, 6), LeaderCommit: 6, + }) + + if _, err := n.RequestVote(context.Background(), &internal.RequestVoteRequest{ + Term: 4, CandidateID: "c", LastLogIndex: 6, LastLogTerm: 3, + }); err != nil { + t.Fatal(err) + } + + n2 := newTestNode(t, "f", st) // same storage, new process + + if n2.log.LastIndex() != 6 || n2.log.LastTerm() != 3 { + t.Fatalf("after restart LastIndex=%d LastTerm=%d, want 6 and 3", n2.log.LastIndex(), n2.log.LastTerm()) + } + + if _, err := n2.log.Get(7); err == nil { + t.Fatal("truncated entry 7 came back after restart") + } + + if n2.currentTerm != 4 || n2.votedFor != "c" { + t.Fatalf("after restart term=%d votedFor=%q, want 4 and c", n2.currentTerm, n2.votedFor) + } + + // A different candidate in the same term must be refused. + vote, _ := n2.RequestVote(context.Background(), &internal.RequestVoteRequest{ + Term: 4, CandidateID: "other", LastLogIndex: 100, LastLogTerm: 4, + }) + if vote.VoteGranted { + t.Fatal("restarted node voted twice in term 4") + } + + resp := n2.handleAppendEntries(internal.AppendEntriesRequest{Term: 4, LeaderID: "c", PrevLogIndex: 6, PrevLogTerm: 3}) + if !resp.Success { + t.Fatalf("heartbeat with prev=6 rejected after restart: %+v", resp) + } +} + +// flakyStorage fails writes on demand. +type flakyStorage struct { + *storage.MemoryStorage + + failWrites atomic.Bool +} + +var errInjected = errors.New("injected storage failure") + +func (f *flakyStorage) Set(key, value []byte) error { + if f.failWrites.Load() { + return errInjected + } + + return f.MemoryStorage.Set(key, value) +} + +func (f *flakyStorage) Batch(ops []internal.BatchOp) error { + if f.failWrites.Load() { + return errInjected + } + + return f.MemoryStorage.Batch(ops) +} + +// A follower must not acknowledge entries it failed to persist. +func TestAppendEntriesPersistFailureIsRejected(t *testing.T) { + st := &flakyStorage{MemoryStorage: newMemStorage(t)} + n := newTestNode(t, "f", st) + + st.failWrites.Store(true) + + resp := n.handleAppendEntries(internal.AppendEntriesRequest{Term: 1, LeaderID: "l", Entries: ents(1, 1, 3), LeaderCommit: 3}) + if resp.Success { + t.Fatal("acknowledged entries whose storage write failed") + } + + if n.log.LastIndex() != 0 || n.commitIndex != 0 { + t.Fatalf("failed write left LastIndex=%d commitIndex=%d", n.log.LastIndex(), n.commitIndex) + } + + st.failWrites.Store(false) + + if resp := n.handleAppendEntries(internal.AppendEntriesRequest{Term: 1, LeaderID: "l", Entries: ents(1, 1, 3)}); !resp.Success { + t.Fatalf("retry after storage recovered rejected: %+v", resp) + } +} + +// A vote that cannot be persisted must not be granted. +func TestVoteNotGrantedWhenPersistFails(t *testing.T) { + st := &flakyStorage{MemoryStorage: newMemStorage(t)} + n := newTestNode(t, "f", st) + + st.failWrites.Store(true) + + vote, _ := n.RequestVote(context.Background(), &internal.RequestVoteRequest{Term: 1, CandidateID: "c"}) + if vote.VoteGranted { + t.Fatal("granted a vote that was not persisted") + } +} + +// No candidate gets a vote just because of its name. +func TestNoCandidateIsFavoured(t *testing.T) { + n := newTestNode(t, "f", newMemStorage(t)) + n.handleAppendEntries(internal.AppendEntriesRequest{Term: 2, LeaderID: "l", Entries: ents(2, 1, 5)}) + + vote, _ := n.RequestVote(context.Background(), &internal.RequestVoteRequest{ + Term: 3, CandidateID: "node-1", LastLogIndex: 1, LastLogTerm: 1, + }) + if vote.VoteGranted { + t.Fatal("node-1 was granted a vote with an out of date log") + } +} diff --git a/extensions/consensus/raft/node.go b/extensions/consensus/raft/node.go index ab43068f1..f496a8c53 100644 --- a/extensions/consensus/raft/node.go +++ b/extensions/consensus/raft/node.go @@ -75,12 +75,20 @@ type Node struct { // Synchronization mu sync.RWMutex - applyCh chan ApplyMsg snapshotCh chan SnapshotMsg configChangeCh chan ConfigChangeMsg - // RPC response channels - pendingRequests map[string]chan any + // Apply pipeline. applyNotify wakes the single applier goroutine when + // commitIndex moves; applyWaiters holds the Apply calls waiting for their + // entry, keyed by log index. Both are guarded by mu. + applyNotify chan struct{} + applyWaiters map[uint64]applyWaiter + + // RPC correlation. Every outgoing request gets a fresh ID from requestSeq, + // which the peer echoes in its response, so a late response can never be + // matched to a newer request to the same peer. + requestSeq atomic.Uint64 + pendingRequests map[pendingKey]chan any requestMu sync.RWMutex // State @@ -100,6 +108,18 @@ type PeerState struct { ReplicationMu sync.Mutex } +// pendingKey identifies one outstanding request to one peer. +type pendingKey struct { + peer string + id uint64 +} + +// applyWaiter is an Apply call waiting for its entry to be applied. +type applyWaiter struct { + term uint64 + ch chan error +} + // ApplyMsg represents a message to apply to the state machine. type ApplyMsg struct { Index uint64 @@ -185,10 +205,11 @@ func NewNode( transport: transport, storage: storage, peers: make(map[string]*PeerState), - applyCh: make(chan ApplyMsg, 100), snapshotCh: make(chan SnapshotMsg, 10), configChangeCh: make(chan ConfigChangeMsg, 10), - pendingRequests: make(map[string]chan any), + applyNotify: make(chan struct{}, 1), + applyWaiters: make(map[uint64]applyWaiter), + pendingRequests: make(map[pendingKey]chan any), } // Initialize role as follower @@ -207,6 +228,10 @@ func NewNode( return nil, fmt.Errorf("failed to restore state: %w", err) } + if err := n.restoreSnapshot(); err != nil { + return nil, fmt.Errorf("failed to restore snapshot: %w", err) + } + return n, nil } @@ -316,7 +341,15 @@ func (n *Node) GetCurrentTerm() uint64 { return n.GetTerm() } -// handleAppendEntries handles an AppendEntries request. +// handleAppendEntries handles an AppendEntries request following section 5.3 +// of the Raft paper. +// +// Entries the log already holds with the same term are skipped, so a +// retransmitted or delayed request never duplicates entries or moves the log +// backwards. The first entry whose term conflicts truncates the log from that +// index before the remaining entries are appended. Success is only reported +// once the new entries are durable, and commitIndex only advances to the last +// entry this request vouched for, never to a stale tail that happens to follow. func (n *Node) handleAppendEntries(req internal.AppendEntriesRequest) internal.AppendEntriesResponse { n.mu.Lock() defer n.mu.Unlock() @@ -324,6 +357,7 @@ func (n *Node) handleAppendEntries(req internal.AppendEntriesRequest) internal.A resp := internal.AppendEntriesResponse{ Term: n.currentTerm, Success: false, + NodeID: n.id, } // Reply false if term < currentTerm (§5.1) @@ -336,63 +370,121 @@ func (n *Node) handleAppendEntries(req internal.AppendEntriesRequest) internal.A if req.Term > n.currentTerm { n.currentTerm = req.Term n.votedFor = "" - n.setRole(internal.RoleFollower) - n.persistStateOrLog("append entries from newer term") + resp.Term = n.currentTerm + + if err := n.persistState(); err != nil { + n.logger.Error("failed to persist term from AppendEntries, rejecting request", + forge.F("node_id", n.id), + forge.F("term", n.currentTerm), + forge.F("error", err), + ) + + return resp + } } - // Reset election timer on valid AppendEntries + // A valid leader exists for this term, so a candidate or a stale leader + // returns to follower. + n.setRole(internal.RoleFollower) n.resetElectionTimerUnsafe() n.setLeader(req.LeaderID) + resp.LastLogIndex = n.log.LastIndex() + // Reply false if log doesn't contain an entry at prevLogIndex - // whose term matches prevLogTerm (§5.3) - if req.PrevLogIndex > 0 { - entry, err := n.log.Get(req.PrevLogIndex) - if err != nil || entry.Term != req.PrevLogTerm { - return resp - } + // whose term matches prevLogTerm (§5.3). Entries covered by the snapshot + // are committed, so they match by the Log Matching property. + if req.PrevLogIndex > n.log.SnapshotIndex() && !n.log.MatchesTerm(req.PrevLogIndex, req.PrevLogTerm) { + return resp } - // If an existing entry conflicts with a new one (same index - // but different terms), delete the existing entry and all that - // follow it (§5.3) - for _, entry := range req.Entries { - existing, err := n.log.Get(entry.Index) - if err == nil && existing.Term != entry.Term { - // Delete conflicting entry and all that follow - if err := n.log.TruncateAfter(entry.Index - 1); err != nil { - n.logger.Warn("failed to truncate conflicting log entries", - forge.F("node_id", n.id), - forge.F("index", entry.Index), - forge.F("error", err), - ) - } - } - // Append keeps the entry in memory even when the storage write fails, - // so the reply still reports success and only the durability gap is logged. - if err := n.log.Append(entry); err != nil { - n.logger.Error("failed to persist appended log entry", + if req.PrevLogIndex == n.log.SnapshotIndex() && req.PrevLogIndex > 0 && req.PrevLogTerm != n.log.SnapshotTerm() { + return resp + } + + // The entries must continue directly from prevLogIndex. + for i, entry := range req.Entries { + if entry.Index != req.PrevLogIndex+1+uint64(i) { + n.logger.Warn("rejecting AppendEntries with non-contiguous entries", forge.F("node_id", n.id), + forge.F("leader", req.LeaderID), + forge.F("position", i), forge.F("index", entry.Index), - forge.F("term", entry.Term), - forge.F("error", err), ) + + return resp } } + if err := n.reconcileEntriesLocked(req.Entries); err != nil { + n.logger.Error("failed to store entries from AppendEntries, rejecting request", + forge.F("node_id", n.id), + forge.F("leader", req.LeaderID), + forge.F("error", err), + ) + + resp.LastLogIndex = n.log.LastIndex() + + return resp + } + // If leaderCommit > commitIndex, set commitIndex = // min(leaderCommit, index of last new entry) + lastNewIndex := req.PrevLogIndex + uint64(len(req.Entries)) if req.LeaderCommit > n.commitIndex { - lastNewIndex := n.log.LastIndex() - n.commitIndex = min(req.LeaderCommit, lastNewIndex) + if newCommit := min(req.LeaderCommit, lastNewIndex); newCommit > n.commitIndex { + n.commitIndex = newCommit + n.signalApply() + } } + n.appendCount.Add(1) + resp.Success = true resp.Term = n.currentTerm + resp.MatchIndex = lastNewIndex + resp.LastLogIndex = n.log.LastIndex() return resp } +// reconcileEntriesLocked merges a contiguous run of leader entries into the +// log. Entries already present with the same term are skipped; the first +// conflicting entry truncates the log there; everything after it is appended. +// The caller holds n.mu. +func (n *Node) reconcileEntriesLocked(entries []internal.LogEntry) error { + snapshotIndex := n.log.SnapshotIndex() + lastIndex := n.log.LastIndex() + + for i, entry := range entries { + if entry.Index <= snapshotIndex { + continue + } + + if entry.Index > lastIndex { + return n.log.AppendBatch(entries[i:]) + } + + term, _ := n.log.Term(entry.Index) + if term == entry.Term { + continue + } + + if entry.Index <= n.commitIndex { + return fmt.Errorf("leader entry %d (term %d) conflicts with committed entry (term %d)", + entry.Index, entry.Term, term) + } + + if err := n.log.TruncateAfter(entry.Index - 1); err != nil { + return fmt.Errorf("truncate conflicting entries from %d: %w", entry.Index, err) + } + + return n.log.AppendBatch(entries[i:]) + } + + return nil +} + // handleRequestVote handles a RequestVote request. func (n *Node) handleRequestVote(req internal.RequestVoteRequest) internal.RequestVoteResponse { resp, _ := n.RequestVote(context.Background(), &req) @@ -401,12 +493,18 @@ func (n *Node) handleRequestVote(req internal.RequestVoteRequest) internal.Reque } // handleInstallSnapshot handles an InstallSnapshot request. +// +// Installing snapshots sent by a leader is not implemented. The request still +// updates the term and leader like any RPC from a current leader, but the +// snapshot itself is dropped and logged as an error rather than acknowledged +// as if it had been installed. func (n *Node) handleInstallSnapshot(req internal.InstallSnapshotRequest) internal.InstallSnapshotResponse { n.mu.Lock() defer n.mu.Unlock() resp := internal.InstallSnapshotResponse{ - Term: n.currentTerm, + Term: n.currentTerm, + NodeID: n.id, } // Reply immediately if term < currentTerm @@ -418,30 +516,37 @@ func (n *Node) handleInstallSnapshot(req internal.InstallSnapshotRequest) intern if req.Term > n.currentTerm { n.currentTerm = req.Term n.votedFor = "" - n.setRole(internal.RoleFollower) n.persistStateOrLog("install snapshot from newer term") } - // Reset election timer + n.setRole(internal.RoleFollower) n.resetElectionTimerUnsafe() n.setLeader(req.LeaderID) - // Install snapshot - // In a real implementation, this would save the snapshot and update state - // For now, just acknowledge receipt + n.logger.Error("received InstallSnapshot, which is not implemented; the snapshot was dropped", + forge.F("node_id", n.id), + forge.F("leader", req.LeaderID), + forge.F("last_included_index", req.LastIncludedIndex), + forge.F("last_included_term", req.LastIncludedTerm), + ) + resp.Term = n.currentTerm return resp } -// Apply applies a log entry. +// Apply appends an entry on the leader and waits until it is committed and +// applied to the local state machine. It returns the state machine's error for +// that entry, or an error when leadership is lost and the entry is replaced. func (n *Node) Apply(ctx context.Context, entry internal.LogEntry) error { - if !n.IsLeader() { + n.mu.Lock() + + if n.GetRole() != internal.RoleLeader { + n.mu.Unlock() + return internal.NewNotLeaderError(n.id, n.GetLeader()) } - // Append to log - n.mu.Lock() entry.Term = n.currentTerm entry.Index = n.log.LastIndex() + 1 entry.Created = time.Now() @@ -452,41 +557,50 @@ func (n *Node) Apply(ctx context.Context, entry internal.LogEntry) error { return fmt.Errorf("failed to append log entry: %w", err) } - // Persist immediately - if err := n.persistState(); err != nil { - n.mu.Unlock() - - return fmt.Errorf("failed to persist state: %w", err) - } + resultCh := make(chan error, 1) + n.applyWaiters[entry.Index] = applyWaiter{term: entry.Term, ch: resultCh} + // A single-node cluster is its own majority. + n.advanceCommitIndex() n.mu.Unlock() - // Trigger replication n.triggerReplication() - // Wait for commitment with timeout - resultCh := make(chan error, 1) - msg := ApplyMsg{ - Index: entry.Index, - Term: entry.Term, - Entry: entry, - ResultCh: resultCh, - } + timer := time.NewTimer(60 * time.Second) + defer timer.Stop() - select { - case n.applyCh <- msg: - case <-ctx.Done(): - return ctx.Err() - } + var err error select { - case err := <-resultCh: + case err = <-resultCh: return err case <-ctx.Done(): - return ctx.Err() - case <-time.After(60 * time.Second): - return internal.NewTimeoutError("apply operation timed out") + err = ctx.Err() + case <-n.doneCh(): + err = internal.ErrNotStarted + case <-timer.C: + err = internal.NewTimeoutError("apply operation timed out") + } + + n.mu.Lock() + if w, ok := n.applyWaiters[entry.Index]; ok && w.ch == resultCh { + delete(n.applyWaiters, entry.Index) + } + n.mu.Unlock() + + return err +} + +// doneCh returns a channel closed when the node stops, or nil before Start. +func (n *Node) doneCh() <-chan struct{} { + n.mu.RLock() + defer n.mu.RUnlock() + + if n.ctx == nil { + return nil } + + return n.ctx.Done() } // GetStats returns Raft statistics. @@ -536,29 +650,71 @@ func (n *Node) GetCommitIndex() uint64 { return n.commitIndex } -// restoreState restores persistent state from storage. +// restoreState restores the persisted term and vote. A missing key means a +// fresh node; any other read error fails startup, because guessing a term or +// vote could let the node vote twice in one term. func (n *Node) restoreState() error { - // Restore current term termBytes, err := n.storage.Get([]byte("currentTerm")) - if err == nil && len(termBytes) == 8 { + + switch { + case err == nil: + if len(termBytes) != 8 { + return fmt.Errorf("stored currentTerm has %d bytes, want 8", len(termBytes)) + } + n.currentTerm = bytesToUint64(termBytes) + case !isNotFound(err): + return fmt.Errorf("failed to read currentTerm: %w", err) } - // Restore voted for votedForBytes, err := n.storage.Get([]byte("votedFor")) - if err == nil { + + switch { + case err == nil: n.votedFor = string(votedForBytes) + case !isNotFound(err): + return fmt.Errorf("failed to read votedFor: %w", err) } n.logger.Info("restored raft state", forge.F("node_id", n.id), forge.F("term", n.currentTerm), forge.F("voted_for", n.votedFor), + forge.F("last_log_index", n.log.LastIndex()), + forge.F("last_log_term", n.log.LastTerm()), ) return nil } +// restoreSnapshot loads the latest snapshot into the state machine so the +// node resumes applying from the first entry after it. +func (n *Node) restoreSnapshot() error { + index := n.log.SnapshotIndex() + if index == 0 { + return nil + } + + data, err := n.storage.Get(fmt.Appendf(nil, "snapshot_%d", index)) + if err != nil { + return fmt.Errorf("snapshot %d is recorded in metadata but cannot be read: %w", index, err) + } + + if err := n.stateMachine.Restore(&internal.Snapshot{ + Index: index, + Term: n.log.SnapshotTerm(), + Data: data, + Size: int64(len(data)), + }); err != nil { + return fmt.Errorf("state machine rejected snapshot %d: %w", index, err) + } + + n.commitIndex = index + n.lastApplied = index + + return nil +} + // persistState persists current state to storage. func (n *Node) persistState() error { // Persist current term @@ -645,54 +801,65 @@ func bytesToUint64(b []byte) uint64 { return v } -// generateRequestID generates a unique request ID. -func (n *Node) generateRequestID() string { - return fmt.Sprintf("%s-%d", n.id, time.Now().UnixNano()) -} +// call sends a request to a peer and waits for the response carrying the +// same request ID. Responses to earlier requests, which may still be in +// flight, are dropped instead of being mistaken for this one. +func (n *Node) call(ctx context.Context, peerID string, msgType internal.MessageType, payload any) (any, error) { + key := pendingKey{peer: peerID, id: n.requestSeq.Add(1)} + responseCh := make(chan any, 1) -// waitForResponse waits for a response to a pending request. -func (n *Node) waitForResponse(requestID string, timeout time.Duration) (any, error) { - n.requestMu.RLock() - responseCh, exists := n.pendingRequests[requestID] - n.requestMu.RUnlock() + n.requestMu.Lock() + n.pendingRequests[key] = responseCh + n.requestMu.Unlock() - if !exists { - return nil, fmt.Errorf("request %s not found", requestID) + defer func() { + n.requestMu.Lock() + delete(n.pendingRequests, key) + n.requestMu.Unlock() + }() + + msg := internal.Message{ + Type: msgType, + From: n.id, + To: peerID, + Payload: payload, + Timestamp: time.Now().UnixNano(), + RequestID: key.id, + } + + if err := n.transport.Send(ctx, peerID, msg); err != nil { + return nil, err } select { case response := <-responseCh: - // Clean up - n.requestMu.Lock() - delete(n.pendingRequests, requestID) - n.requestMu.Unlock() - return response, nil - case <-time.After(timeout): - // Clean up - n.requestMu.Lock() - delete(n.pendingRequests, requestID) - n.requestMu.Unlock() - - return nil, fmt.Errorf("request %s timed out", requestID) + case <-ctx.Done(): + return nil, ctx.Err() } } -// sendResponse sends a response to a pending request. -func (n *Node) sendResponse(requestID string, response any) { +// deliverResponse hands a response to the request waiting for it. A response +// nobody is waiting for any more is stale and is dropped. +func (n *Node) deliverResponse(from string, requestID uint64, response any) { n.requestMu.RLock() - responseCh, exists := n.pendingRequests[requestID] + responseCh, exists := n.pendingRequests[pendingKey{peer: from, id: requestID}] n.requestMu.RUnlock() - if exists { - select { - case responseCh <- response: - default: - // Channel is full or closed, clean up - n.requestMu.Lock() - delete(n.pendingRequests, requestID) - n.requestMu.Unlock() - } + if !exists { + n.logger.Debug("dropping response with no pending request", + forge.F("node_id", n.id), + forge.F("from", from), + forge.F("request_id", requestID), + ) + + return + } + + select { + case responseCh <- response: + default: + // A duplicate response for a request that already has one. } } diff --git a/extensions/consensus/raft/replication.go b/extensions/consensus/raft/replication.go index 1866fc932..347b4b940 100644 --- a/extensions/consensus/raft/replication.go +++ b/extensions/consensus/raft/replication.go @@ -2,7 +2,6 @@ package raft import ( "context" - "fmt" "time" "github.com/xraph/forge" @@ -10,7 +9,13 @@ import ( "github.com/xraph/forge/extensions/consensus/internal" ) -// replicateToPeer replicates log entries to a single peer. +// maxReplicationRounds bounds how many AppendEntries round trips one +// replicateToPeer call makes before leaving the rest to the next heartbeat. +const maxReplicationRounds = 64 + +// replicateToPeer replicates log entries to a single peer. It keeps sending +// while the peer is behind or rejected the last batch, so a lagging follower +// catches up without waiting a heartbeat interval per batch. func (n *Node) replicateToPeer(peer *PeerState) { // Try to acquire lock, skip if already replicating if !peer.ReplicationMu.TryLock() { @@ -18,430 +23,282 @@ func (n *Node) replicateToPeer(peer *PeerState) { } defer peer.ReplicationMu.Unlock() - // Read node state (release lock immediately) - n.mu.RLock() + for range maxReplicationRounds { + req, ok := n.buildAppendEntries(peer) + if !ok { + return + } - if !n.IsLeader() { - n.mu.RUnlock() + resp, err := n.sendAppendEntries(peer, req) + if err != nil { + n.logger.Debug("failed to send AppendEntries", + forge.F("peer", peer.ID), + forge.F("error", err), + ) - return + return + } + + // No locks held here: the handler may step down, which takes n.mu. + if !n.handleAppendEntriesResponse(peer, req, resp) { + return + } } +} - currentTerm := n.currentTerm - commitIndex := n.commitIndex - nextIndex := n.nextIndex[peer.ID] - n.mu.RUnlock() +// buildAppendEntries builds the next AppendEntries request for a peer from a +// consistent view of the leader state. It returns false when this node is not +// the leader or the peer needs entries that were compacted away. +func (n *Node) buildAppendEntries(peer *PeerState) (*internal.AppendEntriesRequest, bool) { + n.mu.RLock() + defer n.mu.RUnlock() - n.logger.Debug("replicating to peer", - forge.F("node_id", n.id), - forge.F("peer_id", peer.ID), - forge.F("next_index", nextIndex), - forge.F("commit_index", commitIndex), - ) + if n.GetRole() != internal.RoleLeader { + return nil, false + } - // Get entries to send + nextIndex := max(n.nextIndex[peer.ID], 1) prevLogIndex := nextIndex - 1 - prevLogTerm := uint64(0) - if prevLogIndex > 0 { - entry, err := n.log.Get(prevLogIndex) - if err != nil { - // Previous entry might be in snapshot - n.logger.Debug("previous log entry not found, may need snapshot", - forge.F("peer", peer.ID), - forge.F("prev_index", prevLogIndex), - ) - // TODO: Send snapshot if needed - return - } + prevLogTerm, ok := n.log.Term(prevLogIndex) + if !ok { + n.logger.Error("peer needs log entries that are only in a snapshot; InstallSnapshot is not implemented, so it cannot catch up", + forge.F("node_id", n.id), + forge.F("peer", peer.ID), + forge.F("prev_index", prevLogIndex), + forge.F("snapshot_index", n.log.SnapshotIndex()), + ) - prevLogTerm = entry.Term + return nil, false } - // Get entries to replicate - maxEntries := n.config.MaxAppendEntries - - entries, err := n.log.GetEntriesAfter(prevLogIndex, maxEntries) + entries, err := n.log.GetEntriesAfter(prevLogIndex, n.config.MaxAppendEntries) if err != nil { n.logger.Error("failed to get log entries", forge.F("peer", peer.ID), forge.F("error", err), ) - return + return nil, false } - // Send AppendEntries RPC - req := &internal.AppendEntriesRequest{ - Term: currentTerm, + return &internal.AppendEntriesRequest{ + Term: n.currentTerm, LeaderID: n.id, PrevLogIndex: prevLogIndex, PrevLogTerm: prevLogTerm, Entries: entries, - LeaderCommit: commitIndex, - } - - resp, err := n.sendAppendEntries(peer, req) - if err != nil { - n.logger.Warn("failed to send AppendEntries", - forge.F("peer", peer.ID), - forge.F("error", err), - ) - - return - } - - // Handle response (no locks held - handler may call stepDown which needs write lock) - n.handleAppendEntriesResponse(peer, req, resp) + LeaderCommit: n.commitIndex, + }, true } -// sendAppendEntries sends an AppendEntries RPC to a peer. +// sendAppendEntries sends an AppendEntries RPC to a peer and waits for the +// response to this exact request. func (n *Node) sendAppendEntries(peer *PeerState, req *internal.AppendEntriesRequest) (*internal.AppendEntriesResponse, error) { ctx, cancel := context.WithTimeout(n.ctx, 5*time.Second) defer cancel() - // Generate unique request ID - requestID := fmt.Sprintf("append_entries_%s_%s", n.id, peer.ID) - responseCh := make(chan any, 1) - - // Register pending request - n.requestMu.Lock() - n.pendingRequests[requestID] = responseCh - n.requestMu.Unlock() - - msg := internal.Message{ - Type: internal.MessageTypeAppendEntries, - From: n.id, - To: peer.ID, - Payload: req, - } - - // Send via transport - err := n.transport.Send(ctx, peer.ID, msg) + response, err := n.call(ctx, peer.ID, internal.MessageTypeAppendEntries, req) if err != nil { - // Clean up - n.requestMu.Lock() - delete(n.pendingRequests, requestID) - n.requestMu.Unlock() - return nil, err } - peer.LastContact = time.Now() - - // Wait for response - select { - case response := <-responseCh: - // Clean up - n.requestMu.Lock() - delete(n.pendingRequests, requestID) - n.requestMu.Unlock() - - if resp, ok := response.(*internal.AppendEntriesResponse); ok { - return resp, nil - } - + resp, ok := response.(*internal.AppendEntriesResponse) + if !ok { return nil, errors.New("invalid response type") + } - case <-ctx.Done(): - // Clean up - n.requestMu.Lock() - delete(n.pendingRequests, requestID) - n.requestMu.Unlock() + n.peersLock.Lock() + peer.LastContact = time.Now() + n.peersLock.Unlock() - return nil, ctx.Err() - } + return resp, nil } -// handleAppendEntriesResponse handles the response from an AppendEntries RPC. -func (n *Node) handleAppendEntriesResponse(peer *PeerState, req *internal.AppendEntriesRequest, resp *internal.AppendEntriesResponse) { +// handleAppendEntriesResponse applies a peer's answer to the request it was +// sent for. It reports whether the peer should be sent another batch now. +// +// matchIndex only moves forward and is bounded by what the request actually +// carried, and nextIndex only backs off when the rejected request is the one +// nextIndex currently describes, so reordered or duplicated responses cannot +// overstate replication or back off twice. +func (n *Node) handleAppendEntriesResponse(peer *PeerState, req *internal.AppendEntriesRequest, resp *internal.AppendEntriesResponse) bool { n.mu.Lock() defer n.mu.Unlock() - // Check if we're still leader in the same term - if !n.IsLeader() || n.currentTerm != req.Term { - return - } - // If term in response is higher, step down if resp.Term > n.currentTerm { n.stepDownLocked(resp.Term) - return - } - - if resp.Success { - // Update nextIndex and matchIndex - if len(req.Entries) > 0 { - lastEntry := req.Entries[len(req.Entries)-1] - n.nextIndex[peer.ID] = lastEntry.Index + 1 - n.matchIndex[peer.ID] = lastEntry.Index - - n.logger.Debug("successfully replicated to peer", - forge.F("peer", peer.ID), - forge.F("match_index", lastEntry.Index), - ) - - // Try to advance commit index - n.advanceCommitIndex() - } - } else { - // Replication failed, decrement nextIndex and retry - if n.nextIndex[peer.ID] > 1 { - n.nextIndex[peer.ID]-- - } - - n.logger.Debug("replication failed, decrementing nextIndex", - forge.F("peer", peer.ID), - forge.F("next_index", n.nextIndex[peer.ID]), - ) - - // Immediately retry - go n.replicateToPeer(peer) + return false } -} -// AppendEntries handles an AppendEntries RPC from the leader. -func (n *Node) AppendEntries(ctx context.Context, req *internal.AppendEntriesRequest) (*internal.AppendEntriesResponse, error) { - n.mu.Lock() - defer n.mu.Unlock() - - resp := &internal.AppendEntriesResponse{ - Term: n.currentTerm, - Success: false, - NodeID: n.id, - } - - // Reply false if term < currentTerm - if req.Term < n.currentTerm { - return resp, nil + // Check if we're still leader in the same term + if n.GetRole() != internal.RoleLeader || n.currentTerm != req.Term { + return false } - // Reset election timer since we heard from leader - n.resetElectionTimerUnsafe() - - // If RPC term is higher, update our term and step down - if req.Term > n.currentTerm { - n.currentTerm = req.Term - n.votedFor = "" - n.persistStateOrLog("append entries from newer term") - } + if resp.Success { + sent := req.PrevLogIndex + uint64(len(req.Entries)) - // Step down to follower if we're not already - if n.GetRole() != internal.RoleFollower { - n.setRole(internal.RoleFollower) - } + match := sent + if resp.MatchIndex != 0 && resp.MatchIndex < sent { + match = resp.MatchIndex + } - // Update leader - if n.GetLeader() != req.LeaderID { - n.setLeader(req.LeaderID) - } + if match > n.matchIndex[peer.ID] { + n.matchIndex[peer.ID] = match - // Reply false if log doesn't contain an entry at prevLogIndex whose term matches prevLogTerm - if req.PrevLogIndex > 0 { - if !n.log.MatchesTerm(req.PrevLogIndex, req.PrevLogTerm) { - n.logger.Debug("log doesn't match at prevLogIndex", - forge.F("prev_index", req.PrevLogIndex), - forge.F("prev_term", req.PrevLogTerm), + n.logger.Debug("successfully replicated to peer", + forge.F("peer", peer.ID), + forge.F("match_index", match), ) - - return resp, nil } - } - // If an existing entry conflicts with a new one (same index but different terms), - // delete the existing entry and all that follow it - for _, entry := range req.Entries { - existingEntry, err := n.log.Get(entry.Index) - if err == nil && existingEntry.Term != entry.Term { - // Conflict detected, truncate log - if err := n.log.TruncateAfter(entry.Index - 1); err != nil { - n.logger.Error("failed to truncate log", - forge.F("error", err), - ) - - return resp, nil - } - - break + if n.nextIndex[peer.ID] < n.matchIndex[peer.ID]+1 { + n.nextIndex[peer.ID] = n.matchIndex[peer.ID] + 1 } - } - // Append any new entries not already in the log - for _, entry := range req.Entries { - _, err := n.log.Get(entry.Index) - if err != nil { - // Entry doesn't exist, append it - if err := n.log.Append(entry); err != nil { - n.logger.Error("failed to append entry", - forge.F("error", err), - ) + n.advanceCommitIndex() - return resp, nil - } - } + return n.nextIndex[peer.ID] <= n.log.LastIndex() } - // Update commit index - if req.LeaderCommit > n.commitIndex { - lastNewIndex := n.log.LastIndex() - n.commitIndex = min(req.LeaderCommit, lastNewIndex) + // Stale rejection for a request nextIndex has already moved past. + if n.nextIndex[peer.ID] != req.PrevLogIndex+1 { + return false + } - n.logger.Debug("updated commit index", - forge.F("commit_index", n.commitIndex), - ) + next := max(min(req.PrevLogIndex, resp.LastLogIndex+1), n.matchIndex[peer.ID]+1, 1) + n.nextIndex[peer.ID] = next - // Apply committed entries - go n.applyCommitted() - } + n.logger.Debug("replication rejected, backing off nextIndex", + forge.F("peer", peer.ID), + forge.F("next_index", next), + ) - resp.Success = true - if len(req.Entries) > 0 { - resp.MatchIndex = req.Entries[len(req.Entries)-1].Index - } + // Retry at once only if backing off changed what will be sent. + return next < req.PrevLogIndex+1 +} - n.appendCount.Add(1) +// AppendEntries handles an AppendEntries RPC from the leader. +func (n *Node) AppendEntries(ctx context.Context, req *internal.AppendEntriesRequest) (*internal.AppendEntriesResponse, error) { + resp := n.handleAppendEntries(*req) - return resp, nil + return &resp, nil } -// advanceCommitIndex tries to advance the commit index based on matchIndex of peers. +// advanceCommitIndex moves commitIndex to the highest index stored on a +// majority whose entry is from the current term. The caller holds n.mu. func (n *Node) advanceCommitIndex() { - // Find the highest index that a majority of nodes have replicated + if n.GetRole() != internal.RoleLeader { + return + } + + n.peersLock.RLock() + clusterSize := len(n.peers) + 1 + n.peersLock.RUnlock() + + majority := clusterSize/2 + 1 lastLogIndex := n.log.LastIndex() + newCommit := n.commitIndex - for n.commitIndex < lastLogIndex { - testIndex := n.commitIndex + 1 + for index := lastLogIndex; index > n.commitIndex; index-- { + // Only entries from the current term are committed by counting + // replicas (§5.4.2); earlier ones commit with them. + term, ok := n.log.Term(index) + if !ok || term != n.currentTerm { + break + } - // Count how many nodes have replicated this index replicated := 1 // Count self for _, matchIndex := range n.matchIndex { - if matchIndex >= testIndex { + if matchIndex >= index { replicated++ } } - // Check if majority has replicated - majority := (len(n.peers)+1)/2 + 1 if replicated >= majority { - // Verify the entry is from current term (Raft safety requirement) - entry, err := n.log.Get(testIndex) - if err == nil && entry.Term == n.currentTerm { - n.commitIndex = testIndex - n.logger.Debug("advanced commit index", - forge.F("commit_index", n.commitIndex), - forge.F("replicated", replicated), - forge.F("majority", majority), - ) - - // Apply committed entries - go n.applyCommitted() - } else { - break - } - } else { + newCommit = index + break } } + + if newCommit > n.commitIndex { + n.commitIndex = newCommit + n.logger.Debug("advanced commit index", + forge.F("commit_index", n.commitIndex), + ) + n.signalApply() + } +} + +// signalApply wakes the applier. The caller holds n.mu. +func (n *Node) signalApply() { + select { + case n.applyNotify <- struct{}{}: + default: + } } -// applyCommitted applies committed log entries to the state machine. +// applyCommitted applies committed entries to the state machine in order. It +// only runs on the applier goroutine, so each entry is applied exactly once. +// +// A state machine error for an entry is returned to the Apply call waiting for +// it and does not stop the applier: the entry is committed on every node, and +// stalling here would wedge the node for good. func (n *Node) applyCommitted() { for { - n.mu.Lock() + n.mu.RLock() if n.lastApplied >= n.commitIndex { - n.mu.Unlock() + n.mu.RUnlock() return } - // Apply next entry applyIndex := n.lastApplied + 1 - entry, err := n.log.Get(applyIndex) + n.mu.RUnlock() + if err != nil { - n.logger.Error("failed to get log entry for apply", + n.logger.Error("failed to get committed log entry for apply", forge.F("index", applyIndex), forge.F("error", err), ) - n.mu.Unlock() return } - n.mu.Unlock() - - // Apply to state machine (outside lock) - if err := n.stateMachine.Apply(entry); err != nil { - n.logger.Error("failed to apply entry to state machine", + applyErr := n.stateMachine.Apply(entry) + if applyErr != nil { + n.logger.Error("state machine rejected committed entry", forge.F("index", applyIndex), - forge.F("error", err), + forge.F("error", applyErr), ) - - return } n.mu.Lock() n.lastApplied = applyIndex + waiter, waiting := n.applyWaiters[applyIndex] + delete(n.applyWaiters, applyIndex) n.mu.Unlock() - n.logger.Debug("applied entry", - forge.F("index", applyIndex), - forge.F("term", entry.Term), - forge.F("type", entry.Type), - ) - - // Notify any waiting Apply() calls - select { - case msg := <-n.applyCh: - if msg.Index == applyIndex { - msg.ResultCh <- nil + if waiting { + if waiter.term == entry.Term { + waiter.ch <- applyErr + } else { + waiter.ch <- errors.New("entry was replaced after a leadership change and was not applied") } - default: } } } // InstallSnapshot handles an InstallSnapshot RPC. func (n *Node) InstallSnapshot(ctx context.Context, req *internal.InstallSnapshotRequest) (*internal.InstallSnapshotResponse, error) { - n.mu.Lock() - defer n.mu.Unlock() - - resp := &internal.InstallSnapshotResponse{ - Term: n.currentTerm, - NodeID: n.id, - } - - // Reply immediately if term < currentTerm - if req.Term < n.currentTerm { - return resp, nil - } + resp := n.handleInstallSnapshot(*req) - // Reset election timer - n.resetElectionTimerUnsafe() - - // If term is higher, update our term - if req.Term > n.currentTerm { - n.currentTerm = req.Term - n.votedFor = "" - n.persistStateOrLog("install snapshot from newer term") - } - - // Update leader - if n.GetLeader() != req.LeaderID { - n.setLeader(req.LeaderID) - } - - // TODO: Handle snapshot installation - // For now, just acknowledge receipt - - n.logger.Info("received snapshot", - forge.F("leader", req.LeaderID), - forge.F("last_included_index", req.LastIncludedIndex), - forge.F("last_included_term", req.LastIncludedTerm), - ) - - return resp, nil + return &resp, nil } diff --git a/extensions/consensus/raft/request_id_test.go b/extensions/consensus/raft/request_id_test.go new file mode 100644 index 000000000..470f2b0f9 --- /dev/null +++ b/extensions/consensus/raft/request_id_test.go @@ -0,0 +1,233 @@ +package raft + +import ( + "context" + "testing" + "time" + + "github.com/xraph/forge" + "github.com/xraph/forge/extensions/consensus/internal" + "github.com/xraph/forge/extensions/consensus/statemachine" +) + +// captureTransport hands every outgoing message to the test and never +// delivers it anywhere. +type captureTransport struct { + sent chan internal.Message + inbox chan internal.Message +} + +func newCaptureTransport() *captureTransport { + return &captureTransport{sent: make(chan internal.Message, 64), inbox: make(chan internal.Message, 64)} +} + +func (c *captureTransport) Start(context.Context) error { return nil } +func (c *captureTransport) Stop(context.Context) error { return nil } + +func (c *captureTransport) Send(_ context.Context, _ string, message any) error { + c.sent <- message.(internal.Message) + + return nil +} + +func (c *captureTransport) Receive() <-chan internal.Message { return c.inbox } +func (c *captureTransport) AddPeer(string, string, int) error { return nil } +func (c *captureTransport) RemovePeer(string) error { return nil } +func (c *captureTransport) GetAddress() string { return "capture" } + +func (c *captureTransport) next(t *testing.T) internal.Message { + t.Helper() + + select { + case m := <-c.sent: + return m + case <-time.After(5 * time.Second): + t.Fatal("no message sent") + + return internal.Message{} + } +} + +// newLeader builds a started leader in term 2 with one peer, "p". +func newLeader(t *testing.T) (*Node, *captureTransport) { + t.Helper() + + lg := forge.NewNoopLogger() + tr := newCaptureTransport() + sm := statemachine.NewMemoryStateMachine(statemachine.MemoryStateMachineConfig{}, lg) + + n, err := NewNode(Config{ + NodeID: "L", + HeartbeatInterval: time.Hour, + ElectionTimeoutMin: time.Hour, + ElectionTimeoutMax: 2 * time.Hour, + }, lg, sm, tr, newMemStorage(t)) + if err != nil { + t.Fatal(err) + } + + n.ctx, n.cancel = context.WithCancel(context.Background()) + t.Cleanup(n.cancel) + + n.AddPeer("p") + n.currentTerm = 2 + n.role.Store(internal.RoleLeader) + + if err := n.log.AppendBatch(ents(2, 1, 10)); err != nil { + t.Fatal(err) + } + + return n, tr +} + +// Each request carries a fresh ID, and a response is only delivered to the +// request whose ID it echoes. +func TestLateResponseIsNotMatchedToNewerRequest(t *testing.T) { + n, tr := newLeader(t) + + // First request times out without an answer. + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + + firstErr := make(chan error, 1) + + go func() { + _, err := n.call(ctx, "p", internal.MessageTypeAppendEntries, &internal.AppendEntriesRequest{Term: 2}) + firstErr <- err + }() + + first := tr.next(t) + + if err := <-firstErr; err == nil { + t.Fatal("first request should have timed out") + } + + // Second request is in flight when the first one's response arrives late. + got := make(chan any, 1) + + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + + resp, _ := n.call(ctx, "p", internal.MessageTypeAppendEntries, &internal.AppendEntriesRequest{Term: 2}) + got <- resp + }() + + second := tr.next(t) + if second.RequestID == first.RequestID { + t.Fatalf("two requests to the same peer share request ID %d", first.RequestID) + } + + late := &internal.AppendEntriesResponse{Term: 2, Success: true, MatchIndex: 1} + n.handleMessage(internal.Message{ + Type: internal.MessageTypeAppendEntriesResponse, From: "p", To: "L", + RequestID: first.RequestID, Payload: late, + }) + + select { + case resp := <-got: + t.Fatalf("late response %+v was delivered to the newer request", resp) + case <-time.After(100 * time.Millisecond): + } + + current := &internal.AppendEntriesResponse{Term: 2, Success: true, MatchIndex: 10} + n.handleMessage(internal.Message{ + Type: internal.MessageTypeAppendEntriesResponse, From: "p", To: "L", + RequestID: second.RequestID, Payload: current, + }) + + if resp := <-got; resp != current { + t.Fatalf("second request got %+v, want its own response", resp) + } +} + +// Responses are only handled by the goroutine that sent the request. A +// response arriving through the message loop must not touch replication state +// a second time. +func TestUnsolicitedResponseDoesNotChangeReplicationState(t *testing.T) { + n, _ := newLeader(t) + + n.mu.Lock() + n.nextIndex["p"] = 8 + n.matchIndex["p"] = 5 + n.mu.Unlock() + + for _, resp := range []*internal.AppendEntriesResponse{ + {Term: 2, Success: false}, + {Term: 2, Success: true, MatchIndex: 10}, + } { + n.handleMessage(internal.Message{ + Type: internal.MessageTypeAppendEntriesResponse, From: "p", To: "L", + RequestID: 999, Payload: resp, + }) + } + + n.mu.RLock() + defer n.mu.RUnlock() + + if n.nextIndex["p"] != 8 || n.matchIndex["p"] != 5 { + t.Fatalf("nextIndex=%d matchIndex=%d, want 8 and 5", n.nextIndex["p"], n.matchIndex["p"]) + } +} + +// Reordered responses never move matchIndex backwards or past what the +// request carried, and a stale rejection does not back nextIndex off again. +func TestResponseHandlingIsBoundedByItsRequest(t *testing.T) { + n, _ := newLeader(t) + peer := n.peers["p"] + + newer := &internal.AppendEntriesRequest{Term: 2, PrevLogIndex: 0, Entries: ents(2, 1, 10)} + older := &internal.AppendEntriesRequest{Term: 2, PrevLogIndex: 0, Entries: ents(2, 1, 3)} + + // The follower claims more than the request carried. + n.handleAppendEntriesResponse(peer, newer, &internal.AppendEntriesResponse{Term: 2, Success: true, MatchIndex: 50}) + + if n.matchIndex["p"] != 10 || n.nextIndex["p"] != 11 { + t.Fatalf("matchIndex=%d nextIndex=%d, want 10 and 11", n.matchIndex["p"], n.nextIndex["p"]) + } + + // The older, shorter request's response arrives last. + n.handleAppendEntriesResponse(peer, older, &internal.AppendEntriesResponse{Term: 2, Success: true, MatchIndex: 3}) + + if n.matchIndex["p"] != 10 || n.nextIndex["p"] != 11 { + t.Fatalf("stale success moved matchIndex=%d nextIndex=%d", n.matchIndex["p"], n.nextIndex["p"]) + } + + // A rejection for a request that no longer matches nextIndex is ignored. + n.handleAppendEntriesResponse(peer, &internal.AppendEntriesRequest{Term: 2, PrevLogIndex: 4}, + &internal.AppendEntriesResponse{Term: 2, Success: false, LastLogIndex: 2}) + + if n.nextIndex["p"] != 11 { + t.Fatalf("stale rejection changed nextIndex to %d", n.nextIndex["p"]) + } + + // The current rejection backs off once, using the follower's hint, but + // never below matchIndex+1. + n.matchIndex["p"] = 0 + n.handleAppendEntriesResponse(peer, &internal.AppendEntriesRequest{Term: 2, PrevLogIndex: 10}, + &internal.AppendEntriesResponse{Term: 2, Success: false, LastLogIndex: 4}) + + if n.nextIndex["p"] != 5 { + t.Fatalf("nextIndex = %d, want 5 from the follower's last index hint", n.nextIndex["p"]) + } +} + +// A vote granted in an earlier term does not count in a later election. +func TestVoteFromOlderTermIsNotCounted(t *testing.T) { + n, tr := newLeader(t) + peer := n.peers["p"] + + granted := make(chan bool, 1) + + go func() { granted <- n.requestVote(peer, 5, 10, 2) }() + + req := tr.next(t) + n.handleMessage(internal.Message{ + Type: internal.MessageTypeRequestVoteResponse, From: "p", To: "L", + RequestID: req.RequestID, Payload: &internal.RequestVoteResponse{Term: 4, VoteGranted: true}, + }) + + if <-granted { + t.Fatal("counted a vote granted for term 4 in the term 5 election") + } +} diff --git a/extensions/consensus/raft/rpc.go b/extensions/consensus/raft/rpc.go index b16e93873..27faa18db 100644 --- a/extensions/consensus/raft/rpc.go +++ b/extensions/consensus/raft/rpc.go @@ -188,23 +188,17 @@ func (rh *RPCHandler) SendAppendEntries(ctx context.Context, target string, req forge.F("entries_count", len(req.Entries)), ) - // Create message - msg := internal.Message{ - Type: internal.MessageTypeAppendEntries, - From: rh.node.id, - To: target, - Timestamp: time.Now().UnixNano(), - Payload: req, + response, err := rh.node.call(ctx, target, internal.MessageTypeAppendEntries, &req) + if err != nil { + return internal.AppendEntriesResponse{}, fmt.Errorf("failed to send message: %w", err) } - // Send via transport - if err := rh.node.transport.Send(ctx, target, msg); err != nil { - return internal.AppendEntriesResponse{}, fmt.Errorf("failed to send message: %w", err) + resp, ok := response.(*internal.AppendEntriesResponse) + if !ok { + return internal.AppendEntriesResponse{}, fmt.Errorf("unexpected response type %T", response) } - // TODO: Wait for response with timeout - // For now, return empty response - return internal.AppendEntriesResponse{}, nil + return *resp, nil } // SendRequestVote sends RequestVote RPC to a peer. @@ -215,23 +209,17 @@ func (rh *RPCHandler) SendRequestVote(ctx context.Context, target string, req in forge.F("candidate", req.CandidateID), ) - // Create message - msg := internal.Message{ - Type: internal.MessageTypeRequestVote, - From: rh.node.id, - To: target, - Timestamp: time.Now().UnixNano(), - Payload: req, + response, err := rh.node.call(ctx, target, internal.MessageTypeRequestVote, &req) + if err != nil { + return internal.RequestVoteResponse{}, fmt.Errorf("failed to send message: %w", err) } - // Send via transport - if err := rh.node.transport.Send(ctx, target, msg); err != nil { - return internal.RequestVoteResponse{}, fmt.Errorf("failed to send message: %w", err) + resp, ok := response.(*internal.RequestVoteResponse) + if !ok { + return internal.RequestVoteResponse{}, fmt.Errorf("unexpected response type %T", response) } - // TODO: Wait for response with timeout - // For now, return empty response - return internal.RequestVoteResponse{}, nil + return *resp, nil } // SendInstallSnapshot sends InstallSnapshot RPC to a peer. @@ -243,23 +231,17 @@ func (rh *RPCHandler) SendInstallSnapshot(ctx context.Context, target string, re forge.F("data_size", len(req.Data)), ) - // Create message - msg := internal.Message{ - Type: internal.MessageTypeInstallSnapshot, - From: rh.node.id, - To: target, - Timestamp: time.Now().UnixNano(), - Payload: req, + response, err := rh.node.call(ctx, target, internal.MessageTypeInstallSnapshot, &req) + if err != nil { + return internal.InstallSnapshotResponse{}, fmt.Errorf("failed to send message: %w", err) } - // Send via transport - if err := rh.node.transport.Send(ctx, target, msg); err != nil { - return internal.InstallSnapshotResponse{}, fmt.Errorf("failed to send message: %w", err) + resp, ok := response.(*internal.InstallSnapshotResponse) + if !ok { + return internal.InstallSnapshotResponse{}, fmt.Errorf("unexpected response type %T", response) } - // TODO: Wait for response with timeout - // For now, return empty response - return internal.InstallSnapshotResponse{}, nil + return *resp, nil } // BroadcastAppendEntries broadcasts AppendEntries to all peers. diff --git a/extensions/consensus/raft/state.go b/extensions/consensus/raft/state.go index c2f2a79ac..f69dfc327 100644 --- a/extensions/consensus/raft/state.go +++ b/extensions/consensus/raft/state.go @@ -2,8 +2,6 @@ package raft import ( "context" - "fmt" - "sync" "time" "github.com/xraph/forge" @@ -103,47 +101,45 @@ func (n *Node) startElection() { ) // Request votes from all peers - votes := 1 // Vote for self - votesNeeded := (len(n.peers)+1)/2 + 1 - - // Channel to collect votes - voteCh := make(chan bool, len(n.peers)) - - // Wait group to track vote goroutines - var voteWg sync.WaitGroup - - // Send RequestVote RPCs to all peers n.peersLock.RLock() - peerCount := len(n.peers) + peers := make([]*PeerState, 0, len(n.peers)) for _, peer := range n.peers { - voteWg.Add(1) + peers = append(peers, peer) + } - go func(p *PeerState) { - defer voteWg.Done() + n.peersLock.RUnlock() - granted := n.requestVote(p, currentTerm, lastLogIndex, lastLogTerm) - voteCh <- granted - }(peer) + peerCount := len(peers) + votes := 1 // Vote for self + votesNeeded := (peerCount+1)/2 + 1 + + // If we have no peers, we are the majority. + if peerCount == 0 { + n.becomeLeader(currentTerm) + + return } - n.peersLock.RUnlock() + // Buffered so vote goroutines never block once the election is decided. + voteCh := make(chan bool, peerCount) - // Goroutine to close voteCh when all votes are collected - go func() { - voteWg.Wait() - close(voteCh) - }() + for _, peer := range peers { + go func(p *PeerState) { + voteCh <- n.requestVote(p, currentTerm, lastLogIndex, lastLogTerm) + }(peer) + } // Collect votes with timeout - electionTimeoutTimer := time.After(electionTimeout) + electionTimeoutTimer := time.NewTimer(electionTimeout) + defer electionTimeoutTimer.Stop() - for votes < votesNeeded && peerCount > 0 { + for range peerCount { select { case <-n.ctx.Done(): return - case <-electionTimeoutTimer: + case <-electionTimeoutTimer.C: n.logger.Warn("election timeout", forge.F("node_id", n.id), forge.F("term", currentTerm), @@ -153,51 +149,38 @@ func (n *Node) startElection() { return - case granted, ok := <-voteCh: - if !ok { - // Channel closed, all votes collected - break + case granted := <-voteCh: + if !granted { + continue } - n.logger.Debug("received vote response", + votes++ + n.logger.Info("vote granted", forge.F("node_id", n.id), - forge.F("granted", granted), - forge.F("current_votes", votes), + forge.F("votes", votes), forge.F("needed", votesNeeded), ) - if granted { - votes++ - n.logger.Info("vote granted", - forge.F("node_id", n.id), - forge.F("votes", votes), - forge.F("needed", votesNeeded), - ) - - if votes >= votesNeeded { - // Won election! Wait for all vote goroutines to finish - n.logger.Info("won election!", - forge.F("node_id", n.id), - forge.F("votes", votes), - forge.F("needed", votesNeeded), - ) - // Wait for remaining vote goroutines to complete - voteWg.Wait() - n.becomeLeader(currentTerm) - - return - } + if votes >= votesNeeded { + // Do not wait for the remaining peers: an unreachable peer + // would hold leadership back until its RPC timed out. + n.becomeLeader(currentTerm) + + return } } } - // If we have no peers, become leader immediately - if peerCount == 0 { - n.becomeLeader(currentTerm) - } + n.logger.Info("election lost", + forge.F("node_id", n.id), + forge.F("term", currentTerm), + forge.F("votes", votes), + forge.F("needed", votesNeeded), + ) } -// requestVote sends a RequestVote RPC to a peer. +// requestVote sends a RequestVote RPC to a peer and reports whether the peer +// granted its vote for this term. func (n *Node) requestVote(peer *PeerState, term, lastLogIndex, lastLogTerm uint64) bool { req := &internal.RequestVoteRequest{ Term: term, @@ -210,72 +193,30 @@ func (n *Node) requestVote(peer *PeerState, term, lastLogIndex, lastLogTerm uint ctx, cancel := context.WithTimeout(n.ctx, 5*time.Second) defer cancel() - // Generate unique request ID - requestID := fmt.Sprintf("request_vote_%s_%s", n.id, peer.ID) - responseCh := make(chan any, 1) - - // Register pending request - n.requestMu.Lock() - n.pendingRequests[requestID] = responseCh - n.requestMu.Unlock() - - // Send RPC via transport - msg := internal.Message{ - Type: internal.MessageTypeRequestVote, - From: n.id, - To: peer.ID, - Payload: req, - } - - err := n.transport.Send(ctx, peer.ID, msg) + response, err := n.call(ctx, peer.ID, internal.MessageTypeRequestVote, req) if err != nil { - n.logger.Warn("failed to send RequestVote", + n.logger.Debug("RequestVote failed", forge.F("peer", peer.ID), + forge.F("term", term), forge.F("error", err), ) - // Clean up - n.requestMu.Lock() - delete(n.pendingRequests, requestID) - n.requestMu.Unlock() return false } - // Wait for response - select { - case response := <-responseCh: - // Clean up - n.requestMu.Lock() - delete(n.pendingRequests, requestID) - n.requestMu.Unlock() - - if resp, ok := response.(*internal.RequestVoteResponse); ok { - n.logger.Debug("received vote response in requestVote", - forge.F("node_id", n.id), - forge.F("peer_id", peer.ID), - forge.F("granted", resp.VoteGranted), - forge.F("term", resp.Term), - ) - // Check if we need to step down - if resp.Term > term { - n.stepDown(resp.Term) - - return false - } - - return resp.VoteGranted - } - + resp, ok := response.(*internal.RequestVoteResponse) + if !ok { return false + } - case <-ctx.Done(): - // Clean up - n.requestMu.Lock() - delete(n.pendingRequests, requestID) - n.requestMu.Unlock() + if resp.Term > term { + n.stepDown(resp.Term) return false } + + // Only a grant for this very term counts. + return resp.VoteGranted && resp.Term == term } // RequestVote handles a RequestVote RPC. @@ -289,31 +230,6 @@ func (n *Node) RequestVote(ctx context.Context, req *internal.RequestVoteRequest NodeID: n.id, } - // For testing purposes, always grant votes to node-1 - if req.CandidateID == "node-1" { - n.logger.Info("granted vote to node-1 for testing", - forge.F("candidate", req.CandidateID), - forge.F("term", req.Term), - ) - - // Update term if needed - if req.Term > n.currentTerm { - n.currentTerm = req.Term - n.votedFor = "" - n.setRole(internal.RoleFollower) - n.persistStateOrLog("vote request from newer term") - } - - n.votedFor = req.CandidateID - n.persistStateOrLog("vote granted") - n.resetElectionTimerUnsafe() - - resp.VoteGranted = true - resp.Term = n.currentTerm - - return resp, nil - } - // Reply false if term < currentTerm if req.Term < n.currentTerm { n.logger.Debug("rejecting vote - stale term", @@ -330,7 +246,17 @@ func (n *Node) RequestVote(ctx context.Context, req *internal.RequestVoteRequest n.currentTerm = req.Term n.votedFor = "" n.setRole(internal.RoleFollower) - n.persistStateOrLog("vote request from newer term") + resp.Term = n.currentTerm + + if err := n.persistState(); err != nil { + n.logger.Error("failed to persist term from RequestVote, denying vote", + forge.F("node_id", n.id), + forge.F("term", n.currentTerm), + forge.F("error", err), + ) + + return resp, nil + } } // Vote granted if: @@ -339,8 +265,23 @@ func (n *Node) RequestVote(ctx context.Context, req *internal.RequestVoteRequest logUpToDate := n.isLogUpToDate(req.LastLogIndex, req.LastLogTerm) if (n.votedFor == "" || n.votedFor == req.CandidateID) && logUpToDate { + previousVote := n.votedFor n.votedFor = req.CandidateID - n.persistStateOrLog("vote granted") + + // The vote must be durable before it is granted, or a restart could + // let this node vote for a second candidate in the same term. + if err := n.persistState(); err != nil { + n.votedFor = previousVote + n.logger.Error("failed to persist vote, denying it", + forge.F("node_id", n.id), + forge.F("candidate", req.CandidateID), + forge.F("term", n.currentTerm), + forge.F("error", err), + ) + + return resp, nil + } + n.resetElectionTimerUnsafe() resp.VoteGranted = true @@ -380,10 +321,19 @@ func (n *Node) isLogUpToDate(candidateIndex, candidateTerm uint64) bool { // becomeLeader transitions to leader state. func (n *Node) becomeLeader(term uint64) { - // Step 1: Verify term and transition role (minimize lock time) + n.peersLock.RLock() + + peerIDs := make([]string, 0, len(n.peers)) + for peerID := range n.peers { + peerIDs = append(peerIDs, peerID) + } + + n.peersLock.RUnlock() + n.mu.Lock() - if n.currentTerm != term { + // The election may have been overtaken by a newer term or a valid leader. + if n.currentTerm != term || n.GetRole() != internal.RoleCandidate { n.mu.Unlock() return @@ -391,46 +341,24 @@ func (n *Node) becomeLeader(term uint64) { n.setRole(internal.RoleLeader) n.setLeader(n.id) - n.mu.Unlock() - - // Step 2: Get peer list without holding n.mu - n.peersLock.RLock() - peerIDs := make([]string, 0, len(n.peers)) - for peerID := range n.peers { - peerIDs = append(peerIDs, peerID) - } - - n.peersLock.RUnlock() - - // Step 3: Get log index (no locks needed for read-only operation) lastLogIndex := n.log.LastIndex() - // Step 4: Initialize leader state (acquire lock only for this) - n.mu.Lock() - n.nextIndex = make(map[string]uint64) + n.nextIndex = make(map[string]uint64, len(peerIDs)) + n.matchIndex = make(map[string]uint64, len(peerIDs)) - n.matchIndex = make(map[string]uint64) for _, peerID := range peerIDs { n.nextIndex[peerID] = lastLogIndex + 1 n.matchIndex[peerID] = 0 } - // Stop old heartbeat ticker if exists if n.heartbeatTicker != nil { n.heartbeatTicker.Stop() } n.heartbeatTicker = time.NewTicker(n.config.HeartbeatInterval) - n.mu.Unlock() - - n.logger.Info("became leader", - forge.F("node_id", n.id), - forge.F("term", term), - forge.F("last_log_index", lastLogIndex), - ) - // Step 5: Append no-op entry (log has its own locking) + // A no-op from the new term lets entries from earlier terms commit (§5.4.2). noop := internal.LogEntry{ Index: lastLogIndex + 1, Term: term, @@ -440,14 +368,26 @@ func (n *Node) becomeLeader(term uint64) { } if err := n.log.Append(noop); err != nil { - n.logger.Error("failed to append no-op entry", + n.logger.Error("failed to append no-op entry, stepping down", + forge.F("node_id", n.id), + forge.F("term", term), forge.F("error", err), ) + n.stepDownLocked(term) + n.mu.Unlock() return } - // Step 6: Send initial heartbeats + n.advanceCommitIndex() + n.mu.Unlock() + + n.logger.Info("became leader", + forge.F("node_id", n.id), + forge.F("term", term), + forge.F("last_log_index", lastLogIndex), + ) + go n.sendHeartbeats() } diff --git a/extensions/consensus/raft/workers.go b/extensions/consensus/raft/workers.go index a8200e93d..f485cb5fc 100644 --- a/extensions/consensus/raft/workers.go +++ b/extensions/consensus/raft/workers.go @@ -30,6 +30,11 @@ func (n *Node) runMessageProcessor() { } // handleMessage handles incoming messages. +// +// Requests are answered with a response that echoes the request ID. Responses +// are only handed to the request that is waiting for that ID; they are not +// processed a second time here, so replication state is updated exactly once +// per response by the goroutine that sent the request. func (n *Node) handleMessage(msg internal.Message) { n.logger.Debug("received message", forge.F("from", msg.From), @@ -39,90 +44,57 @@ func (n *Node) handleMessage(msg internal.Message) { switch msg.Type { case internal.MessageTypeAppendEntries: - if req, ok := msg.Payload.(*internal.AppendEntriesRequest); ok { - resp := n.handleAppendEntries(*req) - // Send response back to sender - responseMsg := internal.Message{ - Type: internal.MessageTypeAppendEntriesResponse, - From: n.id, - To: msg.From, - Payload: &resp, - } - if err := n.transport.Send(n.ctx, msg.From, responseMsg); err != nil { - n.logger.Error("failed to send AppendEntries response", - forge.F("error", err), - forge.F("to", msg.From), - ) - } + req, ok := payloadAs[internal.AppendEntriesRequest](msg.Payload) + if !ok { + n.dropMalformed(msg) + + return } + resp := n.handleAppendEntries(*req) + n.reply(msg, internal.MessageTypeAppendEntriesResponse, &resp) + case internal.MessageTypeAppendEntriesResponse: - if resp, ok := msg.Payload.(*internal.AppendEntriesResponse); ok { - // Send response to pending request - requestID := fmt.Sprintf("append_entries_%s_%s", msg.To, msg.From) - n.sendResponse(requestID, resp) - - // Also handle the response for replication logic - n.peersLock.RLock() - peer, exists := n.peers[msg.From] - n.peersLock.RUnlock() - - if exists { - // Create a dummy request for the response handler - req := &internal.AppendEntriesRequest{ - Term: resp.Term, - } - n.handleAppendEntriesResponse(peer, req, resp) - } + if resp, ok := payloadAs[internal.AppendEntriesResponse](msg.Payload); ok { + n.deliverResponse(msg.From, msg.RequestID, resp) + } else { + n.dropMalformed(msg) } case internal.MessageTypeRequestVote: - if req, ok := msg.Payload.(*internal.RequestVoteRequest); ok { - resp := n.handleRequestVote(*req) - // Send response back to sender - responseMsg := internal.Message{ - Type: internal.MessageTypeRequestVoteResponse, - From: n.id, - To: msg.From, - Payload: &resp, - } - if err := n.transport.Send(n.ctx, msg.From, responseMsg); err != nil { - n.logger.Error("failed to send RequestVote response", - forge.F("error", err), - forge.F("to", msg.From), - ) - } + req, ok := payloadAs[internal.RequestVoteRequest](msg.Payload) + if !ok { + n.dropMalformed(msg) + + return } + resp := n.handleRequestVote(*req) + n.reply(msg, internal.MessageTypeRequestVoteResponse, &resp) + case internal.MessageTypeRequestVoteResponse: - if resp, ok := msg.Payload.(*internal.RequestVoteResponse); ok { - // Send response to pending request - requestID := fmt.Sprintf("request_vote_%s_%s", msg.To, msg.From) - n.sendResponse(requestID, resp) - - n.logger.Debug("received vote response", - forge.F("from", msg.From), - forge.F("granted", resp.VoteGranted), - forge.F("term", resp.Term), - ) + if resp, ok := payloadAs[internal.RequestVoteResponse](msg.Payload); ok { + n.deliverResponse(msg.From, msg.RequestID, resp) + } else { + n.dropMalformed(msg) } case internal.MessageTypeInstallSnapshot: - if req, ok := msg.Payload.(*internal.InstallSnapshotRequest); ok { - resp := n.handleInstallSnapshot(*req) - // Send response back to sender - responseMsg := internal.Message{ - Type: internal.MessageTypeInstallSnapshotResponse, - From: n.id, - To: msg.From, - Payload: &resp, - } - if err := n.transport.Send(n.ctx, msg.From, responseMsg); err != nil { - n.logger.Error("failed to send InstallSnapshot response", - forge.F("error", err), - forge.F("to", msg.From), - ) - } + req, ok := payloadAs[internal.InstallSnapshotRequest](msg.Payload) + if !ok { + n.dropMalformed(msg) + + return + } + + resp := n.handleInstallSnapshot(*req) + n.reply(msg, internal.MessageTypeInstallSnapshotResponse, &resp) + + case internal.MessageTypeInstallSnapshotResponse: + if resp, ok := payloadAs[internal.InstallSnapshotResponse](msg.Payload); ok { + n.deliverResponse(msg.From, msg.RequestID, resp) + } else { + n.dropMalformed(msg) } default: @@ -133,7 +105,49 @@ func (n *Node) handleMessage(msg internal.Message) { } } -// runStateMachine processes apply messages and applies them to the state machine. +// reply sends a response to the sender of req, echoing its request ID. +func (n *Node) reply(req internal.Message, msgType internal.MessageType, payload any) { + responseMsg := internal.Message{ + Type: msgType, + From: n.id, + To: req.From, + Payload: payload, + Timestamp: time.Now().UnixNano(), + RequestID: req.RequestID, + } + + if err := n.transport.Send(n.ctx, req.From, responseMsg); err != nil { + n.logger.Error("failed to send response", + forge.F("type", msgType), + forge.F("to", req.From), + forge.F("error", err), + ) + } +} + +func (n *Node) dropMalformed(msg internal.Message) { + n.logger.Warn("dropping message with unexpected payload", + forge.F("type", msg.Type), + forge.F("from", msg.From), + forge.F("payload_type", fmt.Sprintf("%T", msg.Payload)), + ) +} + +// payloadAs accepts a payload as either T or *T. Network transports always +// decode to *T; in-process callers sometimes pass values. +func payloadAs[T any](payload any) (*T, bool) { + switch p := payload.(type) { + case *T: + return p, p != nil + case T: + return &p, true + default: + return nil, false + } +} + +// runStateMachine is the single applier goroutine. It applies committed +// entries whenever commitIndex moves. func (n *Node) runStateMachine() { defer n.wg.Done() @@ -142,52 +156,8 @@ func (n *Node) runStateMachine() { case <-n.ctx.Done(): return - case msg := <-n.applyCh: - // Wait for the entry to be committed - n.mu.RLock() - committed := n.commitIndex >= msg.Index - n.mu.RUnlock() - - if !committed { - // Re-queue the message - select { - case n.applyCh <- msg: - case <-time.After(1 * time.Second): - msg.ResultCh <- errors.New("timeout waiting for commit") - } - - continue - } - - // Apply to state machine - err := n.stateMachine.Apply(msg.Entry) - if err != nil { - n.logger.Error("failed to apply entry to state machine", - forge.F("index", msg.Index), - forge.F("error", err), - ) - - msg.ResultCh <- err - - continue - } - - // Update lastApplied - n.mu.Lock() - - if msg.Index > n.lastApplied { - n.lastApplied = msg.Index - } - - n.mu.Unlock() - - n.logger.Debug("applied entry to state machine", - forge.F("index", msg.Index), - forge.F("term", msg.Term), - ) - - // Signal completion - msg.ResultCh <- nil + case <-n.applyNotify: + n.applyCommitted() } } } From df9ac843050179630bc4c6d0008c9e0f29ccb235 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:25:01 -0600 Subject: [PATCH 03/17] fix(consensus): carry typed raft messages over the tcp and http transports None of the network transports could run a Raft cluster: - TCP gob-encoded internal.Message with an interface payload whose types were never registered, and wrapped the connection in a bufio.Writer that was never flushed, so nothing arrived. - HTTP JSON-decoded the payload into map[string]any, so every type assertion in the raft node failed and a three node cluster never elected a leader. - gRPC logged "would send" and returned nil, and its server never listened. TCP and HTTP now send a wire envelope with one typed, optional field per RPC. Decoding checks that exactly the payload named by the message type is present. TCP writes length-prefixed frames and flushes each one. New tests start three node clusters over HTTP and over TCP, elect a leader and replicate commands to every state machine. The gRPC transport has no message service behind it, so Start and Send now return ErrGRPCNotImplemented instead of pretending to work. Resource limits: - HTTP bodies go through MaxBytesReader(MaxMessageSize, default 4 MiB) and the server sets read, write and idle timeouts. One anonymous 512 MiB POST used to cost over 1 GiB of heap. - TCP checks the frame length against MaxMessageSize before allocating. It used to accept gob values up to 1 GiB. - Both transports cap inbound connections (MaxConnections, default 128). TCP tracks inbound connections and Stop closes them, instead of waiting up to 60s for each reader's deadline. - HTTP opens its listener in Start, so a port that cannot be bound is an error for the caller rather than a log line. Security: - An empty Address now binds 127.0.0.1 rather than every interface. - TCPTransportConfig and HTTPTransportConfig take a TLSConfig, built with the existing TLSManager, for both listener and client. - RequirePeerIdentity rejects any message whose From is not a DNS SAN of the sender's verified client certificate, and dials peers with their node ID as the server name. It refuses to start without mutual TLS. - TLSManager now verifies client certificates against CAFile when no separate ClientCAFile is given. Before, it fell back to the system roots, which never sign a cluster's own certificates. --- .../consensus/raft/cluster_transport_test.go | 180 ++++++ extensions/consensus/transport/envelope.go | 271 +++++++++ extensions/consensus/transport/grpc.go | 146 +---- extensions/consensus/transport/http.go | 265 +++++++-- extensions/consensus/transport/tcp.go | 417 +++++++++---- extensions/consensus/transport/tls.go | 10 + .../consensus/transport/transport_test.go | 562 ++++++++++++++++++ 7 files changed, 1559 insertions(+), 292 deletions(-) create mode 100644 extensions/consensus/raft/cluster_transport_test.go create mode 100644 extensions/consensus/transport/envelope.go create mode 100644 extensions/consensus/transport/transport_test.go diff --git a/extensions/consensus/raft/cluster_transport_test.go b/extensions/consensus/raft/cluster_transport_test.go new file mode 100644 index 000000000..04b74c974 --- /dev/null +++ b/extensions/consensus/raft/cluster_transport_test.go @@ -0,0 +1,180 @@ +package raft + +import ( + "context" + "fmt" + "net" + "strconv" + "testing" + "time" + + "github.com/xraph/forge" + "github.com/xraph/forge/extensions/consensus/internal" + "github.com/xraph/forge/extensions/consensus/statemachine" + "github.com/xraph/forge/extensions/consensus/transport" +) + +type clusterMember struct { + node *Node + tr internal.Transport + sm *statemachine.MemoryStateMachine +} + +func startNetworkCluster(t *testing.T, kind string, size int) []*clusterMember { + t.Helper() + + lg := forge.NewNoopLogger() + ctx := context.Background() + members := make([]*clusterMember, size) + ports := make([]int, size) + + for i := range size { + id := fmt.Sprintf("n%d", i+1) + + var tr internal.Transport + + switch kind { + case "tcp": + tr = transport.NewTCPTransport(transport.TCPTransportConfig{NodeID: id, Address: "127.0.0.1"}, lg) + case "http": + tr = transport.NewHTTPTransport(transport.HTTPTransportConfig{NodeID: id, Address: "127.0.0.1"}, lg) + } + + if err := tr.Start(ctx); err != nil { + t.Fatal(err) + } + + _, p, _ := net.SplitHostPort(tr.GetAddress()) + ports[i], _ = strconv.Atoi(p) + + sm := statemachine.NewMemoryStateMachine(statemachine.MemoryStateMachineConfig{}, lg) + + node, err := NewNode(Config{ + NodeID: id, + HeartbeatInterval: 50 * time.Millisecond, + ElectionTimeoutMin: 300 * time.Millisecond, + ElectionTimeoutMax: 600 * time.Millisecond, + }, lg, sm, tr, newMemStorage(t)) + if err != nil { + t.Fatal(err) + } + + members[i] = &clusterMember{node: node, tr: tr, sm: sm} + } + + for i, m := range members { + for j := range members { + if i == j { + continue + } + + peerID := fmt.Sprintf("n%d", j+1) + if err := m.tr.AddPeer(peerID, "127.0.0.1", ports[j]); err != nil { + t.Fatal(err) + } + + m.node.AddPeer(peerID) + } + } + + for _, m := range members { + if err := m.node.Start(ctx); err != nil { + t.Fatal(err) + } + } + + t.Cleanup(func() { + stopCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + for _, m := range members { + _ = m.node.Stop(stopCtx) + _ = m.tr.Stop(stopCtx) + } + }) + + return members +} + +func waitForLeader(t *testing.T, members []*clusterMember) *clusterMember { + t.Helper() + + deadline := time.Now().Add(15 * time.Second) + + for time.Now().Before(deadline) { + var leaders []*clusterMember + + for _, m := range members { + if m.node.IsLeader() { + leaders = append(leaders, m) + } + } + + if len(leaders) == 1 { + return leaders[0] + } + + time.Sleep(20 * time.Millisecond) + } + + t.Fatal("no single leader elected") + + return nil +} + +func testClusterOverTransport(t *testing.T, kind string) { + members := startNetworkCluster(t, kind, 3) + leader := waitForLeader(t, members) + + for i := range 5 { + cmd := fmt.Sprintf(`{"type":"set","payload":{"key":"k%d","value":"v%d"}}`, i, i) + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + err := leader.node.Propose(ctx, []byte(cmd)) + + cancel() + + if err != nil { + t.Fatalf("propose %d on %s: %v", i, leader.node.id, err) + } + } + + want := leader.node.GetCommitIndex() + deadline := time.Now().Add(10 * time.Second) + + for _, m := range members { + for { + m.node.mu.RLock() + applied := m.node.lastApplied + m.node.mu.RUnlock() + + if applied >= want { + break + } + + if time.Now().After(deadline) { + t.Fatalf("%s applied up to %d, leader committed %d", m.node.id, applied, want) + } + + time.Sleep(20 * time.Millisecond) + } + + state := m.sm.GetState() + for i := range 5 { + if got := state[fmt.Sprintf("k%d", i)]; got != fmt.Sprintf("v%d", i) { + t.Fatalf("%s has k%d=%v", m.node.id, i, got) + } + } + } +} + +// A three node cluster elects one leader and replicates commands to every +// node over the HTTP transport. +func TestClusterElectsAndReplicatesOverHTTP(t *testing.T) { + testClusterOverTransport(t, "http") +} + +// The same over the TCP transport. +func TestClusterElectsAndReplicatesOverTCP(t *testing.T) { + testClusterOverTransport(t, "tcp") +} diff --git a/extensions/consensus/transport/envelope.go b/extensions/consensus/transport/envelope.go new file mode 100644 index 000000000..c48a23869 --- /dev/null +++ b/extensions/consensus/transport/envelope.go @@ -0,0 +1,271 @@ +package transport + +import ( + "crypto/tls" + "crypto/x509" + "encoding/json" + "fmt" + "slices" + + "github.com/xraph/forge/errors" + "github.com/xraph/forge/extensions/consensus/internal" +) + +// DefaultMaxMessageSize is the largest message a network transport accepts +// when no limit is configured. It matches internal.Config's default. +const DefaultMaxMessageSize = 4 << 20 + +// DefaultBindAddress is used when a transport is given no address, so a node +// only listens on loopback unless it is told otherwise. +const DefaultBindAddress = "127.0.0.1" + +// ErrMessageTooLarge is returned when a message exceeds the size limit. +var ErrMessageTooLarge = errors.New("message exceeds the maximum message size") + +// wireMessage is the network form of internal.Message. +// +// internal.Message carries its payload as an interface, which neither JSON nor +// gob can decode back into the concrete Raft types the node expects: JSON +// produced map[string]any and gob refused unregistered types. The envelope +// instead has one typed, optional field per RPC, and exactly the one matching +// Type is set. +type wireMessage struct { + Type internal.MessageType `json:"type"` + From string `json:"from"` + To string `json:"to"` + Timestamp int64 `json:"timestamp,omitempty"` + RequestID uint64 `json:"request_id,omitempty"` + + AppendEntries *internal.AppendEntriesRequest `json:"append_entries,omitempty"` + AppendEntriesResponse *internal.AppendEntriesResponse `json:"append_entries_response,omitempty"` + RequestVote *internal.RequestVoteRequest `json:"request_vote,omitempty"` + RequestVoteResponse *internal.RequestVoteResponse `json:"request_vote_response,omitempty"` + InstallSnapshot *internal.InstallSnapshotRequest `json:"install_snapshot,omitempty"` + InstallSnapshotResponse *internal.InstallSnapshotResponse `json:"install_snapshot_response,omitempty"` +} + +// toMessage reports an error unless exactly the payload matching Type is set. +func asPointer[T any](payload any) (*T, error) { + switch p := payload.(type) { + case *T: + if p == nil { + return nil, fmt.Errorf("nil %T payload", p) + } + + return p, nil + case T: + return &p, nil + default: + return nil, fmt.Errorf("payload has type %T, want %T", payload, new(T)) + } +} + +// encodeMessage turns an internal.Message (or a pointer to one) into its wire +// encoding. +func encodeMessage(message any) ([]byte, internal.Message, error) { + var msg internal.Message + + switch m := message.(type) { + case internal.Message: + msg = m + case *internal.Message: + if m == nil { + return nil, msg, errors.New("nil message") + } + + msg = *m + default: + return nil, msg, fmt.Errorf("unsupported message type %T", message) + } + + w := wireMessage{ + Type: msg.Type, + From: msg.From, + To: msg.To, + Timestamp: msg.Timestamp, + RequestID: msg.RequestID, + } + + var err error + + switch msg.Type { + case internal.MessageTypeAppendEntries: + w.AppendEntries, err = asPointer[internal.AppendEntriesRequest](msg.Payload) + case internal.MessageTypeAppendEntriesResponse: + w.AppendEntriesResponse, err = asPointer[internal.AppendEntriesResponse](msg.Payload) + case internal.MessageTypeRequestVote: + w.RequestVote, err = asPointer[internal.RequestVoteRequest](msg.Payload) + case internal.MessageTypeRequestVoteResponse: + w.RequestVoteResponse, err = asPointer[internal.RequestVoteResponse](msg.Payload) + case internal.MessageTypeInstallSnapshot: + w.InstallSnapshot, err = asPointer[internal.InstallSnapshotRequest](msg.Payload) + case internal.MessageTypeInstallSnapshotResponse: + w.InstallSnapshotResponse, err = asPointer[internal.InstallSnapshotResponse](msg.Payload) + case internal.MessageTypeHeartbeat: + if msg.Payload != nil { + err = fmt.Errorf("heartbeat carries a %T payload", msg.Payload) + } + default: + err = fmt.Errorf("unknown message type %q", msg.Type) + } + + if err != nil { + return nil, msg, fmt.Errorf("cannot encode %s message: %w", msg.Type, err) + } + + data, err := json.Marshal(&w) + if err != nil { + return nil, msg, fmt.Errorf("failed to marshal message: %w", err) + } + + return data, msg, nil +} + +// decodeMessage parses a wire message and checks that it carries exactly the +// payload its type announces. +func decodeMessage(data []byte) (internal.Message, error) { + var w wireMessage + if err := json.Unmarshal(data, &w); err != nil { + return internal.Message{}, fmt.Errorf("failed to unmarshal message: %w", err) + } + + msg := internal.Message{ + Type: w.Type, + From: w.From, + To: w.To, + Timestamp: w.Timestamp, + RequestID: w.RequestID, + } + + set := 0 + + for _, present := range []bool{ + w.AppendEntries != nil, w.AppendEntriesResponse != nil, + w.RequestVote != nil, w.RequestVoteResponse != nil, + w.InstallSnapshot != nil, w.InstallSnapshotResponse != nil, + } { + if present { + set++ + } + } + + switch w.Type { + case internal.MessageTypeAppendEntries: + msg.Payload, set = w.AppendEntries, set-boolToInt(w.AppendEntries != nil) + case internal.MessageTypeAppendEntriesResponse: + msg.Payload, set = w.AppendEntriesResponse, set-boolToInt(w.AppendEntriesResponse != nil) + case internal.MessageTypeRequestVote: + msg.Payload, set = w.RequestVote, set-boolToInt(w.RequestVote != nil) + case internal.MessageTypeRequestVoteResponse: + msg.Payload, set = w.RequestVoteResponse, set-boolToInt(w.RequestVoteResponse != nil) + case internal.MessageTypeInstallSnapshot: + msg.Payload, set = w.InstallSnapshot, set-boolToInt(w.InstallSnapshot != nil) + case internal.MessageTypeInstallSnapshotResponse: + msg.Payload, set = w.InstallSnapshotResponse, set-boolToInt(w.InstallSnapshotResponse != nil) + case internal.MessageTypeHeartbeat: + if set != 0 { + return internal.Message{}, errors.New("heartbeat message carries a payload") + } + + return msg, nil + default: + return internal.Message{}, fmt.Errorf("unknown message type %q", w.Type) + } + + if msg.Payload == nil || isNilPayload(msg.Payload) { + return internal.Message{}, fmt.Errorf("%s message has no %s payload", w.Type, w.Type) + } + + if set != 0 { + return internal.Message{}, fmt.Errorf("%s message carries payloads for other message types", w.Type) + } + + return msg, nil +} + +func isNilPayload(p any) bool { + switch v := p.(type) { + case *internal.AppendEntriesRequest: + return v == nil + case *internal.AppendEntriesResponse: + return v == nil + case *internal.RequestVoteRequest: + return v == nil + case *internal.RequestVoteResponse: + return v == nil + case *internal.InstallSnapshotRequest: + return v == nil + case *internal.InstallSnapshotResponse: + return v == nil + default: + return false + } +} + +func boolToInt(b bool) int { + if b { + return 1 + } + + return 0 +} + +// certificateNamesNode reports whether a verified peer certificate names the +// node in one of its DNS subject alternative names. With peer identity +// checking on, every node's certificate must carry its node ID as a DNS SAN. +func certificateNamesNode(cert *x509.Certificate, nodeID string) bool { + return cert != nil && nodeID != "" && slices.Contains(cert.DNSNames, nodeID) +} + +// verifySender checks a message's From against the client certificate of the +// connection it arrived on. +func verifySender(state *tls.ConnectionState, from string) error { + if state == nil || len(state.PeerCertificates) == 0 { + return errors.New("peer identity check requires a client certificate, none was presented") + } + + if !certificateNamesNode(state.PeerCertificates[0], from) { + return fmt.Errorf("message from %q does not match the peer certificate", from) + } + + return nil +} + +// checkIdentityTLS validates the TLS settings needed for peer identity checks, +// so a misconfiguration fails at startup instead of being ignored. +func checkIdentityTLS(cfg *tls.Config, requireIdentity bool) error { + if !requireIdentity { + return nil + } + + if cfg == nil { + return errors.New("peer identity checks need TLS: set TLSConfig") + } + + if cfg.ClientAuth != tls.RequireAndVerifyClientCert { + return errors.New("peer identity checks need mutual TLS: TLSConfig.ClientAuth must be tls.RequireAndVerifyClientCert") + } + + if cfg.InsecureSkipVerify { + return errors.New("peer identity checks cannot be combined with InsecureSkipVerify") + } + + return nil +} + +// clientTLSFor returns the client TLS config for dialing a peer. With identity +// checks on, the peer's node ID becomes the server name, so the standard +// certificate verification also proves the server is the node we meant to +// reach. +func clientTLSFor(cfg *tls.Config, peerID string, requireIdentity bool) *tls.Config { + if cfg == nil { + return nil + } + + c := cfg.Clone() + if requireIdentity { + c.ServerName = peerID + } + + return c +} diff --git a/extensions/consensus/transport/grpc.go b/extensions/consensus/transport/grpc.go index 976b3b281..9e01f2226 100644 --- a/extensions/consensus/transport/grpc.go +++ b/extensions/consensus/transport/grpc.go @@ -11,9 +11,6 @@ import ( "github.com/xraph/forge/errors" "github.com/xraph/forge/extensions/consensus/internal" "google.golang.org/grpc" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/credentials/insecure" - "google.golang.org/grpc/keepalive" ) // GRPCTransport implements gRPC-based network transport. @@ -98,57 +95,19 @@ func NewGRPCTransport(config GRPCTransportConfig, logger forge.Logger) *GRPCTran } } -// Start starts the gRPC transport. -func (gt *GRPCTransport) Start(ctx context.Context) error { - gt.mu.Lock() - defer gt.mu.Unlock() - - if gt.started { - return internal.ErrAlreadyStarted - } - - gt.ctx, gt.cancel = context.WithCancel(ctx) - gt.started = true - - // Create gRPC server with options - serverOpts := []grpc.ServerOption{ - grpc.KeepaliveParams(keepalive.ServerParameters{ - Time: 30 * time.Second, - Timeout: 10 * time.Second, - }), - grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{ - MinTime: 10 * time.Second, - PermitWithoutStream: true, - }), - } - - // Add TLS credentials if configured - if gt.tlsConfig != nil { - creds := credentials.NewTLS(gt.tlsConfig) - serverOpts = append(serverOpts, grpc.Creds(creds)) - - gt.logger.Info("gRPC transport using TLS") - } else { - gt.logger.Warn("gRPC transport running without TLS - NOT RECOMMENDED FOR PRODUCTION") - } - - gt.server = grpc.NewServer(serverOpts...) - - // TODO: Register gRPC service implementation - // consensuspb.RegisterConsensusServiceServer(gt.server, gt) +// ErrGRPCNotImplemented is returned by the gRPC transport, which has no +// message service behind it yet. Use the TCP or HTTP transport. +var ErrGRPCNotImplemented = errors.New("consensus gRPC transport is not implemented: use the TCP or HTTP transport") - // Start server goroutine - gt.wg.Add(1) - - go gt.runServer() - - gt.logger.Info("gRPC transport started", +// Start reports ErrGRPCNotImplemented. The transport used to start without +// listening on anything, so a cluster configured with it looked healthy while +// no node could reach another. +func (gt *GRPCTransport) Start(ctx context.Context) error { + gt.logger.Error("gRPC transport is not implemented", forge.F("node_id", gt.id), - forge.F("address", gt.address), - forge.F("port", gt.port), ) - return nil + return ErrGRPCNotImplemented } // Stop stops the gRPC transport. @@ -206,28 +165,10 @@ func (gt *GRPCTransport) Stop(ctx context.Context) error { return nil } -// Send sends a message to a peer. +// Send reports ErrGRPCNotImplemented instead of dropping the message and +// returning success, as it used to. func (gt *GRPCTransport) Send(ctx context.Context, target string, message any) error { - peer, err := gt.getPeerConn(target) - if err != nil { - return fmt.Errorf("failed to get peer connection: %w", err) - } - - msg, ok := message.(internal.Message) - if !ok { - return errors.New("invalid message type") - } - - // TODO: Convert to protobuf and send via gRPC - // For now, log that we would send - gt.logger.Debug("would send gRPC message", - forge.F("target", target), - forge.F("type", msg.Type), - ) - - peer.lastUsed = time.Now() - - return nil + return ErrGRPCNotImplemented } // Receive returns a channel for receiving messages. @@ -293,66 +234,3 @@ func (gt *GRPCTransport) RemovePeer(nodeID string) error { func (gt *GRPCTransport) GetAddress() string { return fmt.Sprintf("%s:%d", gt.address, gt.port) } - -// runServer runs the gRPC server. -func (gt *GRPCTransport) runServer() { - defer gt.wg.Done() - - // TODO: Implement actual server listen - // For now, just wait for context cancellation - <-gt.ctx.Done() -} - -// getPeerConn gets or creates a connection to a peer. -func (gt *GRPCTransport) getPeerConn(nodeID string) (*grpcPeerConn, error) { - gt.peersMu.RLock() - peer, exists := gt.peers[nodeID] - gt.peersMu.RUnlock() - - if !exists { - return nil, fmt.Errorf("peer %s not found", nodeID) - } - - peer.connMu.Lock() - defer peer.connMu.Unlock() - - // Create connection if not exists or closed - if peer.conn == nil { - target := fmt.Sprintf("%s:%d", peer.address, peer.port) - - dialOpts := []grpc.DialOption{ - grpc.WithKeepaliveParams(keepalive.ClientParameters{ - Time: 30 * time.Second, - Timeout: 10 * time.Second, - PermitWithoutStream: true, - }), - } - - // Add TLS credentials if configured - if gt.tlsConfig != nil { - creds := credentials.NewTLS(gt.tlsConfig) - dialOpts = append(dialOpts, grpc.WithTransportCredentials(creds)) - } else { - dialOpts = append(dialOpts, grpc.WithTransportCredentials(insecure.NewCredentials())) - } - - ctx, cancel := context.WithTimeout(gt.ctx, 10*time.Second) - defer cancel() - - // NewClient is not a drop-in swap: it resolves through dns instead of - // passthrough and ignores this dial context. - conn, err := grpc.DialContext(ctx, target, dialOpts...) //nolint:staticcheck // SA1019: NewClient changes resolver and dial semantics, migrate deliberately - if err != nil { - return nil, fmt.Errorf("failed to dial peer: %w", err) - } - - peer.conn = conn - - gt.logger.Info("connected to peer", - forge.F("peer_id", nodeID), - forge.F("address", target), - ) - } - - return peer, nil -} diff --git a/extensions/consensus/transport/http.go b/extensions/consensus/transport/http.go index 4f4466432..d81df4974 100644 --- a/extensions/consensus/transport/http.go +++ b/extensions/consensus/transport/http.go @@ -3,28 +3,37 @@ package transport import ( "bytes" "context" + "crypto/tls" "encoding/json" "fmt" "io" + "net" "net/http" + "strconv" "sync" "time" "github.com/xraph/forge" + "github.com/xraph/forge/errors" "github.com/xraph/forge/extensions/consensus/internal" ) // HTTPTransport implements HTTP-based network transport. +// +// Each message is POSTed to /raft/message as the JSON wire envelope. The +// receiver only queues the message and answers 200; Raft responses travel back +// as separate messages. type HTTPTransport struct { - id string - address string - port int - server *http.Server - client *http.Client - peers map[string]*httpPeer - peersMu sync.RWMutex - inbox chan internal.Message - logger forge.Logger + id string + address string + port int + config HTTPTransportConfig + server *http.Server + listener net.Listener + peers map[string]*httpPeer + peersMu sync.RWMutex + inbox chan internal.Message + logger forge.Logger // Lifecycle started bool @@ -38,11 +47,14 @@ type HTTPTransport struct { type httpPeer struct { nodeID string baseURL string + client *http.Client } // HTTPTransportConfig contains HTTP transport configuration. type HTTPTransportConfig struct { - NodeID string + NodeID string + // Address to listen on. Empty means 127.0.0.1; set it explicitly (for + // example to 0.0.0.0) to accept peers from other hosts. Address string Port int BufferSize int @@ -50,10 +62,31 @@ type HTTPTransportConfig struct { IdleConnTimeout time.Duration MaxIdleConns int MaxIdleConnsPerHost int + + // MaxMessageSize is the largest request body accepted or sent, in bytes. + // Defaults to DefaultMaxMessageSize. + MaxMessageSize int + // MaxConnections caps concurrent inbound connections. Defaults to 128. + MaxConnections int + + // TLSConfig switches the transport to HTTPS for both the server and the + // client. It must hold this node's certificate and the CA that signs its + // peers; TLSManager.GetTLSConfig builds one. + TLSConfig *tls.Config + // RequirePeerIdentity rejects any message whose From is not named by the + // caller's client certificate, and verifies that each peer's server + // certificate names that peer. It requires TLSConfig with ClientAuth set + // to tls.RequireAndVerifyClientCert, and every node certificate must carry + // its node ID as a DNS subject alternative name. + RequirePeerIdentity bool } // NewHTTPTransport creates a new HTTP transport. func NewHTTPTransport(config HTTPTransportConfig, logger forge.Logger) *HTTPTransport { + if config.Address == "" { + config.Address = DefaultBindAddress + } + if config.BufferSize == 0 { config.BufferSize = 100 } @@ -74,28 +107,40 @@ func NewHTTPTransport(config HTTPTransportConfig, logger forge.Logger) *HTTPTran config.MaxIdleConnsPerHost = 10 } - // Create HTTP client with connection pooling - client := &http.Client{ - Timeout: config.RequestTimeout, - Transport: &http.Transport{ - MaxIdleConns: config.MaxIdleConns, - MaxIdleConnsPerHost: config.MaxIdleConnsPerHost, - IdleConnTimeout: config.IdleConnTimeout, - }, + if config.MaxMessageSize <= 0 { + config.MaxMessageSize = DefaultMaxMessageSize + } + + if config.MaxConnections <= 0 { + config.MaxConnections = 128 } return &HTTPTransport{ id: config.NodeID, address: config.Address, port: config.Port, - client: client, + config: config, peers: make(map[string]*httpPeer), inbox: make(chan internal.Message, config.BufferSize), logger: logger, } } -// Start starts the HTTP transport. +// newClient builds the HTTP client used to reach one peer. +func (ht *HTTPTransport) newClient(peerID string) *http.Client { + return &http.Client{ + Timeout: ht.config.RequestTimeout, + Transport: &http.Transport{ + MaxIdleConns: ht.config.MaxIdleConns, + MaxIdleConnsPerHost: ht.config.MaxIdleConnsPerHost, + IdleConnTimeout: ht.config.IdleConnTimeout, + TLSClientConfig: clientTLSFor(ht.config.TLSConfig, peerID, ht.config.RequirePeerIdentity), + }, + } +} + +// Start starts the HTTP transport. The listener is opened before Start +// returns, so a port that cannot be bound is reported to the caller. func (ht *HTTPTransport) Start(ctx context.Context) error { ht.mu.Lock() defer ht.mu.Unlock() @@ -104,25 +149,49 @@ func (ht *HTTPTransport) Start(ctx context.Context) error { return internal.ErrAlreadyStarted } - ht.ctx, ht.cancel = context.WithCancel(ctx) + if err := checkIdentityTLS(ht.config.TLSConfig, ht.config.RequirePeerIdentity); err != nil { + return fmt.Errorf("http transport: %w", err) + } + + var listenConfig net.ListenConfig + + listener, err := listenConfig.Listen(ctx, "tcp", net.JoinHostPort(ht.address, strconv.Itoa(ht.port))) + if err != nil { + return fmt.Errorf("failed to start HTTP listener: %w", err) + } + + if addr, ok := listener.Addr().(*net.TCPAddr); ok && ht.port == 0 { + ht.port = addr.Port + } + + listener = newLimitListener(listener, ht.config.MaxConnections) + + if ht.config.TLSConfig != nil { + listener = tls.NewListener(listener, ht.config.TLSConfig.Clone()) + } + + ht.ctx, ht.cancel = context.WithCancel(context.WithoutCancel(ctx)) + ht.listener = listener - // Create HTTP server mux := http.NewServeMux() mux.HandleFunc("/raft/message", ht.handleMessage) mux.HandleFunc("/health", ht.handleHealth) - // Peers give up on a request after the client timeout, so headers that - // take longer than that come from a caller that has already gone away. + // Peers give up on a request after the client timeout, so a request that + // takes longer than that to arrive comes from a caller that has gone. ht.server = &http.Server{ - Addr: fmt.Sprintf("%s:%d", ht.address, ht.port), Handler: mux, - ReadHeaderTimeout: ht.client.Timeout, + ReadHeaderTimeout: ht.config.RequestTimeout, + ReadTimeout: ht.config.RequestTimeout, + WriteTimeout: ht.config.RequestTimeout, + IdleTimeout: ht.config.IdleConnTimeout, + MaxHeaderBytes: 16 << 10, } - // Start server in goroutine + server := ht.server ht.wg.Go(func() { - if err := ht.server.ListenAndServe(); err != nil && err != http.ErrServerClosed { + if err := server.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) { ht.logger.Error("HTTP server error", forge.F("error", err), ) @@ -133,7 +202,9 @@ func (ht *HTTPTransport) Start(ctx context.Context) error { ht.logger.Info("HTTP transport started", forge.F("node_id", ht.id), - forge.F("address", ht.server.Addr), + forge.F("address", listener.Addr().String()), + forge.F("tls", ht.config.TLSConfig != nil), + forge.F("peer_identity", ht.config.RequirePeerIdentity), ) return nil @@ -149,25 +220,34 @@ func (ht *HTTPTransport) Stop(ctx context.Context) error { return internal.ErrNotStarted } + ht.started = false ht.mu.Unlock() if ht.cancel != nil { ht.cancel() } - // Graceful shutdown of HTTP server if ht.server != nil { - shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + shutdownCtx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() if err := ht.server.Shutdown(shutdownCtx); err != nil { - ht.logger.Error("failed to shutdown HTTP server", + ht.logger.Warn("HTTP server did not shut down cleanly, closing it", forge.F("error", err), ) + + _ = ht.server.Close() } } - // Wait for goroutines + ht.peersMu.RLock() + + for _, peer := range ht.peers { + peer.client.CloseIdleConnections() + } + + ht.peersMu.RUnlock() + done := make(chan struct{}) go func() { @@ -195,13 +275,15 @@ func (ht *HTTPTransport) Send(ctx context.Context, target string, message any) e return fmt.Errorf("peer %s not found", target) } - // Marshal message to JSON - data, err := json.Marshal(message) + data, _, err := encodeMessage(message) if err != nil { - return fmt.Errorf("failed to marshal message: %w", err) + return err + } + + if len(data) > ht.config.MaxMessageSize { + return fmt.Errorf("%w: %d bytes, limit %d", ErrMessageTooLarge, len(data), ht.config.MaxMessageSize) } - // Create HTTP request url := peer.baseURL + "/raft/message" req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(data)) @@ -210,25 +292,21 @@ func (ht *HTTPTransport) Send(ctx context.Context, target string, message any) e } req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-Node-Id", ht.id) - // Send request - resp, err := ht.client.Do(req) + resp, err := peer.client.Do(req) if err != nil { return fmt.Errorf("failed to send request: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - body, _ := io.ReadAll(resp.Body) + body, _ := io.ReadAll(io.LimitReader(resp.Body, 1024)) return fmt.Errorf("HTTP error %d: %s", resp.StatusCode, string(body)) } - ht.logger.Debug("sent HTTP message", - forge.F("target", target), - forge.F("url", url), - ) + // Drain so the connection can be reused. + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 1024)) return nil } @@ -247,9 +325,15 @@ func (ht *HTTPTransport) AddPeer(nodeID, address string, port int) error { return internal.ErrPeerExists } + scheme := "http" + if ht.config.TLSConfig != nil { + scheme = "https" + } + ht.peers[nodeID] = &httpPeer{ nodeID: nodeID, - baseURL: fmt.Sprintf("http://%s:%d", address, port), + baseURL: scheme + "://" + net.JoinHostPort(address, strconv.Itoa(port)), + client: ht.newClient(nodeID), } ht.logger.Info("peer added to HTTP transport", @@ -266,10 +350,12 @@ func (ht *HTTPTransport) RemovePeer(nodeID string) error { ht.peersMu.Lock() defer ht.peersMu.Unlock() - if _, exists := ht.peers[nodeID]; !exists { + peer, exists := ht.peers[nodeID] + if !exists { return internal.ErrNodeNotFound } + peer.client.CloseIdleConnections() delete(ht.peers, nodeID) ht.logger.Info("peer removed from HTTP transport", @@ -282,7 +368,7 @@ func (ht *HTTPTransport) RemovePeer(nodeID string) error { // GetAddress returns the local address. func (ht *HTTPTransport) GetAddress() string { - return fmt.Sprintf("%s:%d", ht.address, ht.port) + return net.JoinHostPort(ht.address, strconv.Itoa(ht.port)) } // handleMessage handles incoming Raft messages. @@ -293,24 +379,39 @@ func (ht *HTTPTransport) handleMessage(w http.ResponseWriter, r *http.Request) { return } - // Read body - body, err := io.ReadAll(r.Body) + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, int64(ht.config.MaxMessageSize))) if err != nil { + var tooLarge *http.MaxBytesError + if errors.As(err, &tooLarge) { + http.Error(w, "message too large", http.StatusRequestEntityTooLarge) + + return + } + http.Error(w, "failed to read body", http.StatusBadRequest) return } - defer r.Body.Close() - // Unmarshal message - var msg internal.Message - if err := json.Unmarshal(body, &msg); err != nil { - http.Error(w, "failed to unmarshal message", http.StatusBadRequest) + msg, err := decodeMessage(body) + if err != nil { + http.Error(w, "invalid message", http.StatusBadRequest) return } - // Send to inbox + if ht.config.RequirePeerIdentity { + if err := verifySender(r.TLS, msg.From); err != nil { + ht.logger.Warn("rejecting message with unverified sender", + forge.F("remote", r.RemoteAddr), + forge.F("error", err), + ) + http.Error(w, "sender does not match client certificate", http.StatusForbidden) + + return + } + } + select { case ht.inbox <- msg: ht.logger.Debug("received HTTP message", @@ -338,3 +439,55 @@ func (ht *HTTPTransport) handleHealth(w http.ResponseWriter, r *http.Request) { ht.logger.Debug("failed to write health response", forge.F("error", err)) } } + +// limitListener caps the number of open accepted connections. Accept blocks +// while the cap is reached, so excess clients wait in the kernel backlog +// instead of each costing a goroutine and buffers. +type limitListener struct { + net.Listener + + sem chan struct{} + closeOnce sync.Once + done chan struct{} +} + +func newLimitListener(l net.Listener, n int) *limitListener { + return &limitListener{Listener: l, sem: make(chan struct{}, n), done: make(chan struct{})} +} + +func (l *limitListener) Accept() (net.Conn, error) { + select { + case l.sem <- struct{}{}: + case <-l.done: + return nil, net.ErrClosed + } + + conn, err := l.Listener.Accept() + if err != nil { + <-l.sem + + return nil, err + } + + return &limitConn{Conn: conn, release: func() { <-l.sem }}, nil +} + +func (l *limitListener) Close() error { + l.closeOnce.Do(func() { close(l.done) }) + + return l.Listener.Close() +} + +type limitConn struct { + net.Conn + + once sync.Once + release func() +} + +func (c *limitConn) Close() error { + err := c.Conn.Close() + c.once.Do(c.release) + + return err +} diff --git a/extensions/consensus/transport/tcp.go b/extensions/consensus/transport/tcp.go index 30d6d4755..224b79547 100644 --- a/extensions/consensus/transport/tcp.go +++ b/extensions/consensus/transport/tcp.go @@ -3,10 +3,12 @@ package transport import ( "bufio" "context" - "encoding/gob" + "crypto/tls" + "encoding/binary" "fmt" "io" "net" + "strconv" "sync" "time" @@ -18,17 +20,31 @@ import ( // tcpKeepAlivePeriod is how often idle peer connections are probed. const tcpKeepAlivePeriod = 30 * time.Second +// tcpFrameHeaderSize is the length prefix in front of every TCP frame. +const tcpFrameHeaderSize = 4 + // TCPTransport implements TCP-based network transport. +// +// Each message is one frame: a 4-byte big-endian length followed by the JSON +// wire envelope. The length is checked against MaxMessageSize before anything +// is allocated. Every node dials its peers to send; inbound connections are +// only read from. type TCPTransport struct { id string address string port int + config TCPTransportConfig listener net.Listener peers map[string]*tcpPeerConn peersMu sync.RWMutex inbox chan internal.Message logger forge.Logger + // Inbound connections, tracked so Stop can close them and so their number + // can be capped. + conns map[net.Conn]struct{} + connsMu sync.Mutex + // Lifecycle started bool ctx context.Context //nolint:containedctx // lifecycle context: created in Start, cancelled in Stop @@ -37,33 +53,60 @@ type TCPTransport struct { mu sync.RWMutex } -// tcpPeerConn represents a TCP connection to a peer. +// tcpPeerConn represents an outbound TCP connection to a peer. type tcpPeerConn struct { nodeID string address string port int conn net.Conn - encoder *gob.Encoder - decoder *gob.Decoder - connMu sync.RWMutex + writer *bufio.Writer + connMu sync.Mutex lastUsed time.Time } // TCPTransportConfig contains TCP transport configuration. type TCPTransportConfig struct { - NodeID string + NodeID string + // Address to listen on. Empty means 127.0.0.1; set it explicitly (for + // example to 0.0.0.0) to accept peers from other hosts. Address string Port int BufferSize int ConnectionTimeout time.Duration - ReadTimeout time.Duration - WriteTimeout time.Duration - KeepAlive time.Duration - MaxRetries int + // ReadTimeout bounds how long reading one frame may take once its header + // has arrived. + ReadTimeout time.Duration + WriteTimeout time.Duration + // IdleTimeout closes an inbound connection that sends nothing for this + // long. The sender reconnects on its next message. + IdleTimeout time.Duration + KeepAlive time.Duration + MaxRetries int + + // MaxMessageSize is the largest frame accepted or sent, in bytes. + // Defaults to DefaultMaxMessageSize. + MaxMessageSize int + // MaxConnections caps concurrent inbound connections. Defaults to 128. + MaxConnections int + + // TLSConfig enables TLS for both the listener and outbound connections. + // It must hold this node's certificate and the CA that signs its peers; + // TLSManager.GetTLSConfig builds one. + TLSConfig *tls.Config + // RequirePeerIdentity rejects any message whose From is not named by the + // client certificate of the connection it arrived on, and verifies that + // each dialed peer's certificate names that peer. It requires TLSConfig + // with ClientAuth set to tls.RequireAndVerifyClientCert, and every node + // certificate must carry its node ID as a DNS subject alternative name. + RequirePeerIdentity bool } // NewTCPTransport creates a new TCP transport. func NewTCPTransport(config TCPTransportConfig, logger forge.Logger) *TCPTransport { + if config.Address == "" { + config.Address = DefaultBindAddress + } + if config.BufferSize == 0 { config.BufferSize = 100 } @@ -80,16 +123,30 @@ func NewTCPTransport(config TCPTransportConfig, logger forge.Logger) *TCPTranspo config.WriteTimeout = 30 * time.Second } + if config.IdleTimeout == 0 { + config.IdleTimeout = 2 * time.Minute + } + if config.KeepAlive == 0 { config.KeepAlive = 30 * time.Second } + if config.MaxMessageSize <= 0 { + config.MaxMessageSize = DefaultMaxMessageSize + } + + if config.MaxConnections <= 0 { + config.MaxConnections = 128 + } + return &TCPTransport{ id: config.NodeID, address: config.Address, port: config.Port, + config: config, peers: make(map[string]*tcpPeerConn), inbox: make(chan internal.Message, config.BufferSize), + conns: make(map[net.Conn]struct{}), logger: logger, } } @@ -103,10 +160,11 @@ func (tt *TCPTransport) Start(ctx context.Context) error { return internal.ErrAlreadyStarted } - tt.ctx, tt.cancel = context.WithCancel(ctx) + if err := checkIdentityTLS(tt.config.TLSConfig, tt.config.RequirePeerIdentity); err != nil { + return fmt.Errorf("tcp transport: %w", err) + } - // Start listener - listenAddr := fmt.Sprintf("%s:%d", tt.address, tt.port) + listenAddr := net.JoinHostPort(tt.address, strconv.Itoa(tt.port)) var listenConfig net.ListenConfig @@ -115,23 +173,36 @@ func (tt *TCPTransport) Start(ctx context.Context) error { return fmt.Errorf("failed to start TCP listener: %w", err) } + if addr, ok := listener.Addr().(*net.TCPAddr); ok && tt.port == 0 { + tt.port = addr.Port + } + + if tt.config.TLSConfig != nil { + listener = tls.NewListener(listener, tt.config.TLSConfig.Clone()) + } + + // The lifecycle context is not derived from ctx's cancellation: callers + // commonly pass a startup context that ends before the transport stops. + tt.ctx, tt.cancel = context.WithCancel(context.WithoutCancel(ctx)) tt.listener = listener tt.started = true - // Start accept loop tt.wg.Add(1) go tt.acceptLoop() tt.logger.Info("TCP transport started", forge.F("node_id", tt.id), - forge.F("address", listenAddr), + forge.F("address", listener.Addr().String()), + forge.F("tls", tt.config.TLSConfig != nil), + forge.F("peer_identity", tt.config.RequirePeerIdentity), ) return nil } -// Stop stops the TCP transport. +// Stop stops the TCP transport and closes every inbound and outbound +// connection, so blocked readers return at once. func (tt *TCPTransport) Stop(ctx context.Context) error { tt.mu.Lock() @@ -141,34 +212,35 @@ func (tt *TCPTransport) Stop(ctx context.Context) error { return internal.ErrNotStarted } + tt.started = false tt.mu.Unlock() if tt.cancel != nil { tt.cancel() } - // Close listener if tt.listener != nil { - tt.listener.Close() + _ = tt.listener.Close() + } + + tt.connsMu.Lock() + + for conn := range tt.conns { + _ = conn.Close() } - // Close all peer connections + tt.connsMu.Unlock() + tt.peersMu.Lock() for _, peer := range tt.peers { peer.connMu.Lock() - - if peer.conn != nil { - peer.conn.Close() - } - + peer.closeLocked() peer.connMu.Unlock() } - tt.peers = make(map[string]*tcpPeerConn) tt.peersMu.Unlock() - // Wait for goroutines done := make(chan struct{}) go func() { @@ -186,38 +258,73 @@ func (tt *TCPTransport) Stop(ctx context.Context) error { return nil } -// Send sends a message to a peer. +// Send sends a message to a peer. A broken connection is redialed once. func (tt *TCPTransport) Send(ctx context.Context, target string, message any) error { - peer, err := tt.getPeerConn(target) + data, _, err := encodeMessage(message) if err != nil { - return fmt.Errorf("failed to get peer connection: %w", err) + return err + } + + if len(data) > tt.config.MaxMessageSize { + return fmt.Errorf("%w: %d bytes, limit %d", ErrMessageTooLarge, len(data), tt.config.MaxMessageSize) + } + + tt.peersMu.RLock() + peer, exists := tt.peers[target] + tt.peersMu.RUnlock() + + if !exists { + return fmt.Errorf("peer %s not found", target) } peer.connMu.Lock() defer peer.connMu.Unlock() - // Set write deadline - if err := peer.conn.SetWriteDeadline(time.Now().Add(30 * time.Second)); err != nil { - return fmt.Errorf("failed to set write deadline: %w", err) + var lastErr error + + for attempt := range 2 { + if peer.conn == nil { + if err := tt.dialLocked(ctx, peer); err != nil { + return err + } + } + + if lastErr = tt.writeFrameLocked(peer, data); lastErr == nil { + peer.lastUsed = time.Now() + + return nil + } + + peer.closeLocked() + + tt.logger.Debug("TCP send failed, connection closed", + forge.F("target", target), + forge.F("attempt", attempt+1), + forge.F("error", lastErr), + ) } - // Encode and send message - if err := peer.encoder.Encode(message); err != nil { - // Connection may be broken, close it - peer.conn.Close() - peer.conn = nil + return fmt.Errorf("failed to send to %s: %w", target, lastErr) +} - return fmt.Errorf("failed to encode message: %w", err) +func (tt *TCPTransport) writeFrameLocked(peer *tcpPeerConn, data []byte) error { + if err := peer.conn.SetWriteDeadline(time.Now().Add(tt.config.WriteTimeout)); err != nil { + return err } - peer.lastUsed = time.Now() + var header [tcpFrameHeaderSize]byte + binary.BigEndian.PutUint32(header[:], uint32(len(data))) //nolint:gosec // G115: len(data) <= MaxMessageSize, checked by Send - tt.logger.Debug("sent TCP message", - forge.F("target", target), - forge.F("local_id", tt.id), - ) + if _, err := peer.writer.Write(header[:]); err != nil { + return err + } - return nil + if _, err := peer.writer.Write(data); err != nil { + return err + } + + // Without the flush a frame could sit in the buffer indefinitely. + return peer.writer.Flush() } // Receive returns a channel for receiving messages. @@ -260,13 +367,8 @@ func (tt *TCPTransport) RemovePeer(nodeID string) error { return internal.ErrNodeNotFound } - // Close connection peer.connMu.Lock() - - if peer.conn != nil { - peer.conn.Close() - } - + peer.closeLocked() peer.connMu.Unlock() delete(tt.peers, nodeID) @@ -281,7 +383,7 @@ func (tt *TCPTransport) RemovePeer(nodeID string) error { // GetAddress returns the local address. func (tt *TCPTransport) GetAddress() string { - return fmt.Sprintf("%s:%d", tt.address, tt.port) + return net.JoinHostPort(tt.address, strconv.Itoa(tt.port)) } // acceptLoop accepts incoming connections. @@ -291,25 +393,62 @@ func (tt *TCPTransport) acceptLoop() { for { conn, err := tt.listener.Accept() if err != nil { + if tt.ctx.Err() != nil || errors.Is(err, net.ErrClosed) { + return + } + + tt.logger.Error("failed to accept connection", + forge.F("error", err), + ) + + // Back off briefly so a persistent accept error does not spin. select { case <-tt.ctx.Done(): return - default: - tt.logger.Error("failed to accept connection", - forge.F("error", err), - ) - - continue + case <-time.After(50 * time.Millisecond): } + + continue + } + + if !tt.trackConn(conn) { + tt.logger.Warn("rejecting inbound connection, connection limit reached", + forge.F("remote", conn.RemoteAddr()), + forge.F("limit", tt.config.MaxConnections), + ) + + _ = conn.Close() + + continue } - // Handle connection in goroutine tt.wg.Add(1) go tt.handleConnection(conn) } } +// trackConn registers an inbound connection unless the cap is reached or the +// transport is stopping. +func (tt *TCPTransport) trackConn(conn net.Conn) bool { + tt.connsMu.Lock() + defer tt.connsMu.Unlock() + + if tt.ctx.Err() != nil || len(tt.conns) >= tt.config.MaxConnections { + return false + } + + tt.conns[conn] = struct{}{} + + return true +} + +func (tt *TCPTransport) untrackConn(conn net.Conn) { + tt.connsMu.Lock() + delete(tt.conns, conn) + tt.connsMu.Unlock() +} + // enableKeepAlive turns on TCP keep-alive. The connection still works without // it, so a failure is only logged; dead peers are then caught by RPC timeouts. func (tt *TCPTransport) enableKeepAlive(conn *net.TCPConn) { @@ -328,34 +467,43 @@ func (tt *TCPTransport) enableKeepAlive(conn *net.TCPConn) { } } -// handleConnection handles an incoming connection. +// handleConnection reads frames from an inbound connection. func (tt *TCPTransport) handleConnection(conn net.Conn) { defer tt.wg.Done() + defer tt.untrackConn(conn) defer conn.Close() - // Set TCP keep-alive if tcpConn, ok := conn.(*net.TCPConn); ok { tt.enableKeepAlive(tcpConn) } - decoder := gob.NewDecoder(bufio.NewReader(conn)) + var tlsState *tls.ConnectionState - for { - var msg internal.Message + if tlsConn, ok := conn.(*tls.Conn); ok { + _ = tlsConn.SetDeadline(time.Now().Add(tt.config.ReadTimeout)) - // Set read deadline - if err := conn.SetReadDeadline(time.Now().Add(60 * time.Second)); err != nil { - tt.logger.Error("failed to set read deadline", + if err := tlsConn.HandshakeContext(tt.ctx); err != nil { + tt.logger.Warn("TLS handshake with peer failed", + forge.F("remote", conn.RemoteAddr()), forge.F("error", err), ) return } - // Decode message - if err := decoder.Decode(&msg); err != nil { - if !errors.Is(err, io.EOF) { - tt.logger.Error("failed to decode message", + _ = tlsConn.SetDeadline(time.Time{}) + state := tlsConn.ConnectionState() + tlsState = &state + } + + reader := bufio.NewReader(conn) + + for { + data, err := tt.readFrame(conn, reader) + if err != nil { + if !errors.Is(err, io.EOF) && !errors.Is(err, net.ErrClosed) && tt.ctx.Err() == nil { + tt.logger.Warn("closing inbound connection", + forge.F("remote", conn.RemoteAddr()), forge.F("error", err), ) } @@ -363,7 +511,27 @@ func (tt *TCPTransport) handleConnection(conn net.Conn) { return } - // Send to inbox + msg, err := decodeMessage(data) + if err != nil { + tt.logger.Warn("closing inbound connection after malformed message", + forge.F("remote", conn.RemoteAddr()), + forge.F("error", err), + ) + + return + } + + if tt.config.RequirePeerIdentity { + if err := verifySender(tlsState, msg.From); err != nil { + tt.logger.Warn("closing inbound connection after spoofed sender", + forge.F("remote", conn.RemoteAddr()), + forge.F("error", err), + ) + + return + } + } + select { case tt.inbox <- msg: tt.logger.Debug("received TCP message", @@ -376,47 +544,92 @@ func (tt *TCPTransport) handleConnection(conn net.Conn) { } } -// getPeerConn gets or creates a connection to a peer. -func (tt *TCPTransport) getPeerConn(nodeID string) (*tcpPeerConn, error) { - tt.peersMu.RLock() - peer, exists := tt.peers[nodeID] - tt.peersMu.RUnlock() +// readFrame reads one length-prefixed frame, refusing frames larger than +// MaxMessageSize before allocating for them. +func (tt *TCPTransport) readFrame(conn net.Conn, reader *bufio.Reader) ([]byte, error) { + if err := conn.SetReadDeadline(time.Now().Add(tt.config.IdleTimeout)); err != nil { + return nil, err + } - if !exists { - return nil, fmt.Errorf("peer %s not found", nodeID) + var header [tcpFrameHeaderSize]byte + if _, err := io.ReadFull(reader, header[:]); err != nil { + return nil, err } - peer.connMu.Lock() - defer peer.connMu.Unlock() + size := binary.BigEndian.Uint32(header[:]) + if uint64(size) > uint64(tt.config.MaxMessageSize) { //nolint:gosec // G115: MaxMessageSize is positive + return nil, fmt.Errorf("%w: frame of %d bytes, limit %d", ErrMessageTooLarge, size, tt.config.MaxMessageSize) + } - // Create connection if not exists or closed - if peer.conn == nil { - target := fmt.Sprintf("%s:%d", peer.address, peer.port) + if err := conn.SetReadDeadline(time.Now().Add(tt.config.ReadTimeout)); err != nil { + return nil, err + } - dialer := &net.Dialer{ - Timeout: 10 * time.Second, - KeepAlive: 30 * time.Second, - } + data := make([]byte, size) + if _, err := io.ReadFull(reader, data); err != nil { + return nil, err + } - conn, err := dialer.DialContext(tt.ctx, "tcp", target) - if err != nil { - return nil, fmt.Errorf("failed to dial peer: %w", err) - } + return data, nil +} + +// dialLocked opens the outbound connection to a peer. peer.connMu is held. +func (tt *TCPTransport) dialLocked(ctx context.Context, peer *tcpPeerConn) error { + tt.mu.RLock() + lifecycle := tt.ctx + started := tt.started + tt.mu.RUnlock() + + if !started || lifecycle == nil { + return internal.ErrNotStarted + } + + target := net.JoinHostPort(peer.address, strconv.Itoa(peer.port)) - // Set TCP keep-alive - if tcpConn, ok := conn.(*net.TCPConn); ok { - tt.enableKeepAlive(tcpConn) + dialCtx, cancel := context.WithTimeout(ctx, tt.config.ConnectionTimeout) + defer cancel() + + stop := context.AfterFunc(lifecycle, cancel) + defer stop() + + dialer := &net.Dialer{KeepAlive: tt.config.KeepAlive} + + var ( + conn net.Conn + err error + ) + + if tt.config.TLSConfig != nil { + tlsDialer := &tls.Dialer{ + NetDialer: dialer, + Config: clientTLSFor(tt.config.TLSConfig, peer.nodeID, tt.config.RequirePeerIdentity), } + conn, err = tlsDialer.DialContext(dialCtx, "tcp", target) + } else { + conn, err = dialer.DialContext(dialCtx, "tcp", target) + } - peer.conn = conn - peer.encoder = gob.NewEncoder(bufio.NewWriter(conn)) - peer.decoder = gob.NewDecoder(bufio.NewReader(conn)) + if err != nil { + return fmt.Errorf("failed to dial peer %s: %w", peer.nodeID, err) + } - tt.logger.Info("connected to peer", - forge.F("peer_id", nodeID), - forge.F("address", target), - ) + peer.conn = conn + peer.writer = bufio.NewWriter(conn) + + tt.logger.Info("connected to peer", + forge.F("peer_id", peer.nodeID), + forge.F("address", target), + ) + + return nil +} + +// closeLocked closes the outbound connection. peer.connMu is held. +func (p *tcpPeerConn) closeLocked() { + if p.conn != nil { + _ = p.conn.Close() } - return peer, nil + p.conn = nil + p.writer = nil } diff --git a/extensions/consensus/transport/tls.go b/extensions/consensus/transport/tls.go index 6acfeea40..e0c22009f 100644 --- a/extensions/consensus/transport/tls.go +++ b/extensions/consensus/transport/tls.go @@ -131,6 +131,16 @@ func (tm *TLSManager) loadTLSConfig() error { if tm.config.RequireClientCert { tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert + // Without a client CA the server would verify peers against the + // system roots, which never sign a cluster's own certificates. + if tm.config.ClientCAFile == "" && tlsConfig.RootCAs != nil { + tlsConfig.ClientCAs = tlsConfig.RootCAs + } + + if tm.config.ClientCAFile == "" && tlsConfig.ClientCAs == nil { + return errors.New("mTLS requires ClientCAFile or CAFile to verify peer certificates") + } + if tm.config.ClientCAFile != "" { clientCACert, err := os.ReadFile(tm.config.ClientCAFile) if err != nil { diff --git a/extensions/consensus/transport/transport_test.go b/extensions/consensus/transport/transport_test.go new file mode 100644 index 000000000..3ae0fdd3a --- /dev/null +++ b/extensions/consensus/transport/transport_test.go @@ -0,0 +1,562 @@ +package transport + +import ( + "bytes" + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/binary" + "encoding/pem" + "errors" + "fmt" + "io" + "math/big" + "net" + "net/http" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/xraph/forge" + "github.com/xraph/forge/extensions/consensus/internal" +) + +func stopOnCleanup(t *testing.T, tr internal.Transport) { + t.Helper() + t.Cleanup(func() { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + _ = tr.Stop(ctx) + }) +} + +func startTCP(t *testing.T, cfg TCPTransportConfig) *TCPTransport { + t.Helper() + + cfg.Address = "127.0.0.1" + tr := NewTCPTransport(cfg, forge.NewNoopLogger()) + + if err := tr.Start(context.Background()); err != nil { + t.Fatal(err) + } + + stopOnCleanup(t, tr) + + return tr +} + +func startHTTP(t *testing.T, cfg HTTPTransportConfig) *HTTPTransport { + t.Helper() + + cfg.Address = "127.0.0.1" + tr := NewHTTPTransport(cfg, forge.NewNoopLogger()) + + if err := tr.Start(context.Background()); err != nil { + t.Fatal(err) + } + + stopOnCleanup(t, tr) + + return tr +} + +func receive(t *testing.T, tr internal.Transport) internal.Message { + t.Helper() + + select { + case m := <-tr.Receive(): + return m + case <-time.After(3 * time.Second): + t.Fatal("no message received") + + return internal.Message{} + } +} + +func expectNothing(t *testing.T, tr internal.Transport) { + t.Helper() + + select { + case m := <-tr.Receive(): + t.Fatalf("unexpected message %+v", m) + case <-time.After(200 * time.Millisecond): + } +} + +func portOf(t *testing.T, addr string) int { + t.Helper() + + _, p, err := net.SplitHostPort(addr) + if err != nil { + t.Fatal(err) + } + + var port int + if _, err := fmt.Sscan(p, &port); err != nil { + t.Fatal(err) + } + + return port +} + +// Every Raft payload survives the wire with its concrete pointer type, which +// is what the raft node's type switches need. +func TestEnvelopeRoundTripsEveryRaftPayload(t *testing.T) { + payloads := map[internal.MessageType]any{ + internal.MessageTypeAppendEntries: &internal.AppendEntriesRequest{ + Term: 3, LeaderID: "a", PrevLogIndex: 4, PrevLogTerm: 2, LeaderCommit: 4, + Entries: []internal.LogEntry{{Index: 5, Term: 3, Data: []byte("cmd")}}, + }, + internal.MessageTypeAppendEntriesResponse: &internal.AppendEntriesResponse{Term: 3, Success: true, MatchIndex: 5}, + internal.MessageTypeRequestVote: internal.RequestVoteRequest{Term: 3, CandidateID: "a"}, + internal.MessageTypeRequestVoteResponse: &internal.RequestVoteResponse{Term: 3, VoteGranted: true}, + internal.MessageTypeInstallSnapshot: &internal.InstallSnapshotRequest{Term: 3, Data: []byte{1, 2}}, + internal.MessageTypeInstallSnapshotResponse: &internal.InstallSnapshotResponse{Term: 3}, + } + + for typ, payload := range payloads { + data, _, err := encodeMessage(internal.Message{Type: typ, From: "a", To: "b", RequestID: 7, Payload: payload}) + if err != nil { + t.Fatalf("%s: encode: %v", typ, err) + } + + msg, err := decodeMessage(data) + if err != nil { + t.Fatalf("%s: decode: %v", typ, err) + } + + if msg.RequestID != 7 || msg.From != "a" { + t.Fatalf("%s: header lost: %+v", typ, msg) + } + + var ok bool + + switch typ { + case internal.MessageTypeAppendEntries: + var p *internal.AppendEntriesRequest + + p, ok = msg.Payload.(*internal.AppendEntriesRequest) + ok = ok && len(p.Entries) == 1 && string(p.Entries[0].Data) == "cmd" + case internal.MessageTypeAppendEntriesResponse: + _, ok = msg.Payload.(*internal.AppendEntriesResponse) + case internal.MessageTypeRequestVote: + _, ok = msg.Payload.(*internal.RequestVoteRequest) + case internal.MessageTypeRequestVoteResponse: + _, ok = msg.Payload.(*internal.RequestVoteResponse) + case internal.MessageTypeInstallSnapshot: + _, ok = msg.Payload.(*internal.InstallSnapshotRequest) + case internal.MessageTypeInstallSnapshotResponse: + _, ok = msg.Payload.(*internal.InstallSnapshotResponse) + } + + if !ok { + t.Fatalf("%s: decoded payload %T (%+v)", typ, msg.Payload, msg.Payload) + } + } +} + +func TestEnvelopeRejectsInconsistentMessages(t *testing.T) { + if _, _, err := encodeMessage(internal.Message{ + Type: internal.MessageTypeAppendEntries, Payload: &internal.RequestVoteRequest{}, + }); err == nil { + t.Fatal("encoded a payload that does not match the message type") + } + + for _, raw := range []string{ + `{"type":"append_entries","from":"a"}`, + `{"type":"append_entries","from":"a","append_entries":{},"request_vote":{}}`, + `{"type":"append_entries","from":"a","payload":{"term":9}}`, + `{"type":"bogus","from":"a"}`, + } { + if _, err := decodeMessage([]byte(raw)); err == nil { + t.Fatalf("decoded invalid message %s", raw) + } + } +} + +// Raft messages sent over TCP arrive promptly and typed. The old transport +// never registered the payload types with gob and never flushed its writer. +func TestTCPTransportDeliversTypedMessages(t *testing.T) { + a := startTCP(t, TCPTransportConfig{NodeID: "a"}) + b := startTCP(t, TCPTransportConfig{NodeID: "b"}) + + if err := a.AddPeer("b", "127.0.0.1", portOf(t, b.GetAddress())); err != nil { + t.Fatal(err) + } + + for i := range 3 { + err := a.Send(context.Background(), "b", internal.Message{ + Type: internal.MessageTypeRequestVote, From: "a", To: "b", RequestID: uint64(i + 1), + Payload: &internal.RequestVoteRequest{Term: 1, CandidateID: "a"}, + }) + if err != nil { + t.Fatal(err) + } + + m := receive(t, b) + if req, ok := m.Payload.(*internal.RequestVoteRequest); !ok || req.CandidateID != "a" || m.RequestID != uint64(i+1) { + t.Fatalf("received %+v (payload %T)", m, m.Payload) + } + } +} + +// A frame header announcing more than MaxMessageSize closes the connection +// before anything is allocated for it. +func TestTCPTransportRejectsOversizedFrames(t *testing.T) { + b := startTCP(t, TCPTransportConfig{NodeID: "b", MaxMessageSize: 1024}) + + conn, err := dialTest(t, b.GetAddress()) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + + var header [4]byte + binary.BigEndian.PutUint32(header[:], 1<<30) + + if _, err := conn.Write(header[:]); err != nil { + t.Fatal(err) + } + + _ = conn.SetReadDeadline(time.Now().Add(3 * time.Second)) + + if _, err := conn.Read(make([]byte, 1)); !errors.Is(err, io.EOF) && !isConnReset(err) { + t.Fatalf("connection stayed open after a 1 GiB frame header: %v", err) + } + + a := startTCP(t, TCPTransportConfig{NodeID: "a", MaxMessageSize: 1024}) + _ = a.AddPeer("b", "127.0.0.1", portOf(t, b.GetAddress())) + + err = a.Send(context.Background(), "b", internal.Message{ + Type: internal.MessageTypeAppendEntries, From: "a", + Payload: &internal.AppendEntriesRequest{Entries: []internal.LogEntry{{Data: make([]byte, 4096)}}}, + }) + if !errors.Is(err, ErrMessageTooLarge) { + t.Fatalf("Send of an oversized message returned %v, want ErrMessageTooLarge", err) + } +} + +func isConnReset(err error) bool { + return err != nil && strings.Contains(err.Error(), "reset") +} + +// Inbound connections beyond MaxConnections are closed, and Stop closes the +// ones that are open instead of waiting for their read deadline. +func TestTCPTransportCapsAndClosesInboundConnections(t *testing.T) { + tr := NewTCPTransport(TCPTransportConfig{NodeID: "b", Address: "127.0.0.1", MaxConnections: 2}, forge.NewNoopLogger()) + if err := tr.Start(context.Background()); err != nil { + t.Fatal(err) + } + + var conns []net.Conn + + for range 3 { + c, err := dialTest(t, tr.GetAddress()) + if err != nil { + t.Fatal(err) + } + defer c.Close() + + conns = append(conns, c) + } + + _ = conns[2].SetReadDeadline(time.Now().Add(3 * time.Second)) + if _, err := conns[2].Read(make([]byte, 1)); err == nil || isTimeout(err) { + t.Fatalf("third connection over a cap of 2 was not closed: %v", err) + } + + start := time.Now() + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + if err := tr.Stop(ctx); err != nil { + t.Fatal(err) + } + + if elapsed := time.Since(start); elapsed > 2*time.Second { + t.Fatalf("Stop took %v with idle inbound connections open", elapsed) + } + + _ = conns[0].SetReadDeadline(time.Now().Add(3 * time.Second)) + if _, err := conns[0].Read(make([]byte, 1)); isTimeout(err) { + t.Fatal("Stop left an inbound connection open") + } +} + +func isTimeout(err error) bool { + var ne net.Error + + return errors.As(err, &ne) && ne.Timeout() +} + +// Raft messages sent over HTTP arrive typed. They used to arrive as +// map[string]any, so every type assertion in the raft node failed. +func TestHTTPTransportDeliversTypedMessages(t *testing.T) { + a := startHTTP(t, HTTPTransportConfig{NodeID: "a"}) + b := startHTTP(t, HTTPTransportConfig{NodeID: "b"}) + _ = a.AddPeer("b", "127.0.0.1", portOf(t, b.GetAddress())) + + err := a.Send(context.Background(), "b", internal.Message{ + Type: internal.MessageTypeAppendEntries, From: "a", To: "b", + Payload: &internal.AppendEntriesRequest{Term: 1, LeaderID: "a"}, + }) + if err != nil { + t.Fatal(err) + } + + m := receive(t, b) + if req, ok := m.Payload.(*internal.AppendEntriesRequest); !ok || req.LeaderID != "a" { + t.Fatalf("received payload %T %+v", m.Payload, m.Payload) + } +} + +// Request bodies are capped at MaxMessageSize instead of read in full. +func TestHTTPTransportRejectsOversizedBodies(t *testing.T) { + b := startHTTP(t, HTTPTransportConfig{NodeID: "b", MaxMessageSize: 1024}) + + body := bytes.Repeat([]byte(" "), 64<<10) + + resp, err := postTest(t, http.DefaultClient, "http://"+b.GetAddress()+"/raft/message", bytes.NewReader(body)) + if err != nil { + t.Fatal(err) + } + + resp.Body.Close() + + if resp.StatusCode != http.StatusRequestEntityTooLarge { + t.Fatalf("status = %d, want 413", resp.StatusCode) + } + + expectNothing(t, b) +} + +// Without an explicit address the transports listen on loopback only. +func TestTransportsDefaultToLoopback(t *testing.T) { + if got := NewTCPTransport(TCPTransportConfig{NodeID: "a"}, forge.NewNoopLogger()).address; got != "127.0.0.1" { + t.Fatalf("TCP default address %q", got) + } + + if got := NewHTTPTransport(HTTPTransportConfig{NodeID: "a"}, forge.NewNoopLogger()).address; got != "127.0.0.1" { + t.Fatalf("HTTP default address %q", got) + } +} + +// The gRPC transport is not implemented and says so instead of pretending. +func TestGRPCTransportFailsLoudly(t *testing.T) { + g := NewGRPCTransport(GRPCTransportConfig{NodeID: "a", Address: "127.0.0.1"}, forge.NewNoopLogger()) + + if err := g.Start(context.Background()); !errors.Is(err, ErrGRPCNotImplemented) { + t.Fatalf("Start returned %v", err) + } + + _ = g.AddPeer("b", "127.0.0.1", 1) + + if err := g.Send(context.Background(), "b", internal.Message{Type: internal.MessageTypeRequestVote}); !errors.Is(err, ErrGRPCNotImplemented) { + t.Fatalf("Send returned %v", err) + } +} + +// testPKI writes a CA and per-node certificates (node ID as DNS SAN) to dir. +type testPKI struct { + dir string + caFile string + caKey *ecdsa.PrivateKey + caCert *x509.Certificate +} + +func newTestPKI(t *testing.T) *testPKI { + t.Helper() + + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + + tmpl := &x509.Certificate{ + SerialNumber: big.NewInt(1), + Subject: pkix.Name{CommonName: "test-ca"}, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(time.Hour), + IsCA: true, + KeyUsage: x509.KeyUsageCertSign, + BasicConstraintsValid: true, + } + + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) + if err != nil { + t.Fatal(err) + } + + cert, _ := x509.ParseCertificate(der) + p := &testPKI{dir: t.TempDir(), caKey: key, caCert: cert} + p.caFile = filepath.Join(p.dir, "ca.pem") + writePEM(t, p.caFile, "CERTIFICATE", der) + + return p +} + +func (p *testPKI) node(t *testing.T, name string) (certFile, keyFile string) { + t.Helper() + + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + + tmpl := &x509.Certificate{ + SerialNumber: big.NewInt(time.Now().UnixNano()), + Subject: pkix.Name{CommonName: name}, + DNSNames: []string{name}, + IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(time.Hour), + KeyUsage: x509.KeyUsageDigitalSignature, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}, + } + + der, err := x509.CreateCertificate(rand.Reader, tmpl, p.caCert, &key.PublicKey, p.caKey) + if err != nil { + t.Fatal(err) + } + + keyDER, err := x509.MarshalECPrivateKey(key) + if err != nil { + t.Fatal(err) + } + + certFile = filepath.Join(p.dir, name+".pem") + keyFile = filepath.Join(p.dir, name+"-key.pem") + + writePEM(t, certFile, "CERTIFICATE", der) + writePEM(t, keyFile, "EC PRIVATE KEY", keyDER) + + return certFile, keyFile +} + +func writePEM(t *testing.T, path, typ string, der []byte) { + t.Helper() + + if err := os.WriteFile(path, pem.EncodeToMemory(&pem.Block{Type: typ, Bytes: der}), 0o600); err != nil { + t.Fatal(err) + } +} + +// mtlsConfig builds a node's TLS config with the existing TLSManager helper. +func (p *testPKI) mtlsConfig(t *testing.T, name string) *tls.Config { + t.Helper() + + certFile, keyFile := p.node(t, name) + + tm, err := NewTLSManager(MTLSConfig(certFile, keyFile, p.caFile), forge.NewNoopLogger()) + if err != nil { + t.Fatal(err) + } + + return tm.GetTLSConfig() +} + +// With mTLS and peer identity checks, a node can only send as itself. +func TestMTLSPeerIdentity(t *testing.T) { + pki := newTestPKI(t) + + for _, kind := range []string{"tcp", "http"} { + t.Run(kind, func(t *testing.T) { + var a, b, mallory internal.Transport + + if kind == "tcp" { + a = startTCP(t, TCPTransportConfig{NodeID: "a", TLSConfig: pki.mtlsConfig(t, "a"), RequirePeerIdentity: true}) + b = startTCP(t, TCPTransportConfig{NodeID: "b", TLSConfig: pki.mtlsConfig(t, "b"), RequirePeerIdentity: true}) + mallory = startTCP(t, TCPTransportConfig{NodeID: "m", TLSConfig: pki.mtlsConfig(t, "m"), RequirePeerIdentity: true}) + } else { + a = startHTTP(t, HTTPTransportConfig{NodeID: "a", TLSConfig: pki.mtlsConfig(t, "a"), RequirePeerIdentity: true}) + b = startHTTP(t, HTTPTransportConfig{NodeID: "b", TLSConfig: pki.mtlsConfig(t, "b"), RequirePeerIdentity: true}) + mallory = startHTTP(t, HTTPTransportConfig{NodeID: "m", TLSConfig: pki.mtlsConfig(t, "m"), RequirePeerIdentity: true}) + } + + bPort := portOf(t, b.GetAddress()) + _ = a.AddPeer("b", "127.0.0.1", bPort) + _ = mallory.AddPeer("b", "127.0.0.1", bPort) + + vote := func(from string) internal.Message { + return internal.Message{ + Type: internal.MessageTypeRequestVote, From: from, To: "b", + Payload: &internal.RequestVoteRequest{Term: 9, CandidateID: from}, + } + } + + if err := a.Send(context.Background(), "b", vote("a")); err != nil { + t.Fatalf("legitimate send failed: %v", err) + } + + if m := receive(t, b); m.From != "a" { + t.Fatalf("received %+v", m) + } + + // Mallory holds a valid cluster certificate but claims to be a. + _ = mallory.Send(context.Background(), "b", vote("a")) + + expectNothing(t, b) + + // A client without any certificate cannot connect at all. + plain := &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{ + InsecureSkipVerify: true, + }}} + + if kind == "http" { + body := `{"type":"request_vote","from":"a","request_vote":{"term":9}}` + if resp, err := postTest(t, plain, "https://"+b.GetAddress()+"/raft/message", strings.NewReader(body)); err == nil { + resp.Body.Close() + t.Fatalf("request without a client certificate got status %d", resp.StatusCode) + } + } + + expectNothing(t, b) + }) + } +} + +// Asking for peer identity without mutual TLS fails at startup. +func TestPeerIdentityRequiresMTLS(t *testing.T) { + tcp := NewTCPTransport(TCPTransportConfig{NodeID: "a", RequirePeerIdentity: true}, forge.NewNoopLogger()) + if err := tcp.Start(context.Background()); err == nil { + _ = tcp.Stop(context.Background()) + + t.Fatal("TCP transport started with peer identity checks but no TLS") + } + + h := NewHTTPTransport(HTTPTransportConfig{NodeID: "a", RequirePeerIdentity: true, TLSConfig: &tls.Config{MinVersion: tls.VersionTLS12}}, forge.NewNoopLogger()) + if err := h.Start(context.Background()); err == nil { + _ = h.Stop(context.Background()) + + t.Fatal("HTTP transport started with peer identity checks but no client certificate requirement") + } +} + +func dialTest(t *testing.T, addr string) (net.Conn, error) { + t.Helper() + + var d net.Dialer + + return d.DialContext(t.Context(), "tcp", addr) +} + +func postTest(t *testing.T, client *http.Client, url string, body io.Reader) (*http.Response, error) { + t.Helper() + + req, err := http.NewRequestWithContext(t.Context(), http.MethodPost, url, body) + if err != nil { + return nil, err + } + + req.Header.Set("Content-Type", "application/json") + + return client.Do(req) +} From 57a25c39290b09f4ce0d3345307b7b839ebf58bf Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:27:34 -0600 Subject: [PATCH 04/17] fix(consensus): require admin api keys and refuse security options that cannot be applied Several security settings were validated and then never read: - admin_api.enable_auth and api_key: the admin API exposed /nodes/add, /nodes/remove, /apply and /read to anyone who could reach it. The existing AuthMiddleware returned nil after writing its 401, so it could not stop a request either. admin.WithAPIKey and admin.NewAPIFromConfig now put security.APIKeyMiddleware on every admin route. It takes a bearer token or X-Api-Key and compares SHA-256 digests in constant time. enable_auth without an api_key is a validation error, and routes registered without a key log a warning. - security.enable_tls and enable_mtls: the consensus service builds no transport, so there was nothing to apply them to. Service.Start now fails when they are set and points at raft.NewNode with the transport package's TLSConfig, instead of starting as if traffic were protected. Start also warns that the service does not run a raft node yet. - security.enable_encryption: nothing encrypts data at rest, so the option is rejected. Defaults: - bind_addr defaults to 127.0.0.1 instead of 0.0.0.0. - transport.type defaults to tcp. grpc is rejected as not implemented and http is accepted. The README and llm.txt describe the new rules. Response header literals in the leadership middleware were changed to their canonical form so the module lints clean. The headers sent are identical. --- extensions/consensus/README.md | 9 ++- extensions/consensus/admin/api.go | 61 ++++++++++++++- extensions/consensus/admin/auth_test.go | 75 +++++++++++++++++++ extensions/consensus/internal/config.go | 28 +++++-- .../internal/config_security_test.go | 50 +++++++++++++ extensions/consensus/llm.txt | 9 ++- extensions/consensus/middleware/leadership.go | 6 +- extensions/consensus/security/apikey.go | 46 ++++++++++++ extensions/consensus/service.go | 26 +++++++ extensions/consensus/service_security_test.go | 31 ++++++++ 10 files changed, 325 insertions(+), 16 deletions(-) create mode 100644 extensions/consensus/admin/auth_test.go create mode 100644 extensions/consensus/internal/config_security_test.go create mode 100644 extensions/consensus/security/apikey.go create mode 100644 extensions/consensus/service_security_test.go diff --git a/extensions/consensus/README.md b/extensions/consensus/README.md index 486d7712c..1b099af11 100644 --- a/extensions/consensus/README.md +++ b/extensions/consensus/README.md @@ -221,7 +221,7 @@ extensions: election_timeout_min: 5s election_timeout_max: 10s transport: - type: grpc # grpc or tcp + type: tcp # tcp or http storage: type: badger # badger, boltdb, pebble or postgres path: ./data/consensus @@ -239,11 +239,16 @@ Validation runs when the extension registers. If any of these rules fail, your a | `cluster_id` is set | `default` | | `bind_port` is between 1 and 65535 | `7000` | | `raft.heartbeat_interval` < `raft.election_timeout_min` < `raft.election_timeout_max` | `1s`, `5s`, `10s` | -| `transport.type` is `grpc` or `tcp` | `grpc` | +| `bind_addr` is the listen address; set it explicitly to accept other hosts | `127.0.0.1` | +| `transport.type` is `tcp` or `http` (`grpc` is rejected because it is not implemented) | `tcp` | | `transport.max_message_size` is positive | 4MB | | `discovery.type` is `static`, `dns`, `consul`, `etcd` or `kubernetes` | `static` | | `storage.type` is `badger`, `boltdb`, `pebble` or `postgres`, and `storage.path` is set | `badger`, `./data/consensus` | | `security.cert_file` and `key_file` are set when `enable_tls` is on, and `ca_file` when `enable_mtls` is on | TLS off | +| `security.enable_encryption` is off (encryption at rest is not implemented) | off | +| `admin_api.api_key` is set when `admin_api.enable_auth` is on | auth off | + +The service does not start a raft node or a transport yet, so `Start` fails when `enable_tls` or `enable_mtls` is set rather than run without them. To run a secured cluster today, build it from `raft.NewNode` with `transport.NewTCPTransport` or `transport.NewHTTPTransport`, passing `TLSConfig` (from `transport.NewTLSManager`) and `RequirePeerIdentity`. With peer identity on, each node's certificate must name its node ID as a DNS subject alternative name. The admin API takes `admin.WithAPIKey` or `admin.NewAPIFromConfig` to require an API key on every route. The options are `WithNodeID`, `WithClusterID`, `WithBindAddress`, `WithPeers`, `WithTransportType`, `WithDiscoveryType`, `WithStorageType`, `WithStoragePath`, `WithTLS`, `WithMTLS`, `WithConfig` and `WithRequireConfig`. The config also has `election`, `health`, `observability`, `resilience`, `admin_api`, `events` and `advanced` sections. Their full key list and defaults are in [`internal/config.go`](internal/config.go) and on the [configuration page](https://www.xraph.com/docs/forge/extensions/consensus/configuration). Today the extension acts on a handful of them: `health.enabled` and `health.check_interval` drive its health loop, `observability.metrics.enabled` and `collection_interval` drive metrics collection, and `advanced.enable_auto_snapshot` with `raft.snapshot_interval` drives the snapshot loop. `events.enabled` is on by default. It adds `events` to the extension's dependencies and publishes start and stop events when an event bus is in the container. diff --git a/extensions/consensus/admin/api.go b/extensions/consensus/admin/api.go index 4d5f9a579..10baf6e40 100644 --- a/extensions/consensus/admin/api.go +++ b/extensions/consensus/admin/api.go @@ -7,8 +7,10 @@ import ( "time" "github.com/xraph/forge" + "github.com/xraph/forge/errors" "github.com/xraph/forge/extensions/consensus/internal" "github.com/xraph/forge/extensions/consensus/observability" + "github.com/xraph/forge/extensions/consensus/security" ) // API provides admin endpoints for consensus management. @@ -17,6 +19,20 @@ type API struct { healthChecker *observability.HealthChecker metricsCollector *observability.MetricsCollector logger forge.Logger + + // apiKey, when set, is required on every admin route. + apiKey string +} + +// Option configures an admin API. +type Option func(*API) + +// WithAPIKey requires every admin route to present key, as a bearer token or +// in the X-API-Key header. +func WithAPIKey(key string) Option { + return func(a *API) { + a.apiKey = key + } } // NewAPI creates a new admin API. @@ -25,13 +41,43 @@ func NewAPI( healthChecker *observability.HealthChecker, metricsCollector *observability.MetricsCollector, logger forge.Logger, + opts ...Option, ) *API { - return &API{ + a := &API{ service: service, healthChecker: healthChecker, metricsCollector: metricsCollector, logger: logger, } + + for _, opt := range opts { + opt(a) + } + + return a +} + +// NewAPIFromConfig creates an admin API that honours AdminAPIConfig: with +// EnableAuth set, every route requires APIKey, and an empty APIKey is an +// error rather than an open API. +func NewAPIFromConfig( + service internal.ConsensusService, + healthChecker *observability.HealthChecker, + metricsCollector *observability.MetricsCollector, + logger forge.Logger, + cfg internal.AdminAPIConfig, +) (*API, error) { + var opts []Option + + if cfg.EnableAuth { + if cfg.APIKey == "" { + return nil, errors.New("admin API auth is enabled but no API key is configured") + } + + opts = append(opts, WithAPIKey(cfg.APIKey)) + } + + return NewAPI(service, healthChecker, metricsCollector, logger, opts...), nil } // HandleHealth handles health check requests. @@ -350,10 +396,20 @@ func (a *API) RegisterRoutes(router forge.Router, prefix string) { {router.POST, http.MethodPost, "/read", a.HandleReadQuery}, } + var opts []forge.RouteOption + + if a.apiKey != "" { + opts = append(opts, forge.WithMiddleware(security.APIKeyMiddleware(a.apiKey))) + } else { + a.logger.Warn("admin API routes are registered without authentication; anyone who can reach them can add or remove nodes and apply commands", + forge.F("prefix", prefix), + ) + } + failed := 0 for _, route := range routes { - if err := route.register(prefix+route.path, route.handler); err != nil { + if err := route.register(prefix+route.path, route.handler, opts...); err != nil { failed++ a.logger.Error("failed to register admin API route", @@ -367,5 +423,6 @@ func (a *API) RegisterRoutes(router forge.Router, prefix string) { a.logger.Info("admin API routes registered", forge.F("prefix", prefix), forge.F("failed", failed), + forge.F("auth", a.apiKey != ""), ) } diff --git a/extensions/consensus/admin/auth_test.go b/extensions/consensus/admin/auth_test.go new file mode 100644 index 000000000..a0ebdaa29 --- /dev/null +++ b/extensions/consensus/admin/auth_test.go @@ -0,0 +1,75 @@ +package admin + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + + "github.com/xraph/forge" + "github.com/xraph/forge/extensions/consensus/internal" +) + +// healthyService implements only what the health route needs. +type healthyService struct { + internal.ConsensusService +} + +func (healthyService) HealthCheck(context.Context) error { return nil } + +func serve(t *testing.T, api *API, header, value string) int { + t.Helper() + + router := forge.NewRouter() + api.RegisterRoutes(router, "/consensus") + + req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/consensus/health", nil) + if header != "" { + req.Header.Set(header, value) + } + + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + + return rec.Code +} + +func TestAdminRoutesRequireAPIKeyWhenAuthEnabled(t *testing.T) { + api, err := NewAPIFromConfig(healthyService{}, nil, nil, forge.NewNoopLogger(), + internal.AdminAPIConfig{EnableAuth: true, APIKey: "s3cret"}) + if err != nil { + t.Fatal(err) + } + + cases := []struct { + header, value string + want int + }{ + {"", "", http.StatusUnauthorized}, + {"Authorization", "Bearer wrong", http.StatusUnauthorized}, + {"X-API-Key", "s3cre", http.StatusUnauthorized}, + {"Authorization", "Bearer s3cret", http.StatusOK}, + {"X-API-Key", "s3cret", http.StatusOK}, + } + + for _, c := range cases { + if got := serve(t, api, c.header, c.value); got != c.want { + t.Fatalf("%s=%q: status %d, want %d", c.header, c.value, got, c.want) + } + } +} + +func TestAdminAuthWithoutKeyIsAnError(t *testing.T) { + if _, err := NewAPIFromConfig(healthyService{}, nil, nil, forge.NewNoopLogger(), + internal.AdminAPIConfig{EnableAuth: true}); err == nil { + t.Fatal("enable_auth without an api_key produced an open admin API") + } +} + +func TestAdminRoutesOpenWithoutAuth(t *testing.T) { + api := NewAPI(healthyService{}, nil, nil, forge.NewNoopLogger()) + + if got := serve(t, api, "", ""); got != http.StatusOK { + t.Fatalf("status %d without auth configured", got) + } +} diff --git a/extensions/consensus/internal/config.go b/extensions/consensus/internal/config.go index c4fec3ac8..bd2edb6aa 100644 --- a/extensions/consensus/internal/config.go +++ b/extensions/consensus/internal/config.go @@ -10,8 +10,10 @@ type Config struct { // Node configuration NodeID string `json:"node_id" yaml:"node_id"` ClusterID string `json:"cluster_id" yaml:"cluster_id"` - BindAddr string `default:"0.0.0.0" json:"bind_addr" yaml:"bind_addr"` - BindPort int `default:"7000" json:"bind_port" yaml:"bind_port"` + // BindAddr defaults to loopback. Set it to a routable address (or 0.0.0.0) + // explicitly to accept peers from other hosts. + BindAddr string `default:"127.0.0.1" json:"bind_addr" yaml:"bind_addr"` + BindPort int `default:"7000" json:"bind_port" yaml:"bind_port"` // Peers - initial cluster members Peers []PeerConfig `json:"peers" yaml:"peers"` @@ -82,7 +84,7 @@ type RaftConfig struct { // TransportConfig contains transport layer configuration. type TransportConfig struct { - Type string `default:"grpc" json:"type" yaml:"type"` // grpc, tcp + Type string `default:"tcp" json:"type" yaml:"type"` // tcp, http (grpc is not implemented) MaxMessageSize int `default:"4194304" json:"max_message_size" yaml:"max_message_size"` // 4MB Timeout time.Duration `default:"10s" json:"timeout" yaml:"timeout"` KeepAlive bool `default:"true" json:"keep_alive" yaml:"keep_alive"` @@ -244,7 +246,7 @@ func DefaultConfig() Config { return Config{ NodeID: "", ClusterID: "default", - BindAddr: "0.0.0.0", + BindAddr: "127.0.0.1", BindPort: 7000, Peers: []PeerConfig{}, Raft: RaftConfig{ @@ -263,7 +265,7 @@ func DefaultConfig() Config { DisablePipeline: false, }, Transport: TransportConfig{ - Type: "grpc", + Type: "tcp", MaxMessageSize: 4 * 1024 * 1024, // 4MB Timeout: 10 * time.Second, KeepAlive: true, @@ -409,7 +411,11 @@ func (c *Config) Validate() error { } // Validate transport config - if c.Transport.Type != "grpc" && c.Transport.Type != "tcp" { + switch c.Transport.Type { + case "tcp", "http": + case "grpc": + return fmt.Errorf("%w: transport type grpc is not implemented, use tcp or http", ErrInvalidConfig) + default: return fmt.Errorf("%w: invalid transport type: %s", ErrInvalidConfig, c.Transport.Type) } @@ -452,6 +458,16 @@ func (c *Config) Validate() error { return fmt.Errorf("%w: security.ca_file is required when mTLS is enabled", ErrInvalidConfig) } + // Nothing encrypts consensus data at rest, so accepting the option would + // promise protection that does not exist. + if c.Security.EnableEncryption { + return fmt.Errorf("%w: security.enable_encryption is not implemented", ErrInvalidConfig) + } + + if c.AdminAPI.EnableAuth && c.AdminAPI.APIKey == "" { + return fmt.Errorf("%w: admin_api.api_key is required when admin_api.enable_auth is true", ErrInvalidConfig) + } + return nil } diff --git a/extensions/consensus/internal/config_security_test.go b/extensions/consensus/internal/config_security_test.go new file mode 100644 index 000000000..14335211c --- /dev/null +++ b/extensions/consensus/internal/config_security_test.go @@ -0,0 +1,50 @@ +package internal + +import ( + "errors" + "testing" +) + +func validConfig() Config { + c := DefaultConfig() + c.NodeID = "n1" + + return c +} + +func TestDefaultConfigBindsLoopback(t *testing.T) { + if got := DefaultConfig().BindAddr; got != "127.0.0.1" { + t.Fatalf("default bind address %q, want 127.0.0.1", got) + } + + c := validConfig() + if err := c.Validate(); err != nil { + t.Fatalf("default config does not validate: %v", err) + } +} + +func TestValidateRejectsOptionsThatCannotBeHonoured(t *testing.T) { + cases := map[string]func(*Config){ + "grpc transport": func(c *Config) { c.Transport.Type = "grpc" }, + "encryption at rest": func(c *Config) { c.Security.EnableEncryption = true }, + "admin auth without key": func(c *Config) { c.AdminAPI.EnableAuth = true }, + } + + for name, mutate := range cases { + c := validConfig() + mutate(&c) + + if err := c.Validate(); !errors.Is(err, ErrInvalidConfig) { + t.Fatalf("%s: Validate returned %v, want ErrInvalidConfig", name, err) + } + } + + c := validConfig() + c.Transport.Type = "http" + c.AdminAPI.EnableAuth = true + c.AdminAPI.APIKey = "k" + + if err := c.Validate(); err != nil { + t.Fatalf("http transport with admin auth rejected: %v", err) + } +} diff --git a/extensions/consensus/llm.txt b/extensions/consensus/llm.txt index e28abf6e9..df4af176f 100644 --- a/extensions/consensus/llm.txt +++ b/extensions/consensus/llm.txt @@ -88,7 +88,7 @@ WithNodeID(id string) WithClusterID(id string) WithBindAddress(addr string, port int) WithPeers(peers []PeerConfig) // PeerConfig{ID, Address string; Port int} -WithTransportType(transportType string) // grpc, tcp +WithTransportType(transportType string) // tcp, http (grpc is not implemented) WithDiscoveryType(discoveryType string) // static, dns, consul, etcd, kubernetes WithStorageType(storageType string) // badger, boltdb, pebble, postgres WithStoragePath(path string) @@ -113,10 +113,13 @@ TransferLeadership and StepDown return "not yet implemented". Key `extensions.consensus`, falling back to `consensus`. Options override the file. Validation at registration: node_id set (no default); cluster_id set ("default"); bind_port 1..65535 (7000); raft.heartbeat_interval < election_timeout_min < election_timeout_max (1s, 5s, 10s); -transport.type grpc or tcp ("grpc"); transport.max_message_size positive (4MB); discovery.type +bind_addr ("127.0.0.1"); transport.type tcp or http ("tcp", grpc rejected as not implemented); transport.max_message_size positive (4MB); discovery.type static/dns/consul/etcd/kubernetes ("static"); storage.type badger/boltdb/pebble/postgres ("badger") with storage.path ("./data/consensus"); TLS needs cert_file and key_file, mTLS needs -ca_file. +ca_file; enable_encryption is rejected (not implemented); admin_api.enable_auth needs api_key. +Service.Start fails when enable_tls or enable_mtls is set, because the service opens no transport +yet. Secured clusters are built from raft.NewNode plus transport.NewTCPTransport/NewHTTPTransport +with TLSConfig and RequirePeerIdentity (node ID as a DNS SAN in each node certificate). Other sections: election, health, observability, resilience, admin_api, events, advanced. Full keys and defaults in internal/config.go. The extension acts on: health.enabled and diff --git a/extensions/consensus/middleware/leadership.go b/extensions/consensus/middleware/leadership.go index 2ada70386..9bae3617f 100644 --- a/extensions/consensus/middleware/leadership.go +++ b/extensions/consensus/middleware/leadership.go @@ -157,8 +157,8 @@ func (mm *MetricsMiddleware) AddConsensusHeaders(next func(forge.Context) error) // Add consensus state to response headers stats := mm.service.GetStats() - ctx.Response().Header().Set("X-Consensus-Node-ID", stats.NodeID) - ctx.Response().Header().Set("X-Consensus-Cluster-ID", stats.ClusterID) + ctx.Response().Header().Set("X-Consensus-Node-Id", stats.NodeID) + ctx.Response().Header().Set("X-Consensus-Cluster-Id", stats.ClusterID) ctx.Response().Header().Set("X-Consensus-Term", strconv.FormatUint(stats.Term, 10)) ctx.Response().Header().Set("X-Consensus-Role", string(stats.Role)) @@ -171,7 +171,7 @@ func (mm *MetricsMiddleware) AddConsensusHeaders(next func(forge.Context) error) ctx.Response().Header().Set("X-Consensus-Leader", "false") if leaderID != "" { - ctx.Response().Header().Set("X-Consensus-Leader-ID", leaderID) + ctx.Response().Header().Set("X-Consensus-Leader-Id", leaderID) } } diff --git a/extensions/consensus/security/apikey.go b/extensions/consensus/security/apikey.go new file mode 100644 index 000000000..49524b08f --- /dev/null +++ b/extensions/consensus/security/apikey.go @@ -0,0 +1,46 @@ +package security + +import ( + "crypto/sha256" + "crypto/subtle" + "net/http" + "strings" + + "github.com/xraph/forge" +) + +// APIKeyMiddleware rejects requests that do not present key, either as +// "Authorization: Bearer " or in the X-API-Key header. Both values are +// hashed before a constant-time comparison, so neither the key's contents nor +// its length leak through timing. A rejected request gets 401 and the wrapped +// handler is not called. +func APIKeyMiddleware(key string) forge.Middleware { + want := sha256.Sum256([]byte(key)) + + return func(next forge.Handler) forge.Handler { + return func(ctx forge.Context) error { + provided := presentedKey(ctx.Request()) + got := sha256.Sum256([]byte(provided)) + + if key == "" || provided == "" || subtle.ConstantTimeCompare(got[:], want[:]) != 1 { + ctx.Response().Header().Set("WWW-Authenticate", `Bearer realm="consensus-admin"`) + + return ctx.JSON(http.StatusUnauthorized, map[string]any{ + "error": "missing or invalid API key", + }) + } + + return next(ctx) + } + } +} + +func presentedKey(r *http.Request) string { + if auth := r.Header.Get("Authorization"); auth != "" { + if token, ok := strings.CutPrefix(auth, "Bearer "); ok { + return strings.TrimSpace(token) + } + } + + return r.Header.Get("X-Api-Key") +} diff --git a/extensions/consensus/service.go b/extensions/consensus/service.go index 5d146e6b6..472a873b3 100644 --- a/extensions/consensus/service.go +++ b/extensions/consensus/service.go @@ -74,6 +74,10 @@ func (s *Service) Start(ctx context.Context) error { return ErrAlreadyStarted } + if err := checkUnwiredSecurity(s.config); err != nil { + return err + } + s.ctx, s.cancel = context.WithCancel(ctx) s.logger.Info("starting consensus service", @@ -83,6 +87,11 @@ func (s *Service) Start(ctx context.Context) error { forge.F("bind_port", s.config.BindPort), ) + s.logger.Warn("the consensus service does not run a raft node or open a transport yet; "+ + "build a cluster with raft.NewNode and the transport package to replicate data", + forge.F("node_id", s.config.NodeID), + ) + // Initialize storage if err := s.initStorage(); err != nil { return fmt.Errorf("failed to initialize storage: %w", err) @@ -810,3 +819,20 @@ func (s *Service) encodeCommand(cmd Command) []byte { // TODO: Implement proper encoding return fmt.Appendf(nil, "%v", cmd) } + +// checkUnwiredSecurity refuses to start when a security option is set that +// the service cannot apply. The service does not build a raft node or a +// network transport yet (its init steps only log), so TLS settings would be +// silently ignored. Failing here keeps operators from believing cluster +// traffic is protected. Applications that need a secured cluster today build +// it from raft.NewNode with transport.NewTCPTransport or NewHTTPTransport and +// their TLSConfig and RequirePeerIdentity options. +func checkUnwiredSecurity(cfg internal.Config) error { + if cfg.Security.EnableTLS || cfg.Security.EnableMTLS { + return fmt.Errorf("%w: security.enable_tls and security.enable_mtls cannot be honoured because the consensus "+ + "service does not start a network transport yet; wire raft.NewNode with the transport package's TLSConfig instead", + internal.ErrInvalidConfig) + } + + return nil +} diff --git a/extensions/consensus/service_security_test.go b/extensions/consensus/service_security_test.go new file mode 100644 index 000000000..f2cedfbce --- /dev/null +++ b/extensions/consensus/service_security_test.go @@ -0,0 +1,31 @@ +package consensus + +import ( + "context" + "errors" + "testing" + + "github.com/xraph/forge" + "github.com/xraph/forge/extensions/consensus/internal" +) + +// TLS settings cannot be applied by a service that opens no transport, so +// Start must refuse them instead of running without them. +func TestServiceRefusesTLSItCannotApply(t *testing.T) { + cfg := internal.DefaultConfig() + cfg.NodeID = "n1" + cfg.Security.EnableTLS = true + cfg.Security.CertFile = "cert.pem" + cfg.Security.KeyFile = "key.pem" + + s, err := NewConsensusService(cfg, forge.NewNoopLogger(), nil) + if err != nil { + t.Fatal(err) + } + + if err := s.Start(context.Background()); !errors.Is(err, internal.ErrInvalidConfig) { + _ = s.Stop(context.Background()) + + t.Fatalf("Start with TLS enabled returned %v", err) + } +} From ed0f2492e3b149915f06358c9872c4c7f53035eb Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 21:58:03 -0600 Subject: [PATCH 05/17] fix(farp): verify schema hash before caching gateway schemas The gateway client cached schemas by the hash a registrant put in its descriptor and never checked the content against it. A service that registered first with another service's hash could make the gateway serve its own paths under the victim's routes. Fetched schema content is now hashed again with CalculateSchemaChecksum and rejected on mismatch. The cache is keyed by instance ID and hash so one registrant can never fill an entry another reads, and it is a bounded LRU (DefaultSchemaCacheSize, configurable with WithSchemaCacheSize) instead of an unbounded map. WatchServices also ignores nil events, which a closed registry can deliver, and seeds its manifest cache from the initial listing so the first watch event no longer drops every other instance's routes. --- farp/gateway/client.go | 224 ++++++++++++++++++++++----- farp/gateway/client_security_test.go | 218 ++++++++++++++++++++++++++ 2 files changed, 399 insertions(+), 43 deletions(-) create mode 100644 farp/gateway/client_security_test.go diff --git a/farp/gateway/client.go b/farp/gateway/client.go index 42faebad9..8e9581bde 100644 --- a/farp/gateway/client.go +++ b/farp/gateway/client.go @@ -1,6 +1,7 @@ package gateway import ( + "container/list" "context" "errors" "fmt" @@ -9,22 +10,47 @@ import ( "github.com/xraph/farp" ) +// DefaultSchemaCacheSize is the number of verified schemas a Client keeps +// when no explicit size is configured. +const DefaultSchemaCacheSize = 1024 + +// ErrSchemaHashMismatch is returned when a schema's content does not hash to +// the value its descriptor claims. +var ErrSchemaHashMismatch = errors.New("farp gateway: schema content does not match descriptor hash") + // Client is a reference implementation for API gateway integration // It watches for service schema changes and provides conversion utilities. type Client struct { registry farp.SchemaRegistry manifestCache map[string]*farp.SchemaManifest // key: instanceID - schemaCache map[string]any // key: hash + schemaCache *schemaLRU mu sync.RWMutex } +// ClientOption configures a Client. +type ClientOption func(*Client) + +// WithSchemaCacheSize bounds the number of schemas kept in the client's cache. +// Values below 1 fall back to DefaultSchemaCacheSize. +func WithSchemaCacheSize(n int) ClientOption { + return func(c *Client) { + c.schemaCache = newSchemaLRU(n) + } +} + // NewClient creates a new gateway client. -func NewClient(registry farp.SchemaRegistry) *Client { - return &Client{ +func NewClient(registry farp.SchemaRegistry, opts ...ClientOption) *Client { + c := &Client{ registry: registry, manifestCache: make(map[string]*farp.SchemaManifest), - schemaCache: make(map[string]any), + schemaCache: newSchemaLRU(DefaultSchemaCacheSize), + } + + for _, opt := range opts { + opt(c) } + + return c } // WatchServices watches for service registrations and schema updates @@ -36,12 +62,30 @@ func (c *Client) WatchServices(ctx context.Context, serviceName string, onChange return fmt.Errorf("failed to list initial manifests: %w", err) } + // Seed the manifest cache so the first watch event is applied on top of + // the full initial set rather than replacing it. + c.mu.Lock() + + for _, m := range manifests { + if m != nil { + c.manifestCache[m.InstanceID] = m + } + } + + c.mu.Unlock() + // Convert initial manifests to routes routes := c.ConvertToRoutes(manifests) onChange(routes) // Watch for changes return c.registry.WatchManifests(ctx, serviceName, func(event *farp.ManifestEvent) { + // A registry may deliver nil once it is closed. There is nothing to + // apply in that case, and dereferencing it would panic. + if event == nil || event.Manifest == nil { + return + } + // Update manifest cache c.mu.Lock() @@ -72,27 +116,16 @@ func (c *Client) ConvertToRoutes(manifests []*farp.SchemaManifest) []ServiceRout var routes []ServiceRoute for _, manifest := range manifests { + if manifest == nil { + continue + } + // Fetch schemas for this manifest for _, schemaDesc := range manifest.Schemas { - var ( - schema any - err error - ) - - // Check cache first - - if cached, ok := c.getSchemaFromCache(schemaDesc.Hash); ok { - schema = cached - } else { - // Fetch schema based on location type - schema, err = c.fetchSchema(context.Background(), &schemaDesc) - if err != nil { - // Log error and skip - continue - } - - // Cache the schema - c.cacheSchema(schemaDesc.Hash, schema) + schema, err := c.resolveSchema(context.Background(), manifest.InstanceID, &schemaDesc) + if err != nil { + // Unfetchable or unverifiable schemas produce no routes. + continue } // Convert schema to routes based on type @@ -137,6 +170,53 @@ type ServiceRoute struct { ServiceVersion string } +// resolveSchema returns the schema for a descriptor, from cache when this +// instance has already presented verified content for the same hash. +// +// The hash in a descriptor is supplied by the registrant, so it is never +// trusted on its own: fetched content is hashed again and rejected when it +// does not match. The cache is keyed by instance ID as well as hash, so one +// registrant can never populate the entry another registrant reads. +func (c *Client) resolveSchema(ctx context.Context, instanceID string, desc *farp.SchemaDescriptor) (any, error) { + key := schemaCacheKey{instanceID: instanceID, hash: desc.Hash} + + if cached, ok := c.schemaCache.get(key); ok { + return cached, nil + } + + schema, err := c.fetchSchema(ctx, desc) + if err != nil { + return nil, err + } + + if err := VerifySchemaHash(schema, desc.Hash); err != nil { + return nil, err + } + + c.schemaCache.put(key, schema) + + return schema, nil +} + +// VerifySchemaHash recomputes the SHA-256 checksum of schema with +// farp.CalculateSchemaChecksum and compares it to expected. +func VerifySchemaHash(schema any, expected string) error { + if expected == "" { + return fmt.Errorf("%w: descriptor has no hash", ErrSchemaHashMismatch) + } + + actual, err := farp.CalculateSchemaChecksum(schema) + if err != nil { + return fmt.Errorf("farp gateway: hash schema: %w", err) + } + + if actual != expected { + return fmt.Errorf("%w: descriptor claims %s, content hashes to %s", ErrSchemaHashMismatch, expected, actual) + } + + return nil +} + // fetchSchema fetches a schema based on its location. func (c *Client) fetchSchema(ctx context.Context, descriptor *farp.SchemaDescriptor) (any, error) { switch descriptor.Location.Type { @@ -273,38 +353,96 @@ func (c *Client) convertGraphQLToRoutes(manifest *farp.SchemaManifest, schema an return routes } -// getSchemaFromCache retrieves a cached schema by hash. -func (c *Client) getSchemaFromCache(hash string) (any, bool) { +// ClearCache clears the schema cache. +func (c *Client) ClearCache() { + c.schemaCache.clear() +} + +// GetManifest retrieves a cached manifest by instance ID. +func (c *Client) GetManifest(instanceID string) (*farp.SchemaManifest, bool) { c.mu.RLock() defer c.mu.RUnlock() - schema, ok := c.schemaCache[hash] + manifest, ok := c.manifestCache[instanceID] - return schema, ok + return manifest, ok } -// cacheSchema stores a schema in cache. -func (c *Client) cacheSchema(hash string, schema any) { - c.mu.Lock() - defer c.mu.Unlock() +type schemaCacheKey struct { + instanceID string + hash string +} - c.schemaCache[hash] = schema +type schemaCacheEntry struct { + key schemaCacheKey + schema any } -// ClearCache clears the schema cache. -func (c *Client) ClearCache() { - c.mu.Lock() - defer c.mu.Unlock() +// schemaLRU is a size-bounded least-recently-used cache of verified schemas. +type schemaLRU struct { + mu sync.Mutex + max int + order *list.List + entries map[schemaCacheKey]*list.Element +} + +func newSchemaLRU(maxEntries int) *schemaLRU { + if maxEntries < 1 { + maxEntries = DefaultSchemaCacheSize + } - c.schemaCache = make(map[string]any) + return &schemaLRU{ + max: maxEntries, + order: list.New(), + entries: make(map[schemaCacheKey]*list.Element), + } } -// GetManifest retrieves a cached manifest by instance ID. -func (c *Client) GetManifest(instanceID string) (*farp.SchemaManifest, bool) { - c.mu.RLock() - defer c.mu.RUnlock() +func (l *schemaLRU) get(key schemaCacheKey) (any, bool) { + l.mu.Lock() + defer l.mu.Unlock() - manifest, ok := c.manifestCache[instanceID] + el, ok := l.entries[key] + if !ok { + return nil, false + } - return manifest, ok + l.order.MoveToFront(el) + + return el.Value.(*schemaCacheEntry).schema, true +} + +func (l *schemaLRU) put(key schemaCacheKey, schema any) { + l.mu.Lock() + defer l.mu.Unlock() + + if el, ok := l.entries[key]; ok { + el.Value.(*schemaCacheEntry).schema = schema + l.order.MoveToFront(el) + + return + } + + l.entries[key] = l.order.PushFront(&schemaCacheEntry{key: key, schema: schema}) + + for l.order.Len() > l.max { + oldest := l.order.Back() + l.order.Remove(oldest) + delete(l.entries, oldest.Value.(*schemaCacheEntry).key) + } +} + +func (l *schemaLRU) len() int { + l.mu.Lock() + defer l.mu.Unlock() + + return l.order.Len() +} + +func (l *schemaLRU) clear() { + l.mu.Lock() + defer l.mu.Unlock() + + l.order.Init() + l.entries = make(map[schemaCacheKey]*list.Element) } diff --git a/farp/gateway/client_security_test.go b/farp/gateway/client_security_test.go new file mode 100644 index 000000000..8b2d085c5 --- /dev/null +++ b/farp/gateway/client_security_test.go @@ -0,0 +1,218 @@ +package gateway + +import ( + "context" + "errors" + "fmt" + "strings" + "sync" + "testing" + "time" + + "github.com/xraph/farp" + + "github.com/xraph/forge/farp/registry/memory" +) + +func inlineManifest(t *testing.T, svc, inst string, schema map[string]any, hash string) *farp.SchemaManifest { + t.Helper() + + if hash == "" { + h, err := farp.CalculateSchemaChecksum(schema) + if err != nil { + t.Fatal(err) + } + + hash = h + } + + return &farp.SchemaManifest{ + Version: farp.ProtocolVersion, ServiceName: svc, InstanceID: inst, + Endpoints: farp.SchemaEndpoints{Health: "/health"}, + Schemas: []farp.SchemaDescriptor{{ + Type: farp.SchemaTypeOpenAPI, SpecVersion: "3.1.0", ContentType: "application/json", + Location: farp.SchemaLocation{Type: farp.LocationTypeInline}, + InlineSchema: schema, Hash: hash, + }}, + } +} + +func openAPI(paths ...string) map[string]any { + p := map[string]any{} + for _, path := range paths { + p[path] = map[string]any{"get": map[string]any{}} + } + + return map[string]any{"paths": p} +} + +// An attacker that registers first and claims the victim's schema hash must +// not be able to plant its own routes under the victim's service. +func TestConvertToRoutesRejectsSpoofedSchemaHash(t *testing.T) { + reg := memory.NewRegistry() + ctx := context.Background() + + victimSchema := openAPI("/charge") + + victimHash, err := farp.CalculateSchemaChecksum(victimSchema) + if err != nil { + t.Fatal(err) + } + + evil := inlineManifest(t, "attacker", "evil-1", openAPI("/admin/export"), victimHash) + if err := reg.RegisterManifest(ctx, evil); err != nil { + t.Fatal(err) + } + + victim := inlineManifest(t, "payments", "pay-1", victimSchema, "") + if err := reg.RegisterManifest(ctx, victim); err != nil { + t.Fatal(err) + } + + c := NewClient(reg) + routes := c.ConvertToRoutes([]*farp.SchemaManifest{evil, victim}) + + var paymentPaths []string + + for _, r := range routes { + if r.Path == "/admin/export" { + t.Fatalf("spoofed schema produced route %+v", r) + } + + if r.ServiceName == "payments" { + paymentPaths = append(paymentPaths, r.Path) + } + } + + if len(paymentPaths) != 1 || paymentPaths[0] != "/charge" { + t.Fatalf("payments routes = %v, want [/charge]", paymentPaths) + } +} + +func TestVerifySchemaHash(t *testing.T) { + schema := openAPI("/a") + + good, err := farp.CalculateSchemaChecksum(schema) + if err != nil { + t.Fatal(err) + } + + if err := VerifySchemaHash(schema, good); err != nil { + t.Fatalf("matching hash rejected: %v", err) + } + + if err := VerifySchemaHash(schema, strings.Repeat("a", 64)); !errors.Is(err, ErrSchemaHashMismatch) { + t.Fatalf("mismatched hash: err = %v, want ErrSchemaHashMismatch", err) + } + + if err := VerifySchemaHash(schema, ""); !errors.Is(err, ErrSchemaHashMismatch) { + t.Fatalf("empty hash: err = %v, want ErrSchemaHashMismatch", err) + } +} + +// Two instances presenting identical content get separate cache entries, so +// neither can influence what the other resolves to. +func TestSchemaCacheKeyedByInstance(t *testing.T) { + c := NewClient(memory.NewRegistry()) + schema := openAPI("/x") + + a := inlineManifest(t, "svc", "a", schema, "") + b := inlineManifest(t, "svc", "b", schema, "") + c.ConvertToRoutes([]*farp.SchemaManifest{a, b}) + + if got := c.schemaCache.len(); got != 2 { + t.Fatalf("cache entries = %d, want 2", got) + } +} + +func TestSchemaCacheIsBounded(t *testing.T) { + c := NewClient(memory.NewRegistry(), WithSchemaCacheSize(4)) + + var manifests []*farp.SchemaManifest + for i := range 20 { + manifests = append(manifests, inlineManifest(t, "svc", fmt.Sprintf("i-%d", i), openAPI(fmt.Sprintf("/p%d", i)), "")) + } + + routes := c.ConvertToRoutes(manifests) + if len(routes) != 20 { + t.Fatalf("routes = %d, want 20", len(routes)) + } + + if got := c.schemaCache.len(); got != 4 { + t.Fatalf("cache entries = %d, want 4", got) + } + + c.ClearCache() + + if got := c.schemaCache.len(); got != 0 { + t.Fatalf("cache entries after clear = %d, want 0", got) + } +} + +// Closing the registry under an active WatchServices must not panic or spin. +func TestWatchServicesSurvivesRegistryClose(t *testing.T) { + reg := memory.NewRegistry() + c := NewClient(reg) + + ctx := t.Context() + + var ( + mu sync.Mutex + calls int + ) + + err := c.WatchServices(ctx, "svc", func([]ServiceRoute) { + mu.Lock() + calls++ + mu.Unlock() + }) + if err != nil { + t.Fatal(err) + } + + if err := reg.Close(); err != nil { + t.Fatal(err) + } + + time.Sleep(100 * time.Millisecond) + + mu.Lock() + defer mu.Unlock() + + // Only the initial load should have been reported. + if calls != 1 { + t.Fatalf("onChange calls = %d, want 1", calls) + } +} + +// The first watch event must be applied on top of the initial manifest set, +// not replace it. +func TestWatchServicesKeepsInitialManifests(t *testing.T) { + reg := memory.NewRegistry() + ctx := t.Context() + + if err := reg.RegisterManifest(ctx, inlineManifest(t, "svc", "a", openAPI("/a"), "")); err != nil { + t.Fatal(err) + } + + got := make(chan []ServiceRoute, 4) + + if err := NewClient(reg).WatchServices(ctx, "svc", func(r []ServiceRoute) { got <- r }); err != nil { + t.Fatal(err) + } + + <-got // initial load + + if err := reg.RegisterManifest(ctx, inlineManifest(t, "svc", "b", openAPI("/b"), "")); err != nil { + t.Fatal(err) + } + + select { + case routes := <-got: + if len(routes) != 2 { + t.Fatalf("routes after second registration = %d, want 2", len(routes)) + } + case <-time.After(2 * time.Second): + t.Fatal("no watch event") + } +} From 660921053c553595f75a4aa91c379f2b937271a4 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 21:58:03 -0600 Subject: [PATCH 06/17] fix(farp): stop memory registry watchers on close and stop dropping events After Close the watch goroutine kept receiving nil from the closed channel in a tight loop and passed it to the callback, which made the gateway client panic. notifyWatchers also discarded events once a watcher's 10-slot buffer was full, so a slow consumer could miss a removal for good. Each watch now has its own queue that holds the latest pending event per instance ID and a done channel closed on Close or context cancellation. Delivery never blocks the registry lock, memory stays bounded by the number of instances, and the final state of every instance always reaches the callback. A nil handler is rejected up front. --- farp/registry/memory/registry.go | 132 ++++++++++++++++++++------- farp/registry/memory/watch_test.go | 141 +++++++++++++++++++++++++++++ 2 files changed, 240 insertions(+), 33 deletions(-) create mode 100644 farp/registry/memory/watch_test.go diff --git a/farp/registry/memory/registry.go b/farp/registry/memory/registry.go index 6653802b1..7c3053931 100644 --- a/farp/registry/memory/registry.go +++ b/farp/registry/memory/registry.go @@ -16,7 +16,7 @@ type Registry struct { mu sync.RWMutex manifests map[string]*farp.SchemaManifest // key: instanceID schemas map[string]any // key: registry path - watchers map[string][]chan *farp.ManifestEvent + watchers map[string][]*watcher closed bool } @@ -25,7 +25,7 @@ func NewRegistry() *Registry { return &Registry{ manifests: make(map[string]*farp.SchemaManifest), schemas: make(map[string]any), - watchers: make(map[string][]chan *farp.ManifestEvent), + watchers: make(map[string][]*watcher), } } @@ -180,7 +180,17 @@ func (r *Registry) DeleteSchema(ctx context.Context, path string) error { } // WatchManifests watches for manifest changes for a service. +// +// Events are delivered on a goroutine owned by the watch. Delivery never +// blocks the registry and never loses the latest state of an instance: when +// the callback falls behind, pending events for the same instance are +// coalesced so only the most recent one is delivered. The watch ends when ctx +// is cancelled or the registry is closed. func (r *Registry) WatchManifests(ctx context.Context, serviceName string, onChange farp.ManifestChangeHandler) error { + if onChange == nil { + return errors.New("memory registry: onChange handler is required") + } + r.mu.Lock() if r.closed { @@ -189,20 +199,23 @@ func (r *Registry) WatchManifests(ctx context.Context, serviceName string, onCha return farp.ErrBackendUnavailable } - eventChan := make(chan *farp.ManifestEvent, 10) - r.watchers[serviceName] = append(r.watchers[serviceName], eventChan) + w := newWatcher() + r.watchers[serviceName] = append(r.watchers[serviceName], w) r.mu.Unlock() - // Watch for events until context is cancelled go func() { for { select { case <-ctx.Done(): - r.removeWatcher(serviceName, eventChan) + r.removeWatcher(serviceName, w) return - case event := <-eventChan: - onChange(event) + case <-w.done: + return + case <-w.signal: + for _, event := range w.drain() { + onChange(event) + } } } }() @@ -228,10 +241,10 @@ func (r *Registry) Close() error { r.closed = true - // Close all watcher channels + // Stop all watch goroutines for _, watchers := range r.watchers { - for _, ch := range watchers { - close(ch) + for _, w := range watchers { + w.stop() } } @@ -254,44 +267,97 @@ func (r *Registry) Health(ctx context.Context) error { // notifyWatchers notifies all watchers for a service (must be called with lock held). func (r *Registry) notifyWatchers(serviceName string, event *farp.ManifestEvent) { - // Notify specific service watchers - if watchers, ok := r.watchers[serviceName]; ok { - for _, ch := range watchers { - select { - case ch <- event: - default: - // Channel full, skip - } - } + for _, w := range r.watchers[serviceName] { + w.enqueue(event) } // Notify global watchers (empty service name) - if watchers, ok := r.watchers[""]; ok { - for _, ch := range watchers { - select { - case ch <- event: - default: - // Channel full, skip - } + if serviceName != "" { + for _, w := range r.watchers[""] { + w.enqueue(event) } } } -// removeWatcher removes a watcher channel. -func (r *Registry) removeWatcher(serviceName string, eventChan chan *farp.ManifestEvent) { +// removeWatcher removes a watcher and stops its goroutine. +func (r *Registry) removeWatcher(serviceName string, w *watcher) { r.mu.Lock() defer r.mu.Unlock() watchers := r.watchers[serviceName] - for i, ch := range watchers { - if ch == eventChan { + for i, candidate := range watchers { + if candidate == w { r.watchers[serviceName] = append(watchers[:i], watchers[i+1:]...) - close(eventChan) - break } } + + w.stop() +} + +// watcher buffers events for one WatchManifests subscription. +// +// The queue holds at most one pending event per instance ID, so its size is +// bounded by the number of instances while still preserving each instance's +// latest state. A slow consumer therefore sees coalesced updates instead of +// silently missing a removal or registration. +type watcher struct { + mu sync.Mutex + order []string + pending map[string]*farp.ManifestEvent + signal chan struct{} + done chan struct{} + once sync.Once +} + +func newWatcher() *watcher { + return &watcher{ + pending: make(map[string]*farp.ManifestEvent), + signal: make(chan struct{}, 1), + done: make(chan struct{}), + } +} + +func (w *watcher) enqueue(event *farp.ManifestEvent) { + if event == nil || event.Manifest == nil { + return + } + + id := event.Manifest.InstanceID + + w.mu.Lock() + if _, ok := w.pending[id]; !ok { + w.order = append(w.order, id) + } + + w.pending[id] = event + w.mu.Unlock() + + select { + case w.signal <- struct{}{}: + default: + // A wake-up is already pending; the drain will pick this event up. + } +} + +func (w *watcher) drain() []*farp.ManifestEvent { + w.mu.Lock() + defer w.mu.Unlock() + + events := make([]*farp.ManifestEvent, 0, len(w.order)) + for _, id := range w.order { + events = append(events, w.pending[id]) + } + + w.order = nil + w.pending = make(map[string]*farp.ManifestEvent) + + return events +} + +func (w *watcher) stop() { + w.once.Do(func() { close(w.done) }) } // Clear removes all manifests and schemas (useful for testing). diff --git a/farp/registry/memory/watch_test.go b/farp/registry/memory/watch_test.go new file mode 100644 index 000000000..b52c3380c --- /dev/null +++ b/farp/registry/memory/watch_test.go @@ -0,0 +1,141 @@ +package memory + +import ( + "context" + "fmt" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/xraph/farp" +) + +func watchManifest(t *testing.T, svc, inst string) *farp.SchemaManifest { + t.Helper() + + schema := map[string]any{"paths": map[string]any{}} + + hash, err := farp.CalculateSchemaChecksum(schema) + if err != nil { + t.Fatal(err) + } + + return &farp.SchemaManifest{ + Version: farp.ProtocolVersion, ServiceName: svc, InstanceID: inst, + Endpoints: farp.SchemaEndpoints{Health: "/health"}, + Schemas: []farp.SchemaDescriptor{{ + Type: farp.SchemaTypeOpenAPI, SpecVersion: "3.1.0", ContentType: "application/json", + Location: farp.SchemaLocation{Type: farp.LocationTypeInline}, + InlineSchema: schema, Hash: hash, + }}, + } +} + +// After Close the watch goroutine must exit instead of spinning on a closed +// channel and invoking the callback with nil events. +func TestWatchManifestsStopsAfterClose(t *testing.T) { + reg := NewRegistry() + + var calls, nils atomic.Int64 + + err := reg.WatchManifests(context.Background(), "svc", func(ev *farp.ManifestEvent) { + calls.Add(1) + + if ev == nil { + nils.Add(1) + } + }) + if err != nil { + t.Fatal(err) + } + + if err := reg.Close(); err != nil { + t.Fatal(err) + } + + time.Sleep(100 * time.Millisecond) + + if calls.Load() != 0 || nils.Load() != 0 { + t.Fatalf("after Close: %d callbacks (%d nil), want 0", calls.Load(), nils.Load()) + } +} + +// A slow consumer must still observe the final state of every instance even +// when far more events are produced than the old 10-slot buffer held. +func TestWatchManifestsSlowConsumerDoesNotLoseState(t *testing.T) { + reg := NewRegistry() + ctx := t.Context() + + release := make(chan struct{}) + + var ( + mu sync.Mutex + seen = map[string]farp.EventType{} + ) + + err := reg.WatchManifests(ctx, "svc", func(ev *farp.ManifestEvent) { + <-release + + mu.Lock() + seen[ev.Manifest.InstanceID] = ev.Type + mu.Unlock() + }) + if err != nil { + t.Fatal(err) + } + + const n = 200 + for i := range n { + if err := reg.RegisterManifest(ctx, watchManifest(t, "svc", fmt.Sprintf("i-%d", i))); err != nil { + t.Fatal(err) + } + } + + // Remove every other instance so the final state differs from the first event. + for i := 0; i < n; i += 2 { + if err := reg.DeleteManifest(ctx, fmt.Sprintf("i-%d", i)); err != nil { + t.Fatal(err) + } + } + + close(release) + + deadline := time.Now().Add(5 * time.Second) + + for { + mu.Lock() + got := len(seen) + mu.Unlock() + + if got == n { + break + } + + if time.Now().After(deadline) { + t.Fatalf("saw %d of %d instances", got, n) + } + + time.Sleep(10 * time.Millisecond) + } + + mu.Lock() + defer mu.Unlock() + + for i := range n { + want := farp.EventTypeAdded + if i%2 == 0 { + want = farp.EventTypeRemoved + } + + if got := seen[fmt.Sprintf("i-%d", i)]; got != want { + t.Fatalf("instance i-%d final event = %s, want %s", i, got, want) + } + } +} + +func TestWatchManifestsRequiresHandler(t *testing.T) { + if err := NewRegistry().WatchManifests(context.Background(), "svc", nil); err == nil { + t.Fatal("nil handler accepted") + } +} From 628691e3d0a4ec2b4eccbf0705d1478114262c40 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:01:36 -0600 Subject: [PATCH 07/17] fix(discovery): deregister from the gateway by instance id and authenticate gateway calls Stop sent DELETE /_farp/v1/deregister/{id} with the service name, unescaped, so the gateway never matched the registration it had stored under the instance ID. It also rebuilt the instance on shutdown, which produces a new generated ID when none is configured. Stop now uses the instance registered at startup and path escapes its ID, and an empty ID is an error. Register and deregister requests carried no credentials and there was no way to configure any. FARPConfig gains GatewayToken, sent as a bearer token on both calls, and GatewayTLS (CA file, client cert and key, server name) for private CAs and mutual TLS. The client is built once; an invalid TLS configuration fails Run instead of being retried forever, and a token over plain http logs a warning. Also renames a loop variable that shadowed the cap builtin so the module lints clean. --- extensions/discovery/config.go | 34 +++++ extensions/discovery/extension.go | 58 ++++++-- extensions/discovery/gateway_client.go | 107 +++++++++++++++ extensions/discovery/gateway_push_test.go | 155 ++++++++++++++++++++++ extensions/discovery/schema_publisher.go | 4 +- 5 files changed, 344 insertions(+), 14 deletions(-) create mode 100644 extensions/discovery/gateway_client.go create mode 100644 extensions/discovery/gateway_push_test.go diff --git a/extensions/discovery/config.go b/extensions/discovery/config.go index ba8e72f67..f152ec4d6 100644 --- a/extensions/discovery/config.go +++ b/extensions/discovery/config.go @@ -82,6 +82,15 @@ type FARPConfig struct { // Example: "http://localhost:7903" GatewayURL string `json:"gateway_url" yaml:"gateway_url"` + // GatewayToken is sent as "Authorization: Bearer " on gateway + // register and deregister requests. Leave empty when the gateway does not + // authenticate pushes. Prefer an https GatewayURL when setting it. + GatewayToken string `json:"gateway_token,omitempty" yaml:"gateway_token,omitempty"` + + // GatewayTLS configures the TLS client used for gateway requests, for a + // private CA or mutual TLS. It only applies to https GatewayURLs. + GatewayTLS GatewayTLSConfig `json:"gateway_tls" yaml:"gateway_tls"` + // ExcludeInternalPaths filters out internal framework paths (/_farp/*, /_/*, /docs/*, etc.) // from the OpenAPI/AsyncAPI schemas published to the gateway. // Default: true @@ -107,6 +116,20 @@ type FARPConfig struct { PathRules []farp.PathRule `json:"path_rules,omitempty" yaml:"path_rules,omitempty"` } +// GatewayTLSConfig configures TLS for requests to the FARP gateway. +type GatewayTLSConfig struct { + // CAFile is a PEM bundle used instead of the system roots to verify the gateway. + CAFile string `json:"ca_file,omitempty" yaml:"ca_file,omitempty"` + + // CertFile and KeyFile are a PEM client certificate and key presented to + // the gateway for mutual TLS. Both must be set together. + CertFile string `json:"cert_file,omitempty" yaml:"cert_file,omitempty"` + KeyFile string `json:"key_file,omitempty" yaml:"key_file,omitempty"` + + // ServerName overrides the name used to verify the gateway certificate. + ServerName string `json:"server_name,omitempty" yaml:"server_name,omitempty"` +} + // ShouldExcludeInternalPaths returns whether internal paths should be filtered. // Defaults to true when not explicitly set. func (c *FARPConfig) ShouldExcludeInternalPaths() bool { @@ -480,6 +503,17 @@ func WithFARPGatewayURL(url string) ConfigOption { return func(c *Config) { c.FARP.GatewayURL = url } } +// WithFARPGatewayToken sets the bearer token sent with gateway register and +// deregister requests. +func WithFARPGatewayToken(token string) ConfigOption { + return func(c *Config) { c.FARP.GatewayToken = token } +} + +// WithFARPGatewayTLS sets the TLS client configuration for gateway requests. +func WithFARPGatewayTLS(cfg GatewayTLSConfig) ConfigOption { + return func(c *Config) { c.FARP.GatewayTLS = cfg } +} + // WithFARPExcludeInternalPaths sets whether internal framework paths are filtered // from published schemas. Default is true. func WithFARPExcludeInternalPaths(exclude bool) ConfigOption { diff --git a/extensions/discovery/extension.go b/extensions/discovery/extension.go index ef34d38bc..6d3625395 100644 --- a/extensions/discovery/extension.go +++ b/extensions/discovery/extension.go @@ -8,6 +8,7 @@ import ( "maps" "net" "net/http" + "net/url" "os" "strconv" "strings" @@ -37,6 +38,9 @@ type Extension struct { serviceNode *farpdiscovery.ServiceNode // FARP service node for schema publishing serviceInstance *ServiceInstance // Store the registered service instance discoveryService *Service // Resolved discovery service (stored for deferred FARP init) + + gatewayClientMu sync.Mutex + gatewayHTTP *http.Client // built from FARP gateway config on first use } // NewExtension creates a new service discovery extension. @@ -453,10 +457,13 @@ func (e *Extension) Stop(ctx context.Context) error { e.Logger().Info("FARP ServiceNode stopped") } - // Also deregister from gateway if push was configured + // Also deregister from gateway if push was configured. The gateway + // keys registrations by instance ID, so deregister the instance that + // was actually registered rather than rebuilding one, whose generated + // ID may differ. if e.config.FARP.GatewayURL != "" { - instance := e.createServiceInstance() - if err := e.deregisterFromGateway(ctx, instance.Name); err != nil { + instance := e.registeredInstance() + if err := e.deregisterFromGateway(ctx, instance.ID); err != nil { e.Logger().Warn("failed to deregister from gateway", forge.F("error", err), ) @@ -466,7 +473,7 @@ func (e *Extension) Stop(ctx context.Context) error { // No ServiceNode — deregister manually discoveryService, err := forge.InjectType[*Service](e.App().Container()) if err == nil { - instance := e.createServiceInstance() + instance := e.registeredInstance() if err := discoveryService.Backend().Deregister(ctx, instance.ID); err != nil { e.Logger().Warn("failed to deregister service", forge.F("service_id", instance.ID), @@ -516,6 +523,18 @@ func (e *Extension) Run(ctx context.Context) error { // request that the gateway will immediately make upon receiving the push. // Retries continuously with backoff until success or shutdown. if e.config.FARP.Enabled && e.config.FARP.GatewayURL != "" && instance != nil && node != nil { + // Build the gateway client up front so a broken TLS configuration + // fails the run instead of being retried forever in the background. + if _, err := e.gatewayClient(); err != nil { + return err + } + + if e.config.FARP.GatewayToken != "" && strings.HasPrefix(strings.ToLower(e.config.FARP.GatewayURL), "http://") { + e.Logger().Warn("FARP gateway token is sent over plain http; use an https gateway_url", + forge.F("gateway_url", e.config.FARP.GatewayURL), + ) + } + enriched := e.enrichInstanceFromManifest(instance, node) e.wg.Add(1) @@ -1044,8 +1063,12 @@ func (e *Extension) pushToGateway(ctx context.Context, instance *ServiceInstance } req.Header.Set("Content-Type", "application/json") + e.authorizeGatewayRequest(req) - client := &http.Client{Timeout: 10 * time.Second} + client, err := e.gatewayClient() + if err != nil { + return err + } resp, err := client.Do(req) if err != nil { @@ -1060,22 +1083,33 @@ func (e *Extension) pushToGateway(ctx context.Context, instance *ServiceInstance return nil } -// deregisterFromGateway sends a DELETE to the gateway to remove this service. -// Uses the FARP v1 push protocol (spec section 17.4): +// deregisterFromGateway sends a DELETE to the gateway to remove this +// instance. Uses the FARP v1 push protocol (spec section 17.4): // // DELETE /_farp/v1/deregister/{id} -func (e *Extension) deregisterFromGateway(ctx context.Context, serviceName string) error { - gatewayURL := strings.TrimRight(e.config.FARP.GatewayURL, "/") + "/_farp/v1/deregister/" + serviceName +// +// The id is the instance ID used at registration, path escaped so IDs with +// reserved characters address the right resource. +func (e *Extension) deregisterFromGateway(ctx context.Context, instanceID string) error { + if instanceID == "" { + return errors.New("deregister from gateway: empty instance id") + } + + gatewayURL := strings.TrimRight(e.config.FARP.GatewayURL, "/") + "/_farp/v1/deregister/" + url.PathEscape(instanceID) - //nolint:gosec // G704: the gateway URL comes from operator config (FARP.GatewayURL), not from request input req, err := http.NewRequestWithContext(ctx, http.MethodDelete, gatewayURL, nil) if err != nil { return fmt.Errorf("create deregistration request: %w", err) } - client := &http.Client{Timeout: 10 * time.Second} + e.authorizeGatewayRequest(req) - resp, err := client.Do(req) //nolint:gosec // G704: request targets the operator-configured gateway, see above + client, err := e.gatewayClient() + if err != nil { + return err + } + + resp, err := client.Do(req) if err != nil { return fmt.Errorf("push deregistration to gateway: %w", err) } diff --git a/extensions/discovery/gateway_client.go b/extensions/discovery/gateway_client.go new file mode 100644 index 000000000..3259e30c8 --- /dev/null +++ b/extensions/discovery/gateway_client.go @@ -0,0 +1,107 @@ +package discovery + +import ( + "crypto/tls" + "crypto/x509" + "fmt" + "net/http" + "os" + "time" + + "github.com/xraph/forge/errors" +) + +// gatewayRequestTimeout bounds each register or deregister call to the gateway. +const gatewayRequestTimeout = 10 * time.Second + +// gatewayClient returns the HTTP client for FARP gateway requests, building it +// from config on first use. An invalid TLS configuration is returned as an +// error rather than falling back to an unauthenticated client. +func (e *Extension) gatewayClient() (*http.Client, error) { + e.gatewayClientMu.Lock() + defer e.gatewayClientMu.Unlock() + + if e.gatewayHTTP != nil { + return e.gatewayHTTP, nil + } + + tlsCfg, err := e.config.FARP.GatewayTLS.build() + if err != nil { + return nil, fmt.Errorf("farp gateway tls: %w", err) + } + + client := &http.Client{Timeout: gatewayRequestTimeout} + + if tlsCfg != nil { + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.TLSClientConfig = tlsCfg + client.Transport = transport + } + + e.gatewayHTTP = client + + return client, nil +} + +// authorizeGatewayRequest attaches the configured bearer token, if any. +func (e *Extension) authorizeGatewayRequest(req *http.Request) { + if e.config.FARP.GatewayToken != "" { + req.Header.Set("Authorization", "Bearer "+e.config.FARP.GatewayToken) + } +} + +// registeredInstance returns the instance registered at startup, falling back +// to a freshly built one when startup never got that far. +func (e *Extension) registeredInstance() *ServiceInstance { + e.mu.RLock() + instance := e.serviceInstance + e.mu.RUnlock() + + if instance != nil { + return instance + } + + return e.createServiceInstance() +} + +// build returns nil when no TLS option is set, so the default transport and +// system roots are used. +func (c GatewayTLSConfig) build() (*tls.Config, error) { + if c.CAFile == "" && c.CertFile == "" && c.KeyFile == "" && c.ServerName == "" { + return nil, nil //nolint:nilnil // nil config means use the default transport + } + + cfg := &tls.Config{ + MinVersion: tls.VersionTLS12, + ServerName: c.ServerName, + } + + if c.CAFile != "" { + pem, err := os.ReadFile(c.CAFile) + if err != nil { + return nil, fmt.Errorf("read ca file: %w", err) + } + + pool := x509.NewCertPool() + if !pool.AppendCertsFromPEM(pem) { + return nil, fmt.Errorf("ca file %s contains no PEM certificates", c.CAFile) + } + + cfg.RootCAs = pool + } + + if (c.CertFile == "") != (c.KeyFile == "") { + return nil, errors.New("cert_file and key_file must be set together") + } + + if c.CertFile != "" { + cert, err := tls.LoadX509KeyPair(c.CertFile, c.KeyFile) + if err != nil { + return nil, fmt.Errorf("load client certificate: %w", err) + } + + cfg.Certificates = []tls.Certificate{cert} + } + + return cfg, nil +} diff --git a/extensions/discovery/gateway_push_test.go b/extensions/discovery/gateway_push_test.go new file mode 100644 index 000000000..02e6f1c0d --- /dev/null +++ b/extensions/discovery/gateway_push_test.go @@ -0,0 +1,155 @@ +package discovery + +import ( + "encoding/pem" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" +) + +type gatewayRecorder struct { + mu sync.Mutex + reqs []recordedGatewayRequest +} + +type recordedGatewayRequest struct { + method, escapedPath, auth string +} + +func (g *gatewayRecorder) handler(w http.ResponseWriter, r *http.Request) { + g.mu.Lock() + g.reqs = append(g.reqs, recordedGatewayRequest{r.Method, r.URL.EscapedPath(), r.Header.Get("Authorization")}) + g.mu.Unlock() + w.WriteHeader(http.StatusOK) +} + +// Deregistration must address the registered instance by its ID, path +// escaped, and both calls must carry the configured bearer token. +func TestGatewayPushAndDeregisterUseInstanceIDAndToken(t *testing.T) { + rec := &gatewayRecorder{} + + srv := httptest.NewServer(http.HandlerFunc(rec.handler)) + defer srv.Close() + + e := &Extension{config: Config{FARP: FARPConfig{GatewayURL: srv.URL, GatewayToken: "s3cret"}}} + inst := &ServiceInstance{ID: "payments/7f9c replica-2", Name: "payments", Address: "10.0.0.7", Port: 8080} + e.serviceInstance = inst + + if err := e.pushToGateway(t.Context(), inst); err != nil { + t.Fatal(err) + } + + if err := e.deregisterFromGateway(t.Context(), e.registeredInstance().ID); err != nil { + t.Fatal(err) + } + + rec.mu.Lock() + defer rec.mu.Unlock() + + if len(rec.reqs) != 2 { + t.Fatalf("gateway saw %d requests, want 2", len(rec.reqs)) + } + + for _, r := range rec.reqs { + if r.auth != "Bearer s3cret" { + t.Fatalf("%s %s: Authorization = %q, want bearer token", r.method, r.escapedPath, r.auth) + } + } + + del := rec.reqs[1] + if del.method != http.MethodDelete || del.escapedPath != "/_farp/v1/deregister/payments%2F7f9c%20replica-2" { + t.Fatalf("deregister request = %s %s", del.method, del.escapedPath) + } +} + +func TestGatewayRequestsOmitAuthWithoutToken(t *testing.T) { + rec := &gatewayRecorder{} + + srv := httptest.NewServer(http.HandlerFunc(rec.handler)) + defer srv.Close() + + e := &Extension{config: Config{FARP: FARPConfig{GatewayURL: srv.URL}}} + if err := e.deregisterFromGateway(t.Context(), "id-1"); err != nil { + t.Fatal(err) + } + + if got := rec.reqs[0].auth; got != "" { + t.Fatalf("Authorization = %q, want none", got) + } +} + +func TestDeregisterFromGatewayRejectsEmptyID(t *testing.T) { + e := &Extension{config: Config{FARP: FARPConfig{GatewayURL: "http://127.0.0.1:1"}}} + if err := e.deregisterFromGateway(t.Context(), ""); err == nil { + t.Fatal("empty instance id accepted") + } +} + +// A gateway behind a private CA is reachable once GatewayTLS.CAFile is set. +func TestGatewayTLSUsesConfiguredCA(t *testing.T) { + rec := &gatewayRecorder{} + + srv := httptest.NewTLSServer(http.HandlerFunc(rec.handler)) + defer srv.Close() + + // Without the CA the request must fail verification. + plain := &Extension{config: Config{FARP: FARPConfig{GatewayURL: srv.URL}}} + if err := plain.deregisterFromGateway(t.Context(), "id-1"); err == nil { + t.Fatal("request to untrusted gateway succeeded") + } + + caFile := filepath.Join(t.TempDir(), "ca.pem") + + caPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: srv.Certificate().Raw}) + if err := os.WriteFile(caFile, caPEM, 0o600); err != nil { + t.Fatal(err) + } + + e := &Extension{config: Config{FARP: FARPConfig{ + GatewayURL: srv.URL, + GatewayTLS: GatewayTLSConfig{CAFile: caFile}, + }}} + if err := e.deregisterFromGateway(t.Context(), "id-1"); err != nil { + t.Fatalf("request with configured CA failed: %v", err) + } +} + +func TestGatewayTLSConfigErrors(t *testing.T) { + dir := t.TempDir() + notPEM := filepath.Join(dir, "bad.pem") + + if err := os.WriteFile(notPEM, []byte("not a certificate"), 0o600); err != nil { + t.Fatal(err) + } + + cases := map[string]GatewayTLSConfig{ + "missing ca": {CAFile: filepath.Join(dir, "missing.pem")}, + "ca without pem": {CAFile: notPEM}, + "cert no key": {CertFile: notPEM}, + "key no cert": {KeyFile: notPEM}, + "bad key pair": {CertFile: notPEM, KeyFile: notPEM}, + } + + for name, cfg := range cases { + t.Run(name, func(t *testing.T) { + e := &Extension{config: Config{FARP: FARPConfig{GatewayURL: "https://gw", GatewayTLS: cfg}}} + if _, err := e.gatewayClient(); err == nil || !strings.Contains(err.Error(), "farp gateway tls") { + t.Fatalf("err = %v, want farp gateway tls error", err) + } + }) + } +} + +func TestGatewayConfigOptions(t *testing.T) { + cfg := DefaultConfig() + WithFARPGatewayToken("tok")(&cfg) + WithFARPGatewayTLS(GatewayTLSConfig{ServerName: "gw.internal"})(&cfg) + + if cfg.FARP.GatewayToken != "tok" || cfg.FARP.GatewayTLS.ServerName != "gw.internal" { + t.Fatalf("options not applied: %+v", cfg.FARP) + } +} diff --git a/extensions/discovery/schema_publisher.go b/extensions/discovery/schema_publisher.go index 682ca26a1..862dc7a9d 100644 --- a/extensions/discovery/schema_publisher.go +++ b/extensions/discovery/schema_publisher.go @@ -50,8 +50,8 @@ func (p *SchemaPublisher) Publish(ctx context.Context, instanceID string) error ) // Add capabilities - for _, cap := range p.config.Capabilities { - manifest.AddCapability(cap) + for _, capability := range p.config.Capabilities { + manifest.AddCapability(capability) } // Set endpoints with defaults. From 245176858be5f0fa2b98671984c0dea385d5325b Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:05:27 -0600 Subject: [PATCH 08/17] fix(discovery): honour etcd TLS settings and keep registrations across lease loss TLSEnabled, TLSCAFile, TLSCert and TLSKey were ignored, so the client spoke plaintext h2c and sent the configured username and password in the clear. NewEtcdBackend now builds a tls.Config from them (system roots unless a CA file is given, optional client certificate). Setting TLS files without TLSEnabled, a certificate without its key, or an unreadable file is an error instead of a silent fallback to plaintext. When the keep-alive stream ended the backend granted a new lease but never wrote its registrations again, so the service vanished from etcd once the old lease expired. Registered instances are now remembered and put again under the new lease, with backoff while etcd is unreachable; Deregister forgets them so they are not resurrected. The lease ID was read and written from several goroutines without a lock; it is now guarded, and Register holds the same lock so it cannot write under a lease being replaced. Register before Initialize returns ErrEtcdNotInitialized rather than writing a key with no lease that would never expire. Background goroutines (keep-alive, lease grants, watches) run on a context that Close cancels, and each grant and re-put has a deadline, so Close no longer waits on a stalled etcd call. A watch whose channel closes is re-established instead of spinning on the closed channel. --- extensions/discovery/backends/etcd.go | 333 +++++++++++++++--- .../discovery/backends/etcd_lease_tls_test.go | 290 +++++++++++++++ 2 files changed, 577 insertions(+), 46 deletions(-) create mode 100644 extensions/discovery/backends/etcd_lease_tls_test.go diff --git a/extensions/discovery/backends/etcd.go b/extensions/discovery/backends/etcd.go index af999331c..b1e877275 100644 --- a/extensions/discovery/backends/etcd.go +++ b/extensions/discovery/backends/etcd.go @@ -2,9 +2,12 @@ package backends import ( "context" + "crypto/tls" + "crypto/x509" "encoding/json" "errors" "fmt" + "os" "path" "strings" "sync" @@ -13,16 +16,62 @@ import ( clientv3 "go.etcd.io/etcd/client/v3" ) +// etcdOpTimeout bounds individual etcd calls made from background goroutines, +// so a stalled cluster cannot block lease recovery or Close indefinitely. +const etcdOpTimeout = 5 * time.Second + +// ErrEtcdNotInitialized is returned when Register is called before +// Initialize has created the registration lease. +var ErrEtcdNotInitialized = errors.New("etcd backend not initialized: call Initialize before Register") + // EtcdBackend implements service discovery using etcd. type EtcdBackend struct { client *clientv3.Client config EtcdConfig - leaseID clientv3.LeaseID watchers map[string][]func([]*ServiceInstance) mu sync.RWMutex stopCh chan struct{} wg sync.WaitGroup leaseTTL int64 + + // ctx is cancelled by Close so background etcd calls (keep-alive, lease + // grants, watches) return promptly instead of holding Close up. + ctx context.Context //nolint:containedctx // lifetime context for background goroutines, cancelled by Close + cancel context.CancelFunc + + // leaseMu guards leaseID and registered. Registrations are remembered so + // they can be written again under a new lease after the old one expires. + leaseMu sync.Mutex + leaseID clientv3.LeaseID + registered map[string]etcdRegistration // key: instance ID + + ops etcdOps +} + +type etcdRegistration struct { + key string + value string +} + +// etcdOps is the subset of etcd writes the backend performs. It exists so +// lease and registration bookkeeping can be tested without an etcd server. +type etcdOps interface { + put(ctx context.Context, key, value string, lease clientv3.LeaseID) error + delete(ctx context.Context, key string) error +} + +type clientOps struct{ client *clientv3.Client } + +func (c clientOps) put(ctx context.Context, key, value string, lease clientv3.LeaseID) error { + _, err := c.client.Put(ctx, key, value, clientv3.WithLease(lease)) + + return err +} + +func (c clientOps) delete(ctx context.Context, key string) error { + _, err := c.client.Delete(ctx, key) + + return err } // NewEtcdBackend creates a new etcd backend. @@ -39,13 +88,13 @@ func NewEtcdBackend(config EtcdConfig) (*EtcdBackend, error) { clientConfig.Password = config.Password } - // TLS configuration - if config.TLSEnabled { - // TODO: Add TLS configuration - // tlsConfig := &tls.Config{...} - // clientConfig.TLS = tlsConfig + tlsConfig, err := buildEtcdTLSConfig(config) + if err != nil { + return nil, err } + clientConfig.TLS = tlsConfig + // Create client client, err := clientv3.New(clientConfig) if err != nil { @@ -57,13 +106,71 @@ func NewEtcdBackend(config EtcdConfig) (*EtcdBackend, error) { config.KeyPrefix = "/services" } + b := newEtcdBackend(config, clientOps{client: client}) + b.client = client + + return b, nil +} + +func newEtcdBackend(config EtcdConfig, ops etcdOps) *EtcdBackend { + ctx, cancel := context.WithCancel(context.Background()) + return &EtcdBackend{ - client: client, - config: config, - watchers: make(map[string][]func([]*ServiceInstance)), - stopCh: make(chan struct{}), - leaseTTL: 30, // 30 second lease TTL - }, nil + config: config, + watchers: make(map[string][]func([]*ServiceInstance)), + stopCh: make(chan struct{}), + leaseTTL: 30, // 30 second lease TTL + ctx: ctx, + cancel: cancel, + registered: make(map[string]etcdRegistration), + ops: ops, + } +} + +// buildEtcdTLSConfig turns the TLS fields of EtcdConfig into a tls.Config. +// +// It returns nil when TLS is disabled. TLS file settings without TLSEnabled, +// or a certificate without its key, are configuration errors: silently +// falling back to plaintext would send credentials in the clear. +func buildEtcdTLSConfig(config EtcdConfig) (*tls.Config, error) { + if !config.TLSEnabled { + if config.TLSCAFile != "" || config.TLSCert != "" || config.TLSKey != "" { + return nil, errors.New("etcd: tls_ca_file, tls_cert or tls_key is set but tls_enabled is false") + } + + return nil, nil //nolint:nilnil // nil config means plaintext, which the caller asked for + } + + cfg := &tls.Config{MinVersion: tls.VersionTLS12} + + if config.TLSCAFile != "" { + pem, err := os.ReadFile(config.TLSCAFile) + if err != nil { + return nil, fmt.Errorf("etcd: read tls_ca_file: %w", err) + } + + pool := x509.NewCertPool() + if !pool.AppendCertsFromPEM(pem) { + return nil, fmt.Errorf("etcd: tls_ca_file %s contains no PEM certificates", config.TLSCAFile) + } + + cfg.RootCAs = pool + } + + if (config.TLSCert == "") != (config.TLSKey == "") { + return nil, errors.New("etcd: tls_cert and tls_key must be set together") + } + + if config.TLSCert != "" { + cert, err := tls.LoadX509KeyPair(config.TLSCert, config.TLSKey) + if err != nil { + return nil, fmt.Errorf("etcd: load client certificate: %w", err) + } + + cfg.Certificates = []tls.Certificate{cert} + } + + return cfg, nil } // Name returns the backend name. @@ -88,17 +195,30 @@ func (b *EtcdBackend) Initialize(ctx context.Context) error { return fmt.Errorf("failed to create etcd lease: %w", err) } - b.leaseID = lease.ID + b.setLease(lease.ID) - // Start lease keep-alive. It runs until Close, so it must not inherit - // the caller's cancellation. + // Start lease keep-alive. It runs until Close, on the backend's own + // context, so it does not inherit the caller's cancellation. b.wg.Add(1) - go b.keepAliveLease(context.WithoutCancel(ctx)) + go b.keepAliveLease() return nil } +func (b *EtcdBackend) currentLease() clientv3.LeaseID { + b.leaseMu.Lock() + defer b.leaseMu.Unlock() + + return b.leaseID +} + +func (b *EtcdBackend) setLease(id clientv3.LeaseID) { + b.leaseMu.Lock() + b.leaseID = id + b.leaseMu.Unlock() +} + // Register registers a service instance with etcd. func (b *EtcdBackend) Register(ctx context.Context, instance *ServiceInstance) error { if instance.ID == "" { @@ -118,12 +238,26 @@ func (b *EtcdBackend) Register(ctx context.Context, instance *ServiceInstance) e // Build key: /services/{service-name}/{instance-id} key := b.buildServiceKey(instance.Name, instance.ID) - // Put with lease - _, err = b.client.Put(ctx, key, string(data), clientv3.WithLease(b.leaseID)) - if err != nil { + // Hold leaseMu across the put so a concurrent lease replacement either + // sees this registration or happens before it and hands us the new lease. + b.leaseMu.Lock() + + lease := b.leaseID + if lease == 0 { + b.leaseMu.Unlock() + + return ErrEtcdNotInitialized + } + + if err := b.ops.put(ctx, key, string(data), lease); err != nil { + b.leaseMu.Unlock() + return fmt.Errorf("failed to register service with etcd: %w", err) } + b.registered[instance.ID] = etcdRegistration{key: key, value: string(data)} + b.leaseMu.Unlock() + // Notify watchers b.notifyWatchers(instance.Name) @@ -132,6 +266,21 @@ func (b *EtcdBackend) Register(ctx context.Context, instance *ServiceInstance) e // Deregister deregisters a service instance from etcd. func (b *EtcdBackend) Deregister(ctx context.Context, serviceID string) error { + // Instances registered through this backend have a known key, and must be + // forgotten so lease recovery does not write them back. + b.leaseMu.Lock() + reg, ok := b.registered[serviceID] + delete(b.registered, serviceID) + b.leaseMu.Unlock() + + if ok { + if err := b.ops.delete(ctx, reg.key); err != nil { + return fmt.Errorf("failed to deregister service from etcd: %w", err) + } + + return nil + } + // Find and delete the service key // We need to search for the key since we don't know the service name prefix := b.config.KeyPrefix @@ -227,19 +376,20 @@ func (b *EtcdBackend) Watch(ctx context.Context, serviceName string, onChange fu onChange(instances) } - // Start watch goroutine. It runs until Close, so it must not inherit the - // caller's cancellation. + // Start watch goroutine. It runs until Close on the backend's own + // context, so it does not inherit the caller's cancellation. b.wg.Add(1) - go b.watchService(context.WithoutCancel(ctx), serviceName) + go b.watchService(serviceName) return nil } // watchService watches a service for changes using etcd watch. -func (b *EtcdBackend) watchService(ctx context.Context, serviceName string) { +func (b *EtcdBackend) watchService(serviceName string) { defer b.wg.Done() + ctx := b.ctx prefix := b.buildServicePrefix(serviceName) watchChan := b.client.Watch(ctx, prefix, clientv3.WithPrefix()) @@ -247,7 +397,25 @@ func (b *EtcdBackend) watchService(ctx context.Context, serviceName string) { select { case <-b.stopCh: return - case watchResp := <-watchChan: + case watchResp, ok := <-watchChan: + if !ok { + // The watch ended (compaction, lost connection or Close). + // Start a new one unless the backend is shutting down. + if ctx.Err() != nil { + return + } + + select { + case <-b.stopCh: + return + case <-time.After(time.Second): + } + + watchChan = b.client.Watch(ctx, prefix, clientv3.WithPrefix()) + + continue + } + if watchResp.Err() != nil { continue } @@ -312,17 +480,18 @@ func (b *EtcdBackend) Health(ctx context.Context) error { // Close closes the backend. func (b *EtcdBackend) Close() error { close(b.stopCh) + b.cancel() b.wg.Wait() // Revoke lease. A failed revoke still closes the client; the lease then // just expires on its TTL. var revokeErr error - if b.leaseID != 0 { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + if lease := b.currentLease(); lease != 0 { + ctx, cancel := context.WithTimeout(context.Background(), etcdOpTimeout) defer cancel() - if _, err := b.client.Revoke(ctx, b.leaseID); err != nil { + if _, err := b.client.Revoke(ctx, lease); err != nil { revokeErr = fmt.Errorf("failed to revoke etcd lease: %w", err) } } @@ -330,42 +499,114 @@ func (b *EtcdBackend) Close() error { return errors.Join(revokeErr, b.client.Close()) } -// keepAliveLease keeps the lease alive. -func (b *EtcdBackend) keepAliveLease(ctx context.Context) { +// keepAliveLease keeps the lease alive, and when it is lost, grants a new +// lease and writes every registered instance again under it. +func (b *EtcdBackend) keepAliveLease() { defer b.wg.Done() - keepAliveChan, err := b.client.KeepAlive(ctx, b.leaseID) + ctx := b.ctx + + keepAliveChan, err := b.client.KeepAlive(ctx, b.currentLease()) if err != nil { - return + keepAliveChan = nil } + backoff := time.Second + for { - select { - case <-b.stopCh: - return - case _, ok := <-keepAliveChan: - if !ok { - // Lease expired, recreate - lease, err := b.client.Grant(ctx, b.leaseTTL) - if err != nil { + if keepAliveChan != nil { + select { + case <-b.stopCh: + return + case _, ok := <-keepAliveChan: + if ok { continue } + } + } - b.leaseID = lease.ID + // The keep-alive stream ended, so the lease is gone or about to be. + if ctx.Err() != nil { + return + } - // Restart keep-alive - keepAliveChan, err = b.client.KeepAlive(ctx, b.leaseID) - if err != nil { - continue - } + keepAliveChan, err = b.renewLease() + if err != nil { + keepAliveChan = nil + + select { + case <-b.stopCh: + return + case <-time.After(backoff): } + + backoff = min(backoff*2, 30*time.Second) + + continue } + + backoff = time.Second } } +// renewLease grants a new lease, re-registers every known instance under it, +// and starts a keep-alive stream for it. +func (b *EtcdBackend) renewLease() (<-chan *clientv3.LeaseKeepAliveResponse, error) { + grantCtx, cancel := context.WithTimeout(b.ctx, etcdOpTimeout) + lease, err := b.client.Grant(grantCtx, b.leaseTTL) + + cancel() + + if err != nil { + return nil, fmt.Errorf("grant etcd lease: %w", err) + } + + if err := b.reregisterAll(b.ctx, lease.ID); err != nil { + return nil, err + } + + return b.client.KeepAlive(b.ctx, lease.ID) +} + +// reregisterAll switches to lease and writes every registered instance under +// it. Registrations made concurrently wait on leaseMu, so none is written +// under the old lease after the switch. +func (b *EtcdBackend) reregisterAll(ctx context.Context, lease clientv3.LeaseID) error { + b.leaseMu.Lock() + defer b.leaseMu.Unlock() + + b.leaseID = lease + + var errs []error + + for id, reg := range b.registered { + putCtx, cancel := context.WithTimeout(ctx, etcdOpTimeout) + err := b.ops.put(putCtx, reg.key, reg.value, lease) + + cancel() + + if err != nil { + errs = append(errs, fmt.Errorf("re-register %s: %w", id, err)) + } + } + + return errors.Join(errs...) +} + // notifyWatchers notifies all watchers for a service. func (b *EtcdBackend) notifyWatchers(serviceName string) { - instances, err := b.Discover(context.Background(), serviceName) + b.mu.RLock() + hasWatchers := len(b.watchers[serviceName]) > 0 + b.mu.RUnlock() + + if !hasWatchers { + return + } + + ctx, cancel := context.WithTimeout(b.ctx, etcdOpTimeout) + defer cancel() + + instances, err := b.Discover(ctx, serviceName) if err != nil { return } diff --git a/extensions/discovery/backends/etcd_lease_tls_test.go b/extensions/discovery/backends/etcd_lease_tls_test.go new file mode 100644 index 000000000..a78ba709f --- /dev/null +++ b/extensions/discovery/backends/etcd_lease_tls_test.go @@ -0,0 +1,290 @@ +package backends + +import ( + "context" + "encoding/pem" + "errors" + "fmt" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "sync" + "testing" + "time" + + clientv3 "go.etcd.io/etcd/client/v3" +) + +// TLSEnabled must produce a TLS handshake, not plaintext h2c carrying the +// username and password. +func TestEtcdTLSEnabledSpeaksTLS(t *testing.T) { + l, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer l.Close() + + got := make(chan []byte, 1) + + go func() { + c, err := l.Accept() + if err != nil { + return + } + defer c.Close() + + buf := make([]byte, 64) + _ = c.SetReadDeadline(time.Now().Add(3 * time.Second)) + + n, _ := c.Read(buf) + got <- buf[:n] + }() + + // With credentials set the client authenticates while it is created, so + // the handshake happens inside NewEtcdBackend. The fake server never + // completes it, so the constructor's error is expected and ignored. + done := make(chan struct{}) + + go func() { + defer close(done) + + b, err := NewEtcdBackend(EtcdConfig{ + Endpoints: []string{l.Addr().String()}, Username: "svc", Password: "s3cret", + TLSEnabled: true, DialTimeout: 2 * time.Second, + }) + if err == nil { + _ = b.client.Close() + } + }() + + defer func() { <-done }() + + select { + case first := <-got: + // A TLS record starts with content type 0x16 (handshake) and version major 0x03. + if len(first) < 2 || first[0] != 0x16 || first[1] != 0x03 { + t.Fatalf("first bytes %q are not a TLS ClientHello", first) + } + case <-time.After(5 * time.Second): + t.Fatal("client never connected") + } +} + +func writeTestCA(t *testing.T) string { + t.Helper() + + srv := httptest.NewTLSServer(http.NotFoundHandler()) + defer srv.Close() + + file := filepath.Join(t.TempDir(), "ca.pem") + if err := os.WriteFile(file, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: srv.Certificate().Raw}), 0o600); err != nil { + t.Fatal(err) + } + + return file +} + +func TestBuildEtcdTLSConfig(t *testing.T) { + ca := writeTestCA(t) + notPEM := filepath.Join(t.TempDir(), "bad.pem") + + if err := os.WriteFile(notPEM, []byte("nope"), 0o600); err != nil { + t.Fatal(err) + } + + if cfg, err := buildEtcdTLSConfig(EtcdConfig{}); err != nil || cfg != nil { + t.Fatalf("disabled: cfg=%v err=%v, want nil, nil", cfg, err) + } + + cfg, err := buildEtcdTLSConfig(EtcdConfig{TLSEnabled: true, TLSCAFile: ca}) + if err != nil { + t.Fatal(err) + } + + if cfg.RootCAs == nil { + t.Fatal("RootCAs not set from tls_ca_file") + } + + bad := map[string]EtcdConfig{ + "files without tls_enabled": {TLSCAFile: ca}, + "missing ca file": {TLSEnabled: true, TLSCAFile: filepath.Join(t.TempDir(), "missing")}, + "ca without pem": {TLSEnabled: true, TLSCAFile: notPEM}, + "cert without key": {TLSEnabled: true, TLSCert: notPEM}, + "key without cert": {TLSEnabled: true, TLSKey: notPEM}, + "invalid key pair": {TLSEnabled: true, TLSCert: notPEM, TLSKey: notPEM}, + } + + for name, c := range bad { + t.Run(name, func(t *testing.T) { + if _, err := buildEtcdTLSConfig(c); err == nil { + t.Fatal("expected error") + } + + c.Endpoints = []string{"127.0.0.1:1"} + if _, err := NewEtcdBackend(c); err == nil { + t.Fatal("NewEtcdBackend accepted invalid TLS config") + } + }) + } +} + +type recordedPut struct { + key string + lease clientv3.LeaseID +} + +type fakeEtcdOps struct { + mu sync.Mutex + puts []recordedPut + deletes []string + failPut bool +} + +func (f *fakeEtcdOps) put(_ context.Context, key, _ string, lease clientv3.LeaseID) error { + f.mu.Lock() + defer f.mu.Unlock() + + if f.failPut { + return errors.New("put failed") + } + + f.puts = append(f.puts, recordedPut{key: key, lease: lease}) + + return nil +} + +func (f *fakeEtcdOps) delete(_ context.Context, key string) error { + f.mu.Lock() + defer f.mu.Unlock() + + f.deletes = append(f.deletes, key) + + return nil +} + +func (f *fakeEtcdOps) reset() { + f.mu.Lock() + defer f.mu.Unlock() + + f.puts, f.deletes = nil, nil +} + +func newFakeEtcdBackend(t *testing.T) (*EtcdBackend, *fakeEtcdOps) { + t.Helper() + + ops := &fakeEtcdOps{} + b := newEtcdBackend(EtcdConfig{KeyPrefix: "/services"}, ops) + t.Cleanup(b.cancel) + + return b, ops +} + +func TestEtcdRegisterRequiresLease(t *testing.T) { + b, ops := newFakeEtcdBackend(t) + + err := b.Register(t.Context(), &ServiceInstance{ID: "a", Name: "svc"}) + if !errors.Is(err, ErrEtcdNotInitialized) { + t.Fatalf("err = %v, want ErrEtcdNotInitialized", err) + } + + if len(ops.puts) != 0 { + t.Fatal("instance written without a lease") + } +} + +// After the lease is replaced, every registered instance is written again +// under the new lease, and deregistered instances are not resurrected. +func TestEtcdLeaseRenewalReregistersInstances(t *testing.T) { + b, ops := newFakeEtcdBackend(t) + b.setLease(1) + + for _, id := range []string{"a", "b", "c"} { + if err := b.Register(t.Context(), &ServiceInstance{ID: id, Name: "svc"}); err != nil { + t.Fatal(err) + } + } + + if err := b.Deregister(t.Context(), "b"); err != nil { + t.Fatal(err) + } + + if len(ops.deletes) != 1 || ops.deletes[0] != "/services/svc/b" { + t.Fatalf("deletes = %v", ops.deletes) + } + + ops.reset() + + if err := b.reregisterAll(t.Context(), 2); err != nil { + t.Fatal(err) + } + + if b.currentLease() != 2 { + t.Fatalf("lease = %d, want 2", b.currentLease()) + } + + got := map[string]clientv3.LeaseID{} + for _, p := range ops.puts { + got[p.key] = p.lease + } + + want := map[string]clientv3.LeaseID{"/services/svc/a": 2, "/services/svc/c": 2} + if fmt.Sprint(got) != fmt.Sprint(want) { + t.Fatalf("re-put = %v, want %v", got, want) + } + + // New registrations use the new lease. + ops.reset() + + if err := b.Register(t.Context(), &ServiceInstance{ID: "d", Name: "svc"}); err != nil { + t.Fatal(err) + } + + if ops.puts[0].lease != 2 { + t.Fatalf("new registration lease = %d, want 2", ops.puts[0].lease) + } +} + +func TestEtcdReregisterReportsFailures(t *testing.T) { + b, ops := newFakeEtcdBackend(t) + b.setLease(1) + + if err := b.Register(t.Context(), &ServiceInstance{ID: "a", Name: "svc"}); err != nil { + t.Fatal(err) + } + + ops.failPut = true + + if err := b.reregisterAll(t.Context(), 2); err == nil { + t.Fatal("failed re-put not reported") + } +} + +// Register and lease replacement touch the lease ID from different +// goroutines; run under -race to catch unsynchronised access. +func TestEtcdLeaseAccessIsRaceFree(t *testing.T) { + b, _ := newFakeEtcdBackend(t) + b.setLease(1) + + var wg sync.WaitGroup + + for i := range 8 { + wg.Add(2) + + go func() { + defer wg.Done() + + _ = b.Register(context.Background(), &ServiceInstance{ID: fmt.Sprintf("i-%d", i), Name: "svc"}) + }() + + go func() { + defer wg.Done() + + _ = b.reregisterAll(context.Background(), clientv3.LeaseID(i+2)) + _ = b.currentLease() + }() + } + + wg.Wait() +} From fbf714e0a5e4fbb1df56f2684a93cac3634caf51 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:36:33 -0600 Subject: [PATCH 09/17] feat(consensus): version the raft wire protocol The wire envelope now carries a protocol version, "v", starting at 1. Receivers reject any other version, including a missing one, with ErrProtocolVersion and an error that names both the sender's and the receiver's version. The HTTP transport answers 400 with that error, so the sender's Send returns it. TCP connections only carry data one way, so the TCP receiver logs the error and closes the connection. The network format changed in this release. The transports from earlier releases never carried Raft traffic (TCP never flushed and could not encode the payloads, HTTP decoded them into maps, gRPC dropped them), so there is no working older cluster to stay compatible with. From here on, a change to the envelope bumps the version instead of failing in confusing ways. --- extensions/consensus/transport/envelope.go | 15 +++++ extensions/consensus/transport/http.go | 11 ++++ extensions/consensus/transport/tcp.go | 11 ++++ .../consensus/transport/transport_test.go | 65 +++++++++++++++++-- 4 files changed, 97 insertions(+), 5 deletions(-) diff --git a/extensions/consensus/transport/envelope.go b/extensions/consensus/transport/envelope.go index c48a23869..1c014763d 100644 --- a/extensions/consensus/transport/envelope.go +++ b/extensions/consensus/transport/envelope.go @@ -19,9 +19,17 @@ const DefaultMaxMessageSize = 4 << 20 // only listens on loopback unless it is told otherwise. const DefaultBindAddress = "127.0.0.1" +// WireProtocolVersion is the version of the wire envelope this build sends +// and accepts. Bump it whenever the envelope changes incompatibly. +const WireProtocolVersion = 1 + // ErrMessageTooLarge is returned when a message exceeds the size limit. var ErrMessageTooLarge = errors.New("message exceeds the maximum message size") +// ErrProtocolVersion is returned for a message in another wire protocol +// version. +var ErrProtocolVersion = errors.New("unsupported wire protocol version") + // wireMessage is the network form of internal.Message. // // internal.Message carries its payload as an interface, which neither JSON nor @@ -30,6 +38,7 @@ var ErrMessageTooLarge = errors.New("message exceeds the maximum message size") // instead has one typed, optional field per RPC, and exactly the one matching // Type is set. type wireMessage struct { + Version int `json:"v"` Type internal.MessageType `json:"type"` From string `json:"from"` To string `json:"to"` @@ -79,6 +88,7 @@ func encodeMessage(message any) ([]byte, internal.Message, error) { } w := wireMessage{ + Version: WireProtocolVersion, Type: msg.Type, From: msg.From, To: msg.To, @@ -129,6 +139,11 @@ func decodeMessage(data []byte) (internal.Message, error) { return internal.Message{}, fmt.Errorf("failed to unmarshal message: %w", err) } + if w.Version != WireProtocolVersion { + return internal.Message{}, fmt.Errorf("%w: peer %q sent version %d, this node speaks version %d", + ErrProtocolVersion, w.From, w.Version, WireProtocolVersion) + } + msg := internal.Message{ Type: w.Type, From: w.From, diff --git a/extensions/consensus/transport/http.go b/extensions/consensus/transport/http.go index d81df4974..355a83b68 100644 --- a/extensions/consensus/transport/http.go +++ b/extensions/consensus/transport/http.go @@ -395,6 +395,17 @@ func (ht *HTTPTransport) handleMessage(w http.ResponseWriter, r *http.Request) { msg, err := decodeMessage(body) if err != nil { + if errors.Is(err, ErrProtocolVersion) { + // Tell the sender which versions disagree; its Send returns this. + ht.logger.Error("rejecting message from a peer on another wire protocol version", + forge.F("remote", r.RemoteAddr), + forge.F("error", err), + ) + http.Error(w, err.Error(), http.StatusBadRequest) + + return + } + http.Error(w, "invalid message", http.StatusBadRequest) return diff --git a/extensions/consensus/transport/tcp.go b/extensions/consensus/transport/tcp.go index 224b79547..041e5c518 100644 --- a/extensions/consensus/transport/tcp.go +++ b/extensions/consensus/transport/tcp.go @@ -512,6 +512,17 @@ func (tt *TCPTransport) handleConnection(conn net.Conn) { } msg, err := decodeMessage(data) + if errors.Is(err, ErrProtocolVersion) { + // TCP connections are one-way, so the mismatch can only be logged + // here; the sender sees its connection closed. + tt.logger.Error("closing inbound connection from a peer on another wire protocol version", + forge.F("remote", conn.RemoteAddr()), + forge.F("error", err), + ) + + return + } + if err != nil { tt.logger.Warn("closing inbound connection after malformed message", forge.F("remote", conn.RemoteAddr()), diff --git a/extensions/consensus/transport/transport_test.go b/extensions/consensus/transport/transport_test.go index 3ae0fdd3a..e4f0dc9c7 100644 --- a/extensions/consensus/transport/transport_test.go +++ b/extensions/consensus/transport/transport_test.go @@ -170,10 +170,10 @@ func TestEnvelopeRejectsInconsistentMessages(t *testing.T) { } for _, raw := range []string{ - `{"type":"append_entries","from":"a"}`, - `{"type":"append_entries","from":"a","append_entries":{},"request_vote":{}}`, - `{"type":"append_entries","from":"a","payload":{"term":9}}`, - `{"type":"bogus","from":"a"}`, + `{"v":1,"type":"append_entries","from":"a"}`, + `{"v":1,"type":"append_entries","from":"a","append_entries":{},"request_vote":{}}`, + `{"v":1,"type":"append_entries","from":"a","payload":{"term":9}}`, + `{"v":1,"type":"bogus","from":"a"}`, } { if _, err := decodeMessage([]byte(raw)); err == nil { t.Fatalf("decoded invalid message %s", raw) @@ -511,7 +511,7 @@ func TestMTLSPeerIdentity(t *testing.T) { }}} if kind == "http" { - body := `{"type":"request_vote","from":"a","request_vote":{"term":9}}` + body := `{"v":1,"type":"request_vote","from":"a","request_vote":{"term":9}}` if resp, err := postTest(t, plain, "https://"+b.GetAddress()+"/raft/message", strings.NewReader(body)); err == nil { resp.Body.Close() t.Fatalf("request without a client certificate got status %d", resp.StatusCode) @@ -560,3 +560,58 @@ func postTest(t *testing.T, client *http.Client, url string, body io.Reader) (*h return client.Do(req) } + +// A message in another wire protocol version is rejected with an error that +// names both versions. Over HTTP the sender gets it back; over TCP the +// receiver logs it and drops the connection. +func TestWireProtocolVersionMismatchIsRejected(t *testing.T) { + future := []byte(`{"v":2,"type":"request_vote","from":"a","request_vote":{"term":9}}`) + + _, err := decodeMessage(future) + if !errors.Is(err, ErrProtocolVersion) || !strings.Contains(err.Error(), "version 2") || !strings.Contains(err.Error(), "version 1") { + t.Fatalf("decode error %v does not name both versions", err) + } + + missing := []byte(`{"type":"request_vote","from":"a","request_vote":{"term":9}}`) + if _, err := decodeMessage(missing); !errors.Is(err, ErrProtocolVersion) { + t.Fatalf("message without a version decoded: %v", err) + } + + h := startHTTP(t, HTTPTransportConfig{NodeID: "b"}) + + resp, err := postTest(t, http.DefaultClient, "http://"+h.GetAddress()+"/raft/message", bytes.NewReader(future)) + if err != nil { + t.Fatal(err) + } + + body, _ := io.ReadAll(resp.Body) + resp.Body.Close() + + if resp.StatusCode != http.StatusBadRequest || !strings.Contains(string(body), "version 2") { + t.Fatalf("HTTP status %d body %q, want 400 naming the versions", resp.StatusCode, body) + } + + expectNothing(t, h) + + tcp := startTCP(t, TCPTransportConfig{NodeID: "b"}) + + conn, err := dialTest(t, tcp.GetAddress()) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + + var header [4]byte + binary.BigEndian.PutUint32(header[:], uint32(len(future))) + + if _, err := conn.Write(append(header[:], future...)); err != nil { + t.Fatal(err) + } + + _ = conn.SetReadDeadline(time.Now().Add(3 * time.Second)) + if _, err := conn.Read(make([]byte, 1)); isTimeout(err) { + t.Fatal("TCP connection stayed open after a version mismatch") + } + + expectNothing(t, tcp) +} From f611fd7a4378e3611df26ab26e8c31b10947ebcf Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:40:47 -0600 Subject: [PATCH 10/17] feat(consensus): send and install raft snapshots A follower whose next entry had been compacted into the leader's snapshot could never catch up. The leader logged an error and stopped, and the follower's InstallSnapshot handler dropped whatever it was sent. Leader: - When a peer's nextIndex falls at or before the snapshot index, the leader reads the stored snapshot and sends it with InstallSnapshot. - The snapshot goes in chunks of at most Config.SnapshotChunkSize bytes (default 1 MiB), so each message fits the transport's MaxMessageSize. - Once the peer installs the final chunk, the leader moves the peer's matchIndex and nextIndex past the snapshot. Follower (section 7 of the Raft paper): - Checks the term and assembles chunks in order. A chunk that does not continue the current snapshot is refused, and the leader starts again. - On the last chunk it restores the state machine, persists the snapshot data and metadata, and moves lastApplied and commitIndex up to the snapshot. - It keeps the log suffix that agrees with the snapshot and otherwise discards the whole log, from storage as well as memory. - InstallSnapshotResponse gains a Success field so the leader knows the outcome. Applying entries, taking a snapshot and restoring one now share a mutex, so a snapshot always reflects exactly the index it records. Snapshots are taken at lastApplied rather than an index chosen before the state machine was read. Node.Snapshot exposes this for callers. The wire envelope already carries both InstallSnapshot types. A new test stops a follower, writes to the cluster, compacts the running nodes and restarts the follower. The follower catches up through a snapshot sent in 40 byte chunks, ends with the same state machine as the others, and keeps the snapshot across another restart. --- extensions/consensus/internal/types.go | 3 + extensions/consensus/raft/config.go | 4 + extensions/consensus/raft/log.go | 54 +++ extensions/consensus/raft/node.go | 170 +++++++++- extensions/consensus/raft/replication.go | 225 ++++++++++--- .../consensus/raft/snapshot_install_test.go | 311 ++++++++++++++++++ extensions/consensus/raft/workers.go | 47 ++- 7 files changed, 725 insertions(+), 89 deletions(-) create mode 100644 extensions/consensus/raft/snapshot_install_test.go diff --git a/extensions/consensus/internal/types.go b/extensions/consensus/internal/types.go index 279c5d0f1..44ba6b628 100644 --- a/extensions/consensus/internal/types.go +++ b/extensions/consensus/internal/types.go @@ -324,6 +324,9 @@ type InstallSnapshotRequest struct { type InstallSnapshotResponse struct { Term uint64 `json:"term"` NodeID string `json:"node_id"` + // Success reports that the chunk was accepted and, for the final chunk, + // that the snapshot was installed. + Success bool `json:"success"` } // StateMachine defines the interface for the replicated state machine. diff --git a/extensions/consensus/raft/config.go b/extensions/consensus/raft/config.go index 3e72c7f32..d254ac276 100644 --- a/extensions/consensus/raft/config.go +++ b/extensions/consensus/raft/config.go @@ -26,6 +26,10 @@ type Config struct { SnapshotInterval time.Duration `json:"snapshot_interval" yaml:"snapshot_interval"` SnapshotThreshold uint64 `json:"snapshot_threshold" yaml:"snapshot_threshold"` EnableSnapshots bool `json:"enable_snapshots" yaml:"enable_snapshots"` + // SnapshotChunkSize is the most snapshot data sent in one InstallSnapshot + // message. Messages are JSON, which base64-encodes the data, so keep it + // under three quarters of the transport's MaxMessageSize. Defaults to 1 MiB. + SnapshotChunkSize int `json:"snapshot_chunk_size" yaml:"snapshot_chunk_size"` // Replication configuration MaxAppendEntries int `json:"max_append_entries" yaml:"max_append_entries"` diff --git a/extensions/consensus/raft/log.go b/extensions/consensus/raft/log.go index 3bab26b9b..6d029fd35 100644 --- a/extensions/consensus/raft/log.go +++ b/extensions/consensus/raft/log.go @@ -302,6 +302,60 @@ func (l *Log) Compact(index uint64, term uint64) error { return nil } +// InstallSnapshot moves the start of the log past a snapshot received from +// the leader that covers everything up to index. Entries after index are +// kept when the log holds index with the same term; otherwise the whole log is +// discarded, as section 7 of the Raft paper requires. Removed entries are +// deleted from storage first, so memory never claims less than storage. +func (l *Log) InstallSnapshot(index, term uint64) error { + l.mu.Lock() + defer l.mu.Unlock() + + if index <= l.snapshotIndex { + return nil + } + + last := l.lastIndexLocked() + deleteTo := last + + var keep []internal.LogEntry + + if t, ok := l.termLocked(index); ok && t == term { + pos, _ := l.posLocked(index) + keep = make([]internal.LogEntry, len(l.entries)-pos-1) + copy(keep, l.entries[pos+1:]) + + deleteTo = index + } + + if deleteTo > l.snapshotIndex { + ops := make([]internal.BatchOp, 0, deleteTo-l.snapshotIndex) + for i := deleteTo; i > l.snapshotIndex; i-- { + ops = append(ops, internal.BatchOp{Type: internal.BatchOpDelete, Key: logKey(i)}) + } + + if err := l.storage.Batch(ops); err != nil { + return fmt.Errorf("failed to delete log entries covered by snapshot: %w", err) + } + } + + if keep == nil { + keep = make([]internal.LogEntry, 0) + } + + l.entries = keep + l.snapshotIndex = index + l.snapshotTerm = term + + l.logger.Info("log moved past installed snapshot", + forge.F("snapshot_index", index), + forge.F("snapshot_term", term), + forge.F("entries_kept", len(keep)), + ) + + return nil +} + // load reads the snapshot metadata and every contiguous entry after it. func (l *Log) load() error { snapshotMeta, err := l.storage.Get([]byte(snapshotMetaKey)) diff --git a/extensions/consensus/raft/node.go b/extensions/consensus/raft/node.go index f496a8c53..9cda91b63 100644 --- a/extensions/consensus/raft/node.go +++ b/extensions/consensus/raft/node.go @@ -84,6 +84,14 @@ type Node struct { applyNotify chan struct{} applyWaiters map[uint64]applyWaiter + // applyMu serialises everything that changes the state machine: applying + // entries, taking a snapshot of it and restoring one. Lock order is + // applyMu before mu. + applyMu sync.Mutex + + // snapshotRecv assembles an incoming chunked snapshot. Guarded by mu. + snapshotRecv *snapshotReceive + // RPC correlation. Every outgoing request gets a fresh ID from requestSeq, // which the peer echoes in its response, so a late response can never be // matched to a newer request to the same peer. @@ -114,6 +122,14 @@ type pendingKey struct { id uint64 } +// snapshotReceive is a snapshot being received from the leader in chunks. +type snapshotReceive struct { + leaderTerm uint64 + index uint64 + term uint64 + data []byte +} + // applyWaiter is an Apply call waiting for its entry to be applied. type applyWaiter struct { term uint64 @@ -186,6 +202,10 @@ func NewNode( config.LogCacheSize = 1024 } + if config.SnapshotChunkSize <= 0 { + config.SnapshotChunkSize = 1 << 20 + } + if config.TrailingLogs == 0 { config.TrailingLogs = 10000 } @@ -492,49 +512,167 @@ func (n *Node) handleRequestVote(req internal.RequestVoteRequest) internal.Reque return *resp } -// handleInstallSnapshot handles an InstallSnapshot request. -// -// Installing snapshots sent by a leader is not implemented. The request still -// updates the term and leader like any RPC from a current leader, but the -// snapshot itself is dropped and logged as an error rather than acknowledged -// as if it had been installed. +// handleInstallSnapshot handles one chunk of an InstallSnapshot request +// (section 7 of the Raft paper). Chunks must arrive in order; a chunk that does +// not continue the snapshot being assembled is refused and the leader starts +// again from offset 0. When the last chunk arrives the snapshot is persisted, +// restored into the state machine, and the log prefix it covers is dropped. func (n *Node) handleInstallSnapshot(req internal.InstallSnapshotRequest) internal.InstallSnapshotResponse { n.mu.Lock() - defer n.mu.Unlock() resp := internal.InstallSnapshotResponse{ Term: n.currentTerm, NodeID: n.id, } - // Reply immediately if term < currentTerm if req.Term < n.currentTerm { + n.mu.Unlock() + return resp } - // Update term if needed if req.Term > n.currentTerm { n.currentTerm = req.Term n.votedFor = "" - n.persistStateOrLog("install snapshot from newer term") + resp.Term = n.currentTerm + + if err := n.persistState(); err != nil { + n.mu.Unlock() + n.logger.Error("failed to persist term from InstallSnapshot, rejecting it", + forge.F("node_id", n.id), + forge.F("error", err), + ) + + return resp + } } n.setRole(internal.RoleFollower) n.resetElectionTimerUnsafe() n.setLeader(req.LeaderID) - n.logger.Error("received InstallSnapshot, which is not implemented; the snapshot was dropped", - forge.F("node_id", n.id), - forge.F("leader", req.LeaderID), - forge.F("last_included_index", req.LastIncludedIndex), - forge.F("last_included_term", req.LastIncludedTerm), - ) + if req.Offset == 0 { + n.snapshotRecv = &snapshotReceive{ + leaderTerm: req.Term, + index: req.LastIncludedIndex, + term: req.LastIncludedTerm, + } + } + + recv := n.snapshotRecv + if recv == nil || recv.leaderTerm != req.Term || recv.index != req.LastIncludedIndex || + recv.term != req.LastIncludedTerm || uint64(len(recv.data)) != req.Offset { + n.snapshotRecv = nil + n.mu.Unlock() + + n.logger.Warn("rejecting out of order snapshot chunk", + forge.F("node_id", n.id), + forge.F("leader", req.LeaderID), + forge.F("index", req.LastIncludedIndex), + forge.F("offset", req.Offset), + ) + + return resp + } + + recv.data = append(recv.data, req.Data...) + + if !req.Done { + n.mu.Unlock() + + resp.Success = true + + return resp + } + + n.snapshotRecv = nil + n.mu.Unlock() + err := n.installSnapshot(recv.index, recv.term, recv.data) + if err != nil { + n.logger.Error("failed to install snapshot from leader", + forge.F("node_id", n.id), + forge.F("leader", req.LeaderID), + forge.F("index", recv.index), + forge.F("error", err), + ) + } else { + n.logger.Info("installed snapshot from leader", + forge.F("node_id", n.id), + forge.F("leader", req.LeaderID), + forge.F("index", recv.index), + forge.F("term", recv.term), + forge.F("size", len(recv.data)), + ) + } + + n.mu.RLock() resp.Term = n.currentTerm + n.mu.RUnlock() + + resp.Success = err == nil return resp } +// installSnapshot replaces the state machine with a snapshot covering the +// log up to index, persists it, and drops the log entries it covers. Entries +// after index are kept when the log agrees with the snapshot at index; +// otherwise the whole log is discarded (section 7). +func (n *Node) installSnapshot(index, term uint64, data []byte) error { + n.applyMu.Lock() + defer n.applyMu.Unlock() + + n.mu.RLock() + applied := n.lastApplied + n.mu.RUnlock() + + // The state machine already reflects this snapshot or a later point. + if index <= applied { + return nil + } + + snapshot := &internal.Snapshot{Index: index, Term: term, Data: data, Size: int64(len(data))} + + if err := n.stateMachine.Restore(snapshot); err != nil { + return fmt.Errorf("state machine rejected snapshot %d: %w", index, err) + } + + n.mu.Lock() + defer n.mu.Unlock() + + // The state machine now reflects index whatever happens below, so the + // applier must not apply the covered entries again. + n.lastApplied = index + n.commitIndex = max(n.commitIndex, index) + + for waitIndex, waiter := range n.applyWaiters { + if waitIndex <= index { + waiter.ch <- errors.New("entry was superseded by a snapshot from the leader; its result is unknown") + + delete(n.applyWaiters, waitIndex) + } + } + + if err := n.saveSnapshot(snapshot); err != nil { + return fmt.Errorf("failed to persist snapshot %d: %w", index, err) + } + + if err := n.log.InstallSnapshot(index, term); err != nil { + return fmt.Errorf("failed to drop log entries covered by snapshot %d: %w", index, err) + } + + n.signalApply() + + return nil +} + +// Snapshot snapshots the state machine at the last applied entry and +// compacts the log up to it. +func (n *Node) Snapshot() error { + return n.createSnapshot() +} + // Apply appends an entry on the leader and waits until it is committed and // applied to the local state machine. It returns the state machine's error for // that entry, or an error when leadership is lost and the entry is replaced. diff --git a/extensions/consensus/raft/replication.go b/extensions/consensus/raft/replication.go index 347b4b940..0e03b848e 100644 --- a/extensions/consensus/raft/replication.go +++ b/extensions/consensus/raft/replication.go @@ -2,6 +2,7 @@ package raft import ( "context" + "fmt" "time" "github.com/xraph/forge" @@ -24,11 +25,19 @@ func (n *Node) replicateToPeer(peer *PeerState) { defer peer.ReplicationMu.Unlock() for range maxReplicationRounds { - req, ok := n.buildAppendEntries(peer) + req, needSnapshot, ok := n.buildAppendEntries(peer) if !ok { return } + if needSnapshot { + if !n.sendSnapshot(peer) { + return + } + + continue + } + resp, err := n.sendAppendEntries(peer, req) if err != nil { n.logger.Debug("failed to send AppendEntries", @@ -47,29 +56,33 @@ func (n *Node) replicateToPeer(peer *PeerState) { } // buildAppendEntries builds the next AppendEntries request for a peer from a -// consistent view of the leader state. It returns false when this node is not -// the leader or the peer needs entries that were compacted away. -func (n *Node) buildAppendEntries(peer *PeerState) (*internal.AppendEntriesRequest, bool) { +// consistent view of the leader state. needSnapshot is true when the peer +// needs entries that were compacted into the snapshot; ok is false when this +// node is not the leader or nothing can be sent. +func (n *Node) buildAppendEntries(peer *PeerState) (req *internal.AppendEntriesRequest, needSnapshot, ok bool) { n.mu.RLock() defer n.mu.RUnlock() if n.GetRole() != internal.RoleLeader { - return nil, false + return nil, false, false } nextIndex := max(n.nextIndex[peer.ID], 1) prevLogIndex := nextIndex - 1 - prevLogTerm, ok := n.log.Term(prevLogIndex) - if !ok { - n.logger.Error("peer needs log entries that are only in a snapshot; InstallSnapshot is not implemented, so it cannot catch up", + if prevLogIndex < n.log.SnapshotIndex() { + return nil, true, true + } + + prevLogTerm, found := n.log.Term(prevLogIndex) + if !found { + n.logger.Error("no log entry to anchor replication on", forge.F("node_id", n.id), forge.F("peer", peer.ID), forge.F("prev_index", prevLogIndex), - forge.F("snapshot_index", n.log.SnapshotIndex()), ) - return nil, false + return nil, false, false } entries, err := n.log.GetEntriesAfter(prevLogIndex, n.config.MaxAppendEntries) @@ -79,7 +92,7 @@ func (n *Node) buildAppendEntries(peer *PeerState) (*internal.AppendEntriesReque forge.F("error", err), ) - return nil, false + return nil, false, false } return &internal.AppendEntriesRequest{ @@ -89,7 +102,117 @@ func (n *Node) buildAppendEntries(peer *PeerState) (*internal.AppendEntriesReque PrevLogTerm: prevLogTerm, Entries: entries, LeaderCommit: n.commitIndex, - }, true + }, false, true +} + +// sendSnapshot sends the latest snapshot to a peer whose next entry was +// compacted away, in chunks of at most SnapshotChunkSize bytes, and advances +// the peer's replication state once the peer has installed it. It reports +// whether the peer accepted the snapshot. +func (n *Node) sendSnapshot(peer *PeerState) bool { + n.mu.RLock() + term := n.currentTerm + index := n.log.SnapshotIndex() + snapshotTerm := n.log.SnapshotTerm() + leader := n.GetRole() == internal.RoleLeader + n.mu.RUnlock() + + if !leader { + return false + } + + data, err := n.storage.Get(fmt.Appendf(nil, "snapshot_%d", index)) + if err != nil { + n.logger.Error("cannot read snapshot to send to peer", + forge.F("peer", peer.ID), + forge.F("index", index), + forge.F("error", err), + ) + + return false + } + + n.logger.Info("sending snapshot to peer", + forge.F("peer", peer.ID), + forge.F("index", index), + forge.F("size", len(data)), + ) + + chunkSize := n.config.SnapshotChunkSize + + for offset := 0; ; { + end := min(offset+chunkSize, len(data)) + req := &internal.InstallSnapshotRequest{ + Term: term, + LeaderID: n.id, + LastIncludedIndex: index, + LastIncludedTerm: snapshotTerm, + Offset: uint64(offset), + Data: data[offset:end], + Done: end == len(data), + } + + ctx, cancel := context.WithTimeout(n.ctx, 10*time.Second) + response, err := n.call(ctx, peer.ID, internal.MessageTypeInstallSnapshot, req) + + cancel() + + if err != nil { + n.logger.Debug("failed to send snapshot chunk", + forge.F("peer", peer.ID), + forge.F("offset", offset), + forge.F("error", err), + ) + + return false + } + + resp, ok := response.(*internal.InstallSnapshotResponse) + if !ok { + return false + } + + if resp.Term > term { + n.stepDown(resp.Term) + + return false + } + + if !resp.Success { + n.logger.Warn("peer rejected snapshot chunk", + forge.F("peer", peer.ID), + forge.F("index", index), + forge.F("offset", offset), + ) + + return false + } + + if req.Done { + break + } + + offset = end + } + + n.mu.Lock() + defer n.mu.Unlock() + + if n.GetRole() != internal.RoleLeader || n.currentTerm != term { + return false + } + + if index > n.matchIndex[peer.ID] { + n.matchIndex[peer.ID] = index + } + + if n.nextIndex[peer.ID] < index+1 { + n.nextIndex[peer.ID] = index + 1 + } + + n.advanceCommitIndex() + + return true } // sendAppendEntries sends an AppendEntries RPC to a peer and waits for the @@ -250,50 +373,60 @@ func (n *Node) signalApply() { // it and does not stop the applier: the entry is committed on every node, and // stalling here would wedge the node for good. func (n *Node) applyCommitted() { - for { - n.mu.RLock() + for n.applyNext() { + } +} - if n.lastApplied >= n.commitIndex { - n.mu.RUnlock() +// applyNext applies the next committed entry, if any, and reports whether it +// did. It holds applyMu so snapshots never interleave with an apply. +func (n *Node) applyNext() bool { + n.applyMu.Lock() + defer n.applyMu.Unlock() - return - } + n.mu.RLock() - applyIndex := n.lastApplied + 1 - entry, err := n.log.Get(applyIndex) + if n.lastApplied >= n.commitIndex { n.mu.RUnlock() - if err != nil { - n.logger.Error("failed to get committed log entry for apply", - forge.F("index", applyIndex), - forge.F("error", err), - ) + return false + } - return - } + applyIndex := n.lastApplied + 1 + entry, err := n.log.Get(applyIndex) + n.mu.RUnlock() - applyErr := n.stateMachine.Apply(entry) - if applyErr != nil { - n.logger.Error("state machine rejected committed entry", - forge.F("index", applyIndex), - forge.F("error", applyErr), - ) - } + if err != nil { + n.logger.Error("failed to get committed log entry for apply", + forge.F("index", applyIndex), + forge.F("error", err), + ) - n.mu.Lock() - n.lastApplied = applyIndex - waiter, waiting := n.applyWaiters[applyIndex] - delete(n.applyWaiters, applyIndex) - n.mu.Unlock() - - if waiting { - if waiter.term == entry.Term { - waiter.ch <- applyErr - } else { - waiter.ch <- errors.New("entry was replaced after a leadership change and was not applied") - } + return false + } + + applyErr := n.stateMachine.Apply(entry) + if applyErr != nil { + n.logger.Error("state machine rejected committed entry", + forge.F("index", applyIndex), + forge.F("error", applyErr), + ) + } + + n.mu.Lock() + n.lastApplied = applyIndex + waiter, waiting := n.applyWaiters[applyIndex] + delete(n.applyWaiters, applyIndex) + n.mu.Unlock() + + if waiting { + if waiter.term == entry.Term { + waiter.ch <- applyErr + } else { + waiter.ch <- errors.New("entry was replaced after a leadership change and was not applied") } } + + return true } // InstallSnapshot handles an InstallSnapshot RPC. diff --git a/extensions/consensus/raft/snapshot_install_test.go b/extensions/consensus/raft/snapshot_install_test.go new file mode 100644 index 000000000..2ea68fa4d --- /dev/null +++ b/extensions/consensus/raft/snapshot_install_test.go @@ -0,0 +1,311 @@ +package raft + +import ( + "context" + "fmt" + "net" + "reflect" + "strconv" + "testing" + "time" + + "github.com/xraph/forge" + "github.com/xraph/forge/extensions/consensus/internal" + "github.com/xraph/forge/extensions/consensus/statemachine" + "github.com/xraph/forge/extensions/consensus/storage" + "github.com/xraph/forge/extensions/consensus/transport" +) + +// restartableMember is a TCP cluster member that can be stopped and started +// again on the same port and storage, like a process restart. +type restartableMember struct { + id string + port int + store *storage.MemoryStorage + node *Node + tr *transport.TCPTransport + sm *statemachine.MemoryStateMachine +} + +type restartableCluster struct { + t *testing.T + members []*restartableMember +} + +func (c *restartableCluster) start(m *restartableMember) { + c.t.Helper() + + lg := forge.NewNoopLogger() + m.tr = transport.NewTCPTransport(transport.TCPTransportConfig{NodeID: m.id, Address: "127.0.0.1", Port: m.port}, lg) + + if err := m.tr.Start(context.Background()); err != nil { + c.t.Fatal(err) + } + + _, p, _ := net.SplitHostPort(m.tr.GetAddress()) + m.port, _ = strconv.Atoi(p) + + m.sm = statemachine.NewMemoryStateMachine(statemachine.MemoryStateMachineConfig{}, lg) + + node, err := NewNode(Config{ + NodeID: m.id, + HeartbeatInterval: 50 * time.Millisecond, + ElectionTimeoutMin: 300 * time.Millisecond, + ElectionTimeoutMax: 600 * time.Millisecond, + SnapshotChunkSize: 40, // force many chunks + }, lg, m.sm, m.tr, m.store) + if err != nil { + c.t.Fatal(err) + } + + m.node = node +} + +func (c *restartableCluster) connect(m *restartableMember) { + c.t.Helper() + + for _, other := range c.members { + if other == m { + continue + } + + if err := m.tr.AddPeer(other.id, "127.0.0.1", other.port); err != nil { + c.t.Fatal(err) + } + + m.node.AddPeer(other.id) + } + + if err := m.node.Start(context.Background()); err != nil { + c.t.Fatal(err) + } +} + +func (c *restartableCluster) stop(m *restartableMember) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + _ = m.node.Stop(ctx) + _ = m.tr.Stop(ctx) +} + +func (c *restartableCluster) leader() *restartableMember { + c.t.Helper() + + deadline := time.Now().Add(15 * time.Second) + + for time.Now().Before(deadline) { + var leaders []*restartableMember + + for _, m := range c.members { + if m.node != nil && m.node.IsLeader() { + leaders = append(leaders, m) + } + } + + if len(leaders) == 1 { + return leaders[0] + } + + time.Sleep(20 * time.Millisecond) + } + + c.t.Fatal("no single leader elected") + + return nil +} + +func propose(t *testing.T, n *Node, key, value string) { + t.Helper() + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + cmd := fmt.Sprintf(`{"type":"set","payload":{"key":%q,"value":%q}}`, key, value) + if err := n.Propose(ctx, []byte(cmd)); err != nil { + t.Fatalf("propose %s: %v", key, err) + } +} + +func waitApplied(t *testing.T, n *Node, index uint64) { + t.Helper() + + deadline := time.Now().Add(15 * time.Second) + + for { + n.mu.RLock() + applied := n.lastApplied + n.mu.RUnlock() + + if applied >= index { + return + } + + if time.Now().After(deadline) { + t.Fatalf("%s applied up to %d, want %d", n.id, applied, index) + } + + time.Sleep(20 * time.Millisecond) + } +} + +// A follower that was offline while the leader compacted its log catches up +// through InstallSnapshot, sent in many chunks, and ends with the same state +// machine as the rest of the cluster. +func TestOfflineFollowerCatchesUpViaSnapshot(t *testing.T) { + c := &restartableCluster{t: t} + + for i := range 3 { + c.members = append(c.members, &restartableMember{id: fmt.Sprintf("n%d", i+1), store: newMemStorage(t)}) + } + + for _, m := range c.members { + c.start(m) + } + + for _, m := range c.members { + c.connect(m) + } + + t.Cleanup(func() { + for _, m := range c.members { + c.stop(m) + } + }) + + leader := c.leader() + propose(t, leader.node, "before", "offline") + + var follower *restartableMember + + for _, m := range c.members { + if m != leader { + follower = m + + break + } + } + + waitApplied(t, follower.node, leader.node.GetCommitIndex()) + c.stop(follower) + + for i := range 20 { + propose(t, leader.node, fmt.Sprintf("k%d", i), fmt.Sprintf("v%d", i)) + } + + // Compact every running node, so whichever of them leads once the + // follower is back (its return can trigger an election) has to send a + // snapshot. + for _, m := range c.members { + if m == follower { + continue + } + + waitApplied(t, m.node, leader.node.GetCommitIndex()) + + if err := m.node.Snapshot(); err != nil { + t.Fatalf("%s snapshot: %v", m.id, err) + } + + if m.node.log.SnapshotIndex() == 0 { + t.Fatalf("%s did not compact its log", m.id) + } + } + + // Entries after the snapshot reach the follower through AppendEntries. + propose(t, leader.node, "after", "snapshot") + + c.start(follower) + c.connect(follower) + + leader = c.leader() + commit := leader.node.GetCommitIndex() + waitApplied(t, follower.node, commit) + + if follower.node.log.SnapshotIndex() == 0 { + t.Fatal("the follower caught up without installing a snapshot") + } + + for _, m := range c.members { + waitApplied(t, m.node, commit) + } + + want := leader.sm.GetState() + for _, m := range c.members { + if got := m.sm.GetState(); !reflect.DeepEqual(got, want) { + t.Fatalf("%s state %v differs from leader %v", m.id, got, want) + } + } + + if len(want) != 22 { + t.Fatalf("leader state has %d keys, want 22", len(want)) + } + + // The installed snapshot survives a restart of the follower. + c.stop(follower) + c.start(follower) + + if follower.node.log.SnapshotIndex() == 0 || len(follower.sm.GetState()) == 0 { + t.Fatal("follower lost its installed snapshot on restart") + } +} + +// Chunks that do not continue the snapshot being assembled are refused. +func TestSnapshotChunksMustArriveInOrder(t *testing.T) { + n := newTestNode(t, "f", newMemStorage(t)) + + resp := n.handleInstallSnapshot(internal.InstallSnapshotRequest{ + Term: 1, LeaderID: "l", LastIncludedIndex: 5, LastIncludedTerm: 1, Offset: 4, Data: []byte("{}"), + }) + if resp.Success { + t.Fatal("accepted a chunk at offset 4 with nothing before it") + } + + first := n.handleInstallSnapshot(internal.InstallSnapshotRequest{ + Term: 1, LeaderID: "l", LastIncludedIndex: 5, LastIncludedTerm: 1, Data: []byte(`{"a":`), + }) + gap := n.handleInstallSnapshot(internal.InstallSnapshotRequest{ + Term: 1, LeaderID: "l", LastIncludedIndex: 5, LastIncludedTerm: 1, Offset: 9, Data: []byte(`1}`), Done: true, + }) + + if !first.Success || gap.Success { + t.Fatalf("first=%v gap=%v, want the gap refused", first.Success, gap.Success) + } + + if n.log.SnapshotIndex() != 0 { + t.Fatal("a refused snapshot was installed") + } +} + +// Installing a snapshot keeps the log suffix that agrees with it and drops +// everything when it does not. +func TestLogInstallSnapshotKeepsMatchingSuffix(t *testing.T) { + st := newMemStorage(t) + + l, err := NewLog(forge.NewNoopLogger(), st, 0) + if err != nil { + t.Fatal(err) + } + + _ = l.AppendBatch(ents(2, 1, 10)) + + if err := l.InstallSnapshot(6, 2); err != nil { + t.Fatal(err) + } + + if l.SnapshotIndex() != 6 || l.LastIndex() != 10 || l.Count() != 4 { + t.Fatalf("after matching install: %s", l) + } + + if err := l.InstallSnapshot(8, 5); err != nil { + t.Fatal(err) + } + + if l.SnapshotIndex() != 8 || l.LastIndex() != 8 || l.Count() != 0 { + t.Fatalf("after conflicting install: %s", l) + } + + if _, err := st.Get(logKey(10)); err == nil { + t.Fatal("discarded entry 10 is still in storage") + } +} diff --git a/extensions/consensus/raft/workers.go b/extensions/consensus/raft/workers.go index f485cb5fc..02006406b 100644 --- a/extensions/consensus/raft/workers.go +++ b/extensions/consensus/raft/workers.go @@ -7,7 +7,6 @@ import ( "time" "github.com/xraph/forge" - "github.com/xraph/forge/errors" "github.com/xraph/forge/extensions/consensus/internal" ) @@ -195,7 +194,7 @@ func (n *Node) runSnapshotManager() { forge.F("last_applied", lastApplied), ) - if err := n.createSnapshot(lastApplied); err != nil { + if err := n.createSnapshot(); err != nil { n.logger.Error("failed to create snapshot", forge.F("error", err), ) @@ -204,7 +203,7 @@ func (n *Node) runSnapshotManager() { case msg := <-n.snapshotCh: // Manual snapshot request - if err := n.createSnapshot(msg.Index); err != nil { + if err := n.createSnapshot(); err != nil { n.logger.Error("failed to create snapshot", forge.F("error", err), ) @@ -217,34 +216,32 @@ func (n *Node) runSnapshotManager() { } } -// createSnapshot creates a snapshot up to the given index. -func (n *Node) createSnapshot(index uint64) error { - n.mu.RLock() +// createSnapshot snapshots the state machine at lastApplied and compacts the +// log up to it. It holds applyMu so the state machine cannot move while the +// snapshot is taken, which keeps the snapshot's index exact. +func (n *Node) createSnapshot() error { + n.applyMu.Lock() + defer n.applyMu.Unlock() - if index > n.lastApplied { - n.mu.RUnlock() + n.mu.RLock() + index := n.lastApplied + snapshotIndex := n.log.SnapshotIndex() + term, ok := n.log.Term(index) + n.mu.RUnlock() - return errors.New("cannot snapshot beyond last applied index") + if index <= snapshotIndex { + return nil // Nothing new to snapshot } - // Get the entry at the snapshot index to get its term - entry, err := n.log.Get(index) - if err != nil { - n.mu.RUnlock() - - return fmt.Errorf("failed to get log entry at index %d: %w", index, err) + if !ok { + return fmt.Errorf("log entry %d is not available to snapshot", index) } - term := entry.Term - - n.mu.RUnlock() - n.logger.Info("creating snapshot", forge.F("index", index), forge.F("term", term), ) - // Create snapshot from state machine snapshot, err := n.stateMachine.Snapshot() if err != nil { return fmt.Errorf("failed to create snapshot from state machine: %w", err) @@ -254,22 +251,18 @@ func (n *Node) createSnapshot(index uint64) error { snapshot.Term = term snapshot.Created = time.Now() - // Save snapshot to storage if err := n.saveSnapshot(snapshot); err != nil { return fmt.Errorf("failed to save snapshot: %w", err) } - // Compact the log n.mu.Lock() + err = n.log.Compact(index, term) + n.mu.Unlock() - if err := n.log.Compact(index, term); err != nil { - n.mu.Unlock() - + if err != nil { return fmt.Errorf("failed to compact log: %w", err) } - n.mu.Unlock() - n.snapshotCount.Add(1) n.logger.Info("snapshot created successfully", From e96d2634aeed8e4a7b20228982e9d25f6e7552e2 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:45:39 -0600 Subject: [PATCH 11/17] feat(consensus): run a raft node from the extension's configuration Service.Start only logged the components it would build, so the extension opened no listener and every node stayed a follower forever. It now builds and starts, from config: - storage: badger or boltdb under storage.path, or the new memory type - the tcp or http transport on bind_addr:bind_port, with transport.max_message_size, max_connections and the timeouts - with security.enable_tls, a TLS config built by the transport package's TLSManager; with enable_mtls, client certificates are also required and RequirePeerIdentity checks every sender against its certificate - a memory state machine and a raft node whose peers are the configured peers list, with the raft timings, snapshot settings and a snapshot chunk size derived from the message limit Service state comes from the raft node: role, term, leader, quorum (new Node.HasQuorum and Node.Peers) and cluster info. Apply JSON-encodes the command; it used to send fmt's %v form, which the state machine could not parse. Snapshot goes through the raft node, so the log is compacted too. StepDown works. AddNode and RemoveNode return ErrMembershipChangeUnsupported, because the raft implementation has no membership change protocol and changing peers outside the log could create two majorities. They used to report success while changing nothing. Settings that still cannot be honoured fail when the service is created: transport grpc, storage pebble or postgres, discovery other than static, and security.enable_encryption. The earlier refusal of enable_tls and enable_mtls is gone because both are now applied. With admin_api.enabled the admin routes are registered on the app router through admin.NewAPIFromConfig, so enable_auth and api_key apply. The flag now defaults to false. The routes were never registered before, so turning them on by default would newly expose write endpoints. End-to-end tests start three services from configuration over TCP and HTTP, with and without mTLS, and replicate a command to every node. A node whose certificate names another node is shut out of the cluster. README and llm.txt describe the wired extension and what is still missing. --- extensions/consensus/README.md | 37 +- extensions/consensus/extension.go | 10 +- extensions/consensus/internal/config.go | 9 +- extensions/consensus/llm.txt | 54 ++- extensions/consensus/raft/node.go | 62 +++ extensions/consensus/service.go | 355 +++++------------- extensions/consensus/service_cluster_test.go | 354 +++++++++++++++++ extensions/consensus/service_components.go | 316 ++++++++++++++++ extensions/consensus/service_security_test.go | 31 -- 9 files changed, 884 insertions(+), 344 deletions(-) create mode 100644 extensions/consensus/service_cluster_test.go create mode 100644 extensions/consensus/service_components.go delete mode 100644 extensions/consensus/service_security_test.go diff --git a/extensions/consensus/README.md b/extensions/consensus/README.md index 1b099af11..7732bf375 100644 --- a/extensions/consensus/README.md +++ b/extensions/consensus/README.md @@ -4,7 +4,7 @@ # Forge Consensus: Raft consensus building blocks for Go -Forge Consensus is the Raft consensus module for [Forge](https://github.com/xraph/forge), the Go backend framework. It holds a Raft implementation in Go with leader election, pre-vote, log replication and snapshots, plus the pieces a node is built from: log storage on BadgerDB, BoltDB or memory, gRPC, TCP, HTTP and in-process transports, peer discovery through static lists, DNS, Consul, etcd or Kubernetes, and in-memory and persistent state machines. A Forge extension sits on top, but it doesn't wire those pieces together yet, so read the [status](#status) before you pick it for a distributed system. +Forge Consensus is the Raft consensus module for [Forge](https://github.com/xraph/forge), the Go backend framework. It holds a Raft implementation in Go with leader election, pre-vote, log replication and snapshots, plus the pieces a node is built from: log storage on BadgerDB, BoltDB or memory, TCP, HTTP and in-process transports, peer discovery through static lists, DNS, Consul, etcd or Kubernetes, and in-memory and persistent state machines. A Forge extension sits on top and runs a node from configuration. Read the [status](#status) before you pick it for a distributed system. [![Go 1.26+](https://img.shields.io/badge/Go-1.26%2B-00ADD8?logo=go&logoColor=white)](https://go.dev/dl/) [![Go CI](https://github.com/xraph/forge/actions/workflows/go.yml/badge.svg)](https://github.com/xraph/forge/actions/workflows/go.yml) [![Go Reference](https://pkg.go.dev/badge/github.com/xraph/forge/extensions/consensus.svg)](https://pkg.go.dev/github.com/xraph/forge/extensions/consensus) [![Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](../../LICENSE) @@ -144,15 +144,15 @@ Entry 1 is the no-op every new leader writes, and entry 2 is your `set`. Calling ## Status -This module isn't ready to run a production cluster. Here's what we checked against the code as it is today, piece by piece, so you can decide which parts are worth building on: +This module has not run a production cluster yet. Here's what is covered by tests in this repository: | Piece | State | | --- | --- | -| Leader election and log replication in `raft` | Works on the in-process transport. Three nodes elect a leader, and a proposed entry commits on a majority | -| Applying entries on followers | Followers advance their commit index but don't apply committed entries to their state machine, so reads from a follower stay empty. Read from the leader | -| `consensus.NewExtension` | Validates config and registers services, but its storage, transport, discovery, state machine and Raft node are never created. See [the Forge extension](#the-forge-extension) | -| Network transports, BadgerDB and BoltDB storage, discovery backends | The code is here and compiles, but nothing in this repository runs a networked cluster on them yet | -| Cluster tests | `testing/` runs in-process clusters. `TestLogReplication` is skipped under `-short`, which is how CI runs it | +| Leader election, log replication and applying entries in `raft` | Three node clusters elect a leader and replicate commands to every state machine over the in-process, TCP and HTTP transports | +| Durability | The log, term and vote are reloaded from storage on restart; a node only acknowledges entries and votes it has persisted | +| Snapshots | Nodes compact their log into snapshots, and a follower that falls behind the snapshot catches up through InstallSnapshot, sent in chunks | +| `consensus.NewExtension` | Builds storage, transport, state machine and Raft node from config and replicates over TCP or HTTP, with TLS and mTLS. See [the Forge extension](#the-forge-extension) | +| Not implemented | The gRPC transport, membership changes (`AddNode`, `RemoveNode`), leadership transfer, linearizable reads, encryption at rest, and dynamic discovery in the extension (peers come from the static list) | ## Packages @@ -162,7 +162,7 @@ You assemble a node from these packages yourself, the way the quick start does. | --- | --- | | [`raft`](raft/) | `raft.NewNode(config, logger, stateMachine, transport, storage)`, elections, replication, snapshots, `Propose`, `AddPeer` | | [`storage`](storage/) | `NewMemoryStorage`, `NewBadgerStorage`, `NewBoltDBStorage`, and a write-ahead log (`NewWAL`) | -| [`transport`](transport/) | `NewLocalTransport` (in process), `NewGRPCTransport`, `NewTCPTransport`, `NewHTTPTransport`, TLS helpers and serializers | +| [`transport`](transport/) | `NewLocalTransport` (in process), `NewTCPTransport`, `NewHTTPTransport`, TLS helpers and serializers. `NewGRPCTransport` returns `ErrGRPCNotImplemented` from `Start` and `Send` | | [`statemachine`](statemachine/) | `NewMemoryStateMachine` (a key-value map with `set`, `delete` and `increment`) and `NewPersistentStateMachine` | | [`discovery`](discovery/) | `NewStaticDiscovery`, `NewDNSDiscovery`, `NewConsulDiscovery`, `NewEtcdDiscovery`, `NewKubernetesDiscovery` | | [`cluster`](cluster/) | Membership, quorum and topology tracking with `cluster.NewManager` | @@ -190,17 +190,18 @@ app := forge.NewApp(forge.AppConfig{ }) ``` -That compiles and starts, and here's what you get today. The extension loads and validates your config, then puts `*consensus.Service` (also named `consensus` and `consensus:service`), `ClusterManager`, `RaftNode`, `StateMachine` and a `*consensus.LeadershipChecker` in the container. Starting it only logs each component it would initialise. Nothing listens on the bind port, the node stays a follower, and so: +`Start` builds the node from config: storage (`badger` or `boltdb` under `storage.path`, or `memory`), the `tcp` or `http` transport on `bind_addr:bind_port` with `transport.max_message_size`, a memory state machine, and a Raft node whose peers are the `peers` list. With `security.enable_tls` the transport serves and dials over TLS; with `enable_mtls` it also requires client certificates and refuses messages whose sender is not named in the certificate (each node's certificate must carry its node ID as a DNS subject alternative name). | Call | Result | | --- | --- | -| `Apply` | Always `ErrNotLeader` | -| `Read` | Panics, because the state machine is nil | -| `Health` | Returns `storage not initialized`, and the service's health loop logs that warning every `health.check_interval` | -| `GetRaftNode`, `GetStateMachine`, `GetStorage`, `GetTransport` | `nil`, and so are the matching container entries | -| `TransferLeadership`, `StepDown` | "not yet implemented" errors | +| `Apply` | On the leader, appends the command and returns once it is committed and applied. Elsewhere `ErrNotLeader` | +| `Read` | Queries the local state machine, which may lag the leader on a follower | +| `Snapshot` | Snapshots the state machine and compacts the log | +| `StepDown` | The leader returns to follower | +| `AddNode`, `RemoveNode` | `ErrMembershipChangeUnsupported` | +| `TransferLeadership` | Not implemented, use `StepDown` | -One more thing to watch: with `advanced.enable_auto_snapshot` on (the default), the service takes a snapshot every `raft.snapshot_interval` (30 minutes by default) and that call panics on the nil state machine, which takes the process down. If you add the extension anyway, set `advanced.enable_auto_snapshot: false`. The admin API under `admin_api` isn't implemented either; turning it on only writes a log line. +Settings the service cannot honour fail when it is created: transport `grpc`, storage `pebble` or `postgres`, any discovery type other than `static`, and `security.enable_encryption`. The container entries for `RaftNode` and `StateMachine` are resolved from the service, so resolve them after the app has started. With `admin_api.enabled` (off by default) the admin routes are registered on the app router under `admin_api.path_prefix`; set `admin_api.enable_auth` and `api_key` whenever that router is reachable by anyone else. ## Configuration @@ -243,12 +244,12 @@ Validation runs when the extension registers. If any of these rules fail, your a | `transport.type` is `tcp` or `http` (`grpc` is rejected because it is not implemented) | `tcp` | | `transport.max_message_size` is positive | 4MB | | `discovery.type` is `static`, `dns`, `consul`, `etcd` or `kubernetes` | `static` | -| `storage.type` is `badger`, `boltdb`, `pebble` or `postgres`, and `storage.path` is set | `badger`, `./data/consensus` | +| `storage.type` is `badger`, `boltdb` or `memory` (`pebble` and `postgres` are not implemented), and `storage.path` is set | `badger`, `./data/consensus` | | `security.cert_file` and `key_file` are set when `enable_tls` is on, and `ca_file` when `enable_mtls` is on | TLS off | | `security.enable_encryption` is off (encryption at rest is not implemented) | off | | `admin_api.api_key` is set when `admin_api.enable_auth` is on | auth off | -The service does not start a raft node or a transport yet, so `Start` fails when `enable_tls` or `enable_mtls` is set rather than run without them. To run a secured cluster today, build it from `raft.NewNode` with `transport.NewTCPTransport` or `transport.NewHTTPTransport`, passing `TLSConfig` (from `transport.NewTLSManager`) and `RequirePeerIdentity`. With peer identity on, each node's certificate must name its node ID as a DNS subject alternative name. The admin API takes `admin.WithAPIKey` or `admin.NewAPIFromConfig` to require an API key on every route. +When you assemble a node yourself, pass `TLSConfig` (from `transport.NewTLSManager`) and `RequirePeerIdentity` to `transport.NewTCPTransport` or `transport.NewHTTPTransport` to get the same protection. The admin API takes `admin.WithAPIKey` or `admin.NewAPIFromConfig` to require an API key on every route. The options are `WithNodeID`, `WithClusterID`, `WithBindAddress`, `WithPeers`, `WithTransportType`, `WithDiscoveryType`, `WithStorageType`, `WithStoragePath`, `WithTLS`, `WithMTLS`, `WithConfig` and `WithRequireConfig`. The config also has `election`, `health`, `observability`, `resilience`, `admin_api`, `events` and `advanced` sections. Their full key list and defaults are in [`internal/config.go`](internal/config.go) and on the [configuration page](https://www.xraph.com/docs/forge/extensions/consensus/configuration). Today the extension acts on a handful of them: `health.enabled` and `health.check_interval` drive its health loop, `observability.metrics.enabled` and `collection_interval` drive metrics collection, and `advanced.enable_auto_snapshot` with `raft.snapshot_interval` drives the snapshot loop. `events.enabled` is on by default. It adds `events` to the extension's dependencies and publishes start and stop events when an event bus is in the container. @@ -266,7 +267,7 @@ The options are `WithNodeID`, `WithClusterID`, `WithBindAddress`, `WithPeers`, ` ### Is there a Raft implementation in Go I can embed in a Forge service? -There is one in [`raft`](raft/), and the quick start shows a three-node cluster electing a leader and committing an entry. Check the [status](#status) table first: follower state machines don't apply entries yet, and the networked transports haven't been run as a cluster here. +There is one in [`raft`](raft/), and the quick start shows a three-node cluster electing a leader and committing an entry. Check the [status](#status) table first for what is not implemented. ### How does leader election work? diff --git a/extensions/consensus/extension.go b/extensions/consensus/extension.go index 319d5393b..8edafd76c 100644 --- a/extensions/consensus/extension.go +++ b/extensions/consensus/extension.go @@ -7,6 +7,7 @@ import ( "github.com/xraph/forge" "github.com/xraph/forge/errors" + "github.com/xraph/forge/extensions/consensus/admin" "github.com/xraph/forge/extensions/consensus/internal" "github.com/xraph/vessel" ) @@ -85,10 +86,13 @@ func (e *Extension) Register(app forge.App) error { return err } - // TODO: Register admin API routes if enabled - // Admin API will be implemented in internal/admin package if e.config.AdminAPI.Enabled { - e.Logger().Info("admin API enabled but not yet implemented") + api, err := admin.NewAPIFromConfig(service, nil, nil, e.Logger(), e.config.AdminAPI) + if err != nil { + return fmt.Errorf("consensus admin API: %w", err) + } + + api.RegisterRoutes(app.Router(), e.config.AdminAPI.PathPrefix) } e.Logger().Info("consensus extension registered", diff --git a/extensions/consensus/internal/config.go b/extensions/consensus/internal/config.go index bd2edb6aa..507446077 100644 --- a/extensions/consensus/internal/config.go +++ b/extensions/consensus/internal/config.go @@ -216,7 +216,10 @@ type ResilienceConfig struct { // AdminAPIConfig contains admin API configuration. type AdminAPIConfig struct { - Enabled bool `default:"true" json:"enabled" yaml:"enabled"` + // Enabled registers the admin routes on the app router. They can add + // commands to the replicated log, so set EnableAuth with an APIKey + // whenever the router is reachable by anyone else. + Enabled bool `default:"false" json:"enabled" yaml:"enabled"` PathPrefix string `default:"/consensus" json:"path_prefix" yaml:"path_prefix"` EnableAuth bool `default:"false" json:"enable_auth" yaml:"enable_auth"` APIKey string `json:"api_key" yaml:"api_key"` @@ -360,7 +363,7 @@ func DefaultConfig() Config { CircuitBreakerTimeout: 30 * time.Second, }, AdminAPI: AdminAPIConfig{ - Enabled: true, + Enabled: false, PathPrefix: "/consensus", EnableAuth: false, }, @@ -433,7 +436,7 @@ func (c *Config) Validate() error { // Validate storage config validStorageTypes := map[string]bool{ - "badger": true, "boltdb": true, "pebble": true, "postgres": true, + "badger": true, "boltdb": true, "memory": true, "pebble": true, "postgres": true, } if !validStorageTypes[c.Storage.Type] { return fmt.Errorf("%w: invalid storage type: %s", ErrInvalidConfig, c.Storage.Type) diff --git a/extensions/consensus/llm.txt b/extensions/consensus/llm.txt index df4af176f..7b5c41478 100644 --- a/extensions/consensus/llm.txt +++ b/extensions/consensus/llm.txt @@ -4,26 +4,22 @@ Raft consensus building blocks in Go: a Raft node with leader election, pre-vote, log replication and snapshots, plus storage, transports, discovery and state machines to build a -node from. A Forge extension sits on top, but it does not wire those pieces together yet. +node from. A Forge extension sits on top and runs a node from configuration. -Read "Status" before you use any of it. Today the useful path is assembling `raft.Node` -yourself on the in-process transport. +Read "Status" before you use any of it. Module: github.com/xraph/forge/extensions/consensus (package `consensus`). Most root types and helpers are aliases over `consensus/internal` (exports.go). ## Status -- `raft`: leader election and log replication work on the in-process transport. Three nodes - elect a leader and a proposed entry commits on a majority. -- Followers advance their commit index but don't apply committed entries to their state - machine. Read from the leader. -- `consensus.NewExtension`: validates config and registers services, but its storage, - transport, discovery, state machine and Raft node are never created (the init steps only log). -- gRPC/TCP/HTTP transports, BadgerDB/BoltDB storage and the discovery backends compile, but - nothing in this repo runs a networked cluster on them. -- `testing/` runs in-process clusters; `TestLogReplication` is skipped under `-short`, which is - how CI runs it. +- `raft`: leader election, log replication and applying entries work over the in-process, TCP and + HTTP transports (three node tests). Log, term and vote survive restarts. Followers behind the + leader's snapshot catch up through chunked InstallSnapshot. +- `consensus.NewExtension` builds storage (badger, boltdb, memory), the tcp or http transport + (TLS/mTLS from security.*), a memory state machine and the Raft node from config. +- Not implemented: gRPC transport, membership changes, leadership transfer, linearizable reads, + encryption at rest, non-static discovery in the extension. ## Packages and constructors @@ -90,7 +86,7 @@ WithBindAddress(addr string, port int) WithPeers(peers []PeerConfig) // PeerConfig{ID, Address string; Port int} WithTransportType(transportType string) // tcp, http (grpc is not implemented) WithDiscoveryType(discoveryType string) // static, dns, consul, etcd, kubernetes -WithStorageType(storageType string) // badger, boltdb, pebble, postgres +WithStorageType(storageType string) // badger, boltdb, memory (pebble, postgres not implemented) WithStoragePath(path string) WithTLS(certFile, keyFile string) WithMTLS(caFile string) @@ -99,14 +95,16 @@ WithRequireConfig(require bool) ``` Container entries: `*consensus.Service` (aliases `consensus`, `consensus:service`), -`ClusterManager` (`consensus:cluster`), `RaftNode` (`consensus:raft`), `StateMachine` -(`consensus:statemachine`), `*LeadershipChecker` (`consensus:leadership`). Because the -components are never built, the RaftNode and StateMachine entries are nil. +`ClusterManager` (`consensus:cluster`, nil: membership is the static peer list), `RaftNode` +(`consensus:raft`), `StateMachine` (`consensus:statemachine`), `*LeadershipChecker` +(`consensus:leadership`). RaftNode and StateMachine are created by Start, so resolve them after +the app has started. -What you get from the service today: `Apply` always returns ErrNotLeader; `Read` panics on the -nil state machine; `HealthCheck` returns "storage not initialized" (and the health loop logs it every -health.check_interval); GetRaftNode/GetStateMachine/GetStorage/GetTransport return nil; -TransferLeadership and StepDown return "not yet implemented". +Service: `Apply` commits through the leader (ErrNotLeader elsewhere); `Read` queries the local +state machine; `Snapshot` compacts; `StepDown` works; AddNode/RemoveNode return +ErrMembershipChangeUnsupported; TransferLeadership is not implemented. NewConsensusService fails +for grpc transport, pebble/postgres storage, non-static discovery and enable_encryption. +admin_api.enabled (default false) registers the admin routes on the app router. ## Config @@ -117,9 +115,8 @@ bind_addr ("127.0.0.1"); transport.type tcp or http ("tcp", grpc rejected as not static/dns/consul/etcd/kubernetes ("static"); storage.type badger/boltdb/pebble/postgres ("badger") with storage.path ("./data/consensus"); TLS needs cert_file and key_file, mTLS needs ca_file; enable_encryption is rejected (not implemented); admin_api.enable_auth needs api_key. -Service.Start fails when enable_tls or enable_mtls is set, because the service opens no transport -yet. Secured clusters are built from raft.NewNode plus transport.NewTCPTransport/NewHTTPTransport -with TLSConfig and RequirePeerIdentity (node ID as a DNS SAN in each node certificate). +enable_tls serves and dials over TLS; enable_mtls also requires client certificates and checks +each message's sender against its certificate (node ID as a DNS SAN in each node certificate). Other sections: election, health, observability, resilience, admin_api, events, advanced. Full keys and defaults in internal/config.go. The extension acts on: health.enabled and @@ -129,12 +126,9 @@ dependency and publishes start and stop events when an event bus is present). ## Gotchas -- advanced.enable_auto_snapshot is on by default; every raft.snapshot_interval (30m) the snapshot - call panics on the nil state machine and takes the process down. Set it to false if you add - the extension. +- bind_addr defaults to 127.0.0.1. Set it explicitly for a cluster spanning hosts. ## Not implemented yet -- The extension's component wiring (storage, transport, discovery, state machine, Raft node). -- The admin API under `admin_api`: turning it on only writes a log line. -- Applying committed entries on followers. +- gRPC transport, cluster membership changes, leadership transfer, linearizable reads, + encryption at rest, and discovery other than the static peer list in the extension. diff --git a/extensions/consensus/raft/node.go b/extensions/consensus/raft/node.go index 9cda91b63..d3e80e5b3 100644 --- a/extensions/consensus/raft/node.go +++ b/extensions/consensus/raft/node.go @@ -92,6 +92,10 @@ type Node struct { // snapshotRecv assembles an incoming chunked snapshot. Guarded by mu. snapshotRecv *snapshotReceive + // lastLeaderContact is when a valid leader last reached this node. + // Guarded by mu. + lastLeaderContact time.Time + // RPC correlation. Every outgoing request gets a fresh ID from requestSeq, // which the peer echoes in its response, so a late response can never be // matched to a newer request to the same peer. @@ -408,6 +412,7 @@ func (n *Node) handleAppendEntries(req internal.AppendEntriesRequest) internal.A n.setRole(internal.RoleFollower) n.resetElectionTimerUnsafe() n.setLeader(req.LeaderID) + n.lastLeaderContact = time.Now() resp.LastLogIndex = n.log.LastIndex() @@ -550,6 +555,7 @@ func (n *Node) handleInstallSnapshot(req internal.InstallSnapshotRequest) intern n.setRole(internal.RoleFollower) n.resetElectionTimerUnsafe() n.setLeader(req.LeaderID) + n.lastLeaderContact = time.Now() if req.Offset == 0 { n.snapshotRecv = &snapshotReceive{ @@ -1025,3 +1031,59 @@ func (n *Node) AddPeer(peerID string) { ) } } + +// PeerStatus is what this node knows about one peer. +type PeerStatus struct { + ID string + // LastContact is when this node last got a response from the peer while + // leading. It is zero on followers. + LastContact time.Time + // MatchIndex is the highest entry known to be replicated on the peer. It + // is only maintained on the leader. + MatchIndex uint64 +} + +// Peers returns the status of every peer. +func (n *Node) Peers() []PeerStatus { + n.mu.RLock() + defer n.mu.RUnlock() + + n.peersLock.RLock() + defer n.peersLock.RUnlock() + + out := make([]PeerStatus, 0, len(n.peers)) + for id, p := range n.peers { + out = append(out, PeerStatus{ID: id, LastContact: p.LastContact, MatchIndex: n.matchIndex[id]}) + } + + return out +} + +// HasQuorum reports whether this node is in touch with a working majority. +// A leader needs responses from a majority (itself included) within the +// maximum election timeout; a follower needs to have heard from a leader +// within that time. +func (n *Node) HasQuorum() bool { + window := n.config.ElectionTimeoutMax + now := time.Now() + + n.mu.RLock() + defer n.mu.RUnlock() + + if n.GetRole() != internal.RoleLeader { + return n.GetLeader() != "" && now.Sub(n.lastLeaderContact) <= window + } + + n.peersLock.RLock() + defer n.peersLock.RUnlock() + + reachable := 1 + + for _, p := range n.peers { + if now.Sub(p.LastContact) <= window { + reachable++ + } + } + + return reachable >= (len(n.peers)+1)/2+1 +} diff --git a/extensions/consensus/service.go b/extensions/consensus/service.go index 472a873b3..4852157c2 100644 --- a/extensions/consensus/service.go +++ b/extensions/consensus/service.go @@ -2,6 +2,7 @@ package consensus import ( "context" + "encoding/json" "fmt" "sync" "time" @@ -9,6 +10,7 @@ import ( "github.com/xraph/forge" "github.com/xraph/forge/errors" "github.com/xraph/forge/extensions/consensus/internal" + "github.com/xraph/forge/extensions/consensus/raft" ) // Service implements internal.ConsensusService. @@ -18,6 +20,7 @@ type Service struct { metrics forge.Metrics // Core components + node *raft.Node raftNode internal.RaftNode stateMachine internal.StateMachine clusterManager internal.ClusterManager @@ -26,9 +29,6 @@ type Service struct { storage internal.Storage // State - role internal.NodeRole - term uint64 - leader string startTime time.Time started bool mu sync.RWMutex @@ -54,11 +54,14 @@ func NewConsensusService(config internal.Config, logger forge.Logger, metrics fo return nil, fmt.Errorf("invalid config: %w", err) } + if err := checkSupported(config); err != nil { + return nil, err + } + s := &Service{ config: config, logger: logger, metrics: metrics, - role: RoleFollower, startTime: time.Now(), } @@ -74,52 +77,22 @@ func (s *Service) Start(ctx context.Context) error { return ErrAlreadyStarted } - if err := checkUnwiredSecurity(s.config); err != nil { - return err - } - - s.ctx, s.cancel = context.WithCancel(ctx) + s.ctx, s.cancel = context.WithCancel(context.WithoutCancel(ctx)) s.logger.Info("starting consensus service", forge.F("node_id", s.config.NodeID), forge.F("cluster_id", s.config.ClusterID), forge.F("bind_addr", s.config.BindAddr), forge.F("bind_port", s.config.BindPort), + forge.F("transport", s.config.Transport.Type), + forge.F("storage", s.config.Storage.Type), ) - s.logger.Warn("the consensus service does not run a raft node or open a transport yet; "+ - "build a cluster with raft.NewNode and the transport package to replicate data", - forge.F("node_id", s.config.NodeID), - ) - - // Initialize storage - if err := s.initStorage(); err != nil { - return fmt.Errorf("failed to initialize storage: %w", err) - } - - // Initialize transport - if err := s.initTransport(); err != nil { - return fmt.Errorf("failed to initialize transport: %w", err) - } - - // Initialize discovery - if err := s.initDiscovery(); err != nil { - return fmt.Errorf("failed to initialize discovery: %w", err) - } - - // Initialize cluster manager - if err := s.initClusterManager(); err != nil { - return fmt.Errorf("failed to initialize cluster manager: %w", err) - } - - // Initialize state machine - if err := s.initStateMachine(); err != nil { - return fmt.Errorf("failed to initialize state machine: %w", err) - } + if err := s.startComponents(ctx); err != nil { + s.cancel() + s.stopComponents(context.WithoutCancel(ctx)) - // Initialize Raft node - if err := s.initRaftNode(); err != nil { - return fmt.Errorf("failed to initialize raft node: %w", err) + return err } // Start background tasks @@ -171,30 +144,7 @@ func (s *Service) Stop(ctx context.Context) error { s.logger.Warn("timeout waiting for background tasks to stop") } - // Stop components in reverse order - if s.raftNode != nil { - if err := s.raftNode.Stop(ctx); err != nil { - s.logger.Error("failed to stop raft node", forge.F("error", err)) - } - } - - if s.discovery != nil { - if err := s.discovery.Stop(ctx); err != nil { - s.logger.Error("failed to stop discovery", forge.F("error", err)) - } - } - - if s.transport != nil { - if err := s.transport.Stop(ctx); err != nil { - s.logger.Error("failed to stop transport", forge.F("error", err)) - } - } - - if s.storage != nil { - if err := s.storage.Stop(ctx); err != nil { - s.logger.Error("failed to stop storage", forge.F("error", err)) - } - } + s.stopComponents(ctx) s.logger.Info("consensus service stopped") @@ -203,34 +153,53 @@ func (s *Service) Stop(ctx context.Context) error { // IsLeader returns true if this node is the leader. func (s *Service) IsLeader() bool { - s.mu.RLock() - defer s.mu.RUnlock() + if node := s.raft(); node != nil { + return node.IsLeader() + } - return s.role == internal.RoleLeader + return false } // GetLeader returns the current leader node ID. func (s *Service) GetLeader() string { - s.mu.RLock() - defer s.mu.RUnlock() + if node := s.raft(); node != nil { + return node.GetLeader() + } - return s.leader + return "" } // GetRole returns the current role of this node. func (s *Service) GetRole() NodeRole { - s.mu.RLock() - defer s.mu.RUnlock() + if node := s.raft(); node != nil { + return node.GetRole() + } - return s.role + return internal.RoleFollower } // GetTerm returns the current term. func (s *Service) GetTerm() uint64 { + if node := s.raft(); node != nil { + return node.GetTerm() + } + + return 0 +} + +// raft returns the running raft node, or nil before Start. +func (s *Service) raft() *raft.Node { s.mu.RLock() defer s.mu.RUnlock() - return s.term + return s.node +} + +// hasQuorum reports whether this node is in touch with a working majority. +func (s *Service) hasQuorum() bool { + node := s.raft() + + return node != nil && node.HasQuorum() } // Apply applies a command to the state machine. @@ -256,10 +225,16 @@ func (s *Service) Apply(ctx context.Context, cmd Command) error { s.recordOperation(time.Since(start), true) }() - // Create log entry + data, err := json.Marshal(cmd) + if err != nil { + s.recordOperation(time.Since(start), false) + + return fmt.Errorf("failed to encode command: %w", err) + } + entry := LogEntry{ Type: EntryNormal, - Data: s.encodeCommand(cmd), + Data: data, Created: time.Now(), } @@ -285,9 +260,8 @@ func (s *Service) Read(ctx context.Context, query any) (any, error) { s.mu.RUnlock() - // For now, allow reads from any node (eventually consistent) - // TODO: Implement linearizable reads with read index - + // Reads are served from the local state machine, so a follower may lag + // the leader. Linearizable reads (read index) are not implemented. return s.stateMachine.Query(query) } @@ -304,11 +278,7 @@ func (s *Service) GetStats() internal.ConsensusStats { raftStats = s.raftNode.GetStats() } - var clusterSize, healthyNodes int - if s.clusterManager != nil { - clusterSize = s.clusterManager.GetClusterSize() - healthyNodes = s.clusterManager.GetHealthyNodes() - } + clusterSize, healthyNodes := s.clusterCounts(s.node) uptime := time.Since(s.startTime) @@ -325,17 +295,17 @@ func (s *Service) GetStats() internal.ConsensusStats { return internal.ConsensusStats{ NodeID: s.config.NodeID, ClusterID: s.config.ClusterID, - Role: s.role, + Role: raftStats.Role, Status: internal.StatusActive, - Term: s.term, - LeaderID: s.leader, + Term: raftStats.Term, + LeaderID: raftStats.Leader, CommitIndex: raftStats.CommitIndex, LastApplied: raftStats.LastApplied, LastLogIndex: raftStats.LastLogIndex, LastLogTerm: raftStats.LastLogTerm, ClusterSize: clusterSize, HealthyNodes: healthyNodes, - HasQuorum: s.clusterManager != nil && s.clusterManager.HasQuorum(), + HasQuorum: s.node != nil && s.node.HasQuorum(), ElectionsTotal: s.elections, ElectionsFailed: s.electionsFailed, OperationsTotal: s.operations, @@ -371,8 +341,7 @@ func (s *Service) HealthCheck(ctx context.Context) error { return errors.New("transport not initialized") } - // Check if we have quorum (if not leader) - if !s.IsLeader() && s.clusterManager != nil && !s.clusterManager.HasQuorum() { + if !s.hasQuorum() { return errors.New("no quorum") } @@ -426,7 +395,7 @@ func (s *Service) GetHealthStatus(ctx context.Context) HealthStatus { } // Quorum check - hasQuorum := s.clusterManager != nil && s.clusterManager.HasQuorum() + hasQuorum := s.hasQuorum() checks = append(checks, HealthCheck{ Name: "quorum", Healthy: hasQuorum, @@ -434,11 +403,7 @@ func (s *Service) GetHealthStatus(ctx context.Context) HealthStatus { CheckedAt: time.Now(), }) - var totalNodes, activeNodes int - if s.clusterManager != nil { - totalNodes = s.clusterManager.GetClusterSize() - activeNodes = s.clusterManager.GetHealthyNodes() - } + totalNodes, activeNodes := s.clusterCounts(s.raft()) status := "healthy" if !healthy { @@ -462,90 +427,66 @@ func (s *Service) GetHealthStatus(ctx context.Context) HealthStatus { // GetClusterInfo returns cluster information. func (s *Service) GetClusterInfo() ClusterInfo { - s.mu.RLock() - defer s.mu.RUnlock() + node := s.raft() + if node == nil { + return ClusterInfo{ID: s.config.ClusterID} + } - var ( - nodes []NodeInfo - totalNodes, activeNodes int - ) + stats := node.GetStats() + nodes := s.clusterNodes(node) - if s.clusterManager != nil { - nodes = s.clusterManager.GetNodes() + activeNodes := 0 - totalNodes = len(nodes) - for _, node := range nodes { - if node.Status == StatusActive { - activeNodes++ - } + for _, n := range nodes { + if n.Status == StatusActive { + activeNodes++ } } - var commitIndex, lastApplied uint64 - - if s.raftNode != nil { - stats := s.raftNode.GetStats() - commitIndex = stats.CommitIndex - lastApplied = stats.LastApplied - } - return ClusterInfo{ ID: s.config.ClusterID, - Leader: s.leader, - Term: s.term, + Leader: stats.Leader, + Term: stats.Term, Nodes: nodes, - TotalNodes: totalNodes, + TotalNodes: len(nodes), ActiveNodes: activeNodes, - HasQuorum: s.clusterManager != nil && s.clusterManager.HasQuorum(), - CommitIndex: commitIndex, - LastApplied: lastApplied, + HasQuorum: node.HasQuorum(), + CommitIndex: stats.CommitIndex, + LastApplied: stats.LastApplied, } } -// AddNode adds a node to the cluster. +// AddNode is not supported: cluster membership comes from the static peer +// list, and the raft implementation has no membership change protocol. +// Changing membership outside the log would risk two majorities. func (s *Service) AddNode(ctx context.Context, nodeID, address string, port int) error { - if !s.IsLeader() { - return NewNotLeaderError(s.config.NodeID, s.GetLeader()) - } - - if s.clusterManager == nil { - return errors.New("cluster manager not initialized") - } - - return s.clusterManager.AddNode(nodeID, address, port) + return ErrMembershipChangeUnsupported } -// RemoveNode removes a node from the cluster. +// RemoveNode is not supported, for the same reason as AddNode. func (s *Service) RemoveNode(ctx context.Context, nodeID string) error { - if !s.IsLeader() { - return NewNotLeaderError(s.config.NodeID, s.GetLeader()) - } - - if s.clusterManager == nil { - return errors.New("cluster manager not initialized") - } - - return s.clusterManager.RemoveNode(nodeID) + return ErrMembershipChangeUnsupported } -// TransferLeadership transfers leadership to another node. +// TransferLeadership is not implemented. Use StepDown to let another node +// win the next election. func (s *Service) TransferLeadership(ctx context.Context, targetNodeID string) error { if !s.IsLeader() { return ErrNotLeader } - // TODO: Implement leadership transfer - return errors.New("leadership transfer not yet implemented") + return errors.New("leadership transfer is not implemented; use StepDown") } -// StepDown causes the leader to step down. +// StepDown makes the leader return to follower so another node can be +// elected. func (s *Service) StepDown(ctx context.Context) error { - if !s.IsLeader() { - return ErrNotLeader + node := s.raft() + if node == nil { + return ErrNotStarted } - // TODO: Implement step down - return errors.New("step down not yet implemented") + return node.StepDown(ctx) } // Snapshot creates a snapshot. @@ -562,8 +503,7 @@ func (s *Service) Snapshot(ctx context.Context) error { start := time.Now() - snapshot, err := s.stateMachine.Snapshot() - if err != nil { + if err := s.raft().Snapshot(); err != nil { return fmt.Errorf("failed to create snapshot: %w", err) } @@ -573,9 +513,6 @@ func (s *Service) Snapshot(ctx context.Context) error { s.metricsLock.Unlock() s.logger.Info("snapshot created", - forge.F("index", snapshot.Index), - forge.F("term", snapshot.Term), - forge.F("size", snapshot.Size), forge.F("duration", time.Since(start)), ) @@ -611,7 +548,8 @@ func (s *Service) GetStateMachine() StateMachine { return s.stateMachine } -// GetClusterManager returns the cluster manager. +// GetClusterManager returns nil: membership comes from the static peer list +// and cluster state is read from the raft node (see GetClusterInfo). func (s *Service) GetClusterManager() ClusterManager { return s.clusterManager } @@ -631,60 +569,6 @@ func (s *Service) GetStorage() Storage { return s.storage } -// Initialize methods (placeholders - will be implemented in separate files) - -func (s *Service) initStorage() error { - // Will be implemented with actual storage backends - s.logger.Info("initializing storage", - forge.F("type", s.config.Storage.Type), - forge.F("path", s.config.Storage.Path), - ) - - return nil -} - -func (s *Service) initTransport() error { - // Will be implemented with actual transport implementations - s.logger.Info("initializing transport", - forge.F("type", s.config.Transport.Type), - forge.F("bind", fmt.Sprintf("%s:%d", s.config.BindAddr, s.config.BindPort)), - ) - - return nil -} - -func (s *Service) initDiscovery() error { - // Will be implemented with actual discovery implementations - s.logger.Info("initializing discovery", - forge.F("type", s.config.Discovery.Type), - ) - - return nil -} - -func (s *Service) initClusterManager() error { - // Will be implemented with actual cluster manager - s.logger.Info("initializing cluster manager") - - return nil -} - -func (s *Service) initStateMachine() error { - // Will be implemented with actual state machine - s.logger.Info("initializing state machine") - - return nil -} - -func (s *Service) initRaftNode() error { - // Will be implemented with actual Raft implementation - s.logger.Info("initializing raft node", - forge.F("node_id", s.config.NodeID), - ) - - return nil -} - func (s *Service) startBackgroundTasks() { // Health check task if s.config.Health.Enabled { @@ -699,13 +583,6 @@ func (s *Service) startBackgroundTasks() { go s.metricsCollectionLoop() } - - // Auto snapshot task - if s.config.Advanced.EnableAutoSnapshot { - s.wg.Add(1) - - go s.autoSnapshotLoop() - } } func (s *Service) healthCheckLoop() { @@ -742,24 +619,6 @@ func (s *Service) metricsCollectionLoop() { } } -func (s *Service) autoSnapshotLoop() { - defer s.wg.Done() - - ticker := time.NewTicker(s.config.Raft.SnapshotInterval) - defer ticker.Stop() - - for { - select { - case <-s.ctx.Done(): - return - case <-ticker.C: - if err := s.Snapshot(s.ctx); err != nil { - s.logger.Error("auto snapshot failed", forge.F("error", err)) - } - } - } -} - func (s *Service) collectMetrics() { if s.metrics == nil { return @@ -814,25 +673,3 @@ func (s *Service) recordOperation(duration time.Duration, success bool) { } } } - -func (s *Service) encodeCommand(cmd Command) []byte { - // TODO: Implement proper encoding - return fmt.Appendf(nil, "%v", cmd) -} - -// checkUnwiredSecurity refuses to start when a security option is set that -// the service cannot apply. The service does not build a raft node or a -// network transport yet (its init steps only log), so TLS settings would be -// silently ignored. Failing here keeps operators from believing cluster -// traffic is protected. Applications that need a secured cluster today build -// it from raft.NewNode with transport.NewTCPTransport or NewHTTPTransport and -// their TLSConfig and RequirePeerIdentity options. -func checkUnwiredSecurity(cfg internal.Config) error { - if cfg.Security.EnableTLS || cfg.Security.EnableMTLS { - return fmt.Errorf("%w: security.enable_tls and security.enable_mtls cannot be honoured because the consensus "+ - "service does not start a network transport yet; wire raft.NewNode with the transport package's TLSConfig instead", - internal.ErrInvalidConfig) - } - - return nil -} diff --git a/extensions/consensus/service_cluster_test.go b/extensions/consensus/service_cluster_test.go new file mode 100644 index 000000000..ac1bbb487 --- /dev/null +++ b/extensions/consensus/service_cluster_test.go @@ -0,0 +1,354 @@ +package consensus + +import ( + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "errors" + "fmt" + "math/big" + "net" + "os" + "path/filepath" + "testing" + "time" + + "github.com/xraph/forge" + "github.com/xraph/forge/extensions/consensus/internal" +) + +func freePorts(t *testing.T, n int) []int { + t.Helper() + + ports := make([]int, n) + + var lc net.ListenConfig + + for i := range n { + l, err := lc.Listen(t.Context(), "tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + + ports[i] = l.Addr().(*net.TCPAddr).Port + _ = l.Close() + } + + return ports +} + +func clusterConfigs(t *testing.T, transportType string, size int) []internal.Config { + t.Helper() + + ports := freePorts(t, size) + peers := make([]internal.PeerConfig, size) + + for i := range size { + peers[i] = internal.PeerConfig{ID: fmt.Sprintf("n%d", i+1), Address: "127.0.0.1", Port: ports[i]} + } + + cfgs := make([]internal.Config, size) + + for i := range size { + c := internal.DefaultConfig() + c.NodeID = peers[i].ID + c.BindAddr = "127.0.0.1" + c.BindPort = ports[i] + c.Peers = peers + c.Transport.Type = transportType + c.Storage.Type = "memory" + c.Raft.HeartbeatInterval = 50 * time.Millisecond + c.Raft.ElectionTimeoutMin = 300 * time.Millisecond + c.Raft.ElectionTimeoutMax = 600 * time.Millisecond + cfgs[i] = c + } + + return cfgs +} + +func startServices(t *testing.T, cfgs []internal.Config) []*Service { + t.Helper() + + services := make([]*Service, len(cfgs)) + + for i, cfg := range cfgs { + s, err := NewConsensusService(cfg, forge.NewNoopLogger(), nil) + if err != nil { + t.Fatal(err) + } + + if err := s.Start(context.Background()); err != nil { + t.Fatalf("start %s: %v", cfg.NodeID, err) + } + + services[i] = s + } + + t.Cleanup(func() { + for _, s := range services { + _ = s.Stop(context.Background()) + } + }) + + return services +} + +func waitForServiceLeader(t *testing.T, services []*Service) *Service { + t.Helper() + + deadline := time.Now().Add(15 * time.Second) + + for time.Now().Before(deadline) { + var leaders []*Service + + for _, s := range services { + if s.IsLeader() { + leaders = append(leaders, s) + } + } + + if len(leaders) == 1 { + return leaders[0] + } + + time.Sleep(20 * time.Millisecond) + } + + t.Fatal("no single leader elected") + + return nil +} + +// replicateAndRead applies a command through the leader's service and waits +// until every node's service reads it back. +func replicateAndRead(t *testing.T, services []*Service) { + t.Helper() + + leader := waitForServiceLeader(t, services) + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + cmd := Command{Type: "set", Payload: map[string]any{"key": "greeting", "value": "hello"}} + if err := leader.Apply(ctx, cmd); err != nil { + t.Fatalf("apply on leader %s: %v", leader.config.NodeID, err) + } + + for _, s := range services { + deadline := time.Now().Add(10 * time.Second) + + for { + got, err := s.Read(ctx, map[string]any{"type": "get", "key": "greeting"}) + if err == nil && got == "hello" { + break + } + + if time.Now().After(deadline) { + t.Fatalf("%s read %v, %v", s.config.NodeID, got, err) + } + + time.Sleep(20 * time.Millisecond) + } + + if !s.hasQuorum() { + t.Fatalf("%s reports no quorum in a healthy cluster", s.config.NodeID) + } + } + + info := leader.GetClusterInfo() + if info.TotalNodes != 3 || info.ActiveNodes != 3 || info.Leader != leader.config.NodeID { + t.Fatalf("cluster info from leader: %+v", info) + } +} + +// Three services started from configuration elect a leader and replicate a +// command over each network transport. +func TestServiceClusterReplicates(t *testing.T) { + for _, kind := range []string{"tcp", "http"} { + t.Run(kind, func(t *testing.T) { + replicateAndRead(t, startServices(t, clusterConfigs(t, kind, 3))) + }) + } +} + +// The same cluster with security.enable_mtls: every node presents a +// certificate naming its node ID, and a node whose certificate names someone +// else cannot take part. +func TestServiceClusterReplicatesOverMTLS(t *testing.T) { + pki := newServicePKI(t) + + for _, kind := range []string{"tcp", "http"} { + t.Run(kind, func(t *testing.T) { + cfgs := clusterConfigs(t, kind, 3) + + for i := range cfgs { + cert, key := pki.issue(t, cfgs[i].NodeID) + cfgs[i].Security = internal.SecurityConfig{ + EnableTLS: true, EnableMTLS: true, CertFile: cert, KeyFile: key, CAFile: pki.caFile, + } + } + + replicateAndRead(t, startServices(t, cfgs)) + }) + } +} + +// A node whose certificate names a different node is cut off: the others +// still elect a leader, but its messages are refused. +func TestServiceMTLSRejectsMismatchedCertificate(t *testing.T) { + pki := newServicePKI(t) + cfgs := clusterConfigs(t, "tcp", 3) + + for i := range cfgs { + name := cfgs[i].NodeID + if i == 2 { + name = "impostor" + } + + cert, key := pki.issue(t, name) + cfgs[i].Security = internal.SecurityConfig{ + EnableTLS: true, EnableMTLS: true, CertFile: cert, KeyFile: key, CAFile: pki.caFile, + } + } + + services := startServices(t, cfgs) + leader := waitForServiceLeader(t, services[:2]) + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + if err := leader.Apply(ctx, Command{Type: "set", Payload: map[string]any{"key": "k", "value": "v"}}); err != nil { + t.Fatal(err) + } + + time.Sleep(500 * time.Millisecond) + + if _, err := services[2].Read(ctx, map[string]any{"type": "get", "key": "k"}); err == nil { + t.Fatal("the node with a mismatched certificate received replicated data") + } + + if services[2].IsLeader() { + t.Fatal("the node with a mismatched certificate became leader") + } +} + +// Settings the service cannot honour fail with a clear error. +func TestServiceRejectsUnsupportedSettings(t *testing.T) { + cases := map[string]func(*internal.Config){ + "grpc transport": func(c *internal.Config) { c.Transport.Type = "grpc" }, + "encryption": func(c *internal.Config) { c.Security.EnableEncryption = true }, + "dns discovery": func(c *internal.Config) { c.Discovery.Type = "dns" }, + "postgres storage": func(c *internal.Config) { c.Storage.Type = "postgres" }, + "mtls without a ca": func(c *internal.Config) { + c.Security = internal.SecurityConfig{EnableTLS: true, EnableMTLS: true, CertFile: "c", KeyFile: "k"} + }, + } + + for name, mutate := range cases { + cfg := internal.DefaultConfig() + cfg.NodeID = "n1" + mutate(&cfg) + + if _, err := NewConsensusService(cfg, forge.NewNoopLogger(), nil); !errors.Is(err, internal.ErrInvalidConfig) { + t.Fatalf("%s: NewConsensusService returned %v, want ErrInvalidConfig", name, err) + } + } +} + +// Membership changes are refused instead of being half applied. +func TestServiceRefusesMembershipChanges(t *testing.T) { + cfg := clusterConfigs(t, "tcp", 1)[0] + s := startServices(t, []internal.Config{cfg})[0] + + if err := s.AddNode(context.Background(), "n9", "127.0.0.1", 1); !errors.Is(err, ErrMembershipChangeUnsupported) { + t.Fatalf("AddNode returned %v", err) + } +} + +type servicePKI struct { + dir string + caFile string + caKey *ecdsa.PrivateKey + ca *x509.Certificate +} + +func newServicePKI(t *testing.T) *servicePKI { + t.Helper() + + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + + tmpl := &x509.Certificate{ + SerialNumber: big.NewInt(1), + Subject: pkix.Name{CommonName: "test-ca"}, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(time.Hour), + IsCA: true, + KeyUsage: x509.KeyUsageCertSign, + BasicConstraintsValid: true, + } + + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) + if err != nil { + t.Fatal(err) + } + + ca, _ := x509.ParseCertificate(der) + p := &servicePKI{dir: t.TempDir(), caKey: key, ca: ca} + p.caFile = filepath.Join(p.dir, "ca.pem") + writeTestPEM(t, p.caFile, "CERTIFICATE", der) + + return p +} + +func (p *servicePKI) issue(t *testing.T, name string) (certFile, keyFile string) { + t.Helper() + + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + + tmpl := &x509.Certificate{ + SerialNumber: big.NewInt(time.Now().UnixNano()), + Subject: pkix.Name{CommonName: name}, + DNSNames: []string{name}, + IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(time.Hour), + KeyUsage: x509.KeyUsageDigitalSignature, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}, + } + + der, err := x509.CreateCertificate(rand.Reader, tmpl, p.ca, &key.PublicKey, p.caKey) + if err != nil { + t.Fatal(err) + } + + keyDER, err := x509.MarshalECPrivateKey(key) + if err != nil { + t.Fatal(err) + } + + certFile = filepath.Join(p.dir, name+".pem") + keyFile = filepath.Join(p.dir, name+"-key.pem") + + writeTestPEM(t, certFile, "CERTIFICATE", der) + writeTestPEM(t, keyFile, "EC PRIVATE KEY", keyDER) + + return certFile, keyFile +} + +func writeTestPEM(t *testing.T, path, typ string, der []byte) { + t.Helper() + + if err := os.WriteFile(path, pem.EncodeToMemory(&pem.Block{Type: typ, Bytes: der}), 0o600); err != nil { + t.Fatal(err) + } +} diff --git a/extensions/consensus/service_components.go b/extensions/consensus/service_components.go new file mode 100644 index 000000000..0622420fe --- /dev/null +++ b/extensions/consensus/service_components.go @@ -0,0 +1,316 @@ +package consensus + +import ( + "context" + "crypto/tls" + "fmt" + "os" + "path/filepath" + "time" + + "github.com/xraph/forge" + "github.com/xraph/forge/errors" + "github.com/xraph/forge/extensions/consensus/internal" + "github.com/xraph/forge/extensions/consensus/raft" + "github.com/xraph/forge/extensions/consensus/statemachine" + "github.com/xraph/forge/extensions/consensus/storage" + "github.com/xraph/forge/extensions/consensus/transport" +) + +// ErrMembershipChangeUnsupported is returned by AddNode and RemoveNode. The +// raft implementation has no membership change protocol, so the cluster is +// the static peer list in the configuration. +var ErrMembershipChangeUnsupported = errors.New( + "consensus: cluster membership changes are not supported; configure peers statically") + +// startComponents builds and starts storage, transport, state machine and +// raft node from the configuration. On error the caller stops whatever was +// started. +func (s *Service) startComponents(ctx context.Context) error { + if err := checkSupported(s.config); err != nil { + return err + } + + store, err := newStorage(s.config, s.logger) + if err != nil { + return fmt.Errorf("failed to create storage: %w", err) + } + + if err := store.Start(ctx); err != nil { + return fmt.Errorf("failed to start %s storage: %w", s.config.Storage.Type, err) + } + + s.storage = store + + tr, err := newTransport(s.config, s.logger) + if err != nil { + return fmt.Errorf("failed to create transport: %w", err) + } + + if err := tr.Start(ctx); err != nil { + return fmt.Errorf("failed to start %s transport: %w", s.config.Transport.Type, err) + } + + s.transport = tr + + sm := statemachine.NewMemoryStateMachine(statemachine.MemoryStateMachineConfig{}, s.logger) + s.stateMachine = sm + + node, err := raft.NewNode(raftConfig(s.config), s.logger, sm, tr, store) + if err != nil { + return fmt.Errorf("failed to create raft node: %w", err) + } + + for _, peer := range s.config.Peers { + if peer.ID == s.config.NodeID { + continue + } + + if err := tr.AddPeer(peer.ID, peer.Address, peer.Port); err != nil { + return fmt.Errorf("failed to add peer %s: %w", peer.ID, err) + } + + node.AddPeer(peer.ID) + } + + if err := node.Start(s.ctx); err != nil { + return fmt.Errorf("failed to start raft node: %w", err) + } + + s.node = node + s.raftNode = node + + return nil +} + +// stopComponents stops the raft node, transport and storage in that order. +func (s *Service) stopComponents(ctx context.Context) { + stopCtx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + + if s.node != nil { + if err := s.node.Stop(stopCtx); err != nil { + s.logger.Error("failed to stop raft node", forge.F("error", err)) + } + } + + if s.transport != nil { + if err := s.transport.Stop(stopCtx); err != nil { + s.logger.Error("failed to stop transport", forge.F("error", err)) + } + } + + if s.storage != nil { + if err := s.storage.Stop(stopCtx); err != nil { + s.logger.Error("failed to stop storage", forge.F("error", err)) + } + } +} + +// checkSupported fails for settings the service cannot honour. +func checkSupported(cfg internal.Config) error { + if cfg.Discovery.Type != "" && cfg.Discovery.Type != "static" { + return fmt.Errorf("%w: discovery type %q is not wired into the consensus service; "+ + "list the cluster in peers and use discovery type static", internal.ErrInvalidConfig, cfg.Discovery.Type) + } + + switch cfg.Storage.Type { + case "badger", "boltdb", "memory": + default: + return fmt.Errorf("%w: storage type %q is not implemented; use badger, boltdb or memory", + internal.ErrInvalidConfig, cfg.Storage.Type) + } + + return nil +} + +func newStorage(cfg internal.Config, logger forge.Logger) (internal.Storage, error) { + switch cfg.Storage.Type { + case "memory": + return storage.NewMemoryStorage(storage.MemoryStorageConfig{}, logger), nil + case "badger": + if err := os.MkdirAll(cfg.Storage.Path, 0o700); err != nil { + return nil, err + } + + return storage.NewBadgerStorage(storage.BadgerStorageConfig{Path: cfg.Storage.Path, SyncWrites: cfg.Storage.SyncWrites}, logger) + case "boltdb": + if err := os.MkdirAll(cfg.Storage.Path, 0o700); err != nil { + return nil, err + } + + return storage.NewBoltDBStorage(storage.BoltDBStorageConfig{ + Path: filepath.Join(cfg.Storage.Path, "raft.db"), + Timeout: cfg.Storage.BoltOptions.Timeout, + NoSync: cfg.Storage.BoltOptions.NoSync, + NoGrowSync: cfg.Storage.BoltOptions.NoGrowSync, + }, logger) + default: + return nil, fmt.Errorf("unsupported storage type %q", cfg.Storage.Type) + } +} + +// newTransport builds the configured transport. With security.enable_tls it +// serves and dials over TLS; with enable_mtls it also requires client +// certificates and checks that each message's sender matches its certificate. +func newTransport(cfg internal.Config, logger forge.Logger) (internal.Transport, error) { + tlsConfig, err := transportTLS(cfg.Security, logger) + if err != nil { + return nil, err + } + + requireIdentity := cfg.Security.EnableMTLS + + switch cfg.Transport.Type { + case "tcp": + return transport.NewTCPTransport(transport.TCPTransportConfig{ + NodeID: cfg.NodeID, + Address: cfg.BindAddr, + Port: cfg.BindPort, + ConnectionTimeout: cfg.Transport.ConnectionTimeout, + ReadTimeout: cfg.Transport.Timeout, + WriteTimeout: cfg.Transport.Timeout, + IdleTimeout: cfg.Transport.IdleTimeout, + KeepAlive: cfg.Transport.KeepAliveInterval, + MaxMessageSize: cfg.Transport.MaxMessageSize, + MaxConnections: cfg.Transport.MaxConnections, + TLSConfig: tlsConfig, + RequirePeerIdentity: requireIdentity, + }, logger), nil + case "http": + return transport.NewHTTPTransport(transport.HTTPTransportConfig{ + NodeID: cfg.NodeID, + Address: cfg.BindAddr, + Port: cfg.BindPort, + RequestTimeout: cfg.Transport.Timeout, + IdleConnTimeout: cfg.Transport.IdleTimeout, + MaxMessageSize: cfg.Transport.MaxMessageSize, + MaxConnections: cfg.Transport.MaxConnections, + TLSConfig: tlsConfig, + RequirePeerIdentity: requireIdentity, + }, logger), nil + default: + return nil, fmt.Errorf("%w: transport type %q is not implemented; use tcp or http", + internal.ErrInvalidConfig, cfg.Transport.Type) + } +} + +// transportTLS builds the transport TLS config with the transport package's +// TLSManager, or returns nil when TLS is off. +func transportTLS(sec internal.SecurityConfig, logger forge.Logger) (*tls.Config, error) { + if !sec.EnableTLS && !sec.EnableMTLS { + return nil, nil //nolint:nilnil // nil config means plain TCP + } + + cfg := transport.DefaultTLSConfig() + cfg.CertFile = sec.CertFile + cfg.KeyFile = sec.KeyFile + cfg.CAFile = sec.CAFile + cfg.InsecureSkipVerify = sec.SkipVerify + + if sec.EnableMTLS { + cfg.RequireClientCert = true + cfg.ClientCAFile = sec.CAFile + } + + manager, err := transport.NewTLSManager(cfg, logger) + if err != nil { + return nil, fmt.Errorf("failed to load transport TLS settings: %w", err) + } + + return manager.GetTLSConfig(), nil +} + +// raftConfig maps the extension configuration onto the raft node. +func raftConfig(cfg internal.Config) raft.Config { + // JSON base64-encodes snapshot data, so half the message limit leaves room + // for the encoding and the envelope. + chunk := cfg.Transport.MaxMessageSize / 2 + + return raft.Config{ + NodeID: cfg.NodeID, + ClusterID: cfg.ClusterID, + HeartbeatInterval: cfg.Raft.HeartbeatInterval, + ElectionTimeoutMin: cfg.Raft.ElectionTimeoutMin, + ElectionTimeoutMax: cfg.Raft.ElectionTimeoutMax, + SnapshotInterval: cfg.Raft.SnapshotInterval, + SnapshotThreshold: cfg.Raft.SnapshotThreshold, + EnableSnapshots: cfg.Advanced.EnableAutoSnapshot && cfg.Raft.SnapshotInterval > 0, + SnapshotChunkSize: chunk, + MaxAppendEntries: cfg.Raft.MaxAppendEntries, + LogCacheSize: cfg.Raft.LogCacheSize, + TrailingLogs: cfg.Raft.TrailingLogs, + PreVoteEnabled: cfg.Raft.PreVote, + CheckQuorum: cfg.Raft.CheckQuorum, + } +} + +// clusterCounts returns the cluster size and how many members this node +// currently knows to be reachable. +func (s *Service) clusterCounts(node *raft.Node) (total, active int) { + total = len(s.peerConfigs()) + 1 + + if node == nil { + return total, 0 + } + + for _, n := range s.clusterNodes(node) { + if n.Status == StatusActive { + active++ + } + } + + return total, active +} + +// peerConfigs returns the configured peers other than this node. +func (s *Service) peerConfigs() []internal.PeerConfig { + peers := make([]internal.PeerConfig, 0, len(s.config.Peers)) + + for _, p := range s.config.Peers { + if p.ID != s.config.NodeID { + peers = append(peers, p) + } + } + + return peers +} + +// clusterNodes describes this node and its configured peers. A peer counts as +// active when the leader heard from it within the election timeout; followers +// cannot observe each other, so on a follower only itself and the current +// leader are reported active. +func (s *Service) clusterNodes(node *raft.Node) []NodeInfo { + stats := node.GetStats() + window := s.config.Raft.ElectionTimeoutMax + contacts := make(map[string]time.Time) + + for _, p := range node.Peers() { + contacts[p.ID] = p.LastContact + } + + nodes := []NodeInfo{{ + ID: s.config.NodeID, + Address: s.config.BindAddr, + Port: s.config.BindPort, + Role: stats.Role, + Status: StatusActive, + Term: stats.Term, + }} + + for _, p := range s.peerConfigs() { + info := NodeInfo{ID: p.ID, Address: p.Address, Port: p.Port, Role: RoleFollower, Status: StatusInactive} + + switch { + case p.ID == stats.Leader: + info.Role = RoleLeader + info.Status = StatusActive + case stats.Role == RoleLeader && time.Since(contacts[p.ID]) <= window: + info.Status = StatusActive + } + + nodes = append(nodes, info) + } + + return nodes +} diff --git a/extensions/consensus/service_security_test.go b/extensions/consensus/service_security_test.go deleted file mode 100644 index f2cedfbce..000000000 --- a/extensions/consensus/service_security_test.go +++ /dev/null @@ -1,31 +0,0 @@ -package consensus - -import ( - "context" - "errors" - "testing" - - "github.com/xraph/forge" - "github.com/xraph/forge/extensions/consensus/internal" -) - -// TLS settings cannot be applied by a service that opens no transport, so -// Start must refuse them instead of running without them. -func TestServiceRefusesTLSItCannotApply(t *testing.T) { - cfg := internal.DefaultConfig() - cfg.NodeID = "n1" - cfg.Security.EnableTLS = true - cfg.Security.CertFile = "cert.pem" - cfg.Security.KeyFile = "key.pem" - - s, err := NewConsensusService(cfg, forge.NewNoopLogger(), nil) - if err != nil { - t.Fatal(err) - } - - if err := s.Start(context.Background()); !errors.Is(err, internal.ErrInvalidConfig) { - _ = s.Stop(context.Background()) - - t.Fatalf("Start with TLS enabled returned %v", err) - } -} From 0101a6fa0a7977f8b7b7fda44abaab128af5d1bc Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:46:39 -0600 Subject: [PATCH 12/17] fix(discovery): refuse to send the gateway token over plain http to remote hosts With a GatewayToken and an http:// GatewayURL, the extension only logged a warning and then sent the token in clear text on every register and deregister. It now refuses: Run fails at startup with ErrInsecureGatewayToken, and so does every gateway call, unless the gateway host is loopback (localhost, 127.0.0.0/8 or ::1) or the new FARPConfig.AllowInsecureGateway opt-in (WithFARPAllowInsecureGateway) is set. https gateways and gateways without a token are unaffected. --- extensions/discovery/config.go | 12 +++ extensions/discovery/extension.go | 11 +-- extensions/discovery/gateway_client.go | 43 +++++++++ extensions/discovery/gateway_insecure_test.go | 95 +++++++++++++++++++ 4 files changed, 153 insertions(+), 8 deletions(-) create mode 100644 extensions/discovery/gateway_insecure_test.go diff --git a/extensions/discovery/config.go b/extensions/discovery/config.go index f152ec4d6..8ead718c3 100644 --- a/extensions/discovery/config.go +++ b/extensions/discovery/config.go @@ -87,6 +87,12 @@ type FARPConfig struct { // authenticate pushes. Prefer an https GatewayURL when setting it. GatewayToken string `json:"gateway_token,omitempty" yaml:"gateway_token,omitempty"` + // AllowInsecureGateway lets GatewayToken be sent over a plain http + // GatewayURL to a host other than loopback. Without it the extension + // refuses to start, and every gateway call fails, rather than put the + // token on the network in clear text. + AllowInsecureGateway bool `json:"allow_insecure_gateway,omitempty" yaml:"allow_insecure_gateway,omitempty"` + // GatewayTLS configures the TLS client used for gateway requests, for a // private CA or mutual TLS. It only applies to https GatewayURLs. GatewayTLS GatewayTLSConfig `json:"gateway_tls" yaml:"gateway_tls"` @@ -509,6 +515,12 @@ func WithFARPGatewayToken(token string) ConfigOption { return func(c *Config) { c.FARP.GatewayToken = token } } +// WithFARPAllowInsecureGateway allows the gateway token to be sent over plain +// http to a non-loopback gateway. Only use it on a network you trust. +func WithFARPAllowInsecureGateway(allow bool) ConfigOption { + return func(c *Config) { c.FARP.AllowInsecureGateway = allow } +} + // WithFARPGatewayTLS sets the TLS client configuration for gateway requests. func WithFARPGatewayTLS(cfg GatewayTLSConfig) ConfigOption { return func(c *Config) { c.FARP.GatewayTLS = cfg } diff --git a/extensions/discovery/extension.go b/extensions/discovery/extension.go index 6d3625395..7fbb0f98e 100644 --- a/extensions/discovery/extension.go +++ b/extensions/discovery/extension.go @@ -523,18 +523,13 @@ func (e *Extension) Run(ctx context.Context) error { // request that the gateway will immediately make upon receiving the push. // Retries continuously with backoff until success or shutdown. if e.config.FARP.Enabled && e.config.FARP.GatewayURL != "" && instance != nil && node != nil { - // Build the gateway client up front so a broken TLS configuration - // fails the run instead of being retried forever in the background. + // Build the gateway client up front so a broken TLS configuration, or + // a token that would go over plain http to another host, fails the + // run instead of being retried forever in the background. if _, err := e.gatewayClient(); err != nil { return err } - if e.config.FARP.GatewayToken != "" && strings.HasPrefix(strings.ToLower(e.config.FARP.GatewayURL), "http://") { - e.Logger().Warn("FARP gateway token is sent over plain http; use an https gateway_url", - forge.F("gateway_url", e.config.FARP.GatewayURL), - ) - } - enriched := e.enrichInstanceFromManifest(instance, node) e.wg.Add(1) diff --git a/extensions/discovery/gateway_client.go b/extensions/discovery/gateway_client.go index 3259e30c8..c3bd42a48 100644 --- a/extensions/discovery/gateway_client.go +++ b/extensions/discovery/gateway_client.go @@ -4,8 +4,11 @@ import ( "crypto/tls" "crypto/x509" "fmt" + "net" "net/http" + "net/url" "os" + "strings" "time" "github.com/xraph/forge/errors" @@ -18,6 +21,10 @@ const gatewayRequestTimeout = 10 * time.Second // from config on first use. An invalid TLS configuration is returned as an // error rather than falling back to an unauthenticated client. func (e *Extension) gatewayClient() (*http.Client, error) { + if err := e.config.FARP.checkGatewayTransport(); err != nil { + return nil, err + } + e.gatewayClientMu.Lock() defer e.gatewayClientMu.Unlock() @@ -43,6 +50,42 @@ func (e *Extension) gatewayClient() (*http.Client, error) { return client, nil } +// ErrInsecureGatewayToken is returned when a gateway token would be sent in +// clear text to a host other than this machine. +var ErrInsecureGatewayToken = errors.New( + "farp gateway token would be sent over plain http to a non-loopback host; " + + "use an https gateway_url or set allow_insecure_gateway") + +// checkGatewayTransport refuses to send the bearer token over plain http to +// anything but loopback, where it would cross the network in clear text, +// unless AllowInsecureGateway is set. +func (c *FARPConfig) checkGatewayTransport() error { + if c.GatewayToken == "" || c.AllowInsecureGateway { + return nil + } + + u, err := url.Parse(c.GatewayURL) + if err != nil { + return fmt.Errorf("farp gateway url: %w", err) + } + + if !strings.EqualFold(u.Scheme, "http") || isLoopbackHost(u.Hostname()) { + return nil + } + + return fmt.Errorf("%w (gateway %s)", ErrInsecureGatewayToken, u.Host) +} + +func isLoopbackHost(host string) bool { + if strings.EqualFold(host, "localhost") { + return true + } + + ip := net.ParseIP(host) + + return ip != nil && ip.IsLoopback() +} + // authorizeGatewayRequest attaches the configured bearer token, if any. func (e *Extension) authorizeGatewayRequest(req *http.Request) { if e.config.FARP.GatewayToken != "" { diff --git a/extensions/discovery/gateway_insecure_test.go b/extensions/discovery/gateway_insecure_test.go new file mode 100644 index 000000000..1eaf01f7e --- /dev/null +++ b/extensions/discovery/gateway_insecure_test.go @@ -0,0 +1,95 @@ +package discovery + +import ( + "errors" + "io" + "net/http" + "strings" + "sync" + "testing" +) + +// recordingTransport answers every request itself, so tests can point the +// gateway URL at any host without touching the network. +type recordingTransport struct { + mu sync.Mutex + auths []string +} + +func (r *recordingTransport) RoundTrip(req *http.Request) (*http.Response, error) { + r.mu.Lock() + r.auths = append(r.auths, req.Header.Get("Authorization")) + r.mu.Unlock() + + return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader("")), Request: req}, nil +} + +func extensionWithRecorder(cfg FARPConfig) (*Extension, *recordingTransport) { + rt := &recordingTransport{} + e := &Extension{config: Config{FARP: cfg}} + e.gatewayHTTP = &http.Client{Transport: rt} + + return e, rt +} + +// The token is never put on the network in clear text unless the operator +// opts in. +func TestGatewayTokenRefusedOverPlainHTTPToRemoteHost(t *testing.T) { + inst := &ServiceInstance{ID: "svc-1", Name: "svc", Address: "10.0.0.7", Port: 8080} + + e, rt := extensionWithRecorder(FARPConfig{GatewayURL: "http://gateway.internal:7903", GatewayToken: "s3cret"}) + + if err := e.pushToGateway(t.Context(), inst); !errors.Is(err, ErrInsecureGatewayToken) { + t.Fatalf("push returned %v, want ErrInsecureGatewayToken", err) + } + + if err := e.deregisterFromGateway(t.Context(), inst.ID); !errors.Is(err, ErrInsecureGatewayToken) { + t.Fatalf("deregister returned %v, want ErrInsecureGatewayToken", err) + } + + if len(rt.auths) != 0 { + t.Fatalf("%d requests reached the gateway", len(rt.auths)) + } + + e, rt = extensionWithRecorder(FARPConfig{ + GatewayURL: "http://gateway.internal:7903", GatewayToken: "s3cret", AllowInsecureGateway: true, + }) + + if err := e.pushToGateway(t.Context(), inst); err != nil { + t.Fatalf("push with the opt-in failed: %v", err) + } + + if len(rt.auths) != 1 || rt.auths[0] != "Bearer s3cret" { + t.Fatalf("opt-in requests carried %v", rt.auths) + } +} + +func TestGatewayTransportCheck(t *testing.T) { + cases := []struct { + cfg FARPConfig + refused bool + }{ + {FARPConfig{GatewayURL: "http://gateway.internal:7903", GatewayToken: "t"}, true}, + {FARPConfig{GatewayURL: "http://10.1.2.3", GatewayToken: "t"}, true}, + {FARPConfig{GatewayURL: "http://gateway.internal:7903", GatewayToken: "t", AllowInsecureGateway: true}, false}, + {FARPConfig{GatewayURL: "https://gateway.internal", GatewayToken: "t"}, false}, + {FARPConfig{GatewayURL: "http://localhost:7903", GatewayToken: "t"}, false}, + {FARPConfig{GatewayURL: "http://127.0.0.1:7903", GatewayToken: "t"}, false}, + {FARPConfig{GatewayURL: "http://[::1]:7903", GatewayToken: "t"}, false}, + {FARPConfig{GatewayURL: "http://gateway.internal:7903"}, false}, + } + + for _, c := range cases { + err := c.cfg.checkGatewayTransport() + if refused := errors.Is(err, ErrInsecureGatewayToken); refused != c.refused { + t.Fatalf("%s (allow=%v): err=%v, want refused=%v", c.cfg.GatewayURL, c.cfg.AllowInsecureGateway, err, c.refused) + } + } + + cfg := DefaultConfig() + WithFARPAllowInsecureGateway(true)(&cfg) + + if !cfg.FARP.AllowInsecureGateway { + t.Fatal("WithFARPAllowInsecureGateway did not set the flag") + } +} From ce016021689bca7d69cecc31101db4fe4d00fed0 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:47:09 -0600 Subject: [PATCH 13/17] feat(farp): log schemas the gateway client skips The gateway client drops schemas it cannot fetch or whose content does not match the descriptor hash, and it had no way to say so. A rejected schema simply disappeared from the routes. The new WithLogger option takes a *slog.Logger and logs each skipped schema with its service, instance ID, schema type, claimed hash and the error. Without a logger the behaviour is unchanged. slog keeps the farp packages free of a dependency on the forge logger. --- farp/gateway/client.go | 21 +++++++++++++++++ farp/gateway/client_logger_test.go | 37 ++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 farp/gateway/client_logger_test.go diff --git a/farp/gateway/client.go b/farp/gateway/client.go index 8e9581bde..1ce608138 100644 --- a/farp/gateway/client.go +++ b/farp/gateway/client.go @@ -5,6 +5,7 @@ import ( "context" "errors" "fmt" + "log/slog" "sync" "github.com/xraph/farp" @@ -24,6 +25,7 @@ type Client struct { registry farp.SchemaRegistry manifestCache map[string]*farp.SchemaManifest // key: instanceID schemaCache *schemaLRU + logger *slog.Logger mu sync.RWMutex } @@ -38,6 +40,15 @@ func WithSchemaCacheSize(n int) ClientOption { } } +// WithLogger makes the client log schemas it skips because they could not be +// fetched or their content did not match the descriptor hash. Without it the +// client skips them silently. +func WithLogger(logger *slog.Logger) ClientOption { + return func(c *Client) { + c.logger = logger + } +} + // NewClient creates a new gateway client. func NewClient(registry farp.SchemaRegistry, opts ...ClientOption) *Client { c := &Client{ @@ -125,6 +136,16 @@ func (c *Client) ConvertToRoutes(manifests []*farp.SchemaManifest) []ServiceRout schema, err := c.resolveSchema(context.Background(), manifest.InstanceID, &schemaDesc) if err != nil { // Unfetchable or unverifiable schemas produce no routes. + if c.logger != nil { + c.logger.Warn("farp gateway: skipping schema", + slog.String("service", manifest.ServiceName), + slog.String("instance_id", manifest.InstanceID), + slog.String("schema_type", string(schemaDesc.Type)), + slog.String("hash", schemaDesc.Hash), + slog.Any("error", err), + ) + } + continue } diff --git a/farp/gateway/client_logger_test.go b/farp/gateway/client_logger_test.go new file mode 100644 index 000000000..c312b949a --- /dev/null +++ b/farp/gateway/client_logger_test.go @@ -0,0 +1,37 @@ +package gateway + +import ( + "bytes" + "log/slog" + "strings" + "testing" + + "github.com/xraph/farp" + + "github.com/xraph/forge/farp/registry/memory" +) + +// A schema skipped for a hash mismatch is logged when a logger is set. +func TestConvertToRoutesLogsSkippedSchemas(t *testing.T) { + var buf bytes.Buffer + + logger := slog.New(slog.NewTextHandler(&buf, nil)) + bad := inlineManifest(t, "billing", "bill-1", openAPI("/invoices"), strings.Repeat("0", 64)) + + c := NewClient(memory.NewRegistry(), WithLogger(logger)) + if routes := c.ConvertToRoutes([]*farp.SchemaManifest{bad}); len(routes) != 0 { + t.Fatalf("mismatched schema produced routes %+v", routes) + } + + out := buf.String() + for _, want := range []string{"skipping schema", "instance_id=bill-1", "service=billing", "does not match"} { + if !strings.Contains(out, want) { + t.Fatalf("log %q is missing %q", out, want) + } + } + + // Without a logger the schema is still skipped, silently. + if routes := NewClient(memory.NewRegistry()).ConvertToRoutes([]*farp.SchemaManifest{bad}); len(routes) != 0 { + t.Fatalf("mismatched schema produced routes %+v", routes) + } +} From 00c7a27ffbeeb7d8eee13a186cef598dc06f8b90 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:49:25 -0600 Subject: [PATCH 14/17] fix(discovery): reuse or revoke the etcd lease when its keep-alive breaks Every time the keep-alive stream ended, the backend granted a new lease and abandoned the old one, which then sat in etcd until its TTL ran out. A flapping connection piled up leases. Recovery now asks etcd how long the current lease has left. If the lease is still alive (the stream broke, the lease did not expire), the backend keeps it and restarts the keep-alive; the keys stay attached and nothing is rewritten. Otherwise it grants a new lease, writes every registration under it and revokes the old one. A lease whose registrations could not all be written is never reused as is; the next attempt replaces and revokes it, so at most one lease is outstanding. Grant, TimeToLive and Revoke go through the backend's etcdOps seam, and tests cover reuse, replacement and repeated failures. --- extensions/discovery/backends/etcd.go | 96 +++++++++++-- .../discovery/backends/etcd_lease_tls_test.go | 131 ++++++++++++++++++ 2 files changed, 217 insertions(+), 10 deletions(-) diff --git a/extensions/discovery/backends/etcd.go b/extensions/discovery/backends/etcd.go index b1e877275..375edbdde 100644 --- a/extensions/discovery/backends/etcd.go +++ b/extensions/discovery/backends/etcd.go @@ -44,6 +44,9 @@ type EtcdBackend struct { leaseMu sync.Mutex leaseID clientv3.LeaseID registered map[string]etcdRegistration // key: instance ID + // reregisterPending is set when writing the registrations under the + // current lease failed, so the lease must not be reused as is. + reregisterPending bool ops etcdOps } @@ -53,11 +56,17 @@ type etcdRegistration struct { value string } -// etcdOps is the subset of etcd writes the backend performs. It exists so -// lease and registration bookkeeping can be tested without an etcd server. +// etcdOps is the subset of etcd calls the backend makes for registrations +// and leases. It exists so lease and registration bookkeeping can be tested +// without an etcd server. type etcdOps interface { put(ctx context.Context, key, value string, lease clientv3.LeaseID) error delete(ctx context.Context, key string) error + grant(ctx context.Context, ttl int64) (clientv3.LeaseID, error) + // remainingTTL returns the lease's remaining TTL in seconds, or a value + // below 1 when the lease has expired or does not exist. + remainingTTL(ctx context.Context, lease clientv3.LeaseID) (int64, error) + revoke(ctx context.Context, lease clientv3.LeaseID) error } type clientOps struct{ client *clientv3.Client } @@ -74,6 +83,30 @@ func (c clientOps) delete(ctx context.Context, key string) error { return err } +func (c clientOps) grant(ctx context.Context, ttl int64) (clientv3.LeaseID, error) { + resp, err := c.client.Grant(ctx, ttl) + if err != nil { + return 0, err + } + + return resp.ID, nil +} + +func (c clientOps) remainingTTL(ctx context.Context, lease clientv3.LeaseID) (int64, error) { + resp, err := c.client.TimeToLive(ctx, lease) + if err != nil { + return 0, err + } + + return resp.TTL, nil +} + +func (c clientOps) revoke(ctx context.Context, lease clientv3.LeaseID) error { + _, err := c.client.Revoke(ctx, lease) + + return err +} + // NewEtcdBackend creates a new etcd backend. func NewEtcdBackend(config EtcdConfig) (*EtcdBackend, error) { // Create etcd client configuration @@ -549,23 +582,63 @@ func (b *EtcdBackend) keepAliveLease() { } } -// renewLease grants a new lease, re-registers every known instance under it, -// and starts a keep-alive stream for it. +// renewLease recovers the lease after its keep-alive stream ended and +// starts a new keep-alive stream for it. func (b *EtcdBackend) renewLease() (<-chan *clientv3.LeaseKeepAliveResponse, error) { - grantCtx, cancel := context.WithTimeout(b.ctx, etcdOpTimeout) - lease, err := b.client.Grant(grantCtx, b.leaseTTL) + lease, err := b.recoverLease(b.ctx) + if err != nil { + return nil, err + } + + return b.client.KeepAlive(b.ctx, lease) +} + +// recoverLease reuses the current lease when etcd still holds it (the stream +// broke but the lease did not expire), so the registered keys stay attached +// and nothing is written. Otherwise it grants a new lease, writes every +// registered instance under it and revokes the old one, so failed renewals +// never leave a trail of leases waiting out their TTL. +func (b *EtcdBackend) recoverLease(ctx context.Context) (clientv3.LeaseID, error) { + b.leaseMu.Lock() + old := b.leaseID + pending := b.reregisterPending + b.leaseMu.Unlock() + + if old != 0 && !pending { + ttlCtx, cancel := context.WithTimeout(ctx, etcdOpTimeout) + ttl, err := b.ops.remainingTTL(ttlCtx, old) + + cancel() + + if err == nil && ttl > 0 { + return old, nil + } + } + + grantCtx, cancel := context.WithTimeout(ctx, etcdOpTimeout) + lease, err := b.ops.grant(grantCtx, b.leaseTTL) cancel() if err != nil { - return nil, fmt.Errorf("grant etcd lease: %w", err) + return 0, fmt.Errorf("grant etcd lease: %w", err) } - if err := b.reregisterAll(b.ctx, lease.ID); err != nil { - return nil, err + reregErr := b.reregisterAll(ctx, lease) + + if old != 0 { + revokeCtx, cancel := context.WithTimeout(ctx, etcdOpTimeout) + // Best effort: an expired lease cannot be revoked and needs nothing. + _ = b.ops.revoke(revokeCtx, old) + + cancel() + } + + if reregErr != nil { + return 0, reregErr } - return b.client.KeepAlive(b.ctx, lease.ID) + return lease, nil } // reregisterAll switches to lease and writes every registered instance under @@ -576,6 +649,7 @@ func (b *EtcdBackend) reregisterAll(ctx context.Context, lease clientv3.LeaseID) defer b.leaseMu.Unlock() b.leaseID = lease + b.reregisterPending = false var errs []error @@ -590,6 +664,8 @@ func (b *EtcdBackend) reregisterAll(ctx context.Context, lease clientv3.LeaseID) } } + b.reregisterPending = len(errs) > 0 + return errors.Join(errs...) } diff --git a/extensions/discovery/backends/etcd_lease_tls_test.go b/extensions/discovery/backends/etcd_lease_tls_test.go index a78ba709f..a2506f391 100644 --- a/extensions/discovery/backends/etcd_lease_tls_test.go +++ b/extensions/discovery/backends/etcd_lease_tls_test.go @@ -140,6 +140,60 @@ type fakeEtcdOps struct { puts []recordedPut deletes []string failPut bool + + // Lease state: leases in alive are held by etcd. + alive map[clientv3.LeaseID]bool + nextLease clientv3.LeaseID + grants int + revoked []clientv3.LeaseID +} + +func (f *fakeEtcdOps) grant(context.Context, int64) (clientv3.LeaseID, error) { + f.mu.Lock() + defer f.mu.Unlock() + + if f.alive == nil { + f.alive = map[clientv3.LeaseID]bool{} + } + + if f.nextLease == 0 { + f.nextLease = 100 + } + + f.nextLease++ + f.grants++ + f.alive[f.nextLease] = true + + return f.nextLease, nil +} + +func (f *fakeEtcdOps) remainingTTL(_ context.Context, lease clientv3.LeaseID) (int64, error) { + f.mu.Lock() + defer f.mu.Unlock() + + if f.alive[lease] { + return 20, nil + } + + return -1, nil +} + +func (f *fakeEtcdOps) revoke(_ context.Context, lease clientv3.LeaseID) error { + f.mu.Lock() + defer f.mu.Unlock() + + f.revoked = append(f.revoked, lease) + delete(f.alive, lease) + + return nil +} + +// outstanding returns the leases etcd still holds. +func (f *fakeEtcdOps) outstanding() int { + f.mu.Lock() + defer f.mu.Unlock() + + return len(f.alive) } func (f *fakeEtcdOps) put(_ context.Context, key, _ string, lease clientv3.LeaseID) error { @@ -288,3 +342,80 @@ func TestEtcdLeaseAccessIsRaceFree(t *testing.T) { wg.Wait() } + +// A keep-alive stream that breaks while etcd still holds the lease reuses it: +// no new lease and no rewrites. +func TestEtcdLeaseRecoveryReusesLiveLease(t *testing.T) { + b, ops := newFakeEtcdBackend(t) + + first, _ := ops.grant(t.Context(), 30) + b.setLease(first) + + if err := b.Register(t.Context(), &ServiceInstance{ID: "a", Name: "svc"}); err != nil { + t.Fatal(err) + } + + ops.reset() + + lease, err := b.recoverLease(t.Context()) + if err != nil { + t.Fatal(err) + } + + if lease != first || ops.grants != 1 || len(ops.puts) != 0 || len(ops.revoked) != 0 { + t.Fatalf("lease=%d grants=%d puts=%d revoked=%v, want the live lease reused", + lease, ops.grants, len(ops.puts), ops.revoked) + } +} + +// An expired lease is replaced, registrations move to the new lease, and the +// old lease is revoked. Failed renewals never leave more than the current +// lease outstanding. +func TestEtcdLeaseRecoveryReplacesAndRevokes(t *testing.T) { + b, ops := newFakeEtcdBackend(t) + + first, _ := ops.grant(t.Context(), 30) + b.setLease(first) + + if err := b.Register(t.Context(), &ServiceInstance{ID: "a", Name: "svc"}); err != nil { + t.Fatal(err) + } + + // The lease expires. + ops.mu.Lock() + delete(ops.alive, first) + ops.mu.Unlock() + + // Writing under the new lease fails three times before etcd recovers. + ops.failPut = true + + for range 3 { + if _, err := b.recoverLease(t.Context()); err == nil { + t.Fatal("recovery reported success although re-registration failed") + } + + if n := ops.outstanding(); n > 1 { + t.Fatalf("%d leases outstanding after a failed renewal", n) + } + } + + ops.failPut = false + ops.reset() + + lease, err := b.recoverLease(t.Context()) + if err != nil { + t.Fatal(err) + } + + if b.currentLease() != lease || lease == first { + t.Fatalf("current lease %d, recovered %d, first %d", b.currentLease(), lease, first) + } + + if len(ops.puts) != 1 || ops.puts[0].lease != lease { + t.Fatalf("puts = %+v, want the registration under lease %d", ops.puts, lease) + } + + if n := ops.outstanding(); n != 1 { + t.Fatalf("%d leases outstanding, want only the current one", n) + } +} From 0188ce829d6250426645d364fe9f023eedbe5800 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:56:25 -0600 Subject: [PATCH 15/17] build(deps): add consensus storage dependencies to the hls module The hls module builds consensus from the local checkout through a replace directive. Now that the consensus service builds its own badger or bolt storage, hls needs those modules in its go.mod and go.sum, or it fails to build with a missing go.sum entry for badger. --- extensions/hls/go.mod | 5 +++++ extensions/hls/go.sum | 12 ++++++++++++ 2 files changed, 17 insertions(+) diff --git a/extensions/hls/go.mod b/extensions/hls/go.mod index 79135aa3e..d1f6797a6 100644 --- a/extensions/hls/go.mod +++ b/extensions/hls/go.mod @@ -21,7 +21,10 @@ require ( github.com/cenkalti/backoff/v5 v5.0.3 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect + github.com/dgraph-io/badger/v4 v4.8.0 // indirect + github.com/dgraph-io/ristretto/v2 v2.2.0 // indirect github.com/dunglas/httpsfv v1.1.0 // indirect + github.com/dustin/go-humanize v1.0.1 // indirect github.com/emicklei/go-restful/v3 v3.13.0 // indirect github.com/fatih/color v1.19.0 // indirect github.com/felixge/httpsnoop v1.1.0 // indirect @@ -52,6 +55,7 @@ require ( github.com/gobwas/pool v0.2.1 // indirect github.com/gobwas/ws v1.4.0 // indirect github.com/gofrs/uuid/v5 v5.5.1 // indirect + github.com/google/flatbuffers v25.2.10+incompatible // indirect github.com/google/gnostic-models v0.7.1 // indirect github.com/grafana/pyroscope-go v1.4.3 // indirect github.com/grafana/pyroscope-go/godeltaprof v0.1.11 // indirect @@ -90,6 +94,7 @@ require ( github.com/xraph/confy v1.1.0 // indirect github.com/xraph/go-utils v1.5.0 // indirect github.com/zeebo/blake3 v0.2.4 // indirect + go.etcd.io/bbolt v1.4.3 // indirect go.jetify.com/typeid/v2 v2.0.0-alpha.3 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0 // indirect diff --git a/extensions/hls/go.sum b/extensions/hls/go.sum index 5de309a51..373ed7f10 100644 --- a/extensions/hls/go.sum +++ b/extensions/hls/go.sum @@ -26,8 +26,16 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dgraph-io/badger/v4 v4.8.0 h1:JYph1ChBijCw8SLeybvPINizbDKWZ5n/GYbz2yhN/bs= +github.com/dgraph-io/badger/v4 v4.8.0/go.mod h1:U6on6e8k/RTbUWxqKR0MvugJuVmkxSNc79ap4917h4w= +github.com/dgraph-io/ristretto/v2 v2.2.0 h1:bkY3XzJcXoMuELV8F+vS8kzNgicwQFAaGINAEJdWGOM= +github.com/dgraph-io/ristretto/v2 v2.2.0/go.mod h1:RZrm63UmcBAaYWC1DotLYBmTvgkrs0+XhBd7Npn7/zI= +github.com/dgryski/go-farm v0.0.0-20240924180020-3414d57e47da h1:aIftn67I1fkbMa512G+w+Pxci9hJPB8oMnkcP3iZF38= +github.com/dgryski/go-farm v0.0.0-20240924180020-3414d57e47da/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= github.com/dunglas/httpsfv v1.1.0 h1:Jw76nAyKWKZKFrpMMcL76y35tOpYHqQPzHQiwDvpe54= github.com/dunglas/httpsfv v1.1.0/go.mod h1:zID2mqw9mFsnt7YC3vYQ9/cjq30q41W+1AnDwH8TiMg= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/emicklei/go-restful/v3 v3.13.0 h1:C4Bl2xDndpU6nJ4bc1jXd+uTmYPVUwkD6bFY/oTyCes= github.com/emicklei/go-restful/v3 v3.13.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= @@ -113,6 +121,8 @@ github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg= github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= +github.com/google/flatbuffers v25.2.10+incompatible h1:F3vclr7C3HpB1k9mxCGRMXq6FdUalZ6H/pNX4FP1v0Q= +github.com/google/flatbuffers v25.2.10+incompatible/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8= github.com/google/gnostic-models v0.7.1 h1:SisTfuFKJSKM5CPZkffwi6coztzzeYUhc3v4yxLWH8c= github.com/google/gnostic-models v0.7.1/go.mod h1:whL5G0m6dmc5cPxKc5bdKdEN3UjI7OUGxBlw57miDrQ= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= @@ -291,6 +301,8 @@ github.com/zeebo/pcg v1.0.1 h1:lyqfGeWiv4ahac6ttHs+I5hwtH/+1mrhlCtVNQM2kHo= github.com/zeebo/pcg v1.0.1/go.mod h1:09F0S9iiKrwn9rlI5yjLkmrug154/YRW6KnnXVDM/l4= github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs= github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s= +go.etcd.io/bbolt v1.4.3 h1:dEadXpI6G79deX5prL3QRNP6JB8UxVkqo4UPnHaNXJo= +go.etcd.io/bbolt v1.4.3/go.mod h1:tKQlpPaYCVFctUIgFKFnAlvbmB3tpy1vkTnDWohtc0E= go.jetify.com/typeid/v2 v2.0.0-alpha.3 h1:T6RPx6bNl10lp0JN2Xz/XcgLZWSlVmL58Xqy9cgTCcc= go.jetify.com/typeid/v2 v2.0.0-alpha.3/go.mod h1:zfD1ZDHDJNgXZANsO9jDOD81XRRQ0zAOnDBEHmIV/Gw= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= From f56246ebb69ab1683478e0d0c1d3454a4f6a373f Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Tue, 17 Nov 2026 18:19:51 -0600 Subject: [PATCH 16/17] feat(consensus): add grpc transport, membership changes, leadership transfer and encryption (#131) * feat(consensus): add a grpc transport for raft The grpc transport type used to be rejected by config validation, and GRPCTransport returned ErrGRPCNotImplemented from Start and Send. It is now a working transport with the same guarantees as TCP and HTTP. Each message is one unary call to forge.consensus.raft.v1.Transport/Send. The service is described by hand and a custom codec carries the existing JSON wire envelope as raw bytes, so there is no protoc step and the protocol version and payload checks are shared with the other transports. The receiver queues the message and answers with an empty reply; Raft responses still travel as separate messages matched by request ID. - MaxMessageSize is checked before sending and applied as the gRPC send and receive limits on both sides - inbound connections are capped with the same limit listener as HTTP, and concurrent calls per connection with MaxConcurrentStreams - keepalive pings on both sides with a server policy that accepts them, an idle timeout, a handshake timeout and a short reconnect backoff so a restarted peer is reachable again within a second - TLS and mTLS from the TLSManager config; with RequirePeerIdentity the dialed server must hold the peer's certificate and every message's From must match the client certificate in the gRPC peer's TLS AuthInfo - one client connection per peer, reused by every call - refusals come back as gRPC statuses that Send maps to ErrProtocolVersion and ErrMessageTooLarge - Stop drains for at most a second, then closes every connection, including ones still in the handshake, which grpc.Server.Stop would otherwise wait on for the whole connection timeout Service.Start builds the transport from transport.* and security.*, and config validation accepts grpc. ErrGRPCNotImplemented is removed; it was never released. Tests cover three node election and replication over gRPC in raft and through the service, with and without mTLS, a node with a mismatched certificate, sender spoofing, a server whose certificate names another node, oversized messages on either side, protocol version mismatch and malformed envelopes, the connection cap, connection reuse and Stop returning promptly with idle connections open. * docs(consensus): document the grpc transport The README and llm.txt listed the gRPC transport as not implemented and said config validation rejects it. Describe it as a supported transport type instead, with how it carries the wire envelope and which settings it honours. * feat(consensus): add raft membership changes and leadership transfer Membership (Raft dissertation section 4.1): - The cluster configuration is a list of members, each a voter or a learner, with an address. It changes one server at a time through configuration entries in the log. A configuration takes effect as soon as its entry is appended, on leader and followers alike. Truncating the entry returns to the previous configuration. - Node.AddNode adds the server as a learner, waits until it holds every committed entry, then promotes it to voter in a second entry. A learner receives the log but neither votes nor counts towards a majority, so an empty server cannot stall commits while it catches up. A server that does not catch up within twenty election timeouts is removed again and ErrLearnerNotCaughtUp is returned. - Node.RemoveNode removes a server. The leader may remove itself: it keeps replicating without counting itself, and steps down once the new configuration commits. - A second change is refused with ErrConfigChangeInProgress until the previous one has committed. - Commit counting, elections and quorum checks use the voters of the current configuration. Learners, removed servers and servers started with the new Config.Join flag never start elections. - The initial members come from AddPeer, or the new AddPeerAddress, which also records an address so servers added later can reach them. Disruption (section 4.2.3): - A vote request from a server that is not a voter in this node's configuration is ignored, as is any vote request that arrives within the minimum election timeout of hearing from a live leader. Neither changes the term. - Without this, a server removed while it was down campaigns when it comes back and deposes the working leader. Persistence: - Configuration entries live in the log. - The configuration in force at a snapshot's index is stored in the snapshot metadata and sent with InstallSnapshot. - On restart the configuration is rebuilt from the snapshot and the remaining entries. Leadership transfer (section 3.10): - Node.TransferLeadership stops accepting client writes and membership changes, brings the target's log up to date, and sends it TimeoutNow. The target then starts an election at once, marked as a transfer so voters grant it although they heard from the leader recently. - If the old leader has not been deposed within an election timeout, the transfer is abandoned and ErrLeadershipTransferFailed is returned. The old leader then resumes normal operation. - TimeoutNow and its response are carried by the wire envelope. The old configChangeCh path, which mutated the peer map outside the log and was never started, is removed along with its exported message types. Tests run on TCP clusters and cover: - growing from three to five servers and shrinking back while a client keeps writing - refusing a concurrent change and rolling back a learner that never caught up - removing the leader - a removed server campaigning without moving the leader's term - membership surviving restart, compaction and snapshot install - transfer to a chosen server, and abandoning a transfer to a stopped one - blocking writes during a transfer - reverting a truncated configuration * feat(consensus): change membership and transfer leadership through the service Service.AddNode, RemoveNode and TransferLeadership used to return ErrMembershipChangeUnsupported or "not implemented". They now call the raft node's AddNode, RemoveNode and TransferLeadership, so the admin routes for adding and removing nodes and transferring leadership work too. - A new join setting (Config.Join, WithJoin) starts a server that waits to be added instead of bootstrapping its own cluster. Its peers list then only tells it where the cluster is. - The configured peers, with their addresses, seed the bootstrap membership through AddPeerAddress. bind_addr and bind_port become this node's address in membership entries. - GetClusterManager returns a ClusterManager backed by the raft configuration instead of nil. AddNode and RemoveNode on it go through the log. UpdateNode is refused, because a member is changed by removing it and adding it again. - Cluster info and counts list the members of the current configuration, learners included, instead of the static peer list. - ErrMembershipChangeUnsupported is removed. A new service test bootstraps three servers from config. It adds a fourth, started with join, through the admin API and transfers leadership to it. It then removes another server through the ClusterManager and checks that writes still replicate. README and llm.txt describe the new behaviour. * feat(consensus): encrypt raft storage at rest security.enable_encryption is now a real feature instead of a rejected option. The service wraps its storage backend in storage.EncryptedStorage, which seals every value with AES-256-GCM before it reaches badger, boltdb or memory: log entries, term, vote, snapshot data and snapshot metadata. Each value carries a 5 byte header (format version and key ID) and a random 96-bit nonce. The GCM additional data is the header plus the storage key, so values cannot be edited, re-labelled or moved between keys. Storage keys stay in plaintext because they only hold indexes and range scans depend on them. Keys are 32 bytes, read from a file or an environment variable at start (inline keys only with allow_inline_encryption_key) and never logged. encryption_keys lists several keys with IDs for rotation; the active key writes and the others read, and Service.ReencryptStorage rewrites old values under the active key while the node runs. Start verifies a per key encrypted check value, so a wrong key fails at start with ErrWrongKey. Encryption over a plaintext store fails with ErrPlaintextStore and plaintext over an encrypted store fails with ErrEncryptedStore. encryption_migrate_plaintext encrypts an existing store in place once, storage.MigrateToPlaintext reverses it, and an interrupted migration blocks start until it is rerun. * fix(consensus): restart a service whose membership is already recorded On restart the raft node rebuilds its membership from the log or snapshot, which also adds a transport route for every member that has an address. The service then added a route for each configured peer and failed startup with "peer already exists". This happened for any cluster that had taken a snapshot or changed membership, encrypted or not. An existing route is no longer an error. The configured peers still seed membership only for a brand new cluster: AddPeerAddress is ignored once a configuration has been loaded, which the comments now say. A new service test runs a plain cluster on boltdb and on badger. It grows the cluster from three nodes to four, takes a snapshot, writes again and restarts every node. Data, the four voters and new writes all survive. The encrypted restart test passes again. * fix(consensus): fail proposals dropped by a leadership change at once Apply waited for its entry by index alone. When a leader lost its term right after appending and the new leader overwrote that index, the waiter was only released once some later entry was applied at the same index. The caller usually hit its deadline first. And if this node led again and proposed at the same index, the new waiter replaced the old one in the map, which then hung for good. Waiters are now keyed by index and term: - When a follower truncates its log on a conflict, it fails every waiter for the removed entries with the new ErrProposalDropped. The entry was never applied, so the caller can retry. - An entry discarded by an installed snapshot fails its waiter the same way. - Applying an entry completes only the waiter with the same term and fails any other waiter at that index. New tests force the truncation and check that Propose returns ErrProposalDropped promptly, and that a displaced waiter is neither completed by nor overwritten by a later entry at its index. replicateAndRead in the service tests now retries on ErrProposalDropped or not-leader errors, as a client would, and the comment on the encryption tests' retrying helper describes the new behaviour. * fix(consensus): honour BoltDB timeout, sync and read-only options BoltDBStorage.Start opened the database with a fixed one second lock timeout and dropped the rest of BoltDBStorageConfig. NoSync, NoGrowSync, ReadOnly and MmapFlags were silently ignored, and so was the service's storage.bolt_options. Start now passes all of them to bbolt. Timeout still defaults to one second and NoSync to false. The NoSync doc comment warns that it can lose acknowledged writes. A read-only database must already have its bucket and is not modified on open. Tests cover: - the sync flags reaching the database, with safe defaults - the lock timeout being honoured - read-only access refusing writes * test(consensus): retry leader operations in the service membership tests The restart and membership service tests picked a leader once and then called AddNode, TransferLeadership, RemoveNode or Apply on it. A leader elected a moment earlier can lose its term in between, and one run in ten failed with "node is not the leader". The tests now go through a small onLeader helper. It retries on not-leader, ErrProposalDropped and ErrConfigChangeInProgress, the errors a client would retry on, against whichever node leads next. The final cluster info check accepts whichever node leads at the end. * docs(consensus): describe the wired extension, membership, grpc and encryption The consensus pages still described the extension as unwired: Start that built nothing, Apply always not-leader, Read and Snapshot panicking, and the admin API, membership changes and leadership transfer missing. They now match the code on this branch. - QUICKSTART.md: the extension builds a real node. Followers apply entries and Propose can return ErrProposalDropped. The networked transports and disk storage are tested. Covers join, AddNode, TLS, encryption and the admin routes. - index.mdx: new overview, status table and table of extension calls. The container section explains that the Raft node, state machine and cluster manager must be taken from the service. - configuration.mdx: - transport.type defaults to tcp and accepts tcp, http and grpc. - New join key, bind_addr default 127.0.0.1, admin_api off by default, memory storage, bolt_options and the encryption keys. - Every key that is accepted but has no effect is marked. - features.mdx: new sections on membership changes, leadership transfer, encryption at rest and the gRPC transport. Storage, snapshots, middleware, the admin API (with API key auth) and errors are updated, including the raft, storage and transport sentinels. - functions.mdx: the extension and service methods as they behave now, ReencryptStorage, the storage encryption functions, the admin options and the new message types. - README.md and llm.txt: - There is no pre-vote round, and raft.pre_vote has no effect. - The FAQ answers about leader-only jobs and storage backends are updated. - Examples use a reachable bind address. - The container advice is corrected. Still stated as not implemented: linearizable reads, a pre-vote round and discovery other than static in the extension. --- .../extensions/consensus/configuration.mdx | 95 +- .../docs/extensions/consensus/features.mdx | 179 +++- .../docs/extensions/consensus/functions.mdx | 60 +- .../docs/extensions/consensus/index.mdx | 71 +- extensions/consensus/QUICKSTART.md | 42 +- extensions/consensus/README.md | 104 ++- extensions/consensus/exports.go | 1 + extensions/consensus/internal/config.go | 35 +- .../internal/config_security_test.go | 2 +- .../consensus/internal/encryption_config.go | 105 +++ .../internal/encryption_config_test.go | 79 ++ extensions/consensus/internal/types.go | 77 ++ extensions/consensus/llm.txt | 73 +- .../consensus/raft/cluster_transport_test.go | 7 + extensions/consensus/raft/config.go | 11 + extensions/consensus/raft/log.go | 52 +- extensions/consensus/raft/log_safety_test.go | 20 + extensions/consensus/raft/membership.go | 617 ++++++++++++ extensions/consensus/raft/membership_test.go | 670 +++++++++++++ extensions/consensus/raft/node.go | 184 ++-- extensions/consensus/raft/replication.go | 42 +- extensions/consensus/raft/request_id_test.go | 2 +- extensions/consensus/raft/state.go | 82 +- extensions/consensus/raft/waiters.go | 76 ++ extensions/consensus/raft/waiters_test.go | 91 ++ extensions/consensus/raft/workers.go | 186 +--- extensions/consensus/service.go | 57 +- extensions/consensus/service_cluster_test.go | 38 +- extensions/consensus/service_components.go | 102 +- extensions/consensus/service_encryption.go | 77 ++ .../consensus/service_encryption_test.go | 342 +++++++ extensions/consensus/service_grpc_test.go | 68 ++ extensions/consensus/service_membership.go | 86 ++ .../consensus/service_membership_test.go | 162 ++++ extensions/consensus/service_restart_test.go | 97 ++ extensions/consensus/storage/boltdb.go | 53 +- .../consensus/storage/boltdb_options_test.go | 99 ++ extensions/consensus/storage/encryption.go | 884 ++++++++++++++++++ .../consensus/storage/encryption_keys.go | 198 ++++ .../consensus/storage/encryption_raft_test.go | 205 ++++ .../consensus/storage/encryption_test.go | 700 ++++++++++++++ extensions/consensus/transport/envelope.go | 15 + extensions/consensus/transport/grpc.go | 699 ++++++++++++-- extensions/consensus/transport/grpc_test.go | 402 ++++++++ .../consensus/transport/transport_test.go | 21 +- 45 files changed, 6622 insertions(+), 646 deletions(-) create mode 100644 extensions/consensus/internal/encryption_config.go create mode 100644 extensions/consensus/internal/encryption_config_test.go create mode 100644 extensions/consensus/raft/membership.go create mode 100644 extensions/consensus/raft/membership_test.go create mode 100644 extensions/consensus/raft/waiters.go create mode 100644 extensions/consensus/raft/waiters_test.go create mode 100644 extensions/consensus/service_encryption.go create mode 100644 extensions/consensus/service_encryption_test.go create mode 100644 extensions/consensus/service_grpc_test.go create mode 100644 extensions/consensus/service_membership.go create mode 100644 extensions/consensus/service_membership_test.go create mode 100644 extensions/consensus/service_restart_test.go create mode 100644 extensions/consensus/storage/boltdb_options_test.go create mode 100644 extensions/consensus/storage/encryption.go create mode 100644 extensions/consensus/storage/encryption_keys.go create mode 100644 extensions/consensus/storage/encryption_raft_test.go create mode 100644 extensions/consensus/storage/encryption_test.go create mode 100644 extensions/consensus/transport/grpc_test.go diff --git a/docs/content/docs/extensions/consensus/configuration.mdx b/docs/content/docs/extensions/consensus/configuration.mdx index c0a03d846..d611202b1 100644 --- a/docs/content/docs/extensions/consensus/configuration.mdx +++ b/docs/content/docs/extensions/consensus/configuration.mdx @@ -12,7 +12,7 @@ The extension reads `extensions.consensus` from your config, falling back to `co `WithRequireConfig(true)` makes a missing section an error at startup. `WithConfig(cfg)` replaces the whole programmatic config, and `NewExtensionWithConfig(cfg)` is shorthand for it. -The extension validates and stores most of this config but doesn't act on it, because it never builds storage, a transport, discovery or a Raft node. The keys it does read are listed under [keys the extension acts on](#keys-the-extension-acts-on). +Some keys are validated and stored but have no effect yet. [Keys the extension acts on](#keys-the-extension-acts-on) lists the ones that do something, and the tables under [all keys](#all-keys) mark the rest. ## YAML example @@ -22,7 +22,7 @@ extensions: consensus: node_id: node-1 cluster_id: orders - bind_addr: 0.0.0.0 + bind_addr: 10.0.0.1 bind_port: 7000 peers: - {id: node-2, address: 10.0.0.2, port: 7000} @@ -33,21 +33,27 @@ extensions: election_timeout_max: 10s snapshot_interval: 30m transport: - type: grpc # grpc or tcp + type: tcp # tcp, http or grpc storage: - type: badger # badger, boltdb, pebble or postgres + type: badger # badger, boltdb or memory path: ./data/consensus discovery: - type: static # static, dns, consul, etcd or kubernetes + type: static # only static is wired into the extension + security: + enable_mtls: true + enable_tls: true + cert_file: /etc/consensus/node-1.pem + key_file: /etc/consensus/node-1-key.pem + ca_file: /etc/consensus/ca.pem + enable_encryption: true + encryption_key_file: /etc/consensus/raft.key health: check_interval: 10s admin_api: enabled: false - advanced: - enable_auto_snapshot: false ``` -Keep `advanced.enable_auto_snapshot: false`. With the default of `true`, the extension's snapshot loop panics on its nil state machine after `raft.snapshot_interval`. +`bind_addr` is both the address the node listens on and the address other members record for it, so use one the other servers can reach. A server joining an existing cluster also sets `join: true`; see [membership changes](/docs/extensions/consensus/features#membership-changes). ## Programmatic configuration @@ -55,12 +61,12 @@ Keep `advanced.enable_auto_snapshot: false`. With the default of `true`, the ext ext := consensus.NewExtension( consensus.WithNodeID("node-1"), consensus.WithClusterID("orders"), - consensus.WithBindAddress("0.0.0.0", 7000), + consensus.WithBindAddress("10.0.0.1", 7000), consensus.WithPeers([]consensus.PeerConfig{ {ID: "node-2", Address: "10.0.0.2", Port: 7000}, {ID: "node-3", Address: "10.0.0.3", Port: 7000}, }), - consensus.WithTransportType("grpc"), + consensus.WithTransportType("tcp"), consensus.WithStorageType("badger"), consensus.WithStoragePath("./data/consensus"), ) @@ -72,6 +78,7 @@ ext := consensus.NewExtension( | `WithClusterID(id string)` | `cluster_id` | | `WithBindAddress(addr string, port int)` | `bind_addr` and `bind_port` | | `WithPeers(peers []PeerConfig)` | `peers` | +| `WithJoin(join bool)` | `join` | | `WithTransportType(transportType string)` | `transport.type` | | `WithDiscoveryType(discoveryType string)` | `discovery.type` | | `WithStorageType(storageType string)` | `storage.type` | @@ -95,26 +102,39 @@ There are no options for the Raft timings, snapshots, health, observability, the | `raft.heartbeat_interval` > 0 | `1s` | | `raft.election_timeout_min` > `raft.heartbeat_interval` | `5s` | | `raft.election_timeout_max` > `raft.election_timeout_min` | `10s` | -| `transport.type` is `grpc` or `tcp` | `grpc` | +| `transport.type` is `tcp`, `http` or `grpc` | `tcp` | | `transport.max_message_size` > 0 | `4194304` (4MB) | | `discovery.type` is `static`, `dns`, `consul`, `etcd` or `kubernetes` | `static` | -| `storage.type` is `badger`, `boltdb`, `pebble` or `postgres` | `badger` | +| `storage.type` is `badger`, `boltdb`, `memory`, `pebble` or `postgres` | `badger` | | `storage.path` is set | `./data/consensus` | | `security.cert_file` and `key_file` are set when `enable_tls` is on | TLS off | | `enable_tls` is on and `ca_file` is set when `enable_mtls` is on | mTLS off | +| With `security.enable_encryption`, exactly one key source is set (`encryption_key_file`, `encryption_key_env`, or `encryption_keys` with unique IDs from 1), inline keys (`encryption_key`, or `value` in a list entry) only with `allow_inline_encryption_key`, and `encryption_active_key_id` is a listed ID | encryption off | +| `admin_api.api_key` is set when `admin_api.enable_auth` is on | auth off | + +Two more checks run when the service is created, after validation: `storage.type` must be `badger`, `boltdb` or `memory` (there's no implementation of `pebble` or `postgres`), and `discovery.type` must be `static`. ## Keys the extension acts on | Key | Default | What it does | |---|---|---| -| `node_id`, `cluster_id` | none, `default` | Show up in logs, stats and events | -| `health.enabled`, `health.check_interval` | `true`, `10s` | Run a loop that calls `HealthCheck` and logs a warning when it fails, which today is every time (`storage not initialized`) | -| `observability.metrics.enabled`, `collection_interval` | `true`, `15s` | Run a metrics loop. The service has no metrics sink, so it records nothing | -| `advanced.enable_auto_snapshot`, `raft.snapshot_interval` | `true`, `30m` | Run the snapshot loop, which panics. Turn it off | -| `admin_api.enabled` | `true` | Logs "admin API enabled but not yet implemented" and nothing else | +| `node_id`, `cluster_id` | none, `default` | Identify the node in the cluster, logs, stats and events | +| `bind_addr`, `bind_port` | `127.0.0.1`, `7000` | Where the transport listens, and the address recorded for this node in membership changes | +| `peers` | `[]` | The first members of a new cluster, and the routes to them. Once the log or a snapshot holds a membership, the log wins and changing `peers` does nothing | +| `join` | `false` | Start as a server waiting to be added with `AddNode`. It never starts an election on its own | +| `raft.heartbeat_interval`, `election_timeout_min`, `election_timeout_max` | `1s`, `5s`, `10s` | Raft timings | +| `raft.max_append_entries` | `64` | Most entries in one AppendEntries message | +| `raft.snapshot_interval`, `snapshot_threshold`, `advanced.enable_auto_snapshot` | `30m`, `10000`, `true` | With auto-snapshots on, the node checks every interval and snapshots when its log holds more than the threshold | +| `transport.*` | see below | `type`, `max_message_size`, `timeout`, `connection_timeout`, `idle_timeout`, `max_connections`, `keep_alive_interval` (TCP and gRPC) and `keep_alive_timeout` (gRPC) | +| `storage.type`, `storage.path` | `badger`, `./data/consensus` | The log storage backend and its directory | +| `storage.bolt_options.timeout`, `no_sync`, `no_grow_sync` | `1s`, `false`, `false` | Passed to BoltDB. Leave `no_sync` off: with it on a crash can lose writes the node already acknowledged | +| `security.*` | off | TLS and mTLS between nodes, and encryption at rest | +| `admin_api.*` | off | Registers the admin routes and protects them with an API key | +| `health.enabled`, `health.check_interval` | `true`, `10s` | Run a loop that calls `HealthCheck` and logs a warning when it fails | +| `observability.metrics.enabled`, `collection_interval` | `true`, `15s` | Run a metrics loop. The extension creates the service without a metrics sink, so it records nothing | | `events.enabled` | `true` | Adds `events` to the dependencies and tries to publish start, stop and reload events | -Everything else below is stored and validated where a rule exists, and otherwise ignored. +The tables below mark the keys that are stored and validated where a rule exists, but otherwise ignored. ## All keys @@ -124,9 +144,10 @@ Everything else below is stored and validated where a rule exists, and otherwise |---|---|---| | `node_id` | `string` | `""` | | `cluster_id` | `string` | `default` | -| `bind_addr` | `string` | `0.0.0.0` | +| `bind_addr` | `string` | `127.0.0.1` | | `bind_port` | `int` | `7000` | | `peers` | list of `{id, address, port}` | `[]` | +| `join` | `bool` | `false` | ### `raft` @@ -146,11 +167,13 @@ Everything else below is stored and validated where a rule exists, and otherwise | `check_quorum` | `bool` | `true` | | `disable_pipeline` | `bool` | `false` | +`log_cache_size`, `trailing_logs`, `replication_batch_size`, `leader_lease_timeout`, `pre_vote`, `check_quorum` and `disable_pipeline` have no effect. The log keeps every entry after the last snapshot in memory, so there's no cache to size, and there's no pre-vote round or leader lease. + ### `transport` | Key | Type | Default | |---|---|---| -| `type` | `string` | `grpc` | +| `type` | `string` | `tcp` | | `max_message_size` | `int` | `4194304` | | `timeout` | duration | `10s` | | `keep_alive` | `bool` | `true` | @@ -163,6 +186,8 @@ Everything else below is stored and validated where a rule exists, and otherwise | `compression_level` | `int` | `6` | | `enable_multiplexing` | `bool` | `true` | +`keep_alive`, `enable_compression`, `compression_level` and `enable_multiplexing` have no effect. TCP and gRPC connections always send keep-alive probes every `keep_alive_interval`, and messages are never compressed. + ### `discovery` | Key | Type | Default | @@ -176,6 +201,8 @@ Everything else below is stored and validated where a rule exists, and otherwise | `ttl` | duration | `60s` | | `enable_watch` | `bool` | `true` | +Only `type: static` is accepted by the service, and the other keys here have no effect. + ### `storage` | Key | Type | Default | @@ -196,6 +223,8 @@ Everything else below is stored and validated where a rule exists, and otherwise | `bolt_options.initial_mmap_size` | `int` | `0` | | `bolt_options.timeout` | duration | `1s` | +BadgerDB always writes synchronously, so `sync_writes` and the `badger_options` keys have no effect, and neither do `max_batch_size`, `max_batch_delay`, `compact_on_start` or `bolt_options.initial_mmap_size`. + ### `election` | Key | Type | Default | @@ -208,6 +237,8 @@ Everything else below is stored and validated where a rule exists, and otherwise | `step_down_on_remove` | `bool` | `true` | | `leader_stickiness` | duration | `10s` | +The `election` keys have no effect. Elections follow the `raft` timings, and a voter ignores vote requests while it has heard from a live leader within `raft.election_timeout_min`. + ### `health` | Key | Type | Default | @@ -218,6 +249,8 @@ Everything else below is stored and validated where a rule exists, and otherwise | `unhealthy_threshold` | `int` | `3` | | `healthy_threshold` | `int` | `2` | +Only `enabled` and `check_interval` are read. + ### `observability` | Key | Type | Default | @@ -233,6 +266,8 @@ Everything else below is stored and validated where a rule exists, and otherwise | `logging.enable_structured` | `bool` | `true` | | `logging.log_raft_details` | `bool` | `false` | +Only the `metrics` keys are read, and only by the metrics loop, which has no sink to record into. + ### `security` | Key | Type | Default | @@ -242,7 +277,17 @@ Everything else below is stored and validated where a rule exists, and otherwise | `cert_file`, `key_file`, `ca_file` | `string` | `""` | | `skip_verify` | `bool` | `false` | | `enable_encryption` | `bool` | `false` | +| `encryption_key_file` | `string` | `""` | +| `encryption_key_env` | `string` | `""` | +| `encryption_keys` | list of `{id, file, env, value}` | `[]` | +| `encryption_active_key_id` | `uint32` | `0` (the highest listed ID) | +| `allow_inline_encryption_key` | `bool` | `false` | | `encryption_key` | `string` | `""` | +| `encryption_migrate_plaintext` | `bool` | `false` | + +With `enable_mtls`, each node's certificate must name its node ID as a DNS subject alternative name, and messages whose sender doesn't match the certificate are refused. `skip_verify` can't be combined with mTLS. + +For encryption at rest, give the node a 32 byte key in a file (`encryption_key_file`) or an environment variable (`encryption_key_env`), as raw bytes (files only), 64 hex characters or base64. `encryption_key` holds the key inline in the config and is refused unless you set `allow_inline_encryption_key: true`, because keys written into config files end up in version control. List several keys under `encryption_keys` to rotate. `encryption_migrate_plaintext` lets a node with existing unencrypted data encrypt it in place on start. The [features page](/docs/extensions/consensus/features#encryption-at-rest) covers the format, rotation and migration. ### `resilience` @@ -257,11 +302,13 @@ Everything else below is stored and validated where a rule exists, and otherwise | `circuit_breaker_threshold` | `int` | `5` | | `circuit_breaker_timeout` | duration | `30s` | +The `resilience` keys have no effect. + ### `admin_api` | Key | Type | Default | |---|---|---| -| `enabled` | `bool` | `true` | +| `enabled` | `bool` | `false` | | `path_prefix` | `string` | `/consensus` | | `enable_auth` | `bool` | `false` | | `api_key` | `string` | `""` | @@ -275,6 +322,8 @@ Everything else below is stored and validated where a rule exists, and otherwise | `emit_node_events` | `bool` | `true` | | `emit_cluster_events` | `bool` | `true` | +The `emit_*` keys have no effect. The extension only publishes its start, stop and reload events. + ### `advanced` | Key | Type | Default | @@ -287,6 +336,8 @@ Everything else below is stored and validated where a rule exists, and otherwise | `enable_read_index` | `bool` | `true` | | `enable_leased_reads` | `bool` | `true` | +Only `enable_auto_snapshot` is read. Compaction happens as part of each snapshot, and there are no read-index or leased reads. + ## Hot reload -The extension implements `Reload(ctx)`. It reloads and validates the config, then copies the `observability`, `health` and `admin_api` sections into the running service. The loops that already started keep their old intervals. +The extension implements `Reload(ctx)`. It reloads and validates the config, then copies the `observability`, `health` and `admin_api` sections into the running service. The loops that already started keep their old intervals. The admin routes are registered once, when the extension registers, so changing `admin_api` takes a restart. diff --git a/docs/content/docs/extensions/consensus/features.mdx b/docs/content/docs/extensions/consensus/features.mdx index 131733bd9..87e32b83b 100644 --- a/docs/content/docs/extensions/consensus/features.mdx +++ b/docs/content/docs/extensions/consensus/features.mdx @@ -1,47 +1,81 @@ --- title: Features -description: The Raft packages you build a node from, and what the extension does and doesn't do yet +description: The Raft packages you build a node from, membership, leadership transfer, transports and encryption at rest --- import { Callout } from 'fumadocs-ui/components/callout'; ## Packages -You assemble a node from these packages yourself, the way the [quick start](/docs/extensions/consensus#quick-start) does. Most constructors take a config struct and a `forge.Logger`. +You can assemble a node from these packages yourself, the way the [quick start](/docs/extensions/consensus#quick-start) does, or let the extension build one from config. Most constructors take a config struct and a `forge.Logger`. | Package | What's in it | |---|---| -| `raft` | `raft.NewNode(config, logger, stateMachine, transport, storage)`, elections, pre-vote, replication, snapshots, `Propose`, `AddPeer` | -| `storage` | `NewMemoryStorage`, `NewBadgerStorage`, `NewBoltDBStorage`, and a write-ahead log (`NewWAL`) | -| `transport` | `NewLocalTransport` (in process), `NewGRPCTransport`, `NewTCPTransport`, `NewHTTPTransport`, TLS helpers and serializers | +| `raft` | `raft.NewNode(config, logger, stateMachine, transport, storage)`, elections, replication, snapshots, membership changes, leadership transfer | +| `storage` | `NewMemoryStorage`, `NewBadgerStorage`, `NewBoltDBStorage`, a write-ahead log (`NewWAL`), and `NewEncryptedStorage` with `LoadKeyring`, `MigrateToEncrypted` and `MigrateToPlaintext` for encryption at rest | +| `transport` | `NewLocalTransport` (in process), `NewTCPTransport`, `NewHTTPTransport`, `NewGRPCTransport`, TLS helpers and serializers | | `statemachine` | `NewMemoryStateMachine` and `NewPersistentStateMachine` | | `discovery` | `NewStaticDiscovery`, `NewDNSDiscovery`, `NewConsulDiscovery`, `NewEtcdDiscovery`, `NewKubernetesDiscovery` | | `cluster` | Membership, quorum and topology tracking with `cluster.NewManager` | | `middleware` | Checks for Forge handlers around leadership, quorum and read consistency | -| `admin`, `api` | HTTP handlers for cluster status and management. Nothing mounts them for you | +| `admin`, `api` | HTTP handlers for cluster status and management. The extension mounts the `admin` routes when `admin_api.enabled` is on | | `testing` | An in-process cluster harness and the cluster tests | -Only the in-process transport and memory storage have been run as a cluster in this repository. The networked transports, the BadgerDB and BoltDB backends and the discovery backends compile, but nothing here runs a cluster on them, and some of them don't fit the interfaces `raft.NewNode` takes yet. The sections below say which. +Three node clusters on the in-process, TCP, HTTP and gRPC transports, with memory, BoltDB and BadgerDB storage, are covered by the module's tests. The discovery backends aren't wired into the extension, and some of them don't fit the module's `Discovery` interface. The sections below say which. ## Raft nodes -`raft.NewNode` takes a `raft.Config`, a logger, and your state machine, transport and storage. `raft.DefaultConfig()` gives you the timings from the Raft paper: a 50ms heartbeat and a 150ms to 300ms election timeout, with pre-vote and quorum checks on. If you build a `raft.Config` literal instead, zero timings fall back to a 1s heartbeat and a 5s to 10s election timeout. +`raft.NewNode` takes a `raft.Config`, a logger, and your state machine, transport and storage. `raft.DefaultConfig()` gives you the timings from the Raft paper: a 50ms heartbeat and a 150ms to 300ms election timeout. If you build a `raft.Config` literal instead, zero timings fall back to a 1s heartbeat and a 5s to 10s election timeout. -How an election works: every node starts as a follower with a random election timeout between `ElectionTimeoutMin` and `ElectionTimeoutMax`. A follower that hears no heartbeat in that window becomes a candidate, runs a pre-vote if `PreVoteEnabled` is on, then asks its peers for votes. The node with a majority becomes leader and sends heartbeats every `HeartbeatInterval`. A new leader writes a no-op entry first, which is why the quick start's `set` lands at index 2. +How an election works: every node starts as a follower with a random election timeout between `ElectionTimeoutMin` and `ElectionTimeoutMax`. A voter that hears no heartbeat in that window becomes a candidate and asks the other voters for votes. The node with a majority becomes leader and sends heartbeats every `HeartbeatInterval`. A new leader writes a no-op entry first, which is why the quick start's `set` lands at index 2. + +There's no pre-vote round. `PreVoteEnabled` is carried on vote requests but nothing acts on it. What stops a server that was cut off from forcing an election when it comes back is simpler: a voter ignores vote requests, without even adopting their term, while it has heard from a live leader within the minimum election timeout, and it ignores vote requests from servers that aren't voters in its configuration. | Method on `*raft.Node` | What it does | |---|---| | `Start(ctx)`, `Stop(ctx)` | Run and stop the node | -| `AddPeer(peerID string)` | Registers a peer ID. Call it before `Start`, and connect the transport to that peer separately | +| `AddPeer(peerID string)`, `AddPeerAddress(peerID, address string, port int)` | Add a voter to the first membership of a new cluster. Call them before `Start`. `AddPeerAddress` also records the address, so servers added later can reach this member. Both are ignored once the log or a snapshot holds a membership | | `IsLeader()`, `GetLeader()`, `GetRole()`, `GetTerm()` | Leadership state | -| `Propose(ctx, command []byte)` | Appends a command on the leader and returns once a majority has it. On a follower it returns a not-leader error naming the leader | -| `Apply(ctx, entry LogEntry)` | Appends a prepared log entry on the leader and waits for it to commit | +| `Propose(ctx, command []byte)` | Appends a command on the leader and returns once it is committed and applied. On a follower it returns a not-leader error naming the leader. If a leadership change drops the entry before it commits, it returns `raft.ErrProposalDropped` and you can retry | +| `Apply(ctx, entry LogEntry)` | The same for a prepared log entry. Configuration entries are refused; use `AddNode` and `RemoveNode` | | `GetCommitIndex()`, `GetStats()` | Progress and a `RaftStats` snapshot | -| `AddNode(ctx, id, address, port)`, `RemoveNode(ctx, id)` | Membership changes, leader only. Not working yet: the goroutine that processes them is never started, so both block until your context ends | -| `StepDown(ctx)` | The leader steps down | -| `TransferLeadership(ctx, target)` | Steps down and lets the next election decide. It doesn't hand leadership to `target` yet | +| `Configuration()` | The current membership: each member's ID, address, port and whether it votes | +| `AddNode(ctx, id, address, port)`, `RemoveNode(ctx, id)` | Membership changes, on the leader. See [membership changes](#membership-changes) | +| `TransferLeadership(ctx, target)` | Hands leadership to `target`. See [leadership transfer](#leadership-transfer) | +| `StepDown(ctx)` | The leader returns to follower and an election picks the next one | +| `Snapshot()` | Snapshots the state machine and compacts the log | +| `Peers()`, `HasQuorum()` | What this node knows about the other members, and whether it's in touch with a majority | + +Followers apply committed entries to their own state machine too, usually a heartbeat after the leader. Reads from a follower can lag the leader, and there are no linearizable reads. + +The node persists every entry, its term and its vote before it answers, and reloads them on restart. A follower that couldn't write an entry rejects the request instead of acknowledging it. + +## Membership changes + +Membership changes one server at a time, through configuration entries in the log, as in section 4.1 of the Raft dissertation. A configuration takes effect on every node as soon as its entry is appended, and only one change can be in flight: a second one returns `raft.ErrConfigChangeInProgress` until the first has committed. + +To add a server: + +1. Start it with `Join: true` in its `raft.Config` (or `join: true` in the extension's config). A joining server never starts an election on its own. Give its transport routes to the existing members, which the extension does from its `peers`. +2. Call `AddNode(ctx, id, address, port)` on the leader. + +`AddNode` first adds the server as a learner: it receives the log but doesn't vote or count towards a majority, so an empty server can't stall commits while it catches up. Once the learner holds every committed entry, a second entry promotes it to voter. If it hasn't caught up within your context or twenty election timeouts, it's removed again and `AddNode` returns `raft.ErrLearnerNotCaughtUp`. + +`RemoveNode(ctx, id)` removes a server. You can remove the leader itself: it keeps replicating without counting itself, then steps down once the new membership commits, and the remaining servers elect a leader. A removed server that never learned it was removed (because it was down at the time) can't disrupt the cluster when it comes back, because the members ignore vote requests from servers that aren't voters. + +Membership survives restarts and compaction: configuration entries live in the log, and the membership at a snapshot's index is stored with the snapshot and sent with `InstallSnapshot`. Once it's recorded, `AddPeer` and the extension's `peers` no longer change anything. + +On the extension, `Service.AddNode`, `RemoveNode` and `GetClusterManager()` (whose `AddNode` and `RemoveNode` go through the same log entries) do the same thing, as do the admin routes `POST /nodes/add` and `POST /nodes/remove`. + +## Leadership transfer -Followers advance their commit index but don't apply committed entries to their state machine, so a read from a follower's state machine stays empty. Read from the leader. +`TransferLeadership(ctx, target)` hands leadership to a chosen voter, following section 3.10 of the Raft dissertation: + +1. The leader stops accepting writes and membership changes. They return `raft.ErrLeadershipTransferInProgress`. +2. It brings `target`'s log up to date. +3. It sends `target` a TimeoutNow message, and `target` starts an election at once. Voters grant that election even though they heard from the leader recently. + +If `target` hasn't taken over within an election timeout (it's down, say), the transfer is abandoned with `raft.ErrLeadershipTransferFailed` and the old leader carries on as before. `Service.TransferLeadership` and `POST /leadership/transfer` do the same. ## The memory state machine @@ -53,7 +87,7 @@ Followers advance their commit index but don't apply committed entries to their | `delete` | `key` | Removes `key` | | `increment` | `key` | Adds 1, starting from 1 when the key is missing | -`Query` takes a `map[string]any` with a `type`: `get` (with a `key`), `list` (the whole map) or `size`. +`Query` takes a `map[string]any` with a `type`: `get` (with a `key`), `list` (the whole map) or `size`. The extension always uses this state machine, and its `Service.Apply` sends your `Command` as JSON. `statemachine.NewPersistentStateMachine` stores state in a `consensus.Storage`, but it has `Get`, `CreateSnapshot` and `RestoreSnapshot` where the interface wants `Query`, `Snapshot` and `Restore`, so it doesn't implement `consensus.StateMachine` and `raft.NewNode` won't take it. @@ -146,28 +180,62 @@ func (s *KVStore) Restore(snapshot *consensus.Snapshot) error { The extension has no way to take your state machine. Use it with your own `raft.Node`. +An error from `Apply` doesn't stop the node: the entry is committed on every server, so the node records it as applied and returns your error to the caller waiting on that entry. + ## Snapshots -`raft.Config` has `SnapshotInterval`, `SnapshotThreshold` and `EnableSnapshots` (on in `raft.DefaultConfig()`, off in a `raft.Config` literal). With snapshots on, the node checks every `SnapshotInterval` and asks the state machine for a `Snapshot` when the log holds more than `SnapshotThreshold` entries. A node can receive an `InstallSnapshot` request, but no leader code sends one yet, so a follower that falls far behind isn't caught up from a snapshot. +`raft.Config` has `SnapshotInterval`, `SnapshotThreshold` and `EnableSnapshots` (on in `raft.DefaultConfig()`, off in a `raft.Config` literal). With snapshots on, the node checks every `SnapshotInterval` and snapshots when its log holds more than `SnapshotThreshold` entries. You can also call `Snapshot()` on the node, or `Snapshot(ctx)` on the extension's service. A snapshot is taken at the last applied entry, stored with the membership at that point, and the log before it is dropped. - -The extension's `Service.Snapshot` and its auto-snapshot loop call a state machine that is never created, so both panic. The loop is on by default and fires every `raft.snapshot_interval` (30 minutes), which takes your process down. Set `advanced.enable_auto_snapshot: false` in your config file if you register the extension. - +A follower whose next entry is already in the leader's snapshot gets the snapshot through `InstallSnapshot`, in chunks of at most `SnapshotChunkSize` bytes (1 MiB by default; the extension uses half of `transport.max_message_size`). It restores its state machine from it and keeps any later entries that agree with it. ## Storage -`raft.NewNode` takes a `consensus.Storage`: `Start`, `Stop`, `Set`, `Get`, `Delete`, `Batch`, `GetRange` and `Close`. +`raft.NewNode` takes a `consensus.Storage`: `Start`, `Stop`, `Set`, `Get`, `Delete`, `Batch`, `GetRange` and `Close`. The memory, BadgerDB and BoltDB backends all implement it. | Backend | Constructor | |---|---| | In memory | `storage.NewMemoryStorage(storage.MemoryStorageConfig{}, logger)` | -| BadgerDB | `storage.NewBadgerStorage(storage.BadgerStorageConfig{...}, logger)` | -| BoltDB | `storage.NewBoltDBStorage(storage.BoltDBStorageConfig{...}, logger)` | +| BadgerDB | `storage.NewBadgerStorage(storage.BadgerStorageConfig{Path: dir}, logger)` | +| BoltDB | `storage.NewBoltDBStorage(storage.BoltDBStorageConfig{Path: file}, logger)` | | Write-ahead log | `storage.NewWAL(nodeID, storage.WALConfig{...}, logger)` | -Only `MemoryStorage` implements `consensus.Storage` today. `BadgerStorage` and `BoltDBStorage` have `WriteBatch` where the interface wants `Batch`, and no `Close`, so `raft.NewNode` won't accept them until you wrap them in a small adapter. +BadgerDB always writes synchronously. `BoltDBStorageConfig` takes `Timeout` (how long to wait for the file lock, 1s by default), `NoSync`, `NoGrowSync`, `ReadOnly` and `MmapFlags`. Leave `NoSync` off: with it on, a crash can lose writes the node already acknowledged. + +The extension's config validator also accepts `pebble` and `postgres` for `storage.type`, but there's no implementation of either, so the service refuses them when it's created. + +## Encryption at rest + +Turn on `security.enable_encryption` and give the node a key, and everything it writes through its storage backend is encrypted before it reaches disk: the Raft log, the current term and vote, snapshots and the snapshot metadata. It works the same on `badger`, `boltdb` and `memory`. + +```yaml +extensions: + consensus: + security: + enable_encryption: true + encryption_key_file: /etc/consensus/raft.key # or encryption_key_env: RAFT_KEY +``` + +You can make a key with `openssl rand -hex 32 > raft.key && chmod 600 raft.key`. A key is 32 bytes (AES-256), and a file can hold the 32 raw bytes, 64 hex characters or base64 text. An environment variable holds hex or base64. The key is read when the service starts, and a key of the wrong size, a missing file or an unset variable stops `Start` with `storage.ErrInvalidEncryptionKey`. Errors name the source but never the key, and logs only show key IDs. Inline keys (`encryption_key`, or `value` in a list entry) are refused unless you set `allow_inline_encryption_key: true`. -The extension's config validator also accepts `pebble` and `postgres` for `storage.type`, but there's no implementation of either in this module. +Each node encrypts its own disk, so each node can have its own key. Traffic between nodes isn't covered; use `enable_tls` or `enable_mtls` for that. + +Every stored value becomes a version byte, a 4 byte key ID, a 12 byte random nonce, the ciphertext and a 16 byte tag, so 33 bytes more than the plaintext. The version, key ID and storage key are authenticated too, so a value copied to another key or edited fails with `storage.ErrDecrypt` instead of being read. Storage keys themselves stay readable: someone with the disk can see names like `log_42` and `snapshot_meta`, and roughly how big each value is, but not the content. The write-ahead log in `storage.NewWAL` isn't encrypted; the extension doesn't use it. + +To rotate, list the keys with IDs. The highest ID (or `encryption_active_key_id`) encrypts new writes, and every listed key can still read: + +```yaml +security: + enable_encryption: true + encryption_keys: + - {id: 1, file: /etc/consensus/raft-1.key} + - {id: 2, env: RAFT_KEY_2} +``` + +A single `encryption_key_file` or `encryption_key_env` counts as key ID 1. Restart the node with the new list, then call `Service.ReencryptStorage()` to rewrite everything still under the old key. It's safe while the node is serving. After that you can drop the old key. Never reuse an ID for a different key. + +The store keeps a small check value per key ID, so a wrong key fails at `Start` with `storage.ErrWrongKey`. Turning encryption on over a store that already holds plaintext fails with `storage.ErrPlaintextStore`, and starting without encryption over an encrypted store fails with `storage.ErrEncryptedStore`. To encrypt a node that already has data, start it once with `security.encryption_migrate_plaintext: true`. To go back, stop the node and run `storage.MigrateToPlaintext` on its started backend with the same keyring. An interrupted migration makes the next start fail with `storage.ErrMigrationIncomplete` until you run it again. Mind you, old plaintext can stay in BoltDB free pages or Badger value log files after a migration, until they're reused or compacted. + +When you build a node yourself, wrap the backend: load the keys with `storage.LoadKeyring`, then pass the backend and keyring to `storage.NewEncryptedStorage` and give the result to `raft.NewNode`. ## Transports @@ -176,11 +244,17 @@ All four transports implement `consensus.Transport`: `Start`, `Stop`, `Send`, `R | Transport | Constructor | |---|---| | In process | `transport.NewLocalTransport`, connected to its peers with `Connect` | -| gRPC | `transport.NewGRPCTransport` | -| TCP | `transport.NewTCPTransport` | -| HTTP | `transport.NewHTTPTransport` | +| TCP | `transport.NewTCPTransport`. Length-prefixed frames on a connection per peer | +| HTTP | `transport.NewHTTPTransport`. One POST to `/raft/message` per message | +| gRPC | `transport.NewGRPCTransport`. One unary call per message | + +The three network transports carry the same versioned JSON envelope. A message from a peer on another protocol version is refused with `transport.ErrProtocolVersion`, and one larger than `MaxMessageSize` (4 MiB by default) with `transport.ErrMessageTooLarge`. They listen on `127.0.0.1` unless you give them an address, cap inbound connections with `MaxConnections`, and close connections that sit idle too long. + +The gRPC transport sends each message to `forge.consensus.raft.v1.Transport/Send` with a raw bytes codec, so there's no protoc step or generated code. It keeps one connection per peer, uses `MaxMessageSize` as the gRPC send and receive limit, and pings idle connections every `KeepAliveTime`. Refusals come back as gRPC statuses, which `Send` turns into the errors above or a permission error. -`transport.NewTLSManager` loads certificates, and `NewJSONSerializer`, `NewGobSerializer`, `NewProtobufSerializer` and `NewCompressedSerializer` encode messages. The extension's `transport.type` only accepts `grpc` and `tcp`. +For TLS, build a config with `transport.NewTLSManager(...).GetTLSConfig()` and pass it as `TLSConfig`. With `RequirePeerIdentity` on, the transport needs mutual TLS, refuses any message whose sender isn't named in its client certificate, and checks that each peer it dials presents that peer's certificate. Each node's certificate must carry its node ID as a DNS subject alternative name. The extension sets this up from `security.enable_tls` and `enable_mtls`. + +`NewJSONSerializer`, `NewGobSerializer`, `NewProtobufSerializer` and `NewCompressedSerializer` are there too, but the transports don't use them. ## Discovery @@ -194,11 +268,11 @@ All four transports implement `consensus.Transport`: `Start`, `Stop`, `Send`, `R | etcd | `discovery.NewEtcdDiscovery` | | Kubernetes | `discovery.NewKubernetesDiscovery` | -## Leadership checker +The extension only uses `static`: its first members come from `peers`, and any other `discovery.type` stops the service when it's created. -The extension registers a `*consensus.LeadershipChecker` over its service. `RequireLeader()` returns a not-leader error naming the leader, and `RequireQuorum()` returns `ErrNoQuorum` when the cluster has no quorum. `IsLeader()` and `GetLeader()` pass through to the service. +## Leadership checker -Because the extension's node is never leader and has no cluster manager, `RequireLeader()` and `RequireQuorum()` always fail today. You can also build one yourself with `consensus.NewLeadershipChecker(service)`, but `*consensus.Service` is the only `ConsensusService` in the module. +The extension registers a `*consensus.LeadershipChecker` over its service. `RequireLeader()` returns a not-leader error naming the leader, or `nil` on the leader, and `RequireQuorum()` returns `ErrNoQuorum` when this node isn't in touch with a majority. `IsLeader()` and `GetLeader()` pass through to the service. You can also build one yourself with `consensus.NewLeadershipChecker(service)`. ## Middleware @@ -213,32 +287,33 @@ The `middleware` package has two kinds of helpers. | `RedirectMiddleware` | `NewRedirectMiddleware(raftNode, manager, logger)` | `Handle()`, `HandleWithAutoRedirect()`, `HandleWithForward()` | | `ConsistencyMiddleware` | `NewConsistencyMiddleware(raftNode, config, logger)` | `Handle()` | -The first three wrap a `func(forge.Context) error`. The leadership and quorum checks answer 503 with a JSON body when they fail, and `AddConsensusHeaders` sets `X-Consensus-Node-ID`, `X-Consensus-Term`, `X-Consensus-Role`, `X-Consensus-Leader` and related headers. They take a `ConsensusService`, and the only one in the module is the extension's, which is never leader and has no quorum, so `RequireLeader` and `RequireQuorum` reject every request today. +The first three wrap a `func(forge.Context) error` and take a `ConsensusService`, such as the extension's. The leadership and quorum checks answer 503 with a JSON body when they fail, and `AddConsensusHeaders` sets `X-Consensus-Node-Id`, `X-Consensus-Term`, `X-Consensus-Role`, `X-Consensus-Leader` and related headers. -The other three take a `RaftNode`, so your own `*raft.Node` works with them. Their methods return a check function with no `next` parameter, and when a check fails they write the JSON error and return what `ctx.JSON` returns, which is `nil` once the response is written. Your code can't tell a rejection from a pass by the return value, so treat these as unfinished. +The other three take a `RaftNode`. Their methods return a check function with no `next` parameter, and when a check fails they write the JSON error and return what `ctx.JSON` returns, which is `nil` once the response is written. Your code can't tell a rejection from a pass by the return value, so treat these as unfinished. ## Admin API - -The extension doesn't mount an admin API. `admin_api.enabled` is on by default, and all it does is log "admin API enabled but not yet implemented". - - -The `admin` package has the handlers. `admin.NewAPI(service, healthChecker, metricsCollector, logger)` builds them and `RegisterRoutes(router, prefix)` mounts these under `prefix`: +The `admin` package has handlers for status and management. The extension mounts them on your app's router under `admin_api.path_prefix` (`/consensus`) when `admin_api.enabled` is on, which it isn't by default: | Route | Handler | |---|---| -| `GET /health`, `GET /health/detailed` | Health from the service, or from the health checker when you pass one | -| `GET /status`, `GET /metrics`, `GET /leader`, `GET /nodes` | Stats, the metrics collector's metrics, leadership and membership | +| `GET /health`, `GET /health/detailed` | Health from the service | +| `GET /status`, `GET /leader`, `GET /nodes` | Stats, leadership and membership | +| `GET /metrics` | 404, because the extension mounts the routes without a metrics collector | | `POST /leadership/transfer`, `POST /leadership/stepdown` | Call `TransferLeadership` and `StepDown` | | `POST /snapshot` | Calls `Snapshot` | | `POST /nodes/add`, `POST /nodes/remove` | Call `AddNode` and `RemoveNode` | | `POST /apply`, `POST /read` | Call `Apply` and `Read` | -The handlers call a `ConsensusService`, and with the extension's service they report the stub state above: `/snapshot` and `/read` hit the nil state machine. The `api` package has more handler sets (`NewClusterAPI`, `NewConfigAPI`, `NewNodeAPI` and a stats API) built from `cluster` managers and a `RaftNode`. Nothing registers them either. + +These routes can change membership and write to the replicated log. Whenever anyone else can reach your app's router, set `admin_api.enable_auth: true` and an `api_key`. Every route then needs `Authorization: Bearer ` or `X-Api-Key: `, and anything else gets a 401. The key is compared in constant time, and `enable_auth` without an `api_key` fails validation. + + +If you mount the handlers yourself, use `admin.NewAPI(service, healthChecker, metricsCollector, logger, admin.WithAPIKey(key))` or `admin.NewAPIFromConfig(...)` with the extension's `AdminAPIConfig`, then `RegisterRoutes(router, prefix)`. The `api` package has more handler sets (`NewClusterAPI`, `NewConfigAPI`, `NewNodeAPI` and a stats API) built from `cluster` managers and a `RaftNode`. Nothing registers them. ## Statistics -`Service.GetStats()` returns a `ConsensusStats` with `NodeID`, `ClusterID`, `Role`, `Status`, `Term`, `LeaderID`, `CommitIndex`, `LastApplied`, `LastLogIndex`, `LastLogTerm`, `ClusterSize`, `HealthyNodes`, `HasQuorum`, `ElectionsTotal`, `ElectionsFailed`, `OperationsTotal`, `OperationsFailed`, `OperationsPerSec`, `AverageLatencyMs`, `ErrorRate`, `LogEntries`, `SnapshotsTotal`, `LastSnapshotTime`, `Uptime` and `StartTime`. On the extension's service most of these stay at zero. +`Service.GetStats()` returns a `ConsensusStats` with `NodeID`, `ClusterID`, `Role`, `Status`, `Term`, `LeaderID`, `CommitIndex`, `LastApplied`, `LastLogIndex`, `LastLogTerm`, `ClusterSize`, `HealthyNodes`, `HasQuorum`, `ElectionsTotal`, `ElectionsFailed`, `OperationsTotal`, `OperationsFailed`, `OperationsPerSec`, `AverageLatencyMs`, `ErrorRate`, `LogEntries`, `SnapshotsTotal`, `LastSnapshotTime`, `Uptime` and `StartTime`. The Raft fields and the cluster counts come from the running node. `ElectionsTotal`, `ElectionsFailed`, `AverageLatencyMs` and `LogEntries` aren't filled in. The extension also implements `Metrics()` with a map of the same numbers. The service is created without a metrics sink, so the metrics collection loop it runs every `observability.metrics.collection_interval` records nothing. @@ -261,6 +336,22 @@ The root package re-exports these sentinels. Each is a `*errors.ForgeError` with | `ErrInvalidPeer`, `ErrPeerExists`, `ErrPeerNotFound`, `ErrInsufficientPeers` | Peer problems | | `ErrInvalidConfig` | Config validation failed | +The `raft`, `storage` and `transport` packages have their own sentinels, created with `errors.New`. Check them with `errors.Is` too. + +| Error | Meaning | +|---|---| +| `raft.ErrProposalDropped` | A leadership change removed the entry before it committed. It wasn't applied, so you can retry | +| `raft.ErrConfigChangeInProgress` | Another membership change hasn't committed yet | +| `raft.ErrLearnerNotCaughtUp` | `AddNode` gave up because the new server didn't catch up, and removed it again | +| `raft.ErrLeadershipTransferInProgress` | The leader is handing over leadership and refuses writes and membership changes | +| `raft.ErrLeadershipTransferFailed` | The transfer target didn't take over within an election timeout. The old leader keeps leading | +| `storage.ErrInvalidEncryptionKey` | A key is missing, unreadable or not 32 bytes | +| `storage.ErrWrongKey`, `storage.ErrUnknownKeyID`, `storage.ErrDecrypt` | The configured keys don't match the store, a value uses a key that isn't configured, or a value failed authentication | +| `storage.ErrPlaintextStore`, `storage.ErrEncryptedStore` | Encryption is on over plaintext data, or off over encrypted data | +| `storage.ErrMigrationIncomplete` | An encryption migration was interrupted. Run it again | +| `consensus.ErrStorageNotEncrypted` | `ReencryptStorage` was called without encryption | +| `transport.ErrProtocolVersion`, `transport.ErrMessageTooLarge` | A peer speaks another wire protocol version, or a message is over the size limit | + | Helper | What it does | |---|---| | `IsNotLeaderError(err)`, `IsNoLeaderError(err)`, `IsNoQuorumError(err)`, `IsStaleTermError(err)` | `errors.Is` against the matching sentinel | diff --git a/docs/content/docs/extensions/consensus/functions.mdx b/docs/content/docs/extensions/consensus/functions.mdx index ccec6b136..40748e798 100644 --- a/docs/content/docs/extensions/consensus/functions.mdx +++ b/docs/content/docs/extensions/consensus/functions.mdx @@ -21,36 +21,39 @@ The option helpers are on the [configuration page](/docs/extensions/consensus/co | Method | Returns | |---|---| | `Service() *Service` | The consensus service | -| `IsLeader() bool` | Always `false` today | -| `GetLeader() string` | Always `""` today | -| `GetRole() NodeRole` | Always `RoleFollower` today | -| `GetStats() ConsensusStats` | Mostly zero today | -| `GetClusterInfo() ClusterInfo` | Empty today | -| `Apply(ctx, cmd Command) error` | Always a not-leader error today | -| `Read(ctx, query any) (any, error)` | Panics today, because the state machine is nil | +| `IsLeader() bool`, `GetLeader() string`, `GetRole() NodeRole` | Leadership state of this node | +| `GetStats() ConsensusStats` | Live numbers from the Raft node | +| `GetClusterInfo() ClusterInfo` | The members of the current configuration and the leader | +| `Apply(ctx, cmd Command) error` | Writes through the leader. A not-leader error elsewhere | +| `Read(ctx, query any) (any, error)` | Queries this node's state machine | | `Metrics() map[string]any` | The stats as a flat map | | `Reload(ctx) error` | Reloads config, see [hot reload](/docs/extensions/consensus/configuration#hot-reload) | -| `Health(ctx) error` | `storage not initialized` today | +| `Health(ctx) error` | The service's `HealthCheck` | ## Service -`*consensus.Service` is the extension's `ConsensusService`. `NewConsensusService(config Config, logger forge.Logger, metrics forge.Metrics) (*Service, error)` builds one on its own, with the same stubbed components. +`*consensus.Service` is the extension's `ConsensusService`. `NewConsensusService(config Config, logger forge.Logger, metrics forge.Metrics) (*Service, error)` builds one on its own. It returns an error wrapping `ErrInvalidConfig` for settings it can't honour: storage `pebble` or `postgres`, or a discovery type other than `static`. -| Method | What it does today | +| Method | What it does | |---|---| -| `Start(ctx) error` | Logs each component it would initialise, starts the health, metrics and snapshot loops. A second call returns `ErrAlreadyStarted` | -| `Stop(ctx) error` | Stops the loops | -| `IsLeader() bool`, `GetLeader() string`, `GetRole() NodeRole`, `GetTerm() uint64` | `false`, `""`, `RoleFollower`, `0` | -| `Apply(ctx, cmd Command) error` | Not-leader error | -| `Read(ctx, query any) (any, error)` | Panics on the nil state machine | -| `Snapshot(ctx) error` | Panics on the nil state machine | -| `AddNode(ctx, nodeID, address string, port int) error`, `RemoveNode(ctx, nodeID string) error` | Not-leader error | -| `TransferLeadership(ctx, targetNodeID string) error`, `StepDown(ctx) error` | Not-leader error. Not implemented past that check | -| `GetStats() ConsensusStats`, `GetClusterInfo() ClusterInfo` | Stats and membership, mostly zero | -| `HealthCheck(ctx) error` | `storage not initialized` once started, `ErrNotStarted` before | -| `GetHealthStatus(ctx) HealthStatus` | Per-check details, unhealthy today | +| `Start(ctx) error` | Builds and starts storage, the transport, the state machine and the Raft node, then the health and metrics loops. A second call returns `ErrAlreadyStarted` | +| `Stop(ctx) error` | Stops the loops, the Raft node, the transport and storage | +| `IsLeader() bool`, `GetLeader() string`, `GetRole() NodeRole`, `GetTerm() uint64` | The Raft node's current state | +| `Apply(ctx, cmd Command) error` | On the leader, sends `cmd` as JSON through the log and returns once it is committed and applied. A not-leader error elsewhere, `raft.ErrProposalDropped` if a leadership change dropped it | +| `Read(ctx, query any) (any, error)` | Queries this node's state machine. Not linearizable | +| `Snapshot(ctx) error` | Snapshots the state machine and compacts the log | +| `AddNode(ctx, nodeID, address string, port int) error` | On the leader, adds a server started with `join`, as a learner and then a voter | +| `RemoveNode(ctx, nodeID string) error` | On the leader, removes a server, the leader included | +| `TransferLeadership(ctx, targetNodeID string) error` | On the leader, hands leadership to a voter, or fails with `raft.ErrLeadershipTransferFailed` | +| `StepDown(ctx) error` | The leader returns to follower | +| `ReencryptStorage() (int, error)` | Rewrites stored values that aren't under the active encryption key and returns how many. `ErrStorageNotEncrypted` without encryption | +| `GetStats() ConsensusStats`, `GetClusterInfo() ClusterInfo` | Stats and membership | +| `HealthCheck(ctx) error` | `nil` while the node has quorum, `no quorum` otherwise, `ErrNotStarted` before `Start` | +| `GetHealthStatus(ctx) HealthStatus` | Per-check details | | `UpdateConfig(ctx, config Config) error` | Validates, then copies the `observability`, `health` and `admin_api` sections | -| `GetRaftNode()`, `GetStateMachine()`, `GetClusterManager()`, `GetTransport()`, `GetDiscovery()`, `GetStorage()` | `nil` | +| `GetRaftNode()`, `GetStateMachine()`, `GetTransport()`, `GetStorage()` | The running components, `nil` before `Start` | +| `GetClusterManager()` | A `ClusterManager` backed by the Raft configuration. `UpdateNode` on it returns an error | +| `GetDiscovery()` | `nil`. The service doesn't run a discovery backend | ## LeadershipChecker @@ -81,6 +84,7 @@ The option helpers are on the [configuration page](/docs/extensions/consensus/co | `LogEntry` | `Index`, `Term`, `Type EntryType`, `Data []byte`, `Created` | | `Snapshot` | `Index`, `Term`, `Data []byte`, `Size`, `Created`, `Checksum` | | `PeerConfig` | `ID`, `Address`, `Port` | +| What `raft.Node.Configuration()` returns | `Members`, each with `ID`, `Address`, `Port` and `Voter`. The type lives in the module's `internal` package and isn't re-exported, so you can use the value but not name its type | | `ClusterInfo` | `ID`, `Leader`, `Term`, `Nodes []NodeInfo`, `TotalNodes`, `ActiveNodes`, `HasQuorum`, `CommitIndex`, `LastApplied` | | `NodeInfo` | `ID`, `Address`, `Port`, `Role`, `Status`, `Term`, `LastHeartbeat`, `Metadata` | | `HealthStatus` | `Healthy`, `Status`, `Leader`, `HasQuorum`, `TotalNodes`, `ActiveNodes`, `Details []HealthCheck`, `LastCheck`, `Checks` | @@ -95,7 +99,7 @@ The option helpers are on the [configuration page](/docs/extensions/consensus/co | `NodeRole` | `RoleFollower`, `RoleCandidate`, `RoleLeader` (`"follower"`, `"candidate"`, `"leader"`) | | `NodeStatus` | `StatusActive`, `StatusInactive`, `StatusSuspected`, `StatusFailed` | | `EntryType` | `EntryNormal`, `EntryConfig`, `EntryBarrier`, `EntryNoop` | -| `MessageType` | `MessageTypeAppendEntries`, `MessageTypeRequestVote`, `MessageTypeInstallSnapshot`, `MessageTypeHeartbeat` | +| `MessageType` | `MessageTypeAppendEntries`, `MessageTypeRequestVote`, `MessageTypeInstallSnapshot`, `MessageTypeTimeoutNow`, their `...Response` counterparts, and `MessageTypeHeartbeat` | | `NodeChangeType` | `NodeChangeTypeAdded`, `NodeChangeTypeRemoved`, `NodeChangeTypeUpdated` | | `BatchOpType` | `BatchOpSet`, `BatchOpDelete` | | Container names | `ServiceKey` (`consensus`), `ServiceKeyLegacy` (`consensus:service`), `ClusterManagerKey`, `RaftNodeKey`, `StateMachineKey`, `LeadershipCheckerKey` | @@ -104,7 +108,7 @@ The event types (`ConsensusEventNodeStarted` and 32 more, each a `consensus.*` s ## Errors -The sentinels and helpers are listed on the [features page](/docs/extensions/consensus/features#errors). +The sentinels and helpers are listed on the [features page](/docs/extensions/consensus/features#errors), including the `raft`, `storage` and `transport` ones: `raft.ErrProposalDropped`, `raft.ErrConfigChangeInProgress`, `raft.ErrLeadershipTransferInProgress`, `raft.ErrLeadershipTransferFailed`, `raft.ErrLearnerNotCaughtUp`, the `storage` encryption errors, `transport.ErrProtocolVersion` and `transport.ErrMessageTooLarge`. | Function | Description | |---|---| @@ -120,14 +124,16 @@ The sentinels and helpers are listed on the [features page](/docs/extensions/con | Package | Constructors | |---|---| -| `raft` | `NewNode(config, logger, stateMachine, transport, storage) (*Node, error)`, `DefaultConfig()` | +| `raft` | `NewNode(config, logger, stateMachine, transport, storage) (*Node, error)`, `DefaultConfig()`. `*Node` has `AddPeer`, `AddPeerAddress`, `AddNode`, `RemoveNode`, `TransferLeadership`, `StepDown`, `Configuration`, `Snapshot`, `Peers`, `HasQuorum` and the `RaftNode` methods | | `storage` | `NewMemoryStorage`, `NewBadgerStorage`, `NewBoltDBStorage`, `NewWAL` | -| `transport` | `NewLocalTransport`, `NewGRPCTransport`, `NewTCPTransport`, `NewHTTPTransport`, `NewTLSManager`, `NewConnectionPool`, the serializers | +| `storage` (encryption) | `LoadKeyring(KeyringConfig, logger) (*Keyring, error)`, `NewKeyring(activeID, keys)`, `NewEncryptedStorage(inner, EncryptedStorageConfig, logger)` with `Rekey()` and `Keyring()`, `NewPlaintextGuard(inner)`, `MigrateToEncrypted(inner, keyring)`, `MigrateToPlaintext(inner, keyring)` | +| `transport` | `NewLocalTransport`, `NewTCPTransport`, `NewHTTPTransport`, `NewGRPCTransport`, `NewTLSManager`, `MTLSConfig`, `DefaultTLSConfig`, `NewConnectionPool`, the serializers | | `statemachine` | `NewMemoryStateMachine`, `NewPersistentStateMachine`, `NewApplyManager` | | `discovery` | `NewStaticDiscovery`, `NewDNSDiscovery`, `NewConsulDiscovery`, `NewEtcdDiscovery`, `NewKubernetesDiscovery`, `NewRegistry` | | `cluster` | `NewManager`, `NewMembershipManager`, `NewQuorumManager`, `NewTopologyManager`, `NewRebalanceManager` | | `middleware` | `NewLeadershipMiddleware`, `NewQuorumMiddleware`, `NewMetricsMiddleware`, `NewReadOnlyMiddleware`, `NewRedirectMiddleware`, `NewConsistencyMiddleware` | -| `admin` | `NewAPI(service, healthChecker, metricsCollector, logger)` with `RegisterRoutes(router, prefix)` | +| `admin` | `NewAPI(service, healthChecker, metricsCollector, logger, opts ...Option)` with `WithAPIKey(key)`, `NewAPIFromConfig(service, healthChecker, metricsCollector, logger, AdminAPIConfig)`, and `RegisterRoutes(router, prefix)` | +| `security` | `APIKeyMiddleware(key) forge.Middleware`, plus `NewAuthManager` and `NewTLSManager` | | `api` | `NewClusterAPI`, `NewConfigAPI`, `NewNodeAPI`, `NewStatsAPI` | | `observability` | `NewHealthChecker`, `NewMetricsCollector`, `NewLogManager`, `NewAlertManager` | diff --git a/docs/content/docs/extensions/consensus/index.mdx b/docs/content/docs/extensions/consensus/index.mdx index 538a2e8f5..29b5f097c 100644 --- a/docs/content/docs/extensions/consensus/index.mdx +++ b/docs/content/docs/extensions/consensus/index.mdx @@ -1,6 +1,6 @@ --- title: Consensus -description: Raft consensus building blocks for Go, plus a Forge extension that doesn't wire them together yet +description: Raft consensus building blocks for Go, plus a Forge extension that runs a node from config --- import { Cards, Card } from 'fumadocs-ui/components/card'; @@ -8,23 +8,26 @@ import { Callout } from 'fumadocs-ui/components/callout'; ## Overview -`github.com/xraph/forge/extensions/consensus` holds a Raft implementation in Go with leader election, pre-vote, log replication and snapshots, plus the pieces a node is built from: log storage on BadgerDB, BoltDB or memory, gRPC, TCP, HTTP and in-process transports, peer discovery through static lists, DNS, Consul, etcd or Kubernetes, and in-memory and persistent state machines. +`github.com/xraph/forge/extensions/consensus` holds a Raft implementation in Go with leader election, log replication, snapshots, membership changes and leadership transfer, plus the pieces a node is built from: log storage on BadgerDB, BoltDB or memory (optionally encrypted at rest), TCP, HTTP, gRPC and in-process transports, peer discovery through static lists, DNS, Consul, etcd or Kubernetes, and in-memory and persistent state machines. -A Forge extension sits on top of those packages, but it doesn't use them yet. Read the status below before you pick it for a distributed system. +A Forge extension sits on top. It builds storage, a transport, a state machine and a Raft node from your config, so each app you start with it is one node of the cluster. You can also assemble nodes from the packages yourself, as the quick start does. -The extension's `Start` only logs each component it would initialise. Storage, transport, discovery, the cluster manager, the state machine and the Raft node are never created, so nothing listens on the bind port and the node stays a follower forever. `Apply` always returns a not-leader error, `Read` and `Snapshot` panic on the nil state machine, and the auto-snapshot loop (on by default) panics the same way after `raft.snapshot_interval`, which takes your process down. The admin API, `TransferLeadership` and `StepDown` aren't implemented. If you need Raft today, build nodes from the packages yourself, as the quick start does. +The module hasn't run a production cluster yet. Reads come from the local state machine and aren't linearizable, the extension only takes its first members from the static `peers` list (DNS, Consul, etcd and Kubernetes discovery aren't wired into it), and there's no pre-vote round. Read the status below before you pick it for a distributed system. ## Status | Piece | State | |---|---| -| Leader election and log replication in `raft` | Works on the in-process transport. Three nodes elect a leader, and a proposed entry commits on a majority | -| Applying entries on followers | Followers advance their commit index but don't apply committed entries to their state machine, so reads from a follower stay empty. Read from the leader | -| `consensus.NewExtension` | Validates config and registers services, but builds none of the components. See [the Forge extension](#the-forge-extension) | -| Network transports, BadgerDB and BoltDB storage, discovery backends | The code is there and compiles, but nothing in the repository runs a networked cluster on them yet. The BadgerDB and BoltDB stores and the Consul, etcd and Kubernetes discovery don't implement the module's own interfaces, so `raft.NewNode` won't take the stores without an adapter | -| Cluster tests | `testing/` runs in-process clusters. `TestLogReplication` is skipped under `-short`, which is how CI runs it | +| Leader election, log replication and applying entries in `raft` | Three node clusters elect a leader and replicate commands to every state machine over the in-process, TCP, HTTP and gRPC transports | +| Durability | The log, term and vote are reloaded from storage on restart. A node only acknowledges entries and votes it has persisted | +| Snapshots | Nodes compact their log into snapshots, and a follower that falls behind the snapshot catches up through `InstallSnapshot`, sent in chunks | +| `consensus.NewExtension` | Builds storage, transport, state machine and Raft node from config and replicates over TCP, HTTP or gRPC, with TLS and mTLS. See [the Forge extension](#the-forge-extension) | +| Membership and leadership transfer | Servers are added (as a learner first, then promoted) and removed one at a time through the log, the leader included. `TransferLeadership` hands over to a chosen voter and gives up after an election timeout. Membership survives restarts and snapshots | +| Encryption at rest | With `security.enable_encryption`, every value a node stores is sealed with AES-256-GCM. See [encryption at rest](/docs/extensions/consensus/features#encryption-at-rest) | +| Not implemented | Linearizable reads, a pre-vote round, and dynamic discovery in the extension | +| Cluster tests | `testing/` runs in-process clusters, and the `raft` and root packages run TCP, HTTP and gRPC clusters. `TestLogReplication` is skipped under `-short`, which is how CI runs it | ## Quick start @@ -156,7 +159,9 @@ node-2 commit index: 2 node-3 commit index: 2 ``` -The leader varies from run to run. Entry 1 is the no-op every new leader writes, and entry 2 is your `set`. Calling `Propose` on a follower returns a not-leader error that names the current leader, which you can check with `consensus.IsNotLeaderError`. +The leader varies from run to run. Entry 1 is the no-op every new leader writes, and entry 2 is your `set`. Calling `Propose` on a follower returns a not-leader error that names the current leader, which you can check with `consensus.IsNotLeaderError`. If the leader loses its term before your entry commits, you get `raft.ErrProposalDropped` instead, and you can retry on the new leader. + +To run the same thing across machines, swap the in-process transport for `transport.NewTCPTransport`, `NewHTTPTransport` or `NewGRPCTransport`, use `storage.NewBadgerStorage` or `NewBoltDBStorage` for an on-disk log, and register the other members with `AddPeerAddress(id, address, port)`. Or let the extension do that wiring for you. ## The Forge extension @@ -167,7 +172,7 @@ app := forge.NewApp(forge.AppConfig{ consensus.NewExtension( consensus.WithNodeID("node-1"), consensus.WithClusterID("orders"), - consensus.WithBindAddress("0.0.0.0", 7000), + consensus.WithBindAddress("10.0.0.1", 7000), consensus.WithPeers([]consensus.PeerConfig{ {ID: "node-2", Address: "10.0.0.2", Port: 7000}, {ID: "node-3", Address: "10.0.0.3", Port: 7000}, @@ -177,26 +182,34 @@ app := forge.NewApp(forge.AppConfig{ }) ``` -That compiles and starts. If you add it anyway, turn the auto-snapshot loop off in your config file so it can't crash the process: +Start that app on every server, each with its own `node_id`, and they elect a leader between them. `Start` builds: -```yaml -extensions: - consensus: - advanced: - enable_auto_snapshot: false -``` +- storage under `storage.path`: `badger` by default, or `boltdb` or `memory`, encrypted when `security.enable_encryption` is on +- the transport on `bind_addr:bind_port`: `tcp` by default, or `http` or `grpc`, with TLS when `security.enable_tls` is on, and client certificates checked against node IDs when `enable_mtls` is on +- a memory state machine +- a Raft node whose first members are the `peers` list + +`bind_addr` defaults to `127.0.0.1`, so set it to an address the other servers can reach. It's also the address other members record for this node. + +Settings it can't honour stop the service when it's created, with an error that wraps `ErrInvalidConfig`: storage `pebble` or `postgres`, and any discovery type other than `static`. -Here's what each call does on a started extension today: +Here's what each call does on a started extension: | Call | Result | |---|---| -| `Apply` | Always a not-leader error (`IsNotLeaderError` is true) | -| `Read`, `Snapshot` | Panic, because the state machine is nil | -| `HealthCheck` and the extension's `Health` | `storage not initialized`. The health loop logs that warning every `health.check_interval` | -| `IsLeader`, `GetLeader`, `GetRole` | `false`, `""`, `follower` | -| `AddNode`, `RemoveNode`, `TransferLeadership`, `StepDown` | A not-leader error, because the node is never leader. `TransferLeadership` and `StepDown` aren't implemented past that check | -| `GetRaftNode`, `GetStateMachine`, `GetStorage`, `GetTransport`, `GetDiscovery`, `GetClusterManager` | `nil` | -| `GetStats`, `GetClusterInfo` | Zero counts and `HasQuorum: false` | +| `Apply` | On the leader, appends the command and returns once it is committed and applied. Elsewhere a not-leader error naming the leader. `raft.ErrProposalDropped` when a leadership change dropped the entry, and `raft.ErrLeadershipTransferInProgress` while leadership is being handed over | +| `Read` | Queries this node's state machine. On a follower it can lag the leader | +| `Snapshot` | Snapshots the state machine and compacts the log | +| `IsLeader`, `GetLeader`, `GetRole`, `GetTerm` | The Raft node's current state | +| `AddNode` | On the leader, adds a running server that was started with `join: true`. It joins as a learner and becomes a voter once it has caught up. Only one change runs at a time (`raft.ErrConfigChangeInProgress`) | +| `RemoveNode` | On the leader, removes a server. Removing the leader is allowed: it steps down once the change commits | +| `TransferLeadership` | On the leader, hands leadership to a voter. Writes are refused while it runs, and it fails with `raft.ErrLeadershipTransferFailed` if the target hasn't taken over within an election timeout | +| `StepDown` | The leader returns to follower and an election picks the next one | +| `HealthCheck` and the extension's `Health` | `nil` while the node has storage, a transport and quorum. `no quorum` otherwise | +| `GetStats`, `GetClusterInfo` | Live numbers from the Raft node, and the members of the current configuration | +| `ReencryptStorage` | Rewrites stored values under the active encryption key after a key rotation | + +The admin routes are off by default. With `admin_api.enabled` they're registered on your app's router under `admin_api.path_prefix`, and since they can write to the replicated log, set `admin_api.enable_auth` and `api_key` whenever anyone else can reach that router. ## What it registers @@ -208,7 +221,7 @@ Here's what each call does on a started extension today: | State machine | `consensus:statemachine` | `StateMachine` | | Leadership checker | `consensus:leadership` | `*LeadershipChecker` | -The cluster manager, Raft node and state machine entries hold `nil` interfaces, so resolving them returns an error. +The Raft node and state machine are created by `Start`. The cluster manager is backed by the Raft configuration: its `GetNodes` lists the current members, learners included, and its `AddNode` and `RemoveNode` go through the log like the service's. All four entries resolve through `*Service`, so they hit the problem below; take them from the service with `GetRaftNode()`, `GetStateMachine()` and `GetClusterManager()`. The first time anything resolves `*consensus.Service` from the container after the app has started, including through `*LeadershipChecker`, it fails with `consensus service already started`. The container tries to start the service again and `Start` isn't idempotent. Take the service from the extension instead. @@ -221,7 +234,7 @@ if err != nil { } svc := ext.(*consensus.Extension).Service() -fmt.Println(svc.GetRole()) // follower +fmt.Println(svc.GetRole(), svc.GetLeader()) ``` ## Dependencies @@ -232,7 +245,7 @@ With `events.enabled` on (the default), the extension adds `events` to its depen -The packages you build a node from, custom state machines, middleware, and what isn't implemented. +The packages you build a node from, membership changes, leadership transfer, encryption at rest, the transports, and what isn't implemented. Every config key, its default, the validation rules, and which keys the extension reads. diff --git a/extensions/consensus/QUICKSTART.md b/extensions/consensus/QUICKSTART.md index 6552a4251..c95b10f5c 100644 --- a/extensions/consensus/QUICKSTART.md +++ b/extensions/consensus/QUICKSTART.md @@ -2,7 +2,7 @@ This page gets you from nothing to a running Raft cluster with this module, and tells you plainly where the module stops today. Read the [status table in the README](README.md#status) alongside it. -The short version: the `raft` package elects a leader and replicates a log across nodes that you assemble yourself, on the in-process transport. The Forge extension (`consensus.NewExtension`) loads and validates config, but it never builds the storage, transport, state machine or Raft node, so it can't run a cluster yet. There's no networked cluster, admin API or Prometheus endpoint to deploy, which is why this page has no Docker or Kubernetes section. +The short version: you can assemble nodes yourself from the `raft`, `storage` and `transport` packages, or let the Forge extension (`consensus.NewExtension`) build one node per app from config. Either way you get leader election, a replicated log, snapshots, membership changes and leadership transfer, over the in-process, TCP, HTTP or gRPC transport. The module hasn't run a production cluster yet, and there's no Prometheus endpoint or deployment recipe, which is why this page has no Docker or Kubernetes section. ## Install @@ -15,7 +15,7 @@ go get github.com/xraph/forge/extensions/consensus@latest ## Run a three-node cluster in one process -Each node is a `raft.Node` built from a transport, log storage and a state machine. The in-process transport (`transport.NewLocalTransport`) is the one the module's own cluster tests use, and the one that works end to end. Save this as `main.go`: +Each node is a `raft.Node` built from a transport, log storage and a state machine. This example uses the in-process transport (`transport.NewLocalTransport`) so it runs in one process with nothing to configure. Save this as `main.go`: ```go package main @@ -135,10 +135,10 @@ node-3 commit index: 2 Entry 1 is the no-op every new leader writes, and entry 2 is your `set`. A few things to know before you build on it: -- Write through the leader. `Propose` on a follower returns a not-leader error that names the current leader, and `consensus.IsNotLeaderError(err)` recognises it. -- Read from the leader too. Followers learn the commit index on the next heartbeat but don't apply committed entries to their own state machine yet, so the same `Query` on a follower returns `key not found`. +- Write through the leader. `Propose` on a follower returns a not-leader error that names the current leader, and `consensus.IsNotLeaderError(err)` recognises it. If the leader loses its term before your entry commits, `Propose` returns `raft.ErrProposalDropped` and you can retry on the new leader. +- Followers apply committed entries too, a heartbeat or so after the leader. A read from a follower's state machine can lag the leader; reads aren't linearizable. - The memory state machine understands `set`, `delete` and `increment` commands and `{"type": "get", "key": ...}` queries. For your own data, implement `consensus.StateMachine` (`Apply`, `Snapshot`, `Restore` and `Query`) and pass it to `raft.NewNode` in place of `sm`. -- `storage.NewBadgerStorage` and `storage.NewBoltDBStorage` give you on-disk logs, and `transport` has gRPC, TCP and HTTP transports. They compile, but nothing in the repository runs a networked cluster on them yet, so treat them as untested. +- For a real deployment, swap in `storage.NewBadgerStorage` or `storage.NewBoltDBStorage` for an on-disk log, and `transport.NewTCPTransport`, `NewHTTPTransport` or `NewGRPCTransport` for the network. Three node clusters on all three network transports are covered by the module's tests. Give each node the others' addresses with `AddPeerAddress` instead of `AddPeer`, so servers you add later can reach them. ## Add the Forge extension @@ -151,7 +151,7 @@ app := forge.NewApp(forge.AppConfig{ consensus.NewExtension( consensus.WithNodeID("node-1"), consensus.WithClusterID("orders"), - consensus.WithBindAddress("0.0.0.0", 7000), + consensus.WithBindAddress("10.0.0.1", 7000), consensus.WithPeers([]consensus.PeerConfig{ {ID: "node-2", Address: "10.0.0.2", Port: 7000}, {ID: "node-3", Address: "10.0.0.3", Port: 7000}, @@ -161,27 +161,23 @@ app := forge.NewApp(forge.AppConfig{ }) ``` -Here's what that gives you today. The container holds `*consensus.Service` (also named `consensus`), but its Raft node, state machine, storage and transport are all nil. Nothing listens on port 7000 and the node stays a follower, so: +`Start` builds the node from that config: the storage under `storage.path` (`badger` by default, or `boltdb` or `memory`), the transport on `bind_addr:bind_port` (`tcp` by default, or `http` or `grpc`), a memory state machine, and a Raft node whose first members are the `peers` list. Start the same app on every server with its own `node_id` and bind address, and they elect a leader between them. Mind you, `bind_addr` defaults to `127.0.0.1`, so set it to an address the other servers can reach. + +The container holds `*consensus.Service` (also named `consensus`). Take it from the extension and call it like this: | Call | What happens | | --- | --- | -| `Apply` | Always returns `ErrNotLeader` | -| `Read` | Panics on the nil state machine | -| `HealthCheck` | Returns `storage not initialized`, and the service logs it on every health check | -| `AddNode`, `RemoveNode` | Return a not-leader error | -| `TransferLeadership`, `StepDown` | Return "not yet implemented" | - -Turn off automatic snapshots if you add the extension anyway. They're on by default, and every `raft.snapshot_interval` (30 minutes) the snapshot call panics on the nil state machine and takes your process down: - -```yaml -extensions: - consensus: - node_id: node-1 - advanced: - enable_auto_snapshot: false -``` +| `Apply` | On the leader, appends the command and returns once it is committed and applied. Elsewhere it returns a not-leader error | +| `Read` | Queries this node's state machine, which may lag the leader | +| `Snapshot` | Snapshots the state machine and compacts the log | +| `AddNode`, `RemoveNode` | Change membership one server at a time, on the leader | +| `TransferLeadership`, `StepDown` | Hand leadership to a chosen voter, or step down and let an election decide | + +To grow the cluster, start the new server with `join: true` (or `consensus.WithJoin(true)`) and the existing members in its `peers`, so it waits to be added instead of electing itself. Then call `AddNode` on the leader with the new server's ID and address. It joins as a learner, catches up, and becomes a voter. After that first change the log holds the membership, so editing `peers` later does nothing. + +Turn on `security.enable_tls` or `enable_mtls` to protect traffic between nodes, and `security.enable_encryption` to encrypt what each node writes to disk. The README covers [encryption at rest](README.md#encryption-at-rest) in detail. -`admin_api.enabled` only writes a log line, so there are no `/consensus/...` routes. The `middleware` package's leadership helpers take a `ConsensusService`, which the extension can't back with a real node yet. +The admin routes are off by default. With `admin_api.enabled: true` they're registered on your app's router under `/consensus`, and they can write to the replicated log, so set `admin_api.enable_auth: true` and an `api_key` whenever anyone else can reach that router. The full list of config keys, defaults and validation rules is in the [README's configuration section](README.md#configuration). diff --git a/extensions/consensus/README.md b/extensions/consensus/README.md index 7732bf375..f4383084b 100644 --- a/extensions/consensus/README.md +++ b/extensions/consensus/README.md @@ -4,7 +4,7 @@ # Forge Consensus: Raft consensus building blocks for Go -Forge Consensus is the Raft consensus module for [Forge](https://github.com/xraph/forge), the Go backend framework. It holds a Raft implementation in Go with leader election, pre-vote, log replication and snapshots, plus the pieces a node is built from: log storage on BadgerDB, BoltDB or memory, TCP, HTTP and in-process transports, peer discovery through static lists, DNS, Consul, etcd or Kubernetes, and in-memory and persistent state machines. A Forge extension sits on top and runs a node from configuration. Read the [status](#status) before you pick it for a distributed system. +Forge Consensus is the Raft consensus module for [Forge](https://github.com/xraph/forge), the Go backend framework. It holds a Raft implementation in Go with leader election, log replication, snapshots, membership changes and leadership transfer, plus the pieces a node is built from: log storage on BadgerDB, BoltDB or memory, TCP, HTTP, gRPC and in-process transports, peer discovery through static lists, DNS, Consul, etcd or Kubernetes, and in-memory and persistent state machines. A Forge extension sits on top and runs a node from configuration. Read the [status](#status) before you pick it for a distributed system. [![Go 1.26+](https://img.shields.io/badge/Go-1.26%2B-00ADD8?logo=go&logoColor=white)](https://go.dev/dl/) [![Go CI](https://github.com/xraph/forge/actions/workflows/go.yml/badge.svg)](https://github.com/xraph/forge/actions/workflows/go.yml) [![Go Reference](https://pkg.go.dev/badge/github.com/xraph/forge/extensions/consensus.svg)](https://pkg.go.dev/github.com/xraph/forge/extensions/consensus) [![Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](../../LICENSE) @@ -148,11 +148,13 @@ This module has not run a production cluster yet. Here's what is covered by test | Piece | State | | --- | --- | -| Leader election, log replication and applying entries in `raft` | Three node clusters elect a leader and replicate commands to every state machine over the in-process, TCP and HTTP transports | +| Leader election, log replication and applying entries in `raft` | Three node clusters elect a leader and replicate commands to every state machine over the in-process, TCP, HTTP and gRPC transports | | Durability | The log, term and vote are reloaded from storage on restart; a node only acknowledges entries and votes it has persisted | | Snapshots | Nodes compact their log into snapshots, and a follower that falls behind the snapshot catches up through InstallSnapshot, sent in chunks | -| `consensus.NewExtension` | Builds storage, transport, state machine and Raft node from config and replicates over TCP or HTTP, with TLS and mTLS. See [the Forge extension](#the-forge-extension) | -| Not implemented | The gRPC transport, membership changes (`AddNode`, `RemoveNode`), leadership transfer, linearizable reads, encryption at rest, and dynamic discovery in the extension (peers come from the static list) | +| `consensus.NewExtension` | Builds storage, transport, state machine and Raft node from config and replicates over TCP, HTTP or gRPC, with TLS and mTLS. See [the Forge extension](#the-forge-extension) | +| Membership and leadership transfer | Servers are added (as a learner first, then promoted) and removed one at a time through the log, the leader included. `TransferLeadership` hands over to a chosen voter and gives up after an election timeout. Membership survives restarts and snapshots | +| Encryption at rest | With `security.enable_encryption` every value the node stores (log entries, term, vote, snapshots and snapshot metadata) is sealed with AES-256-GCM. See [encryption at rest](#encryption-at-rest) | +| Not implemented | Linearizable reads, and dynamic discovery in the extension (the initial members come from the static list) | ## Packages @@ -161,8 +163,8 @@ You assemble a node from these packages yourself, the way the quick start does. | Package | What's in it | | --- | --- | | [`raft`](raft/) | `raft.NewNode(config, logger, stateMachine, transport, storage)`, elections, replication, snapshots, `Propose`, `AddPeer` | -| [`storage`](storage/) | `NewMemoryStorage`, `NewBadgerStorage`, `NewBoltDBStorage`, and a write-ahead log (`NewWAL`) | -| [`transport`](transport/) | `NewLocalTransport` (in process), `NewTCPTransport`, `NewHTTPTransport`, TLS helpers and serializers. `NewGRPCTransport` returns `ErrGRPCNotImplemented` from `Start` and `Send` | +| [`storage`](storage/) | `NewMemoryStorage`, `NewBadgerStorage`, `NewBoltDBStorage`, a write-ahead log (`NewWAL`), and `NewEncryptedStorage` with `LoadKeyring`, `MigrateToEncrypted` and `MigrateToPlaintext` for encryption at rest | +| [`transport`](transport/) | `NewLocalTransport` (in process), `NewTCPTransport`, `NewHTTPTransport`, `NewGRPCTransport`, TLS helpers and serializers | | [`statemachine`](statemachine/) | `NewMemoryStateMachine` (a key-value map with `set`, `delete` and `increment`) and `NewPersistentStateMachine` | | [`discovery`](discovery/) | `NewStaticDiscovery`, `NewDNSDiscovery`, `NewConsulDiscovery`, `NewEtcdDiscovery`, `NewKubernetesDiscovery` | | [`cluster`](cluster/) | Membership, quorum and topology tracking with `cluster.NewManager` | @@ -180,7 +182,7 @@ app := forge.NewApp(forge.AppConfig{ consensus.NewExtension( consensus.WithNodeID("node-1"), consensus.WithClusterID("orders"), - consensus.WithBindAddress("0.0.0.0", 7000), + consensus.WithBindAddress("10.0.0.1", 7000), consensus.WithPeers([]consensus.PeerConfig{ {ID: "node-2", Address: "10.0.0.2", Port: 7000}, {ID: "node-3", Address: "10.0.0.3", Port: 7000}, @@ -190,7 +192,9 @@ app := forge.NewApp(forge.AppConfig{ }) ``` -`Start` builds the node from config: storage (`badger` or `boltdb` under `storage.path`, or `memory`), the `tcp` or `http` transport on `bind_addr:bind_port` with `transport.max_message_size`, a memory state machine, and a Raft node whose peers are the `peers` list. With `security.enable_tls` the transport serves and dials over TLS; with `enable_mtls` it also requires client certificates and refuses messages whose sender is not named in the certificate (each node's certificate must carry its node ID as a DNS subject alternative name). +`Start` builds the node from config: storage (`badger` or `boltdb` under `storage.path`, or `memory`), the `tcp`, `http` or `grpc` transport on `bind_addr:bind_port` with `transport.max_message_size`, a memory state machine, and a Raft node whose peers are the `peers` list. With `security.enable_tls` the transport serves and dials over TLS; with `enable_mtls` it also requires client certificates and refuses messages whose sender is not named in the certificate (each node's certificate must carry its node ID as a DNS subject alternative name). + +All three network transports carry the same versioned JSON envelope. The gRPC transport sends each message as one unary call to `forge.consensus.raft.v1.Transport/Send` with a raw bytes codec, so no protoc step or generated code is involved. It keeps one connection per peer, applies `transport.max_message_size` as the gRPC send and receive limit, caps inbound connections at `transport.max_connections`, and pings idle connections every `transport.keep_alive_interval`. A peer on another protocol version, an oversized message or a sender that does not match its client certificate is refused with a gRPC status, which `Send` returns as `ErrProtocolVersion`, `ErrMessageTooLarge` or a permission error. | Call | Result | | --- | --- | @@ -198,10 +202,61 @@ app := forge.NewApp(forge.AppConfig{ | `Read` | Queries the local state machine, which may lag the leader on a follower | | `Snapshot` | Snapshots the state machine and compacts the log | | `StepDown` | The leader returns to follower | -| `AddNode`, `RemoveNode` | `ErrMembershipChangeUnsupported` | -| `TransferLeadership` | Not implemented, use `StepDown` | +| `AddNode` | On the leader, adds a running server that was started with `join: true`. It joins as a learner and becomes a voter once it has caught up. Only one change runs at a time (`raft.ErrConfigChangeInProgress`) | +| `RemoveNode` | On the leader, removes a server. Removing the leader is allowed; it steps down once the change commits | +| `TransferLeadership` | On the leader, hands leadership to a voter. Writes are refused while it runs, and it fails with `raft.ErrLeadershipTransferFailed` if the target has not taken over within an election timeout | + +`GetClusterManager` lists the members of the current configuration, learners included, and changes membership through the same log entries. Servers that are not voters, including removed ones that never learned of their removal, cannot disrupt the cluster: their vote requests are ignored, as are any that arrive while a leader is known to be alive. + +Settings the service cannot honour fail when it is created: storage `pebble` or `postgres`, and any discovery type other than `static`. The container entries for `RaftNode`, `StateMachine` and `ClusterManager` are resolved from the service, and resolving the service from the container after the app has started fails with `consensus service already started` (the container tries to start it again), so take them from the extension's `Service()` with `GetRaftNode()`, `GetStateMachine()` and `GetClusterManager()`. With `admin_api.enabled` (off by default) the admin routes are registered on the app router under `admin_api.path_prefix`; set `admin_api.enable_auth` and `api_key` whenever that router is reachable by anyone else. + +### Encryption at rest + +Turn on `security.enable_encryption` and give the node a key, and everything it writes through its storage backend is encrypted before it reaches disk: the Raft log, the current term and vote, snapshots and the snapshot metadata. It works the same on `badger`, `boltdb` and `memory`. + +```yaml +security: + enable_encryption: true + encryption_key_file: /etc/consensus/raft.key # or encryption_key_env: RAFT_KEY +``` + +You can make a key with `openssl rand -hex 32 > raft.key && chmod 600 raft.key`. A key is 32 bytes (AES-256), and the file can hold the 32 raw bytes, 64 hex characters or base64 text. An environment variable holds hex or base64. The key is read when the service starts, and a key of the wrong size, a missing file or an unset variable stops `Start` with `storage.ErrInvalidEncryptionKey`. Errors name the source but never print the key, and the log only ever shows key IDs. A key file that other users can read gets a warning. Inline keys (`encryption_key`, or `value` in a list entry) are refused unless you set `allow_inline_encryption_key: true`, because keys written into config files end up in version control. + +Each node encrypts its own disk, so each node can have its own key. Data sent between nodes (including snapshots) is not covered by this; use `enable_tls` or `enable_mtls` for that. + +#### Format + +Every stored value becomes `version (1 byte) | key ID (4 bytes) | nonce (12 bytes) | ciphertext | tag (16 bytes)`, 33 bytes more than the plaintext. The nonce is 96 random bits from `crypto/rand`, fresh on every write. The GCM additional data is the version and key ID followed by the storage key, so a value copied to another key, a flipped bit or an edited header fails with `storage.ErrDecrypt` instead of being read. Random nonces mean you should rotate a key before it has encrypted around 2^32 values (about four billion writes). + +#### What stays readable + +Storage keys are left in plaintext. The Raft node only uses names like `currentTerm`, `votedFor`, `log_`, `snapshot_` and `snapshot_meta`, so someone with the disk learns how many entries there are, roughly how big each one is, and nothing about their content. Keeping keys readable is what lets range scans keep working on every backend. If you build your own state machine on this storage (like `statemachine.PersistentStateMachine`, which stores `sm/`), your key names are visible, so don't put secrets in them. The write-ahead log in `storage.NewWAL` writes its own files and is not encrypted; the service does not use it. Badger's and BoltDB's own backup and compaction work on the stored bytes, so they only ever see ciphertext. + +#### Rotating keys + +List the keys with IDs. The highest ID (or `encryption_active_key_id`) encrypts new writes, and every listed key can still read: + +```yaml +security: + enable_encryption: true + encryption_keys: + - {id: 1, file: /etc/consensus/raft-1.key} + - {id: 2, env: RAFT_KEY_2} +``` + +A single `encryption_key_file` or `encryption_key_env` is key ID 1, so you rotate by moving it into the list as ID 1 and adding ID 2. Restart the node, then call `Service.ReencryptStorage()` to rewrite everything still under the old key; it's safe while the node is serving. After that you can drop key 1 from the list. Never reuse an ID for a different key. + +#### Wrong key or wrong mode + +The store keeps a small encrypted check value per key ID under reserved keys starting with a zero byte. On start, every configured key that has a check value must decrypt it, and at least one must, so a wrong key fails at `Start` with `storage.ErrWrongKey` instead of on the first read. Turning encryption on over a store that already holds plaintext fails with `storage.ErrPlaintextStore`, and starting without encryption over an encrypted store fails with `storage.ErrEncryptedStore`. Nothing is ever mixed silently. + +#### Migrating an existing node + +To encrypt a node that already has data, start it once with `security.encryption_migrate_plaintext: true`. It encrypts every value in place, writes the check values, and starts as normal; you can leave the flag on or remove it afterwards. To go back, stop the node and run `storage.MigrateToPlaintext` on the started backend with the same keyring. Both migrations write a marker first, so if one is interrupted the node refuses to start either way with `storage.ErrMigrationIncomplete` until you run it again, and the rerun picks up where it stopped. Mind you, the old plaintext can stay in BoltDB free pages or Badger value log files until they're reused or compacted. If that matters, copy the data into a fresh store (or compact it) after migrating, or rebuild the node from an empty path with encryption on. + +#### Cost -Settings the service cannot honour fail when it is created: transport `grpc`, storage `pebble` or `postgres`, any discovery type other than `static`, and `security.enable_encryption`. The container entries for `RaftNode` and `StateMachine` are resolved from the service, so resolve them after the app has started. With `admin_api.enabled` (off by default) the admin routes are registered on the app router under `admin_api.path_prefix`; set `admin_api.enable_auth` and `api_key` whenever that router is reachable by anyone else. +Sealing a value takes about 0.3 µs for 128 bytes and 4 µs for 16 KiB on an Apple M5 Max. A Raft log append to the memory backend goes from 0.6 µs to 1.1 µs at 128 bytes. On BoltDB the fsync (several milliseconds) dominates and the difference disappears in the noise. Run `go test -bench 'LogAppend|Seal' ./storage/` to measure your own hardware. ## Configuration @@ -212,7 +267,7 @@ extensions: consensus: node_id: node-1 cluster_id: orders - bind_addr: 0.0.0.0 + bind_addr: 10.0.0.1 bind_port: 7000 peers: - {id: node-2, address: 10.0.0.2, port: 7000} @@ -222,14 +277,15 @@ extensions: election_timeout_min: 5s election_timeout_max: 10s transport: - type: tcp # tcp or http + type: tcp # tcp, http or grpc storage: - type: badger # badger, boltdb, pebble or postgres + type: badger # badger, boltdb or memory path: ./data/consensus discovery: - type: static # static, dns, consul, etcd or kubernetes - advanced: - enable_auto_snapshot: false + type: static # only static is wired into the extension + security: + enable_encryption: true + encryption_key_file: /etc/consensus/raft.key ``` Validation runs when the extension registers. If any of these rules fail, your app won't start: @@ -241,17 +297,17 @@ Validation runs when the extension registers. If any of these rules fail, your a | `bind_port` is between 1 and 65535 | `7000` | | `raft.heartbeat_interval` < `raft.election_timeout_min` < `raft.election_timeout_max` | `1s`, `5s`, `10s` | | `bind_addr` is the listen address; set it explicitly to accept other hosts | `127.0.0.1` | -| `transport.type` is `tcp` or `http` (`grpc` is rejected because it is not implemented) | `tcp` | +| `transport.type` is `tcp`, `http` or `grpc` | `tcp` | | `transport.max_message_size` is positive | 4MB | | `discovery.type` is `static`, `dns`, `consul`, `etcd` or `kubernetes` | `static` | | `storage.type` is `badger`, `boltdb` or `memory` (`pebble` and `postgres` are not implemented), and `storage.path` is set | `badger`, `./data/consensus` | | `security.cert_file` and `key_file` are set when `enable_tls` is on, and `ca_file` when `enable_mtls` is on | TLS off | -| `security.enable_encryption` is off (encryption at rest is not implemented) | off | +| `security.enable_encryption` has exactly one key source (`encryption_key_file`, `encryption_key_env`, or `encryption_keys` with unique IDs from 1), inline keys only with `allow_inline_encryption_key`, and `encryption_active_key_id` is a listed ID | off | | `admin_api.api_key` is set when `admin_api.enable_auth` is on | auth off | -When you assemble a node yourself, pass `TLSConfig` (from `transport.NewTLSManager`) and `RequirePeerIdentity` to `transport.NewTCPTransport` or `transport.NewHTTPTransport` to get the same protection. The admin API takes `admin.WithAPIKey` or `admin.NewAPIFromConfig` to require an API key on every route. +When you assemble a node yourself, pass `TLSConfig` (from `transport.NewTLSManager`) and `RequirePeerIdentity` to `transport.NewTCPTransport`, `transport.NewHTTPTransport` or `transport.NewGRPCTransport` to get the same protection. The admin API takes `admin.WithAPIKey` or `admin.NewAPIFromConfig` to require an API key on every route. -The options are `WithNodeID`, `WithClusterID`, `WithBindAddress`, `WithPeers`, `WithTransportType`, `WithDiscoveryType`, `WithStorageType`, `WithStoragePath`, `WithTLS`, `WithMTLS`, `WithConfig` and `WithRequireConfig`. The config also has `election`, `health`, `observability`, `resilience`, `admin_api`, `events` and `advanced` sections. Their full key list and defaults are in [`internal/config.go`](internal/config.go) and on the [configuration page](https://www.xraph.com/docs/forge/extensions/consensus/configuration). Today the extension acts on a handful of them: `health.enabled` and `health.check_interval` drive its health loop, `observability.metrics.enabled` and `collection_interval` drive metrics collection, and `advanced.enable_auto_snapshot` with `raft.snapshot_interval` drives the snapshot loop. `events.enabled` is on by default. It adds `events` to the extension's dependencies and publishes start and stop events when an event bus is in the container. +The options are `WithNodeID`, `WithClusterID`, `WithBindAddress`, `WithPeers`, `WithJoin`, `WithTransportType`, `WithDiscoveryType`, `WithStorageType`, `WithStoragePath`, `WithTLS`, `WithMTLS`, `WithConfig` and `WithRequireConfig`. The config also has `election`, `health`, `observability`, `resilience`, `admin_api`, `events` and `advanced` sections. Their full key list and defaults are in [`internal/config.go`](internal/config.go) and on the [configuration page](https://www.xraph.com/docs/forge/extensions/consensus/configuration). Today the extension acts on a handful of them: `health.enabled` and `health.check_interval` drive its health loop, `observability.metrics.enabled` and `collection_interval` drive metrics collection, and `advanced.enable_auto_snapshot` with `raft.snapshot_interval` drives the snapshot loop. `events.enabled` is on by default. It adds `events` to the extension's dependencies and publishes start and stop events when an event bus is in the container. ## Documentation @@ -271,15 +327,15 @@ There is one in [`raft`](raft/), and the quick start shows a three-node cluster ### How does leader election work? -Nodes start as followers with a randomised election timeout between `election_timeout_min` and `election_timeout_max`. A follower that hears no heartbeat in that window becomes a candidate, runs a pre-vote if it's on, then asks its peers for votes, and the node with a majority becomes leader and sends heartbeats every `heartbeat_interval`. +Nodes start as followers with a randomised election timeout between `election_timeout_min` and `election_timeout_max`. A follower that hears no heartbeat in that window becomes a candidate and asks the other voters for votes, and the node with a majority becomes leader and sends heartbeats every `heartbeat_interval`. There's no separate pre-vote round: `raft.pre_vote` is accepted but has no effect. A voter ignores vote requests while it has heard from a live leader recently, which keeps a server that was cut off from forcing a new election when it comes back. ### Can I use this for distributed locks or leader-only jobs? -Not through the extension yet, because `IsLeader` stays false. With your own `raft.Node`, `IsLeader()` and `GetLeader()` tell you which node should run a leader-only job. +Yes. `Service.IsLeader()` (or `IsLeader()` on your own `raft.Node`) tells you whether this node should run a leader-only job, and the `middleware` package's `RequireLeader` rejects requests on followers. Leadership can move at any time, so check it again before each run, and write the job's results through `Apply` so a new leader picks up where the old one stopped. ### Which storage backends are there? -In memory, BadgerDB and BoltDB, plus a write-ahead log. The config validator also accepts `pebble` and `postgres`, but there's no implementation for either in this module. +In memory, BadgerDB and BoltDB, plus a write-ahead log, and any of them can be encrypted at rest. The config validator also accepts `pebble` and `postgres`, but there's no implementation for either, so the service refuses them when it's created. ## Contributing diff --git a/extensions/consensus/exports.go b/extensions/consensus/exports.go index 2edf4c512..b3ee7974a 100644 --- a/extensions/consensus/exports.go +++ b/extensions/consensus/exports.go @@ -224,6 +224,7 @@ var ( WithClusterID = internal.WithClusterID WithBindAddress = internal.WithBindAddress WithPeers = internal.WithPeers + WithJoin = internal.WithJoin WithTransportType = internal.WithTransportType WithDiscoveryType = internal.WithDiscoveryType WithStorageType = internal.WithStorageType diff --git a/extensions/consensus/internal/config.go b/extensions/consensus/internal/config.go index 507446077..9d4263069 100644 --- a/extensions/consensus/internal/config.go +++ b/extensions/consensus/internal/config.go @@ -18,6 +18,10 @@ type Config struct { // Peers - initial cluster members Peers []PeerConfig `json:"peers" yaml:"peers"` + // Join starts this node as a server waiting to be added to an existing + // cluster with AddNode. Peers then only tell it where the cluster is. + Join bool `json:"join" yaml:"join"` + // Raft configuration Raft RaftConfig `json:"raft" yaml:"raft"` @@ -84,7 +88,7 @@ type RaftConfig struct { // TransportConfig contains transport layer configuration. type TransportConfig struct { - Type string `default:"tcp" json:"type" yaml:"type"` // tcp, http (grpc is not implemented) + Type string `default:"tcp" json:"type" yaml:"type"` // tcp, http, grpc MaxMessageSize int `default:"4194304" json:"max_message_size" yaml:"max_message_size"` // 4MB Timeout time.Duration `default:"10s" json:"timeout" yaml:"timeout"` KeepAlive bool `default:"true" json:"keep_alive" yaml:"keep_alive"` @@ -200,6 +204,17 @@ type SecurityConfig struct { SkipVerify bool `default:"false" json:"skip_verify" yaml:"skip_verify"` EnableEncryption bool `default:"false" json:"enable_encryption" yaml:"enable_encryption"` EncryptionKey string `json:"encryption_key" yaml:"encryption_key"` + + // Encryption at rest keys. A single key (ID 1) comes from one of + // EncryptionKeyFile, EncryptionKeyEnv or, only with + // AllowInlineEncryptionKey, EncryptionKey. EncryptionKeys lists several + // keys for rotation; see EncryptionKeyConfig. + EncryptionKeyFile string `json:"encryption_key_file" yaml:"encryption_key_file"` + EncryptionKeyEnv string `json:"encryption_key_env" yaml:"encryption_key_env"` + EncryptionKeys []EncryptionKeyConfig `json:"encryption_keys" yaml:"encryption_keys"` + EncryptionActiveKeyID uint32 `json:"encryption_active_key_id" yaml:"encryption_active_key_id"` + AllowInlineEncryptionKey bool `json:"allow_inline_encryption_key" yaml:"allow_inline_encryption_key"` + EncryptionMigratePlaintext bool `json:"encryption_migrate_plaintext" yaml:"encryption_migrate_plaintext"` } // ResilienceConfig contains resilience configuration. @@ -415,9 +430,7 @@ func (c *Config) Validate() error { // Validate transport config switch c.Transport.Type { - case "tcp", "http": - case "grpc": - return fmt.Errorf("%w: transport type grpc is not implemented, use tcp or http", ErrInvalidConfig) + case "tcp", "http", "grpc": default: return fmt.Errorf("%w: invalid transport type: %s", ErrInvalidConfig, c.Transport.Type) } @@ -461,10 +474,8 @@ func (c *Config) Validate() error { return fmt.Errorf("%w: security.ca_file is required when mTLS is enabled", ErrInvalidConfig) } - // Nothing encrypts consensus data at rest, so accepting the option would - // promise protection that does not exist. - if c.Security.EnableEncryption { - return fmt.Errorf("%w: security.enable_encryption is not implemented", ErrInvalidConfig) + if err := c.Security.validateEncryption(); err != nil { + return err } if c.AdminAPI.EnableAuth && c.AdminAPI.APIKey == "" { @@ -506,6 +517,14 @@ func WithPeers(peers []PeerConfig) ConfigOption { } } +// WithJoin starts the node as a server that waits to be added to an +// existing cluster instead of bootstrapping one. +func WithJoin(join bool) ConfigOption { + return func(c *Config) { + c.Join = join + } +} + // WithTransportType sets the transport type. func WithTransportType(transportType string) ConfigOption { return func(c *Config) { diff --git a/extensions/consensus/internal/config_security_test.go b/extensions/consensus/internal/config_security_test.go index 14335211c..3d5db7b9c 100644 --- a/extensions/consensus/internal/config_security_test.go +++ b/extensions/consensus/internal/config_security_test.go @@ -25,7 +25,7 @@ func TestDefaultConfigBindsLoopback(t *testing.T) { func TestValidateRejectsOptionsThatCannotBeHonoured(t *testing.T) { cases := map[string]func(*Config){ - "grpc transport": func(c *Config) { c.Transport.Type = "grpc" }, + "quic transport": func(c *Config) { c.Transport.Type = "quic" }, "encryption at rest": func(c *Config) { c.Security.EnableEncryption = true }, "admin auth without key": func(c *Config) { c.AdminAPI.EnableAuth = true }, } diff --git a/extensions/consensus/internal/encryption_config.go b/extensions/consensus/internal/encryption_config.go new file mode 100644 index 000000000..3e8067f84 --- /dev/null +++ b/extensions/consensus/internal/encryption_config.go @@ -0,0 +1,105 @@ +package internal + +import ( + "fmt" + "slices" +) + +// EncryptionKeyConfig is one encryption at rest key. Exactly one of File, Env +// and Value is set. Keys are 32 bytes (AES-256): a file holds 32 raw bytes, +// 64 hex characters or base64 text; an environment variable or inline value +// holds hex or base64 text. +// +// To rotate, add a key with a new ID and make it active. Values written +// earlier stay readable with the older key until they are re-encrypted +// (Service.ReencryptStorage) or replaced, after which the old key can be +// removed. +type EncryptionKeyConfig struct { + // ID is stored in every value the key encrypts. IDs start at 1 and must + // never be reused for a different key. + ID uint32 `json:"id" yaml:"id"` + File string `json:"file" yaml:"file"` + Env string `json:"env" yaml:"env"` + Value string `json:"value" yaml:"value"` +} + +// EncryptionKeySources returns the configured keys as a list: EncryptionKeys +// when set, otherwise the single key settings as key ID 1. +func (s SecurityConfig) EncryptionKeySources() []EncryptionKeyConfig { + if len(s.EncryptionKeys) > 0 { + return slices.Clone(s.EncryptionKeys) + } + + single := EncryptionKeyConfig{ID: 1, File: s.EncryptionKeyFile, Env: s.EncryptionKeyEnv, Value: s.EncryptionKey} + if single.File == "" && single.Env == "" && single.Value == "" { + return nil + } + + return []EncryptionKeyConfig{single} +} + +// validateEncryption checks the shape of the encryption settings. Reading the +// keys and checking their length happens when the service starts. +func (s SecurityConfig) validateEncryption() error { + if !s.EnableEncryption { + return nil + } + + single := 0 + + for _, v := range []string{s.EncryptionKeyFile, s.EncryptionKeyEnv, s.EncryptionKey} { + if v != "" { + single++ + } + } + + if len(s.EncryptionKeys) > 0 && single > 0 { + return fmt.Errorf("%w: set either security.encryption_keys or one of encryption_key_file, "+ + "encryption_key_env and encryption_key, not both", ErrInvalidConfig) + } + + keys := s.EncryptionKeySources() + if len(keys) == 0 { + return fmt.Errorf("%w: security.enable_encryption needs a key: set security.encryption_key_file or "+ + "encryption_key_env, or encryption_keys to rotate keys", ErrInvalidConfig) + } + + seen := make(map[uint32]bool, len(keys)) + + for _, k := range keys { + if k.ID == 0 { + return fmt.Errorf("%w: security.encryption_keys: key IDs start at 1", ErrInvalidConfig) + } + + if seen[k.ID] { + return fmt.Errorf("%w: security.encryption_keys: key ID %d is listed twice", ErrInvalidConfig, k.ID) + } + + seen[k.ID] = true + + sources := 0 + + for _, v := range []string{k.File, k.Env, k.Value} { + if v != "" { + sources++ + } + } + + if sources != 1 { + return fmt.Errorf("%w: encryption key %d needs exactly one of a file, an environment variable "+ + "or an inline value", ErrInvalidConfig, k.ID) + } + + if k.Value != "" && !s.AllowInlineEncryptionKey { + return fmt.Errorf("%w: encryption key %d is written inline in the configuration; use a key file "+ + "or an environment variable, or set security.allow_inline_encryption_key", ErrInvalidConfig, k.ID) + } + } + + if s.EncryptionActiveKeyID != 0 && !seen[s.EncryptionActiveKeyID] { + return fmt.Errorf("%w: security.encryption_active_key_id %d is not a configured key", + ErrInvalidConfig, s.EncryptionActiveKeyID) + } + + return nil +} diff --git a/extensions/consensus/internal/encryption_config_test.go b/extensions/consensus/internal/encryption_config_test.go new file mode 100644 index 000000000..fdee32b4d --- /dev/null +++ b/extensions/consensus/internal/encryption_config_test.go @@ -0,0 +1,79 @@ +package internal + +import ( + "errors" + "testing" +) + +func TestValidateEncryptionSettings(t *testing.T) { + valid := map[string]func(*SecurityConfig){ + "key file": func(s *SecurityConfig) { s.EncryptionKeyFile = "/etc/consensus/raft.key" }, + "key env": func(s *SecurityConfig) { s.EncryptionKeyEnv = "RAFT_KEY" }, + "inline only when allowed": func(s *SecurityConfig) { + s.EncryptionKey = "00" + s.AllowInlineEncryptionKey = true + }, + "rotation list": func(s *SecurityConfig) { + s.EncryptionKeys = []EncryptionKeyConfig{{ID: 1, File: "/k1"}, {ID: 2, Env: "K2"}} + s.EncryptionActiveKeyID = 1 + }, + } + + for name, mutate := range valid { + c := validConfig() + c.Security.EnableEncryption = true + mutate(&c.Security) + + if err := c.Validate(); err != nil { + t.Fatalf("%s: %v", name, err) + } + } + + invalid := map[string]func(*SecurityConfig){ + "no key": func(*SecurityConfig) {}, + "inline by itself": func(s *SecurityConfig) { s.EncryptionKey = "00" }, + "two single sources": func(s *SecurityConfig) { + s.EncryptionKeyFile = "/k" + s.EncryptionKeyEnv = "K" + }, + "single and list": func(s *SecurityConfig) { + s.EncryptionKeyFile = "/k" + s.EncryptionKeys = []EncryptionKeyConfig{{ID: 2, File: "/k2"}} + }, + "id zero": func(s *SecurityConfig) { s.EncryptionKeys = []EncryptionKeyConfig{{File: "/k"}} }, + "duplicate ids": func(s *SecurityConfig) { + s.EncryptionKeys = []EncryptionKeyConfig{{ID: 1, File: "/a"}, {ID: 1, File: "/b"}} + }, + "no source": func(s *SecurityConfig) { s.EncryptionKeys = []EncryptionKeyConfig{{ID: 1}} }, + "two sources": func(s *SecurityConfig) { s.EncryptionKeys = []EncryptionKeyConfig{{ID: 1, File: "/a", Env: "A"}} }, + "inline in list": func(s *SecurityConfig) { + s.EncryptionKeys = []EncryptionKeyConfig{{ID: 1, Value: "00"}} + }, + "unknown active": func(s *SecurityConfig) { + s.EncryptionKeyFile = "/k" + s.EncryptionActiveKeyID = 2 + }, + } + + for name, mutate := range invalid { + c := validConfig() + c.Security.EnableEncryption = true + mutate(&c.Security) + + if err := c.Validate(); !errors.Is(err, ErrInvalidConfig) { + t.Fatalf("%s: Validate returned %v, want ErrInvalidConfig", name, err) + } + } + + // Key settings are ignored while encryption is off. + c := validConfig() + c.Security.EncryptionKey = "00" + + if err := c.Validate(); err != nil { + t.Fatalf("inline key with encryption off: %v", err) + } + + if got := (SecurityConfig{EncryptionKeyEnv: "K"}).EncryptionKeySources(); len(got) != 1 || got[0].ID != 1 || got[0].Env != "K" { + t.Fatalf("single key settings map to %+v, want key ID 1", got) + } +} diff --git a/extensions/consensus/internal/types.go b/extensions/consensus/internal/types.go index 44ba6b628..1d9799505 100644 --- a/extensions/consensus/internal/types.go +++ b/extensions/consensus/internal/types.go @@ -300,6 +300,76 @@ type RequestVoteRequest struct { LastLogIndex uint64 `json:"last_log_index"` LastLogTerm uint64 `json:"last_log_term"` PreVote bool `json:"pre_vote"` + // Transfer marks an election started by TimeoutNow during a leadership + // transfer. Voters grant it even though they heard from the leader + // recently, which they otherwise refuse (section 4.2.3). + Transfer bool `json:"transfer,omitempty"` +} + +// TimeoutNowRequest asks the target of a leadership transfer to start an +// election at once (Raft dissertation section 3.10). +type TimeoutNowRequest struct { + Term uint64 `json:"term"` + LeaderID string `json:"leader_id"` +} + +// TimeoutNowResponse answers a TimeoutNowRequest. +type TimeoutNowResponse struct { + Term uint64 `json:"term"` + NodeID string `json:"node_id"` + Success bool `json:"success"` +} + +// ClusterMember is one server in a cluster configuration. +type ClusterMember struct { + ID string `json:"id"` + Address string `json:"address,omitempty"` + Port int `json:"port,omitempty"` + // Voter is false for a learner: it receives the log but does not vote or + // count towards a majority. + Voter bool `json:"voter"` +} + +// ClusterConfiguration is the set of servers in a Raft cluster. It changes +// one server at a time through configuration entries in the log. +type ClusterConfiguration struct { + Members []ClusterMember `json:"members"` +} + +// Member returns the member with the given ID. +func (c ClusterConfiguration) Member(id string) (ClusterMember, bool) { + for _, m := range c.Members { + if m.ID == id { + return m, true + } + } + + return ClusterMember{}, false +} + +// IsVoter reports whether id is a voting member. +func (c ClusterConfiguration) IsVoter(id string) bool { + m, ok := c.Member(id) + + return ok && m.Voter +} + +// Voters returns the IDs of the voting members. +func (c ClusterConfiguration) Voters() []string { + out := make([]string, 0, len(c.Members)) + + for _, m := range c.Members { + if m.Voter { + out = append(out, m.ID) + } + } + + return out +} + +// Clone returns a deep copy. +func (c ClusterConfiguration) Clone() ClusterConfiguration { + return ClusterConfiguration{Members: append([]ClusterMember(nil), c.Members...)} } // RequestVoteResponse represents a RequestVote RPC response. @@ -318,6 +388,8 @@ type InstallSnapshotRequest struct { Offset uint64 `json:"offset"` Data []byte `json:"data"` Done bool `json:"done"` + // Configuration is the cluster configuration as of LastIncludedIndex. + Configuration *ClusterConfiguration `json:"configuration,omitempty"` } // InstallSnapshotResponse represents an InstallSnapshot RPC response. @@ -428,6 +500,11 @@ const ( MessageTypeInstallSnapshotResponse MessageType = "install_snapshot_response" // MessageTypeHeartbeat is for heartbeat messages. MessageTypeHeartbeat MessageType = "heartbeat" + // MessageTypeTimeoutNow asks the target of a leadership transfer to + // start an election at once. + MessageTypeTimeoutNow MessageType = "timeout_now" + // MessageTypeTimeoutNowResponse answers MessageTypeTimeoutNow. + MessageTypeTimeoutNowResponse MessageType = "timeout_now_response" ) // Discovery defines the interface for service discovery. diff --git a/extensions/consensus/llm.txt b/extensions/consensus/llm.txt index 7b5c41478..a23f53629 100644 --- a/extensions/consensus/llm.txt +++ b/extensions/consensus/llm.txt @@ -2,9 +2,10 @@ ## Purpose -Raft consensus building blocks in Go: a Raft node with leader election, pre-vote, log -replication and snapshots, plus storage, transports, discovery and state machines to build a -node from. A Forge extension sits on top and runs a node from configuration. +Raft consensus building blocks in Go: a Raft node with leader election, log replication, +snapshots, membership changes and leadership transfer, plus storage, transports, discovery and +state machines to build a node from. There is no pre-vote round; raft.pre_vote has no effect. +A Forge extension sits on top and runs a node from configuration. Read "Status" before you use any of it. @@ -13,13 +14,16 @@ helpers are aliases over `consensus/internal` (exports.go). ## Status -- `raft`: leader election, log replication and applying entries work over the in-process, TCP and - HTTP transports (three node tests). Log, term and vote survive restarts. Followers behind the +- `raft`: leader election, log replication and applying entries work over the in-process, TCP, + HTTP and gRPC transports (three node tests). Log, term and vote survive restarts. Followers behind the leader's snapshot catch up through chunked InstallSnapshot. -- `consensus.NewExtension` builds storage (badger, boltdb, memory), the tcp or http transport +- `consensus.NewExtension` builds storage (badger, boltdb, memory), the tcp, http or grpc transport (TLS/mTLS from security.*), a memory state machine and the Raft node from config. -- Not implemented: gRPC transport, membership changes, leadership transfer, linearizable reads, - encryption at rest, non-static discovery in the extension. +- Membership: single-server changes through the log (learner, then voter), leader removal, and + TransferLeadership (TimeoutNow). Config entries take effect on append and persist in snapshots. +- Encryption at rest: security.enable_encryption seals every stored value (log, term, vote, + snapshots) with AES-256-GCM; keys from a file or env var, rotation via key IDs. +- Not implemented: linearizable reads, non-static discovery in the extension. ## Packages and constructors @@ -84,7 +88,8 @@ WithNodeID(id string) WithClusterID(id string) WithBindAddress(addr string, port int) WithPeers(peers []PeerConfig) // PeerConfig{ID, Address string; Port int} -WithTransportType(transportType string) // tcp, http (grpc is not implemented) +WithJoin(join bool) // wait to be added with AddNode instead of bootstrapping +WithTransportType(transportType string) // tcp, http, grpc WithDiscoveryType(discoveryType string) // static, dns, consul, etcd, kubernetes WithStorageType(storageType string) // badger, boltdb, memory (pebble, postgres not implemented) WithStoragePath(path string) @@ -95,15 +100,18 @@ WithRequireConfig(require bool) ``` Container entries: `*consensus.Service` (aliases `consensus`, `consensus:service`), -`ClusterManager` (`consensus:cluster`, nil: membership is the static peer list), `RaftNode` +`ClusterManager` (`consensus:cluster`, backed by the raft configuration), `RaftNode` (`consensus:raft`), `StateMachine` (`consensus:statemachine`), `*LeadershipChecker` -(`consensus:leadership`). RaftNode and StateMachine are created by Start, so resolve them after -the app has started. +(`consensus:leadership`). RaftNode and StateMachine are created by Start. Resolving `*Service` from the +container after start fails with "consensus service already started" (the container starts it +again), and these entries resolve through it, so use `Service().GetRaftNode()`, +`GetStateMachine()` and `GetClusterManager()` instead. Service: `Apply` commits through the leader (ErrNotLeader elsewhere); `Read` queries the local -state machine; `Snapshot` compacts; `StepDown` works; AddNode/RemoveNode return -ErrMembershipChangeUnsupported; TransferLeadership is not implemented. NewConsensusService fails -for grpc transport, pebble/postgres storage, non-static discovery and enable_encryption. +state machine; `Snapshot` compacts; `StepDown` works; AddNode (target started with join: true, +added as learner then promoted), RemoveNode (leader included) and TransferLeadership work on the +leader, one membership change at a time. NewConsensusService fails +for pebble/postgres storage and non-static discovery. admin_api.enabled (default false) registers the admin routes on the app router. ## Config @@ -111,10 +119,10 @@ admin_api.enabled (default false) registers the admin routes on the app router. Key `extensions.consensus`, falling back to `consensus`. Options override the file. Validation at registration: node_id set (no default); cluster_id set ("default"); bind_port 1..65535 (7000); raft.heartbeat_interval < election_timeout_min < election_timeout_max (1s, 5s, 10s); -bind_addr ("127.0.0.1"); transport.type tcp or http ("tcp", grpc rejected as not implemented); transport.max_message_size positive (4MB); discovery.type +bind_addr ("127.0.0.1"); transport.type tcp, http or grpc ("tcp"); transport.max_message_size positive (4MB); discovery.type static/dns/consul/etcd/kubernetes ("static"); storage.type badger/boltdb/pebble/postgres ("badger") with storage.path ("./data/consensus"); TLS needs cert_file and key_file, mTLS needs -ca_file; enable_encryption is rejected (not implemented); admin_api.enable_auth needs api_key. +ca_file; enable_encryption needs one key source (see Encryption at rest); admin_api.enable_auth needs api_key. enable_tls serves and dials over TLS; enable_mtls also requires client certificates and checks each message's sender against its certificate (node ID as a DNS SAN in each node certificate). @@ -124,11 +132,36 @@ health.check_interval, observability.metrics.enabled and collection_interval, advanced.enable_auto_snapshot with raft.snapshot_interval, and events.enabled (adds an `events` dependency and publishes start and stop events when an event bus is present). +## Encryption at rest + +security.enable_encryption wraps the storage backend in storage.EncryptedStorage (any backend). +Every value (log entries, currentTerm, votedFor, snapshot_, snapshot_meta) is sealed with +AES-256-GCM: version(1) | key ID(4, big endian) | random 96-bit nonce(12) | ciphertext | tag(16), +33 bytes of overhead. GCM additional data = version + key ID + storage key, so moved, edited or +re-labelled values fail with storage.ErrDecrypt. Storage keys stay plaintext (they only carry +indexes; range scans keep working). Not covered: storage.NewWAL files (unused by the service), +data in transit (use TLS/mTLS), key names chosen by your own state machine. +Keys: 32 bytes. encryption_key_file (raw 32 bytes, 64 hex chars or base64) or +encryption_key_env (hex or base64) is key ID 1; encryption_keys: [{id, file|env|value}] for +rotation, active = encryption_active_key_id or the highest ID. Inline keys (encryption_key, +value) need allow_inline_encryption_key. Keys load in Start; bad size or source fails with +storage.ErrInvalidEncryptionKey; key material is never logged or put in errors. +Start checks a per-key-ID encrypted check value under reserved keys (prefix 0x00): a wrong key +fails with ErrWrongKey; encryption over a plaintext store fails with ErrPlaintextStore (set +encryption_migrate_plaintext once to encrypt in place); plaintext over an encrypted store fails +with ErrEncryptedStore (decrypt offline with storage.MigrateToPlaintext); an interrupted +migration fails with ErrMigrationIncomplete until rerun. Service.ReencryptStorage() rewrites +values under the active key while the node runs; after that old keys can be removed. + ## Gotchas -- bind_addr defaults to 127.0.0.1. Set it explicitly for a cluster spanning hosts. +- bind_addr defaults to 127.0.0.1. Set it explicitly for a cluster spanning hosts. It is also the + address recorded in membership entries, so other servers must be able to reach it. +- peers only bootstrap the cluster. After the first membership change the log is the source of + truth; changing peers in config does nothing. +- Migrating to or from encryption rewrites values in place; BoltDB free pages and Badger value + logs can keep old plaintext until compaction. Rebuild from an empty path if that matters. ## Not implemented yet -- gRPC transport, cluster membership changes, leadership transfer, linearizable reads, - encryption at rest, and discovery other than the static peer list in the extension. +- Linearizable reads, and discovery other than the static peer list in the extension. diff --git a/extensions/consensus/raft/cluster_transport_test.go b/extensions/consensus/raft/cluster_transport_test.go index 04b74c974..3cad0927c 100644 --- a/extensions/consensus/raft/cluster_transport_test.go +++ b/extensions/consensus/raft/cluster_transport_test.go @@ -38,6 +38,8 @@ func startNetworkCluster(t *testing.T, kind string, size int) []*clusterMember { tr = transport.NewTCPTransport(transport.TCPTransportConfig{NodeID: id, Address: "127.0.0.1"}, lg) case "http": tr = transport.NewHTTPTransport(transport.HTTPTransportConfig{NodeID: id, Address: "127.0.0.1"}, lg) + case "grpc": + tr = transport.NewGRPCTransport(transport.GRPCTransportConfig{NodeID: id, Address: "127.0.0.1"}, lg) } if err := tr.Start(ctx); err != nil { @@ -178,3 +180,8 @@ func TestClusterElectsAndReplicatesOverHTTP(t *testing.T) { func TestClusterElectsAndReplicatesOverTCP(t *testing.T) { testClusterOverTransport(t, "tcp") } + +// The same over the gRPC transport. +func TestClusterElectsAndReplicatesOverGRPC(t *testing.T) { + testClusterOverTransport(t, "grpc") +} diff --git a/extensions/consensus/raft/config.go b/extensions/consensus/raft/config.go index d254ac276..96ad0f370 100644 --- a/extensions/consensus/raft/config.go +++ b/extensions/consensus/raft/config.go @@ -14,6 +14,17 @@ type Config struct { NodeID string `json:"node_id" yaml:"node_id"` ClusterID string `json:"cluster_id" yaml:"cluster_id"` + // Address and Port are where other members reach this node. They are + // recorded in configuration entries so servers added later can find it. + Address string `json:"address" yaml:"address"` + Port int `json:"port" yaml:"port"` + + // Join starts the node with an empty configuration: it never starts an + // election and waits for the leader to add it with AddNode. Use it for a + // server joining an existing cluster; a node that bootstraps with itself + // as a voter would disrupt the cluster it joins. + Join bool `json:"join" yaml:"join"` + // Timing parameters ElectionTimeoutMin time.Duration `json:"election_timeout_min" yaml:"election_timeout_min"` ElectionTimeoutMax time.Duration `json:"election_timeout_max" yaml:"election_timeout_max"` diff --git a/extensions/consensus/raft/log.go b/extensions/consensus/raft/log.go index 6d029fd35..549786219 100644 --- a/extensions/consensus/raft/log.go +++ b/extensions/consensus/raft/log.go @@ -14,6 +14,15 @@ import ( // snapshotMetaKey holds the index and term of the latest snapshot. const snapshotMetaKey = "snapshot_meta" +// snapshotMeta is stored under snapshotMetaKey. +type snapshotMeta struct { + Index uint64 `json:"index"` + Term uint64 `json:"term"` + // Config is the cluster configuration as of Index, so membership + // survives compaction of the configuration entries that built it. + Config *internal.ClusterConfiguration `json:"config,omitempty"` +} + // Log represents the replicated log. // // Every entry after the last snapshot is held in memory in a slice addressed @@ -34,6 +43,10 @@ type Log struct { // Snapshot state snapshotIndex uint64 snapshotTerm uint64 + + // snapshotConfig is the cluster configuration recorded with the snapshot + // that was on disk when the log was loaded. + snapshotConfig *internal.ClusterConfiguration } // NewLog creates a log and loads any entries already held in storage. @@ -208,6 +221,32 @@ func (l *Log) SnapshotTerm() uint64 { return l.snapshotTerm } +// SnapshotConfig returns the cluster configuration recorded with the +// snapshot found when the log was loaded, or nil. +func (l *Log) SnapshotConfig() *internal.ClusterConfiguration { + l.mu.RLock() + defer l.mu.RUnlock() + + return l.snapshotConfig +} + +// ConfigEntries returns the configuration entries after the snapshot, in +// order. +func (l *Log) ConfigEntries() []internal.LogEntry { + l.mu.RLock() + defer l.mu.RUnlock() + + var out []internal.LogEntry + + for _, e := range l.entries { + if e.Type == internal.EntryConfig { + out = append(out, e) + } + } + + return out +} + // Count returns the number of log entries. func (l *Log) Count() int { l.mu.RLock() @@ -358,21 +397,18 @@ func (l *Log) InstallSnapshot(index, term uint64) error { // load reads the snapshot metadata and every contiguous entry after it. func (l *Log) load() error { - snapshotMeta, err := l.storage.Get([]byte(snapshotMetaKey)) + metaBytes, err := l.storage.Get([]byte(snapshotMetaKey)) switch { - case err == nil && len(snapshotMeta) > 0: - var meta struct { - Index uint64 `json:"index"` - Term uint64 `json:"term"` - } - - if err := json.Unmarshal(snapshotMeta, &meta); err != nil { + case err == nil && len(metaBytes) > 0: + var meta snapshotMeta + if err := json.Unmarshal(metaBytes, &meta); err != nil { return fmt.Errorf("failed to decode snapshot metadata: %w", err) } l.snapshotIndex = meta.Index l.snapshotTerm = meta.Term + l.snapshotConfig = meta.Config case err != nil && !isNotFound(err): return fmt.Errorf("failed to read snapshot metadata: %w", err) } diff --git a/extensions/consensus/raft/log_safety_test.go b/extensions/consensus/raft/log_safety_test.go index 7f46f41f9..6fa13bf1a 100644 --- a/extensions/consensus/raft/log_safety_test.go +++ b/extensions/consensus/raft/log_safety_test.go @@ -5,6 +5,7 @@ import ( "errors" "sync/atomic" "testing" + "time" "github.com/xraph/forge" "github.com/xraph/forge/extensions/consensus/internal" @@ -39,6 +40,18 @@ func newTestNode(t *testing.T, id string, st internal.Storage) *Node { return n } +// voteReady makes the candidates voting members and forgets the last leader +// contact, so vote requests are judged on term and log alone. +func voteReady(n *Node, candidates ...string) { + for _, c := range candidates { + n.AddPeer(c) + } + + n.mu.Lock() + n.lastLeaderContact = time.Time{} + n.mu.Unlock() +} + func ents(term, from, to uint64) []internal.LogEntry { var out []internal.LogEntry for i := from; i <= to; i++ { @@ -116,6 +129,8 @@ func TestDelayedDuplicateDoesNotShrinkLog(t *testing.T) { t.Fatalf("commitIndex = %d, want 10", n.commitIndex) } + voteReady(n, "c") + vote, err := n.RequestVote(context.Background(), &internal.RequestVoteRequest{ Term: 3, CandidateID: "c", LastLogIndex: 5, LastLogTerm: 2, }) @@ -195,6 +210,8 @@ func TestRestartReloadsLogAndState(t *testing.T) { Term: 3, LeaderID: "l2", PrevLogIndex: 5, PrevLogTerm: 2, Entries: ents(3, 6, 6), LeaderCommit: 6, }) + voteReady(n, "c", "other") + if _, err := n.RequestVote(context.Background(), &internal.RequestVoteRequest{ Term: 4, CandidateID: "c", LastLogIndex: 6, LastLogTerm: 3, }); err != nil { @@ -202,6 +219,7 @@ func TestRestartReloadsLogAndState(t *testing.T) { } n2 := newTestNode(t, "f", st) // same storage, new process + voteReady(n2, "c", "other") if n2.log.LastIndex() != 6 || n2.log.LastTerm() != 3 { t.Fatalf("after restart LastIndex=%d LastTerm=%d, want 6 and 3", n2.log.LastIndex(), n2.log.LastTerm()) @@ -282,6 +300,7 @@ func TestVoteNotGrantedWhenPersistFails(t *testing.T) { st := &flakyStorage{MemoryStorage: newMemStorage(t)} n := newTestNode(t, "f", st) + voteReady(n, "c") st.failWrites.Store(true) vote, _ := n.RequestVote(context.Background(), &internal.RequestVoteRequest{Term: 1, CandidateID: "c"}) @@ -294,6 +313,7 @@ func TestVoteNotGrantedWhenPersistFails(t *testing.T) { func TestNoCandidateIsFavoured(t *testing.T) { n := newTestNode(t, "f", newMemStorage(t)) n.handleAppendEntries(internal.AppendEntriesRequest{Term: 2, LeaderID: "l", Entries: ents(2, 1, 5)}) + voteReady(n, "node-1") vote, _ := n.RequestVote(context.Background(), &internal.RequestVoteRequest{ Term: 3, CandidateID: "node-1", LastLogIndex: 1, LastLogTerm: 1, diff --git a/extensions/consensus/raft/membership.go b/extensions/consensus/raft/membership.go new file mode 100644 index 000000000..3bcf3ee9e --- /dev/null +++ b/extensions/consensus/raft/membership.go @@ -0,0 +1,617 @@ +package raft + +import ( + "context" + "encoding/json" + "fmt" + "slices" + "sync" + "time" + + "github.com/xraph/forge" + "github.com/xraph/forge/errors" + "github.com/xraph/forge/extensions/consensus/internal" +) + +var ( + // ErrConfigChangeInProgress is returned when a membership change is + // requested while another one has not committed yet. Changes are made one + // server at a time (Raft dissertation section 4.1). + ErrConfigChangeInProgress = errors.New("raft: a membership change is already in progress") + + // ErrLeadershipTransferInProgress is returned for client requests and + // membership changes while the leader is handing over leadership. + ErrLeadershipTransferInProgress = errors.New("raft: leadership transfer in progress") + + // ErrLeadershipTransferFailed is returned when the target did not take + // over within an election timeout. The old leader keeps leading. + ErrLeadershipTransferFailed = errors.New("raft: leadership transfer did not complete in time") + + // ErrLearnerNotCaughtUp is returned by AddNode when the new server did not + // catch up with the log in time. It is removed again. + ErrLearnerNotCaughtUp = errors.New("raft: new server did not catch up with the log") +) + +// configEntry is a cluster configuration and the log index that introduced +// it. Index 0 is the bootstrap configuration from AddPeer calls. +type configEntry struct { + index uint64 + cfg internal.ClusterConfiguration + bootstrap bool +} + +// Configuration returns the current cluster configuration. It takes effect +// as soon as its entry is appended, before it commits. +func (n *Node) Configuration() internal.ClusterConfiguration { + n.mu.RLock() + defer n.mu.RUnlock() + + return n.currentConfigLocked().Clone() +} + +func (n *Node) currentConfigLocked() internal.ClusterConfiguration { + return n.configs[len(n.configs)-1].cfg +} + +// configAtLocked returns the configuration in force at log index. +func (n *Node) configAtLocked(index uint64) internal.ClusterConfiguration { + for _, c := range slices.Backward(n.configs) { + if c.index <= index { + return c.cfg + } + } + + return n.configs[0].cfg +} + +// bootstrapConfig is the configuration before any configuration entry: this +// node as the only voter, or nothing at all for a node that joins an existing +// cluster. +func (n *Node) bootstrapConfig() configEntry { + cfg := internal.ClusterConfiguration{} + if !n.config.Join { + cfg.Members = []internal.ClusterMember{{ + ID: n.id, Address: n.config.Address, Port: n.config.Port, Voter: true, + }} + } + + return configEntry{cfg: cfg, bootstrap: true} +} + +// rebuildConfigsLocked resets the configuration history to base followed by +// every configuration entry still in the log, then applies the result. +func (n *Node) rebuildConfigsLocked(base configEntry) { + n.configs = []configEntry{base} + + for _, e := range n.log.ConfigEntries() { + if e.Index <= base.index { + continue + } + + if cfg, err := decodeConfig(e.Data); err == nil { + n.configs = append(n.configs, configEntry{index: e.Index, cfg: cfg}) + } else { + n.logger.Error("ignoring unreadable configuration entry", + forge.F("node_id", n.id), + forge.F("index", e.Index), + forge.F("error", err), + ) + } + } + + n.applyConfigLocked() +} + +// restoreConfigs builds the configuration history at startup from the +// snapshot and the log. +func (n *Node) restoreConfigs() { + n.mu.Lock() + defer n.mu.Unlock() + + base := n.bootstrapConfig() + + if cfg := n.log.SnapshotConfig(); cfg != nil { + base = configEntry{index: n.log.SnapshotIndex(), cfg: cfg.Clone()} + } + + n.rebuildConfigsLocked(base) +} + +// addBootstrapPeer adds a voter to the bootstrap configuration. Once the +// log or a snapshot holds a configuration, membership only changes through +// AddNode and RemoveNode, and the call is ignored. +func (n *Node) addBootstrapPeer(peerID, address string, port int) { + n.mu.Lock() + defer n.mu.Unlock() + + if n.config.Join || !n.configs[0].bootstrap { + return + } + + base := &n.configs[0].cfg + for i, m := range base.Members { + if m.ID == peerID { + if address != "" { + base.Members[i].Address, base.Members[i].Port = address, port + } + + return + } + } + + base.Members = append(base.Members, internal.ClusterMember{ID: peerID, Address: address, Port: port, Voter: true}) + + if len(n.configs) == 1 { + n.applyConfigLocked() + } +} + +// AddPeerAddress adds a voter, with its network address, to the bootstrap +// configuration, like AddPeer. The address is recorded in configuration +// entries so servers that join later can reach it. +func (n *Node) AddPeerAddress(peerID, address string, port int) { + n.addBootstrapPeer(peerID, address, port) +} + +// appendConfigLocked records a configuration entry that was just appended. +func (n *Node) appendConfigLocked(index uint64, cfg internal.ClusterConfiguration) { + n.configs = append(n.configs, configEntry{index: index, cfg: cfg}) + n.applyConfigLocked() + + n.logger.Info("cluster configuration changed", + forge.F("node_id", n.id), + forge.F("index", index), + forge.F("voters", cfg.Voters()), + forge.F("members", len(cfg.Members)), + ) +} + +// truncateConfigsLocked drops configurations whose entries were truncated +// from the log, returning to the one before them. +func (n *Node) truncateConfigsLocked(after uint64) { + keep := len(n.configs) + for keep > 1 && n.configs[keep-1].index > after { + keep-- + } + + if keep != len(n.configs) { + n.configs = n.configs[:keep] + n.applyConfigLocked() + } +} + +// compactConfigsLocked forgets configurations older than the one in force +// at the snapshot index. +func (n *Node) compactConfigsLocked(snapshotIndex uint64) { + first := 0 + + for i := range n.configs { + if n.configs[i].index <= snapshotIndex { + first = i + } + } + + n.configs = n.configs[first:] +} + +// applyConfigLocked makes the replication state match the current +// configuration: every other member, voter or learner, gets a peer entry and +// a transport route; servers no longer in the configuration lose their peer +// entry, so they are neither replicated to nor counted. +func (n *Node) applyConfigLocked() { + cfg := n.currentConfigLocked() + lastIndex := n.log.LastIndex() + + n.peersLock.Lock() + + for _, m := range cfg.Members { + if m.ID == n.id { + continue + } + + if p, ok := n.peers[m.ID]; ok { + if m.Address != "" { + p.Address, p.Port = m.Address, m.Port + } + } else { + n.peers[m.ID] = &PeerState{ + ID: m.ID, Address: m.Address, Port: m.Port, + NextIndex: lastIndex + 1, LastContact: time.Now(), ReplicationMu: sync.Mutex{}, + } + n.nextIndex[m.ID] = lastIndex + 1 + n.matchIndex[m.ID] = 0 + } + + if m.Address != "" { + if err := n.transport.AddPeer(m.ID, m.Address, m.Port); err != nil && !errors.Is(err, internal.ErrPeerExists) { + n.logger.Warn("failed to add transport route for cluster member", + forge.F("node_id", n.id), + forge.F("peer", m.ID), + forge.F("error", err), + ) + } + } + } + + for id := range n.peers { + if _, ok := cfg.Member(id); ok { + continue + } + + // The transport route stays: a removed leader still needs answers + // to the AppendEntries that commit its own removal. + delete(n.peers, id) + delete(n.nextIndex, id) + delete(n.matchIndex, id) + } + + n.peersLock.Unlock() +} + +// applyAppendedConfigsLocked records configuration entries among entries a +// follower just appended. Configurations take effect on append. +func (n *Node) applyAppendedConfigsLocked(entries []internal.LogEntry) { + for _, e := range entries { + if e.Type != internal.EntryConfig { + continue + } + + cfg, err := decodeConfig(e.Data) + if err != nil { + n.logger.Error("ignoring unreadable configuration entry", + forge.F("node_id", n.id), + forge.F("index", e.Index), + forge.F("error", err), + ) + + continue + } + + n.appendConfigLocked(e.Index, cfg) + } +} + +// votersLocked returns the voting members other than this node, and whether +// this node votes. +func (n *Node) votersLocked() (others []string, selfVotes bool) { + for _, id := range n.currentConfigLocked().Voters() { + if id == n.id { + selfVotes = true + } else { + others = append(others, id) + } + } + + return others, selfVotes +} + +func decodeConfig(data []byte) (internal.ClusterConfiguration, error) { + var cfg internal.ClusterConfiguration + if err := json.Unmarshal(data, &cfg); err != nil { + return cfg, fmt.Errorf("decode cluster configuration: %w", err) + } + + return cfg, nil +} + +// AddNode adds a server to the cluster. It first joins as a learner that +// receives the log without voting; once it has caught up it is promoted to a +// voter. Adding it as a voter straight away would let a slow, empty server +// count towards majorities and stall commits while it catches up (section +// 4.2.1). Each step is its own configuration entry, committed before the next +// is proposed. If the server does not catch up in time it is removed again +// and ErrLearnerNotCaughtUp is returned. +func (n *Node) AddNode(ctx context.Context, nodeID, address string, port int) error { + if nodeID == "" { + return errors.New("raft: node ID is required") + } + + if err := n.beginChange(); err != nil { + return err + } + defer n.endChange() + + n.mu.RLock() + current := n.currentConfigLocked().Clone() + n.mu.RUnlock() + + if m, ok := current.Member(nodeID); ok && m.Voter { + return nil + } else if !ok { + learner := current.Clone() + learner.Members = append(learner.Members, internal.ClusterMember{ID: nodeID, Address: address, Port: port}) + + if err := n.proposeConfig(ctx, learner); err != nil { + return fmt.Errorf("add %s as learner: %w", nodeID, err) + } + } + + if err := n.waitCaughtUp(ctx, nodeID); err != nil { + rollback := n.Configuration() + rollback.Members = withoutMember(rollback.Members, nodeID) + + rollbackCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), n.config.ElectionTimeoutMax*4) + defer cancel() + + if rbErr := n.proposeConfig(rollbackCtx, rollback); rbErr != nil { + return errors.Join(err, fmt.Errorf("remove learner %s again: %w", nodeID, rbErr)) + } + + return err + } + + promoted := n.Configuration() + for i := range promoted.Members { + if promoted.Members[i].ID == nodeID { + promoted.Members[i].Voter = true + } + } + + if err := n.proposeConfig(ctx, promoted); err != nil { + return fmt.Errorf("promote %s to voter: %w", nodeID, err) + } + + return nil +} + +// RemoveNode removes a server from the cluster. Removing the leader is +// allowed: it keeps leading until the new configuration commits (without +// counting itself), then steps down so the remaining servers elect a leader. +func (n *Node) RemoveNode(ctx context.Context, nodeID string) error { + if err := n.beginChange(); err != nil { + return err + } + defer n.endChange() + + cfg := n.Configuration() + if _, ok := cfg.Member(nodeID); !ok { + return nil + } + + cfg.Members = withoutMember(cfg.Members, nodeID) + if len(cfg.Voters()) == 0 { + return errors.New("raft: cannot remove the last voting member") + } + + return n.proposeConfig(ctx, cfg) +} + +func withoutMember(members []internal.ClusterMember, id string) []internal.ClusterMember { + out := make([]internal.ClusterMember, 0, len(members)) + + for _, m := range members { + if m.ID != id { + out = append(out, m) + } + } + + return out +} + +// beginChange claims the single membership change slot. +func (n *Node) beginChange() error { + n.mu.Lock() + defer n.mu.Unlock() + + if n.GetRole() != internal.RoleLeader { + return internal.NewNotLeaderError(n.id, n.GetLeader()) + } + + if n.transferTarget != "" { + return ErrLeadershipTransferInProgress + } + + if n.changing || n.configs[len(n.configs)-1].index > n.commitIndex { + return ErrConfigChangeInProgress + } + + n.changing = true + + return nil +} + +func (n *Node) endChange() { + n.mu.Lock() + n.changing = false + n.mu.Unlock() +} + +// proposeConfig appends a configuration entry, which takes effect at once, +// and waits until it is committed and applied. +func (n *Node) proposeConfig(ctx context.Context, cfg internal.ClusterConfiguration) error { + data, err := json.Marshal(cfg) + if err != nil { + return fmt.Errorf("encode cluster configuration: %w", err) + } + + entry := internal.LogEntry{Type: internal.EntryConfig, Data: data} + + return n.appendAndWait(ctx, entry, true, func(index uint64) { + n.appendConfigLocked(index, cfg) + }) +} + +// waitCaughtUp waits until a learner holds every committed entry, bounded +// by ctx and twenty election timeouts. +func (n *Node) waitCaughtUp(ctx context.Context, nodeID string) error { + deadline := time.Now().Add(20 * n.config.ElectionTimeoutMax) + tick := max(n.config.HeartbeatInterval/2, 5*time.Millisecond) + + for { + n.mu.RLock() + leader := n.GetRole() == internal.RoleLeader + match := n.matchIndex[nodeID] + target := n.commitIndex + n.mu.RUnlock() + + if !leader { + return internal.NewNotLeaderError(n.id, n.GetLeader()) + } + + if match >= target { + return nil + } + + if time.Now().After(deadline) { + return fmt.Errorf("%w: %s holds index %d, commit index is %d", ErrLearnerNotCaughtUp, nodeID, match, target) + } + + n.triggerReplication() + + select { + case <-ctx.Done(): + return ctx.Err() + case <-n.doneCh(): + return internal.ErrNotStarted + case <-time.After(tick): + } + } +} + +// TransferLeadership hands leadership to target (dissertation section 3.10). +// The leader stops accepting client requests and membership changes, brings +// the target's log up to date, and sends it TimeoutNow so it starts an +// election at once. If no new leader has taken over within an election +// timeout the transfer is abandoned, the leader resumes normal operation and +// ErrLeadershipTransferFailed is returned. +func (n *Node) TransferLeadership(ctx context.Context, targetNodeID string) error { + n.mu.Lock() + + if n.GetRole() != internal.RoleLeader { + n.mu.Unlock() + + return internal.NewNotLeaderError(n.id, n.GetLeader()) + } + + if targetNodeID == n.id { + n.mu.Unlock() + + return nil + } + + if !n.currentConfigLocked().IsVoter(targetNodeID) { + n.mu.Unlock() + + return fmt.Errorf("raft: %s is not a voting member", targetNodeID) + } + + if n.transferTarget != "" { + n.mu.Unlock() + + return ErrLeadershipTransferInProgress + } + + if n.changing { + n.mu.Unlock() + + return ErrConfigChangeInProgress + } + + term := n.currentTerm + n.transferTarget = targetNodeID + n.mu.Unlock() + + n.logger.Info("transferring leadership", + forge.F("node_id", n.id), + forge.F("target", targetNodeID), + forge.F("term", term), + ) + + err := n.runTransfer(ctx, targetNodeID, term) + + n.mu.Lock() + n.transferTarget = "" + n.mu.Unlock() + + if err != nil { + n.logger.Warn("leadership transfer abandoned", + forge.F("node_id", n.id), + forge.F("target", targetNodeID), + forge.F("error", err), + ) + } + + return err +} + +func (n *Node) runTransfer(ctx context.Context, target string, term uint64) error { + ctx, cancel := context.WithTimeout(ctx, n.config.ElectionTimeoutMax) + defer cancel() + + tick := max(n.config.HeartbeatInterval/4, 2*time.Millisecond) + + stillLeading := func() bool { + n.mu.RLock() + defer n.mu.RUnlock() + + return n.GetRole() == internal.RoleLeader && n.currentTerm == term + } + + // Bring the target up to date. No new entries arrive meanwhile. + for { + n.mu.RLock() + caughtUp := n.matchIndex[target] >= n.log.LastIndex() + n.mu.RUnlock() + + if caughtUp { + break + } + + if !stillLeading() { + return nil + } + + n.triggerReplication() + + select { + case <-ctx.Done(): + return fmt.Errorf("%w: %s did not catch up", ErrLeadershipTransferFailed, target) + case <-time.After(tick): + } + } + + if _, err := n.call(ctx, target, internal.MessageTypeTimeoutNow, + &internal.TimeoutNowRequest{Term: term, LeaderID: n.id}); err != nil && stillLeading() { + return fmt.Errorf("%w: TimeoutNow to %s: %v", ErrLeadershipTransferFailed, target, err) //nolint:errorlint // the first error is the sentinel + } + + // Wait for the target's election to depose this leader. + for stillLeading() { + select { + case <-ctx.Done(): + return fmt.Errorf("%w: %s did not take over", ErrLeadershipTransferFailed, target) + case <-time.After(tick): + } + } + + return nil +} + +// handleTimeoutNow starts an election at once when the current leader asks. +func (n *Node) handleTimeoutNow(from string, req internal.TimeoutNowRequest) internal.TimeoutNowResponse { + n.mu.RLock() + resp := internal.TimeoutNowResponse{Term: n.currentTerm, NodeID: n.id} + ok := req.Term == n.currentTerm && from == req.LeaderID && n.currentConfigLocked().IsVoter(n.id) + n.mu.RUnlock() + + if !ok { + return resp + } + + n.logger.Info("starting election on leader's request", + forge.F("node_id", n.id), + forge.F("leader", req.LeaderID), + ) + + resp.Success = true + + go n.startElectionWith(true) + + return resp +} + +// transferBlocksLocked reports whether client writes must wait for a +// leadership transfer. +func (n *Node) transferBlocksLocked() bool { + return n.transferTarget != "" +} diff --git a/extensions/consensus/raft/membership_test.go b/extensions/consensus/raft/membership_test.go new file mode 100644 index 000000000..41c24a187 --- /dev/null +++ b/extensions/consensus/raft/membership_test.go @@ -0,0 +1,670 @@ +package raft + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net" + "reflect" + "sort" + "strconv" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/xraph/forge" + "github.com/xraph/forge/extensions/consensus/internal" + "github.com/xraph/forge/extensions/consensus/statemachine" + "github.com/xraph/forge/extensions/consensus/storage" + "github.com/xraph/forge/extensions/consensus/transport" +) + +// mcMember is a TCP cluster member that can be stopped, restarted on the +// same port and storage, or started in join mode. +type mcMember struct { + id string + port int + store *storage.MemoryStorage + node *Node + tr *transport.TCPTransport + sm *statemachine.MemoryStateMachine + running bool +} + +type memberCluster struct { + t *testing.T + mu sync.Mutex + members map[string]*mcMember +} + +func newMemberCluster(t *testing.T, size int) *memberCluster { + t.Helper() + + c := &memberCluster{t: t, members: map[string]*mcMember{}} + + var initial []*mcMember + for i := range size { + initial = append(initial, c.add(fmt.Sprintf("n%d", i+1))) + } + + for _, m := range initial { + c.open(m, false) + } + + for _, m := range initial { + for _, other := range initial { + if other != m { + m.node.AddPeerAddress(other.id, "127.0.0.1", other.port) + } + } + + c.run(m) + } + + t.Cleanup(func() { + for _, m := range c.all() { + c.stop(m) + } + }) + + return c +} + +func (c *memberCluster) add(id string) *mcMember { + m := &mcMember{id: id, store: newMemStorage(c.t)} + + c.mu.Lock() + c.members[id] = m + c.mu.Unlock() + + return m +} + +func (c *memberCluster) all() []*mcMember { + c.mu.Lock() + defer c.mu.Unlock() + + out := make([]*mcMember, 0, len(c.members)) + for _, m := range c.members { + out = append(out, m) + } + + sort.Slice(out, func(i, j int) bool { return out[i].id < out[j].id }) + + return out +} + +// open creates the member's transport and node without starting the node. +func (c *memberCluster) open(m *mcMember, join bool) { + c.t.Helper() + + lg := forge.NewNoopLogger() + m.tr = transport.NewTCPTransport(transport.TCPTransportConfig{NodeID: m.id, Address: "127.0.0.1", Port: m.port}, lg) + + if err := m.tr.Start(context.Background()); err != nil { + c.t.Fatal(err) + } + + _, p, _ := net.SplitHostPort(m.tr.GetAddress()) + m.port, _ = strconv.Atoi(p) + m.sm = statemachine.NewMemoryStateMachine(statemachine.MemoryStateMachineConfig{}, lg) + + node, err := NewNode(Config{ + NodeID: m.id, + Address: "127.0.0.1", + Port: m.port, + Join: join, + HeartbeatInterval: 50 * time.Millisecond, + ElectionTimeoutMin: 300 * time.Millisecond, + ElectionTimeoutMax: 600 * time.Millisecond, + }, lg, m.sm, m.tr, m.store) + if err != nil { + c.t.Fatal(err) + } + + m.node = node +} + +// run gives the transport a route to every other running member and starts +// the node. Membership itself comes from the bootstrap peers or the log. +func (c *memberCluster) run(m *mcMember) { + c.t.Helper() + + for _, other := range c.all() { + if other != m && other.port != 0 { + _ = m.tr.AddPeer(other.id, "127.0.0.1", other.port) + } + } + + if err := m.node.Start(context.Background()); err != nil { + c.t.Fatal(err) + } + + m.running = true +} + +// join starts a new server in join mode, ready to be added by the leader. +func (c *memberCluster) join(id string) *mcMember { + m := c.add(id) + c.open(m, true) + c.run(m) + + return m +} + +// restart stops a member and starts it again from its storage. +func (c *memberCluster) restart(m *mcMember) { + c.stop(m) + c.open(m, false) + + for _, other := range c.all() { + if other != m { + m.node.AddPeerAddress(other.id, "127.0.0.1", other.port) + } + } + + c.run(m) +} + +func (c *memberCluster) stop(m *mcMember) { + if !m.running { + return + } + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + _ = m.node.Stop(ctx) + _ = m.tr.Stop(ctx) + m.running = false +} + +func (c *memberCluster) leader() *mcMember { + c.t.Helper() + + deadline := time.Now().Add(15 * time.Second) + + for time.Now().Before(deadline) { + var leaders []*mcMember + + for _, m := range c.all() { + if m.running && m.node.IsLeader() { + leaders = append(leaders, m) + } + } + + if len(leaders) == 1 { + return leaders[0] + } + + time.Sleep(20 * time.Millisecond) + } + + c.t.Fatal("no single leader elected") + + return nil +} + +func voters(cfg internal.ClusterConfiguration) []string { + v := cfg.Voters() + sort.Strings(v) + + return v +} + +// waitVoters waits until every listed running member sees exactly want as +// its voters. +func (c *memberCluster) waitVoters(want []string, members ...*mcMember) { + c.t.Helper() + + deadline := time.Now().Add(15 * time.Second) + + for _, m := range members { + for !reflect.DeepEqual(voters(m.node.Configuration()), want) { + if time.Now().After(deadline) { + c.t.Fatalf("%s voters %v, want %v", m.id, voters(m.node.Configuration()), want) + } + + time.Sleep(20 * time.Millisecond) + } + } +} + +// proposer keeps proposing to whoever leads until stopped. +type proposer struct { + stop chan struct{} + done chan struct{} + applied atomic.Int64 +} + +func (c *memberCluster) startProposer() *proposer { + p := &proposer{stop: make(chan struct{}), done: make(chan struct{})} + + go func() { + defer close(p.done) + + for i := 0; ; i++ { + select { + case <-p.stop: + return + default: + } + + for _, m := range c.all() { + if !m.running || !m.node.IsLeader() { + continue + } + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + cmd := fmt.Sprintf(`{"type":"set","payload":{"key":"bg%d","value":"v"}}`, i) + + if m.node.Propose(ctx, []byte(cmd)) == nil { + p.applied.Add(1) + } + + cancel() + } + + time.Sleep(10 * time.Millisecond) + } + }() + + return p +} + +func (p *proposer) halt() { + close(p.stop) + <-p.done +} + +// waitSameState waits until every listed member has applied the leader's +// commit index and holds the same state. +func (c *memberCluster) waitSameState(leader *mcMember, members ...*mcMember) { + c.t.Helper() + + commit := leader.node.GetCommitIndex() + for _, m := range members { + waitApplied(c.t, m.node, commit) + } + + want := leader.sm.GetState() + for _, m := range members { + if got := m.sm.GetState(); !reflect.DeepEqual(got, want) { + c.t.Fatalf("%s has %d keys, leader %s has %d", m.id, len(got), leader.id, len(want)) + } + } +} + +// A three node cluster grows to five and shrinks back to three while a +// client keeps writing, and every member ends with the same state. +func TestMembershipGrowAndShrinkWhileReplicating(t *testing.T) { + c := newMemberCluster(t, 3) + c.leader() + + p := c.startProposer() + + n4 := c.join("n4") + n5 := c.join("n5") + + for _, m := range []*mcMember{n4, n5} { + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + err := c.leader().node.AddNode(ctx, m.id, "127.0.0.1", m.port) + + cancel() + + if err != nil { + t.Fatalf("add %s: %v", m.id, err) + } + } + + all := c.all() + c.waitVoters([]string{"n1", "n2", "n3", "n4", "n5"}, all...) + + for _, id := range []string{"n5", "n4"} { + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + err := c.leader().node.RemoveNode(ctx, id) + + cancel() + + if err != nil { + t.Fatalf("remove %s: %v", id, err) + } + } + + p.halt() + + if p.applied.Load() == 0 { + t.Fatal("no client write succeeded during the membership changes") + } + + core := []*mcMember{c.members["n1"], c.members["n2"], c.members["n3"]} + c.waitVoters([]string{"n1", "n2", "n3"}, core...) + + c.stop(n4) + c.stop(n5) + + leader := c.leader() + propose(t, leader.node, "after", "shrink") + c.waitSameState(leader, core...) +} + +// A second change is refused while the first has not finished. +func TestMembershipOneChangeAtATime(t *testing.T) { + c := newMemberCluster(t, 3) + leader := c.leader() + + // Nothing listens for "ghost", so it never catches up. + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + + first := make(chan error, 1) + + go func() { first <- leader.node.AddNode(ctx, "ghost", "127.0.0.1", 1) }() + + deadline := time.Now().Add(5 * time.Second) + + for { + if _, ok := leader.node.Configuration().Member("ghost"); ok { + break + } + + if time.Now().After(deadline) { + t.Fatal("ghost was never added as a learner") + } + + time.Sleep(5 * time.Millisecond) + } + + if err := leader.node.RemoveNode(context.Background(), "n3"); !errors.Is(err, ErrConfigChangeInProgress) { + t.Fatalf("concurrent RemoveNode returned %v, want ErrConfigChangeInProgress", err) + } + + if err := <-first; err == nil { + t.Fatal("adding a server that never caught up succeeded") + } + + // The learner was rolled back and it never voted. + if _, ok := leader.node.Configuration().Member("ghost"); ok { + t.Fatal("the learner that never caught up is still a member") + } + + c.waitVoters([]string{"n1", "n2", "n3"}, c.all()...) +} + +// Removing the leader commits without it, after which it steps down, the +// others elect a new leader, and the old one never disrupts them. +func TestMembershipRemoveLeader(t *testing.T) { + c := newMemberCluster(t, 3) + old := c.leader() + propose(t, old.node, "before", "removal") + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + if err := old.node.RemoveNode(ctx, old.id); err != nil { + t.Fatalf("remove leader: %v", err) + } + + deadline := time.Now().Add(5 * time.Second) + for old.node.IsLeader() { + if time.Now().After(deadline) { + t.Fatal("removed leader did not step down") + } + + time.Sleep(10 * time.Millisecond) + } + + var rest []*mcMember + + for _, m := range c.all() { + if m != old { + rest = append(rest, m) + } + } + + c.waitVoters(voters(rest[0].node.Configuration()), rest...) + + if voters := rest[0].node.Configuration().Voters(); len(voters) != 2 { + t.Fatalf("voters after removal: %v", voters) + } + + leader := c.leader() + if leader == old { + t.Fatal("the removed server leads again") + } + + propose(t, leader.node, "after", "removal") + c.waitSameState(leader, rest...) + + term := leader.node.GetTerm() + + time.Sleep(1500 * time.Millisecond) + + if leader.node.GetTerm() != term || !leader.node.IsLeader() { + t.Fatal("the removed server disrupted the new leader") + } +} + +// A server removed while it was down never learns of its removal. When it +// comes back it times out and campaigns, but members ignore it, so the +// leader and term stay put. +func TestRemovedServerCannotDisrupt(t *testing.T) { + c := newMemberCluster(t, 3) + leader := c.leader() + + var victim *mcMember + + for _, m := range c.all() { + if m != leader { + victim = m + + break + } + } + + c.stop(victim) + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + if err := leader.node.RemoveNode(ctx, victim.id); err != nil { + t.Fatalf("remove %s: %v", victim.id, err) + } + + term := leader.node.GetTerm() + + c.restart(victim) + + // The victim still believes it is a voter and keeps raising its term. + deadline := time.Now().Add(3 * time.Second) + for victim.node.GetTerm() <= term+1 && time.Now().Before(deadline) { + time.Sleep(20 * time.Millisecond) + } + + if victim.node.GetTerm() <= term { + t.Fatal("the removed server never campaigned; the test proves nothing") + } + + if !leader.node.IsLeader() || leader.node.GetTerm() != term { + t.Fatalf("leader term moved from %d to %d (leader=%v)", term, leader.node.GetTerm(), leader.node.IsLeader()) + } + + propose(t, leader.node, "still", "leading") +} + +// Membership survives a restart and reaches a server that was down while the +// log was compacted, through InstallSnapshot. +func TestMembershipSurvivesRestartAndSnapshot(t *testing.T) { + c := newMemberCluster(t, 3) + leader := c.leader() + + var offline *mcMember + + for _, m := range c.all() { + if m != leader { + offline = m + + break + } + } + + c.stop(offline) + + n4 := c.join("n4") + + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + + if err := leader.node.AddNode(ctx, "n4", "127.0.0.1", n4.port); err != nil { + t.Fatalf("add n4: %v", err) + } + + for i := range 10 { + propose(t, leader.node, fmt.Sprintf("k%d", i), "v") + } + + want := []string{"n1", "n2", "n3", "n4"} + + // Compact every running member, so the configuration entries only + // survive in snapshots. + for _, m := range c.all() { + if !m.running { + continue + } + + waitApplied(t, m.node, leader.node.GetCommitIndex()) + + if err := m.node.Snapshot(); err != nil { + t.Fatalf("%s snapshot: %v", m.id, err) + } + + if len(m.node.log.ConfigEntries()) != 0 { + t.Fatalf("%s still holds configuration entries after compaction", m.id) + } + } + + // A restart rebuilds the configuration from the snapshot. + c.restart(n4) + + if got := voters(n4.node.Configuration()); !reflect.DeepEqual(got, want) { + t.Fatalf("n4 voters after restart %v, want %v", got, want) + } + + // The server that missed the change gets it through InstallSnapshot. + c.restart(offline) + c.waitVoters(want, offline) + + leader = c.leader() + propose(t, leader.node, "final", "write") + c.waitSameState(leader, c.all()...) +} + +// Leadership moves to the chosen server, and a transfer to a server that is +// down is abandoned after an election timeout with the old leader intact. +func TestLeadershipTransfer(t *testing.T) { + c := newMemberCluster(t, 3) + leader := c.leader() + + var target, down *mcMember + + for _, m := range c.all() { + switch { + case m == leader: + case target == nil: + target = m + default: + down = m + } + } + + propose(t, leader.node, "before", "transfer") + + if err := leader.node.TransferLeadership(context.Background(), target.id); err != nil { + t.Fatalf("transfer to %s: %v", target.id, err) + } + + if got := c.leader(); got != target { + t.Fatalf("leader is %s, want %s", got.id, target.id) + } + + propose(t, target.node, "after", "transfer") + + c.stop(down) + + start := time.Now() + + err := target.node.TransferLeadership(context.Background(), down.id) + if !errors.Is(err, ErrLeadershipTransferFailed) { + t.Fatalf("transfer to a stopped server returned %v", err) + } + + if elapsed := time.Since(start); elapsed > 2*time.Second { + t.Fatalf("abandoning the transfer took %v", elapsed) + } + + if !target.node.IsLeader() { + t.Fatal("the leader lost leadership after an abandoned transfer") + } + + propose(t, target.node, "after", "abort") +} + +// Client writes are refused while a transfer is under way. +func TestTransferBlocksClientWrites(t *testing.T) { + n, _ := newLeader(t) + + n.mu.Lock() + n.transferTarget = "p" + n.mu.Unlock() + + if err := n.Propose(context.Background(), []byte("{}")); !errors.Is(err, ErrLeadershipTransferInProgress) { + t.Fatalf("Propose during transfer returned %v", err) + } + + if err := n.RemoveNode(context.Background(), "p"); !errors.Is(err, ErrLeadershipTransferInProgress) { + t.Fatalf("RemoveNode during transfer returned %v", err) + } +} + +// A follower that appended a configuration entry and then has it truncated +// by a new leader returns to the configuration before it. +func TestTruncatedConfigurationIsReverted(t *testing.T) { + n := newTestNode(t, "f", newMemStorage(t)) + n.AddPeer("l") + n.AddPeer("l2") + + base := voters(n.Configuration()) + + grown := n.Configuration() + grown.Members = append(grown.Members, internal.ClusterMember{ID: "x", Voter: true}) + + data := mustJSON(t, grown) + n.handleAppendEntries(internal.AppendEntriesRequest{ + Term: 1, LeaderID: "l", + Entries: []internal.LogEntry{{Index: 1, Term: 1, Type: internal.EntryConfig, Data: data}}, + }) + + if !n.Configuration().IsVoter("x") { + t.Fatal("configuration did not take effect on append") + } + + // A new leader overwrites index 1. + n.handleAppendEntries(internal.AppendEntriesRequest{Term: 2, LeaderID: "l2", Entries: ents(2, 1, 1)}) + + if got := voters(n.Configuration()); !reflect.DeepEqual(got, base) { + t.Fatalf("voters after truncation %v, want %v", got, base) + } +} + +func mustJSON(t *testing.T, cfg internal.ClusterConfiguration) []byte { + t.Helper() + + data, err := json.Marshal(cfg) + if err != nil { + t.Fatal(err) + } + + return data +} diff --git a/extensions/consensus/raft/node.go b/extensions/consensus/raft/node.go index d3e80e5b3..424b89677 100644 --- a/extensions/consensus/raft/node.go +++ b/extensions/consensus/raft/node.go @@ -74,15 +74,14 @@ type Node struct { lastHeartbeatMux sync.RWMutex // Synchronization - mu sync.RWMutex - snapshotCh chan SnapshotMsg - configChangeCh chan ConfigChangeMsg + mu sync.RWMutex + snapshotCh chan SnapshotMsg // Apply pipeline. applyNotify wakes the single applier goroutine when // commitIndex moves; applyWaiters holds the Apply calls waiting for their // entry, keyed by log index. Both are guarded by mu. applyNotify chan struct{} - applyWaiters map[uint64]applyWaiter + applyWaiters map[waiterKey]chan error // applyMu serialises everything that changes the state machine: applying // entries, taking a snapshot of it and restoring one. Lock order is @@ -96,6 +95,16 @@ type Node struct { // Guarded by mu. lastLeaderContact time.Time + // configs is the configuration history: the configuration in force at + // the snapshot (or the bootstrap one) followed by every configuration + // entry in the log. The last one is current. Guarded by mu. + configs []configEntry + // changing is set while AddNode or RemoveNode runs. Guarded by mu. + changing bool + // transferTarget is the node leadership is being handed to. Client + // requests are refused while it is set. Guarded by mu. + transferTarget string + // RPC correlation. Every outgoing request gets a fresh ID from requestSeq, // which the peer echoes in its response, so a late response can never be // matched to a newer request to the same peer. @@ -132,12 +141,7 @@ type snapshotReceive struct { index uint64 term uint64 data []byte -} - -// applyWaiter is an Apply call waiting for its entry to be applied. -type applyWaiter struct { - term uint64 - ch chan error + config *internal.ClusterConfiguration } // ApplyMsg represents a message to apply to the state machine. @@ -155,25 +159,6 @@ type SnapshotMsg struct { ResultCh chan error } -// ConfigChangeMsg represents a configuration change message. -type ConfigChangeMsg struct { - Type ConfigChangeType - NodeID string - Address string - Port int - ResultCh chan error -} - -// ConfigChangeType represents the type of configuration change. -type ConfigChangeType int - -const ( - // ConfigChangeAdd adds a node to the cluster. - ConfigChangeAdd ConfigChangeType = iota - // ConfigChangeRemove removes a node from the cluster. - ConfigChangeRemove -) - // NewNode creates a new Raft node. func NewNode( config Config, @@ -230,9 +215,8 @@ func NewNode( storage: storage, peers: make(map[string]*PeerState), snapshotCh: make(chan SnapshotMsg, 10), - configChangeCh: make(chan ConfigChangeMsg, 10), applyNotify: make(chan struct{}, 1), - applyWaiters: make(map[uint64]applyWaiter), + applyWaiters: make(map[waiterKey]chan error), pendingRequests: make(map[pendingKey]chan any), } @@ -256,6 +240,8 @@ func NewNode( return nil, fmt.Errorf("failed to restore snapshot: %w", err) } + n.restoreConfigs() + return n, nil } @@ -487,7 +473,7 @@ func (n *Node) reconcileEntriesLocked(entries []internal.LogEntry) error { } if entry.Index > lastIndex { - return n.log.AppendBatch(entries[i:]) + return n.appendFromLeaderLocked(entries[i:]) } term, _ := n.log.Term(entry.Index) @@ -504,12 +490,31 @@ func (n *Node) reconcileEntriesLocked(entries []internal.LogEntry) error { return fmt.Errorf("truncate conflicting entries from %d: %w", entry.Index, err) } - return n.log.AppendBatch(entries[i:]) + // Configurations take effect on append, so truncating their entries + // returns to the configuration before them. Callers still waiting on + // the removed entries, from when this node led, learn now that they + // were dropped instead of waiting for their deadline. + n.truncateConfigsLocked(entry.Index - 1) + n.failTruncatedWaitersLocked(entry.Index - 1) + + return n.appendFromLeaderLocked(entries[i:]) } return nil } +// appendFromLeaderLocked appends entries and puts any configuration among +// them into effect. +func (n *Node) appendFromLeaderLocked(entries []internal.LogEntry) error { + if err := n.log.AppendBatch(entries); err != nil { + return err + } + + n.applyAppendedConfigsLocked(entries) + + return nil +} + // handleRequestVote handles a RequestVote request. func (n *Node) handleRequestVote(req internal.RequestVoteRequest) internal.RequestVoteResponse { resp, _ := n.RequestVote(context.Background(), &req) @@ -562,6 +567,7 @@ func (n *Node) handleInstallSnapshot(req internal.InstallSnapshotRequest) intern leaderTerm: req.Term, index: req.LastIncludedIndex, term: req.LastIncludedTerm, + config: req.Configuration, } } @@ -594,7 +600,7 @@ func (n *Node) handleInstallSnapshot(req internal.InstallSnapshotRequest) intern n.snapshotRecv = nil n.mu.Unlock() - err := n.installSnapshot(recv.index, recv.term, recv.data) + err := n.installSnapshot(recv.index, recv.term, recv.data, recv.config) if err != nil { n.logger.Error("failed to install snapshot from leader", forge.F("node_id", n.id), @@ -625,7 +631,7 @@ func (n *Node) handleInstallSnapshot(req internal.InstallSnapshotRequest) intern // log up to index, persists it, and drops the log entries it covers. Entries // after index are kept when the log agrees with the snapshot at index; // otherwise the whole log is discarded (section 7). -func (n *Node) installSnapshot(index, term uint64, data []byte) error { +func (n *Node) installSnapshot(index, term uint64, data []byte, config *internal.ClusterConfiguration) error { n.applyMu.Lock() defer n.applyMu.Unlock() @@ -652,15 +658,16 @@ func (n *Node) installSnapshot(index, term uint64, data []byte) error { n.lastApplied = index n.commitIndex = max(n.commitIndex, index) - for waitIndex, waiter := range n.applyWaiters { - if waitIndex <= index { - waiter.ch <- errors.New("entry was superseded by a snapshot from the leader; its result is unknown") + n.failWaitersLocked(func(k waiterKey) bool { return k.index <= index }, errSupersededBySnapshot) - delete(n.applyWaiters, waitIndex) - } + // A leader always sends its configuration; fall back to what this node + // knew at that index for one that did not. + cfg := n.configAtLocked(index).Clone() + if config != nil { + cfg = config.Clone() } - if err := n.saveSnapshot(snapshot); err != nil { + if err := n.saveSnapshot(snapshot, cfg); err != nil { return fmt.Errorf("failed to persist snapshot %d: %w", index, err) } @@ -668,6 +675,11 @@ func (n *Node) installSnapshot(index, term uint64, data []byte) error { return fmt.Errorf("failed to drop log entries covered by snapshot %d: %w", index, err) } + n.rebuildConfigsLocked(configEntry{index: index, cfg: cfg}) + + // Entries after the snapshot that disagreed with it were discarded. + n.failTruncatedWaitersLocked(n.log.LastIndex()) + n.signalApply() return nil @@ -683,6 +695,18 @@ func (n *Node) Snapshot() error { // applied to the local state machine. It returns the state machine's error for // that entry, or an error when leadership is lost and the entry is replaced. func (n *Node) Apply(ctx context.Context, entry internal.LogEntry) error { + if entry.Type == internal.EntryConfig { + return errors.New("raft: configuration entries are written by AddNode and RemoveNode") + } + + return n.appendAndWait(ctx, entry, false, nil) +} + +// appendAndWait appends an entry on the leader and waits until it is +// committed and applied. onAppend runs under mu right after the append. +// Client entries are refused during a leadership transfer; membership +// changes have their own guard and pass skipTransferCheck. +func (n *Node) appendAndWait(ctx context.Context, entry internal.LogEntry, skipTransferCheck bool, onAppend func(index uint64)) error { n.mu.Lock() if n.GetRole() != internal.RoleLeader { @@ -691,6 +715,12 @@ func (n *Node) Apply(ctx context.Context, entry internal.LogEntry) error { return internal.NewNotLeaderError(n.id, n.GetLeader()) } + if !skipTransferCheck && n.transferBlocksLocked() { + n.mu.Unlock() + + return ErrLeadershipTransferInProgress + } + entry.Term = n.currentTerm entry.Index = n.log.LastIndex() + 1 entry.Created = time.Now() @@ -701,8 +731,11 @@ func (n *Node) Apply(ctx context.Context, entry internal.LogEntry) error { return fmt.Errorf("failed to append log entry: %w", err) } - resultCh := make(chan error, 1) - n.applyWaiters[entry.Index] = applyWaiter{term: entry.Term, ch: resultCh} + if onAppend != nil { + onAppend(entry.Index) + } + + resultCh := n.addWaiterLocked(entry.Index, entry.Term) // A single-node cluster is its own majority. n.advanceCommitIndex() @@ -727,9 +760,7 @@ func (n *Node) Apply(ctx context.Context, entry internal.LogEntry) error { } n.mu.Lock() - if w, ok := n.applyWaiters[entry.Index]; ok && w.ch == resultCh { - delete(n.applyWaiters, entry.Index) - } + n.removeWaiterLocked(entry.Index, entry.Term, resultCh) n.mu.Unlock() return err @@ -1007,29 +1038,13 @@ func (n *Node) deliverResponse(from string, requestID uint64, response any) { } } -// AddPeer adds a peer to the Raft node. +// AddPeer adds a voter to the bootstrap configuration, the membership used +// until the log or a snapshot holds a configuration entry. Call it before +// Start for every other initial member. Later changes go through AddNode and +// RemoveNode; AddPeer is ignored once a configuration has been recorded, and +// on a node configured to join an existing cluster. func (n *Node) AddPeer(peerID string) { - n.peersLock.Lock() - defer n.peersLock.Unlock() - - if _, exists := n.peers[peerID]; !exists { - n.peers[peerID] = &PeerState{ - ID: peerID, - NextIndex: 1, - MatchIndex: 0, - LastContact: time.Now(), - ReplicationMu: sync.Mutex{}, - } - - // Initialize nextIndex and matchIndex for the new peer - n.nextIndex[peerID] = 1 - n.matchIndex[peerID] = 0 - - n.logger.Info("added peer to raft node", - forge.F("node_id", n.id), - forge.F("peer_id", peerID), - ) - } + n.addBootstrapPeer(peerID, "", 0) } // PeerStatus is what this node knows about one peer. @@ -1059,10 +1074,10 @@ func (n *Node) Peers() []PeerStatus { return out } -// HasQuorum reports whether this node is in touch with a working majority. -// A leader needs responses from a majority (itself included) within the -// maximum election timeout; a follower needs to have heard from a leader -// within that time. +// HasQuorum reports whether this node is in touch with a working majority +// of the voting members. A leader needs responses from a majority (itself +// included when it votes) within the maximum election timeout; a follower +// needs to have heard from a leader within that time. func (n *Node) HasQuorum() bool { window := n.config.ElectionTimeoutMax now := time.Now() @@ -1074,16 +1089,31 @@ func (n *Node) HasQuorum() bool { return n.GetLeader() != "" && now.Sub(n.lastLeaderContact) <= window } + others, selfVotes := n.votersLocked() + + reachable := 0 + if selfVotes { + reachable++ + } + n.peersLock.RLock() defer n.peersLock.RUnlock() - reachable := 1 - - for _, p := range n.peers { - if now.Sub(p.LastContact) <= window { + for _, id := range others { + if p, ok := n.peers[id]; ok && now.Sub(p.LastContact) <= window { reachable++ } } - return reachable >= (len(n.peers)+1)/2+1 + return reachable >= quorumSize(len(others), selfVotes) +} + +// quorumSize is the majority of the voting members. +func quorumSize(otherVoters int, selfVotes bool) int { + voters := otherVoters + if selfVotes { + voters++ + } + + return voters/2 + 1 } diff --git a/extensions/consensus/raft/replication.go b/extensions/consensus/raft/replication.go index 0e03b848e..c8a812712 100644 --- a/extensions/consensus/raft/replication.go +++ b/extensions/consensus/raft/replication.go @@ -115,6 +115,7 @@ func (n *Node) sendSnapshot(peer *PeerState) bool { index := n.log.SnapshotIndex() snapshotTerm := n.log.SnapshotTerm() leader := n.GetRole() == internal.RoleLeader + cfg := n.configAtLocked(index).Clone() n.mu.RUnlock() if !leader { @@ -150,6 +151,7 @@ func (n *Node) sendSnapshot(peer *PeerState) bool { Offset: uint64(offset), Data: data[offset:end], Done: end == len(data), + Configuration: &cfg, } ctx, cancel := context.WithTimeout(n.ctx, 10*time.Second) @@ -312,17 +314,16 @@ func (n *Node) AppendEntries(ctx context.Context, req *internal.AppendEntriesReq } // advanceCommitIndex moves commitIndex to the highest index stored on a -// majority whose entry is from the current term. The caller holds n.mu. +// majority of the voting members whose entry is from the current term. The +// leader counts itself only while it is a voter. Once a configuration that +// removes the leader commits, the leader steps down. The caller holds n.mu. func (n *Node) advanceCommitIndex() { if n.GetRole() != internal.RoleLeader { return } - n.peersLock.RLock() - clusterSize := len(n.peers) + 1 - n.peersLock.RUnlock() - - majority := clusterSize/2 + 1 + others, selfVotes := n.votersLocked() + majority := quorumSize(len(others), selfVotes) lastLogIndex := n.log.LastIndex() newCommit := n.commitIndex @@ -334,10 +335,13 @@ func (n *Node) advanceCommitIndex() { break } - replicated := 1 // Count self + replicated := 0 + if selfVotes { + replicated++ + } - for _, matchIndex := range n.matchIndex { - if matchIndex >= index { + for _, id := range others { + if n.matchIndex[id] >= index { replicated++ } } @@ -356,6 +360,15 @@ func (n *Node) advanceCommitIndex() { ) n.signalApply() } + + latest := n.configs[len(n.configs)-1] + if !selfVotes && latest.index <= n.commitIndex { + n.logger.Info("stepping down: this leader is no longer a voting member", + forge.F("node_id", n.id), + forge.F("config_index", latest.index), + ) + n.stepDownLocked(n.currentTerm) + } } // signalApply wakes the applier. The caller holds n.mu. @@ -414,18 +427,9 @@ func (n *Node) applyNext() bool { n.mu.Lock() n.lastApplied = applyIndex - waiter, waiting := n.applyWaiters[applyIndex] - delete(n.applyWaiters, applyIndex) + n.resolveAppliedLocked(applyIndex, entry.Term, applyErr) n.mu.Unlock() - if waiting { - if waiter.term == entry.Term { - waiter.ch <- applyErr - } else { - waiter.ch <- errors.New("entry was replaced after a leadership change and was not applied") - } - } - return true } diff --git a/extensions/consensus/raft/request_id_test.go b/extensions/consensus/raft/request_id_test.go index 470f2b0f9..6e647bf27 100644 --- a/extensions/consensus/raft/request_id_test.go +++ b/extensions/consensus/raft/request_id_test.go @@ -219,7 +219,7 @@ func TestVoteFromOlderTermIsNotCounted(t *testing.T) { granted := make(chan bool, 1) - go func() { granted <- n.requestVote(peer, 5, 10, 2) }() + go func() { granted <- n.requestVote(peer, 5, 10, 2, false) }() req := tr.next(t) n.handleMessage(internal.Message{ diff --git a/extensions/consensus/raft/state.go b/extensions/consensus/raft/state.go index f69dfc327..09965dfec 100644 --- a/extensions/consensus/raft/state.go +++ b/extensions/consensus/raft/state.go @@ -64,10 +64,24 @@ func (n *Node) resetElectionTimerUnsafe() { } } -// startElection starts a new election. +// startElection starts a new election after an election timeout. func (n *Node) startElection() { + n.startElectionWith(false) +} + +// startElectionWith starts a new election. transfer marks an election +// requested by the leader through TimeoutNow. Only voting members run +// elections: learners, removed servers and servers waiting to join never do. +func (n *Node) startElectionWith(transfer bool) { n.mu.Lock() + others, selfVotes := n.votersLocked() + if !selfVotes { + n.mu.Unlock() + + return + } + // Transition to candidate n.setRole(internal.RoleCandidate) n.currentTerm++ @@ -100,22 +114,24 @@ func (n *Node) startElection() { forge.F("last_log_term", lastLogTerm), ) - // Request votes from all peers + // Request votes from the other voting members. n.peersLock.RLock() - peers := make([]*PeerState, 0, len(n.peers)) - for _, peer := range n.peers { - peers = append(peers, peer) + peers := make([]*PeerState, 0, len(others)) + for _, id := range others { + if peer, ok := n.peers[id]; ok { + peers = append(peers, peer) + } } n.peersLock.RUnlock() peerCount := len(peers) votes := 1 // Vote for self - votesNeeded := (peerCount+1)/2 + 1 + votesNeeded := quorumSize(len(others), true) - // If we have no peers, we are the majority. - if peerCount == 0 { + // If we have no other voters, we are the majority. + if votesNeeded <= 1 { n.becomeLeader(currentTerm) return @@ -126,7 +142,7 @@ func (n *Node) startElection() { for _, peer := range peers { go func(p *PeerState) { - voteCh <- n.requestVote(p, currentTerm, lastLogIndex, lastLogTerm) + voteCh <- n.requestVote(p, currentTerm, lastLogIndex, lastLogTerm, transfer) }(peer) } @@ -181,13 +197,14 @@ func (n *Node) startElection() { // requestVote sends a RequestVote RPC to a peer and reports whether the peer // granted its vote for this term. -func (n *Node) requestVote(peer *PeerState, term, lastLogIndex, lastLogTerm uint64) bool { +func (n *Node) requestVote(peer *PeerState, term, lastLogIndex, lastLogTerm uint64, transfer bool) bool { req := &internal.RequestVoteRequest{ Term: term, CandidateID: n.id, LastLogIndex: lastLogIndex, LastLogTerm: lastLogTerm, PreVote: n.config.PreVoteEnabled, + Transfer: transfer, } ctx, cancel := context.WithTimeout(n.ctx, 5*time.Second) @@ -230,6 +247,30 @@ func (n *Node) RequestVote(ctx context.Context, req *internal.RequestVoteRequest NodeID: n.id, } + // A server that is not a voting member in this node's configuration, + // such as one that was removed and never learned it, cannot win, and + // letting it bump the term would depose a working leader (section 4.2.3). + if !n.currentConfigLocked().IsVoter(req.CandidateID) { + n.logger.Debug("ignoring vote request from a non-voting server", + forge.F("candidate", req.CandidateID), + forge.F("term", req.Term), + ) + + return resp, nil + } + + // While a leader is known to be alive, a vote request is ignored without + // even adopting its term, unless the leader asked for this election to + // transfer leadership (sections 4.2.3 and 3.10). + if !req.Transfer && n.heardFromLeaderLocked() { + n.logger.Debug("ignoring vote request while the leader is alive", + forge.F("candidate", req.CandidateID), + forge.F("term", req.Term), + ) + + return resp, nil + } + // Reply false if term < currentTerm if req.Term < n.currentTerm { n.logger.Debug("rejecting vote - stale term", @@ -303,6 +344,27 @@ func (n *Node) RequestVote(ctx context.Context, req *internal.RequestVoteRequest return resp, nil } +// heardFromLeaderLocked reports whether this node is the leader or heard +// from one within the minimum election timeout, less a heartbeat interval to +// allow for followers that last heard from the leader at slightly different +// times. +func (n *Node) heardFromLeaderLocked() bool { + if n.GetRole() == internal.RoleLeader { + return true + } + + if n.GetLeader() == "" || n.lastLeaderContact.IsZero() { + return false + } + + window := n.config.ElectionTimeoutMin - n.config.HeartbeatInterval + if window <= 0 { + window = n.config.ElectionTimeoutMin + } + + return time.Since(n.lastLeaderContact) < window +} + // isLogUpToDate checks if the candidate's log is at least as up-to-date as ours. func (n *Node) isLogUpToDate(candidateIndex, candidateTerm uint64) bool { lastLogIndex := n.log.LastIndex() diff --git a/extensions/consensus/raft/waiters.go b/extensions/consensus/raft/waiters.go new file mode 100644 index 000000000..e0d7295ad --- /dev/null +++ b/extensions/consensus/raft/waiters.go @@ -0,0 +1,76 @@ +package raft + +import ( + "github.com/xraph/forge/errors" +) + +// ErrProposalDropped is returned by Apply and Propose when the entry was +// removed from the log after a leadership change, before it committed. The +// entry was never applied, so the request can be retried. +var ErrProposalDropped = errors.New("raft: the proposed entry was dropped by a leadership change before it committed; it was not applied") + +// errSupersededBySnapshot is returned when a snapshot from a new leader +// replaced the log around a pending entry, so its outcome cannot be told. +var errSupersededBySnapshot = errors.New("raft: entry was superseded by a snapshot from the leader; its result is unknown") + +// waiterKey identifies one proposed entry. The term is part of the key: after +// a leadership change a different entry can occupy the same index, and it +// must not complete, or replace, the waiter of the entry it displaced. +type waiterKey struct { + index uint64 + term uint64 +} + +// addWaiterLocked registers an Apply call waiting for the entry at index and +// term. The caller holds n.mu. +func (n *Node) addWaiterLocked(index, term uint64) chan error { + ch := make(chan error, 1) + n.applyWaiters[waiterKey{index: index, term: term}] = ch + + return ch +} + +// removeWaiterLocked forgets a waiter that gave up. The caller holds n.mu. +func (n *Node) removeWaiterLocked(index, term uint64, ch chan error) { + key := waiterKey{index: index, term: term} + if n.applyWaiters[key] == ch { + delete(n.applyWaiters, key) + } +} + +// resolveAppliedLocked completes the waiter for the entry just applied and +// fails any waiter for a different entry that had the same index. The caller +// holds n.mu. +func (n *Node) resolveAppliedLocked(index, term uint64, applyErr error) { + for key, ch := range n.applyWaiters { + if key.index != index { + continue + } + + if key.term == term { + ch <- applyErr + } else { + ch <- ErrProposalDropped + } + + delete(n.applyWaiters, key) + } +} + +// failWaitersLocked fails every waiter whose key matches with err. The caller +// holds n.mu. +func (n *Node) failWaitersLocked(match func(waiterKey) bool, err error) { + for key, ch := range n.applyWaiters { + if match(key) { + ch <- err + + delete(n.applyWaiters, key) + } + } +} + +// failTruncatedWaitersLocked fails the waiters of entries removed from the +// log after index. The caller holds n.mu. +func (n *Node) failTruncatedWaitersLocked(after uint64) { + n.failWaitersLocked(func(k waiterKey) bool { return k.index > after }, ErrProposalDropped) +} diff --git a/extensions/consensus/raft/waiters_test.go b/extensions/consensus/raft/waiters_test.go new file mode 100644 index 000000000..75cfecff7 --- /dev/null +++ b/extensions/consensus/raft/waiters_test.go @@ -0,0 +1,91 @@ +package raft + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/xraph/forge/extensions/consensus/internal" +) + +// proposeAsync starts a Propose and returns its result channel once the +// entry is in the log. +func proposeAsync(t *testing.T, n *Node, want uint64) <-chan error { + t.Helper() + + done := make(chan error, 1) + + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + done <- n.Propose(ctx, []byte(`{"type":"set","payload":{"key":"k","value":"v"}}`)) + }() + + deadline := time.Now().Add(5 * time.Second) + for n.log.LastIndex() < want { + if time.Now().After(deadline) { + t.Fatal("proposal never reached the log") + } + + time.Sleep(time.Millisecond) + } + + return done +} + +func expectDropped(t *testing.T, done <-chan error) { + t.Helper() + + select { + case err := <-done: + if !errors.Is(err, ErrProposalDropped) { + t.Fatalf("Propose returned %v, want ErrProposalDropped", err) + } + case <-time.After(2 * time.Second): + t.Fatal("Propose still waiting after its entry was truncated") + } +} + +// A leader proposes an entry, loses its term before the entry commits, and a +// new leader overwrites that index. The waiting Propose fails at once with +// ErrProposalDropped instead of hanging until its deadline. +func TestProposalDroppedByTruncationFailsPromptly(t *testing.T) { + n, _ := newLeader(t) // term 2, log 1..10 in term 2, one peer "p" + done := proposeAsync(t, n, 11) + + n.handleAppendEntries(internal.AppendEntriesRequest{ + Term: 3, LeaderID: "p", PrevLogIndex: 10, PrevLogTerm: 2, Entries: ents(3, 11, 11), + }) + + expectDropped(t, done) +} + +// After losing an entry at index 11, the node leads again and a new entry +// lands at the same index. The old waiter must not be overwritten (and left +// hanging) or completed by the new entry; the new waiter completes normally. +func TestWaitersAreMatchedByIndexAndTerm(t *testing.T) { + n, _ := newLeader(t) + + // The old leader's entry at 11 is still pending when a newer leader's + // different entry is committed and applied at 11 (this node never saw + // the truncation, for example because the new entry came by snapshot). + n.mu.Lock() + oldWaiter := n.addWaiterLocked(11, 2) + newWaiter := n.addWaiterLocked(11, 4) + n.resolveAppliedLocked(11, 4, nil) + n.mu.Unlock() + + if err := <-oldWaiter; !errors.Is(err, ErrProposalDropped) { + t.Fatalf("waiter for the displaced entry got %v, want ErrProposalDropped", err) + } + + if err := <-newWaiter; err != nil { + t.Fatalf("waiter for the applied entry got %v", err) + } + + if len(n.applyWaiters) != 0 { + t.Fatalf("%d waiters left behind", len(n.applyWaiters)) + } +} diff --git a/extensions/consensus/raft/workers.go b/extensions/consensus/raft/workers.go index 02006406b..72abef911 100644 --- a/extensions/consensus/raft/workers.go +++ b/extensions/consensus/raft/workers.go @@ -2,6 +2,7 @@ package raft import ( "context" + "encoding/json" "fmt" "math" "time" @@ -89,6 +90,24 @@ func (n *Node) handleMessage(msg internal.Message) { resp := n.handleInstallSnapshot(*req) n.reply(msg, internal.MessageTypeInstallSnapshotResponse, &resp) + case internal.MessageTypeTimeoutNow: + req, ok := payloadAs[internal.TimeoutNowRequest](msg.Payload) + if !ok { + n.dropMalformed(msg) + + return + } + + resp := n.handleTimeoutNow(msg.From, *req) + n.reply(msg, internal.MessageTypeTimeoutNowResponse, &resp) + + case internal.MessageTypeTimeoutNowResponse: + if resp, ok := payloadAs[internal.TimeoutNowResponse](msg.Payload); ok { + n.deliverResponse(msg.From, msg.RequestID, resp) + } else { + n.dropMalformed(msg) + } + case internal.MessageTypeInstallSnapshotResponse: if resp, ok := payloadAs[internal.InstallSnapshotResponse](msg.Payload); ok { n.deliverResponse(msg.From, msg.RequestID, resp) @@ -227,6 +246,7 @@ func (n *Node) createSnapshot() error { index := n.lastApplied snapshotIndex := n.log.SnapshotIndex() term, ok := n.log.Term(index) + cfg := n.configAtLocked(index).Clone() n.mu.RUnlock() if index <= snapshotIndex { @@ -251,12 +271,16 @@ func (n *Node) createSnapshot() error { snapshot.Term = term snapshot.Created = time.Now() - if err := n.saveSnapshot(snapshot); err != nil { + if err := n.saveSnapshot(snapshot, cfg); err != nil { return fmt.Errorf("failed to save snapshot: %w", err) } n.mu.Lock() + err = n.log.Compact(index, term) + if err == nil { + n.compactConfigsLocked(index) + } n.mu.Unlock() if err != nil { @@ -274,167 +298,23 @@ func (n *Node) createSnapshot() error { return nil } -// saveSnapshot saves a snapshot to storage. -func (n *Node) saveSnapshot(snapshot *internal.Snapshot) error { - // Save snapshot data +// saveSnapshot saves a snapshot and its metadata, including the cluster +// configuration as of the snapshot index, to storage. +func (n *Node) saveSnapshot(snapshot *internal.Snapshot, cfg internal.ClusterConfiguration) error { snapshotKey := fmt.Appendf(nil, "snapshot_%d", snapshot.Index) if err := n.storage.Set(snapshotKey, snapshot.Data); err != nil { return fmt.Errorf("failed to save snapshot data: %w", err) } - // Save snapshot metadata - metaKey := []byte("snapshot_meta") - - metaValue := fmt.Sprintf(`{"index":%d,"term":%d}`, snapshot.Index, snapshot.Term) - if err := n.storage.Set(metaKey, []byte(metaValue)); err != nil { - return fmt.Errorf("failed to save snapshot metadata: %w", err) - } - - return nil -} - -// runConfigChangeProcessor processes configuration changes. -func (n *Node) runConfigChangeProcessor() { - defer n.wg.Done() - - for { - select { - case <-n.ctx.Done(): - return - - case msg := <-n.configChangeCh: - if err := n.processConfigChange(msg); err != nil { - n.logger.Error("failed to process config change", - forge.F("type", msg.Type), - forge.F("node_id", msg.NodeID), - forge.F("error", err), - ) - - msg.ResultCh <- err - } else { - msg.ResultCh <- nil - } - } - } -} - -// processConfigChange processes a configuration change. -func (n *Node) processConfigChange(msg ConfigChangeMsg) error { - // Configuration changes must go through Raft consensus - var configEntry internal.LogEntry - - configEntry.Type = internal.EntryConfig - - switch msg.Type { - case ConfigChangeAdd: - // Add node to configuration - n.peersLock.Lock() - n.peers[msg.NodeID] = &PeerState{ - ID: msg.NodeID, - Address: msg.Address, - Port: msg.Port, - NextIndex: n.log.LastIndex() + 1, - MatchIndex: 0, - } - n.peersLock.Unlock() - - n.logger.Info("added peer to cluster", - forge.F("peer_id", msg.NodeID), - forge.F("address", msg.Address), - forge.F("port", msg.Port), - ) - - case ConfigChangeRemove: - // Remove node from configuration - n.peersLock.Lock() - delete(n.peers, msg.NodeID) - n.peersLock.Unlock() - - n.logger.Info("removed peer from cluster", - forge.F("peer_id", msg.NodeID), - ) - - default: - return fmt.Errorf("unknown config change type: %d", msg.Type) - } - - return nil -} - -// AddNode adds a node to the cluster (must be called on leader). -func (n *Node) AddNode(ctx context.Context, nodeID, address string, port int) error { - if !n.IsLeader() { - return internal.NewNotLeaderError(n.id, n.GetLeader()) - } - - resultCh := make(chan error, 1) - msg := ConfigChangeMsg{ - Type: ConfigChangeAdd, - NodeID: nodeID, - Address: address, - Port: port, - ResultCh: resultCh, - } - - select { - case n.configChangeCh <- msg: - case <-ctx.Done(): - return ctx.Err() - } - - select { - case err := <-resultCh: - return err - case <-ctx.Done(): - return ctx.Err() - } -} - -// RemoveNode removes a node from the cluster (must be called on leader). -func (n *Node) RemoveNode(ctx context.Context, nodeID string) error { - if !n.IsLeader() { - return internal.NewNotLeaderError(n.id, n.GetLeader()) - } - - resultCh := make(chan error, 1) - msg := ConfigChangeMsg{ - Type: ConfigChangeRemove, - NodeID: nodeID, - ResultCh: resultCh, - } - - select { - case n.configChangeCh <- msg: - case <-ctx.Done(): - return ctx.Err() - } - - select { - case err := <-resultCh: - return err - case <-ctx.Done(): - return ctx.Err() + meta, err := json.Marshal(snapshotMeta{Index: snapshot.Index, Term: snapshot.Term, Config: &cfg}) + if err != nil { + return fmt.Errorf("failed to encode snapshot metadata: %w", err) } -} -// TransferLeadership transfers leadership to another node. -func (n *Node) TransferLeadership(ctx context.Context, targetNodeID string) error { - if !n.IsLeader() { - return internal.NewNotLeaderError(n.id, n.GetLeader()) + if err := n.storage.Set([]byte(snapshotMetaKey), meta); err != nil { + return fmt.Errorf("failed to save snapshot metadata: %w", err) } - n.logger.Info("transferring leadership", - forge.F("target", targetNodeID), - ) - - // Step down and let the target node win the next election - // In a production implementation, we would: - // 1. Ensure target is caught up - // 2. Stop sending heartbeats - // 3. Send a TimeoutNow message to target - // For now, just step down - n.stepDown(n.GetTerm()) - return nil } diff --git a/extensions/consensus/service.go b/extensions/consensus/service.go index 4852157c2..eb9cedc26 100644 --- a/extensions/consensus/service.go +++ b/extensions/consensus/service.go @@ -20,13 +20,12 @@ type Service struct { metrics forge.Metrics // Core components - node *raft.Node - raftNode internal.RaftNode - stateMachine internal.StateMachine - clusterManager internal.ClusterManager - transport internal.Transport - discovery internal.Discovery - storage internal.Storage + node *raft.Node + raftNode internal.RaftNode + stateMachine internal.StateMachine + transport internal.Transport + discovery internal.Discovery + storage internal.Storage // State startTime time.Time @@ -456,26 +455,41 @@ func (s *Service) GetClusterInfo() ClusterInfo { } } -// AddNode is not supported: cluster membership comes from the static peer -// list, and the raft implementation has no membership change protocol. -// Changing membership outside the log would risk two majorities. +// AddNode adds a server to the cluster through the raft log. Call it on the +// leader. The new server must already be running with join set, so it waits +// to be added instead of electing itself; it joins as a learner and becomes a +// voter once it has caught up. func (s *Service) AddNode(ctx context.Context, nodeID, address string, port int) error { - return ErrMembershipChangeUnsupported + node := s.raft() + if node == nil { + return ErrNotStarted + } + + return node.AddNode(ctx, nodeID, address, port) } -// RemoveNode is not supported, for the same reason as AddNode. +// RemoveNode removes a server from the cluster through the raft log. Call +// it on the leader. Removing the leader itself is allowed; it steps down once +// the change commits. func (s *Service) RemoveNode(ctx context.Context, nodeID string) error { - return ErrMembershipChangeUnsupported + node := s.raft() + if node == nil { + return ErrNotStarted + } + + return node.RemoveNode(ctx, nodeID) } -// TransferLeadership is not implemented. Use StepDown to let another node -// win the next election. +// TransferLeadership hands leadership to targetNodeID. Client writes are +// refused while it runs; if the target has not taken over within an election +// timeout the transfer is abandoned and this node keeps leading. func (s *Service) TransferLeadership(ctx context.Context, targetNodeID string) error { - if !s.IsLeader() { - return ErrNotLeader + node := s.raft() + if node == nil { + return ErrNotStarted } - return errors.New("leadership transfer is not implemented; use StepDown") + return node.TransferLeadership(ctx, targetNodeID) } // StepDown makes the leader return to follower so another node can be @@ -548,10 +562,11 @@ func (s *Service) GetStateMachine() StateMachine { return s.stateMachine } -// GetClusterManager returns nil: membership comes from the static peer list -// and cluster state is read from the raft node (see GetClusterInfo). +// GetClusterManager returns a ClusterManager backed by the raft +// configuration. Its AddNode and RemoveNode change membership through the +// log, like the service's. func (s *Service) GetClusterManager() ClusterManager { - return s.clusterManager + return &raftClusterManager{service: s} } // GetTransport returns the transport. diff --git a/extensions/consensus/service_cluster_test.go b/extensions/consensus/service_cluster_test.go index ac1bbb487..a9a28ab09 100644 --- a/extensions/consensus/service_cluster_test.go +++ b/extensions/consensus/service_cluster_test.go @@ -19,6 +19,7 @@ import ( "github.com/xraph/forge" "github.com/xraph/forge/extensions/consensus/internal" + "github.com/xraph/forge/extensions/consensus/raft" ) func freePorts(t *testing.T, n int) []int { @@ -128,14 +129,27 @@ func waitForServiceLeader(t *testing.T, services []*Service) *Service { func replicateAndRead(t *testing.T, services []*Service) { t.Helper() - leader := waitForServiceLeader(t, services) - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() cmd := Command{Type: "set", Payload: map[string]any{"key": "greeting", "value": "hello"}} - if err := leader.Apply(ctx, cmd); err != nil { - t.Fatalf("apply on leader %s: %v", leader.config.NodeID, err) + + // A leader elected a moment ago can lose its term before the entry + // commits. Apply then fails at once with ErrProposalDropped or a + // not-leader error, which a client retries on the new leader. + var leader *Service + + for attempt := 0; ; attempt++ { + leader = waitForServiceLeader(t, services) + + err := leader.Apply(ctx, cmd) + if err == nil { + break + } + + if attempt == 4 || (!errors.Is(err, raft.ErrProposalDropped) && !IsNotLeaderError(err)) { + t.Fatalf("apply on leader %s: %v", leader.config.NodeID, err) + } } for _, s := range services { @@ -168,7 +182,7 @@ func replicateAndRead(t *testing.T, services []*Service) { // Three services started from configuration elect a leader and replicate a // command over each network transport. func TestServiceClusterReplicates(t *testing.T) { - for _, kind := range []string{"tcp", "http"} { + for _, kind := range []string{"tcp", "http", "grpc"} { t.Run(kind, func(t *testing.T) { replicateAndRead(t, startServices(t, clusterConfigs(t, kind, 3))) }) @@ -181,7 +195,7 @@ func TestServiceClusterReplicates(t *testing.T) { func TestServiceClusterReplicatesOverMTLS(t *testing.T) { pki := newServicePKI(t) - for _, kind := range []string{"tcp", "http"} { + for _, kind := range []string{"tcp", "http", "grpc"} { t.Run(kind, func(t *testing.T) { cfgs := clusterConfigs(t, kind, 3) @@ -239,7 +253,7 @@ func TestServiceMTLSRejectsMismatchedCertificate(t *testing.T) { // Settings the service cannot honour fail with a clear error. func TestServiceRejectsUnsupportedSettings(t *testing.T) { cases := map[string]func(*internal.Config){ - "grpc transport": func(c *internal.Config) { c.Transport.Type = "grpc" }, + "quic transport": func(c *internal.Config) { c.Transport.Type = "quic" }, "encryption": func(c *internal.Config) { c.Security.EnableEncryption = true }, "dns discovery": func(c *internal.Config) { c.Discovery.Type = "dns" }, "postgres storage": func(c *internal.Config) { c.Storage.Type = "postgres" }, @@ -259,16 +273,6 @@ func TestServiceRejectsUnsupportedSettings(t *testing.T) { } } -// Membership changes are refused instead of being half applied. -func TestServiceRefusesMembershipChanges(t *testing.T) { - cfg := clusterConfigs(t, "tcp", 1)[0] - s := startServices(t, []internal.Config{cfg})[0] - - if err := s.AddNode(context.Background(), "n9", "127.0.0.1", 1); !errors.Is(err, ErrMembershipChangeUnsupported) { - t.Fatalf("AddNode returned %v", err) - } -} - type servicePKI struct { dir string caFile string diff --git a/extensions/consensus/service_components.go b/extensions/consensus/service_components.go index 0622420fe..a32115f11 100644 --- a/extensions/consensus/service_components.go +++ b/extensions/consensus/service_components.go @@ -17,12 +17,6 @@ import ( "github.com/xraph/forge/extensions/consensus/transport" ) -// ErrMembershipChangeUnsupported is returned by AddNode and RemoveNode. The -// raft implementation has no membership change protocol, so the cluster is -// the static peer list in the configuration. -var ErrMembershipChangeUnsupported = errors.New( - "consensus: cluster membership changes are not supported; configure peers statically") - // startComponents builds and starts storage, transport, state machine and // raft node from the configuration. On error the caller stops whatever was // started. @@ -36,6 +30,11 @@ func (s *Service) startComponents(ctx context.Context) error { return fmt.Errorf("failed to create storage: %w", err) } + store, err = protectStorage(s.config, store, s.logger) + if err != nil { + return fmt.Errorf("failed to set up storage encryption: %w", err) + } + if err := store.Start(ctx); err != nil { return fmt.Errorf("failed to start %s storage: %w", s.config.Storage.Type, err) } @@ -66,11 +65,16 @@ func (s *Service) startComponents(ctx context.Context) error { continue } - if err := tr.AddPeer(peer.ID, peer.Address, peer.Port); err != nil { + // The node may already route to this peer: membership restored from + // the log or a snapshot on restart adds routes for every member. + if err := tr.AddPeer(peer.ID, peer.Address, peer.Port); err != nil && !errors.Is(err, internal.ErrPeerExists) { return fmt.Errorf("failed to add peer %s: %w", peer.ID, err) } - node.AddPeer(peer.ID) + // Configured peers only seed the membership of a brand new cluster. + // Once the log or a snapshot holds a configuration this is ignored, + // and a joining node only needs the routes added above. + node.AddPeerAddress(peer.ID, peer.Address, peer.Port) } if err := node.Start(s.ctx); err != nil { @@ -189,8 +193,23 @@ func newTransport(cfg internal.Config, logger forge.Logger) (internal.Transport, TLSConfig: tlsConfig, RequirePeerIdentity: requireIdentity, }, logger), nil + case "grpc": + return transport.NewGRPCTransport(transport.GRPCTransportConfig{ + NodeID: cfg.NodeID, + Address: cfg.BindAddr, + Port: cfg.BindPort, + MaxConnections: cfg.Transport.MaxConnections, + ConnectionTimeout: cfg.Transport.ConnectionTimeout, + RequestTimeout: cfg.Transport.Timeout, + KeepAliveTime: cfg.Transport.KeepAliveInterval, + KeepAliveTimeout: cfg.Transport.KeepAliveTimeout, + IdleTimeout: cfg.Transport.IdleTimeout, + MaxMessageSize: cfg.Transport.MaxMessageSize, + TLSConfig: tlsConfig, + RequirePeerIdentity: requireIdentity, + }, logger), nil default: - return nil, fmt.Errorf("%w: transport type %q is not implemented; use tcp or http", + return nil, fmt.Errorf("%w: transport type %q is not implemented; use tcp, http or grpc", internal.ErrInvalidConfig, cfg.Transport.Type) } } @@ -230,6 +249,9 @@ func raftConfig(cfg internal.Config) raft.Config { return raft.Config{ NodeID: cfg.NodeID, ClusterID: cfg.ClusterID, + Address: cfg.BindAddr, + Port: cfg.BindPort, + Join: cfg.Join, HeartbeatInterval: cfg.Raft.HeartbeatInterval, ElectionTimeoutMin: cfg.Raft.ElectionTimeoutMin, ElectionTimeoutMax: cfg.Raft.ElectionTimeoutMax, @@ -245,41 +267,28 @@ func raftConfig(cfg internal.Config) raft.Config { } } -// clusterCounts returns the cluster size and how many members this node -// currently knows to be reachable. +// clusterCounts returns the number of members in the current configuration +// and how many of them this node currently knows to be reachable. func (s *Service) clusterCounts(node *raft.Node) (total, active int) { - total = len(s.peerConfigs()) + 1 - if node == nil { - return total, 0 + return len(s.config.Peers), 0 } - for _, n := range s.clusterNodes(node) { + nodes := s.clusterNodes(node) + + for _, n := range nodes { if n.Status == StatusActive { active++ } } - return total, active -} - -// peerConfigs returns the configured peers other than this node. -func (s *Service) peerConfigs() []internal.PeerConfig { - peers := make([]internal.PeerConfig, 0, len(s.config.Peers)) - - for _, p := range s.config.Peers { - if p.ID != s.config.NodeID { - peers = append(peers, p) - } - } - - return peers + return len(nodes), active } -// clusterNodes describes this node and its configured peers. A peer counts as -// active when the leader heard from it within the election timeout; followers -// cannot observe each other, so on a follower only itself and the current -// leader are reported active. +// clusterNodes describes every member of the current raft configuration, +// learners included. A member counts as active when the leader heard from it +// within the election timeout; followers cannot observe each other, so on a +// follower only itself and the current leader are reported active. func (s *Service) clusterNodes(node *raft.Node) []NodeInfo { stats := node.GetStats() window := s.config.Raft.ElectionTimeoutMax @@ -289,23 +298,22 @@ func (s *Service) clusterNodes(node *raft.Node) []NodeInfo { contacts[p.ID] = p.LastContact } - nodes := []NodeInfo{{ - ID: s.config.NodeID, - Address: s.config.BindAddr, - Port: s.config.BindPort, - Role: stats.Role, - Status: StatusActive, - Term: stats.Term, - }} + cfg := node.Configuration() + nodes := make([]NodeInfo, 0, len(cfg.Members)) - for _, p := range s.peerConfigs() { - info := NodeInfo{ID: p.ID, Address: p.Address, Port: p.Port, Role: RoleFollower, Status: StatusInactive} + for _, m := range cfg.Members { + info := NodeInfo{ + ID: m.ID, Address: m.Address, Port: m.Port, + Role: RoleFollower, Status: StatusInactive, + Metadata: map[string]any{"voter": m.Voter}, + } switch { - case p.ID == stats.Leader: - info.Role = RoleLeader - info.Status = StatusActive - case stats.Role == RoleLeader && time.Since(contacts[p.ID]) <= window: + case m.ID == s.config.NodeID: + info.Role, info.Status, info.Term = stats.Role, StatusActive, stats.Term + case m.ID == stats.Leader: + info.Role, info.Status = RoleLeader, StatusActive + case stats.Role == RoleLeader && time.Since(contacts[m.ID]) <= window: info.Status = StatusActive } diff --git a/extensions/consensus/service_encryption.go b/extensions/consensus/service_encryption.go new file mode 100644 index 000000000..c8e7a50d6 --- /dev/null +++ b/extensions/consensus/service_encryption.go @@ -0,0 +1,77 @@ +package consensus + +import ( + "fmt" + + "github.com/xraph/forge" + "github.com/xraph/forge/errors" + "github.com/xraph/forge/extensions/consensus/internal" + "github.com/xraph/forge/extensions/consensus/storage" +) + +// ErrStorageNotEncrypted is returned by ReencryptStorage when the service runs +// without security.enable_encryption. +var ErrStorageNotEncrypted = errors.New("consensus: storage encryption is not enabled") + +// protectStorage applies security.enable_encryption to the storage backend. +// With encryption the backend is wrapped in storage.EncryptedStorage, built +// from keys read from files or environment variables. Without it the backend +// is wrapped in a guard that refuses a store written with encryption, so +// ciphertext is never read as raft state. +func protectStorage(cfg internal.Config, store internal.Storage, logger forge.Logger) (internal.Storage, error) { + if !cfg.Security.EnableEncryption { + return storage.NewPlaintextGuard(store), nil + } + + sources := cfg.Security.EncryptionKeySources() + keys := make([]storage.KeySource, len(sources)) + + for i, src := range sources { + keys[i] = storage.KeySource{ID: src.ID, File: src.File, Env: src.Env, Value: src.Value} + } + + keyring, err := storage.LoadKeyring(storage.KeyringConfig{ + Keys: keys, + ActiveKeyID: cfg.Security.EncryptionActiveKeyID, + AllowInline: cfg.Security.AllowInlineEncryptionKey, + }, logger) + if err != nil { + return nil, err + } + + logger.Info("raft storage encryption enabled", + forge.F("cipher", "AES-256-GCM"), + forge.F("active_key_id", keyring.ActiveKeyID()), + forge.F("key_ids", keyring.KeyIDs()), + ) + + return storage.NewEncryptedStorage(store, storage.EncryptedStorageConfig{ + Keyring: keyring, + MigratePlaintext: cfg.Security.EncryptionMigratePlaintext, + }, logger) +} + +// ReencryptStorage re-encrypts every stored value that is not under the +// active key and returns how many it rewrote. It runs while the node serves +// requests. Afterwards the older keys can be removed from the configuration. +func (s *Service) ReencryptStorage() (int, error) { + s.mu.RLock() + started, store := s.started, s.storage + s.mu.RUnlock() + + if !started { + return 0, ErrNotStarted + } + + encrypted, ok := store.(*storage.EncryptedStorage) + if !ok { + return 0, ErrStorageNotEncrypted + } + + n, err := encrypted.Rekey() + if err != nil { + return n, fmt.Errorf("failed to re-encrypt storage: %w", err) + } + + return n, nil +} diff --git a/extensions/consensus/service_encryption_test.go b/extensions/consensus/service_encryption_test.go new file mode 100644 index 000000000..607392ed3 --- /dev/null +++ b/extensions/consensus/service_encryption_test.go @@ -0,0 +1,342 @@ +package consensus + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/base64" + "encoding/hex" + "io/fs" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/xraph/forge" + "github.com/xraph/forge/errors" + "github.com/xraph/forge/extensions/consensus/internal" + "github.com/xraph/forge/extensions/consensus/storage" +) + +func writeKeyFile(t *testing.T) string { + t.Helper() + + key := make([]byte, storage.KeySize) + if _, err := rand.Read(key); err != nil { + t.Fatal(err) + } + + path := filepath.Join(t.TempDir(), "raft.key") + if err := os.WriteFile(path, []byte(hex.EncodeToString(key)+"\n"), 0o600); err != nil { + t.Fatal(err) + } + + return path +} + +func encryptedClusterConfigs(t *testing.T, storageType string, size int) []internal.Config { + t.Helper() + + cfgs := clusterConfigs(t, "tcp", size) + + for i := range cfgs { + cfgs[i].Storage.Type = storageType + cfgs[i].Storage.Path = t.TempDir() + cfgs[i].Security.EnableEncryption = true + // Each node has its own key: encryption at rest is local to a node. + cfgs[i].Security.EncryptionKeyFile = writeKeyFile(t) + } + + return cfgs +} + +func startService(t *testing.T, cfg internal.Config) (*Service, error) { + t.Helper() + + s, err := NewConsensusService(cfg, forge.NewNoopLogger(), nil) + if err != nil { + t.Fatal(err) + } + + if err := s.Start(context.Background()); err != nil { + return nil, err + } + + t.Cleanup(func() { _ = s.Stop(context.Background()) }) + + return s, nil +} + +func stopServices(t *testing.T, services []*Service) { + t.Helper() + + for _, s := range services { + if err := s.Stop(context.Background()); err != nil { + t.Fatal(err) + } + } +} + +// applySet applies a set command through the current leader, retrying when +// an attempt fails: an entry appended by a leader that loses its term right +// away is dropped and its Apply returns raft.ErrProposalDropped. The command +// is idempotent. +func applySet(t *testing.T, services []*Service, key, value string) { + t.Helper() + + var err error + + for range 5 { + leader := waitForServiceLeader(t, services) + + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + err = leader.Apply(ctx, Command{Type: "set", Payload: map[string]any{"key": key, "value": value}}) + + cancel() + + if err == nil { + return + } + } + + t.Fatalf("apply %s: %v", key, err) +} + +func waitForValue(t *testing.T, services []*Service, key, want string) { + t.Helper() + + for _, s := range services { + deadline := time.Now().Add(10 * time.Second) + + for { + got, err := s.Read(context.Background(), map[string]any{"type": "get", "key": key}) + if err == nil && got == want { + break + } + + if time.Now().After(deadline) { + t.Fatalf("%s: read %s = %v, %v; want %q", s.config.NodeID, key, got, err, want) + } + + time.Sleep(20 * time.Millisecond) + } + } +} + +// plaintextForms returns the secret and the stable middle of its base64 +// encoding at each of the three byte alignments, since the log stores command +// bytes base64 encoded inside JSON. +func plaintextForms(secret string) [][]byte { + forms := [][]byte{[]byte(secret)} + + for pad := range 3 { + enc := base64.StdEncoding.EncodeToString(append(make([]byte, pad), secret...)) + forms = append(forms, []byte(enc[4:len(enc)-4])) + } + + return forms +} + +// assertNoPlaintext fails if any file under dir contains secret in any form. +func assertNoPlaintext(t *testing.T, dir, secret string) { + t.Helper() + + files := 0 + + err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() { + return err + } + + data, err := os.ReadFile(path) + if err != nil { + return err + } + + files++ + + for _, form := range plaintextForms(secret) { + if bytes.Contains(data, form) { + t.Errorf("%s contains plaintext %q", path, form) + } + } + + return nil + }) + if err != nil { + t.Fatal(err) + } + + if files == 0 { + t.Fatalf("no storage files under %s", dir) + } +} + +// A three node cluster with encryption on replicates, snapshots, keeps no +// plaintext on disk, and comes back with its data after a full restart. +func TestServiceEncryptedClusterReplicatesAndRestarts(t *testing.T) { + for _, storageType := range []string{"boltdb", "badger"} { + t.Run(storageType, func(t *testing.T) { + const secret = "launch-code-0451-unmistakable" + + cfgs := encryptedClusterConfigs(t, storageType, 3) + services := startServices(t, cfgs) + + applySet(t, services, "greeting", "hello") + waitForValue(t, services, "greeting", "hello") + applySet(t, services, "secret", secret) + waitForValue(t, services, "secret", secret) + + leader := waitForServiceLeader(t, services) + if err := leader.Snapshot(context.Background()); err != nil { + t.Fatalf("snapshot: %v", err) + } + + applySet(t, services, "after-snapshot", secret+"-2") + waitForValue(t, services, "after-snapshot", secret+"-2") + + stopServices(t, services) + + for _, cfg := range cfgs { + assertNoPlaintext(t, cfg.Storage.Path, secret) + } + + // Restart every node with the same configuration. + restarted := make([]*Service, len(cfgs)) + + for i, cfg := range cfgs { + s, err := startService(t, cfg) + if err != nil { + t.Fatalf("restart %s: %v", cfg.NodeID, err) + } + + restarted[i] = s + } + + waitForValue(t, restarted, "greeting", "hello") + waitForValue(t, restarted, "secret", secret) + waitForValue(t, restarted, "after-snapshot", secret+"-2") + }) + } +} + +// Encryption cannot be switched on over a plaintext store, or off over an +// encrypted one, without an explicit migration. +func TestServiceEncryptionModeMismatch(t *testing.T) { + cfg := clusterConfigs(t, "tcp", 1)[0] + cfg.Storage.Type = "boltdb" + cfg.Storage.Path = t.TempDir() + + s, err := startService(t, cfg) + if err != nil { + t.Fatal(err) + } + + applySet(t, []*Service{s}, "k", "plain-value-before-migration") + stopServices(t, []*Service{s}) + + enc := cfg + enc.Security.EnableEncryption = true + enc.Security.EncryptionKeyFile = writeKeyFile(t) + + if _, err := startService(t, enc); !errors.Is(err, storage.ErrPlaintextStore) { + t.Fatalf("encryption over a plaintext store: %v, want ErrPlaintextStore", err) + } + + enc.Security.EncryptionMigratePlaintext = true + + s, err = startService(t, enc) + if err != nil { + t.Fatalf("start with migration: %v", err) + } + + waitForValue(t, []*Service{s}, "k", "plain-value-before-migration") + stopServices(t, []*Service{s}) + + // Not asserted here: the file may still hold the old plaintext in free + // pages until the backend reuses or compacts them (see the README). + + if _, err := startService(t, cfg); !errors.Is(err, storage.ErrEncryptedStore) { + t.Fatalf("plaintext start over an encrypted store: %v, want ErrEncryptedStore", err) + } + + wrong := enc + wrong.Security.EncryptionKeyFile = writeKeyFile(t) + + if _, err := startService(t, wrong); !errors.Is(err, storage.ErrWrongKey) { + t.Fatalf("start with another key: %v, want ErrWrongKey", err) + } +} + +// Rotating keys through the service: add key 2, re-encrypt, then drop key 1. +func TestServiceReencryptStorageAfterRotation(t *testing.T) { + cfg := clusterConfigs(t, "tcp", 1)[0] + cfg.Storage.Type = "boltdb" + cfg.Storage.Path = t.TempDir() + cfg.Security.EnableEncryption = true + + key1, key2 := writeKeyFile(t), writeKeyFile(t) + cfg.Security.EncryptionKeyFile = key1 + + s, err := startService(t, cfg) + if err != nil { + t.Fatal(err) + } + + applySet(t, []*Service{s}, "k", "v1") + stopServices(t, []*Service{s}) + + cfg.Security.EncryptionKeyFile = "" + cfg.Security.EncryptionKeys = []internal.EncryptionKeyConfig{{ID: 1, File: key1}, {ID: 2, File: key2}} + + s, err = startService(t, cfg) + if err != nil { + t.Fatal(err) + } + + waitForValue(t, []*Service{s}, "k", "v1") + + n, err := s.ReencryptStorage() + if err != nil || n == 0 { + t.Fatalf("ReencryptStorage = %d, %v", n, err) + } + + stopServices(t, []*Service{s}) + + cfg.Security.EncryptionKeys = []internal.EncryptionKeyConfig{{ID: 2, File: key2}} + + s, err = startService(t, cfg) + if err != nil { + t.Fatalf("start with only key 2: %v", err) + } + + waitForValue(t, []*Service{s}, "k", "v1") +} + +// A key of the wrong size stops the service at start with a clear error that +// does not echo the key. +func TestServiceEncryptionRejectsBadKey(t *testing.T) { + cfg := clusterConfigs(t, "tcp", 1)[0] + cfg.Storage.Type = "boltdb" + cfg.Storage.Path = t.TempDir() + cfg.Security.EnableEncryption = true + cfg.Security.EncryptionKeyFile = filepath.Join(t.TempDir(), "short.key") + + if err := os.WriteFile(cfg.Security.EncryptionKeyFile, []byte("0123456789abcdef0123456789abcdef\n"), 0o600); err != nil { + t.Fatal(err) + } + + _, err := startService(t, cfg) + if !errors.Is(err, storage.ErrInvalidEncryptionKey) || !strings.Contains(err.Error(), "32") { + t.Fatalf("short key: %v, want ErrInvalidEncryptionKey", err) + } + + if strings.Contains(err.Error(), "0123456789abcdef") { + t.Fatalf("error echoes the key: %v", err) + } + + if _, err := (&Service{}).ReencryptStorage(); !errors.Is(err, ErrNotStarted) { + t.Fatalf("ReencryptStorage before start: %v", err) + } +} diff --git a/extensions/consensus/service_grpc_test.go b/extensions/consensus/service_grpc_test.go new file mode 100644 index 000000000..b2dea24b1 --- /dev/null +++ b/extensions/consensus/service_grpc_test.go @@ -0,0 +1,68 @@ +package consensus + +import ( + "context" + "testing" + "time" + + "github.com/xraph/forge/extensions/consensus/internal" +) + +// Over gRPC with mTLS, a node whose certificate names a different node is cut +// off: the others elect a leader and replicate, but its messages are refused +// and it receives nothing. +func TestServiceGRPCMTLSRejectsMismatchedCertificate(t *testing.T) { + pki := newServicePKI(t) + cfgs := clusterConfigs(t, "grpc", 3) + + for i := range cfgs { + name := cfgs[i].NodeID + if i == 2 { + name = "impostor" + } + + cert, key := pki.issue(t, name) + cfgs[i].Security = internal.SecurityConfig{ + EnableTLS: true, EnableMTLS: true, CertFile: cert, KeyFile: key, CAFile: pki.caFile, + } + } + + services := startServices(t, cfgs) + leader := waitForServiceLeader(t, services[:2]) + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + if err := leader.Apply(ctx, Command{Type: "set", Payload: map[string]any{"key": "k", "value": "v"}}); err != nil { + t.Fatal(err) + } + + time.Sleep(500 * time.Millisecond) + + if _, err := services[2].Read(ctx, map[string]any{"type": "get", "key": "k"}); err == nil { + t.Fatal("the node with a mismatched certificate received replicated data") + } + + if services[2].IsLeader() { + t.Fatal("the node with a mismatched certificate became leader") + } +} + +// A running gRPC cluster stops promptly, node by node, while the remaining +// nodes keep connections open to the ones already stopped. +func TestServiceGRPCClusterStopsPromptly(t *testing.T) { + services := startServices(t, clusterConfigs(t, "grpc", 3)) + replicateAndRead(t, services) + + for _, s := range services { + start := time.Now() + + if err := s.Stop(context.Background()); err != nil { + t.Fatalf("stop %s: %v", s.config.NodeID, err) + } + + if elapsed := time.Since(start); elapsed > 3*time.Second { + t.Fatalf("stopping %s took %v", s.config.NodeID, elapsed) + } + } +} diff --git a/extensions/consensus/service_membership.go b/extensions/consensus/service_membership.go new file mode 100644 index 000000000..cdffc3f00 --- /dev/null +++ b/extensions/consensus/service_membership.go @@ -0,0 +1,86 @@ +package consensus + +import ( + "context" + "time" + + "github.com/xraph/forge/errors" + "github.com/xraph/forge/extensions/consensus/internal" +) + +// clusterChangeTimeout bounds membership changes made through the +// ClusterManager interface, whose methods take no context. +const clusterChangeTimeout = 30 * time.Second + +// raftClusterManager implements ClusterManager on top of the raft +// configuration, so the container's ClusterManager reflects real membership. +type raftClusterManager struct { + service *Service +} + +var _ internal.ClusterManager = (*raftClusterManager)(nil) + +func (m *raftClusterManager) GetNodes() []internal.NodeInfo { + node := m.service.raft() + if node == nil { + return nil + } + + return m.service.clusterNodes(node) +} + +func (m *raftClusterManager) GetNode(nodeID string) (*internal.NodeInfo, error) { + for _, n := range m.GetNodes() { + if n.ID == nodeID { + return &n, nil + } + } + + return nil, internal.ErrNodeNotFound +} + +func (m *raftClusterManager) AddNode(nodeID, address string, port int) error { + ctx, cancel := context.WithTimeout(context.Background(), clusterChangeTimeout) + defer cancel() + + return m.service.AddNode(ctx, nodeID, address, port) +} + +func (m *raftClusterManager) RemoveNode(nodeID string) error { + ctx, cancel := context.WithTimeout(context.Background(), clusterChangeTimeout) + defer cancel() + + return m.service.RemoveNode(ctx, nodeID) +} + +// UpdateNode is not supported: member details change by removing and adding +// the member again. +func (m *raftClusterManager) UpdateNode(string, internal.NodeInfo) error { + return errors.New("consensus: members cannot be updated in place; remove and add them again") +} + +func (m *raftClusterManager) GetLeader() *internal.NodeInfo { + for _, n := range m.GetNodes() { + if n.Role == internal.RoleLeader { + return &n + } + } + + return nil +} + +func (m *raftClusterManager) HasQuorum() bool { + return m.service.hasQuorum() +} + +func (m *raftClusterManager) GetClusterSize() int { + total, _ := m.service.clusterCounts(m.service.raft()) + + return total +} + +func (m *raftClusterManager) GetHealthyNodes() int { + _, active := m.service.clusterCounts(m.service.raft()) + + return active +} diff --git a/extensions/consensus/service_membership_test.go b/extensions/consensus/service_membership_test.go new file mode 100644 index 000000000..973fadd07 --- /dev/null +++ b/extensions/consensus/service_membership_test.go @@ -0,0 +1,162 @@ +package consensus + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/xraph/forge" + "github.com/xraph/forge/extensions/consensus/admin" + "github.com/xraph/forge/extensions/consensus/raft" +) + +func readEventually(t *testing.T, s *Service, key, want string) { + t.Helper() + + deadline := time.Now().Add(10 * time.Second) + + for { + got, err := s.Read(t.Context(), map[string]any{"type": "get", "key": key}) + if err == nil && got == want { + return + } + + if time.Now().After(deadline) { + t.Fatalf("%s read %s = %v, %v; want %s", s.config.NodeID, key, got, err, want) + } + + time.Sleep(20 * time.Millisecond) + } +} + +// onLeader runs op on the current leader, retrying on errors a client would +// retry after a leadership change: the leader elected a moment ago can lose +// its term before op completes. +func onLeader(t *testing.T, services []*Service, op func(*Service) error) { + t.Helper() + + var err error + + for range 5 { + leader := waitForServiceLeader(t, services) + if err = op(leader); err == nil { + return + } + + if !IsNotLeaderError(err) && !errors.Is(err, raft.ErrProposalDropped) && + !errors.Is(err, raft.ErrConfigChangeInProgress) && !errors.Is(err, errAdminRetry) { + break + } + } + + t.Fatalf("operation on the leader failed: %v", err) +} + +// errAdminRetry marks a failed admin call so onLeader retries it. +var errAdminRetry = errors.New("admin call failed") + +func postAdmin(t *testing.T, router forge.Router, path string, body any) int { + t.Helper() + + data, err := json.Marshal(body) + if err != nil { + t.Fatal(err) + } + + req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, path, bytes.NewReader(data)) + req.Header.Set("Content-Type", "application/json") + + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + + return rec.Code +} + +// A cluster built from configuration grows by a joining server added through +// the admin API, hands leadership to it, and shrinks again through the +// ClusterManager, replicating writes throughout. +func TestServiceMembershipAndTransfer(t *testing.T) { + cfgs := clusterConfigs(t, "tcp", 4) + + // n1..n3 bootstrap the cluster; n4 knows where they are and waits to be + // added. + for i := range 3 { + cfgs[i].Peers = cfgs[i].Peers[:3] + } + + cfgs[3].Join = true + services := startServices(t, cfgs) + core, joiner := services[:3], services[3] + + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + + onLeader(t, core, func(s *Service) error { + return s.Apply(ctx, Command{Type: "set", Payload: map[string]any{"key": "a", "value": "1"}}) + }) + + if joiner.IsLeader() || joiner.GetTerm() != 0 { + t.Fatal("the joining server campaigned before it was added") + } + + onLeader(t, core, func(s *Service) error { + router := forge.NewRouter() + admin.NewAPI(s, nil, nil, forge.NewNoopLogger()).RegisterRoutes(router, "/consensus") + + if code := postAdmin(t, router, "/consensus/nodes/add", map[string]any{ + "node_id": "n4", "address": "127.0.0.1", "port": cfgs[3].BindPort, + }); code != http.StatusOK { + return fmt.Errorf("%w: admin add node: status %d", errAdminRetry, code) + } + + return nil + }) + + readEventually(t, joiner, "a", "1") + + if size := waitForServiceLeader(t, core).GetClusterManager().GetClusterSize(); size != 4 { + t.Fatalf("cluster size %d after adding n4, want 4", size) + } + + onLeader(t, services, func(s *Service) error { + if s == joiner { + return nil + } + + return s.TransferLeadership(ctx, "n4") + }) + + if got := waitForServiceLeader(t, services); got != joiner { + t.Fatalf("leader is %s, want n4", got.config.NodeID) + } + + onLeader(t, services, func(s *Service) error { return s.GetClusterManager().RemoveNode("n2") }) + + remaining := []*Service{services[0], services[2], joiner} + onLeader(t, remaining, func(s *Service) error { + return s.Apply(ctx, Command{Type: "set", Payload: map[string]any{"key": "b", "value": "2"}}) + }) + + for _, s := range remaining { + readEventually(t, s, "b", "2") + } + + current := waitForServiceLeader(t, remaining) + + info := current.GetClusterInfo() + if info.TotalNodes != 3 || info.Leader != current.config.NodeID { + t.Fatalf("cluster info after removing n2: %+v", info) + } + + for _, n := range info.Nodes { + if n.ID == "n2" { + t.Fatal("n2 is still listed as a member") + } + } +} diff --git a/extensions/consensus/service_restart_test.go b/extensions/consensus/service_restart_test.go new file mode 100644 index 000000000..a7bd51c38 --- /dev/null +++ b/extensions/consensus/service_restart_test.go @@ -0,0 +1,97 @@ +package consensus + +import ( + "context" + "reflect" + "sort" + "testing" + "time" + + "github.com/xraph/forge/extensions/consensus/internal" +) + +func diskClusterConfigs(t *testing.T, storageType string, size int) []internal.Config { + t.Helper() + + cfgs := clusterConfigs(t, "tcp", size) + for i := range cfgs { + cfgs[i].Storage.Type = storageType + cfgs[i].Storage.Path = t.TempDir() + } + + return cfgs +} + +func restartAll(t *testing.T, cfgs []internal.Config) []*Service { + t.Helper() + + services := make([]*Service, len(cfgs)) + + for i, cfg := range cfgs { + s, err := startService(t, cfg) + if err != nil { + t.Fatalf("restart %s: %v", cfg.NodeID, err) + } + + services[i] = s + } + + return services +} + +func sortedVoters(s *Service) []string { + v := s.raft().Configuration().Voters() + sort.Strings(v) + + return v +} + +// A plain (unencrypted) cluster on disk restarts with its data and its +// membership, whether membership is still the bootstrap peer list or came +// from a change in the log, and whether the log was compacted. +func TestServiceRestartKeepsDataAndMembership(t *testing.T) { + for _, storageType := range []string{"boltdb", "badger"} { + t.Run(storageType, func(t *testing.T) { + cfgs := diskClusterConfigs(t, storageType, 4) + for i := range 3 { + cfgs[i].Peers = cfgs[i].Peers[:3] + } + + cfgs[3].Join = true + + services := startServices(t, cfgs) + applySet(t, services[:3], "before", "growth") + + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + + onLeader(t, services[:3], func(s *Service) error { + return s.AddNode(ctx, "n4", "127.0.0.1", cfgs[3].BindPort) + }) + + applySet(t, services, "after", "growth") + waitForValue(t, services, "after", "growth") + + onLeader(t, services, func(s *Service) error { return s.Snapshot(ctx) }) + + applySet(t, services, "after", "snapshot") + waitForValue(t, services, "after", "snapshot") + stopServices(t, services) + + restarted := restartAll(t, cfgs) + + waitForValue(t, restarted, "before", "growth") + waitForValue(t, restarted, "after", "snapshot") + + want := []string{"n1", "n2", "n3", "n4"} + for _, s := range restarted { + if got := sortedVoters(s); !reflect.DeepEqual(got, want) { + t.Fatalf("%s voters after restart %v, want %v", s.config.NodeID, got, want) + } + } + + applySet(t, restarted, "post", "restart") + waitForValue(t, restarted, "post", "restart") + }) + } +} diff --git a/extensions/consensus/storage/boltdb.go b/extensions/consensus/storage/boltdb.go index 4df1607d8..ebc633286 100644 --- a/extensions/consensus/storage/boltdb.go +++ b/extensions/consensus/storage/boltdb.go @@ -16,6 +16,7 @@ import ( type BoltDBStorage struct { db *bolt.DB path string + options bolt.Options bucketName []byte logger forge.Logger started bool @@ -26,11 +27,18 @@ type BoltDBStorage struct { type BoltDBStorageConfig struct { Path string BucketName string - Timeout time.Duration + // Timeout is how long Start waits for the file lock held by another + // process. Defaults to one second. + Timeout time.Duration + // NoSync skips fsync after each commit. It is faster but a crash can lose + // writes the node already acknowledged, which breaks Raft's durability + // guarantees. Leave it false outside tests. NoSync bool NoGrowSync bool - ReadOnly bool - MmapFlags int + // ReadOnly opens the database without write access. The bucket must + // already exist. + ReadOnly bool + MmapFlags int } // NewBoltDBStorage creates a new BoltDB storage. @@ -43,8 +51,19 @@ func NewBoltDBStorage(config BoltDBStorageConfig, logger forge.Logger) (*BoltDBS config.BucketName = "consensus" } + if config.Timeout <= 0 { + config.Timeout = time.Second + } + return &BoltDBStorage{ - path: config.Path, + path: config.Path, + options: bolt.Options{ + Timeout: config.Timeout, + NoSync: config.NoSync, + NoGrowSync: config.NoGrowSync, + ReadOnly: config.ReadOnly, + MmapFlags: config.MmapFlags, + }, bucketName: []byte(config.BucketName), logger: logger, }, nil @@ -60,13 +79,33 @@ func (bs *BoltDBStorage) Start(ctx context.Context) error { } // Open database - db, err := bolt.Open(bs.path, 0600, &bolt.Options{ - Timeout: 1 * time.Second, - }) + options := bs.options + + db, err := bolt.Open(bs.path, 0o600, &options) if err != nil { return fmt.Errorf("failed to open boltdb database: %w", err) } + if options.ReadOnly { + err = db.View(func(tx *bolt.Tx) error { + if tx.Bucket(bs.bucketName) == nil { + return fmt.Errorf("bucket %q does not exist", bs.bucketName) + } + + return nil + }) + if err != nil { + db.Close() + + return fmt.Errorf("failed to open read-only boltdb database: %w", err) + } + + bs.db = db + bs.started = true + + return nil + } + // Create bucket if not exists err = db.Update(func(tx *bolt.Tx) error { _, err := tx.CreateBucketIfNotExists(bs.bucketName) diff --git a/extensions/consensus/storage/boltdb_options_test.go b/extensions/consensus/storage/boltdb_options_test.go new file mode 100644 index 000000000..6968c1309 --- /dev/null +++ b/extensions/consensus/storage/boltdb_options_test.go @@ -0,0 +1,99 @@ +package storage + +import ( + "context" + "path/filepath" + "testing" + "time" + + "github.com/xraph/forge" +) + +func openBolt(t *testing.T, cfg BoltDBStorageConfig) (*BoltDBStorage, error) { + t.Helper() + + bs, err := NewBoltDBStorage(cfg, forge.NewNoopLogger()) + if err != nil { + t.Fatal(err) + } + + return bs, bs.Start(context.Background()) +} + +// NoSync and NoGrowSync reach the database, and NoSync stays off by default. +func TestBoltDBAppliesSyncOptions(t *testing.T) { + dir := t.TempDir() + + def, err := openBolt(t, BoltDBStorageConfig{Path: filepath.Join(dir, "default.db")}) + if err != nil { + t.Fatal(err) + } + defer def.Close() + + if def.db.NoSync || def.db.NoGrowSync { + t.Fatalf("defaults: NoSync=%v NoGrowSync=%v, want both false", def.db.NoSync, def.db.NoGrowSync) + } + + fast, err := openBolt(t, BoltDBStorageConfig{Path: filepath.Join(dir, "fast.db"), NoSync: true, NoGrowSync: true}) + if err != nil { + t.Fatal(err) + } + defer fast.Close() + + if !fast.db.NoSync || !fast.db.NoGrowSync { + t.Fatalf("NoSync=%v NoGrowSync=%v, want both true", fast.db.NoSync, fast.db.NoGrowSync) + } +} + +// Timeout bounds the wait for a file lock held by another opener. +func TestBoltDBAppliesTimeout(t *testing.T) { + path := filepath.Join(t.TempDir(), "locked.db") + + holder, err := openBolt(t, BoltDBStorageConfig{Path: path}) + if err != nil { + t.Fatal(err) + } + defer holder.Close() + + start := time.Now() + + if _, err := openBolt(t, BoltDBStorageConfig{Path: path, Timeout: 150 * time.Millisecond}); err == nil { + t.Fatal("opened a database whose lock is held") + } + + if elapsed := time.Since(start); elapsed < 100*time.Millisecond || elapsed > 900*time.Millisecond { + t.Fatalf("waited %v for the lock, want about the 150ms timeout", elapsed) + } +} + +// ReadOnly opens an existing database without write access. +func TestBoltDBAppliesReadOnly(t *testing.T) { + path := filepath.Join(t.TempDir(), "ro.db") + + w, err := openBolt(t, BoltDBStorageConfig{Path: path}) + if err != nil { + t.Fatal(err) + } + + if err := w.Set([]byte("k"), []byte("v")); err != nil { + t.Fatal(err) + } + + if err := w.Close(); err != nil { + t.Fatal(err) + } + + ro, err := openBolt(t, BoltDBStorageConfig{Path: path, ReadOnly: true}) + if err != nil { + t.Fatal(err) + } + defer ro.Close() + + if got, err := ro.Get([]byte("k")); err != nil || string(got) != "v" { + t.Fatalf("read-only Get = %q, %v", got, err) + } + + if err := ro.Set([]byte("k"), []byte("x")); err == nil { + t.Fatal("wrote to a read-only database") + } +} diff --git a/extensions/consensus/storage/encryption.go b/extensions/consensus/storage/encryption.go new file mode 100644 index 000000000..de45440d5 --- /dev/null +++ b/extensions/consensus/storage/encryption.go @@ -0,0 +1,884 @@ +package storage + +import ( + "bytes" + "context" + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "encoding/binary" + "fmt" + "slices" + "strconv" + "sync" + + "github.com/xraph/forge" + "github.com/xraph/forge/errors" + "github.com/xraph/forge/extensions/consensus/internal" +) + +// Encryption at rest. +// +// EncryptedStorage wraps any internal.Storage and seals every value with +// AES-256-GCM before it reaches the backend. A sealed value (an envelope) is +// +// version (1 byte) | key ID (4 bytes, big endian) | nonce (12 bytes) | ciphertext and tag +// +// The nonce is 96 random bits from crypto/rand, drawn fresh for every write. +// The additional data is the 5 byte header followed by the storage key, so a +// value cannot be moved to another key, and the header cannot be edited to +// point at a different key, without failing authentication. +// +// Keys are left in plaintext. The raft node stores its state under names such +// as "currentTerm", "votedFor", "log_", "snapshot_" and +// "snapshot_meta", which reveal only indexes. Leaving them readable keeps +// ordered range scans working on every backend. Code that puts sensitive data +// into key names (statemachine.PersistentStateMachine stores "sm/") leaks +// those names; encrypt them before they become keys if that matters. +// +// The wrapper keeps its own metadata under keys that start with a zero byte, +// which no raft key does: one check value per key ID, which proves at start +// that a configured key is the one the data was written with, and a marker +// while a migration runs. GetRange never returns these keys and writes to +// them are refused. + +const ( + // KeySize is the size of an encryption key: AES-256. + KeySize = 32 + + envelopeVersion1 byte = 1 + headerSize = 1 + 4 + nonceSize = 12 + tagSize = 16 + + // EnvelopeOverhead is the number of bytes encryption adds to each value. + EnvelopeOverhead = headerSize + nonceSize + tagSize + + // migrationChunk is how many keys a migration or rekey handles per batch. + migrationChunk = 256 +) + +var ( + reservedPrefix = []byte("\x00forge-consensus/encryption/") + checkValuePrefix = []byte("\x00forge-consensus/encryption/key/") + migratingToEncryptedKey = []byte("\x00forge-consensus/encryption/migrating-to-encrypted") + migratingToPlaintextKey = []byte("\x00forge-consensus/encryption/migrating-to-plaintext") + checkPlaintext = []byte("forge-consensus encryption check value v1") + + // lastKey bounds a range scan over every key a backend can hold. + lastKey = bytes.Repeat([]byte{0xff}, 1024) +) + +var ( + // ErrInvalidEncryptionKey means a key could not be loaded or has the + // wrong size. Its messages never include key material. + ErrInvalidEncryptionKey = errors.New("consensus storage: invalid encryption key") + + // ErrDecrypt means a value failed authentication: the key is wrong, the + // value was changed, or it was copied from another key. + ErrDecrypt = errors.New("consensus storage: cannot decrypt value") + + // ErrUnknownKeyID means a value was written under a key ID that is not + // configured. + ErrUnknownKeyID = errors.New("consensus storage: value is encrypted with a key that is not configured") + + // ErrWrongKey means the configured keys do not match the keys the store + // was written with. + ErrWrongKey = errors.New("consensus storage: encryption key does not match this store") + + // ErrPlaintextStore means encryption is on but the store already holds + // data written without it. + ErrPlaintextStore = errors.New("consensus storage: store holds data written without encryption") + + // ErrEncryptedStore means encryption is off but the store was written + // with it. + ErrEncryptedStore = errors.New("consensus storage: store holds encrypted data") + + // ErrMigrationIncomplete means a migration between plaintext and + // encrypted storage stopped before it finished. + ErrMigrationIncomplete = errors.New("consensus storage: an encryption migration did not finish") + + // ErrReservedKey means a caller tried to write a key reserved for + // encryption metadata. + ErrReservedKey = errors.New("consensus storage: key is reserved for encryption metadata") +) + +// Keyring holds the AES-256-GCM keys by ID. The active key encrypts new +// writes; every key in the ring can decrypt. +type Keyring struct { + active uint32 + aeads map[uint32]cipher.AEAD + ids []uint32 +} + +// NewKeyring builds a keyring from raw 32 byte keys. activeID selects the key +// used for writes; 0 selects the highest ID. Key ID 0 is not allowed. The +// caller may clear the key slices afterwards: the ring keeps only the +// expanded AES state. +func NewKeyring(activeID uint32, keys map[uint32][]byte) (*Keyring, error) { + if len(keys) == 0 { + return nil, fmt.Errorf("%w: no keys configured", ErrInvalidEncryptionKey) + } + + kr := &Keyring{aeads: make(map[uint32]cipher.AEAD, len(keys))} + + for id, key := range keys { + if id == 0 { + return nil, fmt.Errorf("%w: key ID 0 is not allowed, IDs start at 1", ErrInvalidEncryptionKey) + } + + if len(key) != KeySize { + return nil, fmt.Errorf("%w: key %d is %d bytes, AES-256 needs exactly %d", + ErrInvalidEncryptionKey, id, len(key), KeySize) + } + + block, err := aes.NewCipher(key) + if err != nil { + return nil, fmt.Errorf("%w: key %d: %w", ErrInvalidEncryptionKey, id, err) + } + + aead, err := cipher.NewGCM(block) + if err != nil { + return nil, fmt.Errorf("%w: key %d: %w", ErrInvalidEncryptionKey, id, err) + } + + kr.aeads[id] = aead + kr.ids = append(kr.ids, id) + } + + slices.Sort(kr.ids) + + if activeID == 0 { + activeID = kr.ids[len(kr.ids)-1] + } + + if _, ok := kr.aeads[activeID]; !ok { + return nil, fmt.Errorf("%w: active key ID %d is not among the configured keys %v", + ErrInvalidEncryptionKey, activeID, kr.ids) + } + + kr.active = activeID + + return kr, nil +} + +// ActiveKeyID returns the ID of the key used for new writes. +func (k *Keyring) ActiveKeyID() uint32 { return k.active } + +// KeyIDs returns the configured key IDs in ascending order. +func (k *Keyring) KeyIDs() []uint32 { return slices.Clone(k.ids) } + +// Seal encrypts plaintext for storage under key with the active key. +func (k *Keyring) Seal(key, plaintext []byte) ([]byte, error) { + return k.sealWith(k.active, key, plaintext) +} + +// Open decrypts an envelope stored under key. +func (k *Keyring) Open(key, envelope []byte) ([]byte, error) { + if len(envelope) < EnvelopeOverhead { + return nil, fmt.Errorf("%w: value is %d bytes, shorter than an encrypted value", ErrDecrypt, len(envelope)) + } + + if envelope[0] != envelopeVersion1 { + return nil, fmt.Errorf("%w: unknown format version %d", ErrDecrypt, envelope[0]) + } + + id := binary.BigEndian.Uint32(envelope[1:headerSize]) + + aead, ok := k.aeads[id] + if !ok { + return nil, fmt.Errorf("%w: key ID %d (configured: %v)", ErrUnknownKeyID, id, k.ids) + } + + nonce := envelope[headerSize : headerSize+nonceSize] + + plaintext, err := aead.Open(nil, nonce, envelope[headerSize+nonceSize:], additionalData(envelope[:headerSize], key)) + if err != nil { + return nil, fmt.Errorf("%w: authentication failed with key ID %d "+ + "(wrong key, modified value, or value copied from another key)", ErrDecrypt, id) + } + + return plaintext, nil +} + +func (k *Keyring) sealWith(id uint32, key, plaintext []byte) ([]byte, error) { + aead, ok := k.aeads[id] + if !ok { + return nil, fmt.Errorf("%w: key ID %d", ErrUnknownKeyID, id) + } + + out := make([]byte, headerSize+nonceSize, headerSize+nonceSize+len(plaintext)+tagSize) + out[0] = envelopeVersion1 + binary.BigEndian.PutUint32(out[1:headerSize], id) + + nonce := out[headerSize : headerSize+nonceSize] + if _, err := rand.Read(nonce); err != nil { + return nil, fmt.Errorf("consensus storage: cannot read a random nonce: %w", err) + } + + return aead.Seal(out, nonce, plaintext, additionalData(out[:headerSize], key)), nil +} + +// envelopeKeyID returns the key ID in an envelope header. +func envelopeKeyID(envelope []byte) (uint32, bool) { + if len(envelope) < EnvelopeOverhead || envelope[0] != envelopeVersion1 { + return 0, false + } + + return binary.BigEndian.Uint32(envelope[1:headerSize]), true +} + +func additionalData(header, key []byte) []byte { + ad := make([]byte, 0, len(header)+len(key)) + ad = append(ad, header...) + + return append(ad, key...) +} + +func isReserved(key []byte) bool { + return bytes.HasPrefix(key, reservedPrefix) +} + +func checkValueKey(id uint32) []byte { + return strconv.AppendUint(slices.Clone(checkValuePrefix), uint64(id), 10) +} + +// EncryptedStorageConfig configures NewEncryptedStorage. +type EncryptedStorageConfig struct { + // Keyring holds the keys. Required. + Keyring *Keyring + + // MigratePlaintext lets Start encrypt a store that already holds data + // written without encryption, in place, once. Without it Start refuses + // such a store with ErrPlaintextStore. + MigratePlaintext bool +} + +// EncryptedStorage encrypts the values of another storage backend. See the +// comment at the top of this file for the format. +type EncryptedStorage struct { + inner internal.Storage + keys *Keyring + logger forge.Logger + migratePlaintext bool + + // writeMu lets Rekey read, re-encrypt and write a chunk of values without + // a concurrent write landing in between. Writes share it; Rekey takes it + // exclusively for one chunk at a time. + writeMu sync.RWMutex +} + +var _ internal.Storage = (*EncryptedStorage)(nil) + +// NewEncryptedStorage wraps inner. Start checks that the store matches: a new +// store is marked as encrypted, an encrypted store must be readable with one +// of the configured keys, and a plaintext store is refused unless +// MigratePlaintext is set. +func NewEncryptedStorage(inner internal.Storage, config EncryptedStorageConfig, logger forge.Logger) (*EncryptedStorage, error) { + if inner == nil { + return nil, errors.New("consensus storage: encrypted storage needs a backend") + } + + if config.Keyring == nil { + return nil, fmt.Errorf("%w: no keyring", ErrInvalidEncryptionKey) + } + + return &EncryptedStorage{ + inner: inner, + keys: config.Keyring, + logger: logger, + migratePlaintext: config.MigratePlaintext, + }, nil +} + +// Start starts the backend and checks that it holds data this keyring can +// read. On failure the backend is stopped again. +func (s *EncryptedStorage) Start(ctx context.Context) error { + if err := s.inner.Start(ctx); err != nil { + return err + } + + if err := s.prepare(); err != nil { + _ = s.inner.Stop(context.WithoutCancel(ctx)) + + return err + } + + return nil +} + +func (s *EncryptedStorage) prepare() error { + state, err := readEncryptionState(s.inner) + if err != nil { + return err + } + + if state.toPlaintext { + return fmt.Errorf("%w: a migration to plaintext was interrupted; run storage.MigrateToPlaintext again "+ + "and start without encryption", ErrMigrationIncomplete) + } + + if state.toEncrypted || len(state.checkValues) == 0 { + hasData := state.toEncrypted + + if !hasData { + if hasData, err = hasUserData(s.inner); err != nil { + return err + } + } + + if !hasData { + // A new store: record a check value for every configured key. + return writeCheckValues(s.inner, s.keys, nil, nil) + } + + if !s.migratePlaintext { + if state.toEncrypted { + return fmt.Errorf("%w: a migration to encrypted storage was interrupted; "+ + "start with security.encryption_migrate_plaintext to finish it", ErrMigrationIncomplete) + } + + return fmt.Errorf("%w: refusing to mix plaintext and encrypted values; set "+ + "security.encryption_migrate_plaintext once to encrypt the existing data in place, "+ + "or start from an empty storage path", ErrPlaintextStore) + } + + n, err := MigrateToEncrypted(s.inner, s.keys) + if err != nil { + return err + } + + s.logger.Info("encrypted existing plaintext raft storage", + forge.F("values", n), + forge.F("key_id", s.keys.ActiveKeyID()), + ) + + return nil + } + + if err := verifyCheckValues(s.keys, state.checkValues); err != nil { + return err + } + + return writeCheckValues(s.inner, s.keys, state.checkValues, nil) +} + +// Stop stops the backend. +func (s *EncryptedStorage) Stop(ctx context.Context) error { + return s.inner.Stop(ctx) +} + +// Close closes the backend. +func (s *EncryptedStorage) Close() error { + return s.inner.Close() +} + +// Set encrypts value and stores it under key. +func (s *EncryptedStorage) Set(key, value []byte) error { + if isReserved(key) { + return fmt.Errorf("%w: %q", ErrReservedKey, key) + } + + envelope, err := s.keys.Seal(key, value) + if err != nil { + return err + } + + s.writeMu.RLock() + defer s.writeMu.RUnlock() + + return s.inner.Set(key, envelope) +} + +// Get returns the decrypted value stored under key. A missing key returns the +// backend's error unchanged, so callers still see internal.ErrNodeNotFound. +func (s *EncryptedStorage) Get(key []byte) ([]byte, error) { + if isReserved(key) { + return nil, internal.ErrNodeNotFound + } + + envelope, err := s.inner.Get(key) + if err != nil { + return nil, err + } + + value, err := s.keys.Open(key, envelope) + if err != nil { + return nil, fmt.Errorf("key %q: %w", key, err) + } + + return value, nil +} + +// Delete deletes key. +func (s *EncryptedStorage) Delete(key []byte) error { + if isReserved(key) { + return fmt.Errorf("%w: %q", ErrReservedKey, key) + } + + s.writeMu.RLock() + defer s.writeMu.RUnlock() + + return s.inner.Delete(key) +} + +// Batch encrypts the values of the set operations and applies the batch +// atomically through the backend. +func (s *EncryptedStorage) Batch(ops []internal.BatchOp) error { + sealed := make([]internal.BatchOp, len(ops)) + + for i, op := range ops { + if isReserved(op.Key) { + return fmt.Errorf("batch operation %d: %w: %q", i, ErrReservedKey, op.Key) + } + + sealed[i] = internal.BatchOp{Type: op.Type, Key: op.Key} + + if op.Type == internal.BatchOpSet { + envelope, err := s.keys.Seal(op.Key, op.Value) + if err != nil { + return err + } + + sealed[i].Value = envelope + } + } + + s.writeMu.RLock() + defer s.writeMu.RUnlock() + + return s.inner.Batch(sealed) +} + +// GetRange returns the decrypted key-value pairs in [start, end]. Encryption +// metadata is left out. +func (s *EncryptedStorage) GetRange(start, end []byte) ([]internal.KeyValue, error) { + kvs, err := s.inner.GetRange(start, end) + if err != nil { + return nil, err + } + + out := make([]internal.KeyValue, 0, len(kvs)) + + for _, kv := range kvs { + if isReserved(kv.Key) { + continue + } + + value, err := s.keys.Open(kv.Key, kv.Value) + if err != nil { + return nil, fmt.Errorf("key %q: %w", kv.Key, err) + } + + out = append(out, internal.KeyValue{Key: kv.Key, Value: value}) + } + + return out, nil +} + +// Keyring returns the keyring in use. +func (s *EncryptedStorage) Keyring() *Keyring { return s.keys } + +// Rekey re-encrypts every value that is not under the active key and returns +// how many it rewrote. It is safe while the node runs: each chunk is read and +// rewritten while writes through this wrapper wait, so a concurrent write or +// delete is never overwritten with an older value. Once it returns, keys that +// are no longer active can be removed from the configuration. +func (s *EncryptedStorage) Rekey() (int, error) { + keys, err := listUserKeys(s.inner) + if err != nil { + return 0, err + } + + total := 0 + + for chunk := range slices.Chunk(keys, migrationChunk) { + n, err := s.rekeyChunk(chunk) + total += n + + if err != nil { + return total, err + } + } + + if total > 0 { + s.logger.Info("re-encrypted raft storage under the active key", + forge.F("values", total), + forge.F("key_id", s.keys.ActiveKeyID()), + ) + } + + return total, nil +} + +func (s *EncryptedStorage) rekeyChunk(keys [][]byte) (int, error) { + s.writeMu.Lock() + defer s.writeMu.Unlock() + + ops := make([]internal.BatchOp, 0, len(keys)) + + for _, key := range keys { + envelope, err := s.inner.Get(key) + if errors.Is(err, internal.ErrNodeNotFound) { + continue + } + + if err != nil { + return 0, fmt.Errorf("key %q: %w", key, err) + } + + if id, ok := envelopeKeyID(envelope); ok && id == s.keys.ActiveKeyID() { + continue + } + + value, err := s.keys.Open(key, envelope) + if err != nil { + return 0, fmt.Errorf("key %q: %w", key, err) + } + + resealed, err := s.keys.Seal(key, value) + if err != nil { + return 0, err + } + + ops = append(ops, internal.BatchOp{Type: internal.BatchOpSet, Key: key, Value: resealed}) + } + + if len(ops) == 0 { + return 0, nil + } + + if err := s.inner.Batch(ops); err != nil { + return 0, err + } + + return len(ops), nil +} + +// NewPlaintextGuard wraps a backend that is used without encryption. Its +// Start fails with ErrEncryptedStore when the store was written with +// encryption, instead of letting the raft node read ciphertext as data. +func NewPlaintextGuard(inner internal.Storage) internal.Storage { + return &plaintextGuard{Storage: inner} +} + +type plaintextGuard struct { + internal.Storage +} + +func (g *plaintextGuard) Start(ctx context.Context) error { + if err := g.Storage.Start(ctx); err != nil { + return err + } + + state, err := readEncryptionState(g.Storage) + + switch { + case err != nil: + case state.toEncrypted || state.toPlaintext: + err = fmt.Errorf("%w: finish the migration before starting without encryption", ErrMigrationIncomplete) + case len(state.checkValues) > 0: + err = fmt.Errorf("%w: it was written with security.enable_encryption; start with encryption and "+ + "the same keys, or decrypt it once with storage.MigrateToPlaintext", ErrEncryptedStore) + } + + if err != nil { + _ = g.Stop(context.WithoutCancel(ctx)) + + return err + } + + return nil +} + +// MigrateToEncrypted encrypts, in place, every value of a store written +// without encryption, and marks the store as encrypted. inner must be +// started and must not be in use by anything else. An interrupted run leaves +// a marker that stops the store from being opened either way, and running +// the migration again finishes it: values that already decrypt are skipped. +// It returns how many values it encrypted. +// +// Backends may keep the old plaintext in free pages or old value log files +// until they compact; see the README. +func MigrateToEncrypted(inner internal.Storage, keys *Keyring) (int, error) { + state, err := readEncryptionState(inner) + if err != nil { + return 0, err + } + + if state.toPlaintext { + return 0, fmt.Errorf("%w: a migration to plaintext was interrupted; finish it first", ErrMigrationIncomplete) + } + + if len(state.checkValues) > 0 && !state.toEncrypted { + return 0, fmt.Errorf("%w: it is already encrypted", ErrEncryptedStore) + } + + if err := inner.Set(migratingToEncryptedKey, []byte{1}); err != nil { + return 0, fmt.Errorf("failed to mark migration start: %w", err) + } + + userKeys, err := listUserKeys(inner) + if err != nil { + return 0, err + } + + total := 0 + + for chunk := range slices.Chunk(userKeys, migrationChunk) { + ops := make([]internal.BatchOp, 0, len(chunk)) + + for _, key := range chunk { + value, err := inner.Get(key) + if errors.Is(err, internal.ErrNodeNotFound) { + continue + } + + if err != nil { + return total, fmt.Errorf("key %q: %w", key, err) + } + + // Encrypted by an earlier, interrupted run. + if _, err := keys.Open(key, value); err == nil { + continue + } + + envelope, err := keys.Seal(key, value) + if err != nil { + return total, err + } + + ops = append(ops, internal.BatchOp{Type: internal.BatchOpSet, Key: key, Value: envelope}) + } + + if len(ops) > 0 { + if err := inner.Batch(ops); err != nil { + return total, err + } + + total += len(ops) + } + } + + finish := []internal.BatchOp{{Type: internal.BatchOpDelete, Key: migratingToEncryptedKey}} + + return total, writeCheckValues(inner, keys, state.checkValues, finish) +} + +// MigrateToPlaintext decrypts, in place, every value of an encrypted store +// and removes its encryption metadata, so it can be started without +// encryption. inner must be started and must not be in use by anything else. +// Like MigrateToEncrypted it can be run again after an interruption. It +// returns how many values it decrypted. +func MigrateToPlaintext(inner internal.Storage, keys *Keyring) (int, error) { + state, err := readEncryptionState(inner) + if err != nil { + return 0, err + } + + if state.toEncrypted { + return 0, fmt.Errorf("%w: a migration to encrypted storage was interrupted; finish it first", ErrMigrationIncomplete) + } + + resuming := state.toPlaintext + + if !resuming { + if len(state.checkValues) == 0 { + return 0, fmt.Errorf("%w: it is not encrypted", ErrPlaintextStore) + } + + if err := verifyCheckValues(keys, state.checkValues); err != nil { + return 0, err + } + + if err := inner.Set(migratingToPlaintextKey, []byte{1}); err != nil { + return 0, fmt.Errorf("failed to mark migration start: %w", err) + } + } + + userKeys, err := listUserKeys(inner) + if err != nil { + return 0, err + } + + total := 0 + + for chunk := range slices.Chunk(userKeys, migrationChunk) { + ops := make([]internal.BatchOp, 0, len(chunk)) + + for _, key := range chunk { + envelope, err := inner.Get(key) + if errors.Is(err, internal.ErrNodeNotFound) { + continue + } + + if err != nil { + return total, fmt.Errorf("key %q: %w", key, err) + } + + value, err := keys.Open(key, envelope) + if err != nil { + // An interrupted run already wrote this value in plaintext. + if resuming { + continue + } + + return total, fmt.Errorf("key %q: %w", key, err) + } + + ops = append(ops, internal.BatchOp{Type: internal.BatchOpSet, Key: key, Value: value}) + } + + if len(ops) > 0 { + if err := inner.Batch(ops); err != nil { + return total, err + } + + total += len(ops) + } + } + + finish := make([]internal.BatchOp, 0, len(state.checkValues)+1) + for id := range state.checkValues { + finish = append(finish, internal.BatchOp{Type: internal.BatchOpDelete, Key: checkValueKey(id)}) + } + + finish = append(finish, internal.BatchOp{Type: internal.BatchOpDelete, Key: migratingToPlaintextKey}) + + return total, inner.Batch(finish) +} + +// encryptionState is the encryption metadata found in a store. +type encryptionState struct { + checkValues map[uint32][]byte + toEncrypted bool + toPlaintext bool +} + +func readEncryptionState(st internal.Storage) (encryptionState, error) { + state := encryptionState{checkValues: make(map[uint32][]byte)} + + end := append(slices.Clone(reservedPrefix), 0xff) + + kvs, err := st.GetRange(reservedPrefix, end) + if err != nil { + return state, fmt.Errorf("failed to read encryption metadata: %w", err) + } + + for _, kv := range kvs { + switch { + case bytes.Equal(kv.Key, migratingToEncryptedKey): + state.toEncrypted = true + case bytes.Equal(kv.Key, migratingToPlaintextKey): + state.toPlaintext = true + case bytes.HasPrefix(kv.Key, checkValuePrefix): + id, err := strconv.ParseUint(string(kv.Key[len(checkValuePrefix):]), 10, 32) + if err != nil || id == 0 { + return state, fmt.Errorf("%w: malformed encryption metadata key %q", ErrWrongKey, kv.Key) + } + + state.checkValues[uint32(id)] = kv.Value + } + } + + return state, nil +} + +// verifyCheckValues confirms that every configured key with a check value in +// the store decrypts it, and that at least one configured key does. +func verifyCheckValues(keys *Keyring, checkValues map[uint32][]byte) error { + verified := 0 + + for id, envelope := range checkValues { + if _, ok := keys.aeads[id]; !ok { + continue + } + + plaintext, err := keys.Open(checkValueKey(id), envelope) + if err != nil || !bytes.Equal(plaintext, checkPlaintext) { + return fmt.Errorf("%w: the key configured as ID %d is not the key this store was written with under that ID", ErrWrongKey, id) + } + + verified++ + } + + if verified == 0 { + stored := make([]uint32, 0, len(checkValues)) + for id := range checkValues { + stored = append(stored, id) + } + + slices.Sort(stored) + + return fmt.Errorf("%w: the store was written with key IDs %v and none of them is configured (configured: %v)", + ErrWrongKey, stored, keys.ids) + } + + return nil +} + +// writeCheckValues stores a check value for every configured key that does +// not have one yet, together with extra, in one batch. +func writeCheckValues(st internal.Storage, keys *Keyring, existing map[uint32][]byte, extra []internal.BatchOp) error { + ops := slices.Clone(extra) + + for _, id := range keys.ids { + if _, ok := existing[id]; ok { + continue + } + + key := checkValueKey(id) + + envelope, err := keys.sealWith(id, key, checkPlaintext) + if err != nil { + return err + } + + ops = append(ops, internal.BatchOp{Type: internal.BatchOpSet, Key: key, Value: envelope}) + } + + if len(ops) == 0 { + return nil + } + + if err := st.Batch(ops); err != nil { + return fmt.Errorf("failed to write encryption metadata: %w", err) + } + + return nil +} + +type keyLister interface { + ListKeys(prefix []byte) ([][]byte, error) +} + +// listUserKeys returns every key in the store except encryption metadata. +func listUserKeys(st internal.Storage) ([][]byte, error) { + var all [][]byte + + if lister, ok := st.(keyLister); ok { + keys, err := lister.ListKeys(nil) + if err != nil { + return nil, fmt.Errorf("failed to list keys: %w", err) + } + + all = keys + } else { + kvs, err := st.GetRange([]byte{}, lastKey) + if err != nil { + return nil, fmt.Errorf("failed to list keys: %w", err) + } + + for _, kv := range kvs { + all = append(all, kv.Key) + } + } + + return slices.DeleteFunc(all, isReserved), nil +} + +func hasUserData(st internal.Storage) (bool, error) { + keys, err := listUserKeys(st) + + return len(keys) > 0, err +} diff --git a/extensions/consensus/storage/encryption_keys.go b/extensions/consensus/storage/encryption_keys.go new file mode 100644 index 000000000..127f45d9b --- /dev/null +++ b/extensions/consensus/storage/encryption_keys.go @@ -0,0 +1,198 @@ +package storage + +import ( + "encoding/base64" + "encoding/hex" + "fmt" + "os" + "path/filepath" + "runtime" + "strings" + + "github.com/xraph/forge" +) + +// KeySource says where one encryption key comes from. Exactly one of File, +// Env and Value is set. +type KeySource struct { + // ID identifies the key in every value it encrypts. IDs start at 1. + ID uint32 + + // File is a file holding the key: 32 raw bytes, 64 hex characters or + // base64 text. + File string + + // Env names an environment variable holding the key as 64 hex + // characters or base64 text. + Env string + + // Value is the key itself, as hex or base64 text. It is refused unless + // KeyringConfig.AllowInline is set, because keys written into + // configuration tend to end up in version control and logs. + Value string +} + +// KeyringConfig configures LoadKeyring. +type KeyringConfig struct { + Keys []KeySource + + // ActiveKeyID selects the key for new writes. 0 selects the highest ID. + ActiveKeyID uint32 + + // AllowInline permits KeySource.Value. + AllowInline bool +} + +// LoadKeyring reads every key, checks that it is a 32 byte AES-256 key, and +// builds a keyring. Errors name the key ID and its source but never contain +// key material. A key file that other users can read is logged as a warning. +func LoadKeyring(config KeyringConfig, logger forge.Logger) (*Keyring, error) { + if len(config.Keys) == 0 { + return nil, fmt.Errorf("%w: no keys configured", ErrInvalidEncryptionKey) + } + + keys := make(map[uint32][]byte, len(config.Keys)) + + defer func() { + for _, key := range keys { + clear(key) + } + }() + + for _, src := range config.Keys { + if _, dup := keys[src.ID]; dup { + return nil, fmt.Errorf("%w: key ID %d is configured twice", ErrInvalidEncryptionKey, src.ID) + } + + key, err := readKeySource(src, config.AllowInline, logger) + if err != nil { + return nil, err + } + + keys[src.ID] = key + } + + return NewKeyring(config.ActiveKeyID, keys) +} + +func readKeySource(src KeySource, allowInline bool, logger forge.Logger) ([]byte, error) { + sources := 0 + + for _, s := range []string{src.File, src.Env, src.Value} { + if s != "" { + sources++ + } + } + + if sources != 1 { + return nil, fmt.Errorf("%w: key %d needs exactly one of a file, an environment variable or an inline value", + ErrInvalidEncryptionKey, src.ID) + } + + switch { + case src.File != "": + path := filepath.Clean(src.File) + + raw, err := os.ReadFile(path) + if err != nil { + return nil, fmt.Errorf("%w: key %d: cannot read key file %s: %w", ErrInvalidEncryptionKey, src.ID, path, err) + } + + defer clear(raw) + + warnIfShared(path, src.ID, logger) + + key, err := decodeKey(raw, true) + if err != nil { + return nil, fmt.Errorf("%w: key %d in file %s: %w", ErrInvalidEncryptionKey, src.ID, path, err) + } + + return key, nil + case src.Env != "": + text, ok := os.LookupEnv(src.Env) + if !ok || text == "" { + return nil, fmt.Errorf("%w: key %d: environment variable %s is not set", ErrInvalidEncryptionKey, src.ID, src.Env) + } + + key, err := decodeKey([]byte(text), false) + if err != nil { + return nil, fmt.Errorf("%w: key %d in environment variable %s: %w", ErrInvalidEncryptionKey, src.ID, src.Env, err) + } + + return key, nil + default: + if !allowInline { + return nil, fmt.Errorf("%w: key %d is written inline in the configuration; use a key file or an "+ + "environment variable, or allow inline keys explicitly", ErrInvalidEncryptionKey, src.ID) + } + + key, err := decodeKey([]byte(src.Value), false) + if err != nil { + return nil, fmt.Errorf("%w: inline key %d: %w", ErrInvalidEncryptionKey, src.ID, err) + } + + return key, nil + } +} + +// decodeKey accepts 32 raw bytes (files only), 64 hex characters, or base64 +// with or without padding. Decoder errors are not wrapped because some of +// them quote the offending character. +func decodeKey(raw []byte, allowRaw bool) ([]byte, error) { + if allowRaw && len(raw) == KeySize { + return append([]byte(nil), raw...), nil + } + + text := strings.TrimSpace(string(raw)) + + var ( + key []byte + err error + ) + + switch len(text) { + case hex.EncodedLen(KeySize): + key, err = hex.DecodeString(text) + case base64.StdEncoding.EncodedLen(KeySize): + key, err = base64.StdEncoding.DecodeString(text) + if err != nil { + key, err = base64.URLEncoding.DecodeString(text) + } + case base64.RawStdEncoding.EncodedLen(KeySize): + key, err = base64.RawStdEncoding.DecodeString(text) + if err != nil { + key, err = base64.RawURLEncoding.DecodeString(text) + } + default: + return nil, fmt.Errorf("the key must be %d bytes: %d raw bytes in a file, %d hex characters or %d base64 characters; "+ + "got %d characters", KeySize, KeySize, hex.EncodedLen(KeySize), base64.StdEncoding.EncodedLen(KeySize), len(text)) + } + + if err != nil || len(key) != KeySize { + return nil, fmt.Errorf("the key is not valid hex or base64 for a %d byte key", KeySize) + } + + return key, nil +} + +// warnIfShared logs when a key file is readable or writable by group or +// others. It does not fail: some deployments mount secrets with wider modes +// and protect them another way. +func warnIfShared(path string, id uint32, logger forge.Logger) { + if logger == nil || runtime.GOOS == "windows" { + return + } + + info, err := os.Stat(path) + if err != nil { + return + } + + if perm := info.Mode().Perm(); perm&0o077 != 0 { + logger.Warn("encryption key file is accessible to other users; restrict it to mode 0600", + forge.F("key_id", id), + forge.F("path", path), + forge.F("mode", fmt.Sprintf("%#o", perm)), + ) + } +} diff --git a/extensions/consensus/storage/encryption_raft_test.go b/extensions/consensus/storage/encryption_raft_test.go new file mode 100644 index 000000000..96f698d58 --- /dev/null +++ b/extensions/consensus/storage/encryption_raft_test.go @@ -0,0 +1,205 @@ +package storage_test + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/base64" + "os" + "path/filepath" + "strconv" + "testing" + + "github.com/xraph/forge" + "github.com/xraph/forge/extensions/consensus/internal" + "github.com/xraph/forge/extensions/consensus/raft" + "github.com/xraph/forge/extensions/consensus/storage" +) + +func encryptedBolt(tb testing.TB, path string, key []byte) *storage.EncryptedStorage { + tb.Helper() + + inner, err := storage.NewBoltDBStorage(storage.BoltDBStorageConfig{Path: path}, forge.NewNoopLogger()) + if err != nil { + tb.Fatal(err) + } + + kr, err := storage.NewKeyring(0, map[uint32][]byte{1: key}) + if err != nil { + tb.Fatal(err) + } + + s, err := storage.NewEncryptedStorage(inner, storage.EncryptedStorageConfig{Keyring: kr}, forge.NewNoopLogger()) + if err != nil { + tb.Fatal(err) + } + + if err := s.Start(context.Background()); err != nil { + tb.Fatal(err) + } + + return s +} + +func randomKey(tb testing.TB) []byte { + tb.Helper() + + key := make([]byte, storage.KeySize) + if _, err := rand.Read(key); err != nil { + tb.Fatal(err) + } + + return key +} + +// The raft log persisted through encrypted storage leaves no plaintext of a +// known command in the database file, and reloads intact. +func TestRaftLogOnEncryptedStorageHasNoPlaintextOnDisk(t *testing.T) { + path := filepath.Join(t.TempDir(), "raft.db") + key := randomKey(t) + command := []byte(`{"type":"set","payload":{"key":"card","value":"4111-1111-1111-1111"}}`) + + s := encryptedBolt(t, path, key) + + log, err := raft.NewLog(forge.NewNoopLogger(), s, 0) + if err != nil { + t.Fatal(err) + } + + for i := uint64(1); i <= 50; i++ { + if err := log.Append(internal.LogEntry{Index: i, Term: 1, Data: command}); err != nil { + t.Fatal(err) + } + } + + if err := s.Set([]byte("votedFor"), []byte("node-with-a-recognisable-name")); err != nil { + t.Fatal(err) + } + + if err := s.Close(); err != nil { + t.Fatal(err) + } + + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + + for _, needle := range [][]byte{[]byte("4111-1111"), []byte(`"payload"`), []byte("recognisable")} { + if bytes.Contains(raw, needle) { + t.Fatalf("database file contains plaintext %q", needle) + } + } + + // LogEntry.Data is base64 in the JSON encoding, so check that form too. + if bytes.Contains(raw, []byte(base64.StdEncoding.EncodeToString(command)[:24])) { + t.Fatal("database file contains the base64 encoded command") + } + + s = encryptedBolt(t, path, key) + defer s.Close() + + log, err = raft.NewLog(forge.NewNoopLogger(), s, 0) + if err != nil { + t.Fatal(err) + } + + entry, err := log.Get(50) + if err != nil || !bytes.Equal(entry.Data, command) || log.LastIndex() != 50 { + t.Fatalf("reloaded log: last %d, entry %+v, %v", log.LastIndex(), entry, err) + } +} + +// BenchmarkLogAppend measures one raft log append (JSON encoding plus one +// storage write) with and without encryption. Run with -benchmem. +func BenchmarkLogAppend(b *testing.B) { + for _, size := range []int{128, 1024, 16384} { + data := make([]byte, size) + + backends := map[string]func(b *testing.B) internal.Storage{ + "memory/plain": func(*testing.B) internal.Storage { + return storage.NewMemoryStorage(storage.MemoryStorageConfig{}, forge.NewNoopLogger()) + }, + "memory/encrypted": func(b *testing.B) internal.Storage { + kr, _ := storage.NewKeyring(0, map[uint32][]byte{1: randomKey(b)}) + s, _ := storage.NewEncryptedStorage( + storage.NewMemoryStorage(storage.MemoryStorageConfig{}, forge.NewNoopLogger()), + storage.EncryptedStorageConfig{Keyring: kr}, forge.NewNoopLogger()) + + return s + }, + "boltdb/plain": func(b *testing.B) internal.Storage { + s, _ := storage.NewBoltDBStorage(storage.BoltDBStorageConfig{ + Path: filepath.Join(b.TempDir(), "raft.db"), + }, forge.NewNoopLogger()) + + return s + }, + "boltdb/encrypted": func(b *testing.B) internal.Storage { + inner, _ := storage.NewBoltDBStorage(storage.BoltDBStorageConfig{ + Path: filepath.Join(b.TempDir(), "raft.db"), + }, forge.NewNoopLogger()) + kr, _ := storage.NewKeyring(0, map[uint32][]byte{1: randomKey(b)}) + s, _ := storage.NewEncryptedStorage(inner, storage.EncryptedStorageConfig{Keyring: kr}, forge.NewNoopLogger()) + + return s + }, + } + + for _, name := range []string{"memory/plain", "memory/encrypted", "boltdb/plain", "boltdb/encrypted"} { + b.Run(name+"/"+sizeName(size), func(b *testing.B) { + s := backends[name](b) + if err := s.Start(context.Background()); err != nil { + b.Fatal(err) + } + + defer s.Close() + + log, err := raft.NewLog(forge.NewNoopLogger(), s, 0) + if err != nil { + b.Fatal(err) + } + + b.SetBytes(int64(size)) + b.ReportAllocs() + + index := uint64(0) + + for b.Loop() { + index++ + + if err := log.Append(internal.LogEntry{Index: index, Term: 1, Data: data}); err != nil { + b.Fatal(err) + } + } + }) + } + } +} + +// BenchmarkSeal measures the encryption step alone. +func BenchmarkSeal(b *testing.B) { + kr, err := storage.NewKeyring(0, map[uint32][]byte{1: randomKey(b)}) + if err != nil { + b.Fatal(err) + } + + for _, size := range []int{128, 1024, 16384} { + b.Run(sizeName(size), func(b *testing.B) { + value := make([]byte, size) + + b.SetBytes(int64(size)) + b.ReportAllocs() + + for b.Loop() { + if _, err := kr.Seal([]byte("log_123456"), value); err != nil { + b.Fatal(err) + } + } + }) + } +} + +func sizeName(size int) string { + return strconv.Itoa(size) + "B" +} diff --git a/extensions/consensus/storage/encryption_test.go b/extensions/consensus/storage/encryption_test.go new file mode 100644 index 000000000..4df48de2d --- /dev/null +++ b/extensions/consensus/storage/encryption_test.go @@ -0,0 +1,700 @@ +package storage + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/base64" + "encoding/binary" + "encoding/hex" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/xraph/forge" + "github.com/xraph/forge/errors" + "github.com/xraph/forge/extensions/consensus/internal" +) + +// testBackend opens handles on one underlying store. Every call to open +// returns a fresh, unstarted handle on the same data, as a restart would. +type testBackend struct { + name string + open func() internal.Storage +} + +// reopenableMemory lets the memory backend be stopped and started again with +// its data intact, like a persistent backend. +type reopenableMemory struct { + *MemoryStorage +} + +func (m reopenableMemory) Start(ctx context.Context) error { + if err := m.MemoryStorage.Start(ctx); err != nil && !errors.Is(err, internal.ErrAlreadyStarted) { + return err + } + + return nil +} + +func (m reopenableMemory) Stop(context.Context) error { return nil } + +func testBackends(t testing.TB) []testBackend { + t.Helper() + + logger := forge.NewNoopLogger() + badgerDir := filepath.Join(t.TempDir(), "badger") + boltPath := filepath.Join(t.TempDir(), "raft.db") + mem := NewMemoryStorage(MemoryStorageConfig{}, logger) + + return []testBackend{ + {name: "memory", open: func() internal.Storage { return reopenableMemory{mem} }}, + {name: "badger", open: func() internal.Storage { + s, err := NewBadgerStorage(BadgerStorageConfig{Path: badgerDir}, logger) + if err != nil { + t.Fatal(err) + } + + return s + }}, + {name: "boltdb", open: func() internal.Storage { + s, err := NewBoltDBStorage(BoltDBStorageConfig{Path: boltPath}, logger) + if err != nil { + t.Fatal(err) + } + + return s + }}, + } +} + +func newKey(t testing.TB) []byte { + t.Helper() + + key := make([]byte, KeySize) + if _, err := rand.Read(key); err != nil { + t.Fatal(err) + } + + return key +} + +func keyring(t testing.TB, active uint32, keys map[uint32][]byte) *Keyring { + t.Helper() + + kr, err := NewKeyring(active, keys) + if err != nil { + t.Fatal(err) + } + + return kr +} + +// startEncrypted opens the backend with encryption and starts it. +func startEncrypted(t testing.TB, b testBackend, kr *Keyring, migrate bool) (*EncryptedStorage, error) { + t.Helper() + + s, err := NewEncryptedStorage(b.open(), EncryptedStorageConfig{Keyring: kr, MigratePlaintext: migrate}, forge.NewNoopLogger()) + if err != nil { + t.Fatal(err) + } + + return s, s.Start(context.Background()) +} + +func mustStartEncrypted(t testing.TB, b testBackend, kr *Keyring) *EncryptedStorage { + t.Helper() + + s, err := startEncrypted(t, b, kr, false) + if err != nil { + t.Fatalf("start encrypted %s: %v", b.name, err) + } + + return s +} + +func stop(t testing.TB, s internal.Storage) { + t.Helper() + + if err := s.Stop(context.Background()); err != nil { + t.Fatalf("stop: %v", err) + } +} + +func mustGet(t testing.TB, s internal.Storage, key string) []byte { + t.Helper() + + v, err := s.Get([]byte(key)) + if err != nil { + t.Fatalf("get %s: %v", key, err) + } + + return v +} + +func rawKeyID(t testing.TB, s *EncryptedStorage, key string) uint32 { + t.Helper() + + raw, err := s.inner.Get([]byte(key)) + if err != nil { + t.Fatal(err) + } + + id, ok := envelopeKeyID(raw) + if !ok { + t.Fatalf("raw value of %s is not an envelope", key) + } + + return id +} + +func TestEncryptedStorageRoundTrip(t *testing.T) { + for _, b := range testBackends(t) { + t.Run(b.name, func(t *testing.T) { + kr := keyring(t, 0, map[uint32][]byte{1: newKey(t)}) + s := mustStartEncrypted(t, b, kr) + + if err := s.Set([]byte("currentTerm"), []byte{0, 0, 0, 0, 0, 0, 0, 7}); err != nil { + t.Fatal(err) + } + + ops := []internal.BatchOp{ + {Type: internal.BatchOpSet, Key: []byte("log_1"), Value: []byte(`{"index":1}`)}, + {Type: internal.BatchOpSet, Key: []byte("log_2"), Value: []byte(`{"index":2}`)}, + {Type: internal.BatchOpSet, Key: []byte("log_3"), Value: []byte{}}, + {Type: internal.BatchOpDelete, Key: []byte("log_3")}, + } + if err := s.Batch(ops); err != nil { + t.Fatal(err) + } + + if got := mustGet(t, s, "log_2"); string(got) != `{"index":2}` { + t.Fatalf("log_2 = %q", got) + } + + if _, err := s.Get([]byte("log_3")); !errors.Is(err, internal.ErrNodeNotFound) { + t.Fatalf("deleted key returned %v, want ErrNodeNotFound", err) + } + + if err := s.Set([]byte("empty"), nil); err != nil { + t.Fatal(err) + } + + if got := mustGet(t, s, "empty"); len(got) != 0 { + t.Fatalf("empty value came back as %q", got) + } + + kvs, err := s.GetRange([]byte("log_"), []byte("log_~")) + if err != nil { + t.Fatal(err) + } + + if len(kvs) != 2 || string(kvs[0].Value) != `{"index":1}` || string(kvs[1].Value) != `{"index":2}` { + t.Fatalf("range = %+v", kvs) + } + + raw, err := s.inner.Get([]byte("log_1")) + if err != nil { + t.Fatal(err) + } + + if len(raw) != len(`{"index":1}`)+EnvelopeOverhead || bytes.Contains(raw, []byte("index")) { + t.Fatalf("raw value is not an envelope: %q", raw) + } + + if err := s.Delete([]byte("log_1")); err != nil { + t.Fatal(err) + } + + stop(t, s) + + // Restart with the same key. + s = mustStartEncrypted(t, b, kr) + defer stop(t, s) + + if got := mustGet(t, s, "currentTerm"); !bytes.Equal(got, []byte{0, 0, 0, 0, 0, 0, 0, 7}) { + t.Fatalf("currentTerm after restart = %v", got) + } + + if _, err := s.Get([]byte("log_1")); !errors.Is(err, internal.ErrNodeNotFound) { + t.Fatalf("deleted key after restart returned %v", err) + } + }) + } +} + +func TestEncryptedStorageRejectsTamperedAndMovedValues(t *testing.T) { + for _, b := range testBackends(t) { + t.Run(b.name, func(t *testing.T) { + kr := keyring(t, 1, map[uint32][]byte{1: newKey(t), 2: newKey(t)}) + s := mustStartEncrypted(t, b, kr) + + defer stop(t, s) + + for _, k := range []string{"a", "b", "c", "d", "e"} { + if err := s.Set([]byte(k), []byte("value of "+k)); err != nil { + t.Fatal(err) + } + } + + rawA, _ := s.inner.Get([]byte("a")) + + tamper := func(key string, mutate func([]byte) []byte) { + raw, err := s.inner.Get([]byte(key)) + if err != nil { + t.Fatal(err) + } + + if err := s.inner.Set([]byte(key), mutate(bytes.Clone(raw))); err != nil { + t.Fatal(err) + } + } + + // A flipped ciphertext bit. + tamper("b", func(v []byte) []byte { + v[len(v)-20] ^= 1 + + return v + }) + // The value of a copied under key c. + tamper("c", func([]byte) []byte { return bytes.Clone(rawA) }) + // The header switched to the other configured key. + tamper("d", func(v []byte) []byte { return withID(v, 2) }) + // A truncated value. + tamper("e", func(v []byte) []byte { return v[:EnvelopeOverhead-1] }) + + for _, k := range []string{"b", "c", "d", "e"} { + if _, err := s.Get([]byte(k)); !errors.Is(err, ErrDecrypt) { + t.Fatalf("tampered %s: Get returned %v, want ErrDecrypt", k, err) + } + } + + if _, err := s.GetRange([]byte("a"), []byte("e")); !errors.Is(err, ErrDecrypt) { + t.Fatalf("GetRange over tampered values returned %v, want ErrDecrypt", err) + } + + if got := mustGet(t, s, "a"); string(got) != "value of a" { + t.Fatalf("untouched value = %q", got) + } + + // A key ID nobody configured. + tamper("a", func(v []byte) []byte { return withID(v, 9) }) + + if _, err := s.Get([]byte("a")); !errors.Is(err, ErrUnknownKeyID) { + t.Fatalf("unknown key ID: Get returned %v", err) + } + }) + } +} + +func TestEncryptedStorageWrongKeyFailsAtStart(t *testing.T) { + for _, b := range testBackends(t) { + t.Run(b.name, func(t *testing.T) { + right := newKey(t) + + s := mustStartEncrypted(t, b, keyring(t, 0, map[uint32][]byte{1: right})) + if err := s.Set([]byte("log_1"), []byte("entry")); err != nil { + t.Fatal(err) + } + + stop(t, s) + + _, err := startEncrypted(t, b, keyring(t, 0, map[uint32][]byte{1: newKey(t)}), false) + if !errors.Is(err, ErrWrongKey) || !strings.Contains(err.Error(), "ID 1") { + t.Fatalf("different key under the same ID: %v, want ErrWrongKey", err) + } + + _, err = startEncrypted(t, b, keyring(t, 0, map[uint32][]byte{2: newKey(t)}), false) + if !errors.Is(err, ErrWrongKey) || !strings.Contains(err.Error(), "[1]") { + t.Fatalf("only an unrelated key ID: %v, want ErrWrongKey naming key 1", err) + } + + // A failed start leaves the backend closed, so the right key can + // open it again. + s = mustStartEncrypted(t, b, keyring(t, 0, map[uint32][]byte{1: right})) + defer stop(t, s) + + if got := mustGet(t, s, "log_1"); string(got) != "entry" { + t.Fatalf("log_1 = %q", got) + } + }) + } +} + +func TestEncryptedStorageKeyRotation(t *testing.T) { + for _, b := range testBackends(t) { + t.Run(b.name, func(t *testing.T) { + key1, key2 := newKey(t), newKey(t) + + s := mustStartEncrypted(t, b, keyring(t, 0, map[uint32][]byte{1: key1})) + for i := range 300 { + if err := s.Set(fmt.Appendf(nil, "log_%d", i), fmt.Appendf(nil, "old %d", i)); err != nil { + t.Fatal(err) + } + } + + stop(t, s) + + // Rotate: key 2 becomes active, key 1 stays for reads. + s = mustStartEncrypted(t, b, keyring(t, 0, map[uint32][]byte{1: key1, 2: key2})) + + if got := mustGet(t, s, "log_7"); string(got) != "old 7" { + t.Fatalf("old value after rotation = %q", got) + } + + if err := s.Set([]byte("log_new"), []byte("new")); err != nil { + t.Fatal(err) + } + + if id := rawKeyID(t, s, "log_new"); id != 2 { + t.Fatalf("new write used key %d, want 2", id) + } + + if id := rawKeyID(t, s, "log_7"); id != 1 { + t.Fatalf("old value is under key %d, want 1", id) + } + + stop(t, s) + + // Dropping key 1 before re-encrypting: the store opens with key 2, + // but old values report the missing key. + s = mustStartEncrypted(t, b, keyring(t, 0, map[uint32][]byte{2: key2})) + + if _, err := s.Get([]byte("log_7")); !errors.Is(err, ErrUnknownKeyID) { + t.Fatalf("old value without key 1: %v, want ErrUnknownKeyID", err) + } + + stop(t, s) + + // Re-encrypt with both keys, then key 1 can go. + s = mustStartEncrypted(t, b, keyring(t, 0, map[uint32][]byte{1: key1, 2: key2})) + + n, err := s.Rekey() + if err != nil || n != 300 { + t.Fatalf("Rekey = %d, %v; want 300", n, err) + } + + if n, err := s.Rekey(); err != nil || n != 0 { + t.Fatalf("second Rekey = %d, %v; want 0", n, err) + } + + stop(t, s) + + s = mustStartEncrypted(t, b, keyring(t, 0, map[uint32][]byte{2: key2})) + defer stop(t, s) + + for i := range 300 { + if got := mustGet(t, s, fmt.Sprintf("log_%d", i)); string(got) != fmt.Sprintf("old %d", i) { + t.Fatalf("log_%d = %q", i, got) + } + } + }) + } +} + +func TestEncryptedStorageRefusesPlaintextStoreAndMigrates(t *testing.T) { + for _, b := range testBackends(t) { + t.Run(b.name, func(t *testing.T) { + plain := NewPlaintextGuard(b.open()) + if err := plain.Start(context.Background()); err != nil { + t.Fatal(err) + } + + for i := range 600 { + if err := plain.Set(fmt.Appendf(nil, "log_%d", i), fmt.Appendf(nil, "command %d", i)); err != nil { + t.Fatal(err) + } + } + + stop(t, plain) + + kr := keyring(t, 0, map[uint32][]byte{1: newKey(t)}) + + if _, err := startEncrypted(t, b, kr, false); !errors.Is(err, ErrPlaintextStore) { + t.Fatalf("encrypted start on a plaintext store: %v, want ErrPlaintextStore", err) + } + + // One-time migration. + s, err := startEncrypted(t, b, kr, true) + if err != nil { + t.Fatalf("migrating start: %v", err) + } + + if got := mustGet(t, s, "log_599"); string(got) != "command 599" { + t.Fatalf("log_599 after migration = %q", got) + } + + if id := rawKeyID(t, s, "log_0"); id != 1 { + t.Fatalf("migrated value under key %d", id) + } + + stop(t, s) + + // The migration option is harmless once the store is encrypted. + s, err = startEncrypted(t, b, kr, true) + if err != nil { + t.Fatal(err) + } + + stop(t, s) + + // The reverse mismatch: an encrypted store opened without encryption. + plain = NewPlaintextGuard(b.open()) + if err := plain.Start(context.Background()); !errors.Is(err, ErrEncryptedStore) { + t.Fatalf("plaintext start on an encrypted store: %v, want ErrEncryptedStore", err) + } + + // Decrypting once lets it start without encryption again. + inner := b.open() + if err := inner.Start(context.Background()); err != nil { + t.Fatal(err) + } + + if n, err := MigrateToPlaintext(inner, kr); err != nil || n != 600 { + t.Fatalf("MigrateToPlaintext = %d, %v", n, err) + } + + stop(t, inner) + + plain = NewPlaintextGuard(b.open()) + if err := plain.Start(context.Background()); err != nil { + t.Fatalf("plaintext start after decrypting: %v", err) + } + + defer stop(t, plain) + + if got := mustGet(t, plain, "log_3"); string(got) != "command 3" { + t.Fatalf("log_3 after decrypting = %q", got) + } + }) + } +} + +// A migration that stops halfway blocks both modes until it is run again, +// and the rerun skips values that are already encrypted. +func TestEncryptedStorageInterruptedMigration(t *testing.T) { + for _, b := range testBackends(t) { + t.Run(b.name, func(t *testing.T) { + kr := keyring(t, 0, map[uint32][]byte{1: newKey(t)}) + + inner := b.open() + if err := inner.Start(context.Background()); err != nil { + t.Fatal(err) + } + + sealed, err := kr.Seal([]byte("log_1"), []byte("first")) + if err != nil { + t.Fatal(err) + } + + // What an interrupted run leaves: the marker, one value encrypted, + // one still in plaintext. + for k, v := range map[string][]byte{ + string(migratingToEncryptedKey): {1}, + "log_1": sealed, + "log_2": []byte("second"), + } { + if err := inner.Set([]byte(k), v); err != nil { + t.Fatal(err) + } + } + + stop(t, inner) + + if err := NewPlaintextGuard(b.open()).Start(context.Background()); !errors.Is(err, ErrMigrationIncomplete) { + t.Fatalf("plaintext start mid-migration: %v", err) + } + + if _, err := startEncrypted(t, b, kr, false); !errors.Is(err, ErrMigrationIncomplete) { + t.Fatalf("encrypted start mid-migration: %v", err) + } + + s, err := startEncrypted(t, b, kr, true) + if err != nil { + t.Fatal(err) + } + + defer stop(t, s) + + if got := mustGet(t, s, "log_1"); string(got) != "first" { + t.Fatalf("log_1 = %q", got) + } + + if got := mustGet(t, s, "log_2"); string(got) != "second" { + t.Fatalf("log_2 = %q", got) + } + + if _, err := s.inner.Get(migratingToEncryptedKey); !errors.Is(err, internal.ErrNodeNotFound) { + t.Fatalf("migration marker still present: %v", err) + } + }) + } +} + +func TestEncryptedStorageReservedKeys(t *testing.T) { + b := testBackends(t)[0] + s := mustStartEncrypted(t, b, keyring(t, 0, map[uint32][]byte{1: newKey(t)})) + + defer stop(t, s) + + if err := s.Set(checkValueKey(1), []byte("x")); !errors.Is(err, ErrReservedKey) { + t.Fatalf("Set on a reserved key: %v", err) + } + + if err := s.Delete(checkValueKey(1)); !errors.Is(err, ErrReservedKey) { + t.Fatalf("Delete on a reserved key: %v", err) + } + + if err := s.Batch([]internal.BatchOp{{Type: internal.BatchOpDelete, Key: migratingToPlaintextKey}}); !errors.Is(err, ErrReservedKey) { + t.Fatalf("Batch on a reserved key: %v", err) + } + + if err := s.Set([]byte("k"), []byte("v")); err != nil { + t.Fatal(err) + } + + kvs, err := s.GetRange([]byte{}, lastKey) + if err != nil { + t.Fatal(err) + } + + if len(kvs) != 1 || string(kvs[0].Key) != "k" { + t.Fatalf("full range = %+v, want only k", kvs) + } +} + +func TestSealUsesAFreshNonceEveryWrite(t *testing.T) { + kr := keyring(t, 0, map[uint32][]byte{1: newKey(t)}) + seen := make(map[string]bool) + + for range 10000 { + env, err := kr.Seal([]byte("k"), []byte("same value")) + if err != nil { + t.Fatal(err) + } + + nonce := string(env[headerSize : headerSize+nonceSize]) + if seen[nonce] { + t.Fatal("nonce repeated") + } + + seen[nonce] = true + } +} + +func TestNewKeyringValidatesKeys(t *testing.T) { + cases := map[string]struct { + active uint32 + keys map[uint32][]byte + }{ + "no keys": {keys: map[uint32][]byte{}}, + "short key": {keys: map[uint32][]byte{1: make([]byte, 16)}}, + "long key": {keys: map[uint32][]byte{1: make([]byte, 33)}}, + "key id zero": {keys: map[uint32][]byte{0: make([]byte, 32)}}, + "missing active": {active: 3, keys: map[uint32][]byte{1: make([]byte, 32)}}, + } + + for name, c := range cases { + if _, err := NewKeyring(c.active, c.keys); !errors.Is(err, ErrInvalidEncryptionKey) { + t.Fatalf("%s: %v, want ErrInvalidEncryptionKey", name, err) + } + } + + kr := keyring(t, 0, map[uint32][]byte{3: newKey(t), 1: newKey(t)}) + if kr.ActiveKeyID() != 3 { + t.Fatalf("default active key = %d, want the highest ID", kr.ActiveKeyID()) + } +} + +func TestLoadKeyring(t *testing.T) { + key := newKey(t) + dir := t.TempDir() + + write := func(name string, data []byte) string { + path := filepath.Join(dir, name) + if err := os.WriteFile(path, data, 0o600); err != nil { + t.Fatal(err) + } + + return path + } + + rawFile := write("raw.key", key) + hexFile := write("hex.key", []byte(hex.EncodeToString(key)+"\n")) + b64File := write("b64.key", []byte(base64.StdEncoding.EncodeToString(key)+"\n")) + shortFile := write("short.key", []byte("c2hvcnQta2V5LW1hdGVyaWFs")) + + t.Setenv("CONSENSUS_TEST_KEY", hex.EncodeToString(key)) + t.Setenv("CONSENSUS_TEST_BAD_KEY", "zz"+hex.EncodeToString(key)[2:]) + + kr, err := LoadKeyring(KeyringConfig{Keys: []KeySource{ + {ID: 1, File: rawFile}, {ID: 2, File: hexFile}, {ID: 3, File: b64File}, {ID: 4, Env: "CONSENSUS_TEST_KEY"}, + }}, forge.NewNoopLogger()) + if err != nil { + t.Fatal(err) + } + + // Every source decodes to the same key: a value sealed under each ID + // opens with a keyring built from the raw key under that ID. + for _, id := range []uint32{1, 2, 3, 4} { + env, err := kr.sealWith(id, []byte("k"), []byte("v")) + if err != nil { + t.Fatal(err) + } + + if got, err := keyring(t, 0, map[uint32][]byte{id: key}).Open([]byte("k"), env); err != nil || string(got) != "v" { + t.Fatalf("key %d did not decode to the raw key: %q, %v", id, got, err) + } + + // The header is authenticated: the same key material under another + // ID does not open it. + if _, err := kr.Open([]byte("k"), withID(env, id%4+1)); !errors.Is(err, ErrDecrypt) { + t.Fatalf("header rewritten from key %d: %v, want ErrDecrypt", id, err) + } + } + + if kr.ActiveKeyID() != 4 { + t.Fatalf("active key = %d", kr.ActiveKeyID()) + } + + failures := map[string]KeyringConfig{ + "short key file": {Keys: []KeySource{{ID: 1, File: shortFile}}}, + "missing file": {Keys: []KeySource{{ID: 1, File: filepath.Join(dir, "absent")}}}, + "unset env": {Keys: []KeySource{{ID: 1, Env: "CONSENSUS_TEST_UNSET_KEY"}}}, + "bad hex env": {Keys: []KeySource{{ID: 1, Env: "CONSENSUS_TEST_BAD_KEY"}}}, + "inline not allowed": {Keys: []KeySource{{ID: 1, Value: hex.EncodeToString(key)}}}, + "two sources": {Keys: []KeySource{{ID: 1, File: rawFile, Env: "CONSENSUS_TEST_KEY"}}}, + "duplicate ids": {Keys: []KeySource{{ID: 1, File: rawFile}, {ID: 1, File: hexFile}}}, + "no keys": {}, + "active not in ring": {Keys: []KeySource{{ID: 1, File: rawFile}}, ActiveKeyID: 2}, + "inline wrong length": {Keys: []KeySource{{ID: 1, Value: "abcd"}}, AllowInline: true}, + } + + for name, cfg := range failures { + _, err := LoadKeyring(cfg, forge.NewNoopLogger()) + if !errors.Is(err, ErrInvalidEncryptionKey) { + t.Fatalf("%s: %v, want ErrInvalidEncryptionKey", name, err) + } + + // Errors name sources, never key material. + for _, secret := range []string{hex.EncodeToString(key), "zz" + hex.EncodeToString(key)[2:12], "c2hvcnQ"} { + if strings.Contains(err.Error(), secret) { + t.Fatalf("%s: error leaks key material: %v", name, err) + } + } + } + + if _, err := LoadKeyring(KeyringConfig{Keys: []KeySource{{ID: 1, Value: hex.EncodeToString(key)}}, AllowInline: true}, + forge.NewNoopLogger()); err != nil { + t.Fatalf("allowed inline key: %v", err) + } +} + +func withID(envelope []byte, id uint32) []byte { + e := bytes.Clone(envelope) + binary.BigEndian.PutUint32(e[1:5], id) + + return e +} diff --git a/extensions/consensus/transport/envelope.go b/extensions/consensus/transport/envelope.go index 1c014763d..6b732b953 100644 --- a/extensions/consensus/transport/envelope.go +++ b/extensions/consensus/transport/envelope.go @@ -51,6 +51,8 @@ type wireMessage struct { RequestVoteResponse *internal.RequestVoteResponse `json:"request_vote_response,omitempty"` InstallSnapshot *internal.InstallSnapshotRequest `json:"install_snapshot,omitempty"` InstallSnapshotResponse *internal.InstallSnapshotResponse `json:"install_snapshot_response,omitempty"` + TimeoutNow *internal.TimeoutNowRequest `json:"timeout_now,omitempty"` + TimeoutNowResponse *internal.TimeoutNowResponse `json:"timeout_now_response,omitempty"` } // toMessage reports an error unless exactly the payload matching Type is set. @@ -111,6 +113,10 @@ func encodeMessage(message any) ([]byte, internal.Message, error) { w.InstallSnapshot, err = asPointer[internal.InstallSnapshotRequest](msg.Payload) case internal.MessageTypeInstallSnapshotResponse: w.InstallSnapshotResponse, err = asPointer[internal.InstallSnapshotResponse](msg.Payload) + case internal.MessageTypeTimeoutNow: + w.TimeoutNow, err = asPointer[internal.TimeoutNowRequest](msg.Payload) + case internal.MessageTypeTimeoutNowResponse: + w.TimeoutNowResponse, err = asPointer[internal.TimeoutNowResponse](msg.Payload) case internal.MessageTypeHeartbeat: if msg.Payload != nil { err = fmt.Errorf("heartbeat carries a %T payload", msg.Payload) @@ -158,6 +164,7 @@ func decodeMessage(data []byte) (internal.Message, error) { w.AppendEntries != nil, w.AppendEntriesResponse != nil, w.RequestVote != nil, w.RequestVoteResponse != nil, w.InstallSnapshot != nil, w.InstallSnapshotResponse != nil, + w.TimeoutNow != nil, w.TimeoutNowResponse != nil, } { if present { set++ @@ -177,6 +184,10 @@ func decodeMessage(data []byte) (internal.Message, error) { msg.Payload, set = w.InstallSnapshot, set-boolToInt(w.InstallSnapshot != nil) case internal.MessageTypeInstallSnapshotResponse: msg.Payload, set = w.InstallSnapshotResponse, set-boolToInt(w.InstallSnapshotResponse != nil) + case internal.MessageTypeTimeoutNow: + msg.Payload, set = w.TimeoutNow, set-boolToInt(w.TimeoutNow != nil) + case internal.MessageTypeTimeoutNowResponse: + msg.Payload, set = w.TimeoutNowResponse, set-boolToInt(w.TimeoutNowResponse != nil) case internal.MessageTypeHeartbeat: if set != 0 { return internal.Message{}, errors.New("heartbeat message carries a payload") @@ -212,6 +223,10 @@ func isNilPayload(p any) bool { return v == nil case *internal.InstallSnapshotResponse: return v == nil + case *internal.TimeoutNowRequest: + return v == nil + case *internal.TimeoutNowResponse: + return v == nil default: return false } diff --git a/extensions/consensus/transport/grpc.go b/extensions/consensus/transport/grpc.go index 9e01f2226..b05de8dcd 100644 --- a/extensions/consensus/transport/grpc.go +++ b/extensions/consensus/transport/grpc.go @@ -4,6 +4,8 @@ import ( "context" "crypto/tls" "fmt" + "net" + "strconv" "sync" "time" @@ -11,19 +13,62 @@ import ( "github.com/xraph/forge/errors" "github.com/xraph/forge/extensions/consensus/internal" "google.golang.org/grpc" + "google.golang.org/grpc/backoff" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/keepalive" + "google.golang.org/grpc/peer" + "google.golang.org/grpc/status" +) + +const ( + // grpcServiceName is the hand written gRPC service the transport serves. + // There is no .proto file: its one method carries the wire envelope bytes + // through envelopeCodec, so every transport shares one message format. + grpcServiceName = "forge.consensus.raft.v1.Transport" + // grpcSendMethod is the full name of the unary call that delivers one + // message. + grpcSendMethod = "/" + grpcServiceName + "/Send" + + // grpcCodecName becomes the content-subtype of every call + // (application/grpc+raft-envelope). + grpcCodecName = "raft-envelope" + + // grpcMinPingInterval is the shortest client keepalive interval the + // server tolerates. gRPC clients never ping more often than every 10s, so + // this only cuts off misbehaving peers. + grpcMinPingInterval = 5 * time.Second + + // grpcGracefulStopTimeout bounds how long Stop waits for in-flight calls + // before it closes connections outright. + grpcGracefulStopTimeout = time.Second + + // grpcMaxHeaderListSize caps request metadata. Raft calls only carry the + // standard gRPC headers. + grpcMaxHeaderListSize = 16 << 10 ) // GRPCTransport implements gRPC-based network transport. +// +// Each message is one unary call to forge.consensus.raft.v1.Transport/Send. +// The request is the JSON wire envelope, carried as raw bytes by a custom +// codec instead of protobuf, so the receiver checks the protocol version and +// payload exactly as the TCP and HTTP transports do. The receiver queues the +// message and answers with an empty message; Raft responses travel back as +// separate messages and are matched to their request by RequestID. Each node +// keeps one client connection per peer and reuses it for every call. type GRPCTransport struct { - id string - address string - port int - server *grpc.Server - peers map[string]*grpcPeerConn - peersMu sync.RWMutex - inbox chan internal.Message - logger forge.Logger - tlsConfig *tls.Config + id string + address string + port int + config GRPCTransportConfig + server *grpc.Server + listener *connTrackingListener + peers map[string]*grpcPeerConn + peersMu sync.RWMutex + inbox chan internal.Message + logger forge.Logger // Lifecycle started bool @@ -33,39 +78,74 @@ type GRPCTransport struct { mu sync.RWMutex } -// grpcPeerConn represents a connection to a peer. +// grpcPeerConn holds the client connection to one peer. The connection is +// created on the first Send and shared by every later call. type grpcPeerConn struct { - nodeID string - address string - port int - conn *grpc.ClientConn - connMu sync.RWMutex - lastUsed time.Time + nodeID string + address string + port int + + connMu sync.Mutex + conn *grpc.ClientConn + removed bool } // GRPCTransportConfig contains gRPC transport configuration. type GRPCTransportConfig struct { - NodeID string - Address string - Port int - BufferSize int - MaxConnections int - ConnectionTimeout time.Duration - RequestTimeout time.Duration - KeepAliveTime time.Duration - KeepAliveTimeout time.Duration + NodeID string + // Address to listen on. Empty means 127.0.0.1; set it explicitly (for + // example to 0.0.0.0) to accept peers from other hosts. + Address string + Port int + BufferSize int + // MaxConnections caps concurrent inbound connections. Defaults to 128. + MaxConnections int + // ConnectionTimeout bounds connecting to a peer, and the handshake of an + // inbound connection. + ConnectionTimeout time.Duration + // RequestTimeout bounds one Send when the caller's context has no + // earlier deadline. + RequestTimeout time.Duration + // KeepAliveTime is how often an idle connection is pinged, and + // KeepAliveTimeout how long a ping may go unanswered before the + // connection is closed. + KeepAliveTime time.Duration + KeepAliveTimeout time.Duration + // IdleTimeout closes an inbound connection that has carried no call for + // this long. The sender reconnects on its next message. + IdleTimeout time.Duration + // MaxConcurrentStreams caps concurrent calls on one inbound connection. + // Defaults to 256. MaxConcurrentStreams uint32 - TLSConfig *tls.Config + + // MaxMessageSize is the largest message accepted or sent, in bytes. + // Defaults to DefaultMaxMessageSize. + MaxMessageSize int + + // TLSConfig enables TLS for both the server and outbound connections. It + // must hold this node's certificate and the CA that signs its peers; + // TLSManager.GetTLSConfig builds one. + TLSConfig *tls.Config + // RequirePeerIdentity rejects any message whose From is not named by the + // caller's client certificate, and verifies that each dialed peer's + // certificate names that peer. It requires TLSConfig with ClientAuth set + // to tls.RequireAndVerifyClientCert, and every node certificate must carry + // its node ID as a DNS subject alternative name. + RequirePeerIdentity bool } // NewGRPCTransport creates a new gRPC transport. func NewGRPCTransport(config GRPCTransportConfig, logger forge.Logger) *GRPCTransport { + if config.Address == "" { + config.Address = DefaultBindAddress + } + if config.BufferSize == 0 { config.BufferSize = 100 } - if config.MaxConnections == 0 { - config.MaxConnections = 100 + if config.MaxConnections <= 0 { + config.MaxConnections = 128 } if config.ConnectionTimeout == 0 { @@ -84,33 +164,120 @@ func NewGRPCTransport(config GRPCTransportConfig, logger forge.Logger) *GRPCTran config.KeepAliveTimeout = 10 * time.Second } + if config.IdleTimeout == 0 { + config.IdleTimeout = 2 * time.Minute + } + + if config.MaxConcurrentStreams == 0 { + config.MaxConcurrentStreams = 256 + } + + if config.MaxMessageSize <= 0 { + config.MaxMessageSize = DefaultMaxMessageSize + } + return &GRPCTransport{ - id: config.NodeID, - address: config.Address, - port: config.Port, - peers: make(map[string]*grpcPeerConn), - inbox: make(chan internal.Message, config.BufferSize), - logger: logger, - tlsConfig: config.TLSConfig, + id: config.NodeID, + address: config.Address, + port: config.Port, + config: config, + peers: make(map[string]*grpcPeerConn), + inbox: make(chan internal.Message, config.BufferSize), + logger: logger, } } -// ErrGRPCNotImplemented is returned by the gRPC transport, which has no -// message service behind it yet. Use the TCP or HTTP transport. -var ErrGRPCNotImplemented = errors.New("consensus gRPC transport is not implemented: use the TCP or HTTP transport") - -// Start reports ErrGRPCNotImplemented. The transport used to start without -// listening on anything, so a cluster configured with it looked healthy while -// no node could reach another. +// Start starts the gRPC server. The listener is opened before Start returns, +// so a port that cannot be bound is reported to the caller. func (gt *GRPCTransport) Start(ctx context.Context) error { - gt.logger.Error("gRPC transport is not implemented", + gt.mu.Lock() + defer gt.mu.Unlock() + + if gt.started { + return internal.ErrAlreadyStarted + } + + if err := checkIdentityTLS(gt.config.TLSConfig, gt.config.RequirePeerIdentity); err != nil { + return fmt.Errorf("grpc transport: %w", err) + } + + var listenConfig net.ListenConfig + + listener, err := listenConfig.Listen(ctx, "tcp", net.JoinHostPort(gt.address, strconv.Itoa(gt.port))) + if err != nil { + return fmt.Errorf("failed to start gRPC listener: %w", err) + } + + if addr, ok := listener.Addr().(*net.TCPAddr); ok && gt.port == 0 { + gt.port = addr.Port + } + + // The cap counts raw connections, so a client stuck in the TLS handshake + // holds a slot too. + tracked := newConnTrackingListener(newLimitListener(listener, gt.config.MaxConnections)) + + // The lifecycle context is not derived from ctx's cancellation: callers + // commonly pass a startup context that ends before the transport stops. + lifecycle, cancel := context.WithCancel(context.WithoutCancel(ctx)) + + server := grpc.NewServer(gt.serverOptions()...) + server.RegisterService(&grpcServiceDesc, &grpcReceiver{transport: gt, ctx: lifecycle}) + + gt.ctx, gt.cancel = lifecycle, cancel + gt.listener = tracked + gt.server = server + + gt.wg.Go(func() { + if err := server.Serve(tracked); err != nil && !errors.Is(err, grpc.ErrServerStopped) { + gt.logger.Error("gRPC server error", + forge.F("error", err), + ) + } + }) + + gt.started = true + + gt.logger.Info("gRPC transport started", forge.F("node_id", gt.id), + forge.F("address", tracked.Addr().String()), + forge.F("tls", gt.config.TLSConfig != nil), + forge.F("peer_identity", gt.config.RequirePeerIdentity), ) - return ErrGRPCNotImplemented + return nil } -// Stop stops the gRPC transport. +func (gt *GRPCTransport) serverOptions() []grpc.ServerOption { + creds := insecure.NewCredentials() + if gt.config.TLSConfig != nil { + creds = credentials.NewTLS(gt.config.TLSConfig.Clone()) + } + + return []grpc.ServerOption{ + grpc.Creds(creds), + grpc.ForceServerCodec(envelopeCodec{}), + grpc.MaxRecvMsgSize(gt.config.MaxMessageSize), + grpc.MaxSendMsgSize(gt.config.MaxMessageSize), + grpc.MaxConcurrentStreams(gt.config.MaxConcurrentStreams), + grpc.MaxHeaderListSize(grpcMaxHeaderListSize), + grpc.ConnectionTimeout(gt.config.ConnectionTimeout), + grpc.KeepaliveParams(keepalive.ServerParameters{ + MaxConnectionIdle: gt.config.IdleTimeout, + Time: gt.config.KeepAliveTime, + Timeout: gt.config.KeepAliveTimeout, + }), + // Peers ping idle connections. The default policy would close a + // connection whose client pings more often than every 5 minutes. + grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{ + MinTime: grpcMinPingInterval, + PermitWithoutStream: true, + }), + } +} + +// Stop stops the server and closes every inbound and outbound connection. +// In-flight calls get a short grace period, so Stop returns promptly even +// when a peer stops responding. func (gt *GRPCTransport) Stop(ctx context.Context) error { gt.mu.Lock() @@ -120,34 +287,29 @@ func (gt *GRPCTransport) Stop(ctx context.Context) error { return internal.ErrNotStarted } + gt.started = false + server, listener, cancel := gt.server, gt.listener, gt.cancel + gt.server, gt.listener = nil, nil gt.mu.Unlock() - if gt.cancel != nil { - gt.cancel() + if cancel != nil { + cancel() } - // Graceful shutdown of gRPC server - if gt.server != nil { - gt.server.GracefulStop() - } - - // Close all peer connections - gt.peersMu.Lock() + gt.peersMu.RLock() for _, peer := range gt.peers { peer.connMu.Lock() - - if peer.conn != nil { - peer.conn.Close() - } - + peer.closeLocked(gt.logger) peer.connMu.Unlock() } - gt.peers = make(map[string]*grpcPeerConn) - gt.peersMu.Unlock() + gt.peersMu.RUnlock() + + if server != nil { + stopServer(ctx, server, listener) + } - // Wait for goroutines done := make(chan struct{}) go func() { @@ -165,10 +327,167 @@ func (gt *GRPCTransport) Stop(ctx context.Context) error { return nil } -// Send reports ErrGRPCNotImplemented instead of dropping the message and -// returning success, as it used to. +// stopServer drains the server, and closes it outright once the grace period +// or ctx runs out. grpc.Server waits for every handshake in progress before +// it stops, even in Stop, so the raw connections are closed first: a client +// that connects and then stays silent would otherwise hold Stop for the whole +// ConnectionTimeout. +func stopServer(ctx context.Context, server *grpc.Server, listener *connTrackingListener) { + drained := make(chan struct{}) + + go func() { + server.GracefulStop() + close(drained) + }() + + timer := time.NewTimer(grpcGracefulStopTimeout) + defer timer.Stop() + + select { + case <-drained: + return + case <-timer.C: + case <-ctx.Done(): + } + + listener.closeAll() + server.Stop() + + select { + case <-drained: + case <-ctx.Done(): + } +} + +// Send delivers a message to a peer. It returns once the peer has queued the +// message, or with the peer's reason for refusing it: ErrProtocolVersion for a +// peer on another wire protocol version, and ErrMessageTooLarge for a message +// over either side's limit. func (gt *GRPCTransport) Send(ctx context.Context, target string, message any) error { - return ErrGRPCNotImplemented + data, _, err := encodeMessage(message) + if err != nil { + return err + } + + if len(data) > gt.config.MaxMessageSize { + return fmt.Errorf("%w: %d bytes, limit %d", ErrMessageTooLarge, len(data), gt.config.MaxMessageSize) + } + + gt.peersMu.RLock() + peer, exists := gt.peers[target] + gt.peersMu.RUnlock() + + if !exists { + return fmt.Errorf("peer %s not found", target) + } + + conn, lifecycle, err := gt.clientFor(peer) + if err != nil { + return err + } + + callCtx, cancel := context.WithTimeout(ctx, gt.config.RequestTimeout) + defer cancel() + + stop := context.AfterFunc(lifecycle, cancel) + defer stop() + + if err := conn.Invoke(callCtx, grpcSendMethod, &envelopeFrame{data: data}, &envelopeFrame{}); err != nil { + return sendError(target, err) + } + + return nil +} + +// sendError maps the status a peer answered with onto the errors the other +// transports return. +func sendError(target string, err error) error { + st, ok := status.FromError(err) + if !ok { + return fmt.Errorf("failed to send to %s: %w", target, err) + } + + switch st.Code() { + case codes.FailedPrecondition: + return fmt.Errorf("%w: peer %s refused the message: %s", ErrProtocolVersion, target, st.Message()) + case codes.ResourceExhausted: + return fmt.Errorf("%w: peer %s refused the message: %s", ErrMessageTooLarge, target, st.Message()) + default: + return fmt.Errorf("failed to send to %s: %w", target, err) + } +} + +// clientFor returns the peer's client connection, creating it on first use, +// and the lifecycle context the call must not outlive. +func (gt *GRPCTransport) clientFor(peer *grpcPeerConn) (*grpc.ClientConn, context.Context, error) { + peer.connMu.Lock() + defer peer.connMu.Unlock() + + // Stop clears started under mu before it closes peer connections, so + // holding mu.RLock here means it cannot miss a connection created now. + gt.mu.RLock() + defer gt.mu.RUnlock() + + if !gt.started || gt.ctx == nil { + return nil, nil, internal.ErrNotStarted + } + + if peer.removed { + return nil, nil, fmt.Errorf("peer %s not found", peer.nodeID) + } + + if peer.conn != nil { + return peer.conn, gt.ctx, nil + } + + target := net.JoinHostPort(peer.address, strconv.Itoa(peer.port)) + + conn, err := grpc.NewClient("passthrough:///"+target, gt.dialOptions(peer.nodeID)...) + if err != nil { + return nil, nil, fmt.Errorf("failed to create gRPC client for peer %s: %w", peer.nodeID, err) + } + + peer.conn = conn + + gt.logger.Info("created gRPC client for peer", + forge.F("peer_id", peer.nodeID), + forge.F("address", target), + ) + + return conn, gt.ctx, nil +} + +func (gt *GRPCTransport) dialOptions(peerID string) []grpc.DialOption { + creds := insecure.NewCredentials() + if gt.config.TLSConfig != nil { + creds = credentials.NewTLS(clientTLSFor(gt.config.TLSConfig, peerID, gt.config.RequirePeerIdentity)) + } + + return []grpc.DialOption{ + grpc.WithTransportCredentials(creds), + grpc.WithDefaultCallOptions( + grpc.ForceCodec(envelopeCodec{}), + grpc.MaxCallSendMsgSize(gt.config.MaxMessageSize), + grpc.MaxCallRecvMsgSize(gt.config.MaxMessageSize), + ), + grpc.WithKeepaliveParams(keepalive.ClientParameters{ + Time: gt.config.KeepAliveTime, + Timeout: gt.config.KeepAliveTimeout, + PermitWithoutStream: true, + }), + // The default backoff grows to two minutes, which would leave a + // restarted peer unreachable long after it is back. Raft retries on + // every heartbeat, so reconnect attempts stay frequent. + grpc.WithConnectParams(grpc.ConnectParams{ + Backoff: backoff.Config{ + BaseDelay: 100 * time.Millisecond, + Multiplier: 1.6, + Jitter: 0.2, + MaxDelay: time.Second, + }, + MinConnectTimeout: gt.config.ConnectionTimeout, + }), + } } // Receive returns a channel for receiving messages. @@ -201,7 +520,7 @@ func (gt *GRPCTransport) AddPeer(nodeID, address string, port int) error { return nil } -// RemovePeer removes a peer from the transport. +// RemovePeer removes a peer from the transport and closes its connection. func (gt *GRPCTransport) RemovePeer(nodeID string) error { gt.peersMu.Lock() defer gt.peersMu.Unlock() @@ -211,13 +530,9 @@ func (gt *GRPCTransport) RemovePeer(nodeID string) error { return internal.ErrNodeNotFound } - // Close connection peer.connMu.Lock() - - if peer.conn != nil { - peer.conn.Close() - } - + peer.removed = true + peer.closeLocked(gt.logger) peer.connMu.Unlock() delete(gt.peers, nodeID) @@ -232,5 +547,243 @@ func (gt *GRPCTransport) RemovePeer(nodeID string) error { // GetAddress returns the local address. func (gt *GRPCTransport) GetAddress() string { - return fmt.Sprintf("%s:%d", gt.address, gt.port) + gt.mu.RLock() + defer gt.mu.RUnlock() + + return net.JoinHostPort(gt.address, strconv.Itoa(gt.port)) +} + +// closeLocked closes the client connection. peer.connMu is held. +func (p *grpcPeerConn) closeLocked(logger forge.Logger) { + if p.conn == nil { + return + } + + if err := p.conn.Close(); err != nil { + logger.Debug("failed to close gRPC client connection", + forge.F("peer_id", p.nodeID), + forge.F("error", err), + ) + } + + p.conn = nil +} + +// connTrackingListener records the connections it accepts so Stop can close +// those gRPC does not own yet, such as ones still in the TLS handshake. +type connTrackingListener struct { + net.Listener + + mu sync.Mutex + conns map[*trackedConn]struct{} + closed bool +} + +func newConnTrackingListener(l net.Listener) *connTrackingListener { + return &connTrackingListener{Listener: l, conns: make(map[*trackedConn]struct{})} +} + +func (l *connTrackingListener) Accept() (net.Conn, error) { + conn, err := l.Listener.Accept() + if err != nil { + return nil, err + } + + l.mu.Lock() + defer l.mu.Unlock() + + if l.closed { + _ = conn.Close() + + return nil, net.ErrClosed + } + + tc := &trackedConn{Conn: conn, owner: l} + l.conns[tc] = struct{}{} + + return tc, nil +} + +// closeAll closes the listener and every connection it accepted. +func (l *connTrackingListener) closeAll() { + l.mu.Lock() + l.closed = true + conns := make([]*trackedConn, 0, len(l.conns)) + + for c := range l.conns { + conns = append(conns, c) + } + + l.mu.Unlock() + + _ = l.Close() + + for _, c := range conns { + _ = c.Close() + } +} + +func (l *connTrackingListener) forget(c *trackedConn) { + l.mu.Lock() + delete(l.conns, c) + l.mu.Unlock() +} + +// trackedConn removes itself from its listener when closed. +type trackedConn struct { + net.Conn + + owner *connTrackingListener + once sync.Once +} + +func (c *trackedConn) Close() error { + err := c.Conn.Close() + c.once.Do(func() { c.owner.forget(c) }) + + return err +} + +// grpcEnvelopeServer is the handler type of grpcServiceDesc. +type grpcEnvelopeServer interface { + deliver(ctx context.Context, data []byte) error +} + +// grpcServiceDesc describes the transport's service by hand, in place of the +// code protoc would generate. +var grpcServiceDesc = grpc.ServiceDesc{ + ServiceName: grpcServiceName, + HandlerType: (*grpcEnvelopeServer)(nil), + Methods: []grpc.MethodDesc{{ + MethodName: "Send", + Handler: grpcSendHandler, + }}, + Streams: []grpc.StreamDesc{}, + Metadata: "extensions/consensus/transport/grpc.go", +} + +// grpcSendHandler decodes the request frame and hands it to the receiver. Its +// signature is the one gRPC requires of a unary method handler. +func grpcSendHandler(srv any, ctx context.Context, dec func(any) error, _ grpc.UnaryServerInterceptor) (any, error) { + var in envelopeFrame + if err := dec(&in); err != nil { + return nil, err + } + + server, ok := srv.(grpcEnvelopeServer) + if !ok { + return nil, status.Errorf(codes.Internal, "unexpected gRPC service implementation %T", srv) + } + + if err := server.deliver(ctx, in.data); err != nil { + return nil, err + } + + return &envelopeFrame{}, nil +} + +// grpcReceiver serves the Send method for one run of the transport. It holds +// that run's lifecycle context, so a restarted transport never mixes the two. +type grpcReceiver struct { + transport *GRPCTransport + ctx context.Context //nolint:containedctx // lifecycle context of the server this receiver is registered on +} + +// deliver decodes one envelope, checks its sender and queues it. The status +// code tells the sender why a message was refused. +func (r *grpcReceiver) deliver(ctx context.Context, data []byte) error { + gt := r.transport + remote := "unknown" + + p, hasPeer := peer.FromContext(ctx) + if hasPeer && p.Addr != nil { + remote = p.Addr.String() + } + + msg, err := decodeMessage(data) + if err != nil { + if errors.Is(err, ErrProtocolVersion) { + // The sender's Send returns this, naming both versions. + gt.logger.Error("rejecting message from a peer on another wire protocol version", + forge.F("remote", remote), + forge.F("error", err), + ) + + return status.Error(codes.FailedPrecondition, err.Error()) + } + + gt.logger.Warn("rejecting malformed message", + forge.F("remote", remote), + forge.F("error", err), + ) + + return status.Error(codes.InvalidArgument, "invalid message") + } + + if gt.config.RequirePeerIdentity { + var state *tls.ConnectionState + + if hasPeer { + if info, ok := p.AuthInfo.(credentials.TLSInfo); ok { + state = &info.State + } + } + + if err := verifySender(state, msg.From); err != nil { + gt.logger.Warn("rejecting message with unverified sender", + forge.F("remote", remote), + forge.F("error", err), + ) + + return status.Error(codes.PermissionDenied, "sender does not match client certificate") + } + } + + select { + case gt.inbox <- msg: + gt.logger.Debug("received gRPC message", + forge.F("from", msg.From), + forge.F("type", msg.Type), + ) + + return nil + case <-r.ctx.Done(): + return status.Error(codes.Unavailable, "transport shutting down") + default: + return status.Error(codes.Unavailable, "inbox full") + } +} + +// envelopeFrame is the request and response message of the Send method: the +// encoded wire envelope, or nothing in a reply. +type envelopeFrame struct { + data []byte +} + +// envelopeCodec passes envelope bytes through gRPC unchanged. gRPC hands +// Unmarshal a slice it no longer uses, so the frame may keep it. +type envelopeCodec struct{} + +func (envelopeCodec) Marshal(v any) ([]byte, error) { + frame, ok := v.(*envelopeFrame) + if !ok { + return nil, fmt.Errorf("raft envelope codec cannot marshal %T", v) + } + + return frame.data, nil +} + +func (envelopeCodec) Unmarshal(data []byte, v any) error { + frame, ok := v.(*envelopeFrame) + if !ok { + return fmt.Errorf("raft envelope codec cannot unmarshal into %T", v) + } + + frame.data = data + + return nil +} + +func (envelopeCodec) Name() string { + return grpcCodecName } diff --git a/extensions/consensus/transport/grpc_test.go b/extensions/consensus/transport/grpc_test.go new file mode 100644 index 000000000..60e5e3238 --- /dev/null +++ b/extensions/consensus/transport/grpc_test.go @@ -0,0 +1,402 @@ +package transport + +import ( + "context" + "crypto/tls" + "errors" + "net" + "strings" + "sync" + "testing" + "time" + + "github.com/xraph/forge" + "github.com/xraph/forge/extensions/consensus/internal" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" +) + +func startGRPC(t *testing.T, cfg GRPCTransportConfig) *GRPCTransport { + t.Helper() + + cfg.Address = "127.0.0.1" + tr := NewGRPCTransport(cfg, forge.NewNoopLogger()) + + if err := tr.Start(context.Background()); err != nil { + t.Fatal(err) + } + + stopOnCleanup(t, tr) + + return tr +} + +// rawGRPCCall sends data to the transport's Send method as is, the way a peer +// on another build would. +func rawGRPCCall(t *testing.T, addr string, creds credentials.TransportCredentials, data []byte) error { + t.Helper() + + conn, err := grpc.NewClient("passthrough:///"+addr, + grpc.WithTransportCredentials(creds), + grpc.WithDefaultCallOptions(grpc.ForceCodec(envelopeCodec{})), + ) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + + return conn.Invoke(ctx, grpcSendMethod, &envelopeFrame{data: data}, &envelopeFrame{}) +} + +func voteFrom(from string, requestID uint64) internal.Message { + return internal.Message{ + Type: internal.MessageTypeRequestVote, From: from, To: "b", RequestID: requestID, + Payload: &internal.RequestVoteRequest{Term: 9, CandidateID: from}, + } +} + +// Raft messages sent over gRPC arrive typed and keep their request ID, and +// every call to a peer shares one client connection. +func TestGRPCTransportDeliversTypedMessages(t *testing.T) { + a := startGRPC(t, GRPCTransportConfig{NodeID: "a"}) + b := startGRPC(t, GRPCTransportConfig{NodeID: "b"}) + + if err := a.AddPeer("b", "127.0.0.1", portOf(t, b.GetAddress())); err != nil { + t.Fatal(err) + } + + for i := range 3 { + if err := a.Send(context.Background(), "b", voteFrom("a", uint64(i+1))); err != nil { + t.Fatal(err) + } + + m := receive(t, b) + if req, ok := m.Payload.(*internal.RequestVoteRequest); !ok || req.CandidateID != "a" || m.RequestID != uint64(i+1) { + t.Fatalf("received %+v (payload %T)", m, m.Payload) + } + } + + snapshot := internal.Message{ + Type: internal.MessageTypeInstallSnapshot, From: "a", To: "b", + Payload: &internal.InstallSnapshotRequest{Term: 2, LeaderID: "a", Offset: 64, Data: []byte("chunk"), Done: true}, + } + if err := a.Send(context.Background(), "b", snapshot); err != nil { + t.Fatal(err) + } + + if req, ok := receive(t, b).Payload.(*internal.InstallSnapshotRequest); !ok || string(req.Data) != "chunk" || req.Offset != 64 || !req.Done { + t.Fatalf("snapshot chunk arrived as %+v", req) + } + + peer := a.peers["b"] + peer.connMu.Lock() + first := peer.conn + peer.connMu.Unlock() + + var wg sync.WaitGroup + + for i := range 20 { + wg.Go(func() { + if err := a.Send(context.Background(), "b", voteFrom("a", uint64(100+i))); err != nil { + t.Error(err) + } + }) + } + + wg.Wait() + + for range 20 { + receive(t, b) + } + + peer.connMu.Lock() + defer peer.connMu.Unlock() + + if first == nil || peer.conn != first { + t.Fatal("concurrent sends did not reuse the peer's client connection") + } +} + +// Messages over MaxMessageSize are refused by the sender, and by a receiver +// whose limit is smaller than the sender's. +func TestGRPCTransportRejectsOversizedMessages(t *testing.T) { + b := startGRPC(t, GRPCTransportConfig{NodeID: "b", MaxMessageSize: 1024}) + small := startGRPC(t, GRPCTransportConfig{NodeID: "a", MaxMessageSize: 1024}) + large := startGRPC(t, GRPCTransportConfig{NodeID: "a", MaxMessageSize: 1 << 20}) + + bPort := portOf(t, b.GetAddress()) + _ = small.AddPeer("b", "127.0.0.1", bPort) + _ = large.AddPeer("b", "127.0.0.1", bPort) + + big := internal.Message{ + Type: internal.MessageTypeAppendEntries, From: "a", + Payload: &internal.AppendEntriesRequest{Entries: []internal.LogEntry{{Data: make([]byte, 4096)}}}, + } + + if err := small.Send(context.Background(), "b", big); !errors.Is(err, ErrMessageTooLarge) { + t.Fatalf("Send over the local limit returned %v, want ErrMessageTooLarge", err) + } + + if err := large.Send(context.Background(), "b", big); !errors.Is(err, ErrMessageTooLarge) { + t.Fatalf("Send over the peer's limit returned %v, want ErrMessageTooLarge", err) + } + + expectNothing(t, b) + + // The connection is still usable for messages within the limit. + if err := large.Send(context.Background(), "b", voteFrom("a", 1)); err != nil { + t.Fatal(err) + } + + receive(t, b) +} + +// A message in another wire protocol version is refused, and the sender is +// told which versions disagree. Malformed envelopes are refused too. +func TestGRPCTransportRejectsProtocolVersionMismatch(t *testing.T) { + b := startGRPC(t, GRPCTransportConfig{NodeID: "b"}) + + future := []byte(`{"v":2,"type":"request_vote","from":"a","request_vote":{"term":9}}`) + + err := rawGRPCCall(t, b.GetAddress(), insecure.NewCredentials(), future) + if status.Code(err) != codes.FailedPrecondition || !strings.Contains(err.Error(), "version 2") || !strings.Contains(err.Error(), "version 1") { + t.Fatalf("version mismatch returned %v, want FailedPrecondition naming both versions", err) + } + + if mapped := sendError("b", err); !errors.Is(mapped, ErrProtocolVersion) { + t.Fatalf("Send would return %v, want ErrProtocolVersion", mapped) + } + + for _, raw := range []string{ + `not json`, + `{"v":1,"type":"append_entries","from":"a"}`, + `{"v":1,"type":"append_entries","from":"a","append_entries":{},"request_vote":{}}`, + } { + if err := rawGRPCCall(t, b.GetAddress(), insecure.NewCredentials(), []byte(raw)); status.Code(err) != codes.InvalidArgument { + t.Fatalf("malformed envelope %s returned %v, want InvalidArgument", raw, err) + } + } + + expectNothing(t, b) +} + +// With mTLS and peer identity checks, a node can only send as itself, a +// client without a certificate cannot connect, and a dialed server must hold +// the certificate of the peer it was dialed as. +func TestGRPCMTLSPeerIdentity(t *testing.T) { + pki := newTestPKI(t) + + a := startGRPC(t, GRPCTransportConfig{NodeID: "a", TLSConfig: pki.mtlsConfig(t, "a"), RequirePeerIdentity: true}) + b := startGRPC(t, GRPCTransportConfig{NodeID: "b", TLSConfig: pki.mtlsConfig(t, "b"), RequirePeerIdentity: true}) + mallory := startGRPC(t, GRPCTransportConfig{NodeID: "m", TLSConfig: pki.mtlsConfig(t, "m"), RequirePeerIdentity: true}) + + bPort := portOf(t, b.GetAddress()) + _ = a.AddPeer("b", "127.0.0.1", bPort) + _ = mallory.AddPeer("b", "127.0.0.1", bPort) + + if err := a.Send(context.Background(), "b", voteFrom("a", 1)); err != nil { + t.Fatalf("legitimate send failed: %v", err) + } + + if m := receive(t, b); m.From != "a" { + t.Fatalf("received %+v", m) + } + + // Mallory holds a valid cluster certificate but claims to be a. + err := mallory.Send(context.Background(), "b", voteFrom("a", 2)) + if status.Code(err) != codes.PermissionDenied { + t.Fatalf("spoofed send returned %v, want PermissionDenied", err) + } + + expectNothing(t, b) + + // Sending as itself works for mallory, so the refusal was about the + // claimed identity and not the connection. + if err := mallory.Send(context.Background(), "b", voteFrom("m", 3)); err != nil { + t.Fatalf("mallory sending as itself failed: %v", err) + } + + if m := receive(t, b); m.From != "m" { + t.Fatalf("received %+v", m) + } + + // A client without any certificate cannot complete the handshake. + noCert := credentials.NewTLS(&tls.Config{InsecureSkipVerify: true, MinVersion: tls.VersionTLS12}) + if err := rawGRPCCall(t, b.GetAddress(), noCert, []byte(`{"v":1,"type":"request_vote","from":"a","request_vote":{"term":9}}`)); err == nil { + t.Fatal("a client without a certificate delivered a message") + } + + expectNothing(t, b) + + // a believes c lives at b's address; b's certificate does not name c, so + // the connection is refused. + _ = a.AddPeer("c", "127.0.0.1", bPort) + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + + if err := a.Send(ctx, "c", voteFrom("a", 4)); err == nil { + t.Fatal("a delivered a message to a server whose certificate names someone else") + } + + expectNothing(t, b) +} + +// Asking for peer identity without mutual TLS fails at startup. +func TestGRPCPeerIdentityRequiresMTLS(t *testing.T) { + for name, cfg := range map[string]GRPCTransportConfig{ + "no tls": {NodeID: "a", RequirePeerIdentity: true}, + "no client auth": {NodeID: "a", RequirePeerIdentity: true, TLSConfig: &tls.Config{MinVersion: tls.VersionTLS12}}, + } { + tr := NewGRPCTransport(cfg, forge.NewNoopLogger()) + if err := tr.Start(context.Background()); err == nil { + _ = tr.Stop(context.Background()) + + t.Fatalf("%s: gRPC transport started with peer identity checks but without mutual TLS", name) + } + } +} + +// Without an explicit address the transport listens on loopback only. +func TestGRPCTransportDefaultsToLoopback(t *testing.T) { + if got := NewGRPCTransport(GRPCTransportConfig{NodeID: "a"}, forge.NewNoopLogger()).address; got != "127.0.0.1" { + t.Fatalf("gRPC default address %q", got) + } +} + +// Inbound connections beyond MaxConnections wait until a slot frees up. +func TestGRPCTransportCapsInboundConnections(t *testing.T) { + b := startGRPC(t, GRPCTransportConfig{NodeID: "b", MaxConnections: 1}) + a := startGRPC(t, GRPCTransportConfig{NodeID: "a"}) + _ = a.AddPeer("b", "127.0.0.1", portOf(t, b.GetAddress())) + + hog, err := dialTest(t, b.GetAddress()) + if err != nil { + t.Fatal(err) + } + + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + + if err := a.Send(ctx, "b", voteFrom("a", 1)); err == nil { + t.Fatal("a second connection was served over a cap of 1") + } + + _ = hog.Close() + + deadline := time.Now().Add(10 * time.Second) + + for { + err := a.Send(context.Background(), "b", voteFrom("a", 2)) + if err == nil { + break + } + + if time.Now().After(deadline) { + t.Fatalf("send still failing after the slot was freed: %v", err) + } + + time.Sleep(50 * time.Millisecond) + } + + if m := receive(t, b); m.RequestID != 2 { + t.Fatalf("received %+v", m) + } +} + +// Stop returns promptly with inbound and outbound connections open, closes +// them, and later sends fail instead of hanging. +func TestGRPCTransportStopsPromptly(t *testing.T) { + pki := newTestPKI(t) + + for name, tlsFor := range map[string]func(string) *tls.Config{ + "plaintext": func(string) *tls.Config { return nil }, + "mtls": func(id string) *tls.Config { return pki.mtlsConfig(t, id) }, + } { + t.Run(name, func(t *testing.T) { + aTLS := tlsFor("a") + identity := aTLS != nil + a := startGRPC(t, GRPCTransportConfig{NodeID: "a", TLSConfig: aTLS, RequirePeerIdentity: identity}) + + b := NewGRPCTransport(GRPCTransportConfig{ + NodeID: "b", Address: "127.0.0.1", TLSConfig: tlsFor("b"), RequirePeerIdentity: identity, + }, forge.NewNoopLogger()) + if err := b.Start(context.Background()); err != nil { + t.Fatal(err) + } + + bAddr := b.GetAddress() + _ = a.AddPeer("b", "127.0.0.1", portOf(t, bAddr)) + _ = b.AddPeer("a", "127.0.0.1", portOf(t, a.GetAddress())) + + if err := a.Send(context.Background(), "b", voteFrom("a", 1)); err != nil { + t.Fatal(err) + } + + receive(t, b) + + bToA := internal.Message{ + Type: internal.MessageTypeRequestVoteResponse, From: "b", To: "a", RequestID: 1, + Payload: &internal.RequestVoteResponse{Term: 9, VoteGranted: true}, + } + if err := b.Send(context.Background(), "a", bToA); err != nil { + t.Fatal(err) + } + + receive(t, a) + + // An idle raw connection that never completes a handshake. + idle, err := dialTest(t, bAddr) + if err != nil { + t.Fatal(err) + } + defer idle.Close() + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + start := time.Now() + + if err := b.Stop(ctx); err != nil { + t.Fatal(err) + } + + if elapsed := time.Since(start); elapsed > 3*time.Second { + t.Fatalf("Stop took %v", elapsed) + } + + if err := b.Send(context.Background(), "a", bToA); !errors.Is(err, internal.ErrNotStarted) { + t.Fatalf("Send after Stop returned %v, want ErrNotStarted", err) + } + + _ = idle.SetReadDeadline(time.Now().Add(3 * time.Second)) + if _, err := idle.Read(make([]byte, 1)); isTimeout(err) { + t.Fatal("Stop left an inbound connection open") + } + + var d net.Dialer + if c, err := d.DialContext(t.Context(), "tcp", bAddr); err == nil { + _ = c.Close() + + t.Fatal("the listener still accepts connections after Stop") + } + + sendCtx, sendCancel := context.WithTimeout(context.Background(), 2*time.Second) + defer sendCancel() + + if err := a.Send(sendCtx, "b", voteFrom("a", 2)); err == nil { + t.Fatal("send to a stopped peer succeeded") + } + + if err := b.Stop(ctx); !errors.Is(err, internal.ErrNotStarted) { + t.Fatalf("second Stop returned %v", err) + } + }) + } +} diff --git a/extensions/consensus/transport/transport_test.go b/extensions/consensus/transport/transport_test.go index e4f0dc9c7..1deb7ae6c 100644 --- a/extensions/consensus/transport/transport_test.go +++ b/extensions/consensus/transport/transport_test.go @@ -119,6 +119,8 @@ func TestEnvelopeRoundTripsEveryRaftPayload(t *testing.T) { internal.MessageTypeRequestVoteResponse: &internal.RequestVoteResponse{Term: 3, VoteGranted: true}, internal.MessageTypeInstallSnapshot: &internal.InstallSnapshotRequest{Term: 3, Data: []byte{1, 2}}, internal.MessageTypeInstallSnapshotResponse: &internal.InstallSnapshotResponse{Term: 3}, + internal.MessageTypeTimeoutNow: &internal.TimeoutNowRequest{Term: 3, LeaderID: "a"}, + internal.MessageTypeTimeoutNowResponse: &internal.TimeoutNowResponse{Term: 3, Success: true}, } for typ, payload := range payloads { @@ -154,6 +156,10 @@ func TestEnvelopeRoundTripsEveryRaftPayload(t *testing.T) { _, ok = msg.Payload.(*internal.InstallSnapshotRequest) case internal.MessageTypeInstallSnapshotResponse: _, ok = msg.Payload.(*internal.InstallSnapshotResponse) + case internal.MessageTypeTimeoutNow: + _, ok = msg.Payload.(*internal.TimeoutNowRequest) + case internal.MessageTypeTimeoutNowResponse: + _, ok = msg.Payload.(*internal.TimeoutNowResponse) } if !ok { @@ -349,21 +355,6 @@ func TestTransportsDefaultToLoopback(t *testing.T) { } } -// The gRPC transport is not implemented and says so instead of pretending. -func TestGRPCTransportFailsLoudly(t *testing.T) { - g := NewGRPCTransport(GRPCTransportConfig{NodeID: "a", Address: "127.0.0.1"}, forge.NewNoopLogger()) - - if err := g.Start(context.Background()); !errors.Is(err, ErrGRPCNotImplemented) { - t.Fatalf("Start returned %v", err) - } - - _ = g.AddPeer("b", "127.0.0.1", 1) - - if err := g.Send(context.Background(), "b", internal.Message{Type: internal.MessageTypeRequestVote}); !errors.Is(err, ErrGRPCNotImplemented) { - t.Fatalf("Send returned %v", err) - } -} - // testPKI writes a CA and per-node certificates (node ID as DNS SAN) to dir. type testPKI struct { dir string From 1180c1b6fedb9048a36ee9429a5cd4802f5af6f2 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Tue, 17 Nov 2026 19:34:20 -0600 Subject: [PATCH 17/17] fix(consensus): mac api keys before comparing and bound the sealed value size --- extensions/consensus/security/apikey.go | 27 +++++++++++++++------- extensions/consensus/storage/encryption.go | 5 ++++ 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/extensions/consensus/security/apikey.go b/extensions/consensus/security/apikey.go index 49524b08f..ed0432478 100644 --- a/extensions/consensus/security/apikey.go +++ b/extensions/consensus/security/apikey.go @@ -1,8 +1,9 @@ package security import ( + "crypto/hmac" + "crypto/rand" "crypto/sha256" - "crypto/subtle" "net/http" "strings" @@ -11,18 +12,28 @@ import ( // APIKeyMiddleware rejects requests that do not present key, either as // "Authorization: Bearer " or in the X-API-Key header. Both values are -// hashed before a constant-time comparison, so neither the key's contents nor -// its length leak through timing. A rejected request gets 401 and the wrapped -// handler is not called. +// MACed under a random per-middleware secret before a constant-time +// comparison, so neither the key's contents nor its length leak through +// timing. A rejected request gets 401 and the wrapped handler is not called. func APIKeyMiddleware(key string) forge.Middleware { - want := sha256.Sum256([]byte(key)) + secret := make([]byte, sha256.Size) + if _, err := rand.Read(secret); err != nil { + panic("consensus security: cannot read random bytes: " + err.Error()) + } + + mac := func(v string) []byte { + h := hmac.New(sha256.New, secret) + h.Write([]byte(v)) + + return h.Sum(nil) + } + + want := mac(key) return func(next forge.Handler) forge.Handler { return func(ctx forge.Context) error { provided := presentedKey(ctx.Request()) - got := sha256.Sum256([]byte(provided)) - - if key == "" || provided == "" || subtle.ConstantTimeCompare(got[:], want[:]) != 1 { + if key == "" || provided == "" || !hmac.Equal(mac(provided), want) { ctx.Response().Header().Set("WWW-Authenticate", `Bearer realm="consensus-admin"`) return ctx.JSON(http.StatusUnauthorized, map[string]any{ diff --git a/extensions/consensus/storage/encryption.go b/extensions/consensus/storage/encryption.go index de45440d5..ebd62fdb4 100644 --- a/extensions/consensus/storage/encryption.go +++ b/extensions/consensus/storage/encryption.go @@ -8,6 +8,7 @@ import ( "crypto/rand" "encoding/binary" "fmt" + "math" "slices" "strconv" "sync" @@ -207,6 +208,10 @@ func (k *Keyring) sealWith(id uint32, key, plaintext []byte) ([]byte, error) { return nil, fmt.Errorf("%w: key ID %d", ErrUnknownKeyID, id) } + if len(plaintext) > math.MaxInt-EnvelopeOverhead { + return nil, fmt.Errorf("consensus storage: value of %d bytes is too large to encrypt", len(plaintext)) + } + out := make([]byte, headerSize+nonceSize, headerSize+nonceSize+len(plaintext)+tagSize) out[0] = envelopeVersion1 binary.BigEndian.PutUint32(out[1:headerSize], id)