config

package
v0.6.6 Latest Latest
Warning

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

Go to latest
Published: May 13, 2026 License: AGPL-3.0 Imports: 4 Imported by: 0

Documentation

Overview

Package config loads the identity service configuration from environment variables with the GATEWAY_ prefix.

This is the Go port of backend/api_gateway/config.py. It uses os.Getenv with typed defaults — no external config library needed. Sensitive values (secrets, encryption keys, client secrets) are never logged.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// Server
	GRPCPort    int
	ConnectPort int
	MetricsPort int

	// Persistence driver. Selects which Repository / DB
	// implementation the binary wires up — "entdb" (default), "memory"
	// for an in-process store useful for local dev, or "postgres"
	// once the Postgres driver lands. Driven by GATEWAY_REPO_DRIVER.
	RepoDriver string

	// EntDB
	EntDBAddress string

	// Tenant
	DefaultTenantID string

	// Email service (internal gRPC)
	EmailServiceHost string
	EmailServicePort int

	// JWT (RS256)
	// JSON array: [{"kid":"k1","private_key_pem":"...","public_key_pem":"...","active":true}]
	// If empty and running locally, an ephemeral RSA key is auto-generated.
	JWTKeys          string
	JWTExpirySeconds int

	// JWT audience. When non-empty, minted access tokens carry this as
	// the "aud" claim and the verifier enforces a match. When
	// JWTRequireAudience is true, tokens with no "aud" claim are also
	// rejected; the false default exists so a deploy can roll out the
	// mint-side change first, wait for in-flight tokens to expire, then
	// flip to required.
	JWTAudience        string
	JWTRequireAudience bool

	// Refresh tokens
	RefreshExpirySeconds int

	// OAuth providers. Identity does the code exchange for these
	// providers itself — see pkg/oauth. A provider is enabled only
	// when BOTH the ID and secret are non-empty.
	GoogleClientID        string
	GoogleClientSecret    string
	MicrosoftClientID     string
	MicrosoftClientSecret string
	MicrosoftTenantID     string
	GitHubClientID        string
	GitHubClientSecret    string

	// Identity Verification (document + selfie). The provider name
	// selects the implementation in pkg/idv. Empty disables IDV; the
	// RPCs return CodeUnimplemented to clients in that case.
	IDVProvider           string // "azure", "stub", or "" (disabled)
	IDVAzureEndpoint      string // e.g. https://my-face.cognitiveservices.azure.com
	IDVAzureKey           string // Cognitive Services key
	IDVAzureSessionTTLSec int    // session token lifetime; default 600
	// When true, PasswordLogin / OAuthLogin reject users without an
	// approved identity verification. The default is false (verification
	// is offered but not required) to match the existing email-verified
	// pattern. Tenants that need stricter onboarding flip this on.
	IDVRequired bool

	// Password
	PasswordSignupEnabled      bool
	PasswordResetEnabled       bool
	PasswordResetExpirySeconds int

	// TOTP (2FA)
	// 32-byte key, base64-encoded. Required in prod; dev falls back to
	// a deterministic throwaway key.
	TOTPEncryptionKey string
	TOTPIssuer        string

	// Pepper used as the HMAC-SHA-256 key for recovery-code hashing.
	// Base64-encoded; must decode to >= 32 bytes. Required whenever
	// TOTPEncryptionKey is set (i.e. any non-dev deployment). The
	// pepper turns a stolen DB into a brute-force-resistant artifact:
	// without it, an attacker cannot precompute or enumerate hashes.
	TOTPRecoveryPepper string

	// Login challenge (how long after password success user has to complete 2FA)
	LoginChallengeExpirySeconds int

	// WebAuthn / Passkeys
	PasskeyRPID                   string
	PasskeyRPName                 string
	PasskeyOrigin                 string
	PasskeyChallengeExpirySeconds int

	// QR Login (cross-device authorization)
	QRLoginBaseURL       string
	QRLoginExpirySeconds int

	// Login security (failed-login lockout)
	LoginMaxFailedAttempts int
	LoginLockoutSeconds    int

	// Default email domain
	DefaultEmailDomain string

	// CORS
	AllowedOrigins string

	// Cookie settings
	CookieDomain   string
	CookieSecure   bool
	CookieSameSite string

	// Dev-only
	AuthAllowLocal bool

	// SMTP single-provider config (simple form). If SMTPProviders is set,
	// that takes precedence.
	SMTPHost string // GATEWAY_SMTP_HOST
	SMTPPort int    // GATEWAY_SMTP_PORT (default 587)
	SMTPUser string // GATEWAY_SMTP_USER
	SMTPPass string // GATEWAY_SMTP_PASS
	SMTPFrom string // GATEWAY_SMTP_FROM
	SMTPTLS  bool   // GATEWAY_SMTP_TLS (default true)

	// SMTP multi-provider JSON. If set, parsed as []email.SMTPConfig and
	// used as a chain in order. Overrides the single-provider env vars.
	SMTPProviders string // GATEWAY_SMTP_PROVIDERS

	// Public app URLs used in email links.
	AppBaseURL string // GATEWAY_APP_BASE_URL — e.g. "https://app.example.com"

	// How long an email-verification or password-reset token is valid for.
	EmailTokenExpirySeconds int // GATEWAY_EMAIL_TOKEN_EXPIRY_SECONDS (default 86400)

	// Per-recipient cooldown between transactional email sends. Defeats
	// inbox-bombing via repeated unauthenticated RequestPasswordReset /
	// SendEmailVerification calls. In-memory per replica.
	EmailSendCooldownSeconds int // GATEWAY_EMAIL_SEND_COOLDOWN_SECONDS (default 60)

	// Per-email cooldown on PasswordSignup. Throttled signups return
	// the same anti-enumeration decoy as a duplicate-email signup so the
	// endpoint cannot be used to probe for which addresses are
	// rate-limited (which would itself reveal recent attempts).
	// Complements the per-IP rate limit at the middleware layer.
	SignupEmailCooldownSeconds int // GATEWAY_SIGNUP_EMAIL_COOLDOWN_SECONDS (default 60)

	// Audit log queue depth for the async flusher. Drops happen if the
	// auth hot path produces events faster than EntDB can absorb them.
	// Surface via audit.Logger.DroppedCount() on a metric.
	AuditQueueSize int // GATEWAY_AUDIT_QUEUE_SIZE (default 4096)

	// Maximum HTTP request body size in bytes, enforced via
	// http.MaxBytesHandler so a slow-POST / oversize-payload attacker
	// can't exhaust memory. Default 1 MiB — auth RPC bodies are tiny.
	HTTPMaxBodyBytes int64 // GATEWAY_HTTP_MAX_BODY_BYTES (default 1048576)

	// Trusted proxies: comma-separated list of CIDRs whose
	// X-Forwarded-For headers the service will honour. Anything outside
	// these ranges is treated as an untrusted client and its forwarded
	// headers are ignored — TCP peer IP is used instead.
	TrustedProxies string // GATEWAY_TRUSTED_PROXIES (default "10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,127.0.0.1/32,::1/128")

	// Rate-limit configuration. The in-memory token bucket is keyed by
	// client IP. quotas are requests-per-window per IP. Set to 0 to
	// disable the per-endpoint limiter.
	RateLimitWindowSeconds int // GATEWAY_RATE_LIMIT_WINDOW_SECONDS (default 60)
	RateLimitSignupPerIP   int // GATEWAY_RATE_LIMIT_SIGNUP_PER_IP (default 10/min)
	RateLimitLoginPerIP    int // GATEWAY_RATE_LIMIT_LOGIN_PER_IP (default 30/min)
	RateLimitResetPerIP    int // GATEWAY_RATE_LIMIT_RESET_PER_IP (default 5/min)
	RateLimitVerifyPerIP   int // GATEWAY_RATE_LIMIT_VERIFY_PER_IP (default 20/min)

	// Postgres (alternate persistence driver). When PostgresDSN is set
	// the application bootstrapper may prefer the Postgres-backed
	// repository over EntDB; the actual driver selection lives in the
	// internal/repo package.
	//
	//   GATEWAY_POSTGRES_DSN          e.g. "postgres://user:pass@host:5432/identity?sslmode=disable"
	//   GATEWAY_POSTGRES_MAX_CONNS    pool size, default 25
	//   GATEWAY_POSTGRES_AUTO_MIGRATE run pending migrations on connect, default false
	//                                 (production: run migrations out-of-band as a
	//                                  separate Job; setting this true on a rolling
	//                                  deploy can race multiple replicas).
	PostgresDSN         string
	PostgresMaxConns    int
	PostgresAutoMigrate bool
}

Config holds all identity service configuration.

func Load

func Load() *Config

Load reads configuration from environment variables with GATEWAY_ prefix, falling back to sensible defaults for local development.

func (*Config) EmailServiceAddress

func (c *Config) EmailServiceAddress() string

EmailServiceAddress returns the host:port for the email service.

func (*Config) JWTExpiry

func (c *Config) JWTExpiry() time.Duration

JWTExpiry returns the JWT expiry as a time.Duration.

func (*Config) PasswordResetExpiry

func (c *Config) PasswordResetExpiry() time.Duration

PasswordResetExpiry returns the password reset expiry as a time.Duration.

func (*Config) RefreshExpiry

func (c *Config) RefreshExpiry() time.Duration

RefreshExpiry returns the refresh token expiry as a time.Duration.

Jump to

Keyboard shortcuts

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