Documentation
¶
Overview ¶
Package wire is the opt-in serialization codec for the NetTact agent <-> server WebSocket channel. It offers a compact protobuf encoding alongside JSON for the Frame envelope (and its payload types), selected per connection via the negotiated WS subprotocol.
Unlike the rest of the protocol module (which is deliberately stdlib-only), this package imports google.golang.org/protobuf. Consumers that stay on JSON need not import it — the protocol/telemetry, protocol/config, protocol/enroll and protocol/permission type packages remain dependency-free.
Index ¶
- Constants
- Variables
- func HasCapability(caps []string, name string) bool
- func MarshalAck(a Ack, contentType string) ([]byte, error)
- func MarshalFrame(f Frame, contentType string) ([]byte, error)
- func MarshalPacket(p telemetry.Packet, contentType string) ([]byte, error)
- func Negotiate(header string) string
- func SubprotocolContentType(subprotocol string) string
- func UnmarshalPacket(data []byte, contentType string) (telemetry.Packet, error)
- type Ack
- type CloseCode
- type CloseError
- type Conn
- type Dialer
- type EpochRotationChallenge
- type EpochRotationChallengeRequest
- type EpochRotationRequest
- type EpochRotationResult
- type Frame
- type Hello
- type MonitorStatus
- type MonitorStatusEntry
- type SequenceFloor
- type SequenceFloorApplied
Constants ¶
const ( ContentTypeJSON = "application/json" ContentTypeProtobuf = "application/x-protobuf" )
Canonical content-type values for the two supported wire formats.
const ( SubprotocolProtobuf = "nettact.v1.protobuf" SubprotocolJSON = "nettact.v1.json" )
WebSocket subprotocol names offered by the agent and accepted by the server. The negotiated subprotocol fixes the Frame encoding for the whole session.
const ( RotationOK = "ok" // new credential + epoch issued; AgentToken/NewEpoch set RotationDenied = "denied" // proof rejected or policy refused; terminal for this challenge RotationRetry = "retry" // server transiently unavailable; agent may retry with a fresh challenge )
EpochRotationResult status values. Unknown status values on the wire must be tolerated and treated by the agent as a denial with reason (open string enum convention).
const ( MonitorStatusActive = "active" MonitorStatusPermissionBlocked = "permission_blocked" MonitorStatusTargetBlocked = "target_blocked" MonitorStatusUnsupported = "unsupported" )
Monitor execution status values (MonitorStatusEntry.Status).
const CapProbeTraceV1 = "probe_trace_v1"
CapProbeTraceV1 declares that the agent runs probe targets of kind "trace" (periodic route monitoring) and reports them as TraceResults stamped with MonitorID/ConfigSerial. A server must not push a "trace" target to an agent that did not declare it: an older agent finds no permission requirement for the unknown kind, reports the monitor active, and then never runs it.
const CapSequenceFloorV1 = "sequence_floor_v1"
Schema 8 capability names, declared by the agent in Hello.Capabilities and granted (or not) by the server. They are a separate axis from PermissionReport: permissions gate which collectors the agent runs, while a capability gates which protocol state machines the two peers may enter. A receiver must ignore names it does not know and must never send a control frame for a capability the peer did not declare.
Variables ¶
var ErrFrameVariant = errors.New("wire: frame must carry exactly one payload")
ErrFrameVariant reports a frame with zero or more than one payload set.
Functions ¶
func HasCapability ¶
HasCapability reports whether caps contains name. Duplicate entries are tolerated (set semantics); the empty list declares nothing.
func MarshalAck ¶
MarshalAck encodes a telemetry Ack in the format named by contentType.
func MarshalFrame ¶
MarshalFrame encodes a Frame in the format named by contentType (canonical constant, raw header value, or a value from SubprotocolContentType).
func MarshalPacket ¶
MarshalPacket encodes a telemetry.Packet in the format named by contentType (raw header value or canonical constant; anything non-protobuf is JSON).
func Negotiate ¶
Negotiate maps a raw HTTP Content-Type or Accept header value to a canonical content-type. Protobuf is chosen when the header advertises it with a non-zero quality; everything else (including an empty header, or protobuf explicitly rejected via q=0) falls back to JSON, preserving compatibility with agents and servers that predate protobuf support. A single Content-Type value (no q) is a media range with the default q=1, so this also handles the request-encoding case.
func SubprotocolContentType ¶
SubprotocolContentType maps a negotiated WS subprotocol to the canonical content-type the codec functions accept. Unknown values fall back to JSON, mirroring Negotiate's safe default.
Types ¶
type Ack ¶
type Ack struct {
HighestSequence uint64 `json:"highest_sequence"`
ServerTime time.Time `json:"server_time"`
}
Ack is the server -> agent acknowledgment for one Packet frame: the durable sequence watermark the agent's WAL prunes against, plus the server clock.
type CloseCode ¶
type CloseCode int
CloseCode mirrors the RFC 6455 status codes plus the NetTact 4000-range application codes. It replaces the transport-specific status code (previously coder/websocket's StatusCode) so both the WebSocket adapters and the in-memory Pipe classify session outcomes through the same vocabulary.
const ( // CloseNormalClosure is a clean shutdown: the agent sent it on Ctrl+C so the // server marks it offline immediately instead of waiting out a timeout. CloseNormalClosure CloseCode = 1000 // CloseGoingAway is the server closing every session for graceful shutdown. CloseGoingAway CloseCode = 1001 // ClosePolicyViolation closes a session that violated a runtime policy, such // as a consumer too slow to drain its outbound queue. ClosePolicyViolation CloseCode = 1008 // CloseInternalError signals an abnormal session end (write failure, decode // trouble) — not a clean close, so the peer knows it was not graceful. CloseInternalError CloseCode = 1011 // CloseSuperseded closes an old session when the same agent connects again; // the replaced side must NOT reconnect (it would kick the new one in a loop). CloseSuperseded CloseCode = 4000 // CloseUnsupportedSchema rejects a Hello whose schema version the server does // not understand; reconnecting won't help until one side is upgraded. CloseUnsupportedSchema CloseCode = 4001 // CloseUnsupportedSubprotocol rejects a client that offered neither // nettact.v1 subprotocol, so the Frame encoding was never agreed on. CloseUnsupportedSubprotocol CloseCode = 4002 // CloseProtocolError rejects a frame the protocol does not allow at that // point (non-Hello first frame, agent-bound frame sent by the agent, or // undecodable bytes). CloseProtocolError CloseCode = 4003 // CloseRevoked evicts the session of an agent being deleted: its credential // is about to stop authenticating, so the agent must re-enroll rather than // reconnect. CloseRevoked CloseCode = 4004 )
func CloseStatus ¶
CloseStatus extracts the close code from err (seeing through fmt.Errorf %w wrapping), or -1 if err carries no CloseError. It is the transport-agnostic replacement for websocket.CloseStatus at every classification site outside the WebSocket adapters.
type CloseError ¶
CloseError is returned by Conn.ReadFrame/WriteFrame/Ping once the link has been closed with a code (by either end). Its Code drives the supervisor's terminal-outcome decision, extracted via CloseStatus through %w wrapping.
func (*CloseError) Error ¶
func (e *CloseError) Error() string
type Conn ¶
type Conn interface {
// ReadFrame returns the next frame, or a *CloseError once the link closed.
ReadFrame(ctx context.Context) (Frame, error)
// WriteFrame sends one frame; it returns a *CloseError if the link closed.
WriteFrame(ctx context.Context, f Frame) error
// Ping verifies liveness. It succeeds while the link is open.
Ping(ctx context.Context) error
// Close ends the link with a code/reason. The first Close wins; later calls
// are no-ops.
Close(code CloseCode, reason string) error
}
Conn is one end of an agent <-> server frame link. Frames cross it already decoded into wire.Frame values; any serialization is the implementation's concern (the WebSocket adapters marshal per the negotiated subprotocol; the in-memory Pipe passes values through untouched). Implementations:
- agent/internal/conn (client-side WebSocket adapter)
- server-core/agentws (server-side WebSocket adapter)
- Pipe below (in-process desktop link)
func Pipe ¶
func Pipe() (agentEnd, serverEnd Conn)
Pipe returns two connected in-memory Conn ends for the desktop's bundled agent and embedded server. Frames cross by value with no serialization, so the sender MUST treat a sent Frame's pointed-to payloads as immutable — both sides already read received frames without mutating them. A Close on either end delivers the same CloseError to both.
type Dialer ¶
Dialer establishes one authenticated frame link for the given bearer token. The default is a WebSocket dialer built from the agent's server URL; the desktop injects the embedded server's in-process pipe dialer instead.
type EpochRotationChallenge ¶
type EpochRotationChallenge struct {
Challenge string `json:"challenge"`
Reason string `json:"reason"`
ExpiresAt time.Time `json:"expires_at"`
}
EpochRotationChallenge is the server->agent opener of the controlled credential/epoch rotation. The challenge string is a server-generated one-time binding of agent, old epoch, expiry and server origin (the exact encoding is server-private; the agent treats it as opaque bytes to sign). The agent proves possession of the enrolled ed25519 key by signing the challenge and answers with EpochRotationRequest.
Reason is an open enum explaining why the server demands a rotation (sequence_conflict: the same (agent, epoch, sequence) carried a different payload; epoch_mismatch: the Hello presented a stale epoch). Unknown values must be tolerated by the agent.
type EpochRotationChallengeRequest ¶
type EpochRotationChallengeRequest struct {
Reason string `json:"reason"`
}
EpochRotationChallengeRequest is the agent->server opener of an agent-initiated rotation: the agent detected it cannot safely proceed on its current epoch — the canonical case is an in-flight WAL claim whose sequence sits at or below the server's accepted floor, which must never be renumbered in place — and asks the server to challenge it. The server answers EpochRotationChallenge and the normal rotation flow follows.
type EpochRotationRequest ¶
type EpochRotationRequest struct {
Challenge string `json:"challenge"`
OldEpoch uint64 `json:"old_epoch"`
Signature []byte `json:"signature"`
}
EpochRotationRequest is the agent->server possession proof answering a challenge. Signature is ed25519 over the challenge bytes with the key the agent enrolled with; OldEpoch states the epoch the agent believes it is rotating out of. The server must re-validate challenge freshness and the signature binding before rotating anything.
type EpochRotationResult ¶
type EpochRotationResult struct {
Status string `json:"status"`
NewEpoch uint64 `json:"new_epoch,omitempty"`
AgentToken string `json:"agent_token,omitempty"`
Reason string `json:"reason,omitempty"`
}
EpochRotationResult is the server->agent terminal of a rotation. On OK the agent must durably persist AgentToken and NewEpoch (and the WAL's epoch state) before it switches identity; on denial or retry the old credential stays in force. AgentToken is shown exactly once, like enrollment.
type Frame ¶
type Frame struct {
// agent -> server
Hello *Hello `json:"hello,omitempty"`
Packet *telemetry.Packet `json:"packet,omitempty"`
HostSnapshot *telemetry.HostSnapshot `json:"host_snapshot,omitempty"`
MonitorStatus *MonitorStatus `json:"monitor_status,omitempty"`
// schema 8 control frames: the sequence-floor barrier
SequenceFloorApplied *SequenceFloorApplied `json:"sequence_floor_applied,omitempty"`
EpochRotationRequest *EpochRotationRequest `json:"epoch_rotation_request,omitempty"`
EpochRotationChallengeRequest *EpochRotationChallengeRequest `json:"epoch_rotation_challenge_request,omitempty"`
// server -> agent
Ack *Ack `json:"ack,omitempty"`
DesiredState *config.DesiredState `json:"desired_state,omitempty"`
SnapshotRequest *config.SnapshotRequest `json:"snapshot_request,omitempty"`
// schema 8 control frames: the sequence-floor barrier and the controlled
// credential/epoch rotation
SequenceFloor *SequenceFloor `json:"sequence_floor,omitempty"`
EpochRotationChallenge *EpochRotationChallenge `json:"epoch_rotation_challenge,omitempty"`
EpochRotationResult *EpochRotationResult `json:"epoch_rotation_result,omitempty"`
}
Frame is the envelope for every message on the agent <-> server WebSocket. Exactly one field is non-nil; MarshalFrame/UnmarshalFrame enforce this.
func UnmarshalFrame ¶
UnmarshalFrame decodes bytes produced by MarshalFrame for the given format.
type Hello ¶
type Hello struct {
SchemaVersion int `json:"schema_version"`
Hostname string `json:"hostname"`
Platform string `json:"platform"`
AgentVersion string `json:"agent_version"`
Permissions permission.PermissionReport `json:"permissions"`
Capabilities []string `json:"capabilities,omitempty"`
EnrollmentEpoch uint64 `json:"enrollment_epoch,omitempty"`
}
Hello is the first frame an agent sends after the WebSocket upgrade. It replaces the per-request X-Agent-* headers of the old POST transport. Permissions is the agent's authoritative supported/granted/effective view, refreshed on every (re)connect. (It used to carry a reported config watermark too; the server pushes DesiredState unconditionally on connect, so the watermark informed nothing and was removed in schema 6.)
Schema 8 added Capabilities and EnrollmentEpoch. Capabilities declares the protocol state machines this agent speaks (see CapSequenceFloorV1); a server must never send control frames for an undeclared capability. EnrollmentEpoch is the server-generated credential generation the agent believes it is on; zero means unknown (enrolled before schema 8), and a schema-8 server must not run the floor barrier for a zero-epoch Hello.
type MonitorStatus ¶
type MonitorStatus struct {
ConfigVersion int `json:"config_version"`
PolicyHash string `json:"policy_hash"`
// UploadIntervalSeconds is the agent's WAL batch-upload interval (its global
// telemetry flush cadence, not a per-monitor value). The server folds it into
// the freshness window (rounded up to whole seconds) so a probe whose sample
// timestamp is the probe instant is not marked stale merely for the agent's
// batching + drain + ingest latency between probe and arrival.
UploadIntervalSeconds int `json:"upload_interval_seconds,omitempty"`
Statuses []MonitorStatusEntry `json:"statuses"`
}
MonitorStatus is the agent's full-state report of how it evaluated every pushed monitor against its effective permissions and target-access policy. It is always the complete set for the given ConfigVersion (never a delta): the server upserts these rows and deletes any monitor absent from the frame. The agent sends it after every DesiredState apply and on any runtime transition (DNS flip, redirect block, recovery), coalesced latest-wins.
type MonitorStatusEntry ¶
type MonitorStatusEntry struct {
MonitorID string `json:"monitor_id"`
Status string `json:"status"` // active | permission_blocked | target_blocked | unsupported
MissingPermissions []string `json:"missing_permissions,omitempty"`
MatchedSelector string `json:"matched_selector,omitempty"`
Reason string `json:"reason,omitempty"` // literal_denied | resolved_denied | redirect_denied | method_requires_extended | …
// EffectiveIntervalSeconds / CycleDeadlineMs are the agent's actual effective
// per-target schedule for this monitor (interval floored by the agent-local
// MinProbeInterval; whole-cycle deadline), reported so the server derives
// freshness from what the agent really runs rather than the configured value.
EffectiveIntervalSeconds int `json:"effective_interval_seconds,omitempty"`
CycleDeadlineMs int `json:"cycle_deadline_ms,omitempty"`
// TargetConfigSerial is the ProbeTarget.ConfigSerial the agent applied for
// this monitor — the per-target material generation echoed back so the server
// distinguishes a current-generation report from a stale/obsolete one.
TargetConfigSerial int `json:"target_config_serial,omitempty"`
}
MonitorStatusEntry is one monitor's execution status.
type SequenceFloor ¶
type SequenceFloor struct {
EnrollmentEpoch uint64 `json:"enrollment_epoch"`
SequenceFloor uint64 `json:"sequence_floor"`
SessionID string `json:"session_id"`
}
SequenceFloor is the server->agent pre-claim barrier (schema 8). Before the agent may claim its first sequence for this credential/epoch, the server pushes the epoch and the highest sequence it has durably accepted, plus a session id for diagnostics. The agent must durably fast-forward its allocator past SequenceFloor and reply SequenceFloorApplied before sending its first Packet; a packet sent before the applied reply is a protocol error on both sides.
Why a dedicated frame and not a TelemetryAck field: the ack is strictly "exactly one confirmation per in-flight packet" — the agent deletes the in-flight claim on receipt. An unsolicited floor carried as an ack would be indistinguishable from a per-packet confirmation and could delete a claim nothing confirmed. A dedicated frame makes the barrier an explicit session phase the server can enforce by its own ordering (no packet admitted before the applied reply) instead of by ack bookkeeping.
type SequenceFloorApplied ¶
type SequenceFloorApplied struct {
EnrollmentEpoch uint64 `json:"enrollment_epoch"`
SequenceFloor uint64 `json:"sequence_floor"`
}
SequenceFloorApplied is the agent->server reply to SequenceFloor: the floor is durably applied and the WAL drain is open. It is a control response, NOT a packet ack — the server must not treat it as telemetry admission.