handshake

package module
v0.3.5-beta.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 9, 2026 License: AGPL-3.0 Imports: 19 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

handshake

ci codecov

Handshake plugin for the Pilot Protocol daemon. Manages node-to-node trust:

  • listens on port 444 for incoming handshake offers
  • emits handshake.requested events to the daemon
  • persists accepted trust records to trust.json
  • consults the trustedagents allowlist for auto-accept of public peers
  • handles both direct and relayed handshakes (NAT-traversal cases)

Install

import "github.com/pilot-protocol/handshake"

Usage

s := handshake.NewService(handshake.Config{
    TrustPath:         "~/.pilot/trust.json",
    AutoApprovePublic: true,
})
rt.Register(s)

Layout

File What it does
handshake.go Wire format and Manager (in-memory trust + pending state).
runtime.go Daemon-facing interface for trust lookup and auto-approve flag.
service.go *Service — coreapi.Service adapter.

License

AGPL-3.0-or-later. See LICENSE.

Documentation

Overview

Package handshake implements the manual trust-handshake protocol on port 444 (the Pilot Protocol PortHandshake well-known port).

This is the higher-level "establish trust between two nodes" RPC, NOT the L5 wire-level key-exchange (which lives in pkg/daemon/tunnel.go). Two daemons that have not previously met exchange a JSON handshake message over a normal stream connection on port 444; both sides validate signatures, optionally consult an allowlist, and either auto-accept or stash the request for manual approval via pilotctl.

Lifecycle: this plugin sits at L11. The composition root (plugins/runtime or test harness) constructs a Service via NewService(rt Runtime), registers it on the plugin runtime, and the daemon's Start() spawns the listener on PortHandshake via rt.PortListener.

Index

Constants

View Source
const (
	HandshakeRequest = "handshake_request"
	HandshakeAccept  = "handshake_accept"
	HandshakeReject  = "handshake_reject"
	HandshakeRevoke  = "handshake_revoke"
)

Handshake message types.

Variables

This section is empty.

Functions

This section is empty.

Types

type HandshakeMsg

type HandshakeMsg struct {
	Type          string `json:"type"`
	NodeID        uint32 `json:"node_id"`
	PublicKey     string `json:"public_key"`    // base64 Ed25519 public key
	Justification string `json:"justification"` // why the sender wants to connect
	Signature     string `json:"signature"`     // Ed25519 sig over "handshake:<node_id>:<peer_id>"
	Reason        string `json:"reason"`        // rejection reason
	Timestamp     int64  `json:"timestamp"`
}

HandshakeMsg is the wire format for handshake protocol messages on port 444.

type KeyedTrustChecker added in v0.2.6

type KeyedTrustChecker interface {
	IsTrustedWithKey(nodeID uint32, pubKeyB64 string) (name string, ok bool)
}

KeyedTrustChecker is the key-bound form of Runtime.IsTrusted. It is an optional extension: the handshake manager type-asserts its Runtime for it and falls back to IsTrusted when the adapter does not provide it, so existing Runtime implementations keep compiling unchanged.

pubKeyB64 is the base64 Ed25519 key the registry confirmed for the peer: the key it signed a direct request with, or, for a request that came over the registry relay, the key a registry lookup returned. It is never empty: without a confirmed key no auto-accept rule runs. Implementations that carry a pinned key for the node MUST require an exact match and MUST treat "" as a miss; entries with no pin answer the node-ID-only question, matching IsTrusted.

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager handles the trust handshake protocol on port 444.

func NewManager

func NewManager(rt Runtime) *Manager

NewManager constructs a Manager bound to the given Runtime. Loads persisted trust state from disk if the runtime exposes an identity path; otherwise the manager is in-memory only.

func (*Manager) ApproveHandshake

func (hm *Manager) ApproveHandshake(peerNodeID uint32) error

ApproveHandshake approves a pending handshake request.

func (*Manager) IsTrusted

func (hm *Manager) IsTrusted(nodeID uint32) bool

IsTrusted returns whether a peer has been approved, by node ID alone. It is IsTrustedByNodeID under the name the daemon's HandshakeService interface (common/daemonapi) uses.

func (*Manager) IsTrustedByNodeID added in v0.3.4

func (hm *Manager) IsTrustedByNodeID(nodeID uint32) bool

IsTrustedByNodeID reports whether a trust record exists for nodeID, whatever key it is bound to. It answers for the node ID, not for whoever presents it: use it only where no key the peer proved is in scope and the node ID is all the question is about (an outbound dial, a list of trusted peers, a gate before a key exchange that is itself checked against the registry). Where the caller knows the key the peer authenticated with, IsTrustedWithKey checks the record's binding. It has no side effects.

func (*Manager) IsTrustedWithKey added in v0.2.5

func (hm *Manager) IsTrustedWithKey(nodeID uint32, currentKeyB64 string) bool

IsTrustedWithKey returns whether a peer has been approved, given the base64 Ed25519 key that peer currently presents (same encoding as TrustRecord.PublicKey — crypto.EncodePublicKey). Callers pass a key the peer proved, such as the key that authenticated its tunnel session.

  • Bound record, same key: trusted.
  • Bound record, different key: the record does not describe the peer behind this node ID any more, so it is dropped and the answer is false; the peer has to handshake again under its new key.
  • Bound record, empty key: false. With no key to check the binding against, the record cannot vouch for whoever is asking; callers that mean the node ID alone ask IsTrustedByNodeID.
  • Unbound record (a pre-binding snapshot, or a record made over the relay or from a request the registry could not confirm): trusted by node ID, which is all such a record grants. The presented key is not adopted: a registry lookup binds the record instead (scheduleBind), so the first key to turn up cannot claim it.

The common case (bound key, matching) is served entirely under the read lock; only dropping takes the write lock.

func (*Manager) PendingCount

func (hm *Manager) PendingCount() int

PendingCount returns the number of pending handshake requests.

func (*Manager) PendingRequests

func (hm *Manager) PendingRequests() []PendingHandshake

PendingRequests returns all pending handshake requests.

func (*Manager) ProcessRelayedApproval

func (hm *Manager) ProcessRelayedApproval(fromNodeID uint32)

ProcessRelayedApproval handles a handshake approval received via registry relay. Exported for daemon-side polling glue.

func (*Manager) ProcessRelayedRejection

func (hm *Manager) ProcessRelayedRejection(fromNodeID uint32)

ProcessRelayedRejection handles a handshake rejection received via registry relay. Exported for daemon-side polling glue.

func (*Manager) ProcessRelayedRequest

func (hm *Manager) ProcessRelayedRequest(fromNodeID uint32, justification string)

ProcessRelayedRequest handles a handshake request received via registry relay. Exported for daemon-side polling glue (Daemon.pollRelayedHandshakes).

func (*Manager) RejectHandshake

func (hm *Manager) RejectHandshake(peerNodeID uint32, reason string) error

RejectHandshake rejects a pending handshake request.

func (*Manager) RevokeTrust

func (hm *Manager) RevokeTrust(peerNodeID uint32) error

RevokeTrust removes a peer from the trusted set and notifies both the registry and the peer itself. Either party can revoke unilaterally.

func (*Manager) SendRequest

func (hm *Manager) SendRequest(peerNodeID uint32, justification string) error

SendRequest sends a handshake request to a remote node. First tries direct connection (port 444). If that fails (e.g. private node), falls back to relaying through the registry.

func (*Manager) Start

func (hm *Manager) Start() error

Start binds port 444 and begins handling handshake connections.

func (*Manager) Stop

func (hm *Manager) Stop()

Stop stops the replay reaper and the save goroutine, and saves trust state one last time: every trust change made before it returns is written, except one made by an RPC still running after the wait below, or one whose write fails (logged).

It first waits for in-flight background RPCs, because some of them change trust (backfillPeerKey binds or drops a record), but only until stopRPCWait after the first Stop: an RPC that is still running then keeps running, and its change is saved by a later Stop, if any. Only after that wait does it stop the drain goroutine, and it waits for that goroutine to finish any save it has started before saving itself. Closing done first, as Stop used to, lost changes: drainSaves picks between a pending dirty signal and done at random, and nothing drained the signals RPCs sent while Stop waited for them.

The final save happens only if something changed since the last successful save. A start followed by a stop leaves trust.json as it was, including one that failed to parse at startup, which the next real trust change overwrites but Stop on its own must not.

Stop is safe to call more than once, concurrently included. The daemon calls it twice (Daemon.Stop and the plugin runtime's Service.Stop). Every call saves what is unsaved, so a second call picks up what RPCs that outlived the first call's wait have changed since, but it does not wait again.

func (*Manager) TrustedPeers

func (hm *Manager) TrustedPeers() []TrustRecord

TrustedPeers returns all trusted peers.

func (*Manager) WaitForTrust

func (hm *Manager) WaitForTrust(nodeID uint32, timeout time.Duration) bool

WaitForTrust blocks until the given peer transitions to trusted, or the timeout elapses. Returns true if trust was granted within the window, false on timeout. The fast path (already trusted) is a single map lookup under hm.mu — no goroutine, no channel allocation.

Self is always trusted: a daemon trivially trusts itself, and gating loopback operations behind a non-existent trust record would block pilotctl self-pings and any plugin operating against the local node.

type PendingHandshake

type PendingHandshake struct {
	NodeID        uint32
	PublicKey     string
	KeyConfirmed  bool
	Justification string
	ReceivedAt    time.Time
	Source        uint32
}

PendingHandshake is an unapproved incoming request.

PublicKey is the key the request was signed with ("" for a request that came over the registry relay). KeyConfirmed records whether the registry listed that same key for NodeID when the request arrived; approving the request binds the trust record to PublicKey only then, and otherwise to the key a registry lookup returns.

type RegistryClient

type RegistryClient interface {
	Lookup(nodeID uint32) (map[string]interface{}, error)
	ReportTrust(nodeID, peerID uint32) (map[string]interface{}, error)
	RevokeTrust(nodeID, peerID uint32) (map[string]interface{}, error)
	RequestHandshake(fromNodeID, toNodeID uint32, justification, signatureB64 string) (map[string]interface{}, error)
	RespondHandshake(nodeID, peerID uint32, accept bool, signatureB64 string) (map[string]interface{}, error)
	PollHandshakes(nodeID uint32) (map[string]interface{}, error)
}

RegistryClient is the subset of pkg/registry/client.Client the handshake manager uses. Defined here as an interface so the manager stays free of import cycles and tests can supply a fake.

Method signatures match *registry/client.Client exactly, so the daemon adapter can return the underlying client directly.

type Runtime

type Runtime interface {
	// NodeID returns this daemon's stable node ID. Returns 0 if
	// identity has not been initialized yet.
	NodeID() uint32

	// HasIdentity reports whether the daemon has loaded an Ed25519
	// identity. SendRequest / signing paths early-return when false.
	HasIdentity() bool

	// PublicKey returns the local Ed25519 public key (for inclusion in
	// outbound HandshakeMsg.PublicKey). Returns nil when HasIdentity is
	// false.
	PublicKey() ed25519.PublicKey

	// Sign signs the given payload with the local Ed25519 private key.
	// Returns nil when HasIdentity is false; callers handle that as
	// "no signature attached".
	Sign(msg []byte) []byte

	// IdentityPath returns the configured on-disk identity path; the
	// trust.json store sits in the same directory. Empty when the
	// daemon runs in-memory only (no persistence).
	IdentityPath() string

	// TrustAutoApprove reports whether the daemon was configured to
	// auto-approve all incoming handshake requests (trust-on-first-use
	// stance for friendly fleets).
	TrustAutoApprove() bool

	// IsTrusted consults the trustedagents allowlist. Returns the
	// agent's display name and ok=true on a match. Returns "", false
	// when no checker has been registered (treated as "not trusted").
	IsTrusted(nodeID uint32) (name string, ok bool)

	// PublishEvent emits a topic+payload event onto the daemon's event
	// bus. Non-blocking; events may be dropped under bus pressure.
	PublishEvent(topic string, payload map[string]any)

	// PortListener binds the given well-known port and returns a
	// coreapi.Listener. The handshake plugin uses this for PortHandshake.
	// Closing the returned listener stops the accept loop.
	PortListener(port uint16) (coreapi.Listener, error)

	// DialAndSend establishes a stream to (peerNodeID, port), writes
	// the JSON-encoded message, and closes after a brief grace period
	// to let the data flush.
	DialAndSend(peerNodeID uint32, port uint16, data []byte) error

	// RemoveTunnelPeer tears down the encrypted tunnel for the given
	// peer. Called from RevokeTrust so a revoked peer's tunnel state
	// (session keys, retransmit queues) is purged immediately.
	RemoveTunnelPeer(nodeID uint32)

	// Registry returns the L8 registry-side-channel client used for
	// peer lookups, trust-pair reporting, and relay-based handshake
	// when direct dial fails. Returns nil when the daemon is offline
	// or running without a registry connection — callers must nil-check.
	Registry() RegistryClient
}

Runtime is the primitives-only contract the handshake manager needs from the surrounding daemon. Every dependency that crossed the old `hm.daemon.X` boundary now flows through one of these methods.

The concrete adapter (plugins/runtime.HandshakeRuntime) wraps a *daemon.Daemon to satisfy this interface. Tests can substitute a fake runtime to exercise the manager in isolation.

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service is the L11 plugin adapter for the manual trust-handshake runtime (port 444). Wraps a Manager and bridges between the coreapi.Service lifecycle (Start/Stop with deps) and the Runtime-interface accept loop.

func NewService

func NewService(rt Runtime) *Service

NewService constructs a handshake plugin Service over the given Runtime. The composition root (plugins/runtime or test harness) builds the Runtime and registers the resulting Service.

func (*Service) Manager

func (s *Service) Manager() *Manager

Manager returns the underlying Manager (test access + composition glue).

func (*Service) Name

func (s *Service) Name() string

func (*Service) Order

func (s *Service) Order() int

func (*Service) Start

func (s *Service) Start(_ context.Context, _ coreapi.Deps) error

func (*Service) Stop

func (s *Service) Stop(_ context.Context) error

type TrustRecord

type TrustRecord struct {
	NodeID     uint32
	PublicKey  string // base64 Ed25519 pubkey
	ApprovedAt time.Time
	Mutual     bool   // true if both sides initiated
	Network    uint16 // non-zero if trust is via network membership
}

TrustRecord holds information about a trusted peer.

PublicKey is the peer key the record was established against, and is what scopes the record: node IDs are recycled (reaped and re-claimed by a different identity) and peers rotate keys, so a record only describes the same counterparty for as long as the key behind the node ID is unchanged. Checks that have the peer's current key in scope go through IsTrustedWithKey, which compares the two.

A record is only ever bound to a key the registry confirmed for the node: the key of a request or accept whose registry lookup matched it, or the key a registry lookup returned. A key a peer merely presents never binds a record, and never drops one either.

An empty PublicKey means "unbound": records restored from a snapshot written before keys were recorded, records made over the registry relay or from a request the registry could not confirm, before their registry lookup has landed. Those stay trusted on node ID alone until backfillPeerKey binds them to the registry's key.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL