config

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: Apache-2.0 Imports: 20 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package config loads the opsgate YAML configuration.

Every field has a safe default: providers are disabled, scopes are read-only, and nothing is allowed unless it is listed explicitly.

Index

Constants

View Source
const (
	ScopeRead  = "ops:read"
	ScopeWrite = "ops:write"
	// ScopeDev allows starting coding agents through the dev provider.
	ScopeDev = "dev:run"
)

Scopes understood by opsgate.

View Source
const (
	AuthBuiltin  = "builtin"
	AuthExternal = "external"
	AuthStatic   = "static"
)

Auth modes for the HTTP transport.

View Source
const (
	LoginPasskey = "passkey"
	LoginGoogle  = "google"
	LoginGitHub  = "github"
)

Sign-in choices offered by `opsgate init`.

View Source
const (
	// ModeKubernetes is a pod that inspects its own cluster.
	ModeKubernetes = "kubernetes"
)

Deployment modes. A mode fills in the defaults for where the server runs as a service; values written in the file still win.

Variables

Scopes lists every scope opsgate understands, in display order.

Functions

func Generate

func Generate(o InitOptions) ([]byte, error)

Generate writes a short configuration that relies on the mode for everything else, and checks it the way the server will.

func KnownScope

func KnownScope(s string) bool

KnownScope reports whether s is one of Scopes.

Types

type Approval

type Approval struct {
	// TTL bounds how long a pending web approval stays valid.
	TTL time.Duration `yaml:"ttl"`
	// Web enables browser approval links.
	// Requires auth.mode builtin (the approver signs in upstream).
	Web bool `yaml:"web"`
	// RequireWeb disables in-client elicitation, including for stdio.
	RequireWeb bool `yaml:"require_web"`
	// RequireWebDefaulted records the HTTP default so stdio can allow elicitation.
	RequireWebDefaulted bool `yaml:"-"`
	// Window is the optional lifetime of a user/tool/target auto-approval grant.
	// Zero disables grants; otherwise it must be between 1 minute and 12 hours.
	Window time.Duration `yaml:"window"`
	// WindowTools is a path.Match glob allowlist. Empty permits no grants.
	WindowTools []string `yaml:"window_tools"`
}

Approval configures human confirmation of write tools.

type Auth

type Auth struct {
	// Mode is one of builtin, external, static. Required for HTTP.
	Mode     string        `yaml:"mode"`
	Builtin  BuiltinAuth   `yaml:"builtin"`
	External ExternalAuth  `yaml:"external"`
	Static   []StaticToken `yaml:"static"`
}

Auth configures how HTTP requests are authenticated.

type BuiltinAuth

type BuiltinAuth struct {
	// StateFile persists registered clients and token hashes (mode 0600).
	StateFile string `yaml:"state_file"`
	// Users allowed to sign in. Anyone else is rejected after upstream login.
	Users           []User        `yaml:"users"`
	Upstream        Upstream      `yaml:"upstream"`
	AccessTokenTTL  time.Duration `yaml:"access_token_ttl"`
	RefreshTokenTTL time.Duration `yaml:"refresh_token_ttl"`
	// MaxClients bounds Dynamic Client Registration.
	MaxClients int `yaml:"max_clients"`
	// AllowedRedirectHosts lists redirect URI hosts that Dynamic Client
	// Registration accepts (exact host names; "localhost" also covers
	// loopback IPs and any port). Empty accepts any host.
	AllowedRedirectHosts []string `yaml:"allowed_redirect_hosts"`
	// UnknownRedirectHosts decides what happens to a registration whose
	// redirect host is not listed: "deny" (default when the list is set) or
	// "approve" (the client stays pending until an admin approves it at
	// /admin/clients). Ignored when AllowedRedirectHosts is empty.
	UnknownRedirectHosts string `yaml:"unknown_redirect_hosts"`
	// Admins are subjects allowed to approve pending clients.
	Admins []string `yaml:"admins"`
	// NotifyURL, if set, receives a JSON POST when a client awaits approval
	// (e.g. an n8n webhook that forwards it to chat).
	NotifyURL string `yaml:"notify_url"`
}

BuiltinAuth configures the embedded OAuth 2.1 authorization server.

type Config

type Config struct {
	// Mode is empty (plain defaults, stdio by default) or kubernetes.
	Mode      string    `yaml:"mode"`
	Server    Server    `yaml:"server"`
	Stdio     Stdio     `yaml:"stdio"`
	HTTP      HTTP      `yaml:"http"`
	Auth      Auth      `yaml:"auth"`
	Approval  Approval  `yaml:"approval"`
	Providers Providers `yaml:"providers"`
	Watch     Watch     `yaml:"watch"`
}

Config holds the server configuration.

func Default

func Default() Config

Default returns the configuration used when no file is given.

func DefaultFor

func DefaultFor(mode string) (Config, error)

DefaultFor returns the defaults of a deployment mode. A mode serves HTTP with builtin passkey sign-in and keeps its state in /var/lib/opsgate.

func Load

func Load(path string) (Config, error)

Load reads path on top of the defaults of its mode. Unknown keys are an error so that typos in security-relevant settings do not silently fall back.

func Parse

func Parse(data []byte, name string) (Config, error)

Parse is Load for configuration already in memory; name labels errors.

func (Config) Effective

func (c Config) Effective() ([]byte, error)

Effective renders every setting, defaults included, as YAML that Load accepts. A mode hides values the file does not spell out; this shows them.

func (Config) Issuer

func (c Config) Issuer() string

Issuer is the built-in authorization server's issuer identifier.

func (Config) ResourceURL

func (c Config) ResourceURL() string

ResourceURL is the MCP endpoint and OAuth resource identifier.

func (Config) Validate

func (c Config) Validate() error

Validate checks settings that do not depend on the transport.

func (Config) ValidateHTTP

func (c Config) ValidateHTTP() error

ValidateHTTP checks the settings required to serve over HTTP. It refuses configurations that would expose tools without authentication.

func (Config) ValidateWatch

func (c Config) ValidateWatch() error

ValidateWatch checks the settings required by `opsgate watch`.

func (Config) WatchClusters

func (c Config) WatchClusters() []KubernetesCluster

WatchClusters returns the clusters `opsgate watch` follows.

type Dev

type Dev struct {
	Enabled bool `yaml:"enabled"`
	// RunnerSocket is the dev-runner's Unix socket.
	RunnerSocket string `yaml:"runner_socket"`
}

Dev lets clients start coding agents (Codex, Claude Code, ...) on the host. opsgate never runs agents itself: it talks to `opsgate dev-runner`, a separate process under its own account whose configuration (DevRunner) alone decides which projects and agent commands exist. Starting a task needs the dev:run scope and human approval.

type DevAgent

type DevAgent struct {
	Command []string `yaml:"command"`
	// Env holds extra KEY=VALUE pairs; the environment is otherwise minimal.
	Env []string `yaml:"env"`
}

DevAgent is an agent command. Command is argv; the runner substitutes {workdir} (the task worktree) and {output} (a file for the final message). The task prompt is written to stdin, never to argv.

type DevProject

type DevProject struct {
	Name string `yaml:"name"`
	Path string `yaml:"path"`
	// BaseRef is the ref new task branches start from (default HEAD).
	BaseRef string `yaml:"base_ref"`
}

DevProject is a git repository agents may work on.

type DevRunner

type DevRunner struct {
	// Admins are exact caller subjects allowed to read and cancel every task.
	Admins []string `yaml:"admins"`
	// Socket is the Unix socket to listen on (mode 0660).
	Socket string `yaml:"socket"`
	// SocketGroup is the group allowed to connect (the opsgate server's).
	SocketGroup string `yaml:"socket_group"`
	// WorkDir holds task worktrees, logs and results.
	WorkDir  string       `yaml:"work_dir"`
	Projects []DevProject `yaml:"projects"`
	// Agents maps an agent name (e.g. "codex", "claude") to its command.
	Agents map[string]DevAgent `yaml:"agents"`
	// Timeout bounds one task.
	Timeout       time.Duration `yaml:"timeout"`
	MaxConcurrent int           `yaml:"max_concurrent"`
	// MaxTasks bounds retained task records; the oldest finished go first.
	MaxTasks int `yaml:"max_tasks"`
}

DevRunner is the configuration of `opsgate dev-runner`, kept in its own file that the opsgate server cannot write.

func LoadDevRunner

func LoadDevRunner(path string) (DevRunner, error)

LoadDevRunner reads a strict, single-document runner configuration.

func (DevRunner) Validate

func (c DevRunner) Validate() error

Validate checks the runner's allowlists and resource limits.

type ExternalAuth

type ExternalAuth struct {
	Issuer string `yaml:"issuer"`
	// Audience defaults to the MCP resource URL (PublicURL + "/mcp").
	Audience string `yaml:"audience"`
	// UserClaim names the claim used as the user identity (default "sub").
	UserClaim string `yaml:"user_claim"`
	// Users, if set, restricts and maps identities like BuiltinAuth.Users
	// with Subject "claim:<value>". Empty means scopes come from the token.
	Users []User `yaml:"users"`
}

ExternalAuth validates JWT access tokens from an existing authorization server via its JWKS.

type HTTP

type HTTP struct {
	// Listen is the TCP address, e.g. "127.0.0.1:8787".
	Listen string `yaml:"listen"`
	// PublicURL is the externally visible origin, e.g.
	// "https://mcp.example.com". The MCP endpoint is PublicURL + "/mcp"
	// and the built-in authorization server's issuer is PublicURL.
	PublicURL string `yaml:"public_url"`
}

HTTP configures the Streamable HTTP transport.

type InitOptions

type InitOptions struct {
	PublicURL string
	Login     string // LoginPasskey, LoginGoogle or LoginGitHub
	// User is a passkey name, a Google email or a GitHub login, without
	// the subject prefix. That user also approves unknown clients.
	User string
	// ClientID and ClientSecretFile configure Google or GitHub sign-in.
	ClientID         string
	ClientSecretFile string
	// Write also grants ops:write; write tools still need targets listed.
	Write          bool
	Namespaces     []string
	DenyNamespaces []string
	PodLogs        bool
	// NoteVault enables read-only notes when set.
	NoteVault string
}

InitOptions are the answers `opsgate init` turns into a configuration.

func (InitOptions) Subject

func (o InitOptions) Subject() string

Subject is the configured identity of the initial user.

type Kubernetes

type Kubernetes struct {
	Enabled bool `yaml:"enabled"`
	// Single-cluster form, kept for existing configurations.
	KubernetesCluster `yaml:",inline"`
	// Clusters is mutually exclusive with the single-cluster fields.
	Clusters []KubernetesCluster `yaml:"clusters,omitempty"`
}

Kubernetes supports either a single cluster or an ordered list of clusters.

func (Kubernetes) ClusterList

func (k Kubernetes) ClusterList() []KubernetesCluster

ClusterList returns the effective clusters. The single-cluster form gets its numeric defaults from Default(), so an explicit zero keeps its meaning there; list entries have no such defaults and treat zero as unset.

type KubernetesCluster

type KubernetesCluster struct {
	// Name is required in Clusters; the single-cluster form defaults to "default".
	Name string `yaml:"name"`
	// Protected requires fresh approval for every write.
	Protected bool `yaml:"protected"`
	// Kubeconfig path. Empty uses in-cluster config, then $KUBECONFIG,
	// then ~/.kube/config.
	Kubeconfig string `yaml:"kubeconfig"`
	Context    string `yaml:"context"`
	// Namespaces is a glob allowlist. Empty allows none; "*" allows all.
	Namespaces []string `yaml:"namespaces"`
	// DenyNamespaces wins over Namespaces.
	DenyNamespaces []string `yaml:"deny_namespaces"`
	// AllowLogs enables k8s_logs.
	AllowLogs bool `yaml:"allow_logs"`
	// ShowConfigMapData returns ConfigMap values; otherwise only keys.
	ShowConfigMapData bool `yaml:"show_configmap_data"`
	MaxLogLines       int  `yaml:"max_log_lines"`
	// Write actions. Each list holds "namespace/name" globs; empty
	// disables the tool. Namespace allow/deny rules still apply.
	RestoreImage      []string `yaml:"restore_image"`
	ActionApprovalURL string   `yaml:"action_approval_url"`
	RolloutRestart    []string `yaml:"rollout_restart"`
	Scale             []string `yaml:"scale"`
	DeletePod         []string `yaml:"delete_pod"`
	// MaxReplicas caps k8s_scale.
	MaxReplicas int32 `yaml:"max_replicas"`
}

KubernetesCluster holds connection and policy settings for one cluster.

type Note

type Note struct {
	Enabled bool `yaml:"enabled"`
	// Vault is the absolute path of the vault root.
	Vault string `yaml:"vault"`
	// Exclude holds extra vault-relative globs that are never read or
	// written. Internal folders (.obsidian, .trash, .git, sync metadata)
	// and sync-conflict copies are always excluded.
	Exclude []string `yaml:"exclude"`
	// AllowWrite registers the note write tools (create, append, replace,
	// trash). Every write still needs ops:write and human approval.
	AllowWrite bool `yaml:"allow_write"`
	// MaxNoteBytes caps the size of a note that is read or written.
	MaxNoteBytes int `yaml:"max_note_bytes"`
}

Note exposes a folder of Markdown notes (an Obsidian vault works as is) by reading files directly; no note app needs to run.

type Providers

type Providers struct {
	Kubernetes Kubernetes `yaml:"kubernetes"`
	Note       Note       `yaml:"note"`
	Dev        Dev        `yaml:"dev"`
}

Providers configures the available tool providers.

type Server

type Server struct {
	// Name reported to MCP clients.
	Name string `yaml:"name"`
	// AuditLog is a JSONL file path. Empty means audit events go to stderr.
	AuditLog string `yaml:"audit_log"`
	// MaxOutputBytes caps the text returned by a single tool call.
	MaxOutputBytes int `yaml:"max_output_bytes"`
	// ToolTimeout bounds a single tool call.
	ToolTimeout time.Duration `yaml:"tool_timeout"`
	// Tools decides which tools exist at all. Denied tools are not
	// registered, so they are absent from tools/list.
	Tools ToolPolicy `yaml:"tools"`
}

Server configures tool execution, registration and audit logging.

type StaticToken

type StaticToken struct {
	Name string `yaml:"name"`
	// SHA256 is the hex SHA-256 of the token; the token itself is never stored.
	SHA256 string   `yaml:"sha256"`
	Scopes []string `yaml:"scopes"`
	// Tools restricts this token like User.Tools.
	Tools []string `yaml:"tools"`
}

StaticToken is a pre-shared bearer token for local HTTP clients.

type Stdio

type Stdio struct {
	User   string   `yaml:"user"`
	Scopes []string `yaml:"scopes"`
}

Stdio describes the identity used for the stdio transport, where the operating system user who launched the process is the trust boundary.

type ToolPolicy

type ToolPolicy struct {
	Allow []string `yaml:"allow"`
	Deny  []string `yaml:"deny"`
}

ToolPolicy holds path.Match globs over tool names. An empty Allow allows every tool; Deny wins over Allow. Patterns that match no registered tool are a configuration error, so typos cannot silently widen access.

type Upstream

type Upstream struct {
	// Provider is "passkey" (no external identity provider), "github" or
	// "oidc" (Google: issuer https://accounts.google.com).
	Provider string `yaml:"provider"`
	// Issuer is required for oidc.
	Issuer   string `yaml:"issuer"`
	ClientID string `yaml:"client_id"`
	// ClientSecretFile holds the client secret; ClientSecretEnv names an
	// environment variable instead. Secrets are never written in YAML.
	ClientSecretFile string `yaml:"client_secret_file"`
	ClientSecretEnv  string `yaml:"client_secret_env"`
}

Upstream is the identity provider that authenticates people.

type User

type User struct {
	Subject string   `yaml:"subject"`
	Scopes  []string `yaml:"scopes"`
	// Tools optionally restricts this user to tools matching these globs,
	// on top of scopes and the server-wide policy. Empty means no extra limit.
	Tools []string `yaml:"tools"`
}

User grants scopes and optional tool restrictions to one identity. Subject is "passkey:<name>", "github:<login>", "email:<verified email>", "oidc:<sub>", or "claim:<value>" for the configured external JWT user claim.

type Watch

type Watch struct {
	Language string        `yaml:"language"`
	Outputs  []WatchOutput `yaml:"outputs,omitempty"`
	// Email delivers alerts by SMTP.
	Email WatchEmail `yaml:"email,omitempty"`
	// ApprovalURL is the public https origin of the opsgate server. When set,
	// restart suggestions link to its approval page. The link holds no secret:
	// opening it still needs sign-in and approval.
	ApprovalURL string `yaml:"approval_url"`
	// Clusters limits watching to these configured cluster names; empty
	// watches every configured cluster.
	Clusters []string `yaml:"clusters"`
	// ProblemsOnly drops informational changes (images, replicas,
	// ConfigMap keys, objects added or removed) and sends warnings only.
	ProblemsOnly bool `yaml:"problems_only"`
	// Batch is how long alerts are gathered into one webhook POST.
	Batch time.Duration `yaml:"batch"`
	// Cooldown suppresses repeats of the same warning for one object.
	Cooldown time.Duration `yaml:"cooldown"`
	// MaxAlerts caps each batch; the rest are counted as dropped.
	MaxAlerts int `yaml:"max_alerts"`
}

Watch configures `opsgate watch`, a separate long-running process that watches Kubernetes and delivers alerts. The MCP server does not use it.

type WatchEmail

type WatchEmail struct {
	Host string `yaml:"host"`
	// Port 465 uses implicit TLS; every other port requires STARTTLS.
	Port int `yaml:"port"`
	// Username and PasswordFile are set together, or not at all for a relay
	// that needs no authentication.
	Username     string   `yaml:"username"`
	PasswordFile string   `yaml:"password_file"`
	From         string   `yaml:"from"`
	To           []string `yaml:"to"`
	// Batch is how long alerts are gathered into one message.
	Batch time.Duration `yaml:"batch"`
	// ProblemsOnly sends warnings only by email.
	ProblemsOnly bool `yaml:"problems_only"`
}

WatchEmail configures SMTP delivery, enabled by Host.

func (WatchEmail) IsZero

func (e WatchEmail) IsZero() bool

IsZero omits disabled email from effective configuration.

type WatchOutput

type WatchOutput struct {
	Name             string            `yaml:"name"`
	Language         string            `yaml:"language,omitempty"`
	Type             string            `yaml:"type"` // webhook (default) or discord
	URL              string            `yaml:"url,omitempty"`
	URLFile          string            `yaml:"url_file,omitempty"`
	Headers          map[string]string `yaml:"headers,omitempty"`
	HeaderFiles      map[string]string `yaml:"header_files,omitempty"`
	SecretFile       string            `yaml:"secret_file,omitempty"`
	BodyTemplate     string            `yaml:"body_template,omitempty"`
	AllowPrivateHTTP bool              `yaml:"allow_private_http"`
	ProblemsOnly     bool              `yaml:"problems_only"`
}

WatchOutput delivers JSON directly to a receiver. Each output has its own queue.

func (WatchOutput) ValidateURL

func (o WatchOutput) ValidateURL(value string) error

ValidateURL checks a URL loaded from a file without exposing its contents.

Jump to

Keyboard shortcuts

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