api

package
v0.12.14-0...-77740bd Latest Latest
Warning

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

Go to latest
Published: Jul 22, 2026 License: AGPL-3.0 Imports: 51 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Run

func Run(ctx context.Context, cfg Config) error

nolint:gocognit

Types

type AuthConfig

type AuthConfig interface {
	// contains filtered or unexported methods
}

AuthConfig is a discriminated union for one authentication resolver. Implementations are selected from TOML auth entries by their type field.

type AuthConfigs

type AuthConfigs []AuthConfig

AuthConfigs is the ordered authentication resolver chain.

func (*AuthConfigs) UnmarshalTOML

func (a *AuthConfigs) UnmarshalTOML(v any) error

UnmarshalTOML decodes the auth array into concrete auth config entries.

type ClickHouseConfig

type ClickHouseConfig struct {
	// URL is the ClickHouse connection string for the shared analytics cluster.
	// When empty, analytics writes are silently discarded.
	// Example: "clickhouse://default:password@clickhouse:9000?secure=false&skip_verify=true"
	URL string `toml:"url"`

	// AnalyticsURL is the base URL for workspace-specific analytics connections.
	// Unlike URL, this endpoint receives per-workspace credentials injected at
	// connection time by the analytics service. Only used when both this field
	// and a [VaultConfig] are configured.
	// Example: "http://clickhouse:8123/default"
	AnalyticsURL string `toml:"analytics_url"`
}

ClickHouseConfig configures connections to ClickHouse for analytics storage. All fields are optional; when URL is empty, a no-op analytics backend is used.

type Config

type Config struct {
	// InstanceID identifies this particular API server instance. Used in log
	// attribution, Kafka consumer group membership, and cache invalidation
	// messages so that a node can ignore its own broadcasts.
	InstanceID string `toml:"instance_id"`

	// Platform identifies the cloud platform where this node runs. Examples
	// include "aws", "gcp", "hetzner", and "kubernetes". Appears in structured
	// logs and metrics labels for filtering by infrastructure.
	Platform string `toml:"platform"`

	// Image is the container image identifier, such as "unkey/api:v1.2.3".
	// Logged at startup for correlating deployments with behavior changes.
	Image string `toml:"image"`

	// HttpPort is the TCP port the API server binds to. Ignored when
	// [TestConfig.Listener] is set, which is the case in test harnesses that
	// use ephemeral ports.
	HttpPort int `toml:"http_port" config:"default=7070,min=1,max=65535"`

	// Region is the geographic region identifier, such as "us-east-1" or "eu-west-1".
	// Included in structured logs and used by the key service when recording
	// which region served a verification request.
	Region string `toml:"region" config:"default=unknown"`

	// RedisURL is the connection string for the Redis instance backing
	// distributed rate limiting counters and usage tracking.
	// Example: "redis://redis:6379"
	RedisURL string `toml:"redis_url" config:"required,nonempty"`

	Observability config.Observability `toml:"observability"`

	// MaxRequestBodySize caps incoming request bodies at this many bytes.
	// The zen server rejects requests exceeding this limit with a 413 status.
	// Set to 0 or negative to disable the limit. Defaults to 10 MiB.
	MaxRequestBodySize int64 `toml:"max_request_body_size" config:"default=10485760"`

	// Database configures MySQL connections. See [config.DatabaseConfig].
	Database config.DatabaseConfig `toml:"database"`

	// ClickHouse configures analytics storage. See [ClickHouseConfig].
	ClickHouse ClickHouseConfig `toml:"clickhouse"`

	// TLS provides filesystem paths for HTTPS certificate and key.
	// See [config.TLSFiles].
	TLS config.TLS `toml:"tls"`

	// Vault configures the encryption/decryption service. See [config.VaultConfig].
	Vault config.VaultConfig `toml:"vault"`

	// Control configures the deployment management service. See [config.ControlConfig].
	Control config.ControlConfig `toml:"control"`

	// PortalBaseURL is the base URL for the customer portal.
	// Example: "https://portal.unkey.com"
	// Used to construct session redirect URLs in portal.createSession responses.
	// When a customer has a verified custom domain, that domain is used instead.
	PortalBaseURL string `toml:"portal_base_url" config:"default=https://portal.unkey.com"`

	// Auth configures the ordered authentication resolver chain.
	Auth AuthConfigs `toml:"auth"`

	// Pprof configures Go profiling endpoints. See [config.PprofConfig].
	// When nil (section omitted), pprof endpoints are not registered.
	Pprof *config.PprofConfig `toml:"pprof"`

	// Clock provides time operations and is injected for testability. Production
	// callers set this to [clock.New]; tests can substitute a fake clock to
	// control time progression.
	Clock clock.Clock `toml:"-"`

	// TLSConfig is the resolved [tls.Config] built from [TLSFiles.CertFile]
	// and [TLSFiles.KeyFile] at startup. This field is populated by the CLI
	// entrypoint after loading the config file and must not be set in TOML.
	TLSConfig *tls.Config `toml:"-"`

	// Test groups runtime-only overrides for integration tests. All fields are
	// zero in production and cannot be set from TOML.
	Test TestConfig `toml:"-"`
}

Config holds the complete configuration for the API server. It is designed to be loaded from a TOML file using config.Load:

cfg, err := config.Load[api.Config]("/etc/unkey/api.toml")

Environment variables are expanded in file values using ${VAR} syntax before parsing. Struct tag defaults are applied to any field left at its zero value after parsing, and validation runs automatically via Config.Validate.

Several fields, Clock, TLSConfig, and the TestConfig group, are runtime-only and cannot be set through a config file. They are tagged toml:"-" and must be set programmatically after loading.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks cross-field constraints that cannot be expressed through struct tags alone. It implements config.Validator so that config.Load calls it automatically after tag-level validation.

Validate rejects TLS configuration that provides only one certificate path.

type JWTAuthConfig

type JWTAuthConfig struct {
	// Issuer is the expected JWT iss claim for this auth entry.
	Issuer string `toml:"issuer"`

	// Audience is the optional JWT aud claim required for this auth entry.
	Audience string `toml:"audience"`

	// Secrets configures HS256 verification. Dashboard proxy routes sign tokens
	// with the first configured secret. The API verifies incoming tokens against
	// every secret in the ordered list so a new secret can be added before
	// removing an old one.
	Secrets []string `toml:"secrets"`

	// JWKSURL configures RS256 verification. The API fetches the JSON Web Key
	// Set from this URL on first use, verifies incoming tokens against the
	// returned RSA signing keys, and refetches the set when a token fails
	// verification against every cached key so key rotations are picked up
	// without a restart.
	JWKSURL string `toml:"jwks_url"`

	// Provider names the permission dialect carried by this entry's tokens.
	// Empty means tokens already carry canonical Unkey permissions. "workos"
	// means tokens carry WorkOS slugs that the resolver translates into Unkey
	// permissions after verification. This is an explicit opt-in rather than
	// an inference from the issuer, so any issuer (including custom auth
	// domains) can be configured without changing how translation is selected.
	Provider string `toml:"provider"`
}

JWTAuthConfig configures JWT bearer authentication.

type PortalSessionAuthConfig

type PortalSessionAuthConfig struct{}

PortalSessionAuthConfig configures portal browser-session authentication.

type RootKeyAuthConfig

type RootKeyAuthConfig struct {
	// Enabled may be set to true for explicitness. Setting it to false is a
	// configuration error; remove the auth entry instead.
	Enabled *bool `toml:"enabled"`
}

RootKeyAuthConfig configures root-key bearer authentication.

type TestConfig

type TestConfig struct {
	// Enabled relaxes certain security checks and trusts client-supplied
	// headers like X-Test-Time that would normally be rejected.
	Enabled bool

	// Counter overrides the distributed counter backend. Multi-node tests
	// share one in-memory counter across all nodes so replays sync in
	// microseconds rather than blocking on real Redis I/O.
	Counter counter.Counter

	// Listener is a pre-created net.Listener for the HTTP server. When set,
	// the server uses this listener instead of binding to HttpPort. Tests
	// use ephemeral ports (":0") to avoid conflicts when running in parallel.
	Listener net.Listener
}

TestConfig groups runtime-only flags and overrides used by integration tests. All fields are zero in production; setting any of them enables test-specific behavior that MUST NOT be reachable from a TOML config file.

Directories

Path Synopsis
internal
auditactor
Package auditactor maps an authenticated principal to the actor recorded on audit logs.
Package auditactor maps an authenticated principal to the actor recorded on audit logs.
deployment
Package deployment maps a stored deployment row onto the openapi.Deployment wire type shared by the deployment read endpoints (getDeployment, listDeployments).
Package deployment maps a stored deployment row onto the openapi.Deployment wire type shared by the deployment read endpoints (getDeployment, listDeployments).
environment
Package environment maps stored app settings onto the openapi.Environment wire type shared by the environment read endpoints.
Package environment maps stored app settings onto the openapi.Environment wire type shared by the environment read endpoints.
pagination
Package pagination implements the cursor pagination idiom shared by the v2 list endpoints:
Package pagination implements the cursor pagination idiom shared by the v2 list endpoints:
policyconfig
Package policyconfig owns the encode and decode rules for stored policy config blobs so the storage contract lives in one place.
Package policyconfig owns the encode and decode rules for stored policy config blobs so the storage contract lives in one place.
portalscope
Package portalscope resolves the external identity a portal route must scope to.
Package portalscope resolves the external identity a portal route must scope to.
testutil
Package testutil provides integration test infrastructure for the API service.
Package testutil provides integration test infrastructure for the API service.
testutil/seed
Package seed provides database seeding utilities for integration tests.
Package seed provides database seeding utilities for integration tests.
Package openapi provides primitives to interact with the openapi HTTP API.
Package openapi provides primitives to interact with the openapi HTTP API.

Jump to

Keyboard shortcuts

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