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 ¶
- Variables
- func AddRemote(stateDir, name, host string) error
- func AddrPath() string
- func BuildServerSANs(listenAddr string, extra []string) []string
- func BundleClientCreds(outPath, stateDir, clientName string) error
- func CertProviderFromConfig(secCfg config.SecurityConfig, stateDir string, logger *slog.Logger) (certprovider.CertificateProvider, error)
- func CertsDir(stateDir string) string
- func DeployBundle(bundlePath, target string, logger *slog.Logger) error
- func DiscoverServerName(stateDir string) string
- func EffectiveAllowedPaths(configured []string) ([]string, error)
- func IsMutualTLS(mode ServerMode) bool
- func IsSecureMode(mode ServerMode) bool
- func IsServerRunning(stateDir string) bool
- func IssueClientCert(stateDir, clientName string, logger *slog.Logger) (certPath, keyPath string, err error)
- func IssueClientCertViaOIDC(stateDir, clientName string, stepCA *StepCAConfig, logger *slog.Logger) (certPath, keyPath string, err error)
- func KnownProviderIDs() []string
- func ModePath() string
- func PIDPath() string
- func ReloadEnrollment(ctx context.Context, stateDir, configPath string) error
- func RemotesPath(stateDir string) string
- func RenewServerCert(stateDir string, serverSANs []string, logger *slog.Logger, ...) error
- func RenewServerCertMaterial(mat *PKIMaterial, serverSANs []string, logger *slog.Logger, ...) error
- func RequestCertACME(stepCA *StepCAConfig, sans []string, certPath, keyPath string, ...) error
- func RequestCertJWK(stepCA *StepCAConfig, sans []string, certPath, keyPath string, ...) error
- func SecureReadFile(path string) ([]byte, error)
- func ServerCertExpiry(certPath string) (notBefore, notAfter time.Time, err error)
- func ServerNamePath() string
- func SetCertRenewerFunc(fn CertRenewerFunc) func()
- func SetCertRequestFuncs(jwk, acme CertRequesterFunc) func()
- func SocketPath() string
- func StateDir() string
- func TelemetrySpoolDir(path, stateDir string) string
- func WriteCertPEM(path string, resp *stepapi.SignResponse) error
- type CertRenewerFunc
- type CertRequesterFunc
- type Config
- type ConfiguredJWTClient
- type PKIMaterial
- type Remote
- type Server
- type ServerMode
- type StepCAConfig
Constants ¶
This section is empty.
Variables ¶
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.
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 ¶
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 ¶
BuildServerSANs extracts the host from listenAddr and merges it with any additional SANs. Deduplicates entries.
func BundleClientCreds ¶
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 DeployBundle ¶
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 ¶
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
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 ¶
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 ReloadEnrollment ¶ added in v1.4.3
ReloadEnrollment waits for the running daemon to apply saved reporting configuration. It never restarts the daemon or interrupts provider sessions.
func RemotesPath ¶
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 ¶
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 ¶
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 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 ¶
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 ¶
CertRenewerFunc is the signature for mTLS-based certificate renewal.
type CertRequesterFunc ¶
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 ¶
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 ¶
Remote represents an enrolled remote bridge server.
func LoadRemotes ¶
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 ¶
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) 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.
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.