Documentation
¶
Overview ¶
Package distributed implements netcap's agent → collector transport.
Agents connect over TLS 1.3 with mutual authentication. Both sides use self-signed Ed25519 certificates and trust each other by pinning the SHA-256 of the peer's public key (SPKI). The collector derives a client's identity, and therefore its output directory, from its allowlist entry, never from anything the client sends.
After the handshake the connection carries frames:
[1 byte type][4 byte big-endian payload length][payload]
The agent sends Hello once, then Batch frames. The collector answers each Batch with an Ack carrying its sequence number once the data is written, or with an Error frame and closes the connection.
Index ¶
- Constants
- Variables
- func ClientTLSConfig(id tls.Certificate, serverFingerprint string) (*tls.Config, error)
- func CountRecords(t types.Type, data []byte) (int, error)
- func DecodeAck(p []byte) (uint64, error)
- func EncodeAck(seq uint64) []byte
- func Fingerprint(cert *x509.Certificate) string
- func GenerateIdentity(certPath, keyPath, commonName string) (string, error)
- func IdentityFingerprint(id tls.Certificate) (string, error)
- func LoadIdentity(certPath, keyPath string) (tls.Certificate, error)
- func NormalizeFingerprint(s string) (string, error)
- func PeerName(cs tls.ConnectionState, allow Allowlist) (string, error)
- func ReadFrame(r io.Reader, maxPayload int) (t byte, payload []byte, err error)
- func RunBatcher(ch <-chan []byte, cfg BatcherConfig)
- func ServerTLSConfig(id tls.Certificate, allow Allowlist) *tls.Config
- func ValidName(name string) bool
- func WriteFrame(w io.Writer, t byte, payload []byte) error
- type Allowlist
- type BatcherConfig
- type Client
- type ClientConfig
- type ClientStats
- type Server
- type ServerConfig
- type Sink
- type SinkFileInfo
Constants ¶
const ( FrameHello byte = 1 // agent → collector, types.AgentHello FrameBatch byte = 2 // agent → collector, types.Batch FrameAck byte = 3 // collector → agent, 8 byte big-endian sequence number FrameError byte = 4 // collector → agent, UTF-8 reason )
Frame types.
const DefaultMaxFrame = 4 << 20
DefaultMaxFrame bounds a frame payload. It is checked before allocating.
const MaxRecordSize = DefaultMaxFrame - batchOverhead
MaxRecordSize is the largest single record a batch can carry within DefaultMaxFrame.
const ProtocolVersion = 1
ProtocolVersion is the wire protocol version sent in the agent hello.
Variables ¶
var ( // ErrFrameTooLarge is returned for a frame whose declared length exceeds the limit. ErrFrameTooLarge = errors.New("frame too large") // ErrUnknownFrame is returned for an unknown frame type. ErrUnknownFrame = errors.New("unknown frame type") )
var ErrServerClosed = errors.New("server closed")
ErrServerClosed is returned by Serve after Shutdown.
var ErrSinkClosed = errors.New("sink closed")
ErrSinkClosed is returned by Write after Close.
Functions ¶
func ClientTLSConfig ¶
ClientTLSConfig returns a TLS 1.3 config that presents id and accepts only a server whose key has the pinned fingerprint.
func CountRecords ¶
CountRecords checks that data is a sequence of complete length-delimited records, each a valid protobuf of the record type for t, and returns how many there are. The collector refuses to write anything that fails this, so a malformed batch can never corrupt an output file.
func Fingerprint ¶
func Fingerprint(cert *x509.Certificate) string
Fingerprint returns the lowercase hex SHA-256 of the certificate's public key.
func GenerateIdentity ¶
GenerateIdentity creates a self-signed Ed25519 certificate and key and writes them as PEM to certPath and keyPath with mode 0600. Existing files are never overwritten. It returns the SPKI fingerprint to pin on the other side.
func IdentityFingerprint ¶
func IdentityFingerprint(id tls.Certificate) (string, error)
IdentityFingerprint returns the fingerprint of a loaded identity.
func LoadIdentity ¶
func LoadIdentity(certPath, keyPath string) (tls.Certificate, error)
LoadIdentity loads a certificate and key written by GenerateIdentity.
func NormalizeFingerprint ¶
NormalizeFingerprint lowercases a fingerprint, strips ':' separators and checks that it is 32 bytes of hex.
func PeerName ¶
func PeerName(cs tls.ConnectionState, allow Allowlist) (string, error)
PeerName returns the allowlist name of the client on an established server-side connection.
func ReadFrame ¶
ReadFrame reads one frame. A declared length above maxPayload fails with ErrFrameTooLarge before any payload memory is allocated.
func RunBatcher ¶
func RunBatcher(ch <-chan []byte, cfg BatcherConfig)
RunBatcher reads length-delimited records from ch and emits batches until ch is closed, then emits what is left. A record larger than MaxBytes is sent in a batch of its own; only one larger than MaxRecordSize is dropped.
func ServerTLSConfig ¶
func ServerTLSConfig(id tls.Certificate, allow Allowlist) *tls.Config
ServerTLSConfig returns a TLS 1.3 config that requires a client certificate whose key is in allow.
Types ¶
type Allowlist ¶
Allowlist maps a client key fingerprint to the client's name.
func LoadAllowlist ¶
LoadAllowlist parses the allowlist file at path.
func ParseAllowlist ¶
ParseAllowlist reads lines of "<fingerprint> <name>". Blank lines and lines starting with '#' are ignored. Any malformed line, invalid name, or duplicate fingerprint or name is an error, so a typo stops the collector rather than silently locking a client out or merging two clients.
type BatcherConfig ¶
type BatcherConfig struct {
Type types.Type
MaxBytes int // flush when Data would exceed this; clamped to MaxRecordSize
FlushInterval time.Duration // flush a non-empty batch at least this often; 0 disables
ContainsPayloads bool
Emit func(*types.Batch)
OnOversize func(size int) // called for a record too large to ever send
}
BatcherConfig configures RunBatcher.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client delivers batches to a collector over one TLS connection, waits for each to be acknowledged, and reconnects with backoff when the connection drops. Unacknowledged batches are kept in memory and resent.
func NewClient ¶
func NewClient(cfg ClientConfig) (*Client, error)
NewClient validates cfg and starts the sender goroutine.
func (*Client) Close ¶
func (c *Client) Close(ctx context.Context) (ClientStats, error)
Close stops accepting batches and waits until the queue is delivered or ctx ends. It returns the final stats; Pending > 0 means batches were not delivered.
func (*Client) Enqueue ¶
Enqueue assigns b a sequence number and queues it. It never blocks; when the queue exceeds MaxPending the oldest batches are dropped and counted.
func (*Client) Stats ¶
func (c *Client) Stats() ClientStats
Stats returns a snapshot of the delivery counters.
type ClientConfig ¶
type ClientConfig struct {
Addr string
Identity tls.Certificate
ServerFingerprint string
Hello types.AgentHello // ProtocolVersion and Session are filled in
MaxPending int // bytes of unacknowledged batches kept for resend, default 64 MiB
DialTimeout time.Duration // default 10s
AckTimeout time.Duration // default 60s
MinBackoff time.Duration // default 1s
MaxBackoff time.Duration // default 60s
Logger *log.Logger // default log.Default()
}
ClientConfig configures an agent Client.
type ClientStats ¶
type ClientStats struct {
Acked uint64 // written by the collector
Dropped uint64 // evicted because MaxPending was exceeded
Rejected uint64 // refused by the collector as invalid
Pending int // still queued
}
ClientStats counts what happened to enqueued batches.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server accepts agent connections and writes their batches into a Sink.
func NewServer ¶
func NewServer(cfg ServerConfig) (*Server, error)
NewServer validates cfg and returns a Server.
type ServerConfig ¶
type ServerConfig struct {
Identity tls.Certificate
Allowlist Allowlist
Sink *Sink
MaxFrame int // default DefaultMaxFrame
MaxConns int // default 256
HandshakeTimeout time.Duration // default 10s
IdleTimeout time.Duration // max wait for the next frame, default 5m
WriteTimeout time.Duration // default 30s
Logger *log.Logger // default log.Default()
}
ServerConfig configures a collector Server.
type Sink ¶
type Sink struct {
// contains filtered or unexported fields
}
Sink writes batches into <root>/<client>/<Type>.ncap.gz, one gzip stream per client and type. It is safe for concurrent use.
func (*Sink) Close ¶
func (s *Sink) Close() ([]SinkFileInfo, error)
Close finalizes every gzip stream and closes the files. Further writes fail.