node

package
v0.0.0-...-3159864 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2026 License: Apache-2.0 Imports: 33 Imported by: 0 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.

Documentation

Overview

Package node defines the product-owned data-plane boundary between the authorized runtime service and the execution engine running a sandbox.

Index

Constants

View Source
const (
	CapabilityVersion = 1
	MaxCapabilityTTL  = 30 * time.Second
)

A node capability authorizes one narrowly bounded operation against one sandbox generation. Capabilities are bearer credentials and must never be logged, persisted with customer content, or returned from public resource APIs.

View Source
const (
	RelayCapabilityScheme = "BrezelCapability"
	RelayRouteHeader      = "X-Brezel-Route-ID"
	RelayContentSHAHeader = "X-Brezel-Content-SHA256"
	RelayFilePathHeader   = "X-Brezel-File-Path"
	RelayFileSizeHeader   = "X-Brezel-File-Size"
)

Variables

View Source
var (
	ErrMalformedCapability        = errors.New("malformed node capability")
	ErrInvalidCapability          = errors.New("invalid node capability")
	ErrUnknownCapabilityKey       = errors.New("unknown node capability key")
	ErrInvalidCapabilitySignature = errors.New("invalid node capability signature")
	ErrCapabilityNotYetValid      = errors.New("node capability is not yet valid")
	ErrCapabilityExpired          = errors.New("node capability has expired")
	ErrCapabilityMismatch         = errors.New("node capability does not match request")
)
View Source
var (
	ErrInvalidBinding = errors.New("invalid sandbox binding")
	ErrStaleBinding   = errors.New("stale sandbox binding")
	ErrRevokedBinding = errors.New("revoked sandbox binding")
)
View Source
var (
	ErrCapabilityReplay = errors.New("operation capability was already used")
	ErrReplayCapacity   = errors.New("operation capability replay cache is full")
)

Functions

func NewRouteAdminHandler

func NewRouteAdminHandler(config RouteAdminHandlerConfig) (http.Handler, error)

NewRouteAdminHandler creates the private node lifecycle endpoint. It does not authorize product lifecycle or placement decisions; it only applies an already-authorized controller decision to the fenced node-local ledger.

func RequestDigest

func RequestDigest(operation CapabilityOperation, canonicalRequest []byte) (string, error)

RequestDigest binds a capability to caller-defined canonical request bytes and the operation namespace without placing request content in the token.

Types

type BackendDataPlane

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

BackendDataPlane adapts the initial in-process engine to the owned node boundary. E2B-specific routing and guest credentials remain encapsulated by its backend implementation.

func NewBackendDataPlane

func NewBackendDataPlane(engine backend.Backend) *BackendDataPlane

func (*BackendDataPlane) Capabilities

func (d *BackendDataPlane) Capabilities() Capabilities

func (*BackendDataPlane) OpenPortWebSocket

func (d *BackendDataPlane) OpenPortWebSocket(ctx context.Context, binding SandboxBinding, port uint16, path string) (*websocket.Conn, *http.Response, error)

func (*BackendDataPlane) ReadFile

func (d *BackendDataPlane) ReadFile(ctx context.Context, binding SandboxBinding, path string, destination io.Writer) (backend.FileInfo, error)

func (*BackendDataPlane) RoundTripPort

func (d *BackendDataPlane) RoundTripPort(ctx context.Context, binding SandboxBinding, port uint16, request *http.Request) (*http.Response, error)

func (*BackendDataPlane) Run

func (*BackendDataPlane) ValidatePort

func (d *BackendDataPlane) ValidatePort(port uint16) error

func (*BackendDataPlane) WriteFile

func (d *BackendDataPlane) WriteFile(ctx context.Context, binding SandboxBinding, path string, source io.Reader) (backend.FileInfo, error)

type BindingOption

type BindingOption func(*SandboxBinding)

BindAuthorizedSandbox creates the handoff used for one admitted guest operation. Callers must complete product authorization before calling it.

func WithBindingClock

func WithBindingClock(now func() time.Time) BindingOption

WithBindingClock keeps handoff expiry on the same clock as the lifecycle service. It is primarily useful for deterministic lifecycle tests.

func WithNodeGeneration

func WithNodeGeneration(generation uint64) BindingOption

WithNodeGeneration binds a remote relay handoff to the exact node-local route generation recorded by durable placement. A rebound route must never silently upgrade an already authorized API operation.

type BindingVerifier

type BindingVerifier func(projectID, sandboxID, backendID string, revision int64) bool

BindingVerifier compares the handoff with the service's current durable sandbox identity. It must not perform network I/O or trust guest state.

type Capabilities

type Capabilities struct {
	CommandStreaming        bool
	FileReadWrite           bool
	AuthenticatedPorts      bool
	AuthenticatedWebSockets bool
}

Capabilities are the guest operations that an attached node data plane can enforce. They are the intersection of the engine's declared capabilities and the interfaces it actually implements.

type CapabilityBounds

type CapabilityBounds struct {
	MaxDurationMillis int64  `json:"max_duration_ms,omitempty"`
	MaxRequestBytes   int64  `json:"max_request_bytes,omitempty"`
	MaxResponseBytes  int64  `json:"max_response_bytes,omitempty"`
	Port              uint32 `json:"port,omitempty"`
}

CapabilityBounds are interpreted according to the capability's sole operation. Unused fields must be zero so adding a field cannot accidentally broaden an existing operation.

type CapabilityClaims

type CapabilityClaims struct {
	Version       int                   `json:"v"`
	KeyID         string                `json:"kid"`
	Issuer        string                `json:"iss"`
	Audience      string                `json:"aud"`
	NodeID        string                `json:"node"`
	BootEpoch     string                `json:"epoch"`
	RouteID       string                `json:"route"`
	Generation    uint64                `json:"generation"`
	ProjectID     string                `json:"project"`
	SandboxID     string                `json:"sandbox"`
	JTI           string                `json:"jti"`
	Operations    []CapabilityOperation `json:"ops"`
	RequestDigest string                `json:"request_digest"`
	IssuedAt      int64                 `json:"iat"`
	NotBefore     int64                 `json:"nbf"`
	ExpiresAt     int64                 `json:"exp"`
	Bounds        CapabilityBounds      `json:"bounds"`
}

CapabilityClaims contain only authorization metadata. They intentionally exclude commands, paths, request bodies, output, credentials, and other customer content; those inputs are bound by RequestDigest instead.

type CapabilityExpected

type CapabilityExpected struct {
	Audience      string
	NodeID        string
	BootEpoch     string
	RouteID       string
	Generation    uint64
	ProjectID     string
	SandboxID     string
	Operation     CapabilityOperation
	RequestDigest string
}

CapabilityExpected is the complete node-local context against which a token is verified. No routing or authorization identity is taken from the token without matching this independently established context.

type CapabilityIssue

type CapabilityIssue struct {
	Audience      string
	NodeID        string
	BootEpoch     string
	RouteID       string
	Generation    uint64
	ProjectID     string
	SandboxID     string
	Operation     CapabilityOperation
	RequestDigest string
	Bounds        CapabilityBounds
	TTL           time.Duration
	NotBefore     time.Time
}

CapabilityIssue requests a single-operation capability. RequestDigest must be produced from the exact canonical operation request with RequestDigest.

type CapabilityOperation

type CapabilityOperation string

CapabilityOperation is deliberately closed. Adding an operation changes the node's authority surface and requires an explicit review of its bounds.

const (
	CapabilityRunCommand CapabilityOperation = "command.run"
	CapabilityReadFile   CapabilityOperation = "file.read"
	CapabilityWriteFile  CapabilityOperation = "file.write"
	CapabilityProxyPort  CapabilityOperation = "port.proxy"
	CapabilityWebSocket  CapabilityOperation = "port.websocket"
)

type CapabilitySigner

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

CapabilitySigner issues short-lived node capabilities under one issuer and key identity.

func NewCapabilitySigner

func NewCapabilitySigner(issuer, keyID string, private ed25519.PrivateKey) (*CapabilitySigner, error)

NewCapabilitySigner copies the private key so subsequent caller mutation cannot change the signing identity.

func (*CapabilitySigner) Issue

Issue returns a compact, self-contained, signed token. It accepts no caller- supplied JTI; every issuance receives 128 bits from crypto/rand.

type CapabilityVerifier

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

CapabilityVerifier validates node capabilities using a fixed key set. The map and every public key are copied at construction.

func NewCapabilityVerifier

func NewCapabilityVerifier(issuer string, keys map[string]ed25519.PublicKey) (*CapabilityVerifier, error)

func (*CapabilityVerifier) Authenticate

func (v *CapabilityVerifier) Authenticate(token string) (CapabilityClaims, error)

Authenticate verifies a token's canonical envelope, signing key, signature, configured issuer, time window, and intrinsic claims. It deliberately does not decide whether those claims match a caller's route or request. Callers must pass the returned claims to Match before using them for authorization. Returned claims are safe authorization metadata, not proof that the operation was executed.

func (*CapabilityVerifier) Match

func (v *CapabilityVerifier) Match(claims CapabilityClaims, expected CapabilityExpected) error

Match checks authenticated claims against the complete independently established node-local request context. Claims passed here must be the unchanged result of Authenticate; Match does not authenticate an arbitrary CapabilityClaims value.

func (*CapabilityVerifier) Verify

func (v *CapabilityVerifier) Verify(token string, expected CapabilityExpected) (CapabilityClaims, error)

Verify authenticates a token before checking its claims against the complete expected request context.

type DataPlane

type DataPlane interface {
	Capabilities() Capabilities
	Run(context.Context, SandboxBinding, backend.CommandRequest, func(backend.CommandEvent) error) error
	WriteFile(context.Context, SandboxBinding, string, io.Reader) (backend.FileInfo, error)
	ReadFile(context.Context, SandboxBinding, string, io.Writer) (backend.FileInfo, error)
	ValidatePort(uint16) error
	RoundTripPort(context.Context, SandboxBinding, uint16, *http.Request) (*http.Response, error)
	OpenPortWebSocket(context.Context, SandboxBinding, uint16, string) (*websocket.Conn, *http.Response, error)
	// contains filtered or unexported methods
}

DataPlane is the product-owned node-facing path for commands, file transfer, and authenticated application traffic. Implementations must never return a guest-management or substrate routing credential to the caller.

type RelayDataPlane

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

RelayDataPlane is the API-side half of the node relay. The durable service keeps authorizing product resources, while this client exchanges that decision for one short-lived, request-bound operation capability.

func NewRelayDataPlane

func NewRelayDataPlane(baseURL string, tlsConfig *tls.Config, signer *CapabilitySigner, audience, nodeID string, options ...RelayDataPlaneOption) (*RelayDataPlane, error)

NewRelayDataPlane requires an HTTPS endpoint and constructs the relay client through the hardened mTLS identity boundary. Redirects are disabled so credentials cannot cross origins.

func (*RelayDataPlane) Capabilities

func (d *RelayDataPlane) Capabilities() Capabilities

func (*RelayDataPlane) OpenPortWebSocket

func (d *RelayDataPlane) OpenPortWebSocket(ctx context.Context, binding SandboxBinding, port uint16, path string) (*websocket.Conn, *http.Response, error)

func (*RelayDataPlane) ReadFile

func (d *RelayDataPlane) ReadFile(ctx context.Context, binding SandboxBinding, path string, destination io.Writer) (backend.FileInfo, error)

func (*RelayDataPlane) Ready

func (d *RelayDataPlane) Ready(ctx context.Context) error

Ready verifies the authenticated node data listener and its engine-backed readiness without requiring a sandbox route.

func (*RelayDataPlane) RequiresNodeAssignment

func (*RelayDataPlane) RequiresNodeAssignment() bool

RequiresNodeAssignment lets the lifecycle service reject a relay configuration that has no durable route administrator. It is intentionally not part of DataPlane so test and embedded implementations stay small.

func (*RelayDataPlane) RoundTripPort

func (d *RelayDataPlane) RoundTripPort(ctx context.Context, binding SandboxBinding, port uint16, incoming *http.Request) (*http.Response, error)

func (*RelayDataPlane) Run

func (d *RelayDataPlane) Run(ctx context.Context, binding SandboxBinding, request backend.CommandRequest, emit func(backend.CommandEvent) error) (resultErr error)

func (*RelayDataPlane) ValidatePort

func (d *RelayDataPlane) ValidatePort(port uint16) error

func (*RelayDataPlane) WriteFile

func (d *RelayDataPlane) WriteFile(ctx context.Context, binding SandboxBinding, path string, source io.Reader) (backend.FileInfo, error)

type RelayDataPlaneOption

type RelayDataPlaneOption func(*RelayDataPlane)

func WithRelayCommandDiagnostics

func WithRelayCommandDiagnostics(observer telemetry.CommandDiagnosticObserver) RelayDataPlaneOption

WithRelayCommandDiagnostics enables content-free benchmark diagnostics for the API-side relay hop. It does not expose route or resource identities.

type RelayServer

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

RelayServer is the node-local command, file, and application-port data path. It deliberately has no logger: capability tokens, engine identities, and customer content must never enter ordinary process logs.

func NewRelayServer

func NewRelayServer(config RelayServerConfig) (*RelayServer, error)

func (*RelayServer) BeginDrain

func (s *RelayServer) BeginDrain()

BeginDrain stops readiness and rejects new data operations. Requests that already hold a generation lease are allowed to finish during HTTP shutdown. It is safe to call more than once.

func (*RelayServer) Draining

func (s *RelayServer) Draining() bool

func (*RelayServer) ServeHTTP

func (s *RelayServer) ServeHTTP(w http.ResponseWriter, r *http.Request)

type RelayServerConfig

type RelayServerConfig struct {
	NodeID   string
	Audience string
	Ledger   *nodeledger.Ledger
	Verifier *CapabilityVerifier
	Replay   *ReplayCache
	Engine   backend.Backend
	// MaxInFlight bounds data operations before any request body is read.
	// Zero selects the conservative default.
	MaxInFlight int
	Now         func() time.Time
	Diagnostics telemetry.CommandDiagnosticObserver
}

RelayServerConfig binds one relay process to one node boot. The surrounding nodeidentity server is responsible for mTLS and exact peer verification.

type ReplayCache

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

ReplayCache consumes capability identifiers exactly once. It never evicts a live identifier to make room: saturation fails closed until an entry expires. The cache is intentionally process-local because every node boot has a new boot epoch and capabilities from an earlier process are invalid.

func NewReplayCache

func NewReplayCache(maxLive int) (*ReplayCache, error)

func (*ReplayCache) Len

func (c *ReplayCache) Len() int

func (*ReplayCache) Use

func (c *ReplayCache) Use(jti string, expiresAt time.Time) error

Use atomically consumes jti until expiresAt. Call it only after signature and claim verification; malformed tokens must not consume capacity.

type RouteAdminClient

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

RouteAdminClient applies durable-controller lifecycle decisions to one exact node. It is a private control client, not a public product API.

func NewRouteAdminClient

func NewRouteAdminClient(baseURL string, tlsConfig *tls.Config, expectedNodeID string) (*RouteAdminClient, error)

NewRouteAdminClient constructs a bounded, redirect-free mTLS client.

func (*RouteAdminClient) AttachReady

func (*RouteAdminClient) Bind

func (*RouteAdminClient) Drain

func (*RouteAdminClient) Ready

func (c *RouteAdminClient) Ready(ctx context.Context) error

Ready verifies the exact node control listener and its generation ledger. A healthy data relay is insufficient because lifecycle changes cannot be fenced safely while this endpoint is unavailable.

func (*RouteAdminClient) Rebind

func (*RouteAdminClient) Release

func (*RouteAdminClient) Remove

func (*RouteAdminClient) Resolve

func (c *RouteAdminClient) Resolve(ctx context.Context, routeID string) (RouteAdminResult, error)

Resolve returns the current public route assignment from the exact node. It is used only for reconciliation; private engine identity remains local.

func (*RouteAdminClient) Standby

type RouteAdminError

type RouteAdminError struct {
	StatusCode int
	Code       string
}

RouteAdminError is a content-minimal node-control failure. It deliberately excludes request bodies, route identities, and private engine identifiers.

func (*RouteAdminError) Error

func (e *RouteAdminError) Error() string

type RouteAdminHandlerConfig

type RouteAdminHandlerConfig struct {
	NodeID string
	Ledger *nodeledger.Ledger
	Now    func() time.Time
}

RouteAdminHandlerConfig supplies the node-local authority for route lifecycle. The handler must be served by nodeidentity.NewControlHTTPServer; it additionally rejects requests that lack a verified TLS peer chain.

type RouteAdminResult

type RouteAdminResult struct {
	NodeID   string           `json:"node_id"`
	Route    nodeledger.Route `json:"route"`
	Replayed bool             `json:"replayed"`
}

RouteAdminResult contains only the public node route. The node-private engine identity is deliberately absent.

type RouteBindRequest

type RouteBindRequest struct {
	RouteID   string `json:"route_id"`
	ProjectID string `json:"project_id"`
	SandboxID string `json:"sandbox_id"`
	EngineID  string `json:"engine_id"`
}

RouteBindRequest creates a node-private engine assignment. EngineID is accepted only by the node control endpoint and never appears in a response.

type RouteRebindRequest

type RouteRebindRequest struct {
	RouteID       string           `json:"route_id"`
	ProjectID     string           `json:"project_id"`
	SandboxID     string           `json:"sandbox_id"`
	Generation    uint64           `json:"generation"`
	ExpectedState nodeledger.State `json:"expected_state"`
	EngineID      string           `json:"engine_id"`
}

RouteRebindRequest replaces the private engine target of a standby route. A successful rebind always returns a newly allocated generation.

type RouteRemoveResult

type RouteRemoveResult struct {
	NodeID     string `json:"node_id"`
	RouteID    string `json:"route_id"`
	ProjectID  string `json:"project_id"`
	SandboxID  string `json:"sandbox_id"`
	Generation uint64 `json:"generation"`
}

RouteRemoveResult confirms removal without serializing the former private binding. Removal retries are not considered idempotent because the ledger intentionally retains no project-scoped removal receipt.

type RouteTransitionRequest

type RouteTransitionRequest struct {
	RouteID       string           `json:"route_id"`
	ProjectID     string           `json:"project_id"`
	SandboxID     string           `json:"sandbox_id"`
	Generation    uint64           `json:"generation"`
	ExpectedState nodeledger.State `json:"expected_state"`
}

RouteTransitionRequest identifies the complete assignment and lifecycle state that the durable controller independently expects to mutate.

type SandboxBinding

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

SandboxBinding is an in-process, content-free authorization handoff. It is not a bearer credential and is not valid outside this process. The runtime service creates it only after project ownership, lifecycle state, expiry, mutation fencing, and quota admission have succeeded.

Fields deliberately remain private so substrate identifiers cannot leak into public API objects or logs through ordinary serialization.

func BindAuthorizedSandbox

func BindAuthorizedSandbox(projectID, sandboxID, backendID, operationID string, revision int64, expiresAt time.Time, verify BindingVerifier, options ...BindingOption) (SandboxBinding, error)

func (SandboxBinding) Revoke

func (b SandboxBinding) Revoke()

Revoke prevents any subsequent use of this handoff. Copies share the same revocation state.

func (SandboxBinding) String

func (b SandboxBinding) String() string

String is intentionally content-minimal. In particular, it excludes the substrate identifier used to address the engine.

Jump to

Keyboard shortcuts

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