server

package
v0.20.0 Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2026 License: Apache-2.0 Imports: 51 Imported by: 1

Documentation

Overview

Package server exposes mounted OpenVaultDB databases over the minimal HTTP API documented in docs/api.md.

Index

Constants

View Source
const BoundedImmutable = "bounded-immutable/1"

BoundedImmutable is the closed profile for immutable, keyed SQLite lookup pages.

View Source
const ProviderExecutionIDHeader = "OVDB-Execution-ID"

ProviderExecutionIDHeader correlates a query with its independently admitted execution. It grants no source, resource, rights or executor authority.

Variables

View Source
var ErrDatabaseMounted = errors.New("database already mounted")

ErrDatabaseMounted is returned by Mount when a database with the same id is already mounted.

View Source
var ErrDatabaseNotMounted = errors.New("database not mounted")

ErrDatabaseNotMounted is returned by Unmount for an unknown database id.

Functions

This section is empty.

Types

type CORSConfig

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

CORSConfig holds the allowed-origin set for the CORS middleware. A nil *CORSConfig means CORS is disabled — no headers are added.

func ParseCORSOrigins

func ParseCORSOrigins(values []string) *CORSConfig

ParseCORSOrigins builds a CORSConfig from a list of origin strings. Each element may be:

Comma-separated values within a single element are split automatically so both --cors "a,b" and --cors a --cors b are equivalent.

func (*CORSConfig) AllowedOrigin

func (c *CORSConfig) AllowedOrigin(origin string) string

AllowedOrigin returns the value to echo back in Access-Control-Allow-Origin, or "" when the origin is not allowed. Exported for testing.

func (*CORSConfig) WithHeaders added in v0.14.0

func (c *CORSConfig) WithHeaders(allowed, exposed []string) (*CORSConfig, error)

WithHeaders returns an independent CORS configuration with additive request and exposed response header names. Origins and legacy default headers persist.

type GrantIdentityConfig added in v0.4.0

type GrantIdentityConfig struct {
	Bootstrap access.PrincipalRef
	Resolve   MembershipResolver
}

GrantIdentityConfig maps verified bearer grants to typed identities. Bootstrap must come from persistent host configuration. It is never derived from a token, generated on startup, or inferred from a provider subject.

type Membership added in v0.4.0

type Membership struct {
	Roles    []string
	Groups   []string
	Revision string
}

Membership is authoritative current state, loaded anew for each request. External OAuth/OIDC bindings remain in the deployment's identity directory.

type MembershipResolver added in v0.4.0

type MembershipResolver func(context.Context, access.PrincipalRef) (Membership, error)

type Option

type Option func(*Server)

Option configures the Server.

func WithAccessInstanceID added in v0.5.0

func WithAccessInstanceID(id string) Option

WithAccessInstanceID supplies a stable deployment identity, shared by all mounts on this server. It must come from persistent host configuration.

func WithAuth

func WithAuth(cfg *auth.Config) Option

WithAuth enables authentication: the connect flow endpoints are served and every data/admin request must carry the owner token or a scoped app token.

func WithCORS

func WithCORS(cfg *CORSConfig) Option

WithCORS configures CORS header injection for browser clients. A nil cfg disables CORS entirely (zero behavior change, the default).

func WithDataDir

func WithDataDir(dir string) Option

WithDataDir enables runtime database creation (POST /v1/databases): each created database gets a manifest YAML plus an inGitDB data directory under dir, so a restart rescan (mount.Dir) remounts them.

func WithDatabaseReadProfiles added in v0.14.0

func WithDatabaseReadProfiles(profiles map[string]ReadProfile) Option

WithDatabaseReadProfiles configures immutable lookup policy per database. The map is copied. NewChecked reports invalid configuration before publication; New retains its signature and serves configuration_error on invalid options.

func WithGrantIdentity added in v0.4.0

func WithGrantIdentity(config GrantIdentityConfig) Option

WithGrantIdentity reuses token authentication and capability checks. It adds typed subject/actor propagation and current membership resolution; it does not validate arbitrary external bearer tokens or create an identity store.

func WithLogger added in v0.6.1

func WithLogger(logger *slog.Logger) Option

WithLogger sets the logger internal (HTTP 500) errors are reported to. A nil logger keeps the default, slog.Default().

func WithOwnerAuthorization added in v0.5.0

func WithOwnerAuthorization(authorize OwnerAuthorization) Option

func WithPrincipalResolver added in v0.4.0

func WithPrincipalResolver(resolve PrincipalResolver) Option

func WithProviderReadProfiles added in v0.18.0

func WithProviderReadProfiles(profiles map[string]ProviderReadProfile) Option

WithProviderReadProfiles opts selected HTTP instances into providerReads v1. Neither query input nor request Host can choose a binding or upstream URL.

func WithPublicOrigin added in v0.9.0

func WithPublicOrigin(origin string) Option

WithPublicOrigin sets the externally reachable HTTP(S) origin used in database connection URLs. Callers must validate it before constructing the server. Without it, request scheme and Host are used (suitable for local use).

func WithQueryLimits added in v0.11.6

func WithQueryLimits(limits QueryLimits) Option

WithQueryLimits sets the relational query limits. Unset fields take the defaults from DefaultQueryLimits.

func WithReadOnly added in v0.7.0

func WithReadOnly(readOnly bool) Option

WithReadOnly makes the entire server read-only. It rejects record, database, and token mutations before authentication or a route handler can cause a side effect. Owner credentials do not bypass this setting.

func WithSnapshotLimits added in v0.11.16

func WithSnapshotLimits(limits SnapshotLimits) Option

WithSnapshotLimits sets the snapshot spool limits. Every field must be positive: a zero or negative value never means "unlimited", and the option panics when the server is built, as WithAccessInstanceID does.

An operator on a memory-backed file system, such as Cloud Run, where the spool in the temporary directory counts against the instance memory, should set Slots * Bytes well below the instance memory (for example 1 slot of 128 MiB on a 512 MiB instance), because a spool as large as the memory can crash the instance.

func WithSourceRights added in v0.15.0

func WithSourceRights(serverID string, declaration *license.Declaration) Option

WithSourceRights supplies the operator's stable server identity and optional authored server license. The identity is never inferred from a request Host. A nil declaration permits database/recordset declarations without server terms. Legacy SPDX parsing uses the Directory-shaped runtime syntax policy; this option does not certify Publisher/Directory admission or legal applicability.

type OwnerAuthorization added in v0.5.0

type OwnerAuthorization func(context.Context, *auth.Principal, az.Source, string, az.Resource) bool

OwnerAuthorization is a trusted deployment binding to each owner's existing authorization authority. A grant at OpenVaultDB never grants administration or protected-row inspection at a lower owner.

type PrincipalResolver added in v0.4.0

type PrincipalResolver func(context.Context, *auth.Principal) (access.Principal, error)

PrincipalResolver maps an authenticated actor to current internal identity and memberships. Implementations are trusted server configuration; callers cannot supply roles, groups, or policy variables in a DTQL request.

type ProviderReadProfile added in v0.18.0

type ProviderReadProfile struct {
	Collection string
	Binding    providerreads.Binding
	// SourceRight optionally supplies reviewed dynamic-definition notices and
	// a metadata-only publisher pin. It cannot replace the mounted declaration,
	// change access/retention, or certify immutable upstream response bytes.
	SourceRight *license.SourceRight `json:"sourceRight,omitempty"`
}

ProviderReadProfile is trusted, externally verified admission configuration. It does not verify artifact existence or authorize public activation. Definition digest must bind the exact decoder, model/meaning and local recordset mapping. Consumers must advertise Format before this opt-in producer is configured.

type QueryLimits added in v0.11.6

type QueryLimits struct {
	// Timeout is the longest a relational query may run.
	Timeout time.Duration
	// InMemory is how many in-memory (leaf read plus join above) queries may
	// run at once.
	InMemory int
	// Database is how many database-route (pushed down) queries may run at once.
	Database int
	// QueueWait is how long a query waits for a free slot before it is refused.
	QueueWait time.Duration
	// MaxSourceRows is the most rows one request may read from sources.
	MaxSourceRows int
	// MaxSourceBytes is the most bytes one request may read from sources.
	MaxSourceBytes int64
	// JoinEngines lists the storage engines whose databases may take part in a
	// join. "ingitdb" means a local working tree only: a GitHub-backed inGitDB
	// database (Storage.InGitDB.GitHub != nil) is never eligible, whatever this
	// list says.
	JoinEngines []string
}

QueryLimits bounds relational (join and aggregation) queries so one request, or a crowd of identical ones, cannot exhaust a small instance. A zero or negative numeric field takes its default; a negative QueueWait means a query that finds the gate full is refused at once instead of queueing.

func DefaultQueryLimits added in v0.11.6

func DefaultQueryLimits() QueryLimits

DefaultQueryLimits returns the default limits. A 512 MiB instance should lower InMemory to 1.

type ReadProfile added in v0.14.0

type ReadProfile struct {
	Kind               string
	AllowOrdinaryQuery bool
	PublishedQuery     bool
}

ReadProfile is trusted per-instance configuration from checked runtime inventory. PublishedQuery controls discovery independently of guarded candidate execution.

type Server

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

Server serves one or more mounted databases.

func New

func New(version string, dbs map[string]*core.Database, opts ...Option) *Server

New creates a Server over mounted databases keyed by database id.

func NewChecked added in v0.14.0

func NewChecked(version string, dbs map[string]*core.Database, opts ...Option) (*Server, error)

NewChecked is New with startup validation of optional read profiles.

func (*Server) CloseSnapshots added in v0.8.0

func (s *Server) CloseSnapshots()

CloseSnapshots removes all materialized query results. Call after stopping HTTP serving and draining in-flight requests during shutdown.

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler builds the HTTP handler. Middleware order (outermost first):

  1. CORS (when --cors is set) — short-circuits preflight OPTIONS before auth
  2. Auth (when --auth is set) — Layer-1 token validation
  3. Per-handler capability checks — Layer-2

func (*Server) Mount added in v0.6.0

func (s *Server) Mount(db *core.Database) error

Mount starts serving db at runtime. It fails with ErrDatabaseMounted when its id is taken; the server owns db once Mount succeeds.

func (*Server) Unmount added in v0.6.0

func (s *Server) Unmount(id string) error

Unmount stops serving database id: new requests get 404 at once, requests already using it run to completion, then the database is closed, releasing its engine resources (e.g. the SQLite file handle). The Close error, if any, is returned; the database is unmounted either way. It waits for in-flight requests without limit; see UnmountContext.

func (*Server) UnmountContext added in v0.6.0

func (s *Server) UnmountContext(ctx context.Context, id string) error

UnmountContext is Unmount with a bound on the wait for in-flight requests. If ctx ends first, the database stays unrouted, requests in flight keep running, Close runs in the background once they finish (its error is dropped), and ctx.Err() is returned. For a profiled instance shared by mount aliases, removing a nonfinal alias only removes that route; leases and resources remain available through the other aliases until the final removal.

type SnapshotLimits added in v0.11.16

type SnapshotLimits struct {
	Slots int   // concurrent snapshots, including captures still being built
	Bytes int64 // spooled bytes of one snapshot
	Rows  int   // rows of one snapshot
}

SnapshotLimits bounds the disk spool behind paged DTQL queries. The most disk a server can use for snapshots is Slots * Bytes.

func DefaultSnapshotLimits added in v0.11.16

func DefaultSnapshotLimits() SnapshotLimits

DefaultSnapshotLimits returns the limits a server uses without WithSnapshotLimits: 2 snapshots of at most 512 MiB and 1,000,000 rows.

Jump to

Keyboard shortcuts

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