Skip to content

Configuration

Every SecurityConfig field with its type, default, and effect. The canonical field names are the snake_case python names (the cross-language interop surface, spec 02): the Kotlin properties are the camelCase forms, and adapters bind them idiomatically (Spring relaxed binding maps guard.redis-url to redisUrl; Ktor takes the builder or the Kotlin property names). Types and defaults are normative; a conformant build with default config behaves as the reference with default config.

Generated by docs/tools/w8d_config_docs.py from ConfigFieldRegistry.kt (the ported reference field table) joined with the spec 02 field semantics. Re-run it whenever the registry or spec 02 changes; a field that exists in code but not here is a defect.

Network / proxy

Field Kotlin property Type Default Effect
trusted_proxies trustedProxies str list (IP or CIDR; "unix" allowed) [] Peers trusted to set X-Forwarded-For. Entries are normalized to canonical IP/CIDR string form at validation. /0 entry logs a warning (spoof risk) but is accepted.
trusted_proxy_depth trustedProxyDepth int 1 Number of proxies expected in the X-Forwarded-For chain. MUST be >= 1; 0 or negative rejected.
trust_x_forwarded_proto trustXForwardedProto bool false When true, HTTPS detection consults X-Forwarded-Proto; otherwise only the URL scheme.
whitelist whitelist str list (IP/CIDR) or none null Non-empty = restrictive: only listed IPs pass the global IP check. An explicit whitelist match overrides the blacklist; dynamic IP bans still apply. null (not empty) means "no whitelist".
blacklist blacklist str list (IP/CIDR) [] Blocked IPs/CIDRs. Enforced ahead of country and cloud checks; overridden by an explicit whitelist match. Entries normalized to canonical form.
## Redis / distributed state
Field Kotlin property Type Default Effect
enable_redis enableRedis bool true Enables distributed state (shared bans, counters, caches). Requires the redis optional package; see Capability gating.
redis_url redisUrl str or none "redis://localhost:6379" Connection URL.
redis_prefix redisPrefix str "guard_core:" Prefix on every Redis key (section 08 key names embed it).
redis_socket_connect_timeout redisSocketConnectTimeout float or none, > 0 (gt=0.0) 2.0 Seconds to wait for a TCP connection. MUST be > 0 (0 = non-blocking mode, not "no timeout"). null disables the timeout.
redis_socket_timeout redisSocketTimeout float or none, > 0 (gt=0.0) 2.0 Seconds to wait per read/write. MUST be > 0. null = no timeout.
redis_health_check_interval redisHealthCheckInterval int, >= 0 (ge=0) 30 Seconds between pooled-connection health checks; 0 disables.
redis_max_connections redisMaxConnections int or none, >= 1 (ge=1) null Connection-pool cap; null = backend default.
redis_retries redisRetries int, >= 0 (ge=0) 1 Retries with exponential backoff on transient connection/timeout errors before surfacing; 0 disables.
redis_fail_open redisFailOpen bool false On Redis unavailability, skip the failing check and let the request through instead of honoring fail_secure. Default false: fail_secure governs every check failure including Redis outages.
## IP banning / penalties
Field Kotlin property Type Default Effect
enable_ip_banning enableIpBanning bool true Master switch for IP banning.
auto_ban_threshold autoBanThreshold int, >= 1 (ge=1) 10 Suspicious-request count that triggers auto-ban.
auto_ban_duration autoBanDuration int, >= 1 (ge=1) 3600 Auto-ban duration in seconds.
threat_ban_config threatBanConfig map of category → {threshold: int >= 1, duration: int >= 1} {} Per-category overrides of auto_ban_threshold/auto_ban_duration. Valid categories: the penetration-detection categories (see enabled_detection_categories) plus the pseudo-category "rate_limit". Unknown category keys: rejected. Unlisted categories fall back to the flat thresholds.
enable_rate_limit_auto_ban enableRateLimitAutoBan bool false Feed rate-limit violations into the auto-ban engine: each active-mode violation increments the "rate_limit" suspicious count and runs the same threshold logic (threat_ban_config["rate_limit"] first, then flat). Requires enable_ip_banning to actually ban.
## Geo / countries
Field Kotlin property Type Default Effect
whitelist_countries whitelistCountries str set (ISO 3166-1 alpha-2) [] Non-empty = restrictive: only listed countries pass; unresolved country is blocked. Overrides blocked_countries (setting both warns).
blocked_countries blockedCountries str set [] Countries always blocked.
geo_ip_handler geoIpHandler handler or none null GeoIP provider (section 01 surface). Auto-resolved at validation when country rules exist and this is null (see Validation semantics).
ipinfo_token ipinfoToken str or none null IPInfo API token for geolocation download.
ipinfo_db_path ipinfoDbPath path "data/ipinfo/country_asn.mmdb" Local MMDB file path.
geo_ip_db_max_age geoIpDbMaxAge int, 3600–604800 (ge=3600, le=604800) 86400 Max age in seconds of the IPInfo MMDB before re-download.
## Cloud providers
Field Kotlin property Type Default Effect
block_cloud_providers blockCloudProviders str set or none null Providers to block. Valid names: AWS, GCP, Azure, DigitalOcean, Linode, Vultr. A bare name blocks the whole provider; "<name>:!<region>" blocks the provider except that region. Region data exists for AWS and GCP only; a carve-out on other providers exempts nothing. Unknown provider names: rejected.
cloud_ip_refresh_interval cloudIpRefreshInterval int, 60–86400 (ge=60, le=86400) 3600 Seconds between cloud IP range refreshes.
cloud_ip_store cloudIpStore store instance, store factory, or none null Override for the shared cloud-IP cache (section 01 surface). null = auto-construct the Redis-backed store when Redis is enabled. A factory is a callable taking the redis handler and returning a store (defers construction).
lazy_init lazyInit bool true Defer cloud-IP HTTP fetches and geo MMDB downloads to a background task. Effective only when Redis is enabled AND the adapter wires the deferred-init startup hook; otherwise cloud/geo init happens on demand and this flag is inert. First requests may see partially populated ranges.
## Rate limiting
Field Kotlin property Type Default Effect
enable_rate_limiting enableRateLimiting bool true Master switch for rate limiting.
rate_limit rateLimit int 10 Max requests per rate_limit_window.
rate_limit_window rateLimitWindow int 60 Window in seconds.
endpoint_rate_limits endpointRateLimits map of endpoint str → (requests int, window int) {} Per-endpoint overrides; normally populated by dynamic rules.
## Detection / penetration
Field Kotlin property Type Default Effect
enable_penetration_detection enablePenetrationDetection bool true Master switch.
enabled_detection_categories enabledDetectionCategories str set all categories Subset of: xss, sqli, dir_traversal, path_traversal, cmd_injection, file_inclusion, ldap, xml, ssrf, nosql, file_upload, template, http_split, sensitive_file, cms_probing, recon, proto_pollution, code_injection, deserialization. Unknown names: rejected. Empty set while detection is on: warning (detection enabled but never matches).
excluded_detection_headers excludedDetectionHeaders str set {} Headers exempted from the categories known to false-positive on their typical values (identity/proxy headers skip ssrf only); other categories still scan them. Merged with the hardcoded default exclusion set.
excluded_semantic_detection_headers excludedSemanticDetectionHeaders str set {} Opt-in header names whose values skip the semantic analyzer only, matched case-insensitively. Regex category scanning of these headers is unchanged. Useful when a JWT session cookie scores near detection_semantic_threshold (for example cookie, authorization). Can also be set per route with detectionExclusion(semanticHeaders = ...).
excluded_detection_params excludedDetectionParams str set {} Query parameters excluded from detection scanning.
excluded_detection_body_fields excludedDetectionBodyFields str set {} JSON body keys excluded from detection scanning, matched at any nesting depth; also applied to form-urlencoded and multipart text-part field names.
detection_scan_body detectionScanBody bool true Scan the request body. False: detection restricted to path, query, headers; the body is never read.
detection_max_body_inspect_bytes detectionMaxBodyInspectBytes int, 1024–10485760 (ge=1024, le=10485760) 262144 Max bytes read from the start of the request body for detection. Only this prefix is scanned; payloads beyond it, or split across the boundary, are not detected. Also bounds gzip-bomb decompression. Without a bounded body reader (section 01.2), the body is not read at all and detection falls back to path/query/headers; either way a one-time warning names the cap, the client, and which happened.
detection_max_content_length detectionMaxContentLength int, 1000–100000 (ge=1000, le=100000) 10000 Budget for the semantic (ML) analyzer slice of preprocessed content and the divisor for retained attack-indicator regions during truncation. Does NOT bound the regex scan window (that is detection_max_body_inspect_bytes).
detection_max_scan_values detectionMaxScanValues int, 2–100000 (ge=2, le=100000) 512 Max individual values (query params, header values, JSON keys/leaf values, form fields, multipart parts) scanned per request; each value costs two units (name + value). Beyond the cap, remaining values are not scanned; one-time warning names the client IP.
detection_max_scan_chars detectionMaxScanChars int, 1024–262144 (ge=1024, le=262144) 65536 Max total characters across every value handed to the pattern engine per request. Beyond the cap: same fail-open + warning as above.
detection_max_scan_seconds detectionMaxScanSeconds float, 0.1–60.0 (ge=0.1, le=60.0) 10.0 Cap on the CPU time (seconds) spent regex scanning one request, not wall time, summed across every field and every pattern. Once reached, remaining patterns and values are not scanned and the request receives a weighted pattern_timeout threat that counts toward the anomaly score, so padding a request cannot skip detection.
detection_max_json_depth detectionMaxJsonDepth int, 1–1000 (ge=1, le=1000) 32 Max JSON nesting depth walked structurally. At the cap, the value is serialized to text and scanned as one value (still scanned, bounded by detection_max_content_length); one-time warning.
detection_preserve_attack_patterns detectionPreserveAttackPatterns bool true Preserve attack patterns during content truncation.
detection_semantic_threshold detectionSemanticThreshold float, 0.0–1.0 (ge=0.0, le=1.0) 0.7 Semantic attack-detection threshold.
detection_anomaly_threshold detectionAnomalyThreshold float, 1.0–10.0 (ge=1.0, le=10.0) 3.0 Standard deviations from mean to flag an anomaly.
detection_threat_score_threshold detectionThreatScoreThreshold float, 0.0–10.0 (ge=0.0, le=10.0) 1.0 Anomaly score required to flag a request as a threat.
detection_slow_pattern_threshold detectionSlowPatternThreshold float, 0.01–1.0 (ge=0.01, le=1.0) 0.1 Execution time (seconds) to consider a pattern slow.
detection_monitor_history_size detectionMonitorHistorySize int, 100–10000 (ge=100, le=10000) 1000 Recent metrics kept in history.
detection_max_tracked_patterns detectionMaxTrackedPatterns int, 100–5000 (ge=100, le=5000) 1000 Max patterns tracked for performance.
detection_anomaly_emission_cooldown detectionAnomalyEmissionCooldown float, 1.0–3600.0 (ge=1.0, le=3600.0) 60.0 Min seconds between anomaly events for the same pattern.
detection_min_samples_for_anomaly detectionMinSamplesForAnomaly int, 10–1000 (ge=10, le=1000) 30 Samples recorded before anomaly detection engages.
detection_compiler_timeout detectionCompilerTimeout float, 0.1–10.0 (ge=0.1, le=10.0) 2.0 Timeout for pattern compilation and matching (seconds).
## Behavioral rules
Field Kotlin property Type Default Effect
global_behavior_rules globalBehaviorRules rule list [] Behavior rules applied to every route in addition to decorator rules (section 12).
behavior_scan_response_body behaviorScanResponseBody bool false When false, no response body is ever read for pattern matching and non-status: return_pattern rules can never match; construction rejects such a rule instead of accepting a silent no-op.
behavior_max_response_body_inspect_bytes behaviorMaxResponseBodyInspectBytes int, 1024–10485760 (ge=1024, le=10485760) 262144 Max bytes of response body retained for return_pattern inspection. Bounds what is retained, not what the app produces: the reader must deliver the full body afterward (section 01.4).
body_read_timeout bodyReadTimeout float, > 0, <= 30.0 (gt=0.0, le=30.0) 3.0 Seconds to wait for an adapter's body read (request-detection read and response-behavior read) before treating the body as unavailable (fail-closed, same as an adapter raising).
sync_body_read_max_concurrent syncBodyReadMaxConcurrent int, 1–10000 (ge=1, le=10000) 64 Max concurrent blocked synchronous body reads before further attempts give up and log exhaustion. Applies to sync-only deployments.
## User agents
Field Kotlin property Type Default Effect
blocked_user_agents blockedUserAgents str list [] User-agent patterns to block. Each pattern MUST pass the pattern-safety (ReDoS) validator; unsafe patterns: rejected.
## HTTPS / passive / failure policy
Field Kotlin property Type Default Effect
enforce_https enforceHttps bool false Redirect HTTP requests to HTTPS.
passive_mode passiveMode bool false Log-only mode: no request is ever blocked; violations are logged/flagged only.
fail_secure failSecure bool true On an unexpected exception in any check: true = block with 500 (check bugs surface); false = log and fall through (fail-open, staging diagnostics only).
route_resolution_strict routeResolutionStrict bool false Block (500) when the adapter cannot resolve the route. False lets unrouted/undecorated requests through with global checks only.
exclude_paths excludePaths str list ["/docs", "/redoc", "/openapi.json", "/openapi.yaml", "/favicon.ico", "/static"] Paths excluded from security checks. Each entry MUST normalize (reject malformed percent-encoding/invalid UTF-8); an entry that normalizes to / is rejected unless it is the literal /, which is accepted with a warning (excludes the whole application).
## Headers / responses / CORS
Field Kotlin property Type Default Effect
security_headers securityHeaders map or none see below Header configuration. Default: {enabled: true, hsts: {max_age: 31536000, include_subdomains: true, preload: false}, csp: null, frame_options: "SAMEORIGIN", content_type_options: "nosniff", xss_protection: "1; mode=block", referrer_policy: "strict-origin-when-cross-origin", permissions_policy: "geolocation=(), microphone=(), camera=()", custom: null}.
custom_error_responses customErrorResponses map of int (status) → str {} Custom response bodies per HTTP status code.
custom_response_modifier customResponseModifier callable(response) → response or none null Applied to every response before send.
custom_request_check customRequestCheck callable(request) → response-or-none or none null Extra per-request check; a returned response blocks.
auth_verifier authVerifier callable or none null Default verifier for auth decorators: verifier(request, credential) -> Principal | null.
enable_cors enableCors bool false CORS handling on/off.
cors_allow_origins corsAllowOrigins str list ["*"] Allowed origins.
cors_allow_methods corsAllowMethods str list ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"] Allowed methods.
cors_allow_headers corsAllowHeaders str list ["*"] Allowed headers.
cors_allow_credentials corsAllowCredentials bool false Allow credentials in CORS.
cors_expose_headers corsExposeHeaders str list [] Headers exposed to browsers.
cors_max_age corsMaxAge int 600 Preflight max-age in seconds.
## Logging / observability
Field Kotlin property Type Default Effect
custom_log_file customLogFile str or none null Path of a custom log file for security events.
log_suspicious_level logSuspiciousLevel enum INFO/DEBUG/WARNING/ERROR/CRITICAL or none "WARNING" Level for suspicious-request logs.
log_request_level logRequestLevel same enum or none null Level for request logs; null = off.
log_country_check_level logCountryCheckLevel same enum or none "INFO" Level for non-blocking country verdicts. Blocked-country hits log at log_suspicious_level; no-rules and no-geolocation cases always log at DEBUG.
log_format logFormat enum text/json "text" Log output format.
muted_event_types mutedEventTypes str set {} Event types suppressed from telemetry dispatch. Values MUST be from the event-type vocabulary (section 10); unknown: rejected.
muted_metric_types mutedMetricTypes str set {} Metric types suppressed. Valid: response_time, request_count, error_rate. Unknown: rejected.
muted_check_logs mutedCheckLogs str set {} Check names muted from pipeline logging. Values MUST be from the check-name vocabulary (section 03); unknown: rejected.
log_sensitive_headers logSensitiveHeaders str set {} Header names redacted from guard log lines, case-insensitive; merged with the hardcoded default set. Bare-string input: rejected (must be a collection).
log_sensitive_params logSensitiveParams str set {} Query parameter names whose values are redacted from logs, case-insensitive; merged with defaults. Same rejection rule.
log_sensitive_body_fields logSensitiveBodyFields str set {} Body field names redacted from detection log lines (JSON keys at any depth, form-urlencoded and multipart text-part names), case-insensitive; merged with defaults. Same rejection rule.
enable_otel enableOtel bool false OpenTelemetry export (requires otel extra; inert without it).
otel_service_name otelServiceName str "guard-core" OTel resource service name.
otel_exporter_endpoint otelExporterEndpoint str or none null OTLP HTTP endpoint.
otel_resource_attributes otelResourceAttributes map of str → str {} Additional OTel resource attributes.
enable_logfire enableLogfire bool false Logfire export (requires logfire extra; inert without it).
logfire_service_name logfireServiceName str "guard-core" Logfire service name.
enable_enrichment enableEnrichment bool false Populate guard.* metadata (project identity, deterministic threat score, matched dynamic rule, per-IP correlation keys) on every event and metric. Requires enable_agent (rejected otherwise).
## Guard Agent (telemetry)
Field Kotlin property Type Default Effect
enable_agent enableAgent bool false Enable Guard Agent telemetry.
agent_api_key agentApiKey str or none null SaaS API key. REQUIRED when enable_agent is true (rejected otherwise).
agent_strict agentStrict bool false True: an enabled agent that cannot be initialized raises at middleware init; false: degrade to agent-off.
on_error onError callable(stage, exception, context) or none null Best-effort failure callback. stage ∈ {agent_init, geoip, transport_send, encryption}. A raising callback is caught and logged, never propagated.
on_block onBlock callable(request, payload) or none null Fired exactly once per blocked (or passive-mode-flagged) request. Payload keys: check_name, reason, trigger_info, passive_mode, client_ip, path, method, status_code (null on the passive path — no response is sent). NOT fired for custom_request_check/route validators (app-authored), the HTTPS redirect (not a block), or an adapter's Redis-unavailable response. A raising callback is caught and logged.
agent_endpoint agentEndpoint str "https://api.guard-core.com" SaaS endpoint.
agent_project_id agentProjectId str or none null Project ID for telemetry organization.
agent_buffer_size agentBufferSize int 100 Events buffered before auto-flush.
agent_flush_interval agentFlushInterval int 30 Seconds between automatic flushes.
agent_enable_events agentEnableEvents bool true Send security events.
agent_enable_metrics agentEnableMetrics bool true Send performance metrics.
agent_timeout agentTimeout int 30 Agent HTTP timeout (seconds).
agent_retry_attempts agentRetryAttempts int 3 Retry attempts for failed agent requests.
agent_backoff_factor agentBackoffFactor float or none null Retry backoff factor; null = agent default.
agent_high_watermark_ratio agentHighWatermarkRatio float or none null Buffer occupancy ratio triggering early flush; null = agent default.
agent_max_concurrent_flushes agentMaxConcurrentFlushes int or none null Max concurrent early flushes; null = agent default.
agent_buffer_overflow_policy agentBufferOverflowPolicy enum drop/block/raise or none null Behavior on full buffer: drop oldest / block caller / raise. null = agent default (drop).
agent_sensitive_headers agentSensitiveHeaders str list or none null Headers excluded from telemetry; null = agent default.
agent_max_payload_size agentMaxPayloadSize int or none null Max telemetry payload bytes; null = agent default.
agent_compression_enabled agentCompressionEnabled bool or none null Gzip-compress batch bodies above the threshold; null = agent default.
agent_compression_threshold agentCompressionThreshold int or none null Min body size before compression; null = agent default.
agent_install_id agentInstallId str or none null Install ID override; null = auto-generate.
agent_payload_signing_secret agentPayloadSigningSecret str or none null HMAC-SHA256 secret signing the X-Payload-Signature header.
agent_project_encryption_key agentProjectEncryptionKey str or none null AES-256-GCM key for encrypted telemetry; when set, the agent posts to /api/v1/events/encrypted instead of /api/v1/events.
agent_guard_version agentGuardVersion str or none null Framework wrapper version propagated to the SaaS for attribution.
agent_status_interval agentStatusInterval int, 60–86400 (ge=60, le=86400) 300 Seconds between agent status reports.
## Dynamic rules
Field Kotlin property Type Default Effect
enable_dynamic_rules enableDynamicRules bool false Enable dynamic rule updates from the SaaS. Requires enable_agent (rejected otherwise).
dynamic_rule_interval dynamicRuleInterval int, >= 60 (ge=60) 300 Seconds between dynamic-rule update polls.
dynamic_rules_cache_path dynamicRulesCachePath path or none null Local JSON file persisting the last-known dynamic-rules snapshot (restart-during-outage fallback; Redis holds the primary snapshot when present). Written/read only when set. Empty/whitespace string: rejected.
## Emergency mode (dynamic-rule controlled)
Field Kotlin property Type Default Effect
emergency_mode emergencyMode bool false Emergency lockdown; set by dynamic rules (section 12).
emergency_whitelist emergencyWhitelist str list [] IPs exempt during emergency mode.

Registry fields beyond the spec 02 tables

These fields exist in the reference field table and the JVM registry but have no row in the spec 02 field semantics tables. Their effect text here is verified against the reference's field descriptions (guard_core/_security_config_fields.py).

Field Kotlin property Type Default Effect
detection_binary_min_run_length detectionBinaryMinRunLength int (ge=4, le=1024) 16 Minimum length a consecutive printable-character run inside a binary-dense multipart file-part payload must reach before that run is handed to the pattern scan. Text uploads and short or mostly-text payloads never reach the binary-density ratio and keep their full scan, and whole-body fallback scans are never island-reduced, so raw-body signature coverage stays intact.
detection_pattern_validation_cache_path detectionPatternValidationCachePath str or none None Optional file path for a disk-backed pattern-validation cache. When set, the empirical cost-verdict outcome of pattern-safety validation is cached keyed by pattern, flags, and engine version, so a process boot reuses prior certifications instead of re-timing every custom pattern; the cheap deterministic layers always re-run. Cache entries from a different engine version are ignored and overwritten. Leave unset (the default) to keep every validation fully empirical.
exempt_ips exemptIps str list (IP/CIDR) () IP addresses or CIDR ranges that skip rate limiting and the user-agent and cloud-provider checks. Not restrictive: every other IP is checked as usual. The blacklist, dynamic IP bans, per-route IP rules and penetration detection still apply to listed IPs.

Assignment-time revalidation: the fields flagged in the registry (list at ConfigFieldRegistry.kt, revalidatedOnAssignment) re-run their validators on every mutation after construction, mirroring _FIELD_REVALIDATORS in the reference.