Skip to main content

edgeguard/
config.rs

1//! Configuration. Env-first so EdgeGuard drops into any PaaS that injects `$PORT`
2//! with zero edits; an optional TOML file layers richer policy on top.
3
4use anyhow::{Context, Result};
5use serde::Deserialize;
6use std::collections::BTreeMap;
7use std::env;
8use std::time::Duration;
9
10#[derive(Debug, Clone, Default, Deserialize)]
11#[serde(default)]
12pub struct Config {
13    pub server: ServerCfg,
14    pub auth: AuthCfg,
15    pub ratelimit: RateLimitCfg,
16    pub validation: ValidationCfg,
17    pub headers: HeadersCfg,
18    pub tls: TlsCfg,
19    pub waf: WafCfg,
20    /// Optional per-path-prefix upstream overrides. Empty by default (everything goes to the
21    /// single `server.upstream`/`app_port`). A common use: `/api` → a backend, everything else →
22    /// a static frontend. Longest matching prefix wins; no match falls back to the default
23    /// upstream. This is a static prefix map, not a service mesh — see [`UpstreamRoute`].
24    pub upstreams: Vec<UpstreamRoute>,
25    /// IP allow/deny lists (CIDR). Empty by default (allow all); when set, requests are gated by
26    /// client IP before auth/rate-limit. See [`AccessCfg`].
27    pub access: AccessCfg,
28    /// Cross-Origin Resource Sharing policy. Off by default; when enabled, EdgeGuard answers
29    /// browser preflights and decorates responses so a separate-origin frontend can call the
30    /// app it fronts. See [`CorsCfg`].
31    pub cors: CorsCfg,
32    /// Optional "managed mode": pull policy from / report metrics to a remote control plane. Off
33    /// by default; the edge is a standalone proxy unless this is configured.
34    pub control_plane: ControlPlaneCfg,
35    /// Optional LLM token metering (gateway L0). Off by default; when enabled, OpenAI-compatible
36    /// traffic is parsed to meter tokens + cost (metering only — never blocks). See [`LlmCfg`].
37    pub llm: LlmCfg,
38    /// Optional outbound alerting (gateway L4). Off by default; when enabled with a webhook, the
39    /// gateway fires a Slack-compatible alert when a hard budget nears its limit. See [`AlertsCfg`].
40    pub alerts: AlertsCfg,
41}
42
43/// Outbound alerting (`[alerts]`). When `enabled` with a `webhook_url`, EdgeGuard POSTs a
44/// Slack-compatible alert (`{ "text": … }`) when a hard-budget's consumed ratio (`used/limit`)
45/// crosses `budget_consumed_threshold` — cost-regression alerting entirely in your own VPC (no SaaS
46/// alerting plane to depend on). Fire-and-forget
47/// and **edge-triggered** (one alert per crossing into the alert zone, not one per request). Off by
48/// default. A first cut on budget breaches; latency-percentile / error-rate / eval-drift rules follow.
49#[derive(Debug, Clone, Deserialize)]
50#[serde(default)]
51pub struct AlertsCfg {
52    /// Master switch. Default false.
53    pub enabled: bool,
54    /// Slack incoming-webhook URL (or any endpoint accepting `{ "text": … }`). Required when enabled.
55    pub webhook_url: String,
56    /// Fire when a budget's consumed ratio (`used/limit`) reaches this (`0.0`–`1.0+`). Default `0.9`.
57    pub budget_consumed_threshold: f64,
58    /// Per-emit timeout for the background POST, in milliseconds. Default 2000.
59    pub timeout_ms: u64,
60}
61
62impl Default for AlertsCfg {
63    fn default() -> Self {
64        AlertsCfg {
65            enabled: false,
66            webhook_url: String::new(),
67            budget_consumed_threshold: 0.9,
68            timeout_ms: 2000,
69        }
70    }
71}
72
73/// LLM token-metering settings (`[llm]`). When `enabled`, the proxy parses OpenAI-compatible
74/// request/response bodies to count tokens (from the upstream's `usage` object) and, for any model
75/// listed in `[llm.models]`, the cost. Metering is observe-only: it never blocks or alters traffic.
76/// An unmapped model still has its tokens counted (cost is simply omitted).
77#[derive(Debug, Clone, Deserialize)]
78#[serde(default)]
79pub struct LlmCfg {
80    pub enabled: bool,
81    /// Wire format. Only `"openai"` is understood today (the default).
82    pub api_style: String,
83    /// Per-model price book, keyed by the `model` string clients send. Prices are USD per
84    /// 1,000,000 tokens. Example:
85    /// `[llm.models."gpt-4o"]` `input_per_1m = 2.5` / `output_per_1m = 10.0`.
86    pub models: BTreeMap<String, ModelPrice>,
87    /// What to do with a request whose `model` is **not** in `[llm.models]`: `"count"` (default —
88    /// meter tokens, omit cost, forward the request) or `"block"` (reject `402` before it reaches the
89    /// upstream, so an unpriced model is never served at a silent `$0`). `"block"` only bites when a
90    /// price book is configured — a metering-only deployment (empty `[llm.models]`) never rejects.
91    pub on_unpriced_model: String,
92    /// Hard token/cost budgets (gateway L1). Empty by default (no enforcement — L0 metering only).
93    /// Each `[[llm.budgets]]` is a ceiling enforced fail-closed via reserve→reconcile. See [`BudgetCfg`].
94    pub budgets: Vec<BudgetCfg>,
95    /// Budget store backend: `"memory"` (single replica / default) or `"redis"` (shared across
96    /// replicas — required for a true fleet-wide cap). `"local"` is treated as `"memory"`.
97    pub store: String,
98    /// Redis URL when `store = "redis"`, e.g. `redis://127.0.0.1:6379`. Note: `EDGEGUARD_REDIS_URL`
99    /// only overrides `ratelimit.redis_url`, not this key — set it here (or via pushed policy).
100    pub redis_url: String,
101    /// Key prefix for budget keys in Redis (namespacing a shared server). Defaults to `edgeguard`.
102    pub redis_prefix: String,
103    /// On a budget-store error, allow the request (`true`) or reject it `503` (`false`, the default
104    /// — fail-closed, so an outage can't silently uncap spend).
105    pub fail_open: bool,
106    /// Completion tokens to assume when a request omits `max_tokens`, used only for the *reserve*
107    /// estimate (the reservation is reconciled to actual usage afterward). Default 1024.
108    pub default_max_tokens: u64,
109    /// Request header carrying the **team / tag** a request is attributed to, for the per-team budget
110    /// scope and team chargeback. Case-insensitive; default `x-edgeguard-team`. A request without it
111    /// falls into the shared `_none` team bucket.
112    pub team_header: String,
113    /// BYO-key vault + egress governance (gateway L2). Empty by default (no vault). Each
114    /// `[[llm.keys]]` maps a client-facing **virtual key** to a real **provider key** (injected
115    /// upstream, never returned to the client) plus an optional per-key model egress allowlist.
116    /// When any key is configured, every proxied request must present a known virtual key. See
117    /// [`KeyEntryCfg`].
118    pub keys: Vec<KeyEntryCfg>,
119    /// Edge DLP — PII / secret detection + redaction (gateway L3). Off by default. See [`DlpCfg`].
120    pub dlp: DlpCfg,
121    /// OTLP span emission (gateway L4) — SDK-free tracing to an OTel-native store. Off by default.
122    /// See [`TelemetryCfg`].
123    pub telemetry: TelemetryCfg,
124}
125
126/// OTLP span emission (`[llm.telemetry]`). When `enabled`, the gateway emits one OpenInference/OTLP
127/// span per metered LLM request to `endpoint` (an OTLP/HTTP `/v1/traces` receiver — e.g. evald),
128/// carrying the model, per-tier tokens, computed cost, and server-side TTFT/TPOT/latency already
129/// attached. Because the proxy sits in the request path, this needs **no** client SDK and is immune
130/// to the import-order / per-framework instrumentor drift that plagues in-process instrumentation.
131/// Emission is fire-and-forget — it never blocks or fails the client response. Off by default.
132#[derive(Debug, Clone, Deserialize)]
133#[serde(default)]
134pub struct TelemetryCfg {
135    /// Master switch. Default false.
136    pub enabled: bool,
137    /// OTLP/HTTP traces endpoint, e.g. `http://127.0.0.1:4318/v1/traces`. Required when `enabled`.
138    pub endpoint: String,
139    /// Fraction of LLM requests to emit a span for, `0.0`–`1.0` (deterministic per-trace sampling —
140    /// the same trace always gets the same verdict). Default `1.0` (all).
141    pub sample_rate: f64,
142    /// `service.name` resource attribute on emitted spans. Default `edgeguard`.
143    pub service_name: String,
144    /// Capture the (DLP-redacted) prompt/response as `input.value`/`output.value` on the span. Off by
145    /// default — content leaves the gateway only when this is explicitly enabled, and when an
146    /// `[llm.dlp]` engine is configured the captured content is redacted before it is emitted.
147    pub capture_content: bool,
148    /// Cap on each captured content field in bytes (truncated past this). Default 8192.
149    pub max_content_bytes: usize,
150    /// Per-emit timeout for the background POST, in milliseconds. Default 2000.
151    pub timeout_ms: u64,
152}
153
154impl Default for TelemetryCfg {
155    fn default() -> Self {
156        TelemetryCfg {
157            enabled: false,
158            endpoint: String::new(),
159            sample_rate: 1.0,
160            service_name: "edgeguard".into(),
161            capture_content: false,
162            max_content_bytes: 8192,
163            timeout_ms: 2000,
164        }
165    }
166}
167
168/// Edge-DLP settings (`[llm.dlp]`). When `mode` is not `off`, request and/or response bodies are
169/// scanned for PII and secrets; the `mode` decides what happens on a finding (report / block /
170/// redact). See [`crate::dlp`].
171#[derive(Debug, Clone, Deserialize)]
172#[serde(default)]
173pub struct DlpCfg {
174    /// `off` | `report` | `block` | `redact`. Default `off`.
175    pub mode: String,
176    /// How a span is rewritten in `redact` mode: `full` (`[REDACTED:<cat>]`, default) | `mask`
177    /// (keep last 4) | `hash` (stable opaque token). See [`crate::dlp::RedactStyle`].
178    pub redact_style: String,
179    /// Scan the inbound request body (the prompt). Default true.
180    pub scan_request: bool,
181    /// Scan the (buffered) response body and, in report mode, streamed frames. Default true.
182    pub scan_response: bool,
183    /// In `redact` mode, also rewrite *streamed* SSE frames (not just buffered bodies). Deterministic
184    /// detectors only — NER never runs on the stream. Off by default: streaming redaction can only
185    /// rewrite spans the carry buffer fully contains, so enable it deliberately. See [`crate::dlp`].
186    pub stream_redact: bool,
187    /// **Reversible masking** (`redact` mode only). When on, an inbound finding is replaced with a
188    /// stable placeholder token (`<edgeguard-<cat>-<n>>`) instead of an irreversible `[REDACTED]`
189    /// tag, and the placeholder→original map is kept for the request so the **response is unmasked**
190    /// (buffered *and* streamed) back to the original value. The provider never sees the PII; the
191    /// client gets its own data back — the round-trip an unmask keyed on shared state gets wrong.
192    /// Off by default.
193    /// When on, the response is unmasked rather than re-scanned/redacted (restore, not detect).
194    pub reversible: bool,
195    /// Built-in detectors.
196    pub detect_email: bool,
197    pub detect_credit_card: bool,
198    /// Require the Luhn checksum before flagging a digit run as a card (cuts false positives).
199    /// Default true.
200    pub luhn_validate_credit_card: bool,
201    /// AWS keys, provider-style `xx-…` keys, and private-key blocks.
202    pub detect_secrets: bool,
203    /// US SSN (`NNN-NN-NNNN`). Default true.
204    pub detect_ssn: bool,
205    /// Phone numbers. Off by default — false-positives on ordinary numeric runs.
206    pub detect_phone: bool,
207    /// IBAN account numbers. Off by default — false-positives on uppercase+digit tokens.
208    pub detect_iban: bool,
209    /// High-entropy token sweep (catch-all). Off by default — can false-positive.
210    pub detect_high_entropy: bool,
211    /// Prompt-injection / jailbreak heuristics for agent traffic (a small, high-precision built-in
212    /// deny set — "ignore previous instructions", "reveal your system prompt", etc.), reported under
213    /// the `prompt_injection` category. Off by default (opt-in, report-first) since instructions to a
214    /// model are legitimate traffic; enable and watch the counter before moving to `block`.
215    pub detect_prompt_injection: bool,
216    /// Minimum token length the entropy sweep considers.
217    pub entropy_min_len: usize,
218    /// Per-character Shannon-entropy threshold (bits) for the entropy sweep.
219    pub entropy_threshold: f64,
220    /// Dictionary deny-list: literal terms matched case-insensitively (Aho-Corasick), reported under
221    /// the `gazetteer` category. The fast, many-term path for known names / codenames / identifiers.
222    pub gazetteer_terms: Vec<String>,
223    /// Extra regexes (linear-time `regex` syntax), all reported under the `custom` category.
224    pub custom_patterns: Vec<String>,
225    /// Optional ML NER family (`[llm.dlp.ner]`). Requires the `ner` cargo feature; catches
226    /// person/address/org spans regex can't. See [`NerCfg`].
227    pub ner: NerCfg,
228}
229
230impl Default for DlpCfg {
231    fn default() -> Self {
232        DlpCfg {
233            mode: "off".into(),
234            redact_style: "full".into(),
235            scan_request: true,
236            scan_response: true,
237            stream_redact: false,
238            reversible: false,
239            detect_email: true,
240            detect_credit_card: true,
241            luhn_validate_credit_card: true,
242            detect_secrets: true,
243            detect_ssn: true,
244            detect_phone: false,
245            detect_iban: false,
246            detect_high_entropy: false,
247            detect_prompt_injection: false,
248            entropy_min_len: 24,
249            entropy_threshold: 4.0,
250            gazetteer_terms: Vec::new(),
251            custom_patterns: Vec::new(),
252            ner: NerCfg::default(),
253        }
254    }
255}
256
257/// ML NER settings (`[llm.dlp.ner]`). Off by default. When `enabled`, the proxy must be built with
258/// `--features ner`; otherwise startup fails with a clear error rather than running regex-only while
259/// the operator believes ML coverage is active. The model is an ONNX token-classification (BIO) NER
260/// network run through the pure-Rust [`edgeguard_ner`] crate.
261#[derive(Debug, Clone, Deserialize)]
262#[serde(default)]
263pub struct NerCfg {
264    /// Turn the NER family on. Requires the `ner` feature.
265    pub enabled: bool,
266    /// Path to the ONNX model file.
267    pub model_path: String,
268    /// Path to the HuggingFace `tokenizer.json`.
269    pub tokenizer_path: String,
270    /// Per-class label list in model id order (e.g. `["O","B-PER","I-PER","B-LOC", …]`). Used to map
271    /// argmax class ids back to entity labels.
272    pub labels: Vec<String>,
273    /// Confidence floor in `[0.0, 1.0]`; spans below it are dropped. Default 0.5.
274    pub threshold: f32,
275    /// Max tokens fed to the model per scan (longer inputs are truncated). Default 256.
276    pub max_seq_len: usize,
277}
278
279impl Default for NerCfg {
280    fn default() -> Self {
281        NerCfg {
282            enabled: false,
283            model_path: String::new(),
284            tokenizer_path: String::new(),
285            labels: Vec::new(),
286            threshold: 0.5,
287            max_seq_len: 256,
288        }
289    }
290}
291
292impl Default for LlmCfg {
293    fn default() -> Self {
294        LlmCfg {
295            enabled: false,
296            api_style: "openai".into(),
297            models: BTreeMap::new(),
298            on_unpriced_model: "count".into(),
299            budgets: Vec::new(),
300            store: "memory".into(),
301            redis_url: String::new(),
302            redis_prefix: "edgeguard".into(),
303            fail_open: false,
304            default_max_tokens: 1024,
305            team_header: "x-edgeguard-team".into(),
306            keys: Vec::new(),
307            dlp: DlpCfg::default(),
308            telemetry: TelemetryCfg::default(),
309        }
310    }
311}
312
313/// One vault entry (`[[llm.keys]]`): a client-facing virtual key mapped to a real provider key and
314/// an optional model egress allowlist. The provider key is injected into the upstream `Authorization`
315/// and is **never** sent back to the client; the client only ever holds the virtual key.
316#[derive(Debug, Clone, Default, Deserialize)]
317#[serde(default)]
318pub struct KeyEntryCfg {
319    /// The secret the client presents (`Authorization: Bearer <virtual_key>`). Required.
320    pub virtual_key: String,
321    /// The real upstream provider secret injected on the way out. Required. Prefer sourcing this
322    /// from a pushed control-plane policy / secret store rather than committing it.
323    pub provider_key: String,
324    /// Allowed model names for this key (egress allowlist). Empty = unrestricted; non-empty = only
325    /// these models may be requested (others get `403`).
326    pub allowed_models: Vec<String>,
327    /// Optional label for logs/metrics/audit (never the secret). Defaults to a positional id.
328    pub label: String,
329}
330
331/// One hard budget (`[[llm.budgets]]`): a ceiling of `limit` (in `unit`) over `window`, keyed by
332/// `scope`. Enforced fail-closed before the request reaches the upstream.
333#[derive(Debug, Clone, Deserialize)]
334#[serde(default)]
335pub struct BudgetCfg {
336    /// Identifier (also the metric/log label and part of the store key). Required, non-empty.
337    pub name: String,
338    /// Keying dimension: `"global"`, `"key"` (per authenticated principal), or `"model"`.
339    pub scope: String,
340    /// `"tokens"` (prompt + completion) or `"usd"` (cost via the price book).
341    pub unit: String,
342    /// The ceiling, in `unit`: a token count, or — for `unit = "usd"` — dollars (e.g. `25.0`).
343    pub limit: f64,
344    /// Reset window, e.g. `"1h"`, `"24h"`, `"30d"`. The budget resets at each window boundary.
345    pub window: String,
346}
347
348impl Default for BudgetCfg {
349    fn default() -> Self {
350        BudgetCfg {
351            name: String::new(),
352            scope: "global".into(),
353            unit: "tokens".into(),
354            limit: 0.0,
355            window: "24h".into(),
356        }
357    }
358}
359
360/// One model's price, in USD per 1,000,000 tokens (input and output billed separately, matching
361/// provider pricing). Compiled to integer micro-dollars at load (see [`crate::llm`]).
362///
363/// `cached_per_1m` prices the cached-prompt subset (`prompt_tokens_details.cached_tokens`, usually a
364/// steep discount) and `reasoning_per_1m` the reasoning subset (`completion_tokens_details.
365/// reasoning_tokens`). Both default to `0.0`, which means **inherit the base input/output rate** —
366/// so an existing book prices exactly as before; set them only to apply a provider's separate
367/// cached/reasoning rate.
368#[derive(Debug, Clone, Copy, Default, Deserialize)]
369#[serde(default)]
370pub struct ModelPrice {
371    pub input_per_1m: f64,
372    pub output_per_1m: f64,
373    /// USD per 1M cached prompt tokens. `0.0` = inherit `input_per_1m`.
374    pub cached_per_1m: f64,
375    /// USD per 1M reasoning tokens. `0.0` = inherit `output_per_1m`.
376    pub reasoning_per_1m: f64,
377}
378
379/// Managed-mode settings: when `enabled`, the edge pulls its policy from a remote control plane
380/// (and hot-reloads it), reports metric deltas, and forwards CSP reports. The policy the control
381/// plane pushes is the *policy subset* (auth/ratelimit/validation/headers/waf) — the edge keeps
382/// its own local `server`/`tls`. The edge token is a secret, so prefer `EDGEGUARD_CP_EDGE_TOKEN`.
383#[derive(Debug, Clone, Deserialize)]
384#[serde(default)]
385pub struct ControlPlaneCfg {
386    pub enabled: bool,
387    /// Base URL of the control plane, e.g. `https://cp.example`.
388    pub url: String,
389    /// This edge's tenant id at the control plane.
390    pub tenant_id: String,
391    /// Per-tenant edge token (Bearer). Prefer `EDGEGUARD_CP_EDGE_TOKEN`.
392    pub edge_token: String,
393    /// How often to poll for policy, e.g. `"30s"`.
394    pub poll_interval: String,
395    /// How often to flush a metrics delta, e.g. `"60s"`.
396    pub report_interval: String,
397    /// Forward received CSP reports to the control plane (default true).
398    pub forward_csp: bool,
399    /// Enforce the configured quota as a **hard stop**: poll the control plane's
400    /// `/v3/edge/{id}/quota` and, while the edge is over its quota, reject the edge's
401    /// traffic with `429` (a `Retry-After` reset hint). Off by default — opt in to turn the
402    /// rate signal into a hard cap. Prefer `EDGEGUARD_CP_QUOTA_ENFORCE`.
403    pub enforce_quota: bool,
404    /// How often to poll the quota verdict, e.g. `"30s"`. A failed poll keeps the last verdict, so
405    /// a control-plane blip neither over- nor under-enforces.
406    pub quota_poll_interval: String,
407}
408
409impl Default for ControlPlaneCfg {
410    fn default() -> Self {
411        ControlPlaneCfg {
412            enabled: false,
413            url: String::new(),
414            tenant_id: String::new(),
415            edge_token: String::new(),
416            poll_interval: "30s".into(),
417            report_interval: "60s".into(),
418            forward_csp: true,
419            enforce_quota: false,
420            quota_poll_interval: "30s".into(),
421        }
422    }
423}
424
425#[derive(Debug, Clone, Deserialize)]
426#[serde(default)]
427pub struct ServerCfg {
428    /// Public listen port. Overridden by the `PORT` env var.
429    pub port: u16,
430    /// Internal port the wrapped/upstream app listens on. Overridden by `APP_PORT`.
431    pub app_port: u16,
432    /// Full upstream base URL. Overridden by `UPSTREAM`. If empty, derived from app_port.
433    pub upstream: String,
434    /// Trust the `X-Forwarded-For` header for client identity. Enable ONLY when
435    /// EdgeGuard sits behind a trusted proxy/load balancer that sets it (e.g. a PaaS
436    /// edge). When false (default) the peer socket address is used, so clients can't
437    /// spoof their IP to defeat per-IP rate limiting or forge access-log entries.
438    pub trust_forwarded_for: bool,
439    /// Private listener port for the internal `/__edgeguard/*` ops endpoints (health,
440    /// readiness, metrics). `0` (default) keeps them on the public port. When non-zero,
441    /// EdgeGuard binds a second, plain-HTTP listener on `admin_addr:admin_port` that serves
442    /// those endpoints, and the public port serves only the proxy (plus the browser-facing CSP
443    /// report sink) — so metrics/health aren't exposed on the internet. Overridden by
444    /// `ADMIN_PORT`. (Point your platform's health check at this port when you enable it.)
445    pub admin_port: u16,
446    /// Address the private admin listener binds when `admin_port` is set. Defaults to
447    /// `127.0.0.1` (same-host only — e.g. a sidecar scraper); set to `0.0.0.0` to expose it on
448    /// a private network interface (rely on your network policy to keep it off the internet).
449    pub admin_addr: String,
450}
451
452#[derive(Debug, Clone, Deserialize)]
453#[serde(default)]
454pub struct AuthCfg {
455    /// "none" | "basic" | "apikey" | "jwt". Selects the gate applied to every proxied
456    /// request; the internal `/__edgeguard/*` endpoints are always exempt.
457    pub mode: String,
458    pub realm: String,
459    /// username -> password. Value may be plaintext (dev) or a `$argon2...` PHC hash.
460    /// Used when `mode = "basic"`.
461    pub users: BTreeMap<String, String>,
462    /// Accepted API keys (compared in constant time). Used when `mode = "apikey"`. A request
463    /// may present a key either as `Authorization: Bearer <key>` or in `api_key_header`.
464    /// Overridable from the env via `EDGEGUARD_API_KEYS` (comma-separated) so keys need not
465    /// live in the config file.
466    pub api_keys: Vec<String>,
467    /// Header carrying the API key (in addition to `Authorization: Bearer`), default
468    /// `X-API-Key`. Used when `mode = "apikey"`.
469    pub api_key_header: String,
470    /// JWT verification policy. Used when `mode = "jwt"`.
471    pub jwt: JwtCfg,
472}
473
474/// JWT bearer-token verification. Either a symmetric `secret` (HS*) or an asymmetric key
475/// (RS*/ES*/PS*) supplied as a static `public_key_pem` or fetched from `jwks_url`.
476#[derive(Debug, Clone, Deserialize)]
477#[serde(default)]
478pub struct JwtCfg {
479    /// Expected signature algorithm, e.g. "HS256", "RS256", "ES256". The token's own `alg`
480    /// header must match this (we never trust the token to pick its own algorithm — that is
481    /// the classic JWT downgrade/`alg=none` foot-gun).
482    pub algorithm: String,
483    /// Shared secret for HS* algorithms. Prefer the `EDGEGUARD_JWT_SECRET` env var over
484    /// putting it in the config file.
485    pub secret: String,
486    /// Static PEM public key (SPKI or PKCS#1) for RS*/ES*/PS* verification, as an
487    /// alternative to `jwks_url`.
488    pub public_key_pem: String,
489    /// JWKS endpoint to fetch verification keys from (RS*/ES*/PS*). Keys are cached and
490    /// selected by the token's `kid`.
491    pub jwks_url: String,
492    /// How long (seconds) to cache a fetched JWKS before refetching. Default 300.
493    pub jwks_cache_secs: u64,
494    /// If set, the token's `iss` claim must equal this.
495    pub issuer: String,
496    /// If set, the token's `aud` claim must contain this.
497    pub audience: String,
498    /// Clock-skew leeway (seconds) applied to `exp`/`nbf` validation. Default 60.
499    pub leeway_secs: u64,
500}
501
502#[derive(Debug, Clone, Deserialize)]
503#[serde(default)]
504pub struct RateLimitCfg {
505    pub enabled: bool,
506    /// Default per-client-IP limit, e.g. "60/min", "10/sec", "1000/hour".
507    pub rate: String,
508    pub burst: u32,
509    /// Per-route overrides. A request whose path starts with `path` uses that route's limit
510    /// (still keyed per client IP) instead of the global one; the longest matching prefix
511    /// wins, so `/api/admin/` can be stricter than `/api/`.
512    pub routes: Vec<RouteRateLimit>,
513    /// An additional limit keyed by the authenticated principal (API-key id or JWT subject)
514    /// rather than IP, so a single credential can't fan out across many IPs. Only applies to
515    /// authenticated requests.
516    pub per_key: PerKeyRateLimit,
517    /// Where limiter state lives: `"local"` (default) is the in-process `governor` limiter (fast,
518    /// no dependency, but per-replica). `"redis"` shares GCRA state across replicas via a Redis
519    /// store, so N instances enforce one global limit. `"memory"` uses the same shared-store code
520    /// path backed by an in-process map (a single-replica/testing backend). All three honor the
521    /// same `rate`/`burst`/route/per-key settings above.
522    pub store: String,
523    /// Redis connection URL for `store = "redis"`, e.g. `redis://host:6379` or (TLS)
524    /// `rediss://host:6379`. Prefer the `EDGEGUARD_REDIS_URL` env var over this file.
525    pub redis_url: String,
526    /// Key prefix/namespace for the shared store, so multiple EdgeGuard deployments can share one
527    /// Redis without colliding. Keys look like `<prefix>:ip:<addr>`.
528    pub redis_prefix: String,
529    /// What to do when the shared store is unreachable. `false` (default) fails **closed** — a
530    /// store error returns `503`, so an outage can't silently disable rate limiting. `true` fails
531    /// **open** — a store error allows the request (favor availability over strict limiting).
532    /// Only relevant for `store = "redis"`.
533    pub fail_open: bool,
534}
535
536/// A per-route rate-limit override (matched by path prefix).
537#[derive(Debug, Clone, Deserialize)]
538#[serde(default)]
539pub struct RouteRateLimit {
540    /// Path prefix this limit applies to, e.g. "/api/".
541    pub path: String,
542    pub rate: String,
543    pub burst: u32,
544}
545
546impl Default for RouteRateLimit {
547    fn default() -> Self {
548        RouteRateLimit {
549            path: String::new(),
550            rate: "60/min".into(),
551            burst: 20,
552        }
553    }
554}
555
556/// Per-principal rate limit (keyed by API-key id / JWT subject).
557#[derive(Debug, Clone, Deserialize)]
558#[serde(default)]
559pub struct PerKeyRateLimit {
560    pub enabled: bool,
561    pub rate: String,
562    pub burst: u32,
563}
564
565impl Default for PerKeyRateLimit {
566    fn default() -> Self {
567        PerKeyRateLimit {
568            enabled: false,
569            rate: "1000/hour".into(),
570            burst: 100,
571        }
572    }
573}
574
575#[derive(Debug, Clone, Deserialize)]
576#[serde(default)]
577pub struct ValidationCfg {
578    /// e.g. "2MiB". Requests with a larger body are rejected with 413.
579    pub max_body: String,
580    /// Cap on the upstream response body EdgeGuard buffers, e.g. "16MiB". "0" disables
581    /// the cap (unbounded). Protects against an upstream OOM-ing the proxy; raise it if
582    /// you proxy large downloads.
583    pub max_response_body: String,
584    /// Max time to wait for the upstream response and to read its body, e.g. "30s",
585    /// "500ms", "2m". "0" disables the timeout. Bounds a stalled upstream so it can't pin a
586    /// handler task indefinitely; on elapse the proxy returns 504.
587    pub upstream_timeout: String,
588    /// Cap on the total size of incoming request headers (sum of name + value bytes), e.g.
589    /// "32KiB". "0" disables the cap (default). Requests over the limit get `431`. This is a
590    /// policy limit enforced by EdgeGuard on top of hyper's own transport-level header cap.
591    pub max_header_bytes: String,
592    /// Allowed HTTP methods; empty list means allow all.
593    pub allow_methods: Vec<String>,
594    /// Stream (don't buffer) responses whose `Content-Type` is `text/event-stream`. Off by
595    /// default: the proxy normally buffers the whole upstream body so it can cap size
596    /// (`max_response_body`) and account exact egress bytes. That buffering defeats Server-Sent
597    /// Events / chunked streaming — the client only sees the body once the upstream finishes.
598    /// Turn this on to forward SSE responses frame-by-frame as they arrive (preserving
599    /// time-to-first-byte). When a response is streamed this way the `max_response_body` cap and
600    /// the body-read deadline don't apply (the connect/first-byte `upstream_timeout` still
601    /// does); egress bytes are tallied as frames flow. Non-SSE responses are unaffected.
602    pub stream_passthrough: bool,
603    /// Tunnel WebSocket (and other `Upgrade`) connections through to the upstream. Off by
604    /// default: the normal path strips the hop-by-hop `Upgrade`/`Connection` headers, so an
605    /// upgrade request would be forwarded as a plain HTTP request and the handshake would fail.
606    /// When on, an authenticated, rate-limited upgrade request is forwarded *with* its upgrade
607    /// headers and, on the upstream's `101 Switching Protocols`, EdgeGuard splices the two
608    /// connections into a raw bidirectional tunnel. Response hardening / WAF body inspection
609    /// don't apply to a tunneled connection (there is no buffered response). Non-upgrade requests
610    /// are unaffected.
611    pub websocket_passthrough: bool,
612    /// gzip-compress responses for clients that send `Accept-Encoding: gzip`. Off by default.
613    /// Skips already-compressed content types and (always) `text/event-stream`, so SSE streaming
614    /// is never buffered by the compressor. Applied at the listener, so toggling it needs a
615    /// restart (it is not part of the hot-reloadable policy).
616    pub compress_responses: bool,
617}
618
619#[derive(Debug, Clone, Deserialize)]
620#[serde(default)]
621pub struct HeadersCfg {
622    pub hsts: bool,
623    pub csp: String,
624    /// Send the CSP as `Content-Security-Policy-Report-Only` instead of enforcing it. Lets
625    /// you roll out / tighten a policy by collecting violations first without breaking the
626    /// page.
627    pub csp_report_only: bool,
628    /// If set, a `report-uri <value>` directive is appended to the CSP so browsers POST
629    /// violation reports there. Point it at EdgeGuard's own sink ("/__edgeguard/csp-report")
630    /// to have them logged, or at any external collector.
631    pub csp_report_uri: String,
632    pub referrer_policy: String,
633    pub permissions_policy: String,
634    pub frame_options: String,
635    pub force_secure_cookies: bool,
636    /// Add `HttpOnly` to `Set-Cookie` responses that lack it. On by default. Turn off (or use
637    /// `httponly_cookie_exempt`) for apps that intentionally expose a cookie to JavaScript —
638    /// e.g. a double-submit CSRF token the frontend must read from `document.cookie`.
639    pub httponly_cookies: bool,
640    /// Cookie NAMES that must never get `HttpOnly`, even when `httponly_cookies` is on. The
641    /// surgical exemption for a readable double-submit CSRF cookie, e.g. `["doneyet_csrf"]`.
642    /// Names match exactly (cookies are case-sensitive).
643    pub httponly_cookie_exempt: Vec<String>,
644    /// Response headers to strip (case-insensitive), e.g. ["Server", "X-Powered-By"].
645    pub strip: Vec<String>,
646}
647
648impl Default for ServerCfg {
649    fn default() -> Self {
650        ServerCfg {
651            port: 8080,
652            app_port: 3000,
653            upstream: String::new(),
654            trust_forwarded_for: false,
655            admin_port: 0,
656            admin_addr: "127.0.0.1".into(),
657        }
658    }
659}
660
661impl Default for AuthCfg {
662    fn default() -> Self {
663        AuthCfg {
664            mode: "none".into(),
665            realm: "EdgeGuard".into(),
666            users: BTreeMap::new(),
667            api_keys: vec![],
668            api_key_header: "X-API-Key".into(),
669            jwt: JwtCfg::default(),
670        }
671    }
672}
673
674impl Default for JwtCfg {
675    fn default() -> Self {
676        JwtCfg {
677            algorithm: "HS256".into(),
678            secret: String::new(),
679            public_key_pem: String::new(),
680            jwks_url: String::new(),
681            jwks_cache_secs: 300,
682            issuer: String::new(),
683            audience: String::new(),
684            leeway_secs: 60,
685        }
686    }
687}
688
689impl Default for RateLimitCfg {
690    fn default() -> Self {
691        RateLimitCfg {
692            enabled: true,
693            rate: "60/min".into(),
694            burst: 20,
695            routes: vec![],
696            per_key: PerKeyRateLimit::default(),
697            store: "local".into(),
698            redis_url: "redis://127.0.0.1:6379".into(),
699            redis_prefix: "edgeguard".into(),
700            fail_open: false,
701        }
702    }
703}
704
705impl Default for ValidationCfg {
706    fn default() -> Self {
707        ValidationCfg {
708            max_body: "2MiB".into(),
709            max_response_body: "0".into(),
710            upstream_timeout: "30s".into(),
711            max_header_bytes: "0".into(),
712            allow_methods: vec![],
713            stream_passthrough: false,
714            websocket_passthrough: false,
715            compress_responses: false,
716        }
717    }
718}
719
720impl Default for HeadersCfg {
721    fn default() -> Self {
722        HeadersCfg {
723            hsts: true,
724            csp: "default-src 'self'".into(),
725            csp_report_only: false,
726            csp_report_uri: String::new(),
727            referrer_policy: "no-referrer".into(),
728            permissions_policy: "geolocation=(), microphone=(), camera=()".into(),
729            frame_options: "DENY".into(),
730            force_secure_cookies: true,
731            httponly_cookies: true,
732            httponly_cookie_exempt: Vec::new(),
733            strip: vec!["Server".into(), "X-Powered-By".into()],
734        }
735    }
736}
737
738/// TLS termination. When `enabled`, EdgeGuard serves HTTPS on the public port using a
739/// certificate either loaded from `cert_path`/`key_path` or obtained automatically via ACME.
740/// All-default fields (disabled, empty paths, default ACME) so `Default` is derivable.
741#[derive(Debug, Clone, Default, Deserialize)]
742#[serde(default)]
743pub struct TlsCfg {
744    pub enabled: bool,
745    /// PEM certificate chain (leaf first). When ACME is enabled this is where the obtained
746    /// certificate is written/read.
747    pub cert_path: String,
748    /// PEM private key (PKCS#8/PKCS#1/SEC1).
749    pub key_path: String,
750    pub acme: AcmeCfg,
751}
752
753/// Automatic certificate management (ACME / Let's Encrypt) via the HTTP-01 challenge. The
754/// obtained certificate is written to `TlsCfg::cert_path`/`key_path` and served by the TLS
755/// listener. Issuance runs at startup only when no certificate exists at `cert_path`;
756/// there is **no automatic renewal yet** (see docs/ROADMAP.md) — delete the cert/key files
757/// and restart to re-issue.
758#[derive(Debug, Clone, Deserialize)]
759#[serde(default)]
760pub struct AcmeCfg {
761    pub enabled: bool,
762    /// Domains to request a certificate for (the first is the primary CN).
763    pub domains: Vec<String>,
764    /// Contact email for the ACME account (registration + expiry notices).
765    pub email: String,
766    /// ACME directory URL. Defaults to Let's Encrypt **staging** so a misconfiguration can't
767    /// burn the strict production rate limits; switch to production explicitly.
768    pub directory_url: String,
769    /// Directory for the cached ACME account key (so renewals reuse the same account).
770    pub cache_dir: String,
771    /// You must set this to `true` to signify acceptance of the ACME provider's Terms of
772    /// Service; EdgeGuard refuses to register otherwise.
773    pub accept_tos: bool,
774}
775
776impl Default for AcmeCfg {
777    fn default() -> Self {
778        AcmeCfg {
779            enabled: false,
780            domains: vec![],
781            email: String::new(),
782            // Let's Encrypt staging — safe default; see the field doc.
783            directory_url: "https://acme-staging-v02.api.letsencrypt.org/directory".into(),
784            cache_dir: "./acme".into(),
785            accept_tos: false,
786        }
787    }
788}
789
790/// WAF-lite input inspection (Phase 4 / v2). Screens a request for common attack signatures
791/// before it is forwarded, using built-in heuristic rulesets (SQLi/XSS/path-traversal) plus
792/// any operator-defined deny patterns. Disabled by default — these are heuristics, so the
793/// intended rollout is `report` (log + count matches without blocking) until the operator is
794/// confident, then `block` (return `403`). Compiled into a `crate::waf::WafEngine`.
795#[derive(Debug, Clone, Deserialize)]
796#[serde(default)]
797pub struct WafCfg {
798    /// "off" (default) | "report" | "block". `report` evaluates rules and logs/counts matches
799    /// but forwards the request anyway; `block` rejects a matching request with `403`.
800    pub mode: String,
801    /// Enable the built-in SQL-injection heuristic ruleset.
802    pub sqli: bool,
803    /// Enable the built-in cross-site-scripting heuristic ruleset.
804    pub xss: bool,
805    /// Enable the built-in path-traversal heuristic ruleset.
806    pub path_traversal: bool,
807    /// Inspect the request path + query string (matched raw and percent-decoded). Default true.
808    pub inspect_path: bool,
809    /// Inspect request header values. Off by default: header bytes (cookies, tokens, opaque
810    /// blobs) are noisy and prone to false positives.
811    pub inspect_headers: bool,
812    /// Inspect the request body (already capped by `validation.max_body`). Off by default.
813    pub inspect_body: bool,
814    /// Operator-defined deny patterns, evaluated alongside the enabled built-in rulesets.
815    pub rules: Vec<WafRule>,
816}
817
818/// A single operator-defined WAF deny pattern (a `[[waf.rules]]` entry).
819#[derive(Debug, Clone, Deserialize)]
820#[serde(default)]
821pub struct WafRule {
822    /// Identifier reported in logs/metrics when this rule matches (defaults to `custom-<n>`).
823    pub id: String,
824    /// Regular expression (RE2 syntax: linear-time, no backreferences/lookaround, so it can't
825    /// ReDoS the proxy). A request matching it in any targeted location is treated as a hit.
826    pub pattern: String,
827    /// Request location to match against: "path" (path+query, default), "headers", "body", or
828    /// "all". A location is only examined when its `inspect_*` flag above is also enabled.
829    pub target: String,
830}
831
832impl Default for WafCfg {
833    fn default() -> Self {
834        WafCfg {
835            mode: "off".into(),
836            sqli: true,
837            xss: true,
838            path_traversal: true,
839            inspect_path: true,
840            inspect_headers: false,
841            inspect_body: false,
842            rules: vec![],
843        }
844    }
845}
846
847impl Default for WafRule {
848    fn default() -> Self {
849        WafRule {
850            id: String::new(),
851            pattern: String::new(),
852            target: "path".into(),
853        }
854    }
855}
856
857/// A per-path-prefix upstream override (a `[[upstreams]]` entry). Requests whose path starts with
858/// `path` are forwarded to `target` instead of the default `server.upstream`; the longest matching
859/// prefix wins. This is deliberately a *static prefix map* for the common "static frontend + `/api`
860/// backend" shape — not a gateway: no service discovery, load balancing, health-based routing, or
861/// request rewriting (the path is forwarded unchanged). For those, put EdgeGuard behind a real
862/// gateway/mesh.
863#[derive(Debug, Clone, Default, Deserialize)]
864#[serde(default)]
865pub struct UpstreamRoute {
866    /// Path prefix this upstream applies to, e.g. `/api/`.
867    pub path: String,
868    /// Upstream base URL for this prefix, e.g. `http://api.internal:4000`.
869    pub target: String,
870}
871
872/// IP allow/deny lists, matched against the resolved client IP (the same IP rate limiting keys
873/// on — so behind a trusted proxy, set `server.trust_forwarded_for` for this to see the real
874/// client). Both lists accept plain IPs (`203.0.113.7`, `::1`) and CIDR ranges
875/// (`10.0.0.0/8`, `2001:db8::/32`). `deny` wins over `allow`; a non-empty `allow` means
876/// "only these may connect". Both empty (the default) = allow all. Compiled into a
877/// `crate::access::AccessPolicy`; an unparseable entry fails at startup/reload.
878#[derive(Debug, Clone, Default, Deserialize)]
879#[serde(default)]
880pub struct AccessCfg {
881    /// CIDRs/IPs allowed in. Empty = allow all (subject to `deny`).
882    pub allow: Vec<String>,
883    /// CIDRs/IPs always rejected (takes precedence over `allow`).
884    pub deny: Vec<String>,
885}
886
887/// Cross-Origin Resource Sharing policy. A drop-in front door commonly sits in front of an app
888/// whose browser frontend is served from a *different* origin (a separate static host, a
889/// preview URL, `localhost:5173` in dev); without CORS those `fetch` calls are blocked by the
890/// browser. When `enabled`, EdgeGuard answers preflight `OPTIONS` requests itself (before auth —
891/// preflights carry no credentials) and adds the matching `Access-Control-*` headers to actual
892/// responses. Off by default: opening cross-origin access is a deliberate choice. Compiled into
893/// a `crate::cors::CorsPolicy`.
894#[derive(Debug, Clone, Deserialize)]
895#[serde(default)]
896pub struct CorsCfg {
897    pub enabled: bool,
898    /// Allowed request origins, matched exactly (scheme + host + port), e.g.
899    /// `["https://app.example.com"]`. The single entry `["*"]` allows any origin — but a
900    /// wildcard cannot be combined with `allow_credentials = true` (the Fetch spec forbids it),
901    /// so that combination is rejected at startup.
902    pub allow_origins: Vec<String>,
903    /// Methods advertised in the preflight `Access-Control-Allow-Methods`. Empty = a sensible
904    /// default set (`GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD`).
905    pub allow_methods: Vec<String>,
906    /// Request headers advertised in `Access-Control-Allow-Headers`. Empty = reflect whatever the
907    /// browser asks for in `Access-Control-Request-Headers` (the common, permissive default).
908    pub allow_headers: Vec<String>,
909    /// Response headers the browser is allowed to read, advertised in
910    /// `Access-Control-Expose-Headers`. Empty = none beyond the CORS-safelisted set.
911    pub expose_headers: Vec<String>,
912    /// Send `Access-Control-Allow-Credentials: true` so the browser may send cookies / HTTP auth.
913    /// Requires explicit `allow_origins` (no `"*"`).
914    pub allow_credentials: bool,
915    /// How long a browser may cache the preflight result, e.g. `"600s"`, `"1h"`. `"0"` omits the
916    /// `Access-Control-Max-Age` header (the browser uses its own short default).
917    pub max_age: String,
918}
919
920impl Default for CorsCfg {
921    fn default() -> Self {
922        CorsCfg {
923            enabled: false,
924            allow_origins: vec![],
925            allow_methods: vec![],
926            allow_headers: vec![],
927            expose_headers: vec![],
928            allow_credentials: false,
929            max_age: "600s".into(),
930        }
931    }
932}
933
934impl Config {
935    /// Load defaults, overlay an optional TOML file, then apply env overrides.
936    pub fn load(path: Option<&str>) -> Result<Config> {
937        let mut cfg = if let Some(p) = path {
938            let raw =
939                std::fs::read_to_string(p).with_context(|| format!("reading config file {p}"))?;
940            toml::from_str::<Config>(&raw).with_context(|| format!("parsing config file {p}"))?
941        } else {
942            Config::default()
943        };
944
945        if let Ok(p) = env::var("PORT") {
946            if let Ok(v) = p.parse() {
947                cfg.server.port = v;
948            }
949        }
950        if let Ok(p) = env::var("APP_PORT") {
951            if let Ok(v) = p.parse() {
952                cfg.server.app_port = v;
953            }
954        }
955        if let Ok(p) = env::var("ADMIN_PORT") {
956            if let Ok(v) = p.parse() {
957                cfg.server.admin_port = v;
958            }
959        }
960        if let Ok(u) = env::var("UPSTREAM") {
961            if !u.is_empty() {
962                cfg.server.upstream = u;
963            }
964        }
965        // Keep secrets out of the config file: let the environment supply them, either directly
966        // (`EDGEGUARD_JWT_SECRET`) or from a file (`EDGEGUARD_JWT_SECRET_FILE`) for Docker/K8s
967        // secret mounts. The direct variable wins when both are set; see `env_or_file`.
968        if let Some(s) = env_or_file("EDGEGUARD_JWT_SECRET")? {
969            cfg.auth.jwt.secret = s;
970        }
971        if let Some(u) = env_or_file("EDGEGUARD_REDIS_URL")? {
972            cfg.ratelimit.redis_url = u;
973        }
974        if let Some(keys) = env_or_file("EDGEGUARD_API_KEYS")? {
975            let keys: Vec<String> = keys
976                .split(',')
977                .map(|k| k.trim().to_string())
978                .filter(|k| !k.is_empty())
979                .collect();
980            if !keys.is_empty() {
981                cfg.auth.api_keys = keys;
982            }
983        }
984        if let Some(t) = env_or_file("EDGEGUARD_CP_EDGE_TOKEN")? {
985            cfg.control_plane.edge_token = t;
986        }
987        if let Some(u) = env_or_file("EDGEGUARD_CP_URL")? {
988            cfg.control_plane.url = u;
989        }
990        if let Ok(v) = env::var("EDGEGUARD_CP_QUOTA_ENFORCE") {
991            // Only an explicit, recognized value overrides the file config; an empty value is a
992            // no-op and a typo is a hard error rather than silently disabling a security control.
993            match v.trim().to_ascii_lowercase().as_str() {
994                "" => {}
995                "1" | "true" | "yes" | "on" => cfg.control_plane.enforce_quota = true,
996                "0" | "false" | "no" | "off" => cfg.control_plane.enforce_quota = false,
997                other => anyhow::bail!(
998                    "invalid EDGEGUARD_CP_QUOTA_ENFORCE value {other:?}; expected 1/true/yes/on or 0/false/no/off"
999                ),
1000            }
1001        }
1002        Ok(cfg)
1003    }
1004
1005    /// Produce an effective config by overlaying a control-plane-pushed *policy* document onto
1006    /// this (local) config: the policy sections
1007    /// (`auth`/`ratelimit`/`validation`/`headers`/`waf`/`access`/`cors`) come from the pushed TOML;
1008    /// `server`/`tls`/`upstreams`/`telemetry`/`control_plane` stay local (the control plane manages
1009    /// security policy, not this edge's listener/plumbing/topology). The result feeds the normal
1010    /// `build_runtime` + hot-swap path, so a malformed policy is rejected like any bad reload.
1011    pub fn with_policy_from(&self, policy_toml: &str) -> Result<Config> {
1012        let p: Config =
1013            toml::from_str(policy_toml).context("parsing control-plane policy document")?;
1014        Ok(Config {
1015            server: self.server.clone(),
1016            tls: self.tls.clone(),
1017            control_plane: self.control_plane.clone(),
1018            // Upstream topology is edge-local (like `server`), not pushed policy.
1019            upstreams: self.upstreams.clone(),
1020            auth: p.auth,
1021            ratelimit: p.ratelimit,
1022            validation: p.validation,
1023            headers: p.headers,
1024            waf: p.waf,
1025            access: p.access,
1026            cors: p.cors,
1027            // LLM metering is a policy section (the control plane can push a fleet-wide price
1028            // book) — except `telemetry`, which (like `alerts` below) is edge-local operational
1029            // config, not fleet-pushed policy: preserve it from the edge rather than letting a
1030            // pushed policy silently repoint `endpoint`/`capture_content`/`sample_rate`.
1031            llm: LlmCfg {
1032                telemetry: self.llm.telemetry.clone(),
1033                ..p.llm
1034            },
1035            // Alerting is edge-local operational config (its webhook is a local secret/endpoint), not
1036            // fleet-pushed policy — carry it from the edge, like `server`/`tls`.
1037            alerts: self.alerts.clone(),
1038        })
1039    }
1040
1041    /// The upstream base URL EdgeGuard forwards to, e.g. "http://127.0.0.1:3000".
1042    pub fn upstream_base(&self) -> String {
1043        if self.server.upstream.is_empty() {
1044            format!("http://127.0.0.1:{}", self.server.app_port)
1045        } else {
1046            self.server.upstream.trim_end_matches('/').to_string()
1047        }
1048    }
1049
1050    /// The `(host, port)` EdgeGuard probes for readiness, mirroring [`Self::upstream_base`]:
1051    /// co-process mode probes `127.0.0.1:app_port`; an explicit upstream URL is parsed,
1052    /// defaulting the port from the scheme. Returns `None` if the URL carries no usable
1053    /// host, so the readiness check reports "not ready" rather than panicking.
1054    pub fn upstream_probe_addr(&self) -> Option<(String, u16)> {
1055        if self.server.upstream.is_empty() {
1056            Some(("127.0.0.1".to_string(), self.server.app_port))
1057        } else {
1058            parse_host_port(&self.server.upstream)
1059        }
1060    }
1061}
1062
1063/// Extract `(host, port)` from an upstream URL like `http://host:3000/base`. Only the
1064/// scheme (for the default port), host, and port are needed — any path is ignored. Handles
1065/// bracketed IPv6 literals (`http://[::1]:3000`). This is deliberately small rather than a
1066/// full URL parser; the proxy itself is HTTP-only in v0.
1067fn parse_host_port(url: &str) -> Option<(String, u16)> {
1068    let (default_port, rest) = if let Some(r) = url.strip_prefix("http://") {
1069        (80u16, r)
1070    } else if let Some(r) = url.strip_prefix("https://") {
1071        (443u16, r)
1072    } else {
1073        (80u16, url)
1074    };
1075    // Authority is everything up to the first '/'; drop any `user:pass@` userinfo.
1076    let authority = rest.split('/').next().unwrap_or(rest);
1077    let authority = authority.rsplit('@').next().unwrap_or(authority);
1078    if authority.is_empty() {
1079        return None;
1080    }
1081    // Bracketed IPv6 literal: `[::1]` or `[::1]:port`.
1082    if let Some(after) = authority.strip_prefix('[') {
1083        let (host, tail) = after.split_once(']')?;
1084        let port = match tail.strip_prefix(':') {
1085            Some(p) => p.parse().ok()?,
1086            None => default_port,
1087        };
1088        return Some((host.to_string(), port));
1089    }
1090    match authority.rsplit_once(':') {
1091        // Reject an empty host (e.g. `http://:3000`) rather than deferring the failure to a
1092        // connect call — the "usable host" contract is checked here.
1093        Some((host, port)) if !host.is_empty() => Some((host.to_string(), port.parse().ok()?)),
1094        Some(_) => None,
1095        None => Some((authority.to_string(), default_port)),
1096    }
1097}
1098
1099/// Resolve a secret from the environment, supporting a `*_FILE` indirection for Docker/K8s
1100/// secret mounts (`EDGEGUARD_JWT_SECRET` *or* `EDGEGUARD_JWT_SECRET_FILE` pointing at a file
1101/// whose contents are the secret). The direct variable takes precedence when both are set; a
1102/// `*_FILE` that can't be read is a hard error (a misconfigured secret mount must fail loudly,
1103/// not silently fall back to no secret). A trailing newline (the common `echo`/editor artifact)
1104/// is trimmed. Returns `None` when neither is set / both are empty, so the caller keeps the
1105/// file/default value.
1106fn env_or_file(name: &str) -> Result<Option<String>> {
1107    if let Ok(v) = env::var(name) {
1108        if !v.is_empty() {
1109            return Ok(Some(v));
1110        }
1111    }
1112    let file_var = format!("{name}_FILE");
1113    if let Ok(path) = env::var(&file_var) {
1114        if !path.is_empty() {
1115            let content = std::fs::read_to_string(&path)
1116                .with_context(|| format!("reading {file_var} ({path})"))?;
1117            let trimmed = content.trim_end_matches(['\n', '\r']);
1118            if !trimmed.is_empty() {
1119                return Ok(Some(trimmed.to_string()));
1120            }
1121        }
1122    }
1123    Ok(None)
1124}
1125
1126/// Parse a human size like "2MiB", "512KB", "1048576" into bytes.
1127pub fn parse_size(s: &str) -> Result<usize> {
1128    let s = s.trim();
1129    let (num, mult): (&str, usize) = if let Some(n) = s.strip_suffix("GiB") {
1130        (n, 1024 * 1024 * 1024)
1131    } else if let Some(n) = s.strip_suffix("MiB") {
1132        (n, 1024 * 1024)
1133    } else if let Some(n) = s.strip_suffix("KiB") {
1134        (n, 1024)
1135    } else if let Some(n) = s.strip_suffix("GB") {
1136        (n, 1_000_000_000)
1137    } else if let Some(n) = s.strip_suffix("MB") {
1138        (n, 1_000_000)
1139    } else if let Some(n) = s.strip_suffix("KB") {
1140        (n, 1_000)
1141    } else if let Some(n) = s.strip_suffix('B') {
1142        (n, 1)
1143    } else {
1144        (s, 1)
1145    };
1146    let n: usize = num
1147        .trim()
1148        .parse()
1149        .with_context(|| format!("invalid size: {s}"))?;
1150    n.checked_mul(mult)
1151        .with_context(|| format!("size too large: {s}"))
1152}
1153
1154/// Parse a rate like "60/min" into (count, period).
1155pub fn parse_rate(s: &str) -> Result<(u32, Duration)> {
1156    let (n, unit) = s
1157        .split_once('/')
1158        .with_context(|| format!("invalid rate (expected N/unit): {s}"))?;
1159    let count: u32 = n
1160        .trim()
1161        .parse()
1162        .with_context(|| format!("invalid rate count: {s}"))?;
1163    let period = match unit.trim() {
1164        "s" | "sec" | "second" => Duration::from_secs(1),
1165        "m" | "min" | "minute" => Duration::from_secs(60),
1166        "h" | "hour" => Duration::from_secs(3600),
1167        other => anyhow::bail!("unsupported rate unit: {other}"),
1168    };
1169    Ok((count, period))
1170}
1171
1172/// Parse a timeout like "30s", "500ms", "2m", or a bare number of seconds ("45"). "0"
1173/// yields a zero duration, which callers treat as "disabled".
1174pub fn parse_duration(s: &str) -> Result<Duration> {
1175    let s = s.trim();
1176    // Order matters: check "ms" before the single-char "s"/"m" suffixes.
1177    if let Some(n) = s.strip_suffix("ms") {
1178        let ms: u64 = n
1179            .trim()
1180            .parse()
1181            .with_context(|| format!("invalid duration: {s}"))?;
1182        Ok(Duration::from_millis(ms))
1183    } else if let Some(n) = s.strip_suffix('s') {
1184        let secs: u64 = n
1185            .trim()
1186            .parse()
1187            .with_context(|| format!("invalid duration: {s}"))?;
1188        Ok(Duration::from_secs(secs))
1189    } else if let Some(n) = s.strip_suffix('m') {
1190        let mins: u64 = n
1191            .trim()
1192            .parse()
1193            .with_context(|| format!("invalid duration: {s}"))?;
1194        let secs = mins
1195            .checked_mul(60)
1196            .with_context(|| format!("duration too large: {s}"))?;
1197        Ok(Duration::from_secs(secs))
1198    } else if let Some(n) = s.strip_suffix('h') {
1199        let hours: u64 = n
1200            .trim()
1201            .parse()
1202            .with_context(|| format!("invalid duration: {s}"))?;
1203        let secs = hours
1204            .checked_mul(3_600)
1205            .with_context(|| format!("duration too large: {s}"))?;
1206        Ok(Duration::from_secs(secs))
1207    } else if let Some(n) = s.strip_suffix('d') {
1208        let days: u64 = n
1209            .trim()
1210            .parse()
1211            .with_context(|| format!("invalid duration: {s}"))?;
1212        let secs = days
1213            .checked_mul(86_400)
1214            .with_context(|| format!("duration too large: {s}"))?;
1215        Ok(Duration::from_secs(secs))
1216    } else {
1217        let secs: u64 = s
1218            .parse()
1219            .with_context(|| format!("invalid duration: {s}"))?;
1220        Ok(Duration::from_secs(secs))
1221    }
1222}
1223
1224#[cfg(test)]
1225mod tests {
1226    use super::*;
1227
1228    #[test]
1229    fn parse_size_units_and_plain_bytes() {
1230        assert_eq!(parse_size("0").unwrap(), 0);
1231        assert_eq!(parse_size("1048576").unwrap(), 1_048_576);
1232        assert_eq!(parse_size("512B").unwrap(), 512);
1233        assert_eq!(parse_size("1KB").unwrap(), 1_000);
1234        assert_eq!(parse_size("1KiB").unwrap(), 1_024);
1235        assert_eq!(parse_size("2MiB").unwrap(), 2 * 1024 * 1024);
1236        assert_eq!(parse_size("16MiB").unwrap(), 16 * 1024 * 1024);
1237        assert_eq!(parse_size("1GiB").unwrap(), 1024 * 1024 * 1024);
1238        // surrounding / internal whitespace is tolerated
1239        assert_eq!(parse_size("  4 MiB ").unwrap(), 4 * 1024 * 1024);
1240    }
1241
1242    #[test]
1243    fn parse_size_rejects_garbage_and_overflow() {
1244        assert!(parse_size("abc").is_err());
1245        assert!(parse_size("MiB").is_err());
1246        // would overflow usize -> Err, not a silent wrap
1247        assert!(parse_size("99999999999999999999GiB").is_err());
1248    }
1249
1250    #[test]
1251    fn parse_rate_counts_and_units() {
1252        assert_eq!(parse_rate("60/min").unwrap(), (60, Duration::from_secs(60)));
1253        assert_eq!(parse_rate("10/sec").unwrap(), (10, Duration::from_secs(1)));
1254        assert_eq!(
1255            parse_rate("1000/hour").unwrap(),
1256            (1000, Duration::from_secs(3600))
1257        );
1258        // short and long unit spellings, plus tolerated whitespace
1259        assert_eq!(parse_rate(" 5 / m ").unwrap(), (5, Duration::from_secs(60)));
1260    }
1261
1262    #[test]
1263    fn parse_rate_rejects_garbage() {
1264        assert!(parse_rate("60").is_err()); // no unit
1265        assert!(parse_rate("x/min").is_err()); // bad count
1266        assert!(parse_rate("60/year").is_err()); // bad unit
1267    }
1268
1269    #[test]
1270    fn probe_addr_defaults_to_app_port_in_coprocess_mode() {
1271        let cfg = Config::default();
1272        assert_eq!(
1273            cfg.upstream_probe_addr(),
1274            Some(("127.0.0.1".to_string(), cfg.server.app_port))
1275        );
1276    }
1277
1278    #[test]
1279    fn parse_host_port_handles_schemes_paths_and_ipv6() {
1280        assert_eq!(
1281            parse_host_port("http://127.0.0.1:3000"),
1282            Some(("127.0.0.1".to_string(), 3000))
1283        );
1284        // a trailing path is ignored
1285        assert_eq!(
1286            parse_host_port("http://app.internal:8080/health"),
1287            Some(("app.internal".to_string(), 8080))
1288        );
1289        // port defaults from the scheme
1290        assert_eq!(
1291            parse_host_port("https://example.com"),
1292            Some(("example.com".to_string(), 443))
1293        );
1294        assert_eq!(
1295            parse_host_port("http://example.com"),
1296            Some(("example.com".to_string(), 80))
1297        );
1298        // bracketed IPv6 literal, with and without an explicit port
1299        assert_eq!(
1300            parse_host_port("http://[::1]:3000"),
1301            Some(("::1".to_string(), 3000))
1302        );
1303        assert_eq!(
1304            parse_host_port("http://[2001:db8::1]"),
1305            Some(("2001:db8::1".to_string(), 80))
1306        );
1307    }
1308
1309    #[test]
1310    fn parse_host_port_rejects_empty_or_unusable_host() {
1311        // empty host (port only) is not a usable probe target
1312        assert_eq!(parse_host_port("http://:3000"), None);
1313        // non-numeric port
1314        assert_eq!(parse_host_port("http://host:notaport"), None);
1315    }
1316
1317    #[test]
1318    fn parse_duration_units_and_bare_seconds() {
1319        assert_eq!(parse_duration("30s").unwrap(), Duration::from_secs(30));
1320        assert_eq!(parse_duration("500ms").unwrap(), Duration::from_millis(500));
1321        assert_eq!(parse_duration("2m").unwrap(), Duration::from_secs(120));
1322        assert_eq!(parse_duration("3h").unwrap(), Duration::from_secs(10_800));
1323        assert_eq!(parse_duration("2d").unwrap(), Duration::from_secs(172_800));
1324        assert_eq!(parse_duration("45").unwrap(), Duration::from_secs(45));
1325        // "0" disables (zero duration); callers map it to "no timeout"
1326        assert_eq!(parse_duration("0").unwrap(), Duration::ZERO);
1327        assert_eq!(parse_duration("  10s ").unwrap(), Duration::from_secs(10));
1328    }
1329
1330    #[test]
1331    fn with_policy_from_keeps_local_plumbing_takes_policy() {
1332        let mut local = Config::default();
1333        local.server.port = 9999;
1334        local.server.upstream = "http://up:1".into();
1335        local.control_plane.enabled = true;
1336        // A pushed policy that changes auth + disables rate limiting.
1337        let policy = "[auth]\nmode = \"apikey\"\n\n[ratelimit]\nenabled = false\n";
1338        let merged = local.with_policy_from(policy).unwrap();
1339        // Local server / control-plane settings are preserved...
1340        assert_eq!(merged.server.port, 9999);
1341        assert_eq!(merged.server.upstream, "http://up:1");
1342        assert!(merged.control_plane.enabled);
1343        // ...while the policy sections are taken from the pushed document.
1344        assert_eq!(merged.auth.mode, "apikey");
1345        assert!(!merged.ratelimit.enabled);
1346    }
1347
1348    #[test]
1349    fn with_policy_from_keeps_llm_telemetry_edge_local() {
1350        // Regression: `llm: p.llm` used to take the pushed policy's `llm.telemetry` wholesale,
1351        // silently repointing `endpoint`/`capture_content`/`sample_rate` even though telemetry
1352        // is documented as edge-local operational config (like `alerts`), not fleet-pushed
1353        // policy — a pushed policy could redirect span data to an attacker-controlled endpoint.
1354        let mut local = Config::default();
1355        local.llm.telemetry.enabled = true;
1356        local.llm.telemetry.endpoint = "http://local-collector:4318/v1/traces".into();
1357        local.llm.telemetry.capture_content = false;
1358        // A pushed policy that tries to repoint telemetry AND legitimately updates the price book.
1359        let policy = "[llm]\non_unpriced_model = \"block\"\n\n[llm.telemetry]\nenabled = true\nendpoint = \"http://evil:4318/v1/traces\"\ncapture_content = true\n";
1360        let merged = local.with_policy_from(policy).unwrap();
1361        // Telemetry stayed exactly as configured at the edge...
1362        assert_eq!(
1363            merged.llm.telemetry.endpoint,
1364            "http://local-collector:4318/v1/traces"
1365        );
1366        assert!(!merged.llm.telemetry.capture_content);
1367        // ...while the rest of `llm` still took the pushed policy.
1368        assert_eq!(merged.llm.on_unpriced_model, "block");
1369    }
1370
1371    #[test]
1372    fn with_policy_from_rejects_bad_toml() {
1373        assert!(Config::default()
1374            .with_policy_from("not = valid = toml")
1375            .is_err());
1376    }
1377
1378    #[test]
1379    fn parse_duration_rejects_garbage() {
1380        assert!(parse_duration("abc").is_err());
1381        assert!(parse_duration("10x").is_err());
1382        assert!(parse_duration("s").is_err());
1383    }
1384
1385    #[test]
1386    fn env_or_file_reads_file_trims_newline_and_prefers_direct() {
1387        // A uniquely-named var so this doesn't collide with any real config key or another test.
1388        let name = "EDGEGUARD_TEST_SECRET_QZX";
1389        let file_var = format!("{name}_FILE");
1390        let path = std::env::temp_dir().join("edgeguard_test_secret_qzx.txt");
1391        std::fs::write(&path, "s3cr3t\n").unwrap();
1392
1393        // No direct var, only *_FILE -> read the file (trailing newline trimmed).
1394        std::env::remove_var(name);
1395        std::env::set_var(&file_var, &path);
1396        assert_eq!(env_or_file(name).unwrap().as_deref(), Some("s3cr3t"));
1397
1398        // Direct var set -> it wins over the file.
1399        std::env::set_var(name, "direct");
1400        assert_eq!(env_or_file(name).unwrap().as_deref(), Some("direct"));
1401
1402        // Neither set -> None (caller keeps the file/default value).
1403        std::env::remove_var(name);
1404        std::env::remove_var(&file_var);
1405        assert_eq!(env_or_file(name).unwrap(), None);
1406
1407        // A *_FILE pointing at a missing path is a hard error, not a silent fallback.
1408        std::env::set_var(&file_var, "/nonexistent/edgeguard/secret");
1409        assert!(env_or_file(name).is_err());
1410        std::env::remove_var(&file_var);
1411
1412        let _ = std::fs::remove_file(&path);
1413    }
1414}