config

package
v2.2.2 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2026 License: AGPL-3.0 Imports: 12 Imported by: 0

Documentation

Index

Constants

View Source
const (
	AuditStoreDB   = "db"
	AuditStoreFile = "file"
	AuditStoreBoth = "both"
)

Variables

View Source
var FilterLimitNames = []string{
	"FILTER_SCRIPT_TIMEOUT",
	"FILTER_SCRIPT_MAX_ALLOCS",
	"FILTER_HTTP_TIMEOUT",
	"FILTER_HTTP_MAX_RESPONSE_BYTES",
	"FILTER_LLM_TIMEOUT",
}

FilterLimitNames are the tuning limits of Enterprise filter scripts and the helpers they call, which AppConf.FilterLimits may set.

Functions

func ExportEnvFile

func ExportEnvFile(envFile string)

ExportEnvFile copies the variables in envFile (".env" when empty) into the process environment, leaving variables that are already set untouched. The standalone binary calls it so packages that still read the environment directly see values from the file.

func IsEnterprise

func IsEnterprise() bool

IsEnterprise returns false for Community Edition builds

func NormalizeBasePath

func NormalizeBasePath(p string) string

NormalizeBasePath returns p as a path prefix with a leading slash and no trailing one ("ai-studio/" becomes "/ai-studio"), or "" for the root.

func ResetGlobalConfig

func ResetGlobalConfig()

ResetGlobalConfig resets the global configuration cache, forcing a reload on next Get() call This is primarily for testing purposes to ensure test isolation

func Set

func Set(conf *AppConf)

Set installs conf as the configuration Get returns.

Types

type AppConf

type AppConf struct {
	SMTPServer         string
	SMTPPort           int
	SMTPUser           string
	SMTPPass           string
	FromEmail          string
	AllowRegistrations bool
	// AllowSSOUserAPIKeys lets administrators issue a user API key to an
	// account provisioned through SSO. Off by default: an IdP-managed user
	// should hold no credential the IdP cannot revoke.
	AllowSSOUserAPIKeys bool
	// SSOAPIKeyLiveness bounds how long an SSO-provisioned user's API key
	// keeps working without a fresh SSO login (0 disables the check).
	SSOAPIKeyLiveness    time.Duration
	AdminEmail           string
	SiteURL              string
	ProxyURL             string
	ToolDisplayURL       string
	DataSourceDisplayURL string
	ServerPort           string
	ProxyPort            int
	// UnifiedRouterPath moves the gateway's OpenRouter-style single endpoint
	// ({base}/chat/completions, {base}/completions, {base}/models) off its default
	// "/v1". UnifiedRouterDisabled removes it altogether. Both exist because the
	// gateway is embeddable in hosts that own the "/v1" path space.
	UnifiedRouterPath     string
	UnifiedRouterDisabled bool
	// GatewayServerTiming adds Server-Timing headers/trailers to embedded
	// gateway LLM responses (GATEWAY_SERVER_TIMING), for benchmarking.
	GatewayServerTiming bool
	CertFile            string
	KeyFile             string
	DisableCors         bool
	DatabaseURL         string
	DatabaseType        string
	// DatabaseSchema (DATABASE_SCHEMA), for postgres only, puts Studio's
	// tables in this schema instead of the connection's default (public).
	// studio.OpenDatabase creates it when missing and pins search_path to it
	// alone. Use it to share a database with another application: Studio's
	// table names are unprefixed and include common ones such as users,
	// roles and audit_records.
	DatabaseSchema string
	// MigrationLockTimeout (MIGRATION_LOCK_TIMEOUT, default 15m), for
	// postgres only, bounds how long a starting Studio waits for another
	// instance sharing its database to finish migrating before it gives up
	// with an error.
	MigrationLockTimeout  time.Duration
	FilterSignupDomains   []string
	EchoConversation      bool
	ProxyOnly             bool
	DocsURL               string
	DefaultSignupMode     string
	TIBEnabled            bool
	TIBAPISecret          string
	DocsLinks             DocsLinks
	DevMode               bool
	AuthServerURL         string
	ProxyOAuthMetadataURL string
	TelemetryEnabled      bool
	QueueConfig           QueueConfig
	LogLevel              string

	// Session Configuration
	SessionDuration time.Duration

	// OCI Plugin Configuration
	OCIPlugins OCIConfig

	// Audit Trail Configuration (Enterprise)
	Audit AuditConfig

	// Webhooks Configuration (Enterprise)
	Webhooks WebhooksConfig

	// Tyk Dashboard MCP integration (Enterprise)
	TykMCP TykMCPConfig

	// Marketplace Configuration
	MarketplaceEnabled      bool
	MarketplaceIndexURL     string
	MarketplaceSyncInterval time.Duration
	MarketplaceCacheDir     string

	// Hub-and-Spoke Configuration
	GatewayMode       string
	GRPCPort          int
	GRPCHost          string
	GRPCTLSEnabled    bool
	GRPCTLSCertPath   string
	GRPCTLSKeyPath    string
	GRPCAuthToken     string
	GRPCNextAuthToken string
	// GRPCMaxMessageSize bounds a control server message in bytes
	// (GRPC_MAX_MESSAGE_SIZE, default 16 MB, as on the edge).
	GRPCMaxMessageSize int
	// GRPCMaxConnectionAge closes edge connections after about this long so
	// they rebalance over replicas behind a load balancer, with
	// GRPCMaxConnectionAgeGrace for streams to finish
	// (GRPC_MAX_CONNECTION_AGE, GRPC_MAX_CONNECTION_AGE_GRACE; default off).
	GRPCMaxConnectionAge      time.Duration
	GRPCMaxConnectionAgeGrace time.Duration

	// Licensing Configuration (Enterprise Edition)
	LicenseKey                  string
	LicenseTelemetryPeriod      time.Duration
	LicenseDisableTelemetry     bool
	LicenseTelemetryURL         string
	LicenseValidityPeriod       time.Duration
	LicenseTelemetryConcurrency int

	// Budget Configuration
	DefaultAppBudget *float64

	// Docs Server Configuration
	DocsPort     int
	DocsDisabled bool

	// Metrics Configuration
	MetricsEnabled bool
	MetricsPath    string
	// MetricsAuthToken, when set, requires "Authorization: Bearer <token>" on the
	// metrics endpoint. When empty, the endpoint is only served if
	// MetricsAllowUnauthenticated is explicitly enabled.
	MetricsAuthToken            string
	MetricsAllowUnauthenticated bool

	// Tracing Configuration. Names match the microgateway's equivalents so a
	// single set of env vars configures either side of the hub-spoke pair.
	TracingEnabled  bool
	TracingEndpoint string

	// Submission Configuration
	MaxResourcePayloadSize int // Max size in bytes for submission resource_payload JSON (default: 5MB)

	// BasePath is the path prefix Studio's HTTP interface is served under,
	// such as "/ai-studio" (BASE_PATH); empty serves it at the root. SiteURL
	// should include it.
	BasePath string

	// SecretKey encrypts secrets at rest (TYK_AI_SECRET_KEY).
	SecretKey string
	// MicrogatewayEncryptionKey is the 32-character key edges decrypt the
	// credentials in their configuration with (MICROGATEWAY_ENCRYPTION_KEY).
	MicrogatewayEncryptionKey string
	// CSRFTrustedOrigins lists extra origins, comma-separated, the CSRF check
	// accepts in DevMode (CSRF_TRUSTED_ORIGINS).
	CSRFTrustedOrigins string
	// CSRFKey is a secret the CSRF token key is derived from (CSRF_KEY).
	// Set it so tokens survive restarts and are shared by replicas; empty
	// uses a random key per process.
	CSRFKey string
	// CSRFCookieName names the CSRF cookie (CSRF_COOKIE_NAME, default
	// _gorilla_csrf); change it when a host on the same domain uses the
	// default name too.
	CSRFCookieName string
	// ExportStoragePath is where log exports are written (EXPORT_STORAGE_PATH,
	// default ./data/exports).
	ExportStoragePath string
	// BrandingStoragePath is where uploaded logos and favicons are kept
	// (BRANDING_STORAGE_PATH, default ./data/branding).
	BrandingStoragePath string
	// DebugHTTP logs admin API request and response bodies (DEBUG_HTTP).
	DebugHTTP bool
	// ChatUIV2Enabled turns on the v2 chat UI; it is on unless
	// CHAT_UI_V2_ENABLED is explicitly false.
	ChatUIV2Enabled bool
	// ChatSessionIdleTTL is how long an idle chat session keeps its queue
	// (CHAT_SESSION_IDLE_TTL, default 10m).
	ChatSessionIdleTTL time.Duration

	// AnalyticsBufferSize is how many analytics records wait in memory to
	// be written (ANALYTICS_BUFFER_SIZE, default 1000).
	AnalyticsBufferSize int
	// BudgetSyncInterval is how often budget usage is synced to edges
	// (BUDGET_SYNC_INTERVAL, default 30s).
	BudgetSyncInterval time.Duration
	// DebugHTTPProxy logs the embedded gateway's requests
	// (DEBUG_HTTP_PROXY).
	DebugHTTPProxy bool
	// MetricsNoLegacyNames stops emitting the pre-conventions aistudio_*
	// metrics next to the gen_ai.* ones (METRICS_LEGACY_NAMES=false). The
	// zero value keeps them, so dashboards built on them keep working.
	MetricsNoLegacyNames bool
	// CORSAllowedOrigins is the comma-separated origin list for the
	// endpoints that allow cross-origin calls (CORS_ALLOWED_ORIGINS; empty
	// allows any origin).
	CORSAllowedOrigins string
	// SkipFilterDefaults skips creating the example filters in an
	// Enterprise database (SKIP_FILTER_DEFAULTS).
	SkipFilterDefaults bool
	// FilterLimits are the Enterprise filter-script limits, by their
	// environment variable names (see FilterLimitNames). A name missing
	// here falls back to the environment. The switch that lets scripts use
	// the operating system (FILTER_SCRIPT_ALLOW_OS) is a security setting
	// and is read from the environment only.
	FilterLimits map[string]string
}

func Get

func Get(envFile string) *AppConf

func Installed

func Installed() *AppConf

Installed returns the configuration installed with Set (or loaded by Get), or nil. Unlike Get it never loads one: code shared with the microgateway, which has no AppConf, uses it to prefer Studio's settings when there are any.

func Load

func Load(envFile string) *AppConf

Load reads the configuration from the process environment. Variables the environment leaves unset are taken from envFile (".env" when empty) if it exists. Unlike Get, Load neither caches the result nor writes to the process environment.

func LoadFrom

func LoadFrom(getenv func(string) string) *AppConf

LoadFrom builds a configuration from getenv, which maps a variable name to its value ("" when unset), applying the same defaults and validation as Load. It lets a host build the configuration from its own settings rather than from the process environment. Unlike Load it does not log the "environment variable is not set" notices, since a host supplies only the settings it needs; and because only the standalone binary runs the documentation server, the docs link is left out (DocsURL empty, DocsDisabled set) unless DOCS_URL_OVERRIDE names one.

func (*AppConf) PublicPath

func (c *AppConf) PublicPath(path string) string

PublicPath returns path (which starts with "/") as seen by a browser: under BasePath.

type AuditConfig

type AuditConfig struct {
	// Enabled turns recording on. Enterprise builds default to true.
	Enabled bool
	// StoreType is "db" (queryable from the API/UI), "file" (append-only log
	// file), or "both".
	StoreType string
	// FilePath is the audit log file used when StoreType is "file" or "both".
	FilePath string
	// FileFormat is "json" (one JSON object per line) or "text".
	FileFormat string
	// DetailedRecording stores redacted request and response bodies.
	DetailedRecording bool
	// RecordReads also records GET requests. Off by default because the admin
	// UI polls several read endpoints and the volume is rarely useful.
	RecordReads bool
	// RetentionDays deletes database records older than this. 0 keeps forever.
	RetentionDays int
	// MaxBodyBytes caps each stored request/response dump and diff.
	MaxBodyBytes int
	// QueueSize bounds the in-memory write queue between the HTTP path and
	// the background writer. Overflow is dropped and logged, never blocking
	// the request.
	QueueSize int
	// RedactKeys adds to the built-in list of column / JSON key fragments
	// whose values are replaced with [REDACTED] in diffs and dumps. Matching
	// is case-insensitive substring, e.g. "ssn" matches "customer_ssn".
	RedactKeys []string
	// RedactHeaders adds to the built-in list of HTTP header names masked in
	// detailed request/response dumps.
	RedactHeaders []string
}

getOCIConfig parses OCI plugin-related environment variables AuditConfig controls the platform audit trail (Enterprise feature). The keys mirror the Tyk Dashboard audit settings (enabled, store_type, path, format, detailed_recording) with retention and read-recording added.

func (AuditConfig) StoresToDB

func (c AuditConfig) StoresToDB() bool

StoresToDB reports whether records are written to the database.

func (AuditConfig) StoresToFile

func (c AuditConfig) StoresToFile() bool

StoresToFile reports whether records are appended to the log file.

type DocsLinks map[string]string

func (DocsLinks) ReadFromFile

func (d DocsLinks) ReadFromFile(fileName string)

type NATSConfig

type NATSConfig struct {
	URL             string `json:"url"`
	StorageType     string `json:"storage_type"`     // "memory" | "file"
	RetentionPolicy string `json:"retention_policy"` // "limits" | "interest" | "workqueue"
	MaxAge          string `json:"max_age"`          // Duration string like "2h", "30m"
	MaxBytes        int64  `json:"max_bytes"`
	DurableConsumer bool   `json:"durable_consumer"`
	AckWait         string `json:"ack_wait"` // Duration string like "30s"
	MaxDeliver      int    `json:"max_deliver"`
	FetchTimeout    string `json:"fetch_timeout"`  // Duration string like "5s"
	RetryInterval   string `json:"retry_interval"` // Duration string like "1s"
	MaxRetries      int    `json:"max_retries"`    // Max retries for failed operations

	// Authentication options
	CredentialsFile string `json:"credentials_file"` // Optional NATS credentials file
	Username        string `json:"username"`         // Optional username for basic auth
	Password        string `json:"password"`         // Optional password for basic auth
	Token           string `json:"token"`            // Optional token for token-based auth
	NKeyFile        string `json:"nkey_file"`        // Optional NKey file path

	// TLS options
	TLSEnabled    bool   `json:"tls_enabled"`     // Enable TLS connection
	TLSCertFile   string `json:"tls_cert_file"`   // Optional client certificate file
	TLSKeyFile    string `json:"tls_key_file"`    // Optional client key file
	TLSCAFile     string `json:"tls_ca_file"`     // Optional CA certificate file
	TLSSkipVerify bool   `json:"tls_skip_verify"` // Skip TLS certificate verification
}

NATSConfig holds NATS JetStream configuration

type OCIConfig

type OCIConfig struct {
	// Cache settings
	CacheDir     string `env:"AI_STUDIO_OCI_CACHE_DIR" envDefault:""`
	MaxCacheSize int64  `env:"AI_STUDIO_OCI_MAX_CACHE_SIZE" envDefault:"1073741824"` // 1GB

	// Bounds a single plugin binary (see ociplugins.OCIConfig.MaxPluginSize)
	MaxPluginSize int64 `env:"AI_STUDIO_OCI_MAX_PLUGIN_SIZE" envDefault:"536870912"` // 512MB

	// Security settings
	AllowedRegistries []string `env:"AI_STUDIO_OCI_ALLOWED_REGISTRIES" envSeparator:","`
	RequireSignature  bool     `env:"AI_STUDIO_OCI_REQUIRE_SIGNATURE" envDefault:"false"` // More permissive default for AI Studio

	// Network settings
	Timeout       time.Duration `env:"AI_STUDIO_OCI_TIMEOUT" envDefault:"30s"`
	RetryAttempts int           `env:"AI_STUDIO_OCI_RETRY_ATTEMPTS" envDefault:"3"`

	// Garbage collection
	GCInterval   time.Duration `env:"AI_STUDIO_OCI_GC_INTERVAL" envDefault:"24h"`
	KeepVersions int           `env:"AI_STUDIO_OCI_KEEP_VERSIONS" envDefault:"3"`

	// Advanced settings
	InsecureRegistries []string `env:"AI_STUDIO_OCI_INSECURE_REGISTRIES" envSeparator:","`
}

OCIConfig holds OCI plugin configuration for AI Studio Uses AI_STUDIO_OCI_* environment variables to avoid conflicts with microgateway

func (*OCIConfig) IsEnabled

func (c *OCIConfig) IsEnabled() bool

IsEnabled returns true if OCI support is enabled (cache directory is configured)

func (*OCIConfig) SetDefaults

func (c *OCIConfig) SetDefaults()

SetDefaults sets sensible default values for AI Studio

func (*OCIConfig) ToOCILibConfig

func (c *OCIConfig) ToOCILibConfig() *ociplugins.OCIConfig

ToOCILibConfig converts AI Studio OCI config to the library config format Reuses microgateway's registry auth and public key loading functions

func (*OCIConfig) Validate

func (c *OCIConfig) Validate() error

Validate validates the OCI configuration

type PostgreSQLQueueConfig

type PostgreSQLQueueConfig struct {
	ReconnectInterval   string `json:"reconnect_interval"`    // Duration string like "2s"
	MaxReconnectRetries int    `json:"max_reconnect_retries"` // Maximum reconnection attempts (default: 10)
	NotifyTimeout       string `json:"notify_timeout"`        // Duration string like "5s"
}

PostgreSQLQueueConfig holds PostgreSQL-specific queue configuration

type QueueConfig

type QueueConfig struct {
	Type       string                `json:"type"`        // "inmemory" | "nats" | "postgres"
	BufferSize int                   `json:"buffer_size"` // Local channel buffer (default: 100)
	NATS       NATSConfig            `json:"nats"`        // NATS-specific config
	PostgreSQL PostgreSQLQueueConfig `json:"postgresql"`  // PostgreSQL-specific config
}

QueueConfig holds configuration for message queues

type TykMCPConfig

type TykMCPConfig struct {
	// Enabled turns the feature on. Enterprise builds default to true.
	Enabled bool
	// SyncMinInterval is the floor for a connection's sync interval.
	SyncMinInterval time.Duration
	// RequestTimeout is the per-call HTTP timeout for Dashboard reads;
	// writes get three times this value.
	RequestTimeout time.Duration
	// AllowedHosts, when non-empty, restricts Dashboard and MDCB URLs to
	// these hosts (exact or ".suffix"). DeniedHosts always rejects and wins.
	AllowedHosts []string
	DeniedHosts  []string
	// RequireDifferentActivator rejects activation of a connection by the
	// administrator who created it.
	RequireDifferentActivator bool
	// SyncRunRetention deletes sync run records older than this.
	SyncRunRetention time.Duration
	// RateLimitPerSecond caps outbound Dashboard calls per connection.
	RateLimitPerSecond int
}

TykMCPConfig controls the Tyk Dashboard MCP integration (Enterprise feature): MCP proxies defined in a Tyk Dashboard are imported into the AI Portal, registered from Studio, and access keys are brokered against Tyk policies. Every switch here can only disable or tighten the feature.

type WebhooksConfig

type WebhooksConfig struct {
	// Enabled turns the feature on. Enterprise builds default to true.
	Enabled bool
	// WorkerEnabled runs the delivery worker on this node. Set false on nodes
	// that should only manage targets (all nodes still ingest events).
	WorkerEnabled bool
	// WorkerCount is the number of concurrent delivery workers per node.
	WorkerCount int
	// MaxAttempts is the number of HTTP attempts before a delivery is dead-lettered.
	MaxAttempts int
	// BaseBackoff and MaxBackoff bound the exponential retry schedule.
	BaseBackoff time.Duration
	MaxBackoff  time.Duration
	// RequestTimeout is the per-attempt HTTP timeout (capped at 60s).
	RequestTimeout time.Duration
	// AllowInternalTargets permits targets on loopback, RFC1918, link-local
	// and other internal ranges. Off by default: webhooks are an
	// exfiltration vector and internal services must not be reachable.
	AllowInternalTargets bool
	// AllowedHosts, when non-empty, restricts targets to these hosts (exact
	// or ".suffix"). DeniedHosts always rejects, and wins over AllowedHosts.
	AllowedHosts []string
	DeniedHosts  []string
	// RetentionDays deletes succeeded/cancelled deliveries older than this.
	// DeadLetterRetentionDays does the same for dead letters. 0 keeps forever.
	RetentionDays           int
	DeadLetterRetentionDays int
	// MaxResponseSnippetBytes caps the stored response body per attempt.
	MaxResponseSnippetBytes int
	// RequireDifferentApprover rejects approval by the admin who created the target.
	RequireDifferentApprover bool
	// SecretRotationGrace is how long the previous signing secret keeps
	// producing a second signature after a rotation.
	SecretRotationGrace time.Duration
	// RedactKeys adds to the built-in list of JSON key fragments whose values
	// are replaced with [REDACTED] before an event is stored or templated.
	RedactKeys []string
	// AuditDeliveries records every succeeded delivery in the audit trail
	// (dead letters are always recorded). Off by default because of volume.
	AuditDeliveries bool
	// ShutdownDrainTimeout bounds how long Stop waits for in-flight deliveries.
	ShutdownDrainTimeout time.Duration
}

WebhooksConfig controls outbound webhook delivery (Enterprise feature): event-bus events are fanned out to admin-approved HTTP targets with retries, dead-lettering and a searchable delivery log.

Jump to

Keyboard shortcuts

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