diff --git a/docs/content/docs/extensions/consensus/configuration.mdx b/docs/content/docs/extensions/consensus/configuration.mdx index c0a03d84..d611202b 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 131733bd..87e32b83 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 ccec6b13..40748e79 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 538a2e8f..29b5f097 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 6552a425..c95b10f5 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 7732bf37..f4383084 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 2edf4c51..b3ee7974 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 50744607..9d426306 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 14335211..3d5db7b9 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 00000000..3e8067f8 --- /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 00000000..fdee32b4 --- /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 44ba6b62..1d979950 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 7b5c4147..a23f5362 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 04b74c97..3cad0927 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 d254ac27..96ad0f37 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 6d029fd3..54978621 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 7f46f41f..6fa13bf1 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 00000000..3bcf3ee9 --- /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 00000000..41c24a18 --- /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 d3e80e5b..424b8967 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 0e03b848..c8a81271 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 470f2b0f..6e647bf2 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 f69dfc32..09965dfe 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 00000000..e0d7295a --- /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 00000000..75cfecff --- /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 02006406..72abef91 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 4852157c..eb9cedc2 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 ac1bbb48..a9a28ab0 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 0622420f..a32115f1 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 00000000..c8e7a50d --- /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 00000000..607392ed --- /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 00000000..b2dea24b --- /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 00000000..cdffc3f0 --- /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 00000000..973fadd0 --- /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 00000000..a7bd51c3 --- /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 4df1607d..ebc63328 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 00000000..6968c130 --- /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 00000000..de45440d --- /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 00000000..127f45d9 --- /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 00000000..96f698d5 --- /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 00000000..4df48de2 --- /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 1c014763..6b732b95 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 9e01f222..b05de8dc 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 00000000..60e5e323 --- /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 e4f0dc9c..1deb7ae6 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