localserver

package
v1.7.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 55 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 localserver provides an embeddable gRPC bridge server for local and remote use. In local mode it runs without TLS on a unix-domain socket. In secure mode (--listen flag) it binds to a TCP address with mTLS + JWT.

Index

Constants

This section is empty.

Variables

View Source
var CollectorCredentialPattern = regexp.MustCompile(`^brc_[A-Za-z0-9_-]{43}$`)

CollectorCredentialPattern matches Bridge's documented brc_ telemetry-only credential format (brc_ followed by base64url(32 random bytes), 43 characters). Shared between the enrollment write path (cmd/bridgectl) and the server-start read path here so a malformed credential file is rejected the same way regardless of how it got there.

View Source
var ControlCredentialPattern = regexp.MustCompile(`^bri_[A-Za-z0-9_-]{43}$`)

ControlCredentialPattern matches Bridge's documented bri_ control-only credential format (bri_ followed by base64url(32 random bytes), 43 characters). It must never match a brc_ telemetry credential and vice versa; the two are never interchangeable. Shared between the enrollment write path (cmd/bridgectl) and this server-start read path.

Functions

func AddRemote

func AddRemote(stateDir, name, host string) error

AddRemote appends a remote to the registry if no entry with the same host already exists. Creates the file if it does not exist.

func AddrPath

func AddrPath() string

AddrPath returns the path to the server address file (TCP fallback on Windows).

func BuildServerSANs

func BuildServerSANs(listenAddr string, extra []string) []string

BuildServerSANs extracts the host from listenAddr and merges it with any additional SANs. Deduplicates entries.

func BundleClientCreds

func BundleClientCreds(outPath, stateDir, clientName string) error

BundleClientCreds creates a .tar.gz archive containing the 4 files needed by a remote client: ca-bundle.crt, <name>.crt, <name>.key, jwt-signing.key. Files are stored flat (no directory prefix) so they extract into the current directory.

func CertProviderFromConfig

func CertProviderFromConfig(secCfg config.SecurityConfig, stateDir string, logger *slog.Logger) (certprovider.CertificateProvider, error)

CertProviderFromConfig constructs a CertificateProvider based on the security configuration. This bridges the new v1.1 SecurityConfig model to the certprovider package.

For the "auto" and "stepca" providers, the returned provider delegates to the same underlying functions as the existing EnsurePKI and RenewServerCertMaterial code paths. For "filesystem", it reads pre-existing certificate material from disk.

Note: EnsurePKI remains the authoritative function for setting up the full PKI state directory (CA, bundles, JWT keypairs, etc.). This function provides a provider handle for operations that only need the CertificateProvider interface (enrollment, renewal, root discovery).

func CertsDir

func CertsDir(stateDir string) string

CertsDir returns the path to the certs subdirectory within the state dir.

func DeployBundle

func DeployBundle(bundlePath, target string, logger *slog.Logger) error

DeployBundle copies a credential bundle to a remote host via scp. The target format is "host:path" (e.g. "do-dev2:~/bridge-creds/"). Uses the system scp binary; requires SSH keys or agent to be configured.

func DiscoverServerName

func DiscoverServerName(stateDir string) string

DiscoverServerName reads the TLS server name recorded by secure startup. Older state directories do not have this file, so auto-PKI's historical "server" name remains the fallback.

func EffectiveAllowedPaths added in v1.4.4

func EffectiveAllowedPaths(configured []string) ([]string, error)

EffectiveAllowedPaths returns the allowed-path list the session policy should enforce: the resolved $HOME directory is always included so agent startup is safe-by-default even with no allowed_paths configured, and any explicitly configured entries extend rather than replace it. Without this, an empty configured list means bridge.Policy.ValidateRepoPath allows every path on the filesystem (see its own "no patterns configured" fast path), which is the opposite of what a safe default should be for a tool that hands an AI agent a working directory to operate in.

It errors rather than silently falling back to an unrestricted policy if $HOME cannot be resolved: a caller that ignored the error and used only `configured` would, with no configured paths either, pass an empty slice to bridge.Policy and end up installing exactly the unrestricted policy this function exists to prevent. Callers must fail startup on error.

func IsMutualTLS

func IsMutualTLS(mode ServerMode) bool

IsMutualTLS reports whether the given mode requires client certificates.

func IsSecureMode

func IsSecureMode(mode ServerMode) bool

IsSecureMode reports whether the given mode requires TLS (either server-only TLS or mutual TLS).

func IsServerRunning

func IsServerRunning(stateDir string) bool

IsServerRunning checks if a local server is already running by probing the socket/address file.

func IssueClientCert

func IssueClientCert(stateDir, clientName string, logger *slog.Logger) (certPath, keyPath string, err error)

IssueClientCert issues a new client certificate signed by the existing CA. The cert is written to stateDir/certs/clients/<clientName>/. Returns paths to the cert and key files.

func IssueClientCertViaOIDC

func IssueClientCertViaOIDC(stateDir, clientName string, stepCA *StepCAConfig, logger *slog.Logger) (certPath, keyPath string, err error)

IssueClientCertViaOIDC obtains a short-lived client certificate from Step CA using the OIDC provisioner. It opens a browser for the OIDC login flow and waits for Step CA to issue the certificate. The `step` CLI must be on PATH.

The cert and key are written to stateDir/certs/clients/<clientName>/ (same layout as IssueClientCert) so the same SDK configuration works for both auto-PKI and Step CA clients.

func KnownProviderIDs added in v1.4.4

func KnownProviderIDs() []string

KnownProviderIDs returns the built-in provider IDs eligible for a top-level CLI shortcut (`bridgectl <provider>`, issue #238) — the full knownProviders() catalog, unfiltered by exec.LookPath so a shortcut is available before the provider CLI is even installed, minus internal compatibility aliases such as "codex-app-server" that share a real provider's binary and would be a confusing duplicate shortcut.

func ModePath

func ModePath() string

ModePath returns the path to the server mode file.

func PIDPath

func PIDPath() string

PIDPath returns the path to the server PID file.

func ReloadEnrollment added in v1.4.3

func ReloadEnrollment(ctx context.Context, stateDir, configPath string) error

ReloadEnrollment waits for the running daemon to apply saved reporting configuration. It never restarts the daemon or interrupts provider sessions.

func RemotesPath

func RemotesPath(stateDir string) string

RemotesPath returns the path to the remotes registry file.

func RenewServerCert

func RenewServerCert(stateDir string, serverSANs []string, logger *slog.Logger, stepCA *StepCAConfig, certValidity time.Duration) error

RenewServerCert re-issues the server certificate in-place. For auto-PKI it re-signs using the existing CA; for Step CA it requests a new cert from the CA server. The new cert is written to the same file paths so the CertReloader picks it up on the next TLS handshake without a server restart.

func RenewServerCertMaterial

func RenewServerCertMaterial(mat *PKIMaterial, serverSANs []string, logger *slog.Logger, stepCA *StepCAConfig, certValidity time.Duration) error

RenewServerCertMaterial re-issues the certificate described by mat in-place. It is used both for state-dir managed certificates and for explicit TLS certificate paths loaded from config.

func RequestCertACME

func RequestCertACME(stepCA *StepCAConfig, sans []string, certPath, keyPath string, logger *slog.Logger) error

RequestCertACME obtains a certificate from Step CA using the ACME provisioner. It starts a temporary HTTP server on port 80 to solve the HTTP-01 challenge. Exported for use by CLI commands.

func RequestCertJWK

func RequestCertJWK(stepCA *StepCAConfig, sans []string, certPath, keyPath string, logger *slog.Logger) error

RequestCertJWK obtains a certificate from Step CA using the JWK provisioner. The provisioner password is read from stepCA.ProvisionerPasswordFile, or prompted from stdin if not set. Exported for use by CLI commands.

func SecureReadFile

func SecureReadFile(path string) ([]byte, error)

SecureReadFile reads path only if it is a regular, non-symlink file with no group/world permission bits set, restoring 0600 afterward. A permissive or replaced credential file (e.g. bridge-credentials.json) must not be silently trusted just because it happens to exist at the expected path.

func ServerCertExpiry

func ServerCertExpiry(certPath string) (notBefore, notAfter time.Time, err error)

ServerCertExpiry returns the NotBefore and NotAfter times of the server certificate at the given path. Used by the renewal loop to determine when to trigger renewal.

func ServerNamePath

func ServerNamePath() string

ServerNamePath returns the path to the file recording the TLS name local clients should use when probing or dialing a secure server.

func SetCertRenewerFunc

func SetCertRenewerFunc(fn CertRenewerFunc) func()

SetCertRenewerFunc overrides the mTLS renewal function variable. It returns a restore function that should be called (e.g. via t.Cleanup) to reset the original. This is exported for use by e2e tests in other packages.

func SetCertRequestFuncs

func SetCertRequestFuncs(jwk, acme CertRequesterFunc) func()

SetCertRequestFuncs overrides the JWK and ACME cert request functions. It returns a restore function that should be called (e.g. via t.Cleanup) to reset the originals. This is exported for use by e2e tests in other packages.

func SocketPath

func SocketPath() string

SocketPath returns the default unix socket path.

func StateDir

func StateDir() string

StateDir returns the bridgectl state directory. It respects the BRIDGECTL_STATE_DIR environment variable for testing; otherwise defaults to ~/.config/bridgectl.

func TelemetrySpoolDir

func TelemetrySpoolDir(path, stateDir string) string

TelemetrySpoolDir resolves a configured segmented telemetry spool directory.

func WriteCertPEM

func WriteCertPEM(path string, resp *stepapi.SignResponse) error

WriteCertPEM writes the certificate chain from a Step CA SignResponse to a PEM file.

Types

type CertRenewerFunc

type CertRenewerFunc func(*StepCAConfig, string, string, *slog.Logger) error

CertRenewerFunc is the signature for mTLS-based certificate renewal.

type CertRequesterFunc

type CertRequesterFunc func(*StepCAConfig, []string, string, string, *slog.Logger) error

CertRequesterFunc is the signature for certificate request functions.

type Config

type Config struct {
	// StateDir overrides the default ~/.config/bridgectl directory.
	StateDir string
	// Version is the running bridgectl build version, reported as the
	// collector version in telemetry segments sent to Bridge. Empty means
	// unknown ("dev"), which is expected for local builds but should never
	// appear in released binaries' delivered telemetry.
	Version string
	// Logger overrides the default logger. Nil uses a default logger at
	// Warn level; set Verbose to lower it to Info.
	Logger *slog.Logger
	// Verbose enables Info-level logging (session lifecycle events).
	// Ignored when Logger is explicitly provided.
	Verbose bool
	// AllowedPaths restricts which repo paths sessions may use.
	// Empty means allow all.
	AllowedPaths []string

	// SecurityMode overrides the security mode determined from ListenAddr.
	// When set to ModeTLS, the server uses server-only TLS + JWT.
	// When set to ModeMTLS or ModeSecure, the server uses mTLS + JWT.
	// When empty, the mode is determined from ListenAddr: non-empty
	// ListenAddr → ModeSecure (mTLS), empty → ModeLocal.
	SecurityMode ServerMode

	// ListenAddr, when set, enables secure mode: the server binds to this
	// TCP address with mTLS + JWT instead of a unix socket. Example:
	// "10.0.0.1:9445" or "0.0.0.0:9445".
	ListenAddr string
	// ServerSANs are additional DNS names or IP addresses for the server
	// certificate. The host from ListenAddr is added automatically.
	ServerSANs []string

	// ConfigPath is an optional path to a YAML config file (same schema as
	// the former daemon bridge.yaml). Values from the file are merged into
	// Config; explicit fields in Config take precedence over file values.
	ConfigPath string

	// DBPath enables BoltDB session persistence. When set, the supervisor
	// writes session metadata and PTY chunks to the file and rehydrates
	// them on startup via LoadHistory.
	DBPath string

	// ProviderFallbacks maps each provider ID to an ordered list of
	// fallback provider IDs to try when the primary is unavailable.
	// Fallbacks are only used when ProviderFallbacksEnabled is true or
	// when the config file sets feature_flags.provider_fallbacks: true.
	ProviderFallbacks map[string][]string

	// ProviderFallbacksEnabled gates whether provider fallback logic is
	// active. When false (the default), fallback lists are ignored even if
	// configured. Set by feature_flags.provider_fallbacks in the config
	// file or programmatically for tests.
	ProviderFallbacksEnabled bool

	// RedactPatterns are compiled into a Redactor that scrubs sensitive
	// values from log output.
	RedactPatterns []string

	// RepoSetup controls repo-local pre-agent setup files. Nil means enabled
	// with built-in defaults.
	RepoSetupEnabled        *bool
	RepoSetupConfigPath     string
	RepoSetupDefaultTimeout time.Duration
	RepoSetupMaxTimeout     time.Duration

	// RateLimits overrides the default rate-limit config. Zero values keep
	// the built-in defaults.
	RateLimits server.RateLimitConfig

	// EventBufferSize overrides the per-session output ring-buffer size in
	// bytes. Zero uses the default (8 MiB).
	EventBufferSize int

	// IdleTimeout overrides the session idle-timeout. Zero uses the
	// default (24 hours).
	IdleTimeout time.Duration

	// Explicit TLS cert paths. When set, these override auto-PKI generation
	// so pre-issued certificates (e.g. from a CI/CD pipeline) can be used.
	// All three (CABundlePath, TLSCertPath, TLSKeyPath) must be provided
	// together; mixed partial configuration is not supported.
	CABundlePath string
	TLSCertPath  string
	TLSKeyPath   string

	// JWTPublicKeys maps issuer name to public key file path for JWT
	// verification in explicit-cert mode. Populated from auth.jwt_public_keys
	// in the config file.
	JWTPublicKeys map[string]string
	// StepCAClients declares Step CA-authenticated clients whose JWT public
	// keys should be loaded at startup if present. Missing optional clients are
	// logged and skipped; missing required clients fail secure startup.
	StepCAClients []ConfiguredJWTClient

	// StepCAURL enables Step CA integration. When set, auto-PKI generation is
	// skipped and server certificates are obtained from the Step CA instance
	// instead. The `step` CLI must be on PATH.
	StepCAURL string
	// StepCARootPath is the path to the Step CA root certificate. Required
	// when StepCAURL is set.
	StepCARootPath string
	// StepCAOIDCProvider is the OIDC issuer URL configured as a Step CA
	// provisioner. Used by `bridgectl server issue-client --oidc-provider`.
	StepCAOIDCProvider string
	// StepCAProvisioner is the name of the Step CA provisioner to use
	// (e.g. "acme", "bridge-jwk"). When empty, the step CLI selects the
	// default provisioner.
	StepCAProvisioner string
	// StepCAProvisionerPasswordFile is the path to a file containing the
	// JWK provisioner password. When set, `step ca certificate` runs
	// non-interactively (required in Docker/headless environments).
	StepCAProvisionerPasswordFile string

	// CertValidity overrides the server certificate validity duration.
	// Zero uses the default (90 days). Useful for testing renewal flows.
	CertValidity time.Duration
	// CertRenewalCheckInterval overrides how often the renewal loop checks
	// certificate expiry. Zero uses the default (1 hour).
	CertRenewalCheckInterval time.Duration
	// contains filtered or unexported fields
}

Config controls local server behaviour.

type ConfiguredJWTClient

type ConfiguredJWTClient struct {
	Issuer   string
	KeyPath  string
	Required bool
}

ConfiguredJWTClient declares a client JWT public key that should be loaded during secure startup when present.

type PKIMaterial

type PKIMaterial struct {
	CACertPath      string // certs/ca.crt
	CAKeyPath       string // certs/ca.key
	ServerCertPath  string // certs/server.crt
	ServerKeyPath   string // certs/server.key
	LocalClientCert string // certs/local-client.crt
	LocalClientKey  string // certs/local-client.key
	CABundlePath    string // certs/ca-bundle.crt
	JWTSigningKey   string // certs/jwt-signing.key
	JWTSigningPub   string // certs/jwt-signing.pub
}

PKIMaterial holds resolved paths to all PKI files needed for secure mode.

func EnsureLocalManagementPKI

func EnsureLocalManagementPKI(stateDir, externalCABundle string, logger *slog.Logger) (*PKIMaterial, error)

EnsureLocalManagementPKI creates the local-only client credentials needed by same-machine bridgectl commands when the server uses externally managed TLS certificates. The returned CA bundle is a state-directory copy of the external server CA bundle plus the generated local management CA.

func EnsurePKI

func EnsurePKI(stateDir string, serverSANs []string, logger *slog.Logger, stepCA *StepCAConfig, certValidity time.Duration) (*PKIMaterial, error)

EnsurePKI ensures that all PKI material exists in stateDir/certs/.

When stepCA is nil (default), the entire set is auto-generated:

  • CA cert/key (ECDSA P-384, 10-year validity)
  • Server cert/key with the provided SANs (90-day validity)
  • Local-client cert/key for CLI's own connections
  • CA trust bundle
  • Ed25519 JWT signing keypair

When stepCA is non-nil, auto-generation is skipped. Instead, the Step CA root is copied to ca-bundle.crt and the server certificate is obtained from Step CA via the `step` CLI. The JWT keypair is still generated locally.

If the CA bundle already exists, this is a no-op and returns existing paths.

func LoadPKIMaterial

func LoadPKIMaterial(stateDir string) *PKIMaterial

LoadPKIMaterial returns a PKIMaterial with resolved paths for an existing certs directory. It does not check whether the files exist.

type Remote

type Remote struct {
	Name string `yaml:"name"`
	Host string `yaml:"host"`
}

Remote represents an enrolled remote bridge server.

func LoadRemotes

func LoadRemotes(stateDir string) ([]Remote, error)

LoadRemotes reads the remotes registry from disk. Returns an empty slice if the file does not exist.

type Server

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

Server wraps all the components needed for a local bridge server.

func Start

func Start(cfg Config) (*Server, error)

Start launches a local bridge gRPC server. In local mode (default) it listens on a unix socket (or TCP localhost on Windows) without auth. In secure mode (ListenAddr set) it binds to TCP with mTLS + JWT.

func (*Server) Addr

func (s *Server) Addr() string

Addr returns the listener address (unix socket path or TCP address).

func (*Server) CertProvider

func (s *Server) CertProvider() certprovider.CertificateProvider

CertProvider returns the v1.1 CertificateProvider, if one was constructed during startup. Returns nil when the server is running with legacy config or in local mode.

func (*Server) Stop

func (s *Server) Stop()

Stop gracefully shuts down the server and cleans up state files.

func (*Server) Target

func (s *Server) Target() string

Target returns the gRPC dial target for this server.

type ServerMode

type ServerMode string

ServerMode represents how the server is running.

const (
	// ModeLocal is the default mode: unix socket, no auth.
	ModeLocal ServerMode = "local"
	// ModeTLS uses TCP + server TLS + JWT for remote access on trusted networks.
	ModeTLS ServerMode = "tls"
	// ModeMTLS uses TCP + mutual TLS + JWT for production/zero-trust access.
	ModeMTLS ServerMode = "mtls"
	// ModeSecure is a deprecated alias for ModeMTLS. It is recognized for
	// backward compatibility with existing server.mode files and tests.
	ModeSecure ServerMode = "secure"
)

func DiscoverMode

func DiscoverMode(stateDir string) ServerMode

DiscoverMode reads the server.mode file to determine how to connect. Returns ModeLocal if the file is missing or unreadable. Recognizes "mtls" and "tls" as new v1.1 mode values alongside the legacy "secure".

func DiscoverTarget

func DiscoverTarget(stateDir string) (target string, mode ServerMode)

DiscoverTarget returns the gRPC dial target and mode for an existing local server. Returns empty target if none is found/reachable.

type StepCAConfig

type StepCAConfig struct {
	// URL is the Step CA server URL (e.g. "https://step-ca.internal:443").
	URL string
	// RootPath is the path to the Step CA root certificate used to verify
	// the CA server's TLS connection.
	RootPath string
	// OIDCProviderURL is the OIDC issuer URL configured as a Step CA
	// provisioner (e.g. "https://accounts.google.com"). Used by
	// IssueClientCertViaOIDC to select the correct provisioner.
	OIDCProviderURL string
	// Provisioner is the name of the Step CA provisioner to use for
	// certificate requests (e.g. "acme", "bridge-jwk"). When empty, the
	// step CLI selects the default provisioner.
	Provisioner string
	// ProvisionerPasswordFile is the path to a file containing the JWK
	// provisioner password. When set, it is passed as
	// --provisioner-password-file to `step ca certificate` so the command
	// can run non-interactively (e.g. in Docker containers without a TTY).
	ProvisionerPasswordFile string
}

StepCAConfig holds optional Step CA integration settings. When URL is set, EnsurePKI delegates certificate issuance to the Step CA instance instead of generating a self-signed CA. The `step` CLI must be on PATH.

func StepCAConfigFromProvider

func StepCAConfigFromProvider(secCfg config.SecurityConfig) *StepCAConfig

StepCAConfigFromProvider extracts a legacy StepCAConfig from a SecurityConfig. This is used during the transition period while EnsurePKI still needs the old config format.

Jump to

Keyboard shortcuts

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