server

package
v0.5.3 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Overview

Package server serves a session.Client over host-defined wire protocols.

Protocol is the extension point; the ACP built-in is package server/acp. More protocols can be served by the same Server, each at its own path:

srv := server.NewServer(rt, agent, acp.New(wire), myProtocol{})
_ = srv.ServeHTTP(ctx, addr) // or srv.Serve(ctx, listener)

A connection is event-driven: its Handler gets each frame from the peer and each event of the sessions it follows, one call at a time, and never waits for the peer. On net/http the Server accepts each connection as a WebSocket and holds it in a goroutine. A platform that holds the socket itself (a Cloudflare Durable Object) calls Connect, then Connection.Serve on its socket, so every host runs the same protocol code. docs/protocol.md follows a turn through the server, from the client's prompt to the answer.

The program on the other end of a connection is the caller's. This module does not ship it. A protocol parses its own credential payload and stores the bindings on a CredentialBag; it puts bag.Take() on Prompt or Resume. Runtime, harness, VFS, and Temporal do not import this package.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrAuthenticationRequired means no authenticated principal is available.
	ErrAuthenticationRequired = errors.New("authentication required")
	// ErrAuthenticationFailed means supplied credentials were rejected.
	ErrAuthenticationFailed = errors.New("authentication failed")
	// ErrAuthorizationDenied means the principal cannot perform an operation.
	ErrAuthorizationDenied = errors.New("authorization denied")
)
View Source
var (
	ErrInvalidRequest  = errors.New("invalid request")
	ErrMethodNotFound  = errors.New("method not found")
	ErrInternal        = errors.New("internal server error")
	ErrSessionNotFound = session.ErrNotFound
)

Wire-facing sentinels. Session errors are the owning package's sentinels (same pointer) so errors.Is is one check. Authentication sentinels live in auth.go.

View Source
var ErrNetworkSecurityPolicyRequired = errors.New("server: configure security or explicitly allow anonymous network access")

ErrNetworkSecurityPolicyRequired prevents accidental anonymous listeners.

View Source
var ErrStreamEnded = errors.New("server: the session's event stream ended")

ErrStreamEnded is why a follow ended before its Handler stopped it: the session's event stream broke, or the session closed.

Functions

func ErrorCause added in v0.4.0

func ErrorCause(sentinel, cause error, format string, args ...any) error

ErrorCause is Errorf with an underlying cause for errors.Is.

func Errorf added in v0.4.0

func Errorf(sentinel error, format string, args ...any) error

Errorf is a caller-facing error that unwraps to sentinel.

func IsClientError

func IsClientError(err error) bool

func PublicError

func PublicError(err error) error

PublicError returns a wire-safe error: client errors pass through unchanged; all other errors become ErrInternal so internal details are not leaked.

Types

type Attempt added in v0.4.0

type Attempt struct {
	Scheme     string
	Credential Secret
	Binding    ChannelBinding
}

Attempt is the canonical input to a host Authenticator.

type Authenticator added in v0.4.0

type Authenticator interface {
	Authenticate(context.Context, Attempt) (Principal, error)
}

Authenticator verifies an authentication attempt supplied by a protocol or transport adapter.

type Authorizer added in v0.4.0

type Authorizer interface {
	Authorize(context.Context, Principal, Operation) error
}

Authorizer decides whether a principal can perform an operation.

type ChannelBinding added in v0.4.0

type ChannelBinding struct {
	Kind string
	ID   string
}

ChannelBinding identifies the logical channel on which authentication occurred. Values are transport-neutral and contain no credential material.

type Connection

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

Connection is one connection that a Server admitted (Connect): its protocol and its caller. Serve runs it on a socket.

func (*Connection) Serve added in v0.5.0

func (c *Connection) Serve(ctx context.Context, sock Socket)

Serve runs the connection on sock until a read from sock fails or ctx ends. It reads the frames in order and gives each to the protocol's Handler, and it runs one subscription for each follow of the Handler. The sessions' turns go on after the connection ends: a new connection can load a session and follow it again.

type Context added in v0.4.0

type Context struct {
	Principal Principal
	Binding   ChannelBinding
}

Context is the authenticated state propagated through server connections.

func (Context) Authenticated added in v0.4.0

func (c Context) Authenticated() bool

Authenticated reports whether this context contains a valid principal.

type CredentialBag added in v0.5.0

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

CredentialBag is the VFS credential state for one wire session. A protocol parses its own payload into mount.Binding values, then calls Bind, Refresh, and Unbind. Take copies that state onto AuthContext for the next Prompt or Resume and clears the drop list.

func (*CredentialBag) Bind added in v0.5.0

func (b *CredentialBag) Bind(binding mount.Binding) error

Bind validates b and stores it. A later bind with the same provider and alias replaces the previous one.

func (*CredentialBag) Refresh added in v0.5.0

func (b *CredentialBag) Refresh(provider string, cred mount.Credential) bool

Refresh replaces the token on every binding for provider. It reports whether any binding matched.

func (*CredentialBag) Take added in v0.5.0

func (b *CredentialBag) Take() session.AuthContext

Take returns the bindings for the next work item and clears drops.

func (*CredentialBag) Unbind added in v0.5.0

func (b *CredentialBag) Unbind(point, provider string)

Unbind removes bindings whose alias or provider matches and records the alias on the next Take drop list.

type Env added in v0.5.0

type Env struct {
	Client session.Client
	Agent  tacklr.AgentOptions
	// Workspace says the runtime mounts a workspace for the sessions
	// (Server.Workspace), so clients may bind backends to it.
	Workspace bool
	// Security is the host's authentication and authorization. Nil allows
	// every operation.
	Security *Service
	// Caller is the security context of the request that opened the
	// connection: its principal when the request carried a credential the
	// host accepted, else the zero Context.
	Caller Context
}

Env is what a connection serves with.

type HTTPAttemptExtractor added in v0.2.0

type HTTPAttemptExtractor func(*http.Request) (Attempt, bool)

HTTPAttemptExtractor translates transport credential evidence into the protocol-neutral security model. It is an edge adapter, not part of the core.

type Handler added in v0.5.0

type Handler interface {
	// Frame handles one frame from the peer.
	Frame(ctx context.Context, frame []byte)
	// Deliver handles one event of session id, which the Handler follows.
	// When the events stop before the Handler stops the follow, the last
	// event is an EventError whose Error wraps ErrStreamEnded.
	Deliver(ctx context.Context, id session.ID, ev session.Event)
	// Closed is the end of the connection: the Handler ends what it has
	// open (its requests' spans). The sessions' turns go on.
	Closed(ctx context.Context)
}

Handler is a protocol's side of one connection. The host calls it one call at a time, so it needs no lock, and each call returns without waiting for the peer.

type MemoryWireStore

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

MemoryWireStore is an in-process ProtocolWireStore.

func NewMemoryWireStore

func NewMemoryWireStore() *MemoryWireStore

NewMemoryWireStore returns an empty in-memory wire store.

func (*MemoryWireStore) Delete

func (s *MemoryWireStore) Delete(_ context.Context, sessionID string) error

func (*MemoryWireStore) Get

func (s *MemoryWireStore) Get(_ context.Context, sessionID string) ([]byte, error)

func (*MemoryWireStore) Put

func (s *MemoryWireStore) Put(_ context.Context, sessionID string, payload []byte) error

type Operation added in v0.4.0

type Operation struct {
	Action   string
	Resource string
}

Operation is a protocol-neutral authorization request.

type Peer added in v0.5.0

type Peer interface {
	// Send writes one frame to the peer.
	Send(ctx context.Context, frame []byte) error
	// Follow delivers the events of session id after after to
	// Handler.Deliver, until the Handler calls stop or the connection
	// ends. stop does not wait. The Handler owns its follows: the host
	// keeps none it would have to match.
	Follow(ctx context.Context, id session.ID, after session.Seq) (stop func(), err error)
}

Peer is a connection as its Handler sees it: the host sends the frames and delivers the events of the sessions the Handler follows.

type Principal added in v0.4.0

type Principal struct {
	Subject string
}

Principal is the stable, opaque identity returned by a host Authenticator. Subject must be stable across reconnects when durable sessions can be loaded.

func NewPrincipal added in v0.4.0

func NewPrincipal(subject string) (Principal, error)

NewPrincipal constructs a Principal and rejects an empty subject.

func (Principal) Valid added in v0.4.0

func (p Principal) Valid() bool

Valid reports whether the principal has a stable subject.

type Protocol

type Protocol interface {
	// Path is where the protocol's connections open, such as "/acp".
	Path() string
	// Open is the protocol's side of a new connection.
	Open(env Env, peer Peer) Handler
}

Protocol is a wire protocol over session.Client: the Server admits its connections at Path, and each connection gets a Handler from Open.

A connection is event-driven. The host calls the Handler once for each frame from the peer and once for each event of a session the Handler follows, one call at a time. The Handler keeps no goroutine and does not wait for the peer: it sends its own requests and handles the answers as frames. So the same protocol runs on a host that holds the socket in a process (net/http, a Durable Object) and on one where the platform holds it and calls the host once for each frame.

The ACP built-in is package server/acp.

type ProtocolWireStore

type ProtocolWireStore interface {
	Put(ctx context.Context, sessionID string, payload []byte) error
	Get(ctx context.Context, sessionID string) ([]byte, error)
	Delete(ctx context.Context, sessionID string) error
}

ProtocolWireStore persists protocol-owned session envelopes (not harness checkpoints). Payload is opaque JSON defined by each protocol. May share a database connection with other Tacklr stores without sharing schema.

type Secret added in v0.4.0

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

Secret is ephemeral credential material. Its String and GoString methods are deliberately redacted so ordinary structured logging cannot reveal it.

func NewSecret added in v0.4.0

func NewSecret(value []byte) Secret

NewSecret copies credential material into a redaction-safe value.

func (Secret) Bytes added in v0.4.0

func (s Secret) Bytes() []byte

Bytes returns a copy for a host Authenticator.

func (Secret) Empty added in v0.4.0

func (s Secret) Empty() bool

Empty reports whether no credential material is present.

func (Secret) GoString added in v0.4.0

func (Secret) GoString() string

func (Secret) String added in v0.4.0

func (Secret) String() string

type Server

type Server struct {
	Client session.Client
	Agent  tacklr.AgentOptions
	// Workspace says the runtime mounts a workspace for the sessions
	// (worker.Config.Workspace), so clients may bind backends to it (ACP
	// vfs/bind). False refuses binds.
	Workspace bool
	// Protocols are the wire protocols the server serves, each at its
	// Path.
	Protocols []Protocol
	// Security is protocol-neutral authentication and authorization supplied by the host.
	Security *Service
	// HTTPAttempt translates request credentials at the HTTP transport edge.
	HTTPAttempt HTTPAttemptExtractor
	// contains filtered or unexported fields
}

Server serves a session.Client to the protocols' clients. On net/http, ServeHTTP (or Serve, or HTTPMux) accepts each connection as a WebSocket. A platform that holds the socket itself calls Connect, then Connection.Serve on its socket.

func NewServer

func NewServer(rt session.Client, agent tacklr.AgentOptions, protocols ...Protocol) *Server

NewServer serves rt over one or more Protocols. The ACP built-in is acp.New.

func (*Server) AllowAnonymousNetwork added in v0.2.0

func (s *Server) AllowAnonymousNetwork() *Server

AllowAnonymousNetwork explicitly enables unauthenticated network serving. It is intended for local development and trusted private environments.

func (*Server) Connect added in v0.5.0

func (s *Server) Connect(r *http.Request) (*Connection, int)

Connect admits r as a connection of the protocol at r's path. A credential on r (HTTPAttempt) must be one the host accepts; a request with none opens an anonymous connection, which a protocol can authenticate later. A refusal is the HTTP status to answer r with.

func (*Server) HTTPMux

func (s *Server) HTTPMux() *http.ServeMux

HTTPMux serves each protocol's connections at its Path, as WebSockets. Used by ServeHTTP and tests.

func (*Server) Policy added in v0.5.0

func (s *Server) Policy() error

Policy is ErrNetworkSecurityPolicyRequired until the host chose a network policy (WithSecurity or AllowAnonymousNetwork). A host that serves the server on a platform's own listener checks it before it serves.

func (*Server) Serve added in v0.5.0

func (s *Server) Serve(ctx context.Context, ln net.Listener) error

Serve serves all protocol routes on ln until ctx ends, then shuts the server down and returns ctx's error. It closes ln.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(ctx context.Context, addr string) error

ServeHTTP listens on addr and serves all protocol routes there (Serve). A server with no network policy does not listen.

func (*Server) WithSecurity added in v0.2.0

func (s *Server) WithSecurity(service *Service, extract HTTPAttemptExtractor) *Server

WithSecurity installs host authentication and optional HTTP credential extraction. Protocol-native flows such as ACP authenticate can use service without an extractor.

type Service added in v0.4.0

type Service struct {
	Authenticator Authenticator
	Authorizer    Authorizer
}

Service coordinates host-provided authentication and authorization without knowing how any protocol represents credentials or errors.

func (*Service) Authenticate added in v0.4.0

func (s *Service) Authenticate(ctx context.Context, attempt Attempt) (Context, error)

Authenticate delegates to the host and validates its returned invariant.

func (*Service) Authorize added in v0.4.0

func (s *Service) Authorize(ctx context.Context, securityContext Context, operation Operation) error

Authorize requires an authenticated principal and delegates to the optional host policy. No Authorizer means every authenticated principal is allowed.

type Socket added in v0.5.0

type Socket interface {
	// Read is the next frame from the peer. An error ends the connection.
	Read(ctx context.Context) ([]byte, error)
	// Write sends one frame to the peer.
	Write(ctx context.Context, frame []byte) error
}

Socket is one connection of text frames, both ways: a WebSocket that net/http accepted, or one that a platform holds (on Cloudflare, the server side of a WebSocketPair).

Directories

Path Synopsis
Package acp is the Agent Client Protocol built into the server.
Package acp is the Agent Client Protocol built into the server.
Package postgres keeps protocol wire envelopes in Postgres: the server.ProtocolWireStore a protocol reads on session/load.
Package postgres keeps protocol wire envelopes in Postgres: the server.ProtocolWireStore a protocol reads on session/load.

Jump to

Keyboard shortcuts

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