corev2

package
v0.0.0-...-c82e7e9 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MPL-2.0 Imports: 20 Imported by: 0

Documentation

Overview

Package corev2 implements the backend-neutral FlexModule v2 module SDK. Authentication, actual grants, lifecycle admission and resource ownership are host responsibilities; none are inferred from RPC metadata by this package.

Index

Constants

View Source
const (
	// MaxUploadChunkBytes is the normative per-chunk limit (256 KiB).
	MaxUploadChunkBytes = 256 * 1024
	// MaxUploadFileBytes is the storage limit, not a backend send guarantee.
	MaxUploadFileBytes uint64 = 500 * 1024 * 1024
)
View Source
const (
	// ProtocolMajor is the application handshake and manifest major version.
	ProtocolMajor = 2
	// PluginKey is the only go-plugin service key in application protocol v2.
	PluginKey = "core-v2"
	// HelperBrokerID identifies the single authenticated reverse connection.
	HelperBrokerID uint32 = 1
	// WorkRefMetadata is a bounded active-delivery reference, never an identity.
	WorkRefMetadata        = "flexmodule-work-ref"
	CapabilityConfigRead   = "core.config.read"
	CapabilityUpload       = "core.upload"
	CapabilityPublicEgress = "core.network.public_egress"
)

Variables

This section is empty.

Functions

func DecodeExactJSON

func DecodeExactJSON(value *wire.JSONValue, limits JSONLimits) (any, error)

DecodeExactJSON returns a local dynamic view with json.Number numeric leaves. The wire representation remains the exact original bytes, not a re-encoding.

func HandshakeConfig

func HandshakeConfig() plugin.HandshakeConfig

HandshakeConfig returns a fresh application-v2 handshake. The cookie only detects accidental execution; AutoMTLS and the trusted host binding establish connection authentication, not this public cookie.

func HelperContext

func HelperContext(ctx context.Context) context.Context

HelperContext strips all outgoing metadata and forwards only an active event work reference installed by the SDK. It never propagates claimed identities, authorization headers or arbitrary inbound metadata. A saved callback context loses its reference when that callback returns or is canceled. Host-side validation of the active reference is still required; it grants no authority.

func NewJSONValue

func NewJSONValue(raw []byte, limits JSONLimits) (*wire.JSONValue, error)

NewJSONValue validates and copies exact bytes; nil does not mean JSON null.

func SafeRPCError

func SafeRPCError(err error) error

SafeRPCError preserves only locally minted safe errors and cancellation. Unknown application errors (even arbitrary status errors) become INTERNAL; their messages, details and causes must not cross the module boundary.

func ValidateConfigJSON

func ValidateConfigJSON(value *wire.JSONValue, limits JSONLimits) error

ValidateConfigJSON enforces the additional core configuration object contract. Whitespace is preserved; an absent value, array, scalar or null is not config.

func ValidateExactJSON

func ValidateExactJSON(raw []byte, limits JSONLimits) error

ValidateExactJSON accepts exactly one complete UTF-8 JSON value. It validates without converting numeric tokens to float64, preserving large integers and exact decimal/exponent lexemes. NaN, infinity and trailing values are invalid.

Types

type BrokerGuard

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

BrokerGuard admits exactly one reverse-helper knock and acknowledgement for one primary connection over the entire instance lifetime. Install DialOption on that primary go-plugin ClientConfig before Client(), never on a later helper connection. onFailure must be nonblocking and terminate the instance; it is called at most once, without a guard lock held.

In pinned go-plugin 1.8, each blockedClientListener.Accept consumes one token from waitCh before one yamux session.Accept. AcceptKnock adds one token, not a permanent opening. Rejecting every second knock therefore permits at most one reverse gRPC connection, including an idle/incomplete first connection. Raw unknocked yamux streams remain in its bounded backlog and cannot unblock a second helper Accept. No reconnect or replacement connection is authorized.

func NewBrokerGuard

func NewBrokerGuard(onFailure func(error)) (*BrokerGuard, error)

NewBrokerGuard requires a terminal failure callback. It uses the already linked go-plugin descriptor, not a duplicate wire schema or an internal import.

func (*BrokerGuard) Close

func (g *BrokerGuard) Close()

Close disables future broker admission and suppresses expected teardown failures. It deliberately does not cancel the existing stream or close the helper transport: STOP cleanup may still use that authenticated connection. The ordinary joined broker/client cleanup remains responsible for transport.

func (*BrokerGuard) DialOption

func (g *BrokerGuard) DialOption() grpc.DialOption

DialOption preserves all go-plugin AutoMTLS and multiplex dial options.

type CoreClient

type CoreClient interface {
	GetConfig(context.Context) (*wire.JSONValue, error)
}

CoreClient returns only the authenticated instance's structured configuration. Configuration is an exact JSON object, not a flattened string map.

func NewCoreClient

func NewCoreClient(conn grpc.ClientConnInterface, limits JSONLimits) (CoreClient, error)

NewCoreClient constructs a context-aware, instance-scoped config client. The returned JSONValue preserves exact bytes and is validated as an object.

type CredentialBinding

type CredentialBinding struct {
	BackendID     string
	Purpose       string
	ResourceScope *wire.ResourceSelector
	ExpiresAt     time.Time
}

CredentialBinding describes one secret's permitted use and finite lifetime. The owner is obtained from ctx, never from these caller-visible fields.

type CredentialEncoder

type CredentialEncoder interface {
	EncodeCredential(ctx context.Context, binding CredentialBinding, rawSecret string) (*wire.CredentialRef, error)
}

CredentialEncoder exists only on the runtime side of the trust boundary. It stores the raw secret for the authenticated destination instance and returns a typed opaque ref; it must not log or embed the raw secret in diagnostics.

type CredentialResolver

type CredentialResolver interface {
	ResolveCredential(ctx context.Context, ref *wire.CredentialRef, expected CredentialUse) (string, error)
}

CredentialResolver is host-only and is never exposed as a module RPC. It checks owner, purpose, resource, expiry and instance state before returning a secret for the immediate trusted adapter call.

type CredentialUse

type CredentialUse struct {
	BackendID     string
	Purpose       string
	ResourceScope *wire.ResourceSelector
}

CredentialUse describes the exact operation binding expected by an adapter. It is constructed by trusted operation policy, not copied from the ref.

type FileClient

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

FileClient explicitly uploads local bytes; no Reader crosses the wire. There is no implicit upload or automatic retry after an ambiguous final reply.

func NewFileClient

func NewFileClient(conn grpc.ClientConnInterface) (*FileClient, error)

NewFileClient binds file operations to the authenticated helper connection.

func (*FileClient) DeleteUpload

func (c *FileClient) DeleteUpload(ctx context.Context, ref *wire.UploadedFileRef) error

DeleteUpload requests owned cleanup; the host enforces ownership and expiry.

func (*FileClient) Upload

Upload sends metadata followed by nonempty sequential chunks. Cancellation cancels the RPC and closes src if it implements io.ReadCloser, interrupting readers whose Close unblocks Read. Other Readers must return from Read in bounded time: Go cannot forcibly interrupt an arbitrary io.Reader. The SDK never starts an unbounded read goroutine and does not close src on success.

type HelperBinder

type HelperBinder func(ctx context.Context, conn grpc.ClientConnInterface) error

HelperBinder installs core and selected backend clients before user INIT. The connection is owned by ModulePlugin. The callback must honor ctx and must not close or retain independent ownership of the connection. The supplied connection enforces HelperContext for all calls, including stream creation.

type HelperRegistrar

type HelperRegistrar func(grpc.ServiceRegistrar) error

HelperRegistrar installs concrete instance-bound helper services. Its closure captures the host's trusted principal and authorizer; no identity is accepted from module payloads or metadata. Registration must not perform blocking work. Services registered before manifest/grant negotiation must deny all access until P4 has bound the immutable actual grants to this authenticated instance.

type HelperServerFactory

type HelperServerFactory func(brokerOptions []grpc.ServerOption) (*grpc.Server, error)

HelperServerFactory constructs a per-instance server using ALL brokerOptions, including the broker's AutoMTLS credentials. The host adds its own finite RPC limits and principal-binding interceptors. It must return a fresh server with no services registered; the bridge invokes every supplied registrar before signaling readiness. Construction must not block or perform I/O. This is the P4 authentication integration boundary.

type HookClient

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

HookClient is the host's complete context-aware module hook client. Closing it stops its owned reverse helper server, not the primary go-plugin connection. The host must additionally terminate/close the owning go-plugin instance.

func (*HookClient) Close

func (c *HookClient) Close() error

Close forcibly stops helper RPCs, without waiting for untrusted handlers.

func (*HookClient) GetManifest

func (c *HookClient) GetManifest(ctx context.Context) (*wire.ModuleManifest, error)

func (*HookClient) GetStatus

func (c *HookClient) GetStatus(ctx context.Context) (*wire.Status, error)

func (*HookClient) HelperErrors

func (c *HookClient) HelperErrors() <-chan error

HelperErrors reports an unexpected reverse acceptor exit after readiness. P4 must fail the instance if this channel receives an error. It closes after normal shutdown. Readiness itself is awaited before Dispense returns.

func (*HookClient) OnEvent

func (c *HookClient) OnEvent(ctx context.Context, event *wire.EventEnvelope) error

func (*HookClient) OnStage

func (c *HookClient) OnStage(ctx context.Context, req *wire.StageRequest) error

type HostPlugin

type HostPlugin struct {
	plugin.NetRPCUnsupportedPlugin
	// contains filtered or unexported fields
}

HostPlugin owns one reverse helper acceptor and returns *HookClient from go-plugin Dispense. The host injects its authenticated per-instance server factory and concrete core/file/backend registrars. There is no authorization fallback: this SDK neither invents grants nor installs permissive services.

func NewHostPlugin

func NewHostPlugin(startup context.Context, factory HelperServerFactory, registrars []HelperRegistrar, limits TransportLimits, guard *BrokerGuard) (*HostPlugin, error)

NewHostPlugin captures the single global startup context, trusted server factory, finite limits and all concrete registrars (Core and FileTransfer must be included). P4 must configure its go-plugin ClientConfig with AutoMTLS=true, GRPCBrokerMultiplex=true, SkipHostEnv=true and AllowedProtocols=[ProtocolGRPC]. RunnerFunc, primary path confinement and instance cleanup remain host-owned. guard.DialOption must be installed on the same primary ClientConfig before Client is called. Helper startup rejects absent/mismatched guard binding.

func (*HostPlugin) GRPCClient

func (p *HostPlugin) GRPCClient(lifetime context.Context, broker *plugin.GRPCBroker, conn *grpc.ClientConn) (interface{}, error)

GRPCClient starts exactly one reverse acceptor. It waits for actual listener establishment and service registration, not Dial or Serve completion, avoiding the sequential multiplex broker deadlock. Early acceptor exit is an error.

func (*HostPlugin) GRPCServer

func (p *HostPlugin) GRPCServer(*plugin.GRPCBroker, *grpc.Server) error

GRPCServer rejects serving a host-side plugin as a module.

func (*HostPlugin) PluginMap

func (p *HostPlugin) PluginMap() plugin.PluginSet

PluginMap returns the complete host plugin map for application protocol v2.

type JSONLimits

type JSONLimits struct {
	MaxBytes int
	MaxDepth int
}

JSONLimits bounds input bytes and nested array/object containers. Both values must be positive; operators must choose finite values rather than defaults.

type ModuleHooks

type ModuleHooks interface {
	GetManifest(context.Context) (*wire.ModuleManifest, error)
	GetStatus(context.Context) (*wire.Status, error)
	OnStage(context.Context, *wire.StageRequest) error
	OnEvent(context.Context, *wire.EventEnvelope) error
}

ModuleHooks is the complete module-facing lifecycle and event contract. Implementations must honor cancellation and return actual failures. START launches workers and returns without waiting for RUNNING-only helper calls. DRAIN must not wait for queued events that the host can still deliver.

type ModulePlugin

type ModulePlugin struct {
	plugin.NetRPCUnsupportedPlugin
	// contains filtered or unexported fields
}

ModulePlugin exposes Hook over the primary go-plugin connection and owns the single reverse helper connection. No backend package is imported here. Construct one plugin per process/instance; it cannot be reinitialized.

func NewModulePlugin

func NewModulePlugin(lifetime context.Context, hooks ModuleHooks, bind HelperBinder, limits TransportLimits) (*ModulePlugin, error)

NewModulePlugin binds an explicit process lifetime, hooks, helper-client binder and finite RPC limits. The binder runs before the user's INIT callback. Cancel lifetime or call Close to terminate all owned helper work on startup failure.

func (*ModulePlugin) Close

func (p *ModulePlugin) Close() error

Close cancels and closes owned helper transport. It is safe to call repeatedly and does not wait for user callbacks that ignore cancellation.

func (*ModulePlugin) GRPCClient

func (p *ModulePlugin) GRPCClient(context.Context, *plugin.GRPCBroker, *grpc.ClientConn) (interface{}, error)

GRPCClient rejects using a module-side plugin as a host-side plugin.

func (*ModulePlugin) GRPCServer

func (p *ModulePlugin) GRPCServer(broker *plugin.GRPCBroker, server *grpc.Server) error

GRPCServer implements go-plugin's module registration boundary.

func (*ModulePlugin) PluginMap

func (p *ModulePlugin) PluginMap() plugin.PluginSet

PluginMap returns the one and only v2 plugin key. The caller serves it with HandshakeConfig and grpc support; stdout before the handshake is forbidden.

func (*ModulePlugin) ServeConfig

func (p *ModulePlugin) ServeConfig() *plugin.ServeConfig

ServeConfig supplies the complete module bootstrap configuration, preserving go-plugin's TLS options and applying finite primary-server RPC limits. Pass this to plugin.Serve; do not print to stdout before Serve's handshake.

type Reason

type Reason uint8

Reason selects a fixed safe diagnostic. Arbitrary source error text, URLs, response bodies, secret values and caller-provided strings are never copied.

const (
	ReasonInternal Reason = iota
	ReasonInvalidArgument
	ReasonProtocolMismatch
	ReasonInvalidStage
	ReasonInvalidStatus
	ReasonInvalidJSON
	ReasonJSONLimit
	ReasonInvalidLimits
	ReasonHelperUnavailable
	ReasonHelperStartup
	ReasonHelperBinding
	ReasonAlreadyInitialized
	ReasonNotInitialized
	ReasonUploadSequence
	ReasonUploadSizeMismatch
	ReasonUploadTooLarge
	ReasonChunkTooLarge
	ReasonSourceRead
	ReasonCanceled
	ReasonDeadlineExceeded
	ReasonUnauthenticated
	ReasonCapabilityDenied
	ReasonScopeDenied
	ReasonInstanceNotRunning
	ReasonInstanceDraining
	ReasonQuotaExceeded
	ReasonRefNotFound
	ReasonRefExpired
	ReasonUnsupportedVariant
	ReasonNumericOutOfRange
)

type SafeError

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

SafeError is a locally constructed structured status whose text is fixed. It deliberately does not retain an unsafe source error as an unwrap cause.

func NewError

func NewError(code codes.Code, reason Reason) *SafeError

NewError creates a fixed diagnostic without retaining arbitrary source text. Local rejections are NOT_SENT; helper transport failures conservatively report UNKNOWN. Invalid codes/reasons fail closed rather than returning nil success.

func (*SafeError) Error

func (e *SafeError) Error() string

func (*SafeError) GRPCStatus

func (e *SafeError) GRPCStatus() *status.Status

GRPCStatus allows grpc-go to transmit the safe status and typed detail.

type TransportLimits

type TransportLimits struct {
	MaxReceiveBytes int
	MaxSendBytes    int
}

TransportLimits are explicit finite transport limits. There are no unlimited defaults. JSON limits are separately required by NewCoreClient.

Jump to

Keyboard shortcuts

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