config

package
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: Apache-2.0 Imports: 25 Imported by: 0

Documentation

Overview

Package config loads and validates AgentSQL configuration.

Index

Constants

View Source
const (
	DemoDatasourcePG       = "ds-demo-pg"
	DemoDatasourceMySQL    = "ds-demo-mysql"
	DemoAgentRO            = "agent-demo-ro"
	DemoAgentDML           = "agent-demo-dml"
	DemoDefaultQPSPerAgent = 2
	DemoDefaultBanner      = "演示环境·数据每日重置·禁止接入真实数据与真实数据库"
)
View Source
const (
	RedactionHashKeyEnv      = "AGENTSQL_REDACTION_HASH_KEY"
	RedactionHashKeysFileEnv = "AGENTSQL_REDACTION_HASH_KEYS_FILE"
)
View Source
const (
	MetadataDSNEnv = "AGENTSQL_STORE_METADATA_DSN"
	AuditDSNEnv    = "AGENTSQL_STORE_AUDIT_DSN"
)

Variables

View Source
var (
	// ErrMissingSQLitePath indicates that store.sqlite_path is empty.
	ErrMissingSQLitePath = errors.New("store.sqlite_path is required")
	// ErrInvalidHTTPListen indicates that server.http_listen is not a valid host and TCP port.
	ErrInvalidHTTPListen = errors.New("server.http_listen must contain a valid host and TCP port")
	// ErrNegativeStatementTimeout indicates that defaults.statement_timeout_ms is negative.
	ErrNegativeStatementTimeout = errors.New("defaults.statement_timeout_ms must not be negative")
	// ErrInvalidDefault indicates that a safety-related default is not positive.
	ErrInvalidDefault = errors.New("row, connection, and QPS defaults must be positive")
	// ErrInvalidTheme indicates that theme.default is neither light nor dark.
	ErrInvalidTheme = errors.New("theme.default must be light or dark")
	// ErrMultipleYAMLDocuments indicates that a configuration file contains trailing YAML documents.
	ErrMultipleYAMLDocuments = errors.New("configuration must contain exactly one YAML document")
	// ErrInvalidEventStreamMaxConnections indicates an SSE connection limit outside 1-1000.
	ErrInvalidEventStreamMaxConnections = errors.New("server.event_stream_max_connections must be between 1 and 1000")
	// ErrInvalidColumnAuthorizationInstanceID indicates an explicitly empty or corrupt persisted instance identity.
	ErrInvalidColumnAuthorizationInstanceID = errors.New("column_authorization.instance_id must be non-empty when explicitly configured")
	// ErrB5MySQLUnsupported prevents a configuration switch from advertising a
	// transaction dialect whose ownership and binder contracts are not closed.
	ErrB5MySQLUnsupported = errors.New("mcp.transactions.mysql 不受支持;请关闭该开关并使用 PostgreSQL")
)
View Source
var (
	ErrInvalidRedactionHashKey  = errors.New("redaction hash key must be at least 32 bytes")
	ErrRedactionSourceConflict  = errors.New("redaction hash key configuration sources conflict")
	ErrInvalidHashKeysManifest  = errors.New("redaction hash keys manifest is invalid")
	ErrWeakHashKey              = errors.New("redaction key does not satisfy the minimum diversity policy")
	ErrDuplicateHashKeyMaterial = errors.New("different redaction key versions must not use identical key material")
)
View Source
var (
	ErrConflictingStoreConfig = errors.New("store.sqlite_path and store.metadata are mutually exclusive")
	ErrMissingPostgresDSN     = errors.New("store.metadata.dsn is required for postgres")
	ErrMissingAuditDSN        = errors.New("store.audit.dsn is required for a separate audit store")
)

Functions

func DeriveRedactionRevision

func DeriveRedactionRevision(activeVersion int, commitments map[int]string) string

DeriveRedactionRevision hashes canonical JSON containing only the active selector and sorted id-to-commitment pairs. Source bytes and paths are absent.

func InsecureModeFromEnv

func InsecureModeFromEnv() (bool, error)

InsecureModeFromEnv reports whether explicitly allowing public test credentials has been requested. This switch is permanently limited to that purpose; it must never disable authentication, security rules, or fail-closed behavior.

func ValidateAdminPassword

func ValidateAdminPassword(username, password string, insecure bool) error

ValidateAdminPassword enforces the production startup policy for the web console administrator password.

func ValidateStartupSecret

func ValidateStartupSecret(secret string, insecure bool) error

ValidateStartupSecret enforces the production startup policy for the encryption key without changing the lower-level cipher contract.

Types

type AuditStoreConfig

type AuditStoreConfig struct {
	Separate     bool   `yaml:"separate"`
	Driver       string `yaml:"driver"`
	DSN          string `yaml:"dsn"`
	MaxOpenConns int    `yaml:"max_open_conns"`
	MaxIdleConns int    `yaml:"max_idle_conns"`
	// contains filtered or unexported fields
}

type AuthConfig added in v0.5.0

type AuthConfig struct {
	MFA  MFAConfig  `yaml:"mfa"`
	OIDC OIDCConfig `yaml:"oidc"`
	LDAP LDAPConfig `yaml:"ldap"`
}

AuthConfig controls human control-plane authentication. Every provider is opt-in; an omitted auth section preserves local password authentication.

func (AuthConfig) Validate added in v0.5.0

func (config AuthConfig) Validate() error

type ColumnAuthorizationConfig

type ColumnAuthorizationConfig struct {
	Enabled             bool   `yaml:"enabled"`
	DryRun              bool   `yaml:"dry_run"`
	InstanceID          string `yaml:"instance_id"`
	InstanceIDFile      string `yaml:"instance_id_file"`
	LeaseMS             int    `yaml:"lease_ms"`
	HeartbeatIntervalMS int    `yaml:"heartbeat_interval_ms"`
	// contains filtered or unexported fields
}

ColumnAuthorizationConfig controls the PostgreSQL protocol-3 path. Enabled defaults on for parsed YAML, while an explicitly configured false remains an authoritative rollback switch. Load resolves an omitted InstanceID from a persistent per-deployment random identity before production assembly.

type Config

type Config struct {
	Server              ServerConfig              `yaml:"server"`
	Store               StoreConfig               `yaml:"store"`
	Defaults            DefaultsConfig            `yaml:"defaults"`
	Theme               ThemeConfig               `yaml:"theme"`
	Demo                DemoConfig                `yaml:"demo"`
	Redaction           RedactionConfig           `yaml:"redaction"`
	ColumnAuthorization ColumnAuthorizationConfig `yaml:"column_authorization"`
	MCP                 MCPConfig                 `yaml:"mcp"`
	Auth                AuthConfig                `yaml:"auth"`
}

Config is the root AgentSQL configuration.

func Load

func Load(path string) (Config, error)

Load reads one YAML document, validates all startup settings, and creates the parent directory for the SQLite database.

func Parse

func Parse(contents []byte) (Config, error)

Parse decodes exactly one YAML configuration document, applies strict environment switches, and validates it without changing the filesystem.

func (Config) DemoEnabled

func (config Config) DemoEnabled() bool

DemoEnabled reports whether the Live Demo mode is explicitly enabled.

func (Config) EffectiveMCP

func (config Config) EffectiveMCP() MCPConfig

EffectiveMCP returns the factory defaults for programmatically constructed Config values as well as parsed YAML. Parsed explicit false values remain authoritative because Parse fills the non-boolean defaults before decode.

func (Config) Validate

func (config Config) Validate() error

Validate checks every T01 startup invariant and fails closed on invalid input.

type ConfigDuration

type ConfigDuration time.Duration

ConfigDuration is a YAML string containing a Go duration such as 30m or 1h.

func (*ConfigDuration) UnmarshalYAML

func (duration *ConfigDuration) UnmarshalYAML(node *yaml.Node) error

type DefaultsConfig

type DefaultsConfig struct {
	StatementTimeoutMS    int `yaml:"statement_timeout_ms"`
	RowLimit              int `yaml:"row_limit"`
	MaxConnsPerDatasource int `yaml:"max_conns_per_datasource"`
	QPSPerAgent           int `yaml:"qps_per_agent"`
}

DefaultsConfig contains global execution and capacity limits.

type DemoConfig

type DemoConfig struct {
	Enabled              bool     `yaml:"enabled"`
	Banner               string   `yaml:"banner"`
	AllowedDatasourceIDs []string `yaml:"allowed_datasource_ids"`
	QPSPerAgent          int      `yaml:"qps_per_agent"`
	AnchorDate           string   `yaml:"anchor_date"`
}

DemoConfig controls the bounded Live Demo surface.

func (DemoConfig) AllowsDatasource

func (demo DemoConfig) AllowsDatasource(id string) bool

AllowsDatasource reports whether an ID belongs to the enabled demo's fixed datasource allowlist.

func (DemoConfig) EffectiveQPS

func (demo DemoConfig) EffectiveQPS() int

EffectiveQPS returns the configured demo rate or its default.

type LDAPConfig added in v0.5.0

type LDAPConfig struct {
	Enabled            bool                `yaml:"enabled"`
	URL                string              `yaml:"url"`
	StartTLS           bool                `yaml:"start_tls"`
	CAFile             string              `yaml:"ca_file"`
	ServerName         string              `yaml:"server_name"`
	BindDN             string              `yaml:"bind_dn"`
	BindPasswordEnv    string              `yaml:"bind_password_env"`
	UserBaseDN         string              `yaml:"user_base_dn"`
	UserFilter         string              `yaml:"user_filter"`
	UsernameAttribute  string              `yaml:"username_attribute"`
	GroupBaseDN        string              `yaml:"group_base_dn"`
	GroupFilter        string              `yaml:"group_filter"`
	GroupNameAttribute string              `yaml:"group_name_attribute"`
	TenantID           string              `yaml:"tenant_id"`
	AutoProvision      bool                `yaml:"auto_provision"`
	GroupRoleMap       map[string][]string `yaml:"group_role_map"`
}

type MCPConfig

type MCPConfig struct {
	HTTP         MCPHTTPConfig         `yaml:"http"`
	Sessions     MCPSessionsConfig     `yaml:"sessions"`
	Transactions MCPTransactionsConfig `yaml:"transactions"`
	// contains filtered or unexported fields
}

MCPConfig is the production configuration root for the MCP HTTP transport, explicit logical sessions, and planned multi-request transactions.

type MCPHTTPConfig

type MCPHTTPConfig struct {
	Stateful           bool `yaml:"stateful"`
	SessionTimeoutMS   int  `yaml:"session_timeout_ms"`
	EventStoreEnabled  bool `yaml:"event_store_enabled"`
	EventStoreMaxBytes int  `yaml:"event_store_max_bytes"`
	EventStoreTTLMS    int  `yaml:"event_store_ttl_ms"`
}

MCPHTTPConfig controls protocol-level Streamable HTTP sessions. These sessions are independent from the application-level B5 sessions below.

type MCPSessionsConfig

type MCPSessionsConfig struct {
	Enabled       bool   `yaml:"enabled"`
	InstanceID    string `yaml:"instance_id"`
	StickyRoute   string `yaml:"sticky_route"`
	IdleTTLMS     int    `yaml:"idle_ttl_ms"`
	AbsoluteTTLMS int    `yaml:"absolute_ttl_ms"`
}

type MCPTransactionsConfig

type MCPTransactionsConfig struct {
	Postgres           bool   `yaml:"postgres"`
	MySQL              bool   `yaml:"mysql"`
	IdleTimeoutMS      int    `yaml:"idle_timeout_ms"`
	WallTimeoutMS      int    `yaml:"wall_timeout_ms"`
	StatementTimeoutMS int    `yaml:"statement_timeout_ms"`
	ShutdownDrainMS    int    `yaml:"shutdown_drain_ms"`
	WALDirectory       string `yaml:"wal_directory"`
}

type MFAConfig added in v0.5.0

type MFAConfig struct {
	Enabled bool   `yaml:"enabled"`
	Issuer  string `yaml:"issuer"`
}

type MetadataStoreConfig

type MetadataStoreConfig struct {
	Driver          string         `yaml:"driver"`
	SQLitePath      string         `yaml:"sqlite_path"`
	DSN             string         `yaml:"dsn"`
	MaxOpenConns    int            `yaml:"max_open_conns"`
	MaxIdleConns    int            `yaml:"max_idle_conns"`
	ConnMaxLifetime ConfigDuration `yaml:"conn_max_lifetime"`
}

type OIDCConfig added in v0.5.0

type OIDCConfig struct {
	Enabled         bool                `yaml:"enabled"`
	IssuerURL       string              `yaml:"issuer_url"`
	ClientID        string              `yaml:"client_id"`
	ClientSecretEnv string              `yaml:"client_secret_env"`
	RedirectURL     string              `yaml:"redirect_url"`
	PostLogoutURL   string              `yaml:"post_logout_url"`
	TenantID        string              `yaml:"tenant_id"`
	UsernameClaim   string              `yaml:"username_claim"`
	GroupsClaim     string              `yaml:"groups_claim"`
	Scopes          []string            `yaml:"scopes"`
	AutoProvision   bool                `yaml:"auto_provision"`
	GroupRoleMap    map[string][]string `yaml:"group_role_map"`
}

type RedactionAssembly

type RedactionAssembly struct {
	Plan        mask.RedactionPlan
	PlanOptions []mask.Option
	Observed    redaction.Observed
	Verify      func(version int, value, candidate string) (bool, error)
}

func BuildRedactionAssembly

func BuildRedactionAssembly(rc RedactionConfig) (RedactionAssembly, error)

type RedactionConfig

type RedactionConfig struct {
	HashKey  string                   `yaml:"hash_key"`
	HashKeys *RedactionHashKeysConfig `yaml:"hash_keys,omitempty"`
	// contains filtered or unexported fields
}

RedactionConfig contains process-local redaction secret sources. Resolved key bytes are unexported, copied only into the immutable assembly, and can be actively cleared with Clear after assembly.

func ResolveRedaction

func ResolveRedaction(cfg *Config, lookup func(string) (string, bool)) (RedactionConfig, error)

ResolveRedaction atomically selects one source, completes both manifest validation phases, and returns a minimally exposed assembly input.

func (*RedactionConfig) Clear

func (config *RedactionConfig) Clear()

type RedactionHashKeySpec

type RedactionHashKeySpec struct {
	ID      int     `yaml:"id"`
	KeyFile *string `yaml:"key_file,omitempty"`
	KeyB64  *string `yaml:"key_b64,omitempty"`
}

RedactionHashKeySpec is one manifest entry. Pointer source fields preserve the distinction between omitted and explicitly empty YAML values.

func (*RedactionHashKeySpec) UnmarshalYAML

func (spec *RedactionHashKeySpec) UnmarshalYAML(node *yaml.Node) error

type RedactionHashKeysConfig

type RedactionHashKeysConfig struct {
	ActiveVersion int                    `yaml:"active_version"`
	Keys          []RedactionHashKeySpec `yaml:"keys"`
	Revision      *string                `yaml:"revision,omitempty"`
}

RedactionHashKeysConfig is the sole accepted root shape for both inline redaction.hash_keys and AGENTSQL_REDACTION_HASH_KEYS_FILE.

func (*RedactionHashKeysConfig) UnmarshalYAML

func (manifest *RedactionHashKeysConfig) UnmarshalYAML(node *yaml.Node) error

type ResolvedStore

type ResolvedStore struct {
	Metadata    ResolvedStoreTarget
	Audit       ResolvedStoreTarget
	AutoMigrate bool
}

ResolvedStore is the normalized, environment-aware two-target configuration.

func ResolveStore

func ResolveStore(cfg *Config, lookup func(string) (string, bool)) (*ResolvedStore, error)

ResolveStore applies defaults, then explicit environment overrides, and finally validates all cross-field invariants. It never touches the filesystem.

func (ResolvedStore) AuditOptions

func (resolved ResolvedStore) AuditOptions() store.AuditOptions

AuditOptions maps the resolved audit target without copying a shared DSN.

func (ResolvedStore) MetadataOptions

func (resolved ResolvedStore) MetadataOptions() store.MetadataOptions

MetadataOptions maps both resolved targets to the store package.

type ResolvedStoreTarget

type ResolvedStoreTarget struct {
	Driver          store.Dialect
	SQLitePath      string
	PostgresDSN     string
	MaxOpenConns    int
	MaxIdleConns    int
	ConnMaxLifetime ConfigDuration
	ReuseMetadata   bool
}

ResolvedStoreTarget is one normalized database target. ReuseMetadata is only true for the audit target when it shares the metadata connection; in that case PostgresDSN and SQLitePath deliberately remain empty.

type ServerConfig

type ServerConfig struct {
	HTTPListen                string `yaml:"http_listen"`
	ConsoleEnabled            bool   `yaml:"console_enabled"`
	EventStream               bool   `yaml:"event_stream"`
	EventStreamMaxConnections int    `yaml:"event_stream_max_connections"`
}

ServerConfig controls the shared HTTP listener and console availability.

type StoreConfig

type StoreConfig struct {
	SQLitePath  string               `yaml:"sqlite_path"`
	Metadata    *MetadataStoreConfig `yaml:"metadata"`
	Audit       *AuditStoreConfig    `yaml:"audit"`
	AutoMigrate bool                 `yaml:"auto_migrate"`
	// contains filtered or unexported fields
}

StoreConfig supports both the v0.1 SQLite shorthand and the extensible metadata/audit form. SQLitePath must remain compatible with programmatic StoreConfig{SQLitePath: ...} construction.

type ThemeConfig

type ThemeConfig struct {
	Default string `yaml:"default"`
}

ThemeConfig controls the initial console theme.

Jump to

Keyboard shortcuts

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