dataexchange

package module
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2026 License: AGPL-3.0 Imports: 26 Imported by: 2 modules, 3 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

dataexchange

ci codecov

Data-exchange plugin for the Pilot Protocol daemon. Listens on port 1001 and persists inbound frames under ~/.pilot/: files land in received/ and text/JSON/binary messages land in inbox/.

Install

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

Usage

f := &dataexchange.Frame{Type: dataexchange.TypeJSON, Payload: body}
if err := dataexchange.WriteFrame(conn, f); err != nil {
    return err
}

// Register as a plugin on the daemon runtime:
rt.Register(dataexchange.NewService(dataexchange.ServiceConfig{}))

Layout

File What it does
dataexchange.go Wire format: Frame, WriteFrame, ReadFrame, TraceFrame, TypeText/Binary/JSON/File/Trace/Governed/Tagged, TypeName.
tagged.go Optional request/reply correlation on the wire: Frame.MessageID / Frame.ReplyTo (TypeTagged), NewMessageID, ValidMessageID.
client.go Client — Dial, Send (waits for the ACK, falls back for older receivers) and send helpers.
governed.go Signed decision envelope, receiver-side verifier, and enforceable transport constraints.
server.go Server — accept loop and handler dispatch.
service.go *Service — coreapi.Service adapter. Build tag !no_dataexchange.
inbox_budget.go Inbox caps: running byte total, oldest-first eviction to 90% of the byte cap, file-count cap.
dedupe.go Receiver-side suppression of identical re-deliveries.
service_disabled.go Stub *Service for -tags no_dataexchange builds.

Wire format

[4-byte type][4-byte length][payload]

For TypeFile the payload is prefixed with [2-byte name length][name bytes]. For TypeTrace the payload is [4-byte inner_type][8-byte sent_at_ns][inner payload]. For TypeTagged (10) the payload is [2-byte header_len][header: JSON object][4-byte inner_type][inner payload]; see Request/reply correlation.

Max frame size: 64 MiB by default (configurable at process start with PILOT_DATAEXCHANGE_MAX_FRAME within its documented safe range). The limit applies to the whole payload after the 8-byte header, so for TypeTagged it includes the correlation header (see below).

Inbox

Text, JSON and binary messages are written to ~/.pilot/inbox/ as one JSON file each:

{"type":"TEXT","from":"0:0000.0002.BBE4","bytes":5,"received_at":"2026-09-24T10:00:00.123456789Z",
 "data":"hello","data_encoding":"utf8","message_id":"4f1c…","reply_to":"9b2e…"}

message_id and reply_to appear only when the sender supplied them (see below). Binary or non-UTF-8 payloads are stored as data_b64 with "data_encoding":"base64".

Two caps bound the inbox, and both evict the oldest messages first:

  • ServiceConfig.InboxMaxFiles (default 10000), checked every 64 messages.
  • ServiceConfig.InboxMaxBytes (default 256 MiB), checked before every write against a running byte total (no directory scan per message). When a new message would not fit, the oldest messages are removed until the inbox plus the new message is at or below 90% of the cap, so recent replies survive and the next messages do not each trigger another eviction. A message that another connection is still writing is never evicted. A single message larger than the cap is rejected without evicting anything. A negative value disables the byte cap.

Request/reply correlation (for service authors)

A data-exchange message is fire-and-forget: the sender gets an ACK that the peer stored it, and any answer arrives later as a separate message in the sender's inbox. To let a requester tell which request an answer belongs to, a frame can carry two optional fields:

Field (Go) Inbox / event key Meaning
Frame.MessageID message_id An ID the sender chose for this message. Use a fresh random value per message (NewMessageID(), 32 hex chars).
Frame.ReplyTo reply_to The message_id of the message this one answers.

IDs are 1–128 characters of A-Z a-z 0-9 - _ . :. They are correlation metadata only: they are not authenticated (a governed frame's signature does not cover them), so never use them for authorization.

If you run a service (an agent that answers requests): when a request's inbox record (or message.received event) has a message_id, send your answer with ReplyTo set to that value. If you answer in several messages, set it on each. Give each answer its own MessageID too if you want the requester's daemon to drop duplicate copies of it (for example when you retry a send or it arrives over two network paths). Requests without a message_id come from older clients: answer them as before.

c, err := dataexchange.Dial(drv, requester)
if err != nil { return err }
defer c.Close()
res, err := c.Send(&dataexchange.Frame{
    Type:      dataexchange.TypeJSON,
    Payload:   answer,
    MessageID: dataexchange.NewMessageID(),
    ReplyTo:   request.MessageID, // the request's "message_id"
})

If you send requests: generate a MessageID, send with Client.Send, then wait for an inbox record from that peer whose reply_to equals it. Services that predate this field answer without reply_to; for those, fall back to matching on the sender alone.

Compatibility. Frames without either field use the original wire format, byte for byte. A frame with either field travels as TypeTagged. A receiver that predates it stores nothing and answers in one of two ways:

  • dataexchange v0.2.1 and older (every stable pilot daemon through v1.13.9) has no case for an unknown frame type. It drops the frame and still answers ACK UNKNOWN(10) <n> bytes.
  • dataexchange v0.2.2 and later answers ERR UNKNOWN(10) save failed: ....

Client.Send recognises both answers, re-sends the same frame without the fields on the same connection, and reports SendResult.Tagged == false, so a new sender can always talk to an old receiver and the message is stored exactly once. A raw WriteFrame of a tagged frame does not fall back: against a v0.2.1-or-older receiver the message is silently lost, so use Client.Send.

Size. The tagged header adds up to MaxTaggedOverhead (293) bytes, and the whole tagged frame must fit in the max frame size. A payload within 293 bytes of the limit may fit only untagged. Client.Send then sends it untagged (SendResult.Tagged == false), and a raw WriteFrame returns ErrTaggedFrameTooLarge without writing anything.

Whenever Tagged is false, the reply cannot carry reply_to; match it on the sender alone. The fields can accompany text, JSON, binary, file, governed and trace frames. On TypeFileStream frames they are ignored.

Wire layout of a tagged frame, for other languages:

[4-byte type = 10][4-byte length][payload]
payload = [2-byte header_len, 1..1024][header_len bytes: JSON object]
          [4-byte inner_type][inner payload, exactly as the inner type sends it]
header  = {"message_id":"…","reply_to":"…"}   (both optional; unknown keys are ignored)
length  = 2 + header_len + 4 + len(inner payload), at most the max frame size

Duplicate deliveries. The receiver remembers every stored frame that carried a MessageID for ServiceConfig.DedupeWindow (default 10 minutes). An identical re-delivery — same sender, MessageID, ReplyTo, type, filename and bytes — is acknowledged with the original ACK plus (duplicate) (SendResult.Duplicate) and is not stored again. Frames without a MessageID are always stored, as before, unless the operator sets ServiceConfig.DedupeContentWindow (off by default) to also drop byte-identical copies from the same sender inside a short window.

Governed delivery

TypeGoverned wraps one text, JSON, binary, or single-frame file delivery in the sender's signed decision.Intent and signed decision.Decision. The intent payload hash binds the frame type, filename, and exact bytes; the receiver verifies the signatures, tenant authority state, local deterministic ceiling, exact local destination, and any applicable transport constraints before it writes to disk. A workflow-approved action uses the same short-lived execution Decision as an ordinary allowed action—there is no reusable transport permit.

Large resumable files use TypeGovernedFileStream: the signed envelope binds the exact TypeFileStream INIT (filename, declared length, full SHA-256, chunk size, and transfer ID). Required receivers admit later chunks only for that verified transfer on the same connection. Compute the file hash first, call BuildStreamInitPayload, sign an Intent using GovernedStreamPayloadHash, then call SendGovernedFileStream.

For a required typed-disclosure profile, build a decision.DisclosureBinding whose content hash, byte length, filename, and stream transfer ID match the file, bind its canonical hash in the signed Intent, and use SendGovernedWithDisclosure or SendGovernedFileStreamWithDisclosure. A DecisionFrameVerifier with RequireDisclosure rejects governed messages, single-frame files, and resumable stream INITs that omit this evidence. When a receipt recorder is configured, typed deliveries require its V2 disclosure-evidence method; the resulting signed receipt binds the canonical disclosure hash without retaining the file or message body.

Set ServiceConfig.GovernedVerifier to DecisionFrameVerifier (or an equivalent local verifier). Once all senders have been upgraded, set ServiceConfig.RequireGoverned to reject unsigned legacy deliveries. Roll out in that order: upgraded receiver with verification available, upgraded senders, then required mode. An older receiver does not understand TypeGoverned; a required receiver intentionally rejects TypeTrace and raw TypeFileStream INIT frames. Governed stream INITs are supported.

For auditable enterprise ingress, configure GovernedReceiptRecorder and set RequireGovernedReceipts. The service writes the received message/file first, then requires the recorder to durably capture the exact signed Intent and Decision before it emits the success ACK or delivery event. If recording fails, the staged file is removed and the sender receives an error rather than a successful but unreceipted delivery.

Local content inspection

ServiceConfig.GovernedContentInspector is an optional receiver-local hook that runs after the signed envelope and local policy ceiling are verified but before a message/file is released. Set RequireGovernedContentInspection to make startup fail unless the hook is present; an inspection error removes a staged file or rejects the message. decision.PresidioInspector is the included OSS adapter for bounded text, JSON, XML, YAML, and form content. It rejects unsupported binary/document types rather than truncating or silently skipping them. The inspector is local to the receiver; neither the decision authority nor the sender's authority receives plaintext for this check.

Typed disclosure binding V2 adds a tenant-defined retention_class to the same Intent hash. A signed policy can select allowed classes; the receiver sees the bound metadata. Configure GovernedRetentionPolicies to map those classes to local expiry durations. The service writes an owner-only retention journal before a governed message/file becomes accepted (and before a streamed file's final rename), then removes the content after expiry across restarts. An unknown, V1, or unconfigured class is rejected when retention is enabled. This is deletion retention, not a legal-hold or WORM-storage implementation.

Per-agent transfer quotas

ServiceConfig.GovernedTransferQuota admits a bounded number of bytes and/or actions for each signed Intent.AgentID in a fixed local window. It is charged only after governed verification, including the declared bytes of a verified stream INIT; a peer address cannot select or reset another agent's budget. Quota is deliberately charged for an admitted attempt even if later local DLP or receipt persistence rejects it, so repeatedly failing submissions cannot turn the scanner into an unmetered denial-of-service target.

The v1 action mapping is:

Frame Intent action
text data.send.text
JSON data.send.json
binary data.send.binary
file file.share

Build tags

Tag Effect
no_dataexchange Compiles a no-op stub whose Start does nothing. Useful for integration tests that don't want inbox files written.

License

AGPL-3.0-or-later. See LICENSE.

Documentation

Index

Constants

View Source
const (
	TypeText   uint32 = 1
	TypeBinary uint32 = 2
	TypeJSON   uint32 = 3
	TypeFile   uint32 = 4
	// TypeTrace wraps another frame type with nanosecond-precision timing.
	// Wire layout: [4-byte TypeTrace][4-byte len][4-byte inner_type][8-byte sent_at_ns][inner_payload]
	TypeTrace uint32 = 5
	// Type 6 is reserved (see Alex's reply-on-conn PR chain / TypeAutoAnswer).
	//
	// TypeFileStream is the chunked/ACK'd/resumable file-transfer protocol
	// (see docs/PROPOSAL-reliable-file-transfer.md and filestream.go). Each
	// TypeFileStream frame carries a small control header + at most one
	// chunk of file data, so a multi-GiB transfer never collapses into a
	// single giant frame the way TypeFile does. Backward compatible: a
	// peer that does not understand TypeFileStream never sends INIT-ACK, so
	// the sender falls back to TypeFile.
	TypeFileStream uint32 = 7
	// TypeGoverned carries a regular data frame together with the sender's
	// signed intent and authority decision. It is opt-in; enterprise receivers
	// can require this envelope before persisting a message or file.
	TypeGoverned uint32 = 8
	// TypeGovernedFileStream carries the signed authorization evidence for a
	// TypeFileStream INIT. Subsequent chunks are accepted only while bound to
	// that verified transfer ID on the same connection.
	TypeGovernedFileStream uint32 = 9
	// TypeTagged wraps another frame with optional correlation metadata
	// (Frame.MessageID / Frame.ReplyTo). Callers never set it directly:
	// WriteFrame emits it when either field is set and ReadFrame unwraps it,
	// returning the inner frame with the fields populated. See tagged.go for
	// the wire layout and the fallback rule for receivers that predate it.
	TypeTagged uint32 = 10
)

Frame types for data exchange on port 1001.

View Source
const (
	// DefaultInboxMaxBytes caps inbox JSON at 256 MiB total.
	DefaultInboxMaxBytes int64 = 256 << 20
	// DefaultReceivedMaxBytes caps received files + partials at 2 GiB total.
	DefaultReceivedMaxBytes int64 = 2 << 30
	// DefaultIdleTimeout drops a connection idle for 2 minutes between frames.
	DefaultIdleTimeout = 2 * time.Minute
)

Defensible defaults applied when the corresponding ServiceConfig field is left at its zero value. A negative field value disables the limit.

View Source
const DefaultDedupeWindow = 10 * time.Minute

DefaultDedupeWindow is how long a stored frame that carried a MessageID is remembered for duplicate suppression when ServiceConfig.DedupeWindow is 0.

View Source
const DefaultMaxFrameSize uint32 = 64 << 20

DefaultMaxFrameSize caps a single data-exchange frame at 64 MiB.

The wire format's length field is a uint32 (see Frame docstring below), so the absolute ceiling is ~4 GiB; this cap exists to bound the memory a single hostile peer can make the receiver commit for one transfer. The receiver no longer pre-allocates the attacker-declared length up front (see ReadFrame) — it grows the buffer as bytes actually arrive — but the cap still bounds the steady-state worst case, so it is deliberately set well below the wire ceiling.

64 MiB comfortably covers inbox messages and the deprecated legacy single-frame TypeFile path; anything larger should ride the chunked TypeFileStream protocol (filestream.go), which never buffers a whole file in memory. Operators who genuinely need bigger single frames can raise the cap via PILOT_DATAEXCHANGE_MAX_FRAME (both ends must agree).

History: 256 MiB pre-2026-06-14, then briefly 1 GiB (sized for the test fleet's 100 MiB payloads on multi-GiB-RAM hosts). 1 GiB let a single hostile peer OOM the receiver, so the default was lowered to 64 MiB and the up-front allocation was removed.

View Source
const MaxMessageIDLen = 128

MaxMessageIDLen is the longest MessageID or ReplyTo value accepted on the wire. IDs are 1..MaxMessageIDLen bytes of ASCII letters, digits, '-', '_', '.' or ':' — enough for UUIDs, ULIDs and hex nonces, and safe to embed in file names, JSON and log lines without escaping.

View Source
const MaxTaggedOverhead = 2 + len(`{"message_id":"","reply_to":""}`) + 2*MaxMessageIDLen + 4

MaxTaggedOverhead is the most a MessageID/ReplyTo header adds to a frame's payload: the 2-byte header length, the JSON header with two MaxMessageIDLen IDs ({"message_id":"…","reply_to":"…"}, 287 bytes) and the 4-byte inner type. A frame stays taggable if its untagged payload is at most MaxFrameSize - MaxTaggedOverhead bytes.

View Source
const (
	StreamChunkSize = 48 * 1024
)

Defaults. Chunk size is deliberately held below 64 KiB: on the Mac↔GCP-VM rig, single tunnel writes at/above ~256 KiB are silently swallowed by the reliable-stream layer (a 64 KiB TypeFile transfer succeeds byte-perfect; 256 KiB stalls), so a large chunk would reproduce the very failure this protocol exists to avoid. 48 KiB chunks each ride the known-good path, and the per-chunk ACK keeps the reverse direction busy so the tunnel's blackhole heuristic does not flip the link mid-transfer. Window bounds the in-flight (unacked) bytes; 16 × 48 KiB = 768 KiB.

Variables

View Source
var ErrRejected = errors.New("dataexchange: receiver rejected frame")

ErrRejected is wrapped by the error Client.Send returns when the receiver answered with an "ERR ..." acknowledgement instead of storing the frame.

View Source
var ErrStreamUnsupported = errors.New("dataexchange: peer does not support TypeFileStream")

ErrStreamUnsupported is returned by SendFileStream when the peer does not answer INIT with an INIT-ACK within the negotiation window — i.e. it is a pre-TypeFileStream receiver. The caller should fall back to SendFile on a fresh connection.

View Source
var ErrTaggedFrameTooLarge = errors.New("dataexchange: frame with MessageID/ReplyTo exceeds MaxFrameSize")

ErrTaggedFrameTooLarge is returned (wrapped) by WriteFrame when a frame with a MessageID or ReplyTo would exceed MaxFrameSize once its header is added. Nothing is written in that case. Client.Send handles it by sending the frame untagged, which succeeds when the payload alone fits; a raw WriteFrame caller can do the same, or shrink the payload by up to MaxTaggedOverhead bytes.

View Source
var MaxFrameSize uint32 = func() uint32 {
	v := os.Getenv("PILOT_DATAEXCHANGE_MAX_FRAME")
	if v == "" {
		return DefaultMaxFrameSize
	}
	n, err := strconv.ParseUint(v, 10, 32)
	if err != nil || n < 1<<16 || n >= 1<<31 {

		return DefaultMaxFrameSize
	}
	return uint32(n)
}()

MaxFrameSize is the runtime-effective frame cap. Set at package init from the PILOT_DATAEXCHANGE_MAX_FRAME env var (in bytes) if present and within the safe range [64 KiB, 2 GiB); otherwise DefaultMaxFrameSize.

Both ends of a transfer must agree on the cap — a sender that exceeds the receiver's cap will see the receiver return "frame too large" and drop the connection. The env var is honored at process start, so rolling out a higher cap means restarting daemons on both sides.

Functions

func BuildStreamInitPayload added in v0.2.2

func BuildStreamInitPayload(name string, size int64, fullHash [32]byte) ([]byte, error)

BuildStreamInitPayload returns the deterministic INIT payload that a caller must bind in a signed file.share Intent before SendGovernedFileStream. The transfer ID is derived from the supplied full SHA-256, matching the sender's resumable-transfer state machine.

func GovernedAction added in v0.2.2

func GovernedAction(frameType uint32) string

GovernedAction returns the only signed Intent action that can authorize a regular governed data frame of frameType. An empty result means the type is not eligible for a governed envelope.

func GovernedPayloadHash added in v0.2.2

func GovernedPayloadHash(frameType uint32, filename string, payload []byte) string

GovernedPayloadHash returns the exact payload binding required by a TypeGoverned Intent. It includes the frame kind and filename as well as the bytes, so callers must use it when creating the Intent before SendGoverned.

func GovernedStreamDisclosureMetadata added in v0.2.2

func GovernedStreamDisclosureMetadata(initPayload []byte) (transferID string, declaredBytes uint64, contentHash string, filename string, err error)

GovernedStreamDisclosureMetadata returns the canonical values a hosted federation disclosure must bind for an already-built stream INIT.

func GovernedStreamPayloadHash added in v0.2.2

func GovernedStreamPayloadHash(initPayload []byte) string

GovernedStreamPayloadHash binds the exact bytes of the file-stream INIT frame. It therefore covers the filename, size, full content hash, chunk size, and transfer ID without having to duplicate the stream wire grammar.

func NewMessageID added in v0.2.3

func NewMessageID() string

NewMessageID returns a random 128-bit message ID as 32 lowercase hex characters, suitable for Frame.MessageID.

func TypeName

func TypeName(t uint32) string

TypeName returns a human-readable name for a frame type.

func ValidMessageID added in v0.2.3

func ValidMessageID(id string) bool

ValidMessageID reports whether id is acceptable as a Frame.MessageID or Frame.ReplyTo value on the wire.

func WriteFrame

func WriteFrame(w io.Writer, f *Frame) error

WriteFrame writes a frame to a writer. A frame with MessageID or ReplyTo set is written as a TypeTagged wrapper around its own type; receivers that predate TypeTagged do not store it, so prefer Client.Send, which falls back to the untagged form for them. If the wrapper would push the frame over MaxFrameSize, WriteFrame writes nothing and returns an error wrapping ErrTaggedFrameTooLarge.

func WriteTraceFrame

func WriteTraceFrame(w io.Writer, tf *TraceFrame) error

WriteTraceFrame serialises a TraceFrame as a TypeTrace outer frame.

Types

type Client

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

Client connects to a remote data exchange service on port 1001.

func Dial

func Dial(d *driver.Driver, addr protocol.Addr) (*Client, error)

Dial connects to a remote agent's data exchange port.

func (*Client) Close

func (c *Client) Close() error

Close closes the connection.

func (*Client) Recv

func (c *Client) Recv() (*Frame, error)

Recv reads the next frame from the connection.

func (*Client) Send added in v0.2.3

func (c *Client) Send(frame *Frame) (*SendResult, error)

Send writes frame, waits for the receiver's acknowledgement and reports the outcome. It is the preferred way to send a frame that carries a MessageID or ReplyTo, because it delivers the frame untagged (and reports SendResult.Tagged == false) in the two cases where the tagged form cannot get through:

  • The receiver predates TypeTagged. Send recognises its answer (see untaggedReceiverAckPrefixes) and re-sends the same frame without the metadata on the same connection. Such a receiver never stores the tagged copy, so the message is stored exactly once.
  • The tagged header would push the frame over MaxFrameSize. Send writes the frame untagged in the first place instead of sending a frame the receiver would drop the connection over.

If the receiver answers "ERR ...", Send returns the result together with an error wrapping ErrRejected. Send reads from the connection, so do not use it concurrently with Recv on the same Client.

func (*Client) SendBinary

func (c *Client) SendBinary(data []byte) error

SendBinary sends a binary frame.

func (*Client) SendFile

func (c *Client) SendFile(name string, data []byte) error

SendFile sends a file frame with a filename and data.

func (*Client) SendFileStream added in v0.2.1

func (c *Client) SendFileStream(name string, r io.ReadSeeker, size int64, stepTimeout time.Duration) (*StreamResult, error)

SendFileStream transfers a file using the chunked TypeFileStream protocol with a sliding window, end-to-end SHA-256 verification, and automatic resume (the receiver reports how many contiguous bytes it already has).

Returns ErrStreamUnsupported if the peer never answers INIT with an INIT-ACK within the negotiation window — the caller should fall back to SendFile on a fresh connection. stepTimeout bounds the wait for any single ACK and for the final COMPLETE (0 ⇒ default).

func (*Client) SendGoverned added in v0.2.2

func (c *Client) SendGoverned(frame *Frame, intent decision.Intent, result decision.Decision) error

SendGoverned sends a frame with exact signed intent/decision evidence. The remote service must have RequireGoverned enabled to enforce it.

func (*Client) SendGovernedFileStream added in v0.2.2

func (c *Client) SendGovernedFileStream(name string, r io.ReadSeeker, size int64, intent decision.Intent, result decision.Decision, stepTimeout time.Duration) (*StreamResult, error)

SendGovernedFileStream sends a large resumable file with a signed authority decision bound to its exact INIT metadata. Callers compute the intent payload hash with GovernedStreamPayloadHash over the deterministic INIT payload (use BuildStreamInitPayload after calculating the file hash), then pass the same signed intent and decision here. The receiver accepts chunks only for that verified transfer ID and records its receipt on successful completion.

func (*Client) SendGovernedFileStreamWithAuthorizer added in v0.2.2

func (c *Client) SendGovernedFileStreamWithAuthorizer(name string, r io.ReadSeeker, size int64, authorize GovernedStreamAuthorizer, stepTimeout time.Duration) (*StreamResult, error)

SendGovernedFileStreamWithAuthorizer obtains an exact signed decision only after the resumable stream's INIT bytes are known. This is the preferred sender API when the decision comes from an online authority.

func (*Client) SendGovernedFileStreamWithDisclosure added in v0.2.2

func (c *Client) SendGovernedFileStreamWithDisclosure(name string, r io.ReadSeeker, size int64, intent decision.Intent, result decision.Decision, disclosure decision.DisclosureBinding, stepTimeout time.Duration) (*StreamResult, error)

SendGovernedFileStreamWithDisclosure sends a governed resumable file whose Intent and authority Decision bind the supplied typed disclosure metadata. The metadata must match the final INIT (content hash, size, filename, and transfer ID) exactly; callers can derive these with BuildStreamInitPayload.

func (*Client) SendGovernedFileStreamWithDisclosureAuthorizer added in v0.2.2

func (c *Client) SendGovernedFileStreamWithDisclosureAuthorizer(name string, r io.ReadSeeker, size int64, authorize GovernedStreamDisclosureAuthorizer, stepTimeout time.Duration) (*StreamResult, error)

func (*Client) SendGovernedWithDisclosure added in v0.2.2

func (c *Client) SendGovernedWithDisclosure(frame *Frame, intent decision.Intent, result decision.Decision, disclosure decision.DisclosureBinding) error

SendGovernedWithDisclosure sends a single governed message or file with a typed disclosure binding. The Intent and Decision must already have been obtained for the exact binding.

func (*Client) SendJSON

func (c *Client) SendJSON(data []byte) error

SendJSON sends a JSON frame.

func (*Client) SendText

func (c *Client) SendText(text string) error

SendText sends a text frame.

func (*Client) SendTrace

func (c *Client) SendTrace(innerType uint32, data []byte) (sentAtNs int64, err error)

SendTrace wraps data in a TypeTrace frame with the current nanosecond clock. Returns sentAtNs so the caller can correlate it against the timing ACK.

type DecisionFrameVerifier added in v0.2.2

type DecisionFrameVerifier struct {
	Enforcer          *decision.Enforcer
	Resource          func(coreapi.Addr, *Frame) string
	RequireDisclosure bool
}

DecisionFrameVerifier is the reference receiver-side verifier. Resource must return the exact local resource identifier expected for this incoming frame (for example, "agent:finance/inbox"). This prevents a sender from reusing a valid decision for a different local destination.

func (DecisionFrameVerifier) VerifyGovernedFrame added in v0.2.2

func (verifier DecisionFrameVerifier) VerifyGovernedFrame(ctx context.Context, remote coreapi.Addr, governed GovernedFrame) error

func (DecisionFrameVerifier) VerifyGovernedStreamInit added in v0.2.2

func (verifier DecisionFrameVerifier) VerifyGovernedStreamInit(ctx context.Context, remote coreapi.Addr, stream GovernedStreamInit) error

type Frame

type Frame struct {
	Type     uint32
	Payload  []byte
	Filename string // only for TypeFile

	// MessageID optionally identifies this message so the receiver can drop
	// an identical re-delivery and the recipient can answer it. Use
	// NewMessageID to generate one. Empty means "no ID" (the pre-existing
	// wire format). See tagged.go.
	MessageID string
	// ReplyTo optionally names the MessageID of the message this frame
	// answers, so the original sender can match the reply to its request.
	// Empty means "not a correlated reply".
	ReplyTo string
}

Frame is a typed data unit exchanged between agents. Wire format: [4-byte type][4-byte length][payload] For TypeFile, payload is: [2-byte name length][name bytes][file data]

func EncodeGovernedFrame added in v0.2.2

func EncodeGovernedFrame(frame GovernedFrame) (*Frame, error)

func EncodeGovernedStreamInit added in v0.2.2

func EncodeGovernedStreamInit(stream GovernedStreamInit) (*Frame, error)

func ReadFrame

func ReadFrame(r io.Reader) (*Frame, error)

ReadFrame reads a frame from a reader.

type GovernedDisclosureReceiptRecorder added in v0.2.2

type GovernedDisclosureReceiptRecorder interface {
	RecordGovernedDisclosureReceipt(context.Context, decision.Intent, decision.Decision, decision.DisclosureBinding) error
}

GovernedDisclosureReceiptRecorder is the evidence extension for a disclosure-bound transport. A configured recorder must implement this when it receives typed metadata: silently emitting a V1 receipt would lose the evidence a required disclosure profile relies on.

type GovernedFrame added in v0.2.2

type GovernedFrame struct {
	Version    uint16                      `json:"version"`
	Type       uint32                      `json:"type"`
	Filename   string                      `json:"filename,omitempty"`
	Payload    []byte                      `json:"payload"`
	Disclosure *decision.DisclosureBinding `json:"disclosure,omitempty"`
	Intent     decision.Intent             `json:"intent"`
	Decision   decision.Decision           `json:"decision"`
}

GovernedFrame transports an ordinary data frame with the exact signed authorization evidence for that frame. PayloadHash is computed over frame type, filename, and bytes, so a decision for text cannot be replayed as a file or against different contents.

func DecodeGovernedFrame added in v0.2.2

func DecodeGovernedFrame(frame *Frame) (GovernedFrame, error)

func NewGovernedFrame added in v0.2.2

func NewGovernedFrame(frame *Frame, intent decision.Intent, result decision.Decision) (GovernedFrame, error)

func NewGovernedFrameWithDisclosure added in v0.2.2

func NewGovernedFrameWithDisclosure(frame *Frame, intent decision.Intent, result decision.Decision, disclosure decision.DisclosureBinding) (GovernedFrame, error)

NewGovernedFrameWithDisclosure creates a governed frame whose Intent binds a canonical disclosure metadata object. The caller must obtain the Decision for the disclosure-bound Intent; this constructor never changes authority.

func (GovernedFrame) DataFrame added in v0.2.2

func (frame GovernedFrame) DataFrame() *Frame

func (GovernedFrame) Validate added in v0.2.2

func (frame GovernedFrame) Validate() error

type GovernedFrameVerifier added in v0.2.2

type GovernedFrameVerifier interface {
	VerifyGovernedFrame(context.Context, coreapi.Addr, GovernedFrame) error
}

GovernedFrameVerifier maps a trusted transport peer and governed frame into a local enforcement decision. The service invokes it before any disk write.

type GovernedReceiptRecorder added in v0.2.2

type GovernedReceiptRecorder interface {
	RecordGovernedReceipt(context.Context, decision.Intent, decision.Decision) error
}

GovernedReceiptRecorder durably records a receiver-side enforcement receipt for a verified governed delivery. It receives the exact signed objects that authorized the data frame; implementations must fail closed on a recording error when their deployment requires evidence before acknowledgement.

type GovernedRetentionPolicy added in v0.2.2

type GovernedRetentionPolicy struct {
	Class     string
	RetainFor time.Duration
}

GovernedRetentionPolicy maps one V2 signed retention class to a local retention duration. The class is selected by signed policy and bound to the Intent; the duration is attachment-controlled, so a sender cannot extend it.

type GovernedStreamAuthorizer added in v0.2.2

type GovernedStreamAuthorizer func(initPayload []byte) (decision.Intent, decision.Decision, error)

GovernedStreamAuthorizer receives the exact FileStream INIT payload after its stable transfer ID and content hash have been calculated. It must return a short-lived signed Intent and Decision bound to that exact payload. The callback runs before any stream frame is written, so a deny or unavailable authority cannot produce a partial transfer.

type GovernedStreamDisclosureAuthorizer added in v0.2.2

type GovernedStreamDisclosureAuthorizer func(initPayload []byte) (decision.Intent, decision.Decision, decision.DisclosureBinding, error)

GovernedStreamDisclosureAuthorizer returns typed disclosure evidence for the exact INIT. Hosted federation clients use this after uploading the full file content and before the first stream byte is released to the peer.

type GovernedStreamInit added in v0.2.2

type GovernedStreamInit struct {
	Version     uint16                      `json:"version"`
	InitPayload []byte                      `json:"init_payload"`
	Disclosure  *decision.DisclosureBinding `json:"disclosure,omitempty"`
	Intent      decision.Intent             `json:"intent"`
	Decision    decision.Decision           `json:"decision"`
}

GovernedStreamInit binds a signed authority decision to the exact INIT frame for a resumable file stream. The INIT includes the full file hash, filename, declared length, and transfer ID; individual chunks are accepted only after this envelope has been verified locally.

func DecodeGovernedStreamInit added in v0.2.2

func DecodeGovernedStreamInit(frame *Frame) (GovernedStreamInit, error)

func NewGovernedStreamInit added in v0.2.2

func NewGovernedStreamInit(init *Frame, intent decision.Intent, result decision.Decision) (GovernedStreamInit, error)

func NewGovernedStreamInitWithDisclosure added in v0.2.2

func NewGovernedStreamInitWithDisclosure(init *Frame, intent decision.Intent, result decision.Decision, disclosure decision.DisclosureBinding) (GovernedStreamInit, error)

NewGovernedStreamInitWithDisclosure creates a governed resumable transfer whose signed Intent binds typed metadata as well as the content hash, filename, declared bytes, and stable transfer ID in its INIT frame.

func (GovernedStreamInit) DeclaredBytes added in v0.2.2

func (stream GovernedStreamInit) DeclaredBytes() (uint64, error)

DeclaredBytes returns the signed stream length from its verified INIT. It is used by receiver-local admission controls before any stream chunks are accepted.

func (GovernedStreamInit) InitFrame added in v0.2.2

func (stream GovernedStreamInit) InitFrame() *Frame

func (GovernedStreamInit) TransferID added in v0.2.2

func (stream GovernedStreamInit) TransferID() ([transferIDLen]byte, error)

func (GovernedStreamInit) Validate added in v0.2.2

func (stream GovernedStreamInit) Validate() error

type GovernedStreamVerifier added in v0.2.2

type GovernedStreamVerifier interface {
	VerifyGovernedStreamInit(context.Context, coreapi.Addr, GovernedStreamInit) error
}

GovernedStreamVerifier verifies a stream INIT before the receiver creates a partial file. It is intentionally distinct from GovernedFrameVerifier so embedders that do not support large files need not accidentally authorize them.

type Handler

type Handler func(conn net.Conn, frame *Frame)

Handler is called for each incoming frame on a connection.

type SendResult added in v0.2.3

type SendResult struct {
	// Ack is the receiver's acknowledgement frame, normally a TypeText
	// "ACK <TYPE> <n> bytes" (or "ERR ..." on rejection).
	Ack *Frame
	// Tagged is true when the frame's MessageID/ReplyTo reached the
	// receiver. It is false when the frame carried neither, and also when
	// Send delivered the frame without them: because the receiver predates
	// TypeTagged, or because the tagged header would have pushed the frame
	// over MaxFrameSize (see ErrTaggedFrameTooLarge). A requester that sees
	// Tagged == false cannot expect a reply carrying reply_to, and should
	// match the answer on the sender alone.
	Tagged bool
	// Duplicate is true when the receiver recognised the frame as an
	// identical re-delivery of one it had already stored, and did not store
	// it a second time.
	Duplicate bool
}

SendResult reports what the receiver did with a frame sent by Client.Send.

type Server

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

Server listens on port 1001 and dispatches incoming frames to a handler.

func NewServer

func NewServer(d *driver.Driver, handler Handler) *Server

NewServer creates a data exchange server.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe() error

ListenAndServe binds port 1001 and starts accepting connections.

type Service

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

Service is the L11 plugin adapter. Daemon (L7) holds it only as coreapi.Service; cmd/daemon/main.go (L12) constructs it.

func NewService

func NewService(cfg ServiceConfig) *Service

func (*Service) Name

func (s *Service) Name() string

func (*Service) Order

func (s *Service) Order() int

Order: 110 — after handshake (~70) and the trust subsystem (~50).

func (*Service) Start

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

func (*Service) Stop

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

type ServiceConfig

type ServiceConfig struct {
	ReceivedDir string
	InboxDir    string
	// IncludeBase64 adds a lossless `data_b64` field to inbox JSON
	// alongside `data`. Off by default — only enable when binary
	// payloads (e.g. zlib-compressed envelopes) need to round-trip
	// without UTF-8 mangling.
	IncludeBase64 bool
	// InboxMaxFiles caps the number of inbox files retained on disk.
	// On exceeding the cap, oldest files (by mtime) are evicted FIFO.
	// Zero or negative ⇒ default 10000. Without this cap, a
	// misbehaving peer or sustained inbound load fills the operator's
	// disk indefinitely.
	InboxMaxFiles int
	// InboxMaxBytes caps the total on-disk bytes used by the inbox. Every
	// write is checked against a running total; when a message would not
	// fit, the oldest messages are evicted until the inbox plus the new
	// message is at or below 90% of the cap. A single message larger than the
	// cap is rejected without evicting anything. Zero ⇒ DefaultInboxMaxBytes;
	// a negative value disables the byte cap entirely (escape hatch).
	InboxMaxBytes int64
	// DedupeWindow is how long a stored frame that carried a MessageID is
	// remembered, so an identical re-delivery (same sender, MessageID,
	// ReplyTo, type, filename and bytes) is acknowledged without being
	// stored again. Zero ⇒ DefaultDedupeWindow (10 min); negative disables.
	// Frames without a MessageID are unaffected unless DedupeContentWindow
	// is set.
	DedupeWindow time.Duration
	// DedupeContentWindow, when positive, also suppresses byte-identical
	// frames WITHOUT a MessageID from the same sender that arrive within this
	// window (for example a peer that answers one request over two paths).
	// Zero (the default) keeps the historical behaviour of storing every
	// such frame: two identical legacy messages can be deliberate, and a
	// sender cannot mark them otherwise. Keep it short (a few seconds).
	DedupeContentWindow time.Duration
	// ReceivedMaxBytes caps the total on-disk bytes used by the received-
	// files directory (completed TypeFile / TypeFileStream files plus any
	// retained .partial fragments). Enforced before every write so a peer
	// cannot fill the disk. Zero ⇒ DefaultReceivedMaxBytes; a negative
	// value disables the quota entirely (escape hatch).
	ReceivedMaxBytes int64
	// IdleTimeout bounds how long a single connection may sit without
	// delivering the next frame. Reset before every read, so a slowloris
	// peer that opens a connection and dribbles (or stalls) is dropped
	// instead of pinning the goroutine and its buffers indefinitely.
	// Zero ⇒ DefaultIdleTimeout; a negative value disables the deadline.
	IdleTimeout time.Duration
	// RequireGoverned rejects legacy frames unless they carry a signed
	// governed envelope verified by GovernedVerifier. Enable this only after
	// sender rollout; the default preserves compatibility with older peers.
	RequireGoverned         bool
	GovernedVerifier        GovernedFrameVerifier
	GovernedStreamVerifier  GovernedStreamVerifier
	RequireGovernedReceipts bool
	GovernedReceiptRecorder GovernedReceiptRecorder
	// GovernedContentInspector runs only at this receiver, after signed
	// governed verification and before a message/file is released. It receives
	// a reader, not an exported payload copy, so central authority services do
	// not need application plaintext for DLP.
	GovernedContentInspector         decision.DisclosureContentInspector
	RequireGovernedContentInspection bool
	// GovernedTransferQuota bounds admitted transfers for each verified
	// Intent.AgentID. It never uses an untrusted peer address as the subject.
	// Quota is charged at governed-frame verification (or stream INIT) and does
	// not silently apply to legacy traffic.
	GovernedTransferQuota *decision.TransferQuotaLimiter
	// GovernedRetentionPolicies maps signed V2 disclosure retention classes to
	// durable local expiry work. When non-empty, governed deliveries without a
	// configured V2 retention class are rejected before persistence.
	GovernedRetentionPolicies []GovernedRetentionPolicy
	RetentionStateDir         string
	RetentionSweepInterval    time.Duration
}

ServiceConfig configures the daemon-side dataexchange handler. Both paths default to ~/.pilot/{received,inbox} when empty.

type StreamReceiver added in v0.2.1

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

StreamReceiver handles the receive side of TypeFileStream for a single connection. It writes incoming chunks contiguously to a .partial file (so the on-disk size is always the resume offset), verifies the full SHA-256 on DONE, and atomically renames into place. Decoupled from the daemon Service so it can be unit-tested with just a directory.

func NewStreamReceiver added in v0.2.1

func NewStreamReceiver(receivedDir string, nameSuffix func(base string) string, onSaved func(name, path string, size int64)) *StreamReceiver

NewStreamReceiver builds a receiver writing into receivedDir. nameSuffix maps a base filename to a final unique name (nil ⇒ a timestamped default). onSaved (nil ok) fires after a verified file is renamed into place. No disk quota is enforced — use NewStreamReceiverWithQuota to bound on-disk bytes.

func NewStreamReceiverWithQuota added in v0.2.1

func NewStreamReceiverWithQuota(receivedDir string, nameSuffix func(base string) string, onSaved func(name, path string, size int64), quotaBytes int64) *StreamReceiver

NewStreamReceiverWithQuota is NewStreamReceiver with a disk quota: quotaBytes caps the total on-disk bytes under receivedDir (completed files plus retained .partial fragments). Enforced on INIT and on every chunk write so a peer cannot fill the disk mid-stream. Zero ⇒ unlimited.

func NewStreamReceiverWithQuotaAndCommit added in v0.2.2

func NewStreamReceiverWithQuotaAndCommit(receivedDir string, nameSuffix func(base string) string, onSaved func(name, path string, size int64), onCommit func([transferIDLen]byte, string, string, int64) error, quotaBytes int64) *StreamReceiver

NewStreamReceiverWithQuotaAndCommit extends the normal receiver with a transactional commit hook. It is intended for governed streams: the hook records evidence after the final file is durable but before consumers are notified. A hook failure removes the final file and reports COMPLETE failure.

func NewStreamReceiverWithQuotaAndPrepareAndCommit added in v0.2.2

func NewStreamReceiverWithQuotaAndPrepareAndCommit(receivedDir string, nameSuffix func(base string) string, onSaved func(name, path string, size int64), onPrepare, onCommit func([transferIDLen]byte, string, string, int64) error, quotaBytes int64) *StreamReceiver

NewStreamReceiverWithQuotaAndPrepareAndCommit adds a pre-rename durable preparation hook to the governed commit path. A preparation error leaves no final file visible; callers may keep the partial for retry/inspection.

func (*StreamReceiver) Close added in v0.2.1

func (sr *StreamReceiver) Close()

Close releases any open .partial handles (call on connection teardown). The .partial files themselves remain for resume.

func (*StreamReceiver) HandleFrame added in v0.2.1

func (sr *StreamReceiver) HandleFrame(f *Frame) *Frame

HandleFrame processes one TypeFileStream frame and returns the response frame to send back (nil ⇒ nothing to send). It never returns an error for protocol-level problems — those are reported to the peer via COMPLETE / ABORT frames so the connection loop stays simple.

type StreamResult added in v0.2.1

type StreamResult struct {
	BytesSent    int64  // chunk bytes actually written to the wire this run
	BytesResumed int64  // bytes the receiver already had (skipped)
	TotalBytes   int64  // file size
	Sha256       string // hex of the full-content hash declared in INIT
	OK           bool
	Message      string // receiver's COMPLETE message (empty on success)
}

StreamResult summarizes a completed (or failed) TypeFileStream transfer.

type TraceFrame

type TraceFrame struct {
	SentAtNs  int64
	InnerType uint32
	Payload   []byte
}

TraceFrame carries timing metadata around an inner message frame.

func ReadTracePayload

func ReadTracePayload(f *Frame) (*TraceFrame, error)

ReadTracePayload decodes a TraceFrame from a raw TypeTrace Frame.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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