Documentation
¶
Index ¶
- Constants
- Variables
- func AddSQLitePragmas(connectString string, journalSizeLimit int64) string
- func AppRBACMarkerPresent(ctx context.Context) bool
- func CanonicalHost(u *url.URL) string
- func CheckPublicHost(ctx context.Context, what, host string) error
- func CleanAbsolutePath(name string) (string, error)
- func CleanFilename(filename string) (string, error)
- func CleanRelativeLocalPath(name string) (string, error)
- func CleanRelativePath(name string) (string, error)
- func DeleteLogin(serverUrl string)
- func DisableWriteDeadline(w http.ResponseWriter)
- func FileExists(filename string) bool
- func FindExec(name string) string
- func FuncNow(dbType DBType) string
- func GetClientIP(r *http.Request, trustedProxies []string) string
- func GetConnectString(pluginContext *types.PluginContext) (string, error)
- func GetContextApiCredential(ctx context.Context) *types.Credential
- func GetContextApiInvoker(ctx context.Context) string
- func GetContextApiScopes(ctx context.Context) ([]string, bool)
- func GetContextAppId(ctx context.Context) types.AppId
- func GetContextAppPathDomain(ctx context.Context) types.AppPathDomain
- func GetContextDiskSourceAccess(ctx context.Context) (allowed bool, set bool)
- func GetContextGroups(ctx context.Context) []string
- func GetContextRequestId(ctx context.Context) string
- func GetContextUserEmail(ctx context.Context) string
- func GetContextUserId(ctx context.Context) string
- func GetContextUserSubject(ctx context.Context) string
- func GetContextValue(ctx context.Context, key types.ContextKey) string
- func GetCustomPerms(ctx context.Context) []string
- func GetDefaultConfigs() (*types.GlobalConfig, *types.ClientConfig, *types.ServerConfig, error)
- func GetFuncMap() template.FuncMap
- func GetHostname(host string) string
- func GetRequestContext(thread *starlark.Thread) context.Context
- func GetRequestScheme(r *http.Request, trustedProxies []string) string
- func GetRequestUrl(r *http.Request, trustedProxies []string) string
- func GetSQLiteMaintenanceStatus(dbFilePath string) (types.SQLiteMetadataMetrics, bool)
- func GetThreadLocalKey(thread *starlark.Thread, key string) string
- func GuardStarlarkThread(thread *starlark.Thread)
- func HumanDuration(d time.Duration, resolution int) string
- func InsertIgnorePrefix(dbType DBType) string
- func InsertIgnoreSuffix(dbType DBType) string
- func IsAppRBACEnabled(ctx context.Context) bool
- func IsGit(url string) bool
- func IsPrivateOrLocalIP(ip net.IP) bool
- func IsRunningAsService() bool
- func IsTrustedOperation(ctx context.Context) bool
- func KillGroup(process *os.Process) error
- func LitestreamBindingPrefix(config types.LitestreamConfig, pathPrefixOverride, bindingId, env string) string
- func LitestreamEffectivePrefix(config types.LitestreamConfig, pathPrefixOverride string, subPath string) string
- func LitestreamReplicaURL(config types.LitestreamConfig, replicaPath string) (string, error)
- func LitestreamTruncatePageN(config types.LitestreamConfig) (int, bool)
- func LoadClientConfig(contents string, config *types.ClientConfig) error
- func LoadGlobalConfig(contents string, config *types.GlobalConfig) error
- func LoadProperties(filename string) (map[string]string, error)
- func LoadServerConfig(contents string, config *types.ServerConfig) error
- func MapDataType(dbType DBType, dataType string) string
- func MapServerHost(host string) string
- func MaybeRunAsService()
- func MemoryHighWater() int64
- func MemoryInUse() int64
- func NewClientConfigEmbedded() (*types.ClientConfig, error)
- func NewPlainHttpClient(skipCertCheck bool) *http.Client
- func NewPrefixedId(prefix string) (string, error)
- func NewServerConfigEmbedded() (*types.ServerConfig, error)
- func NotifyServiceFailed(exitCode uint32)
- func NotifyServiceReady()
- func NotifyServiceStopped()
- func NotifyServiceStopping()
- func PathInDir(root, relPath string) (string, error)
- func PathWithinDir(root, targetPath string) (bool, error)
- func PostgresRebind(q string) string
- func ProcessExists(pid int) bool
- func PublicOnlyDialControl(what string) func(network, address string, _ syscall.RawConn) error
- func RebindQuery(dbType DBType, q string) string
- func ResolveLoginToken(serverUrl string, skipCertCheck bool) string
- func SQLiteFilePath(connectString, invoker string) (string, error)
- func SaveLogin(login *StoredLogin) error
- func ServiceStopNotify() <-chan struct{}
- func SetMemoryHighWater(bytes int64)
- func SetProcessGroup(cmd *exec.Cmd)
- func StreamLines(reader io.ReadCloser, cleanup func()) func(yield func(any, error) bool)
- func ValidHostHeader(host string) bool
- func ValidateExecAllowlist(entries []string, envEntries []string) error
- func ValidateLitestreamConfig(name string, config types.LitestreamConfig) error
- func WithApiCredential(ctx context.Context, cred *types.Credential) context.Context
- func WithApiInvoker(ctx context.Context, invoker string) context.Context
- func WithApiScopes(ctx context.Context, scopes []string) context.Context
- func WithDiskSourceAccess(ctx context.Context, allowed bool) context.Context
- func WithTrustedOperation(ctx context.Context) context.Context
- type BackgroundTask
- type DBType
- type ExecAllowlist
- type HttpClient
- func (h *HttpClient) CloseIdleConnections()
- func (h *HttpClient) Delete(url string, params url.Values, output any) error
- func (h *HttpClient) Get(url string, params url.Values, output any) error
- func (h *HttpClient) GetRaw(ctx context.Context, apiPath string, params url.Values) (*http.Response, error)
- func (h *HttpClient) IsRemote() bool
- func (h *HttpClient) Post(url string, params url.Values, input any, output any) error
- func (h *HttpClient) PostForm(apiPath string, form url.Values) (*OAuthTokenResponse, error)
- func (h *HttpClient) PostRaw(ctx context.Context, apiPath string, params url.Values, contentType string, ...) (*http.Response, error)
- func (h *HttpClient) Put(url string, params url.Values, input any, output any) error
- func (h *HttpClient) ResponseError(status int, body []byte) error
- func (h *HttpClient) SetHeader(name, value string)
- type LitestreamDBStatus
- type LitestreamManager
- func (m *LitestreamManager) Close(ctx context.Context) error
- func (m *LitestreamManager) ConfigName() string
- func (m *LitestreamManager) PrepareDB(ctx context.Context, name, dbFilePath string) error
- func (m *LitestreamManager) Start(ctx context.Context) error
- func (m *LitestreamManager) Status(ctx context.Context) []LitestreamDBStatus
- type LitestreamReplicaDB
- type OAuthTokenResponse
- type PublicOnlyTransport
- type RunRegistry
- func (r *RunRegistry) Add(id, group string, cancel context.CancelFunc)
- func (r *RunRegistry) Begin() (context.Context, func(), error)
- func (r *RunRegistry) Cancel(id, by string) bool
- func (r *RunRegistry) CanceledBy(id string) string
- func (r *RunRegistry) CountGroup(group string) int
- func (r *RunRegistry) Has(id string) bool
- func (r *RunRegistry) Remove(id string)
- func (r *RunRegistry) Reserve(group string, limit int) (func(), bool)
- func (r *RunRegistry) Stop()
- func (r *RunRegistry) Wait()
- type SQLiteMaintenanceOwner
- type SecretManager
- func (s *SecretManager) AppEvalTemplate(appSecrets [][]string, defaultProvider, input string, strict bool) (string, error)
- func (s *SecretManager) AppEvalTemplateRecord(appSecrets [][]string, defaultProvider, input string, strict bool, ...) (string, error)
- func (s *SecretManager) BindDBStores(ctx context.Context, store SecretStore) error
- func (s *SecretManager) CreateSecret(ctx context.Context, req *types.CreateSecretRequest, createdBy string, ...) (*types.SecretCreateResponse, error)
- func (s *SecretManager) DeleteSecret(ctx context.Context, providerName, name string) error
- func (s *SecretManager) EvalTemplate(input string) (string, error)
- func (s *SecretManager) GetSecretInfo(ctx context.Context, providerName, name string, reveal bool) (*types.SecretGetResponse, error)
- func (s *SecretManager) ListSecrets(ctx context.Context, providerName, nameGlob string) ([]types.SecretInfo, error)
- func (s *SecretManager) ReferencesSecrets(input string) bool
- func (s *SecretManager) RekeySecrets(ctx context.Context, providerName string) (*types.SecretRekeyResponse, error)
- func (s *SecretManager) ServiceEvalTemplate(input string) (string, error)
- type SecretStore
- type StoredLogin
- type Transport
- type Upgrader
- func (u *Upgrader) Exit() <-chan struct{}
- func (u *Upgrader) HasParent() bool
- func (u *Upgrader) Listen(network, addr string, bind func(network, addr string) (net.Listener, error)) (net.Listener, error)
- func (u *Upgrader) ParentExited() bool
- func (u *Upgrader) Ready() error
- func (u *Upgrader) Stop()
- func (u *Upgrader) Supported() bool
- func (u *Upgrader) Upgrade() error
- func (u *Upgrader) WaitForParent(ctx context.Context) error
Constants ¶
const ( ApplicationJson = "application/json" OpenRunServiceLocation = "openrun" )
const ( // MaxTemplateItems caps the element count of the sequence functions // until, untilStep and seq MaxTemplateItems = 1_000_000 // MaxTemplateBytes caps the output of the string generating functions // repeat, indent, nindent and rand* MaxTemplateBytes = 16 << 20 )
The sprig functions which allocate in proportion to an integer argument are capped: a template commonly passes a request value to them ({{ range until .n }}, {{ repeat .n "-" }}), template rendering has no cancellation, and nothing else bounds the allocation
const (
DB_CONNECTION_CONFIG = "db_connection"
)
const DEFAULT_CONFIG = "openrun.default.toml"
const LitestreamMetadataPrefix = "metadata"
LitestreamMetadataPrefix is the replica sub-path for the server's own databases, below the config's path_prefix. App binding replicas use "bindings/<binding-id>/<env>" instead.
const LitestreamReplicaTypeFile = "file"
LitestreamReplicaTypeFile is the litestream config type for a local directory replica (tests, simple local-disk backups); the default is s3.
const LitestreamTruncatePageDisabled = -1
LitestreamTruncatePageDisabled is the TruncatePageN value passed to litestream when truncate_page_n = 0 is configured.
const MaxLineChunkBytes = 1024 * 1024
MaxLineChunkBytes bounds the partial-line buffer of a line stream; a line longer than this is force-broken so memory stays bounded
const ( // MaxSecretValueBytes is the max size of a secret value (after base64 // decoding). This is a config secrets store, not a blob store MaxSecretValueBytes = 1 << 20 )
const (
MaxStarlarkCallDepth = 10_000
)
The Starlark thread guard: a periodic check installed on the threads which run app code (handlers, actions, jobs, the app load) through the interpreter's step limit callback, every guardStepInterval instructions. It cancels the thread when
- the call depth exceeds MaxStarlarkCallDepth. The interpreter's own guard allows 100 000 frames, about 460MB of goroutine stack per request: a recursion driven by a request value must fail well below
- the Go runtime's memory in use is over the memory high water mark (see MemoryHighWater). The interpreter has no allocation accounting: this bounds app code which grows memory gradually (a loop appending to a list) before the process is killed, at the cost of the handler running when the mark is reached
Builtins and template rendering run between checks (a request cancel cannot reach inside them either), so the guard bounds interpreted code, and the caps on the builtins and the template functions bound the rest
const Scheme = "http+unix"
Scheme is the URL scheme used for HTTP over UNIX domain sockets.
Variables ¶
var ( DB_SQLITE_POSTGRES = []DBType{DB_TYPE_SQLITE, DB_TYPE_POSTGRES} DB_SQLITE = []DBType{DB_TYPE_SQLITE} DRIVER_MAP = map[DBType]string{ DB_TYPE_SQLITE: "sqlite", DB_TYPE_POSTGRES: "pgx", } )
var ErrExecSelf = errors.New("the OpenRun binary cannot be run through exec.in; use the openrun_admin plugin for management operations")
ErrExecSelf is returned when an app tries to run the OpenRun server binary
ErrInPlaceRestartUnavailable is returned by Upgrader.Upgrade when a zero downtime in-place restart cannot be performed in this environment. The wrapped message says why and what to do instead.
var ErrNoSecretAccess = errors.New("the plugin call has no secret access: no secrets are approved on the app's permission for the call and the server config allows none")
ErrNoSecretAccess is the error for a plugin call resolving a secret when the call has no secret access at all: no secrets are approved on the app's permission for the call and the server config allows none for it. The template engine returns a function panic as an error wrapping it, so callers can errors.Is it to add app specific guidance
var ErrPrivateAddress = errors.New("private or local address")
ErrPrivateAddress is wrapped by the errors refusing a fetch of a private or local address
var ErrSecretNotAllowed = errors.New("the plugin call is not allowed to access the secret")
ErrSecretNotAllowed is the error for a plugin call resolving a secret which none of its allowed secret patterns match
Functions ¶
func AddSQLitePragmas ¶ added in v0.18.5
AddSQLitePragmas appends the default _pragma query parameters to a sqlite connect string (the file path part, after the sqlite: prefix is stripped). Pragmas already present in the connect string are not overridden.
func AppRBACMarkerPresent ¶ added in v0.18.7
AppRBACMarkerPresent reports whether the per-request RBAC enforcement bool is present in the context, regardless of its value. It is set for every app request during authentication, so presence identifies an attributed app request: enforcement state is computed once per request and stays stable for its lifetime (enabling RBAC mid-request applies from the next request on)
func CanonicalHost ¶ added in v0.20.7
CanonicalHost is u's host as net/http sends it in a proxy CONNECT (its canonicalAddr): a non-ASCII host is mapped through IDNA, so a fullwidth 127.0.0.1 becomes 127.0.0.1
func CheckPublicHost ¶ added in v0.20.7
CheckPublicHost refuses a host which is, or resolves to, a private or local address. It is for a fetch whose connection is made by a proxy, where the dial check sees only the proxy's address. It is best effort: the proxy does its own lookup, so a name rebinding between the two lookups is not caught, and a name which does not resolve here (the proxy may resolve names the server cannot) is allowed. The proxy's egress policy covers those
func CleanAbsolutePath ¶ added in v0.17.0
CleanAbsolutePath returns an absolute, cleaned local filesystem path. If the path exists, symlinks are resolved.
func CleanFilename ¶ added in v0.17.0
CleanFilename returns a single filename with no directory components.
As with CleanRelativePath, backslashes are treated as path separators on every platform so that filenames are validated portably. On Windows the result is also checked against reserved device names (NUL, CON, COM1, ...).
func CleanRelativeLocalPath ¶ added in v0.17.0
CleanRelativeLocalPath returns a platform-local relative path that cannot escape its containing directory. On Windows, filepath.IsLocal additionally rejects reserved device names such as NUL, CON, COM1, etc.
For example, `sub\file.txt` is returned as `sub/file.txt` on Unix and `sub\file.txt` on Windows. Use this when the result is passed to filepath, os, or host commands.
func CleanRelativePath ¶ added in v0.17.0
CleanRelativePath returns a slash-separated relative path that cannot escape its containing directory.
For example, `sub\file.txt` is returned as `sub/file.txt`. Use this for logical paths such as fs.FS names, URL/static paths, metadata paths, and tar header names.
Backslashes in the input are treated as path separators on every platform so that configs authored on Windows or Unix are validated identically. The trade-off is that a legitimate Unix filename containing a backslash will be re-interpreted as a multi-component path; callers that need to preserve such names should not route them through this function.
func DeleteLogin ¶ added in v0.19.3
func DeleteLogin(serverUrl string)
DeleteLogin removes the stored login for the server url
func DisableWriteDeadline ¶ added in v0.20.6
func DisableWriteDeadline(w http.ResponseWriter)
DisableWriteDeadline clears the per-response write deadline that the http.Server WriteTimeout sets, for responses that legitimately stay open longer than the timeout (SSE, streamed command output, large downloads). WriteTimeout is absolute from the request header read, so without this a stream is cut mid-body once the timeout elapses even while the client is still reading. The read side is unaffected: net/http clears the read deadline once the body is consumed. Every wrapper on the writer chain must implement Unwrap for this to reach the connection; a chain that does not keeps the timeout (the error is ignored, nothing worse than today happens)
func FileExists ¶
func FindExec ¶
FindExec looks for the executable in the system PATH and returns its full path. If not found, it checks common Homebrew locations for the executable.
func GetClientIP ¶ added in v0.17.0
GetClientIP returns the caller IP, honoring forwarding headers only when the direct peer is explicitly configured as a trusted proxy.
func GetConnectString ¶
func GetConnectString(pluginContext *types.PluginContext) (string, error)
func GetContextApiCredential ¶ added in v0.19.3
func GetContextApiCredential(ctx context.Context) *types.Credential
GetContextApiCredential returns the authenticating credential, nil when the caller did not authenticate with one (UDS, console plugin)
func GetContextApiInvoker ¶ added in v0.19.3
GetContextApiInvoker returns the invoker marker, "" when not set
func GetContextApiScopes ¶ added in v0.19.3
GetContextApiScopes returns the credential scope ceiling and whether one is present. Absent means unscoped: no ceiling applies
func GetContextAppPathDomain ¶ added in v0.18.7
func GetContextAppPathDomain(ctx context.Context) types.AppPathDomain
GetContextAppPathDomain returns the path domain of the app serving the request, the zero value when not present
func GetContextDiskSourceAccess ¶ added in v0.20.4
GetContextDiskSourceAccess returns the disk source decision and whether one is set
func GetContextGroups ¶ added in v0.15.0
func GetContextRequestId ¶
func GetContextUserEmail ¶ added in v0.17.3
func GetContextUserId ¶
func GetContextUserSubject ¶ added in v0.17.3
func GetContextValue ¶
func GetContextValue(ctx context.Context, key types.ContextKey) string
func GetCustomPerms ¶ added in v0.16.26
func GetDefaultConfigs ¶
func GetDefaultConfigs() (*types.GlobalConfig, *types.ClientConfig, *types.ServerConfig, error)
func GetFuncMap ¶
GetFuncMap returns a template.FuncMap that includes all the sprig functions except for env and expandenv.
func GetHostname ¶ added in v0.17.0
GetHostname returns the hostname portion of an HTTP host header, handling hostnames, IPv4 addresses, and bracketed or bare IPv6 literals.
func GetRequestContext ¶ added in v0.15.14
GetRequestContext returns the request context stored on the Starlark thread. A missing thread context yields context.Background(), which carries no enforcement or trust marker: RBAC fails closed for it when enabled, so a propagation bug denies instead of silently running as a trusted internal call
func GetRequestScheme ¶ added in v0.17.1
GetRequestScheme returns "https" if the request was received over TLS locally, or if the direct peer is listed in trustedProxies and set X-Forwarded-Proto: https. Otherwise it returns "http". Only the first value of X-Forwarded-Proto is honored and only when the direct peer is a trusted proxy.
func GetRequestUrl ¶ added in v0.15.3
func GetSQLiteMaintenanceStatus ¶ added in v0.18.19
func GetSQLiteMaintenanceStatus(dbFilePath string) (types.SQLiteMetadataMetrics, bool)
GetSQLiteMaintenanceStatus returns the latest maintenance counters plus current sqlite file sizes. false means this process has not opened the file.
func GuardStarlarkThread ¶ added in v0.20.6
GuardStarlarkThread installs the periodic check on a thread about to run app code. It must be called before the thread runs
func HumanDuration ¶ added in v0.15.10
HumanDuration returns a compact human readable duration string: "1d 2h ago" style short units. resolution caps how many units are included, most significant first: 1 gives "105d ago", 2 "105d 3h ago". 0 keeps every non-zero unit after rounding. Durations always collapse into the largest unit, so hours never accumulate past a day ("1540 hours" renders as days)
func InsertIgnorePrefix ¶
func InsertIgnoreSuffix ¶
func IsAppRBACEnabled ¶ added in v0.16.26
func IsPrivateOrLocalIP ¶ added in v0.20.7
IsPrivateOrLocalIP is the SSRF guard for outbound fetches of untrusted urls: they must never be steered into loopback, private, link-local (incl. cloud metadata 169.254.169.254), carrier-grade NAT, unspecified or multicast addresses
func IsRunningAsService ¶ added in v0.18.15
func IsRunningAsService() bool
IsRunningAsService reports whether the process was started by the OS service control manager. Always false on platforms without OS service integration. Only valid after MaybeRunAsService has been called.
func IsTrustedOperation ¶ added in v0.18.7
IsTrustedOperation reports whether the context is a trusted administrative path, see WithTrustedOperation
func LitestreamBindingPrefix ¶ added in v0.18.15
func LitestreamBindingPrefix(config types.LitestreamConfig, pathPrefixOverride, bindingId, env string) string
LitestreamBindingPrefix is the replica key prefix for one sqlite binding: keyed by the stable binding id (not the path, which can be deleted and recreated) and the environment (prod/staged). Data follows the binding: re-attaching a base binding to a new app restores into the new app's fresh volume.
func LitestreamEffectivePrefix ¶ added in v0.18.15
func LitestreamEffectivePrefix(config types.LitestreamConfig, pathPrefixOverride string, subPath string) string
LitestreamEffectivePrefix returns the replica key prefix for a sub path, applying the config's path_prefix (or the per-service override when set).
func LitestreamReplicaURL ¶ added in v0.18.15
func LitestreamReplicaURL(config types.LitestreamConfig, replicaPath string) (string, error)
LitestreamReplicaURL returns the replica URL for one database, in the form the litestream CLI accepts for restore (s3://bucket/path?endpoint=...). Credentials are never part of the URL; they are passed via the LITESTREAM_ACCESS_KEY_ID / LITESTREAM_SECRET_ACCESS_KEY env variables.
func LitestreamTruncatePageN ¶ added in v0.20.2
func LitestreamTruncatePageN(config types.LitestreamConfig) (int, bool)
LitestreamTruncatePageN returns the TruncatePageN value to hand to litestream for config (the embedded DB or the sidecar's truncate-page-n), and false when truncate_page_n is unset (litestream's default applies).
OpenRun documents truncate_page_n = 0 as disabling the blocking TRUNCATE checkpoint. Litestream 0.5.15 treated 0 that way, but 0.5.16+ maps 0 to its default threshold (~500MB) and only a negative value disables the checkpoint; negative values disable it in both versions. So an explicit 0 is translated to LitestreamTruncatePageDisabled, keeping the documented meaning across the library upgrade and across sidecar image versions.
func LoadClientConfig ¶
func LoadClientConfig(contents string, config *types.ClientConfig) error
LoadClientConfig load a ClientConfig from the given contents
func LoadGlobalConfig ¶
func LoadGlobalConfig(contents string, config *types.GlobalConfig) error
LoadGlobalConfig load a GlobalConfig from the given contents
func LoadServerConfig ¶
func LoadServerConfig(contents string, config *types.ServerConfig) error
LoadServerConfig loads a ServerConfig from the given contents
func MapDataType ¶
func MapServerHost ¶
func MaybeRunAsService ¶ added in v0.18.5
func MaybeRunAsService()
MaybeRunAsService is a no-op on platforms without OS service integration
func MemoryHighWater ¶ added in v0.20.6
func MemoryHighWater() int64
MemoryHighWater returns the memory in use (as the Go memory limit counts it) over which running Starlark threads are canceled: the configured system.memory_high_water_bytes, else 90% of the Go memory limit (GOMEMLIMIT or debug.SetMemoryLimit) when one is set, else 0 (no check)
func MemoryInUse ¶ added in v0.20.6
func MemoryInUse() int64
MemoryInUse returns the Go runtime's memory in use, as the memory limit counts it (all memory mapped by the runtime, less what is released to the OS), read at most every memoryReadInterval
func NewClientConfigEmbedded ¶
func NewClientConfigEmbedded() (*types.ClientConfig, error)
NewClientConfigEmbedded reads the embedded toml file and creates a ClientConfig
func NewPlainHttpClient ¶ added in v0.19.3
NewPlainHttpClient returns a plain *http.Client for direct requests (well-known metadata fetches), honoring skip_cert_check
func NewPrefixedId ¶ added in v0.20.0
NewPrefixedId returns a random, time ordered id with the prefix (run_ for job runs; async action run ids have no prefix)
func NewServerConfigEmbedded ¶
func NewServerConfigEmbedded() (*types.ServerConfig, error)
NewServerConfigEmbedded reads the embedded toml file and creates a ServerConfig
func NotifyServiceFailed ¶ added in v0.18.5
func NotifyServiceFailed(exitCode uint32)
NotifyServiceFailed reports a failed startup or shutdown with a service specific exit code. Call before exiting the process on a fatal error so the control manager does not log an unexpected termination.
func NotifyServiceReady ¶ added in v0.17.6
func NotifyServiceReady()
NotifyServiceReady reports the Running state to the service control manager. No-op when not running as a service.
func NotifyServiceStopped ¶ added in v0.17.6
func NotifyServiceStopped()
NotifyServiceStopped reports a clean shutdown to the service control manager and waits for the report to be delivered before returning
func NotifyServiceStopping ¶ added in v0.17.6
func NotifyServiceStopping()
NotifyServiceStopping reports that a graceful shutdown has started
func PathInDir ¶ added in v0.17.0
PathInDir joins relPath under root after validating that relPath is local.
Because CleanRelativeLocalPath enforces filepath.IsLocal, the resulting joined path is guaranteed to be lexically inside root. This is a lexical guarantee only: it does not resolve symlinks. For symlink-safe access use os.Root from the standard library.
func PathWithinDir ¶ added in v0.17.0
PathWithinDir reports whether targetPath is lexically inside root.
This is a purely lexical check: symlinks under root that point outside root are not detected. For symlink-safe access prefer os.Root from the standard library.
func PostgresRebind ¶
func ProcessExists ¶ added in v0.18.18
ProcessExists reports whether a process with the given pid is running. EPERM means the process exists but is owned by another user
func PublicOnlyDialControl ¶ added in v0.20.7
PublicOnlyDialControl is a net.Dialer Control function refusing a connection to a private or local address. It runs after DNS resolution, on the address actually dialed, so a public name resolving (or rebinding) to an internal address is refused too. what names the fetch in the error
func RebindQuery ¶
func ResolveLoginToken ¶ added in v0.19.3
ResolveLoginToken returns a valid access token for the server from the stored login, transparently refreshing (with rotation) when the access token is stale. Returns "" when no stored login exists or refresh fails. Refresh runs under a cross-process lock: refresh tokens are single-use (rotation), so two CLI processes refreshing concurrently would trip the server's reuse detection and revoke the whole login
func SQLiteFilePath ¶ added in v0.18.19
SQLiteFilePath resolves the canonical file identity used by SQLite maintenance. Callers should resolve it while opening the database; relative paths must not be interpreted again after a later process-wide chdir.
func SaveLogin ¶ added in v0.19.3
func SaveLogin(login *StoredLogin) error
SaveLogin persists the login for its server url
func ServiceStopNotify ¶ added in v0.17.6
func ServiceStopNotify() <-chan struct{}
ServiceStopNotify returns a channel that is closed when the OS requests a service stop or shutdown. Returns nil when not running as a service.
func SetMemoryHighWater ¶ added in v0.20.6
func SetMemoryHighWater(bytes int64)
SetMemoryHighWater sets the memory high water mark from the config, see MemoryHighWater
func SetProcessGroup ¶
SetProcessGroup sets the process group flag for the command
func StreamLines ¶ added in v0.20.0
func StreamLines(reader io.ReadCloser, cleanup func()) func(yield func(any, error) bool)
StreamLines converts a reader of line-oriented output (a process pipe, a container log stream) into a range func yielding chunks of complete lines as plain Go strings (not starlark values, so the stream writer sends them verbatim without quoting). Each yielded value holds one or more complete lines without the trailing newline (the consumer adds one per value). One yield per read keeps the per-line overhead minimal for large outputs while still delivering each line promptly when the producer is slow. Reads use a 64KB buffer; a newline-less run is force-broken at MaxLineChunkBytes. The reader is closed and cleanup runs when the stream ends or the consumer stops iterating. A read failure (other than EOF, a canceled context or a closed pipe, which are normal endings) is yielded as the terminal error after the buffered output, so a consumer can tell a cut stream from a complete one. Shared by the container log stream and the exec plugin
func ValidHostHeader ¶ added in v0.17.5
ValidHostHeader reports whether host is well-formed enough to be used as an HTTP Host value. Empty is rejected — OpenRun's TCP router and app proxying always require a concrete authority.
func ValidateExecAllowlist ¶ added in v0.20.4
ValidateExecAllowlist reports whether the command and env entries parse, for config validation at startup and on dynamic config updates
func ValidateLitestreamConfig ¶ added in v0.18.15
func ValidateLitestreamConfig(name string, config types.LitestreamConfig) error
ValidateLitestreamConfig checks one named [litestream.<name>] entry. The credential values are expected to be already secret-resolved.
func WithApiCredential ¶ added in v0.19.3
WithApiCredential attaches the bearer credential the request authenticated with. CreateApiKey enforces attenuation against it: a credential can only mint credentials at most as powerful (scopes, resources, expiry) as itself
func WithApiInvoker ¶ added in v0.19.3
WithApiInvoker marks which front end dispatched this management API call: "plugin", "uds", "tcp" or "mcp"
func WithApiScopes ¶ added in v0.19.3
WithApiScopes attaches a bearer credential's scope ceiling (permission globs) to the request context. Only set for scoped credentials; RBAC enforcement applies the ceiling before evaluating grants
func WithDiskSourceAccess ¶ added in v0.20.4
WithDiskSourceAccess records whether the caller may name paths on the server's disk (app sources, apply and sync files). true is set for calls over the unix domain socket and for server-owned flows over directories the server manages; false marks a run on behalf of a remote creator (a sync entry created over the remote API), overriding the trusted marker a background context carries. Unset falls back to the trusted marker, see Server.diskSourceAllowed
func WithTrustedOperation ¶ added in v0.18.7
WithTrustedOperation marks the context as a trusted administrative path. Set ONLY where the caller's authority is established by other means: the UDS management API, token authenticated webhooks, and internal background operations (newBackgroundOperationContext). Admin-over-TCP requests are attributed and RBAC checked instead of trusted. RBAC enforcement fails closed for contexts with neither this nor an enforcement marker, so an unmarked context (a propagation bug, e.g. a missing Starlark thread context) is denied instead of running as admin
Types ¶
type BackgroundTask ¶ added in v0.19.4
type BackgroundTask struct {
// contains filtered or unexported fields
}
BackgroundTask owns one cancellable goroutine. Stop cancels its work and waits for cleanup to finish; it is safe to call more than once.
func StartBackgroundTask ¶ added in v0.19.4
func StartBackgroundTask(parent context.Context, run func(context.Context)) *BackgroundTask
func StartPeriodicTask ¶ added in v0.19.4
func StartPeriodicTask(parent context.Context, interval time.Duration, immediate bool, pass func(context.Context)) *BackgroundTask
StartPeriodicTask serializes passes and checks cancellation before each one.
func (*BackgroundTask) Stop ¶ added in v0.19.4
func (t *BackgroundTask) Stop()
type DBType ¶
type DBType string
func CheckConnectString ¶
func InitDBConnection ¶
func InitDBConnection(logger *types.Logger, connectString string, invoker string, supportedDBs []DBType, sqliteCfg *types.MetadataConfig, owner *SQLiteMaintenanceOwner) (*sql.DB, DBType, error)
InitDBConnection opens a database connection pool. sqliteCfg carries the sqlite self-maintenance settings from the [metadata] config section; nil uses the built-in defaults (app data stores, tests). It is ignored for postgres. The caller must close its pools and owner when the component stops.
type ExecAllowlist ¶ added in v0.20.4
type ExecAllowlist struct {
// contains filtered or unexported fields
}
ExecAllowlist decides which host executables the exec plugin may run, from the security.allowed_exec_commands server config, and which environment variables an app may hand them, from security.allowed_exec_env. The requested command is resolved to the real file (PATH lookup, then symlinks) and every decision is made on that file, never on the string the app passed, so a renamed symlink or a relative path cannot stand in for a different program.
Entry forms:
- "*" allows every executable
- a bare name ("du") is looked up on the server's PATH
- an absolute path ("/usr/local/bin/ffmpeg")
- a glob ("/bin/*", "/opt/tools/**"): doublestar syntax, where * does not cross a path separator and ** does. The literal directory prefix is resolved through symlinks, so "/bin/*" also covers /usr/bin on merged-usr Linux where /bin is a symlink
- a "!" prefix makes an exclusion ("!/bin/*sh"), applied after the allow entries, so a broad glob can carve interpreters back out
An exact allow entry matches when the requested command is the same file (os.SameFile) and has the same base name as the entry. The file check stops a symlink or relative path from standing in for another program; the name check stops one program from standing in for another when the two are one file, as every command of a multi-call binary is (busybox on Alpine, uutils coreutils on recent Ubuntu): listing "ls" there must not admit "sh". An exact exclusion is broader, matching by file or by name. Globs match the real path. Environment variables in entries are expanded. The OpenRun server binary itself is always refused, whatever the list says.
The environment the app passes is checked against the allowed_exec_env names separately (CheckEnv): the loader and most programs take variables such as LD_PRELOAD, BASH_FUNC_* or GIT_SSH_COMMAND as instructions to run other code, so an allowed command is only as safe as its environment.
func NewExecAllowlist ¶ added in v0.20.4
func NewExecAllowlist(entries []string, envEntries []string) (*ExecAllowlist, error)
NewExecAllowlist parses and validates the security.allowed_exec_commands entries and the security.allowed_exec_env variable names. An empty list allows nothing: no command, or no environment variable
func (*ExecAllowlist) CheckEnv ¶ added in v0.20.4
func (l *ExecAllowlist) CheckEnv(env []string) error
CheckEnv reports whether every variable in the environment an app passes to a host command is permitted by security.allowed_exec_env. Entries are KEY=VALUE; only the name is checked. An exclusion wins over an allow entry. Names are compared case-insensitively on Windows, where the child sees "Path" as PATH, so an exclusion cannot be spelled around
func (*ExecAllowlist) Resolve ¶ added in v0.20.4
func (l *ExecAllowlist) Resolve(command, cwd string) (string, error)
Resolve checks that the command may run and returns the path to execute. A bare name is looked up on the server's PATH; a relative path is taken relative to cwd (the server's working directory when cwd is empty). The returned path is the symlink-resolved file the decision was made on, so a link retargeted between the check and the exec cannot swap in another program; the caller keeps the requested name as argv[0]
type HttpClient ¶
type HttpClient struct {
// contains filtered or unexported fields
}
func NewHttpClient ¶
func NewHttpClient(serverUri, apiKey string, skipCertCheck bool) *HttpClient
NewHttpClient creates a new HttpClient instance. apiKey is the bearer credential for remote (TCP) servers; over the unix domain socket no credential is needed (filesystem permissions authenticate the caller)
func (*HttpClient) CloseIdleConnections ¶ added in v0.19.4
func (h *HttpClient) CloseIdleConnections()
CloseIdleConnections releases pooled connections when the client is no longer needed.
func (*HttpClient) GetRaw ¶ added in v0.20.0
func (h *HttpClient) GetRaw(ctx context.Context, apiPath string, params url.Values) (*http.Response, error)
GetRaw sends a GET and returns the raw response, see PostRaw (a file download)
func (*HttpClient) IsRemote ¶ added in v0.20.1
func (h *HttpClient) IsRemote() bool
IsRemote reports whether the client talks to a TCP server (http/https) rather than the trusted unix domain socket
func (*HttpClient) PostForm ¶ added in v0.19.3
func (h *HttpClient) PostForm(apiPath string, form url.Values) (*OAuthTokenResponse, error)
PostForm posts a form-encoded body to the client's base url plus path and decodes the OAuth token response
func (*HttpClient) PostRaw ¶ added in v0.20.0
func (h *HttpClient) PostRaw(ctx context.Context, apiPath string, params url.Values, contentType string, body io.Reader) (*http.Response, error)
PostRaw sends a POST with the given body and returns the raw response, for APIs whose response is not a single JSON document (an action result can be a stream, with the exit status in a trailer). No overall timeout applies: the response is read for as long as the server keeps producing it, cancel through ctx. The caller closes the response body
func (*HttpClient) ResponseError ¶ added in v0.20.1
func (h *HttpClient) ResponseError(status int, body []byte) error
ResponseError turns a non-success response of the management API into the error the CLI reports. All response error handling goes through here so every command gets the same message shape: the server's structured error when the body is one (RequestError, or an {"error": ...} document), the body text otherwise, with a hint added for the statuses where the client knows what to do about it (401: how to provide a credential)
func (*HttpClient) SetHeader ¶ added in v0.18.7
func (h *HttpClient) SetHeader(name, value string)
SetHeader adds a header sent with every request made by this client
type LitestreamDBStatus ¶ added in v0.18.15
type LitestreamDBStatus struct {
Name string `json:"name"` // metadata, audit
Path string `json:"path"`
LocalTXID uint64 `json:"local_txid"`
RemoteTXID uint64 `json:"remote_txid"`
InSync bool `json:"in_sync"`
LastSyncAt time.Time `json:"last_sync_at"`
Error string `json:"error,omitempty"`
}
LitestreamDBStatus is the replication state of one embedded-litestream database, reported by the replication status API.
type LitestreamManager ¶ added in v0.18.15
type LitestreamManager struct {
// contains filtered or unexported fields
}
LitestreamManager replicates the server's own sqlite databases (metadata and audit; the file cache is a rebuildable cache and is excluded) using litestream embedded as a library. Usage: NewLitestreamManager, PrepareDB for each database before its pool is opened (restores a missing file from the replica), Start once all databases are open, Close on server shutdown.
func NewLitestreamManager ¶ added in v0.18.15
func NewLitestreamManager(logger *types.Logger, logLevel string, configName string, config types.LitestreamConfig) (*LitestreamManager, error)
NewLitestreamManager builds the manager. logLevel is the level for litestream's own logs (logging.litestream_log_level, WARN by default); they are written to the openrun log sinks through the logger's slog bridge.
func (*LitestreamManager) Close ¶ added in v0.18.15
func (m *LitestreamManager) Close(ctx context.Context) error
Close performs a final sync and stops replication.
func (*LitestreamManager) ConfigName ¶ added in v0.18.15
func (m *LitestreamManager) ConfigName() string
ConfigName returns the [litestream.<name>] config name this manager uses.
func (*LitestreamManager) PrepareDB ¶ added in v0.18.15
func (m *LitestreamManager) PrepareDB(ctx context.Context, name, dbFilePath string) error
PrepareDB registers one database for replication and restores it from the replica if the local file is missing (disaster recovery: a wiped metadata directory is repopulated from the replica on startup). Must be called before the database pool is opened and before Start.
func (*LitestreamManager) Start ¶ added in v0.18.15
func (m *LitestreamManager) Start(ctx context.Context) error
Start begins replication for all prepared databases. Called after the database pools are open (litestream opens its own read connection).
func (*LitestreamManager) Status ¶ added in v0.18.15
func (m *LitestreamManager) Status(ctx context.Context) []LitestreamDBStatus
Status reports the replication state of each managed database.
type LitestreamReplicaDB ¶ added in v0.18.15
type LitestreamReplicaDB struct {
SubPath string `json:"sub_path"`
MaxTXID uint64 `json:"max_txid"`
LastUpdated time.Time `json:"last_updated"`
Size int64 `json:"size"`
}
LitestreamReplicaDB describes one database found in a litestream replica location: its path relative to the listed prefix (e.g. "data.db" or "tenants/acme.db") plus activity derived from the LTX object listing.
func ListLitestreamReplicaDBs ¶ added in v0.18.15
func ListLitestreamReplicaDBs(ctx context.Context, config types.LitestreamConfig, replicaPrefix string) ([]LitestreamReplicaDB, error)
ListLitestreamReplicaDBs lists the databases replicated under replicaPrefix (a full key prefix inside the bucket / file root). A database is recognized by its "<subpath>/ltx/<level>/<min>-<max>.ltx" objects; the returned info aggregates the latest activity per database.
type OAuthTokenResponse ¶ added in v0.19.3
type OAuthTokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
Scope string `json:"scope"`
Principal string `json:"principal"`
}
OAuthTokenResponse is the token endpoint response the CLI consumes
type PublicOnlyTransport ¶ added in v0.20.7
type PublicOnlyTransport struct {
// contains filtered or unexported fields
}
PublicOnlyTransport routes each request (each redirect hop is a separate request) to one of two transports, so that whether a connection is checked is fixed by the transport making it, not by state shared between requests. direct never uses a proxy and dials public addresses only. proxied dials only the proxy, which may be on a private address: its Proxy function fails a request the proxy does not apply to instead of letting it dial direct, and the target host is checked before the request is handed to it
func NewPublicOnlyTransport ¶ added in v0.20.7
func NewPublicOnlyTransport(what string, proxy func(*http.Request) (*url.URL, error), newTransport func(proxy func(*http.Request) (*url.URL, error), control func(network, address string, c syscall.RawConn) error) *http.Transport) *PublicOnlyTransport
NewPublicOnlyTransport returns a transport refusing private or local targets. what names the fetch in errors. proxy is the proxy policy (http.ProxyFromEnvironment, or nil for direct connections only). newTransport builds a transport with the caller's timeouts from the proxy function and dial control it must use; it is called once per inner transport. CloseIdleConnections releases both
func (*PublicOnlyTransport) CloseIdleConnections ¶ added in v0.20.7
func (t *PublicOnlyTransport) CloseIdleConnections()
CloseIdleConnections closes the idle connections of both inner transports
type RunRegistry ¶ added in v0.20.0
type RunRegistry struct {
// contains filtered or unexported fields
}
RunRegistry tracks the background runs (job runs, async action runs) executing on this node, by run id, so a cancel request can stop them and the server shutdown can refuse new runs and wait for the active ones. Runs are grouped (by app id for action runs) so admission limits can count the active runs of a group
func (*RunRegistry) Add ¶ added in v0.20.0
func (r *RunRegistry) Add(id, group string, cancel context.CancelFunc)
Add registers an executing run with its cancel function
func (*RunRegistry) Begin ¶ added in v0.20.0
func (r *RunRegistry) Begin() (context.Context, func(), error)
Begin registers work before it can touch the database, so shutdown can reject new runs and wait for every claimed run to finish cleanup. The returned context is canceled by Stop; done must be called when the work ends
func (*RunRegistry) Cancel ¶ added in v0.20.0
func (r *RunRegistry) Cancel(id, by string) bool
Cancel cancels the run when it is executing here, reporting whether it was; by names who asked (recorded with the run)
func (*RunRegistry) CanceledBy ¶ added in v0.20.0
func (r *RunRegistry) CanceledBy(id string) string
CanceledBy returns who canceled the run: the user who asked, "server shutdown" when the registry was stopped, empty otherwise
func (*RunRegistry) CountGroup ¶ added in v0.20.0
func (r *RunRegistry) CountGroup(group string) int
CountGroup returns the number of active and reserved runs of the group
func (*RunRegistry) Has ¶ added in v0.20.0
func (r *RunRegistry) Has(id string) bool
Has reports whether the run is executing on this node
func (*RunRegistry) Remove ¶ added in v0.20.0
func (r *RunRegistry) Remove(id string)
Remove drops a finished run
func (*RunRegistry) Reserve ¶ added in v0.20.0
func (r *RunRegistry) Reserve(group string, limit int) (func(), bool)
Reserve admits a run of the group when fewer than limit runs of it are active or reserved, atomically with the check, so concurrent submissions cannot all pass the limit. The reservation is released by the returned function: after Add registered the run (it counts as active then), or when the submission fails
func (*RunRegistry) Stop ¶ added in v0.20.0
func (r *RunRegistry) Stop()
Stop refuses new runs and cancels the active ones
func (*RunRegistry) Wait ¶ added in v0.20.0
func (r *RunRegistry) Wait()
Wait blocks until every begun run has called done
type SQLiteMaintenanceOwner ¶ added in v0.19.4
type SQLiteMaintenanceOwner struct {
// contains filtered or unexported fields
}
SQLiteMaintenanceOwner holds a reference to each database file used by one component. Closing it rejects late opens and releases only its references. The last owner cancels and joins the file's worker and closes its pool. The zero value is ready to use.
func (*SQLiteMaintenanceOwner) Close ¶ added in v0.19.4
func (o *SQLiteMaintenanceOwner) Close() error
type SecretManager ¶
type SecretManager struct {
// contains filtered or unexported fields
}
SecretManager provides access to the secrets for the system
func NewSecretManager ¶
func NewSecretManager(ctx context.Context, secretConfig map[string]types.SecretConfig, defaultProvider string, serverConfig *types.ServerConfig) (*SecretManager, error)
func (*SecretManager) AppEvalTemplate ¶
func (s *SecretManager) AppEvalTemplate(appSecrets [][]string, defaultProvider, input string, strict bool) (string, error)
AppEvalTemplate evaluates a template on behalf of an app, with the secret/secret_from functions limited to the secrets the app (plugin call) is allowed. In strict mode (templates the app explicitly asked to evaluate: ace.eval values) the input must parse and is always executed. In lenient mode (container env and build args, where values are arbitrary operator strings) only templates referencing secrets are executed and anything else passes through literally
func (*SecretManager) AppEvalTemplateRecord ¶ added in v0.20.5
func (s *SecretManager) AppEvalTemplateRecord(appSecrets [][]string, defaultProvider, input string, strict bool, record func(secretKeys []string)) (string, error)
AppEvalTemplateRecord is AppEvalTemplate reporting each secret the template resolves, as the key list of the secret/secret_from call, to record (nil for no reporting). The caller learns which secrets the evaluated value holds, e.g. to check a derived plugin call against them
func (*SecretManager) BindDBStores ¶ added in v0.18.6
func (s *SecretManager) BindDBStores(ctx context.Context, store SecretStore) error
BindDBStores connects the db secret providers to the metadata database. Called after the metadata database is initialized (the db provider cannot be used for server config values because of this ordering). A no-op when no db provider is configured
func (*SecretManager) CreateSecret ¶ added in v0.18.6
func (s *SecretManager) CreateSecret(ctx context.Context, req *types.CreateSecretRequest, createdBy string, update bool) (*types.SecretCreateResponse, error)
CreateSecret stores a secret value. If req.Name is set, that name is used (update allows overwriting an existing value). Otherwise a unique name is generated from req.Prefix. Returns the name and the {{secret}} template reference to use
func (*SecretManager) DeleteSecret ¶ added in v0.18.6
func (s *SecretManager) DeleteSecret(ctx context.Context, providerName, name string) error
DeleteSecret deletes a stored secret
func (*SecretManager) EvalTemplate ¶
func (s *SecretManager) EvalTemplate(input string) (string, error)
EvalTemplate evaluates the input string and replaces any secret placeholders with the actual secret value
func (*SecretManager) GetSecretInfo ¶ added in v0.18.6
func (s *SecretManager) GetSecretInfo(ctx context.Context, providerName, name string, reveal bool) (*types.SecretGetResponse, error)
GetSecretInfo returns info about one stored secret. With reveal, the value is included: binary values are base64 encoded with Encoding set to "base64"
func (*SecretManager) ListSecrets ¶ added in v0.18.6
func (s *SecretManager) ListSecrets(ctx context.Context, providerName, nameGlob string) ([]types.SecretInfo, error)
ListSecrets returns info about stored secrets (never values), optionally filtered by a glob pattern on the name
func (*SecretManager) ReferencesSecrets ¶ added in v0.18.18
func (s *SecretManager) ReferencesSecrets(input string) bool
ReferencesSecrets reports whether the value is a template that calls the secret or secret_from function. Values that do not parse as a template are not references
func (*SecretManager) RekeySecrets ¶ added in v0.18.6
func (s *SecretManager) RekeySecrets(ctx context.Context, providerName string) (*types.SecretRekeyResponse, error)
RekeySecrets re-encrypts stored secrets with the active master key. Used after adding a new key to the key material to phase out old keys
func (*SecretManager) ServiceEvalTemplate ¶ added in v0.18.18
func (s *SecretManager) ServiceEvalTemplate(input string) (string, error)
ServiceEvalTemplate resolves {{secret}}/{{secret_from}} references in a service config value. Unlike EvalTemplate, values that do not parse as a template or that parse without referencing a secret pass through literally: service config values are arbitrary strings (connection urls, passwords, PEM keys) that may contain "{{" without being templates
type SecretStore ¶ added in v0.18.6
type SecretStore interface {
GetSecretEntry(ctx context.Context, name string) (*types.SecretEntry, error)
InsertSecretEntry(ctx context.Context, entry *types.SecretEntry) error
UpdateSecretEntry(ctx context.Context, entry *types.SecretEntry) error
// UpdateSecretEntryIfUnchanged updates the row only if its current key_id
// and nonce still match prevKeyId/prevNonce, returning whether a row was
// updated. Used by rekey so a concurrent value update is never overwritten
// with re-encrypted stale plaintext
UpdateSecretEntryIfUnchanged(ctx context.Context, entry *types.SecretEntry, prevKeyId string, prevNonce []byte) (bool, error)
DeleteSecretEntry(ctx context.Context, name string) error
// ListSecretEntries returns all rows sorted by name. With includeValues
// false, the Value and Nonce fields are not fetched (listing does not need
// the ciphertext)
ListSecretEntries(ctx context.Context, includeValues bool) ([]*types.SecretEntry, error)
}
SecretStore is the persistence interface for the db secret provider, implemented by the metadata database layer. Values are encrypted by the provider before being stored
type StoredLogin ¶ added in v0.19.3
type StoredLogin struct {
ServerUrl string `json:"server_url"`
Principal string `json:"principal"`
AccessToken string `json:"access_token"`
AccessExpiry time.Time `json:"access_expiry"`
RefreshToken string `json:"refresh_token"`
TokenEndpoint string `json:"token_endpoint"`
}
StoredLogin is the persisted result of an openrun login flow for one server
func LoadLogin ¶ added in v0.19.3
func LoadLogin(serverUrl string) *StoredLogin
LoadLogin returns the stored login for the server url, nil when absent
func RefreshLogin ¶ added in v0.19.3
func RefreshLogin(login *StoredLogin, skipCertCheck bool) (*StoredLogin, error)
RefreshLogin exchanges the refresh token for a new token pair and persists the rotation
type Transport ¶
type Transport struct {
// DialTimeout is deprecated. Use context instead.
DialTimeout time.Duration
// RequestTimeout is deprecated and has no effect.
RequestTimeout time.Duration
// ResponseHeaderTimeout is deprecated. Use context instead.
ResponseHeaderTimeout time.Duration
// contains filtered or unexported fields
}
Transport is a http.RoundTripper that connects to Unix domain sockets.
func (*Transport) CloseIdleConnections ¶ added in v0.19.4
func (t *Transport) CloseIdleConnections()
CloseIdleConnections releases idle Unix socket connections and their transport goroutines.
func (*Transport) RegisterLocation ¶
RegisterLocation registers an URL location and maps it to the given file system path.
Calling RegisterLocation twice for the same location is a programmer error, and causes a panic.
type Upgrader ¶ added in v0.18.15
type Upgrader struct {
// contains filtered or unexported fields
}
Upgrader wraps tableflip to provide zero downtime in-place restarts: the running process re-execs its binary, passes the listener fds to the child and drains once the child reports ready. tableflip allows a single Upgrader per process, so an Upgrader is only created for the `server start` command path (config.EnableInPlaceRestart); embedded and test servers fall back to plain listeners. The fallback is also used where a handoff cannot work: Windows (fds cannot be turned back into listeners) and containers (the parent exiting after handoff terminates the container, killing the child)
func NewUpgrader ¶ added in v0.18.15
func NewUpgrader(logger *types.Logger, config *types.ServerConfig) *Upgrader
NewUpgrader creates the process Upgrader. It never fails: when in-place restarts are not possible the Upgrader runs in fallback mode where Listen binds plain listeners and Upgrade returns ErrInPlaceRestartUnavailable
func (*Upgrader) Exit ¶ added in v0.18.15
func (u *Upgrader) Exit() <-chan struct{}
Exit returns a channel that is closed when an upgrade has succeeded and the process must drain and exit. Returns nil in fallback mode (a nil channel never fires in a select)
func (*Upgrader) HasParent ¶ added in v0.18.15
HasParent reports whether this process was started as the child of an in-place restart handoff, meaning the previous process is still running (draining) until it exits
func (*Upgrader) Listen ¶ added in v0.18.15
func (u *Upgrader) Listen(network, addr string, bind func(network, addr string) (net.Listener, error)) (net.Listener, error)
Listen returns a listener for the address, inheriting it from the previous process during an in-place restart when possible. bind is used to create a fresh listener when there is nothing to inherit; it also runs in fallback mode, so address-specific recovery logic (like the UDS stale socket probe) applies on every path
func (*Upgrader) ParentExited ¶ added in v0.18.15
ParentExited reports whether the previous process of an in-place restart handoff has exited. True when there was no handoff. Once true, stays true
func (*Upgrader) Ready ¶ added in v0.18.15
Ready signals the previous process (if any) that this process has bound its listeners and can serve traffic, allowing the old process to drain. It also writes the pid file. Must be called once startup is complete
func (*Upgrader) Stop ¶ added in v0.18.15
func (u *Upgrader) Stop()
Stop releases upgrade resources on shutdown. In-flight upgrades are aborted
func (*Upgrader) Supported ¶ added in v0.18.15
Supported reports whether an in-place restart can be attempted
Source Files
¶
- authstore.go
- background.go
- config.go
- exec_allow.go
- http.go
- linestream.go
- litestream.go
- litestream_replica.go
- netguard.go
- path.go
- process_unix.go
- properties.go
- run_registry.go
- secrets.go
- secrets_db.go
- service.go
- service_other.go
- source.go
- sprig.go
- sqlite.go
- thread_guard.go
- thread_local.go
- time.go
- unix_sockets.go
- upgrader.go