mirror of
https://github.com/telemt/telemt.git
synced 2026-11-23 07:46:37 +03:00
Compare commits
30 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 66708d2866 | |||
| 6d65074389 | |||
| d5e01460de | |||
| 82baf0dda4 | |||
| c42ef876be | |||
| 8fce8fb0df | |||
| 982c4e4a34 | |||
| b1502b629b | |||
| af951f4db3 | |||
| b1d8f221d6 | |||
| af806d2f3d | |||
| 4dbd834840 | |||
| 4ff565193f | |||
| 55e7b16ec3 | |||
| 996274bed3 | |||
| 5040195ca7 | |||
| e0cbced3e9 | |||
| 108e14f628 | |||
| 84e5b827a6 | |||
| 907209cafa | |||
| c89cf46bd9 | |||
| 4635ecadd3 | |||
| 3df59cfa28 | |||
| ed2139502f | |||
| b144075b73 | |||
| 9ee8f99413 | |||
| 70b357a3bd | |||
| 56ca6e2582 | |||
| 477d819fd9 | |||
| cecc8df758 |
@@ -210,6 +210,14 @@ Use English for newly written or substantively updated source comments, document
|
||||
- Follow local formatting and naming patterns. Avoid style-only churn.
|
||||
- Remove an obsolete item only when doing so is necessary for the task; do not perform general warning or dead-code cleanup by default.
|
||||
|
||||
### 12.1 Mermaid Diagram Validation
|
||||
|
||||
- When adding or changing Mermaid diagrams, validate every Mermaid block in the affected documents, including localized versions, with a real Mermaid parser (`mermaid.parse`) or Mermaid CLI (`mmdc`). Checking Markdown fences alone is insufficient.
|
||||
- Fix parse errors before completing the change. For syntax fixes, reproduce the original failure before validating the correction when practical.
|
||||
- When changing diagram layout, also render and inspect readability, label clipping, and connections when a renderer is available.
|
||||
- Avoid unescaped semicolons in sequence-diagram labels and notes because Mermaid can interpret them as statement separators. Use commas or supported escaping instead.
|
||||
- Report the Mermaid version and actual validation results. Distinguish parser validation, rendering, and GitHub verification; mark checks that were not executed as **NOT RUN** or **BLOCKED**, as applicable.
|
||||
|
||||
## 13. Communication and Deliverables
|
||||
|
||||
For a simple answer, answer directly. For a nontrivial implementation, briefly convey the plan, meaningful impact, and verification. Avoid repetitive process narration.
|
||||
|
||||
Generated
+25
-8
@@ -2780,7 +2780,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "telemt"
|
||||
version = "3.5.15"
|
||||
version = "3.5.17"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"anyhow",
|
||||
@@ -2834,6 +2834,7 @@ dependencies = [
|
||||
"tokio-tungstenite",
|
||||
"tokio-util",
|
||||
"toml",
|
||||
"toml_edit",
|
||||
"tracing",
|
||||
"tracing-appender",
|
||||
"tracing-subscriber",
|
||||
@@ -3076,27 +3077,40 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "toml_datetime"
|
||||
version = "1.1.1+spec-1.1.0"
|
||||
version = "1.1.3+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7"
|
||||
checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_parser"
|
||||
version = "1.1.3+spec-1.1.0"
|
||||
name = "toml_edit"
|
||||
version = "0.25.19+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56"
|
||||
checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218"
|
||||
dependencies = [
|
||||
"indexmap",
|
||||
"toml_datetime",
|
||||
"toml_parser",
|
||||
"toml_writer",
|
||||
"winnow",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_parser"
|
||||
version = "1.1.5+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
|
||||
dependencies = [
|
||||
"winnow",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_writer"
|
||||
version = "1.1.2+spec-1.1.0"
|
||||
version = "1.2.0+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2"
|
||||
checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"
|
||||
|
||||
[[package]]
|
||||
name = "tower"
|
||||
@@ -3697,6 +3711,9 @@ name = "winnow"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "telemt"
|
||||
version = "3.5.15"
|
||||
version = "3.5.17"
|
||||
edition = "2024"
|
||||
rust-version = "1.88"
|
||||
|
||||
@@ -49,6 +49,7 @@ shadowsocks = { version = "1.24.0", default-features = false, features = [
|
||||
serde = { version = "1.0.229", features = ["derive"] }
|
||||
serde_json = "1.0.151"
|
||||
toml = "1.1.5"
|
||||
toml_edit = "0.25.19"
|
||||
x509-parser = "0.18.1"
|
||||
|
||||
# Utils
|
||||
|
||||
+593
-32
@@ -12,6 +12,7 @@ API runtime is configured in `[server.api]`.
|
||||
| `enabled` | `bool` | `true` | Enables REST API listener. |
|
||||
| `listen` | `string` (`IP:PORT`) | `0.0.0.0:9091` | API bind address. |
|
||||
| `whitelist` | `CIDR[]` | `127.0.0.0/8` | Source IP allowlist. Empty list means allow all. |
|
||||
| `gray_action` | `"drop"`, `"api"`, `"200"` | `"drop"` | Response to a direct peer outside the whitelist: close without HTTP, structured `403 forbidden`, or empty `200` respectively. |
|
||||
| `auth_header` | `string` | `""` | Exact value for `Authorization` header. Empty disables header auth. |
|
||||
| `request_body_limit_bytes` | `usize` | `65536` | Maximum request body size. Must be within `[1, 1048576]`. |
|
||||
| `minimal_runtime_enabled` | `bool` | `true` | Enables runtime snapshot endpoints requiring ME pool read-lock aggregation. |
|
||||
@@ -32,6 +33,16 @@ Runtime validation for API config:
|
||||
- `server.api.runtime_edge_top_n` must be within `[1, 1000]`.
|
||||
- `server.api.runtime_edge_events_capacity` must be within `[16, 4096]`.
|
||||
|
||||
The file watcher retains every `server.api.*` field. Explicit generation reload
|
||||
applies `whitelist`, `gray_action`, `auth_header`, `request_body_limit_bytes`,
|
||||
`minimal_runtime_enabled`, `minimal_runtime_cache_ttl_ms`,
|
||||
`runtime_edge_enabled`, `runtime_edge_cache_ttl_ms`, `runtime_edge_top_n`, and
|
||||
`read_only`. `enabled`, `listen`, and `runtime_edge_events_capacity` remain
|
||||
process-owned and require a process restart. The five [observability settings](#api-observability-settings)
|
||||
are editable through `PATCH /v1/config`; other API settings require editing the
|
||||
owning TOML source. A client polling after an authentication change must use the
|
||||
new header explicitly.
|
||||
|
||||
## Protocol Contract
|
||||
|
||||
| Item | Value |
|
||||
@@ -51,6 +62,10 @@ Runtime validation for API config:
|
||||
}
|
||||
```
|
||||
|
||||
`GET /v1/config/state` is the additive exception to the non-null revision: its
|
||||
`revision` equals `data.desired_revision` and is `null` when the desired source
|
||||
cannot be captured. Its effective runtime identity remains available.
|
||||
|
||||
### Error Envelope
|
||||
```json
|
||||
{
|
||||
@@ -67,7 +82,9 @@ Runtime validation for API config:
|
||||
|
||||
Requests are processed in this order:
|
||||
1. `api_enabled` gate (`503 api_disabled` if disabled).
|
||||
2. Source IP whitelist gate (`403 forbidden`).
|
||||
2. Source IP whitelist gate: `gray_action="drop"` closes without an HTTP
|
||||
response, `"api"` returns `403 forbidden`, and `"200"` returns an empty
|
||||
`200 OK` with `text/html; charset=utf-8`.
|
||||
3. `Authorization` header gate when configured (`401 unauthorized`).
|
||||
4. Route and method matching (`404 not_found` or `405 method_not_allowed`).
|
||||
5. `read_only` gate for mutating routes (`403 read_only`).
|
||||
@@ -77,6 +94,24 @@ Requests are processed in this order:
|
||||
Notes:
|
||||
- Whitelist is evaluated against the direct TCP peer IP (`SocketAddr::ip`), without `X-Forwarded-For` support.
|
||||
- `Authorization` check is exact constant-time byte equality against configured `auth_header`.
|
||||
- `gray_action` does not grant API access and does not mask authentication or
|
||||
read-only failures for allowed peers. An empty gray `200` is not a JSON success
|
||||
envelope; clients must not interpret it as a successful operation.
|
||||
|
||||
## Python client and CLI
|
||||
|
||||
The standard-library [Python client](../../../tools/telemt_api.py) covers the 53
|
||||
JSON operations, including discovery, preflight/state, user quota/period/rates,
|
||||
generation reload and WEB lifecycle/session controls. The HTML `/web-status`
|
||||
viewer remains a browser endpoint. See the [client guide](PYTHON_CLIENT.md) for
|
||||
command and method mappings, exact sparse/null updates, source/runtime
|
||||
preconditions, process references and polling examples.
|
||||
|
||||
`APIResponse.http_status` retains HTTP status independently from the JSON `ok`
|
||||
flag. Readiness `503` and WEB tombstone `410` with `ok=true` are returned as data
|
||||
only by their documented wrappers. Mutations returning `202` remain accepted
|
||||
operations or pending publication; they are not silently promoted to success.
|
||||
`TelemtAPIError` retains `http_status`, `code`, `request_id` and field `details`.
|
||||
|
||||
## Endpoint Matrix
|
||||
|
||||
@@ -84,6 +119,9 @@ Notes:
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `GET` | `/v1/health` | none | `200` | `HealthData` |
|
||||
| `GET` | `/v1/health/ready` | none | `200` or `503` | `HealthReadyData` |
|
||||
| `GET` | `/v1/capabilities` | none | `200` | `CapabilitiesData` |
|
||||
| `GET` | `/v1/config/schema` | none | `200` | `ConfigSchemaData` |
|
||||
| `GET` | `/v1/config/state` | optional `sections` query | `200` | `ConfigStateData`, including partial results |
|
||||
| `GET` | `/v1/system/info` | none | `200` | `SystemInfoData` |
|
||||
| `GET` | `/v1/runtime/gates` | none | `200` | `RuntimeGatesData` |
|
||||
| `GET` | `/v1/runtime/initialization` | none | `200` | `RuntimeInitializationData` |
|
||||
@@ -117,8 +155,11 @@ Notes:
|
||||
| `GET` | `/v1/stats/users/active-ips` | none | `200` | `UserActiveIps[]` |
|
||||
| `GET` | `/v1/stats/users` | none | `200` | `UserInfo[]` |
|
||||
| `GET` | `/v1/stats/users/quota` | none | `200` | User quota counters and recurring schedule status in `data.users`. |
|
||||
| `GET` | `/v1/access/policy` | none | `200` | Desired/effective access policy |
|
||||
| `PATCH` | `/v1/access/policy` | `AccessPolicyPatch` | `200` | Desired/effective access policy with changed paths |
|
||||
| `GET` | `/v1/config` | none | `200` | `ConfigData` |
|
||||
| `PATCH` | `/v1/config` | sparse JSON object; optional reload query | `200` or `202` | `PatchConfigResponse` |
|
||||
| `POST` | `/v1/config/validate` | same sparse patch, preconditions and reload query | `200` | `ConfigValidationData` |
|
||||
| `POST` | `/v1/system/reload` | `ReloadRequest` or empty body | `202` | `ReloadAccepted` |
|
||||
| `GET` | `/v1/system/reload/{id}` | none | `200` | `ReloadStatus` |
|
||||
| `GET` | `/v1/users` | none | `200` | `UserInfo[]` |
|
||||
@@ -137,6 +178,9 @@ Notes:
|
||||
| --- | --- |
|
||||
| `GET /v1/health` | Returns basic API liveness and current `read_only` flag. |
|
||||
| `GET /v1/health/ready` | Returns readiness based on admission state and upstream health; returns `503` when not ready. |
|
||||
| `GET /v1/capabilities` | Lists implemented operations, feature gates, runtime prerequisites and mutation policy. |
|
||||
| `GET /v1/config/schema` | Lists configuration paths and their static value, exposure and application contracts without configured values. |
|
||||
| `GET /v1/config/state` | Compares redacted desired and published snapshots, with generation/epoch, pending fields and owner outcomes; permits read-only mode. |
|
||||
| `GET /v1/system/info` | Returns binary/build metadata, process uptime, config path/hash, and reload counters. |
|
||||
| `GET /v1/runtime/gates` | Returns admission, ME readiness, fallback/reroute, and startup gate state. |
|
||||
| `GET /v1/runtime/initialization` | Returns startup progress, ME initialization status, and per-component timeline. |
|
||||
@@ -168,8 +212,11 @@ Notes:
|
||||
| `POST /v1/runtime/web/lifecycle/resume` | Cancels an active drain, if any, and reopens only the operator-owned admission fence. |
|
||||
| `GET /v1/stats/users/active-ips` | Returns users that currently have non-empty active source-IP lists. |
|
||||
| `GET /v1/stats/users` | Alias of `GET /v1/users`; returns disk-first user views with runtime lag flag. |
|
||||
| `GET /v1/access/policy` | Desired and published shared access limits and CIDR rate rules, with source revision and runtime token. |
|
||||
| `PATCH /v1/access/policy` | Atomic policy edit; optional `If-Match` and `If-Runtime-Match`. Watcher publication is asynchronous. |
|
||||
| `GET /v1/config` | Returns the current editable config sections as JSON (no `access.*`) plus the revision. |
|
||||
| `PATCH /v1/config` | Applies a sparse patch and optionally submits an in-process runtime reload to Maestro. |
|
||||
| `POST /v1/config/validate` | Prepares and classifies a candidate without persistence or runtime publication; allowed in read-only mode. |
|
||||
| `POST /v1/system/reload` | Loads and validates the current on-disk config, then asks Maestro to prepare and activate a new runtime generation. |
|
||||
| `GET /v1/system/reload/{id}` | Returns one retained reload status; the coordinator retains the most recent 32 operations. |
|
||||
| `GET /v1/users` | Returns disk-first user views sorted by username. |
|
||||
@@ -188,14 +235,17 @@ Notes:
|
||||
| --- | --- | --- |
|
||||
| `400` | `bad_request` | Invalid JSON, validation failures, malformed request body. |
|
||||
| `400` | `access_not_editable` | `PATCH /v1/config` body contains an `access` key (managed via users API). |
|
||||
| `400` | `section_not_editable` | `PATCH /v1/config` body contains `network` or an unknown top-level key. |
|
||||
| `400` | `field_not_editable` | `PATCH /v1/config` body contains a forbidden nested field under a partially editable section (e.g. `server.api`, `server.port`). |
|
||||
| `400` | `section_not_editable` | `PATCH /v1/config` body contains an unknown top-level key or a non-null, non-object partial section. |
|
||||
| `400` | `field_not_editable` | `PATCH /v1/config` body contains a forbidden nested field under a partially editable section (e.g. `server.api.auth_header`, `server.port`, `network.ipv4`). |
|
||||
| `401` | `unauthorized` | Missing/invalid `Authorization` when `auth_header` is configured. |
|
||||
| `403` | `forbidden` | Source IP is not allowed by whitelist. |
|
||||
| `403` | `read_only` | Mutating endpoint called while `read_only=true`. |
|
||||
| `404` | `not_found` | Unknown route, unknown user, or unsupported sub-route. |
|
||||
| `405` | `method_not_allowed` | Unsupported method for `/v1/users/{username}` route shape. |
|
||||
| `409` | `revision_conflict` | `If-Match` mismatch, or the source graph/owner changed during a fenced write. |
|
||||
| `409` | `runtime_conflict` | Active generation/config publication changed during config preparation, or `If-Runtime-Match` is stale. |
|
||||
| `429` | `config_preflight_busy` | Both config preflight preparation slots are occupied. |
|
||||
| `504` | `config_preflight_timeout` | Config preflight exceeded its 30-second deadline. |
|
||||
| `409` | `reload_in_progress` | Another reload operation is non-terminal. |
|
||||
| `409` | `web_runtime_mismatch` | A runtime instance, session reference, or operation reference belongs to another WEB process instance. |
|
||||
| `409` | `web_issuance_enabled` | A WEB close-all operation was requested while effective issuance remained enabled. |
|
||||
@@ -227,6 +277,115 @@ Notes:
|
||||
| `POST /v1/users/{username}/disable/` | Trailing slash is trimmed and the route matches `disable`. |
|
||||
| `POST /v1/users/{username}/reset-quota/` | Trailing slash is trimmed and the route matches `reset-quota`. |
|
||||
|
||||
## Discovery
|
||||
|
||||
`GET /v1/capabilities` and `GET /v1/config/schema` use the common success envelope
|
||||
and the same enabled, direct-peer whitelist and Authorization gates as other API
|
||||
routes. Both work with `read_only=true`, reject nonempty query strings with
|
||||
`400 bad_request`, and reject other methods with `405` and `Allow: GET`. Whitelist
|
||||
denial follows the configured `gray_action`: `api` returns `403`, `200` returns an
|
||||
empty response, and `drop` closes the connection. Discovery grants no separate
|
||||
observer role.
|
||||
|
||||
The envelope revision remains the current recursive **disk source** revision.
|
||||
It does not identify a runtime generation or prove that desired values have been
|
||||
applied. Reading that revision requires the source graph to remain readable.
|
||||
|
||||
### CapabilitiesData
|
||||
|
||||
Top-level fields are `api_version` (`v1`), `schema_version` (`1`),
|
||||
`software_version`, `config_schema`, `openapi_artifact`, `read_only`,
|
||||
`availability_scope`, and `operations`. `openapi_artifact` identifies the versioned
|
||||
repository artifact; it is not another HTTP route.
|
||||
|
||||
Each operation has a stable `id`, `method`, canonical `path`, optional `aliases`,
|
||||
`gate`, possible success status codes in `success`, `credential_bearing`, optional
|
||||
request `body` schema name, `optional_body`, `exact_json_content_type`, and
|
||||
`if_match`. The last flag means the route accepts an optional source revision;
|
||||
WEB controls instead use their existing process-instance fence.
|
||||
|
||||
| Field | Meaning |
|
||||
| --- | --- |
|
||||
| `supported` | This build implements the operation; currently always `true` for listed entries. |
|
||||
| `enabled` | The API and this operation's diagnostic feature gate are enabled. A diagnostic route may still return HTTP 200 with a disabled-state payload. |
|
||||
| `available` | `true` or `false` for sampled feature/runtime-source prerequisites; `null` when a source was not sampled or its lock was busy. |
|
||||
| `mutable` | This is a mutation and the API allows writes. It is independent of runtime availability and request validation. |
|
||||
| `disabled_reason` | Present for `api_disabled` or `feature_disabled`. |
|
||||
| `unavailable_reason` | Present for `source_unavailable`, `web_runtime_unavailable`, `snapshot_busy`, or `availability_not_sampled`. |
|
||||
| `mutation_blocked_reason` | `read_only` when the write policy blocks a mutation. |
|
||||
| `read_only_operation` | Explicitly non-mutating operation despite its method; currently config validation uses POST. It remains `mutable=false` without a read-only rejection. |
|
||||
| `if_runtime_match` | Supports the optional active-publication precondition from config validation. |
|
||||
|
||||
Availability describes prerequisites at the time of sampling, not health or the
|
||||
outcome of a later request. Discovery does not run self-tests, enumerate sessions,
|
||||
aggregate upstream statistics, or wait for the ME pool lock. WEB reads require a
|
||||
published runtime in `Running` or `Draining`; controls require `Running`.
|
||||
Resource identity, exact snapshot contention, admission fences and operation
|
||||
capacity are checked by the requested operation itself.
|
||||
|
||||
The `minimal` gate on `/v1/stats/upstreams` describes its optional runtime
|
||||
snapshot; its existing counters remain readable when that snapshot is disabled.
|
||||
`/v1/runtime/upstream_quality` has no minimal-feature gate; discovery leaves its
|
||||
optional source availability unsampled. `/v1/runtime/web/status` remains available
|
||||
to report an absent WEB runtime. Existing endpoint-local `enabled` fields retain
|
||||
their original meanings.
|
||||
|
||||
### ConfigSchemaData
|
||||
|
||||
`fields` contains canonical paths for the full serialized configuration model,
|
||||
including file-only policy. Dot notation selects members, `[]` selects an array
|
||||
element, and `{username}`, `{cidr}`, `{hostname}` or `{dc}` denotes a dynamic map
|
||||
key. A path entry describes a field; it is not a JSON Pointer or a PATCH request.
|
||||
|
||||
| Field | Meaning |
|
||||
| --- | --- |
|
||||
| `path`, `aliases`, `description` | Canonical field identity, accepted source aliases where applicable, and purpose. |
|
||||
| `value`, `unit` | JSON Schema 2020-12 vocabulary for non-null canonical values, including known enums and bounds, plus a unit when applicable. Absence and null are described separately by `default_kind` and `api.null_behavior`; source shorthand and normalization may accept additional forms. |
|
||||
| `default_kind`, `default` | Unconfigured type defaults, before loader normalization. `unset` has a null default; `required`, `nested_fields`, `map_entry` and `redacted` omit the value. |
|
||||
| `sensitivity` | `public`, `deployment` or `credential`. This classifies the field without exposing its configured value. |
|
||||
| `dependencies`, `constraints` | Referenced fields and relevant validation or normalization rules. Complete candidate validation remains authoritative. |
|
||||
| `api.config_read`, `api.config_write` | Static config GET/PATCH allowlist membership, independent of current read-only policy. Partially exposed containers must be inspected through their child entries. |
|
||||
| `api.read_routes`, `api.write_routes`, `api.request_field` | Related API views/mutations and a users DTO field where applicable. A user view is not a lossless export of the source map. |
|
||||
| `api.non_editable_reason`, `api.null_behavior` | Why config PATCH does not own a field and how its applicable mutation treats null. |
|
||||
| `apply.watcher`, `apply.reload`, `apply.effect` | Application support and the relevant consumption boundary. |
|
||||
|
||||
`apply.watcher` is `supported`, `unsupported`, `conditional`, `mixed` for a
|
||||
container, or `not_applicable` for source-only validation. `apply.reload` uses
|
||||
`supported`, `process_restart`, `conditional`, `mixed`, or `not_applicable`.
|
||||
Conditional decisions require the complete candidate and active process policy;
|
||||
schema discovery does not preview them. Watcher publication also does not imply
|
||||
that existing connections reconstruct their buffers or session policy. Effects
|
||||
identify new-connection consumption, subsequent ME policy updates, preserved
|
||||
session contracts, or the instant/drain generation policy as applicable.
|
||||
|
||||
The schema is built once from unconfigured types and checked metadata. It never
|
||||
receives the active configuration or serialized disk contents. Credentials have
|
||||
no default payload, including the built-in example user secret. Loader-derived
|
||||
values, environment-derived capacities and effective process state are not
|
||||
reported as defaults. Tagged upstream and WEB decoy fields apply only to their
|
||||
respective variant, as described by their constraints.
|
||||
|
||||
`config_patch` states the existing shared semantics: objects merge recursively,
|
||||
arrays replace wholesale, object null members are ignored before candidate
|
||||
validation, and reset is unsupported. One mutation may touch only one independently
|
||||
writable source. This differs from supported user PATCH fields, where null
|
||||
removes an override. Discovery does not expand either write allowlist.
|
||||
|
||||
### Versioned artifact and maintenance
|
||||
|
||||
[openapi-v1.json](openapi-v1.json) publishes the implemented routes, aliases,
|
||||
request shapes and common response envelopes, with detailed schemas for both
|
||||
discovery responses. Legacy response payloads and query filters remain described
|
||||
in this reference. The artifact is intentionally not a complete configuration
|
||||
validator; `/v1/config/schema` supplements it with field contracts.
|
||||
|
||||
Regenerate with `python3 tools/generate_api_openapi.py` and verify with
|
||||
`python3 tools/generate_api_openapi.py --check`. `cargo test --bin telemt
|
||||
api::discovery` checks route/field inventories, defaults, enums, application
|
||||
classification, credential exclusion and HTTP admission. Contract changes must
|
||||
update the registry and artifact together. Additive metadata and operations are
|
||||
compatible; incompatible discovery changes require a new `schema_version`.
|
||||
|
||||
## Body and JSON Semantics
|
||||
|
||||
- Request body is read only for mutating routes that define a body contract.
|
||||
@@ -261,6 +420,7 @@ Notes:
|
||||
| `rate_limit_down_bps` | `u64` | no | Per-user download rate limit in bits per second. |
|
||||
| `max_unique_ips` | `usize` | no | Per-user unique source IP limit. |
|
||||
| `enabled` | `bool` | no | User enable flag. Missing means enabled. `false` persists a disabled override. |
|
||||
| `source_deny` | `string[]` or `null` | no | CIDR list; omission retains any orphan rule, null removes it. Generation reload required. |
|
||||
|
||||
### `PatchUserRequest`
|
||||
| Field | Type | Required | Description |
|
||||
@@ -275,31 +435,122 @@ Notes:
|
||||
| `rate_limit_down_bps` | `u64` or `null` | no | Per-user download rate limit in bits per second; `null` removes the download direction limit. |
|
||||
| `max_unique_ips` | `usize` or `null` | no | Per-user unique source IP limit; `null` removes the per-user override. |
|
||||
| `enabled` | `bool` or `null` | no | `false` disables the user. `true` or `null` removes the disabled override, so the user is enabled. |
|
||||
| `source_deny` | `string[]` or `null` | no | Replace the CIDR list; omission preserves it, null removes the entry. Generation reload required. |
|
||||
|
||||
### Shared access policy
|
||||
|
||||
`GET /v1/access/policy` and `PATCH /v1/access/policy` use the ordinary
|
||||
administrative authorization and whitelist; mutations require `read_only=false`.
|
||||
Both return `200` with `data.desired`, `data.effective`, `data.runtime`
|
||||
(`active_generation`, `config_epoch`, `runtime_match`), `published_match`,
|
||||
`effective_scope="active_config_snapshot"`, `subsystem_convergence="unknown"`,
|
||||
`apply_mode="watcher"`, and the source-manifest `revision`. PATCH also returns
|
||||
`changed_paths`. These snapshots do not acknowledge completion by every consumer.
|
||||
|
||||
The policy contains exactly five fields:
|
||||
|
||||
- `user_max_tcp_conns_global_each`: nonnegative per-user TCP default; `0` is unlimited.
|
||||
- `user_max_unique_ips_global_each`: nonnegative per-user unique-IP default; `0` is unlimited.
|
||||
- `user_max_unique_ips_mode`: `active_window`, `time_window`, or `combined`.
|
||||
- `user_max_unique_ips_window_secs`: positive recent-IP window in seconds.
|
||||
- `cidr_rate_limits`: a map of explicit IPv4/IPv6 CIDRs or `*4/N`, `*6/N`, `*/N` templates
|
||||
to `{ "up_bps": ..., "down_bps": ... }`, in **bits per second**.
|
||||
|
||||
Omission preserves a field. Scalar `null` removes its authored setting and restores
|
||||
its type default. A non-null CIDR map merges entries: `null` removes that entry,
|
||||
and a rate object replaces the whole pair (omitted directions become `0`, meaning
|
||||
unlimited). At least one direction must be positive, and neither may exceed
|
||||
`100000000000`. A whole-map `null` clears all CIDR rules. Empty patches are rejected.
|
||||
Unknown fields, invalid prefixes/rates and duplicate normalized auto templates
|
||||
return `400`. Explicit CIDRs retain longest-prefix precedence over auto templates;
|
||||
`*/N` expands to IPv4 `/N` and IPv6 `/(N * 4)`. Existing bounded bursts are unchanged.
|
||||
|
||||
```json
|
||||
{
|
||||
"user_max_tcp_conns_global_each": 12,
|
||||
"cidr_rate_limits": {
|
||||
"192.0.2.0/24": {"up_bps": 8000000, "down_bps": 16000000},
|
||||
"*6/64": {"down_bps": 16000000},
|
||||
"203.0.113.0/24": null
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Edits use the exact field's source owner, or the nearest existing parent for
|
||||
insertion. Literal map keys are preserved. All changes in one request must belong
|
||||
to one independently writable source; ambiguous or multiple owners return
|
||||
`409 config_patch_not_atomic` without writing. The complete candidate is validated
|
||||
before atomic replacement. Other source files remain unchanged; the owner is
|
||||
edited structurally with comments retained where supported by the TOML editor.
|
||||
Stale `If-Match` returns `409 revision_conflict`; stale `If-Runtime-Match` returns
|
||||
`409 runtime_conflict`. Query parameters, including automatic reload, are rejected.
|
||||
Users, credentials, replay limits and `ignore_time_skew` are outside this endpoint.
|
||||
The legacy `PATCH /v1/config` still rejects the entire `access` section.
|
||||
|
||||
`UserInfo.limits` contains `desired` and nullable `effective` snapshots for
|
||||
`max_tcp_conns` and `max_unique_ips`. Each has `value` (null means unlimited),
|
||||
`configured_override` (null means no authored entry), `global_value`, and `origin`
|
||||
(`user_override`, `global_default`, `unlimited`). A zero user override inherits the
|
||||
global default. `effective` is null when the user is absent from the sampled runtime
|
||||
or no runtime snapshot was supplied. The scope is `active_config_snapshot` and
|
||||
`subsystem_convergence` is `unknown`; legacy top-level limit fields retain their
|
||||
desired-config fallback behavior. Policy edits do not cancel sessions or reset
|
||||
quota usage; subsequent admission/publication follows existing runtime behavior.
|
||||
|
||||
### `access.user_source_deny` via API
|
||||
- In current API surface, per-user deny-list is **not** exposed as a dedicated field in `CreateUserRequest` / `PatchUserRequest`.
|
||||
- Configure it in `config.toml` under `[access.user_source_deny]` and apply via normal config reload path.
|
||||
- Runtime behavior after apply:
|
||||
- auth succeeds for username/secret
|
||||
- source IP is checked against `access.user_source_deny[username]`
|
||||
- on match, handshake is rejected with the same fail-closed outcome as invalid auth
|
||||
|
||||
Example config:
|
||||
```toml
|
||||
[access.user_source_deny]
|
||||
alice = ["203.0.113.0/24", "2001:db8:abcd::/48"]
|
||||
bob = ["198.51.100.42/32"]
|
||||
User GET/create/PATCH expose `source_deny`, an IPv4/IPv6 CIDR array. Omission
|
||||
preserves the existing rule, an array replaces the entire list (`[]` means no
|
||||
denied networks), and explicit `null` removes that user's authored entry.
|
||||
Strict configuration accepts `[access.user_source_deny]`. Malformed networks or
|
||||
non-array values return `400` before writing. Changes to a username containing
|
||||
dots edit that literal key, preserving other users' deny rows.
|
||||
|
||||
`UserInfo.source_deny` is the desired list (empty when absent).
|
||||
`source_deny_status` contains `effective` (the list in the sampled request
|
||||
generation), `runtime_reload_required` (whether the lists differ),
|
||||
`apply_mode="generation_reload"`, `effective_scope="request_generation_snapshot"`,
|
||||
and `reload_endpoint="POST /v1/system/reload"`. Effective/reload fields are null
|
||||
when no runtime snapshot is available. Existing `in_runtime` and HTTP `200/202`
|
||||
only describe username membership; they do not prove deny-policy enforcement.
|
||||
|
||||
After persistence, explicitly submit an instant or drain generation reload using
|
||||
its returned source revision, then inspect reload status and the user's effective
|
||||
list. The watcher does not overlay these rules. Saving a list does not cancel
|
||||
sessions; retirement follows the selected reload mode. A reload that captured an
|
||||
older revision may still activate that older policy: the desired/effective
|
||||
comparison remains pending until a generation using the new revision is active.
|
||||
This comparison does not describe still-draining older generations.
|
||||
|
||||
User deletion retains source-deny rows. Recreating the same name with the field
|
||||
omitted inherits the retained row, including a rule already present in runtime.
|
||||
To remove it, PATCH `{"source_deny":null}` before deletion, or include
|
||||
`"source_deny":null` when recreating the user; removal also needs generation
|
||||
reload. A PATCH of a missing username still returns `404`.
|
||||
|
||||
The mutation edits the exact owning source, or the nearest existing parent for
|
||||
insertion. A request combining user-table and deny-rule changes in different
|
||||
files returns `409 config_patch_not_atomic` and writes neither file. Source
|
||||
revision fencing covers the entire include graph. After successful authentication,
|
||||
the existing TLS/MTProto source check still rejects matching addresses through
|
||||
the invalid-auth/fallback path without writing a protocol error or modifying the
|
||||
original ClientHello.
|
||||
|
||||
```json
|
||||
{"source_deny":["203.0.113.0/24","2001:db8:abcd::/48"]}
|
||||
```
|
||||
|
||||
### `PatchConfigRequest`
|
||||
|
||||
A sparse JSON object containing only the top-level config sections to modify. Each key must be one of the editable sections (`general`, `timeouts`, `censorship`, `upstreams`, `dc_overrides`, `web`) or the partially editable `server` object (only `listeners` is allowed under `server`; see below). Tables within a section are deep-merged field-by-field into the existing config; arrays and scalar values replace the existing value wholesale. Untouched table bodies and other source files remain byte-identical; a touched TOML table body is reserialized, so comments and formatting inside it can change.
|
||||
A sparse JSON object containing only the top-level config sections to modify. Each key must be one of the editable sections (`general`, `timeouts`, `censorship`, `upstreams`, `dc_overrides`, `web`) or the partially editable objects `server` (`listeners` and five API observability fields) and `network` (only `dns_overrides`; see below). Tables within a section are deep-merged field-by-field into the existing config; arrays and scalar values replace the existing value wholesale. Untouched table bodies and other source files remain byte-identical; touched TOML table bodies are reserialized, except for the field edits described below, so comments and formatting inside a rewritten body can change.
|
||||
|
||||
**Rejected keys:**
|
||||
- `access` → `400 access_not_editable` (users/secrets are managed via `POST/PATCH /v1/users`).
|
||||
- `network` or any unknown top-level key → `400 section_not_editable`.
|
||||
- `server` with any key other than `listeners` (e.g. `port`, `api`, `admin_api`) → `400 field_not_editable`.
|
||||
- An unknown top-level key or a non-null, non-object `server`/`network` value → `400 section_not_editable`.
|
||||
- `network` with any key other than `dns_overrides`, even when that key is null, → `400 field_not_editable`.
|
||||
- `server` with any key other than `listeners`/`api` (e.g. `port`, `admin_api`), or `server.api` with a key outside its five-field allowlist, even when null, → `400 field_not_editable`.
|
||||
- An object with no editable keys → `400 bad_request` (empty patch).
|
||||
- Within otherwise editable sections/fields, unknown nested fields, including fields with null values, → `400 bad_request` with `error.details[].code=unknown_field`, independently of `general.config_strict`. Known fields from an incompatible upstream/decoy variant are rejected with `field_not_applicable`. Open DC/domain maps remain supported; `upstreams[].force_bind` remains an alias of `bindtodevice`.
|
||||
|
||||
Example — patch only the SNI domain:
|
||||
```json
|
||||
@@ -311,6 +562,102 @@ Example — replace `[[server.listeners]]` (other `[server]` fields including `[
|
||||
{"server": {"listeners": [{"ip": "0.0.0.0", "port": 443, "client_mss": "92"}]}}
|
||||
```
|
||||
|
||||
#### API observability settings
|
||||
|
||||
`GET /v1/config`, `PATCH /v1/config`, and `POST /v1/config/validate` expose
|
||||
exactly these nested settings, including their typed defaults in GET:
|
||||
|
||||
| Path | Type / bounds | Default |
|
||||
| --- | --- | --- |
|
||||
| `server.api.minimal_runtime_enabled` | Boolean | `true` |
|
||||
| `server.api.minimal_runtime_cache_ttl_ms` | Integer, `0..60000` | `1000` |
|
||||
| `server.api.runtime_edge_enabled` | Boolean | `false` |
|
||||
| `server.api.runtime_edge_cache_ttl_ms` | Integer, `0..60000` | `1000` |
|
||||
| `server.api.runtime_edge_top_n` | Integer, `1..1000` | `10` |
|
||||
|
||||
```json
|
||||
{"server":{"api":{"runtime_edge_enabled":true,"runtime_edge_cache_ttl_ms":0,"runtime_edge_top_n":20}}}
|
||||
```
|
||||
|
||||
Omitted fields and allowed null members retain their values; a server object
|
||||
without a concrete editable value is rejected. TTL `0` disables cache reuse.
|
||||
Other API fields, including `auth_header`, `whitelist`, `gray_action`, `read_only`,
|
||||
`enabled`, `listen`, `request_body_limit_bytes`, and `runtime_edge_events_capacity`,
|
||||
remain excluded. Forbidden keys are rejected even when null. Authentication and
|
||||
read-only checks still apply to these mutations.
|
||||
|
||||
Each setting edits its exact source owner, using the nearest existing parent
|
||||
for insertion. API siblings, listener definitions and other source files survive.
|
||||
Inline, dotted and quoted TOML forms are supported. PATCH uses `server.api` even
|
||||
when the source retains the legacy `[server.admin_api]` spelling. Ambiguous or
|
||||
multiple owners return `409 config_patch_not_atomic` without writing.
|
||||
|
||||
Saving reports `runtime_reload_required=true` while active values differ; these
|
||||
settings also retain the legacy `restart_required=true` classification when the
|
||||
desired source changes, without requiring a process restart. The watcher never
|
||||
overlays them, including in mixed patches. Use `?reload=instant` or
|
||||
`?reload=drain&timeout_secs=30`, or submit `POST /v1/system/reload` with the saved revision.
|
||||
Acceptance is asynchronous: inspect reload status and `GET /v1/config/state` for
|
||||
activation. The existing API listener and event-ring capacity are retained.
|
||||
|
||||
After activation, diagnostic endpoints and capabilities reflect the new flags.
|
||||
Disabled diagnostics return their existing payload with `reason=feature_disabled`;
|
||||
enabled ME diagnostics can still report `source_unavailable` when no pool exists.
|
||||
Cache entries are checked against each request's pinned generation, including
|
||||
stale edge-cache fallback, so a late old-generation calculation cannot supply a
|
||||
new-generation response. Requests already in flight may finish using their
|
||||
original generation. Recompute contention without a matching cache can report
|
||||
`source_unavailable`.
|
||||
|
||||
#### DNS overrides
|
||||
|
||||
`network.dns_overrides` is the only editable network field. GET includes the
|
||||
empty default array; PATCH and preflight use the same DNS entry validator as
|
||||
file configuration. Each of at most 4096 strings has the form `host:port:ip`,
|
||||
with a nonempty host without `:`, a `u16` port, and IPv4 or bracketed IPv6.
|
||||
Host matching is case-insensitive and port-specific; the last duplicate
|
||||
host/port entry wins. Other network fields remain unavailable through this API.
|
||||
|
||||
```json
|
||||
{"network": {"dns_overrides": ["upstream.example:443:192.0.2.10", "v6.example:8443:[2001:db8::10]"]}}
|
||||
```
|
||||
|
||||
The array replaces the whole override list. Clear it with
|
||||
`{"network":{"dns_overrides":[]}}`; null is not a removal operation, and a
|
||||
network object containing only null/omitted editable fields is an empty patch.
|
||||
The client can send this object through `validate_config`/`patch_config` or the
|
||||
CLI's `validate`/`config-patch --json FILE` commands.
|
||||
|
||||
Persistence selects the source owning `network.dns_overrides`. If the key is
|
||||
absent, it selects the single source containing `network`, or the root when
|
||||
neither exists. Only the array value is replaced (or its declaration inserted),
|
||||
preserving sibling keys, comments outside the value, and other source files.
|
||||
Table, dotted-key, quoted-key and inline-table forms are supported. Ambiguous
|
||||
ownership or a patch spanning multiple files returns `409 config_patch_not_atomic`.
|
||||
|
||||
Without a reload query, PATCH persists desired state and does not wait for the
|
||||
existing watcher. The watcher updates the active generation resolver for future
|
||||
lookups; established connections retain their endpoints. Inspect
|
||||
`GET /v1/config/state?sections=network` for snapshot publication;
|
||||
`subsystem_convergence` may remain `unknown`. No process restart is needed for DNS-only
|
||||
changes; `runtime_reload_required` can still be true before the watcher publishes
|
||||
because it compares desired and active snapshots. Explicit reload remains an
|
||||
optional generation change with the normal instant/drain contract.
|
||||
|
||||
#### WEB retry jitter configuration
|
||||
|
||||
The managed `web.retry_jitter` object supports `enabled`, `min_ms`, `max_ms`,
|
||||
`distribution` (`uniform` or `triangular`) and optional triangular `peak_ms`.
|
||||
Validation is identical to file configuration, including when disabled. Reload
|
||||
updates newly rendered bridge pages without a process restart. Existing pages
|
||||
retain their policy through recovery; the recovery representation is unchanged.
|
||||
Require `0 <= min_ms <= max_ms <= 30000`; an explicit `peak_ms` is valid only
|
||||
with `triangular` and must lie within that interval. Unknown keys and
|
||||
distributions are rejected. The range is an additive delay, not the total pause.
|
||||
See [retry jitter parameters](../../Config_params/CONFIG_PARAMS.en.md#webretry_jitter)
|
||||
and the [WEB guide](../../WEB/WEB_PROXY.en.md#configurable-http-retry-jitter)
|
||||
for defaults, budgets and compatibility semantics.
|
||||
|
||||
### `RotateSecretRequest`
|
||||
| Field | Type | Required | Description |
|
||||
| --- | --- | --- | --- |
|
||||
@@ -332,9 +679,10 @@ Returned by `GET /v1/config` as the envelope `data`. The fields are exactly the
|
||||
| `upstreams` | `object[]` | Complete normalized upstream array. When no upstream is authored, the loader inserts one enabled direct upstream. |
|
||||
| `dc_overrides` | `object` | Complete normalized DC override map, including the synthesized DC 203 endpoint when it is not authored. |
|
||||
| `web` | `object` | Complete normalized `[web]` section, including defaults. Each `web.vhosts[]` item preserves either `host` or `hosts` and includes `base_path` (empty string when omitted in TOML); hostname lists remain grouped. The derived runtime-only `web.runtime` field is excluded. |
|
||||
| `server` | `object?` | Partial `[server]` view when editable nested fields are present. Currently only `listeners` may appear; `api`/`admin_api`, `port`, unix sockets, and other bind-identity fields are never returned. |
|
||||
| `network` | `object` | Only `dns_overrides`, a `string[]` defaulting to `[]`; other network fields are excluded. |
|
||||
| `server` | `object` | Partial `[server]` view: `listeners` and the five allowlisted `api` observability settings. API secrets, access controls, `admin_api`, `port`, unix sockets, and other bind-identity fields are never returned. |
|
||||
|
||||
The editable typed sections are serialized from the fully defaulted configuration, even when omitted from the source files. Only the editable sections above are returned; `access` (users/secrets) and `network` (per-node addresses) are always excluded. Under `server`, only the nested field-level allowlist (`listeners`) is exposed, and an empty listener array is omitted. Changes to `web.allow_wildcard_hosts` and `[web.limits]` remain process-deferred; the patch response reports them in `deferred_process_fields` until restart. Wildcard patterns require the flag to be enabled in the active process; staging the flag does not authorize patterns before restart.
|
||||
The editable typed sections are serialized from the fully defaulted configuration, even when omitted from the source files. Only the editable sections above are returned; `access` (users/secrets) is excluded, and `network` exposes only `dns_overrides`, including its default empty array. Under `server`, only the nested allowlists (`listeners` and five `api` fields) are exposed, and an empty listener array is omitted. Changes to `web.allow_wildcard_hosts` and `[web.limits]` remain process-deferred; the patch response reports them in `deferred_process_fields` until restart. Wildcard patterns require the flag to be enabled in the active process; staging the flag does not authorize patterns before restart.
|
||||
|
||||
### WEB runtime identity and lifecycle
|
||||
|
||||
@@ -417,7 +765,7 @@ for `POST /v1/runtime/web/lifecycle/pause` and `/resume`, and:
|
||||
|
||||
for `POST /v1/runtime/web/lifecycle/drain`, where `timeout_secs` is bounded to `1..=3600`. Pause and resume return `200`; drain freezes one monotonic absolute deadline and returns `202` without waiting for completion. A second drain while one is `draining` or `force_closing` returns `409 web_lifecycle_in_progress` and cannot alter the first deadline. Repeated pause/resume requests already satisfied by the current state are idempotent and do not advance the lifecycle epoch. Pause during an active drain leaves that drain running. Resume cancels an active drain and opens admission; if the deadline already committed its forced-close snapshot, those old session close signals remain effective.
|
||||
|
||||
Pause and drain block bootstrap issuance, initial/replacement session creation, and logical-stream admission. Exact session-creation replay, existing DATA/WINDOW/CLOSE, carrier polling/WebSocket exchanges, and explicit session DELETE remain available. Rejection does not consume bootstrap/session/stream rate or quota state: authenticated session creation returns retryable `503` with `Retry-After: 1`, while bridge issuance preserves the decoy route and a rejected logical `OPEN` receives a stream-local close.
|
||||
Pause and drain block bootstrap issuance, initial/replacement session creation, and logical-stream admission. Exact session-creation replay, existing DATA/WINDOW/CLOSE, carrier polling/WebSocket exchanges, and explicit session DELETE remain available. Rejection does not consume bootstrap/session/stream rate or quota state: authenticated session creation returns retryable `503` with `Retry-After: 1` and `X-Telemt-Retry-After-Ms: 250`, while bridge issuance preserves the decoy route and a rejected logical `OPEN` receives a stream-local close.
|
||||
|
||||
Drain remains graceful until either all live sessions, logical-stream ownership, and session-owned WebSockets reach zero or its deadline fires. The deadline is the latest time to commit close signals, not a claim that cooperative task teardown is already complete. At the deadline every remaining live session receives an idempotent close signal outside manager locks, status becomes `force_closing`, and only confirmed zero publishes `drained` with outcome `forced`. Natural zero publishes outcome `graceful`. Both outcomes keep operator admission closed until explicit resume.
|
||||
|
||||
@@ -472,6 +820,8 @@ Returned by `PATCH /v1/config` on success (`200`, or `202` when a reload was acc
|
||||
| `process_restart_required` | `bool` | `true` when a process-owned field changed and remains deferred after an in-process reload. |
|
||||
| `deferred_process_fields` | `string[]` | Process-owned sockets, paths, capacities, or policies retained by the active process. |
|
||||
| `changed` | `string[]` | Top-level section names that differed between the old and new config (e.g. `["censorship"]`). |
|
||||
| `changed_paths` | `string[]` | Canonical changed field paths between old desired and candidate config; array indices and redacted map placeholders, without values. |
|
||||
| `normalization_effects` | `object[]` | `{path, code}` entries for `normalized`, `null_ignored` and `alias_canonicalized` fields, without values. |
|
||||
| `reload` | `ReloadAccepted?` | Present only when the patch included a valid reload query and Maestro accepted the operation. |
|
||||
|
||||
### `HealthData`
|
||||
@@ -1455,6 +1805,9 @@ JA3 follows the Salesforce ClientHello field order. JA4 follows the FoxIO TLS-cl
|
||||
| `username` | `string` | Username. |
|
||||
| `enabled` | `bool` | Effective user enable flag. Missing config entry is reported as `true`. |
|
||||
| `in_runtime` | `bool` | Whether current runtime config already contains this user. |
|
||||
| `limits` | `object` | Desired/published TCP and unique-IP limits with override/global/unlimited origins; see shared access policy. |
|
||||
| `source_deny` | `string[]` | Desired source CIDRs; empty if no rule exists. |
|
||||
| `source_deny_status` | `object` | Effective list and generation reload requirement; see source-deny contract. |
|
||||
| `user_ad_tag` | `string?` | Optional ad tag (32 hex chars). |
|
||||
| `max_tcp_conns` | `usize?` | Optional max concurrent TCP limit. |
|
||||
| `expiration_rfc3339` | `string?` | Optional expiration timestamp. |
|
||||
@@ -1612,6 +1965,206 @@ The real `data` object contains every fully defaulted editable section; the exam
|
||||
|
||||
---
|
||||
|
||||
### `GET /v1/config/state`
|
||||
|
||||
Reads the normalized desired source and the active generation's published
|
||||
configuration. Authentication, direct-peer whitelist and the API enabled gate
|
||||
apply; `read_only=true` permits this request. Other methods return `405` with
|
||||
`Allow: GET`.
|
||||
|
||||
The optional query selects comma-separated sections, for example
|
||||
`?sections=general,access,web`. Allowed values are `general`, `network`, `server`,
|
||||
`timeouts`, `censorship`, `upstreams`, `dc_overrides`, `web`, `access`, `logging`,
|
||||
and `root` (top-level scalars such as `default_dc`). Omission selects all eleven.
|
||||
Unknown, empty or repeated values, repeated parameters, other query parameters,
|
||||
and queries longer than 256 bytes return `400`.
|
||||
|
||||
`ConfigStateData` has the following fields:
|
||||
|
||||
| Field | Contract |
|
||||
| --- | --- |
|
||||
| `scope` | Always `published_configuration_not_subsystem_acknowledgment`. |
|
||||
| `sections` | Selected section names. Projections and comparison paths use this scope. |
|
||||
| `runtime.active_generation`, `runtime.config_epoch` | Identity of the actual active runtime and its published config snapshot. An epoch also changes for watcher publications within one generation. |
|
||||
| `runtime.runtime_match` | Opaque optimistic publication token, also accepted by PATCH and preflight as `If-Runtime-Match`. |
|
||||
| `runtime_sample_current` | Whether the captured generation/config still matched when the read was checked. `false` means the response describes an older sample; retry before making a decision. |
|
||||
| `desired_revision` | Captured recursive source-manifest hash, or `null` when unavailable. This is an input identity, never an applied-state acknowledgment. |
|
||||
| `desired_status` | `valid`, `invalid`, `unreadable`, `timeout`, `busy`, or `unavailable`. `valid` means normalized source validation succeeded; DNS, static acquisition and effective retained-policy validation were not attempted. |
|
||||
| `desired_error`, `projection_error` | Nullable bounded `{path, code, message}` diagnostics. Raw parser/reload messages, source excerpts and filesystem paths are omitted. |
|
||||
| `desired`, `effective` | Nullable `ConfigProjection` objects described below. Effective publication can remain readable when desired input is unavailable. |
|
||||
| `comparison` | Scoped differences and expected application boundaries, described below. |
|
||||
| `watcher` | Latest outcome from the active generation's watcher, or `null` if none is available. |
|
||||
| `watcher_matches_desired` | Whether that outcome considered the captured desired revision; `null` if either identity is unavailable. |
|
||||
| `reload`, `reload_observation` | Latest retained Maestro operation metadata; observation is `sampled`, `busy`, or `unknown`. A sampled `null` means no retained operation. |
|
||||
| `reload_matches_desired` | Whether that reload targeted the captured desired revision, or `null` if unavailable. |
|
||||
| `subsystem_convergence` | Always `unknown`: asynchronous consumers do not yet supply a complete acknowledgment contract. |
|
||||
|
||||
The source, runtime, watcher and Maestro observations are independently sampled.
|
||||
Even `runtime_sample_current=true` is an optimistic check, not a freeze. A
|
||||
successful reload or equal snapshots cannot establish that every consumer has
|
||||
adopted a policy, that existing sessions use new credentials, or that an external
|
||||
resource is healthy. A publication racing the initial capture can return
|
||||
`409 runtime_conflict`; retry against a fresh runtime.
|
||||
|
||||
`comparison.scope` is `selected_sections`. Its `status` is `unknown` when a
|
||||
comparison cannot be made, `published_match` when selected serialized values
|
||||
match, `process_deferred` when remaining differences require process restart,
|
||||
or `pending_publication` otherwise. `pending_paths` lists all differences;
|
||||
`watcher_pending_paths`, `generation_pending_paths` and `process_deferred_paths`
|
||||
classify the expected watcher/reload/process boundaries using the same overlay
|
||||
and retention rules as preflight. `deferred_process_fields` gives the retained
|
||||
policy groups. These are projections of policy, not proof that a future reload
|
||||
can prepare or bind successfully. Use preflight to validate a candidate.
|
||||
|
||||
Each path list is capped at 512 entries and `comparison.truncated` signals
|
||||
omission. Dynamic identities are replaced with path placeholders, including
|
||||
`access.users.{entry}`, `dc_overrides.{dc}` and
|
||||
`censorship.exclusive_mask.{hostname}`. `runtime_derived_paths` excludes the
|
||||
random default `censorship.fake_cert_len` from drift: its desired value is
|
||||
undetermined, and the effective projection may show its currently published value.
|
||||
|
||||
Each `ConfigProjection` contains `fields`, `truncated`, `provenance`,
|
||||
`source_revision` and `source_count`. Source metadata identifies input evidence;
|
||||
it does not attribute a mixed publication to the latest file. `provenance` is
|
||||
`normalized_source`, `mixed_publication`, or `unknown`. Mixed watcher overlays,
|
||||
retained process policy, CLI overrides and startup fallback use conservative
|
||||
unknown field provenance.
|
||||
|
||||
Each field row has:
|
||||
|
||||
| Field | Meaning |
|
||||
| --- | --- |
|
||||
| `path` | Canonical config path with array indices, at most 256 bytes. Dynamic maps are aggregated. |
|
||||
| `value` | Present only for allowed public booleans, numbers, nulls, known enum strings and bounded arrays of those values. |
|
||||
| `redacted` | Whether the value is omitted. Arbitrary strings, deployment identities and credential values are omitted even when a string could contain URL userinfo. |
|
||||
| `present` | Whether the value is non-null and nonempty. `false` and zero are present scalar values. |
|
||||
| `entries` | Array/map size, or `null` for a scalar. |
|
||||
| `differs` | Difference from the other projection, or `null` when unknown or runtime-derived. Secret rotation changes this metadata without revealing the secret. |
|
||||
| `origin` | `source`, `type_default`, `default_or_derived`, `inherited`, `runtime_derived`, `mixed_unknown`, or `unknown`. `source` refers to normalized input, not necessarily its original spelling. |
|
||||
| `inherited_from` | Included for a known inheritance relationship, currently an unset `upstreams[].prefer` inheriting `network.prefer`. |
|
||||
|
||||
Explicit-source evidence retains at most 4096 paths of at most 256 bytes, plus
|
||||
the source count/hash. Incomplete provenance is reported as unknown. There are
|
||||
at most 1024 rows per projection, and the complete JSON envelope is capped at
|
||||
512 KiB; further rows are dropped with `truncated=true` if necessary. Projections
|
||||
are inspection DTOs, **not PATCH payloads**. No masked replacement secrets are
|
||||
generated, and this endpoint never writes them or any other configuration.
|
||||
|
||||
Watcher metadata contains `sequence`, `observed_at_epoch_secs`, `phase`,
|
||||
`source_revision`, `published_config_epoch`, and a nullable fixed `error_code`.
|
||||
Phases distinguish `initial`, `preparing`, `published`, `published_partial`,
|
||||
`retained`, `unchanged`, `source_refreshed`, `rejected`, and `publication_failed`.
|
||||
The last two retain the prior effective publication. Only the latest record is
|
||||
retained per watcher; an unchanged source is not a new consumer acknowledgment.
|
||||
|
||||
Reload metadata contains `reload_id`, `target_generation`, `source_revision`,
|
||||
`phase`, `source_generation`, `activated_generation`, `retiring_generation`,
|
||||
`retiring_config_epoch`, `retirement`, `error_present`, and `warning_count`.
|
||||
Activation and retirement identities remain null until the owner reaches those
|
||||
steps. After a swap, the new generation is active while the old generation is
|
||||
identified during `draining`. The retiring epoch is sampled at replacement.
|
||||
`retirement` is null, `retiring`, `draining`, `retired`, or `cleanup_timeout`.
|
||||
The final record retains the retired identity; `rolled_back`/`failed` before
|
||||
activation do not claim a swap. Raw error/warning text is excluded. This reads
|
||||
the latest operation from the existing bounded 32-operation store without
|
||||
waiting on its mutex.
|
||||
|
||||
Inspection uses two process-shared slots and a five-second work budget.
|
||||
Source/projection workers run off Tokio's async workers; cancellation or timeout
|
||||
retains a slot until any detached blocking worker finishes. No source mutation
|
||||
lock, DNS lookup, static-asset load, listener bind or reload reservation is
|
||||
performed. Invalid or unreadable desired files produce `200` with an effective
|
||||
projection and a bounded desired error. Exhausted slots or an effective
|
||||
projection timeout still return `200` with runtime identity, partial metadata,
|
||||
and `comparison.status=unknown`; callers must inspect the status fields.
|
||||
|
||||
Legacy `GET /v1/config` and user/link responses retain their existing contracts.
|
||||
They remain administratively sensitive and may include configured credentials
|
||||
or provisioning secrets. The redacted state endpoint does not change their
|
||||
defaults or replace the existing authorization requirement.
|
||||
|
||||
---
|
||||
|
||||
### `POST /v1/config/validate`
|
||||
|
||||
Prepares the same candidate as `PATCH /v1/config`, including source ownership,
|
||||
normalization, DNS/static-asset acquisition, and resolution against retained
|
||||
process limits. Accepts the same `PatchConfigRequest`, optional `If-Match` and
|
||||
`If-Runtime-Match` headers, and `reload`, `timeout_secs`, `failure_policy` query
|
||||
parameters described below. Ordinary authentication, direct-peer whitelist and
|
||||
body limits apply. This POST is permitted with `read_only=true`. Other methods
|
||||
return `405` with `Allow: POST`.
|
||||
|
||||
Preparation is limited to two concurrent requests per API server and a 30-second
|
||||
deadline. A cancelled/timed-out OS resolver or blocking file worker retains its
|
||||
slot until it exits; the deadline bounds the HTTP wait, not OS call termination.
|
||||
Exhaustion returns `429 config_preflight_busy`; the deadline returns
|
||||
`504 config_preflight_timeout`. Existing per-origin DNS and static-site limits
|
||||
still apply. Preview creates no source/lock/staging files, reload reservations,
|
||||
config publications, listeners, credential rotations or persistent tasks.
|
||||
|
||||
Success is `200` with the standard envelope. Its `revision` is the unchanged
|
||||
`base_revision`. `data` contains:
|
||||
|
||||
| Field | Meaning |
|
||||
| --- | --- |
|
||||
| `valid` | `true`; invalid candidates use the standard error envelope. |
|
||||
| `base_revision`, `candidate_revision` | Source-manifest hashes before and after the proposed source rendering. Candidate hash is not a runtime/DNS/static-content identity. |
|
||||
| `runtime.active_generation` | Sampled active Maestro generation. |
|
||||
| `runtime.config_epoch` | Process-local publication counter assigned by the configuration owner, including hot updates. It is not a subsystem convergence acknowledgment. |
|
||||
| `runtime.runtime_match` | Opaque process/generation/publication token to send back as `If-Runtime-Match`. A process restart invalidates it. |
|
||||
| `changed_paths` | Old desired source → prepared desired candidate. Paths only; this can be empty while active state still differs. |
|
||||
| `normalization_effects` | `{path, code}` for normalized values, ignored object nulls, and canonicalized aliases. |
|
||||
| `apply.watcher_paths` | Active → watcher overlay: fields the existing hot reload policy can apply. |
|
||||
| `apply.generation_paths` | Watcher overlay → resolved reload configuration: additional changes requiring generation activation. |
|
||||
| `apply.process_restart_paths` | Resolved reload configuration → desired: fields retained until process restart. |
|
||||
| `apply.restart_required` | Unchanged legacy watcher classification of old desired → candidate. |
|
||||
| `apply.runtime_reload_required` | Whether effective runtime-owned state differs from active, including hot fields. It does not imply a generation reload is always necessary. |
|
||||
| `apply.process_restart_required`, `apply.deferred_process_fields` | Deferred process classification and existing coarse field labels. |
|
||||
| `source_ownership`, `touched_sections` | `single_source` and sections to render. Multiple owners return `409 config_patch_not_atomic` with a `source_ownership_conflict` detail; paths to files are omitted. |
|
||||
| `reload` | Validated query options, or null; no operation is reserved or accepted. |
|
||||
| `warnings` | `{path, code, message}` entries for preparation reads, generation changes without an explicit reload, and deferred process fields. |
|
||||
|
||||
Changed/application paths use indices such as `upstreams[0].password` and
|
||||
placeholders such as `dc_overrides.{dc}[0]` and
|
||||
`censorship.exclusive_mask.{hostname}`. They never contain old/new values or
|
||||
dynamic map identities. Each path list and the normalization list is bounded
|
||||
to 4096 entries; larger feedback returns `400`. Validation errors add optional
|
||||
`error.details` entries with `path`, `code`, and `message`; `$` denotes a
|
||||
whole-document failure when no safe specific field can be identified. Unknown
|
||||
field feedback is limited to 64 entries. Raw validator text, source excerpts,
|
||||
credentials and URL values are not returned.
|
||||
An unreadable or invalid current source retains PATCH's `500 internal_error`
|
||||
status, with a redacted `source_load_failed` detail.
|
||||
|
||||
For example, an unknown nested key returns:
|
||||
|
||||
```json
|
||||
{
|
||||
"ok": false,
|
||||
"error": {
|
||||
"code": "bad_request",
|
||||
"message": "Unknown configuration fields",
|
||||
"details": [{
|
||||
"path": "general.me_keepalive_enabld",
|
||||
"code": "unknown_field",
|
||||
"message": "Field is not part of the configuration contract"
|
||||
}]
|
||||
},
|
||||
"request_id": 1
|
||||
}
|
||||
```
|
||||
|
||||
Clients should preview with `If-Match`, then PATCH the identical body/query using
|
||||
both the returned `base_revision` and `runtime.runtime_match` as preconditions.
|
||||
PATCH reconstructs the candidate and rechecks the source graph and active
|
||||
publication before persistence; changes return `409 revision_conflict` or
|
||||
`409 runtime_conflict`. Both headers remain optional for existing clients.
|
||||
These are optimistic checks, not a lock freezing later runtime publication.
|
||||
Preview does not bind sockets or probe generation startup, and DNS/static assets
|
||||
may change before commit. Successful preflight therefore does not guarantee
|
||||
subsequent network startup or completed application by asynchronous subsystems.
|
||||
|
||||
### `PATCH /v1/config`
|
||||
|
||||
Applies a sparse patch to the editable config sections. The merged config is fully validated before writing; if validation fails the file is not modified.
|
||||
@@ -1625,21 +2178,24 @@ Applies a sparse patch to the editable config sections. The merged config is ful
|
||||
| `Authorization` | when configured | Same token as all other endpoints. |
|
||||
| `Content-Type: application/json` | recommended | Not enforced, but body must be valid JSON. |
|
||||
| `If-Match: <revision>` | no | Optimistic concurrency. `<revision>` is the `revision` value from `GET /v1/config` or `config_hash` from `GET /v1/system/info`. It covers the complete recursive include graph. If supplied and it does not match the current source manifest, returns `409 revision_conflict`. Omitting it removes the caller precondition, but the internal graph/owner race fence can still return the same conflict. |
|
||||
| `If-Runtime-Match: <runtime_match>` | no | Token from `POST /v1/config/validate` or `GET /v1/config/state`, quoted or unquoted. A stale publication returns `409 runtime_conflict`; malformed/repeated headers return `400`. Even without it, active state is rechecked during preparation and immediately before the source rename. |
|
||||
|
||||
**Editable sections:** `general`, `timeouts`, `censorship`, `upstreams`, `dc_overrides`, `web`, plus partially editable `server` (only nested `listeners`).
|
||||
**Editable sections:** `general`, `timeouts`, `censorship`, `upstreams`, `dc_overrides`, `web`, plus partially editable `server` (`listeners` and five [API observability settings](#api-observability-settings)) and `network` (only nested `dns_overrides`).
|
||||
|
||||
**Rejected keys and their error codes:**
|
||||
|
||||
| Key | HTTP | `error.code` |
|
||||
| --- | --- | --- |
|
||||
| `access` | `400` | `access_not_editable` |
|
||||
| `network` or any unknown top-level key | `400` | `section_not_editable` |
|
||||
| `server` with keys other than `listeners` | `400` | `field_not_editable` |
|
||||
| Unknown top-level key or non-null, non-object `server`/`network` | `400` | `section_not_editable` |
|
||||
| `network` with keys other than `dns_overrides` (including null members) | `400` | `field_not_editable` |
|
||||
| `server` with keys other than `listeners`/`api`, or `server.api` with keys outside its five-field allowlist (including null members) | `400` | `field_not_editable` |
|
||||
| Object with no editable key | `400` | `bad_request` |
|
||||
| Unknown nested field or inapplicable variant field | `400` | `bad_request`, with `error.details` |
|
||||
|
||||
**Merge semantics:** tables are deep-merged field-by-field; arrays and scalar values replace the existing value wholesale. In particular, `web.vhosts` is an array: changing one vhost `base_path` requires sending the complete vhost array, including every retained vhost and each required hostname selector (`host` or non-empty `hosts`), `public_addr`, `decoy`, and profile field. A mutation is written to the single source file that owns every touched semantic section. Untouched table bodies, the root file when it is not the owner, and all other include files remain byte-identical; touched TOML table bodies are reserialized and may lose their internal formatting or comments. A target split across sources, a patch spanning multiple owners, or an include directive nested inside a TOML table returns `409 config_patch_not_atomic` without writing any file.
|
||||
**Merge semantics:** tables are deep-merged field-by-field; arrays and scalar values replace the existing value wholesale. In particular, `web.vhosts` is an array: changing one vhost `base_path` requires sending the complete vhost array, including every retained vhost and each required hostname selector (`host` or non-empty `hosts`), `public_addr`, `decoy`, and profile field. A mutation is written to the single source file that owns every touched semantic section or allowlisted field. DNS overrides use the exact leaf owner (or its parent for insertion), preserving all bytes outside the edited value; see [DNS overrides](#dns-overrides). Untouched table bodies, the root file when it is not the owner, and all other include files remain byte-identical; other touched TOML table bodies are reserialized and may lose their internal formatting or comments. A target split across sources, a patch spanning multiple owners, or an include directive nested inside a TOML table returns `409 config_patch_not_atomic` without writing any file.
|
||||
|
||||
**Validation:** the merged config is deserialized into the full `ProxyConfig` type and validated before writing. Failures return `400` with a descriptive message; the file is not modified. WEB host selectors are mutually exclusive; duplicate normalized names are rejected across all groups. The effective configuration must fit active process limits: `max_vhosts` counts exact hostname entries and `max_profiles` counts exact host/profile pairs plus one shared profile set per wildcard source group. Wildcard selectors count toward `web.limits.wildcard.max_rules`. Raising desired restart-only limits in the same patch cannot bypass the active ceilings.
|
||||
**Validation:** nested keys are checked before typed deserialization can discard them, then the full candidate is prepared and validated. Validation failures return `400` with redacted path/code/message details; the file is not modified. WEB host selectors are mutually exclusive; duplicate normalized names are rejected across all groups. The effective configuration must fit active process limits: `max_vhosts` counts exact hostname entries and `max_profiles` counts exact host/profile pairs plus one shared profile set per wildcard source group. Wildcard selectors count toward `web.limits.wildcard.max_rules`. Raising desired restart-only limits in the same patch cannot bypass the active ceilings.
|
||||
|
||||
**Read-only mode:** returns `403 read_only` when the API runs with `read_only = true`.
|
||||
|
||||
@@ -1663,6 +2219,8 @@ Without a `reload` query parameter, the endpoint writes the patch and the file w
|
||||
"process_restart_required": false,
|
||||
"deferred_process_fields": [],
|
||||
"changed": ["censorship"],
|
||||
"changed_paths": ["censorship.tls_domain"],
|
||||
"normalization_effects": [],
|
||||
"reload": {
|
||||
"reload_id": 7,
|
||||
"target_generation": 2,
|
||||
@@ -1707,13 +2265,14 @@ A valid base-path-only change reports `restart_required=false`, `runtime_reload_
|
||||
| `202` | — | Patch applied and runtime reload accepted. |
|
||||
| `400` | `bad_request` | Invalid JSON, empty patch, or config validation/deserialization failure. |
|
||||
| `400` | `access_not_editable` | Patch contains an `access` key. |
|
||||
| `400` | `section_not_editable` | Patch contains `network` or an unknown top-level key. |
|
||||
| `400` | `field_not_editable` | Patch contains a forbidden nested `server.*` field (anything other than `listeners`). |
|
||||
| `400` | `section_not_editable` | Patch contains an unknown top-level key or a non-null, non-object partial section. |
|
||||
| `400` | `field_not_editable` | Patch contains a nested field outside `server.listeners`, the five `server.api` observability fields, or `network.dns_overrides`. |
|
||||
| `401` | `unauthorized` | Missing or invalid `Authorization` header. |
|
||||
| `403` | `read_only` | API is in read-only mode. |
|
||||
| `405` | `method_not_allowed` | Method other than `GET` or `PATCH` used on `/v1/config`. |
|
||||
| `409` | `revision_conflict` | `If-Match` does not match, or the source graph/owner changes during the fenced write. |
|
||||
| `409` | `reload_in_progress` | Another runtime reload is active; the patch is not written. |
|
||||
| `409` | `runtime_conflict` | `If-Runtime-Match` is stale or active state changes during preparation/before persistence. |
|
||||
| `409` | `config_patch_not_atomic` | Touched semantic sections have multiple source owners or cannot be mutated as one source-file transaction. |
|
||||
| `500` | `internal_error` | I/O or serialization failure. |
|
||||
|
||||
@@ -1796,13 +2355,15 @@ Deployment, TLS-terminator examples, links, and WEB-specific verification are do
|
||||
| Endpoint | Notes |
|
||||
| --- | --- |
|
||||
| `PATCH /v1/config` | Deep-merges and validates the patch, writes touched sections via atomic `tmp + rename`, and optionally submits the exact written revision for an in-process Maestro reload. |
|
||||
| `GET /v1/config/state` | Returns bounded, redacted desired/effective projections and publication outcomes; partial results preserve runtime identity when source inspection is unavailable. |
|
||||
| `POST /v1/config/validate` | Returns a bounded, redacted preview with source/runtime preconditions and apply classification; allowed in read-only mode, without mutation side effects. |
|
||||
| `POST /v1/users` | Before saving any new user, including one without a recurring quota, reads existing quota state and durably clears any retired row; read/write failure returns `500` without creating the user. Creates and validates a user, atomically updates only affected `access.*` TOML tables, then stages the credential and enabled state in process-wide admission after the durable write. |
|
||||
| `PATCH /v1/users/{username}` | Partial update of provided fields only. Missing fields remain unchanged; explicit `null` removes optional entries. Admission is staged when `secret` or `enabled` is explicitly supplied, even if unchanged; an identity change or disable cancels current owners, while a metadata-only patch does not. Every accepted patch also fences quota policy freshness, including metadata-only or no-op patches. |
|
||||
| `POST /v1/users/{username}/rotate-secret` | Replaces the user's secret with a provided valid 32-hex value or a generated value, stages the new process-wide admission identity, cancels owners of the old identity, then returns the effective secret in `CreateUserResponse`. |
|
||||
| `POST /v1/users/{username}/enable` | Enables the user idempotently by removing the `access.user_enabled[username]` override and updating the runtime admission state immediately. |
|
||||
| `POST /v1/users/{username}/disable` | Disables the user idempotently by writing `access.user_enabled[username] = false`, updating runtime admission immediately, and cancelling active sessions for that username. |
|
||||
| `POST /v1/users/{username}/reset-quota` | Persists the quota checkpoint to `general.quota_state_path` before resetting live accounting for the route username; does not modify user config. |
|
||||
| `DELETE /v1/users/{username}` | Deletes only the specified user, removes it from API-managed optional `access.user_*` maps, blocks last-user deletion, stages a deletion tombstone that cancels active owners, and atomically updates only related API-managed `access.*` TOML tables. It leaves `access.user_source_deny` untouched; manage that table manually in TOML. |
|
||||
| `DELETE /v1/users/{username}` | Deletes only the specified user, removes it from API-managed optional `access.user_*` maps, blocks last-user deletion, stages a deletion tombstone that cancels active owners, and atomically updates only related API-managed `access.*` TOML tables. It leaves `access.user_source_deny` untouched; explicitly clear `source_deny` before deletion or during recreation, then reload the generation. |
|
||||
|
||||
All accepted durable config, user, and quota mutations:
|
||||
- Respect `read_only` mode.
|
||||
@@ -1892,13 +2453,13 @@ The current runtime exports these additional bounded-cardinality families. All u
|
||||
| Bind failure | Failed API bind logs warning and API task exits (no auto-retry loop). |
|
||||
| ME runtime status endpoints | `/v1/stats/me-writers`, `/v1/stats/dcs`, `/v1/stats/minimal/all` require `[server.api].minimal_runtime_enabled=true`; otherwise they return disabled payload with `reason=feature_disabled`. |
|
||||
| Upstream runtime endpoint | `/v1/stats/upstreams` always returns `zero`, but runtime fields (`summary`, `upstreams`) require `[server.api].minimal_runtime_enabled=true`. |
|
||||
| Restart requirements | `server.api` changes are restart-required for predictable behavior. |
|
||||
| Hot-reload nuance | A pure `server.api`-only config change may not propagate through watcher broadcast; a mixed change (with hot fields) may propagate API flags while still warning that restart is required. |
|
||||
| Runtime apply path | Successful writes are picked up by existing config watcher/hot-reload path. |
|
||||
| API observability settings | The five editable `server.api` settings need explicit generation reload. API listener identity and event-ring capacity remain process-owned. |
|
||||
| Watcher behavior | The watcher retains every `server.api` field, including in mixed changes with watcher-supported settings. |
|
||||
| Runtime apply path | Saving updates desired state. Watcher-supported fields publish asynchronously; generation-owned fields require explicit reload. |
|
||||
| Exposure | Built-in TLS/mTLS is not provided. Use loopback bind + reverse proxy if needed. |
|
||||
| Pagination | User list currently has no pagination/filtering. |
|
||||
| Serialization side effect | Updated TOML table bodies are re-serialized on write. Endpoints that persist full config can still rewrite broader formatting/comments. |
|
||||
|
||||
## Known Limitations (Current Release)
|
||||
|
||||
- API runtime controls under `server.api` are documented as restart-required; hot-reload behavior for these fields is not strictly uniform in all change combinations.
|
||||
- API observability settings require explicit generation reload; saving them alone leaves diagnostics unchanged in the active generation.
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
# Python Control API client and CLI
|
||||
|
||||
[tools/telemt_api.py](../../../tools/telemt_api.py) provides a Python 3.10+
|
||||
standard-library client. No third-party package is required. Import
|
||||
`TelemtAPI` from `tools.telemt_api` when running from the repository, or add the
|
||||
`tools` directory to your Python import path and import from `telemt_api`.
|
||||
The CLI parser lives in
|
||||
[tools/telemt_api_cli.py](../../../tools/telemt_api_cli.py); keep both files
|
||||
together when copying the tool.
|
||||
|
||||
```bash
|
||||
python3 tools/telemt_api.py help
|
||||
python3 tools/telemt_api.py --url http://127.0.0.1:9091 --auth 'Bearer synthetic-demo' capabilities --json-output
|
||||
python3 tools/telemt_api.py config-state --sections general,access,web --json-output
|
||||
```
|
||||
|
||||
The authorization value is exact, including any `Bearer ` prefix configured by
|
||||
the operator. Global `--url`, `--auth`, `--timeout`, `--if-match`, and
|
||||
`--json-output` may appear before or after a command. `--timeout` is the socket
|
||||
timeout in seconds and defaults to 10; preflight can need a larger value because
|
||||
its server work budget is 30 seconds. Authentication applies independently to
|
||||
each request, including polling after a reload.
|
||||
|
||||
Default output retains human-readable user/create/delete output and prints
|
||||
other payloads as JSON followed by revision/status metadata. `--json-output`
|
||||
prints one JSON object containing `ok`, `data`, `revision`, and `http_status`.
|
||||
`http_status` belongs to the client wrapper, not the server's JSON envelope.
|
||||
The state endpoint can have `revision=null` while returning an effective
|
||||
snapshot and a bounded desired-source error.
|
||||
|
||||
## Commands and methods
|
||||
|
||||
Existing statistics commands retain their names: `health`, `info`, `status`,
|
||||
`init`, `limits`, `posture`, `whitelist`, `summary`, `zero`, `upstreams`,
|
||||
`minimal`, `me-writers`, `dcs`, `me-pool`, `me-quality`, `upstream-quality`,
|
||||
`nat-stun`, `me-selftest`, `connections`, and `events --limit N`.
|
||||
|
||||
| CLI | Python method | Contract |
|
||||
| --- | --- | --- |
|
||||
| `ready` | `health_ready()` | `200` ready or `503` readiness data; CLI exits 1 when not ready. |
|
||||
| `capabilities` | `capabilities()` | Supported routes, feature gates and mutation availability. |
|
||||
| `schema` | `config_schema()` | Types, defaults, sensitivity, exposure and apply policy. |
|
||||
| `config` | `get_config()` | Desired editable config, including `web`; administratively sensitive. |
|
||||
| `config-state [--sections general,web]` | `config_state(["general", "web"])` | Redacted desired/effective state and owner observations. |
|
||||
| `validate --json FILE` | `validate_config(patch, ...)` | Candidate preparation without persistence/publication. |
|
||||
| `config-patch --json FILE [--reload instant] [--wait]` | `patch_config(patch, ...)` | Exact sparse patch, optional reload policy, source/runtime preconditions. |
|
||||
| `reload [--mode instant] [--wait]` | `reload(mode, ...)` | Submit generation reload; default failure policy is server-owned `keep_new`. |
|
||||
| `reload-status ID` | `reload_status(id)` | Read one retained operation. |
|
||||
| `reload-wait ID [--expected-revision REV]` | `wait_reload(id, ...)` | Poll to `succeeded`, `failed` or `rolled_back`. |
|
||||
| `users`, `user NAME` | `list_users()`, `get_user(name)` | User/link responses can carry provisioning secrets. |
|
||||
| `create NAME`, `patch NAME`, `delete NAME` | `create_user()`, `patch_user()`, `delete_user()` | Existing convenience methods and command names remain available. |
|
||||
| `patch NAME --json FILE` or `--clear FIELD` | `patch_user_fields(name, fields)` | Exact omitted/null/value semantics. |
|
||||
| `secret NAME [--secret HEX]` | `rotate_secret(name, ...)` | Implemented rotation endpoint, not a reserved route. |
|
||||
| `enable NAME`, `disable NAME` | `enable_user()`, `disable_user()` | User admission controls with optional `If-Match`. |
|
||||
| `reset-quota NAME` | `reset_user_quota()` | Durable quota reset; preserves the recurring boundary contract. |
|
||||
| `quota` | `users_quota()` | Desired quota/period and effective recurring schedule/counters. |
|
||||
| `active-ips` | `users_active_ips()` | Current per-user IP observations. |
|
||||
| `tls-fingerprints [--limit N]` | `runtime_tls_fingerprints(limit)` | `1..1000`, subject to runtime-edge availability. |
|
||||
| `web-status` | `web_status()` | Runtime identity, availability and operator lifecycle. |
|
||||
| `web-sessions [FILTERS]` | `web_sessions(...)` | One bounded page; caller follows `next_cursor`. |
|
||||
| `web-session REF` | `web_session(ref)` | Live `200` or retained closed `410` tombstone. |
|
||||
| `web-close --runtime-instance INSTANCE --selector FILE [--wait]` | `web_close_sessions(instance, selector)` | Exact `refs`, nonempty `filter`, or `all` selector. |
|
||||
| `web-operation ID`, `web-wait ID` | `web_operation(id)`, `wait_web_operation(id)` | Read/poll the process-scoped close operation. |
|
||||
| `web-debug-clear --runtime-instance INSTANCE` | `web_debug_clear(instance)` | Clears retained debug records. |
|
||||
| `web-learning-reset --runtime-instance INSTANCE` | `web_learning_reset(instance)` | Resets process-owned carrier learning. |
|
||||
| `web-pause --runtime-instance INSTANCE` | `web_pause(instance)` | Stops admission of new WEB work. |
|
||||
| `web-drain --runtime-instance INSTANCE --timeout-secs N [--wait]` | `web_drain(instance, seconds)` | Starts one bounded server drain, returns `202`. |
|
||||
| `web-drain-wait ID --runtime-instance INSTANCE` | `wait_web_drain(instance, id)` | Polls the same drain through WEB status. |
|
||||
| `web-resume --runtime-instance INSTANCE` | `web_resume(instance)` | Resumes operator admission subject to other policy gates. |
|
||||
| `gen-secret` | `TelemtAPI.generate_secret()` | Generates a new 32-hex secret locally. |
|
||||
|
||||
The client covers all 53 JSON operations in the operation catalog. Open the
|
||||
HTML `/web-status` viewer in a browser; it is not decoded as a JSON response.
|
||||
Feature gates and missing runtime planes still return the server's documented
|
||||
errors. Discovery availability is a snapshot, not a reservation.
|
||||
|
||||
## Sparse values and user updates
|
||||
|
||||
`create`/`patch` accept `--secret`, `--ad-tag`, `--max-conns`, `--expires`,
|
||||
`--quota`, `--max-ips`, `--quota-period daily|weekly|monthly`, `--rate-up`,
|
||||
`--rate-down`, and mutually exclusive `--enabled`/`--disabled`. Rate units are
|
||||
bits per second. A zero or false option is transmitted explicitly.
|
||||
|
||||
Shared access policy is available through `api.access_policy()` and
|
||||
`api.patch_access_policy(body, if_match=..., if_runtime_match=...)`, or CLI
|
||||
`access-policy` / `access-policy-patch --json FILE --if-runtime-match TOKEN`.
|
||||
JSON null is transmitted unchanged: scalar null restores a default, a null CIDR
|
||||
entry deletes that rule, and `cidr_rate_limits=null` clears the map. A rate object
|
||||
replaces both directions, with omitted directions unlimited. Inspect
|
||||
`desired` / `effective` and the runtime token before relying on publication.
|
||||
|
||||
For backward compatibility, `patch_user(..., field=None)` continues to omit that
|
||||
convenience argument. Use `patch_user_fields` or CLI JSON/`--clear` to transmit
|
||||
null. The exact method does not alter the supplied dictionary:
|
||||
|
||||
```python
|
||||
from tools.telemt_api import TelemtAPI
|
||||
|
||||
api = TelemtAPI("http://127.0.0.1:9091", auth_header="Bearer synthetic-demo")
|
||||
api.patch_user_fields("alice", {
|
||||
"quota_period": None,
|
||||
"rate_limit_up_bps": 0,
|
||||
"enabled": False,
|
||||
}, if_match="synthetic-source-revision")
|
||||
```
|
||||
|
||||
For user fields, omission preserves the setting and null removes its override;
|
||||
`enabled=null` restores the default enabled state. `secret=null` is ignored,
|
||||
so the CLI excludes `secret` from `--clear`. Removing a quota or recurring period
|
||||
still follows server validation and durable scheduling rules. `--json` cannot
|
||||
be combined with field options/`--clear`; conflicting set/clear options fail
|
||||
before any HTTP request.
|
||||
|
||||
```bash
|
||||
python3 tools/telemt_api.py patch alice --quota 0 --disabled
|
||||
python3 tools/telemt_api.py patch alice --clear quota_period --clear rate_limit_up_bps
|
||||
printf '%s\n' '{"quota_period":null,"enabled":false}' | python3 tools/telemt_api.py patch alice --json -
|
||||
```
|
||||
|
||||
Source-deny lists use `source_deny=["192.0.2.0/24", "2001:db8::/32"]`,
|
||||
`create/patch --source-deny CIDR` (repeatable), or exact PATCH JSON.
|
||||
`patch alice --clear source_deny` removes the authored row. User deletion retains
|
||||
that row; `create_user("alice", source_deny=None)` or CLI
|
||||
`create alice --clear-source-deny` explicitly removes it on recreation. Omitting
|
||||
the creation argument retains any old rule. The older `patch_user(...,
|
||||
source_deny=None)` convenience call omits the field; use `patch_user_fields`
|
||||
for null removal. Empty arrays replace the list with no denied networks.
|
||||
|
||||
These changes need explicit generation reload. Inspect
|
||||
`source_deny_status.runtime_reload_required`, submit `reload` with the returned
|
||||
revision, and check reload status plus the effective list. Saving alone does not
|
||||
cancel sessions or change rules in a running generation; a reload already in
|
||||
progress may have captured an older source revision.
|
||||
|
||||
Rotation returns the new raw credential, cancels owners tied to the old
|
||||
credential identity and relies on asynchronous owner/watcher work for subsequent
|
||||
publication. `UserInfo.in_runtime` only tests username membership. It does not
|
||||
prove that a new credential or quota period has reached every consumer. Use
|
||||
`config_state()` and `users_quota()` to inspect the corresponding evidence.
|
||||
|
||||
## Config preparation, ownership and reload
|
||||
|
||||
Config objects merge sparsely, arrays replace the complete array, and nested
|
||||
object null members are ignored by the server. These semantics differ from
|
||||
user PATCH nulls. In particular, `web.vhosts` is already editable and is replaced
|
||||
as an array; fetch and retain the complete desired array before changing an entry.
|
||||
|
||||
`network.dns_overrides` accepts the same array replacement contract through
|
||||
`validate_config`/`patch_config` and CLI JSON input. For example,
|
||||
`{"network":{"dns_overrides":["upstream.example:443:192.0.2.10"]}}` replaces the
|
||||
list, and `{"network":{"dns_overrides":[]}}` clears it. Other `network` fields
|
||||
remain rejected. PATCH without a reload query leaves publication to the existing
|
||||
watcher; it does not wait for the resolver update or move established connections.
|
||||
See [DNS overrides](API.md#dns-overrides) for limits and source ownership.
|
||||
|
||||
The same methods and CLI JSON input accept the five
|
||||
[API observability settings](API.md#api-observability-settings). For example,
|
||||
`{"server":{"api":{"runtime_edge_enabled":true,"runtime_edge_cache_ttl_ms":0,"runtime_edge_top_n":20}}}`
|
||||
enables edge diagnostics with caching disabled after generation activation.
|
||||
Preview and PATCH the identical body with `reload="instant"`, or `reload="drain"`
|
||||
and a required `timeout_secs` value, then poll the returned reload ID.
|
||||
Saving without a reload leaves these settings
|
||||
pending; the watcher never applies them. `false` and `0` are preserved, while
|
||||
`null` retains an allowed field's previous value. API security settings and
|
||||
listener identity remain outside this write surface.
|
||||
|
||||
State projections are inspection DTOs and must not be used as PATCH bodies.
|
||||
|
||||
`If-Match` fences the recursive desired-source revision. `If-Runtime-Match`
|
||||
fences the active publication and is accepted by config preflight/PATCH only.
|
||||
Both quoted and unquoted values are passed through unchanged. A patch must be
|
||||
owned by one independently writable source; a cross-include edit can fail with
|
||||
`409 config_patch_not_atomic`. The client preserves the server's error details
|
||||
and does not split a rejected edit into partial commits.
|
||||
|
||||
```python
|
||||
patch = {"general": {"log_level": "debug"}}
|
||||
preview = api.validate_config(patch, reload="drain", timeout_secs=30,
|
||||
failure_policy="rollback")
|
||||
result = api.patch_config(
|
||||
patch,
|
||||
if_match=preview.data["base_revision"],
|
||||
if_runtime_match=preview.data["runtime"]["runtime_match"],
|
||||
reload="drain", timeout_secs=30, failure_policy="rollback",
|
||||
)
|
||||
accepted = result.data.get("reload")
|
||||
if accepted:
|
||||
final = api.wait_reload(accepted["reload_id"],
|
||||
expected_revision=accepted["config_revision"], timeout=60)
|
||||
if final.data["state"] != "succeeded":
|
||||
raise RuntimeError("Reload did not succeed")
|
||||
```
|
||||
|
||||
`restart_required` is the legacy watcher classification;
|
||||
`runtime_reload_required` describes differences requiring runtime activation;
|
||||
`process_restart_required` identifies fields retained until process restart.
|
||||
Do not reduce these flags to one generic restart action. A successful preflight
|
||||
does not guarantee future binding, unchanged external resources, or consumer
|
||||
convergence. `published_match` in state describes selected snapshot equality;
|
||||
`subsystem_convergence` can remain `unknown`.
|
||||
|
||||
`--reload drain`/`--mode drain` requires `--timeout-secs 1..3600`; instant forbids
|
||||
that option. `--failure-policy` is `keep_new` or `rollback`. Config preflight and
|
||||
PATCH accept those query options; direct reload sends the corresponding JSON
|
||||
body. Process-only patches can return no reload operation even with `--wait`.
|
||||
For the CLI examples below, save the sparse config object as `patch.json` and
|
||||
replace the synthetic preconditions with the tokens returned by preflight.
|
||||
|
||||
```bash
|
||||
python3 tools/telemt_api.py --timeout 35 validate --json patch.json --json-output
|
||||
python3 tools/telemt_api.py config-patch --json patch.json --if-match synthetic-source-revision --if-runtime-match synthetic-publication-token --reload drain --timeout-secs 30 --failure-policy rollback --wait
|
||||
python3 tools/telemt_api.py reload --mode instant --wait --wait-timeout 60
|
||||
```
|
||||
|
||||
Polling uses a monotonic budget (`--wait-timeout`, default 60) and a positive
|
||||
interval (`--poll-interval`, default 0.25). Each request's socket timeout is capped
|
||||
by the remaining budget; urllib's timeout is a socket wait limit, not a hard
|
||||
end-to-end deadline against a peer that continuously streams bytes. Polling
|
||||
only reads status. A timeout raises `TelemtAPIError(code="poll_timeout")` with
|
||||
`last_response`, and does not cancel or resubmit the server operation. A normal
|
||||
transport failure remains a transport error and is not retried automatically.
|
||||
|
||||
Library waiters return terminal `failed`, `rolled_back`, or `cancelled` data so
|
||||
callers can inspect it. CLI wait/status commands exit 1 for those terminal
|
||||
failures, 0 for a successful response/terminal result, and 2 for invalid local
|
||||
input. Readiness false exits 1; a readable WEB tombstone exits 0. `202` without
|
||||
`--wait` means the request was accepted, not that the operation completed.
|
||||
|
||||
Reload IDs are process-local. `expected_revision` detects a different source
|
||||
target, but cannot distinguish all ID reuse after process restart with identical
|
||||
source bytes. WEB identifiers already carry a process reference and are handled
|
||||
as described below.
|
||||
|
||||
## WEB process references and bounded queries
|
||||
|
||||
Read `web_status().data["runtime"]["runtime_instance"]` and pass that exact
|
||||
reference to WEB controls. Copy `session_ref`/`operation_id` unchanged from
|
||||
server responses. The client never substitutes a fresh runtime reference after
|
||||
`409 web_runtime_mismatch`; re-evaluate operator intent before submitting work
|
||||
to a new process.
|
||||
|
||||
```python
|
||||
status = api.web_status()
|
||||
instance = status.data["runtime"]["runtime_instance"]
|
||||
page = api.web_sessions(limit=25, user="alice")
|
||||
refs = [row["session_ref"] for row in page.data["sessions"]]
|
||||
if refs:
|
||||
close = api.web_close_sessions(instance, {"kind": "refs", "session_refs": refs})
|
||||
done = api.wait_web_operation(close.data["operation_id"])
|
||||
|
||||
drain = api.web_drain(instance, 30)
|
||||
drain_id = drain.data["drain"]["operation_id"]
|
||||
finished = api.wait_web_drain(instance, drain_id, timeout=60)
|
||||
```
|
||||
|
||||
Enumeration defaults to 50 rows and accepts `limit=1..200`. `session_ref` is
|
||||
mutually exclusive with `cursor`/`limit`. Filters are `ip`, `host`, `user`,
|
||||
`user_agent_id`, `key_id`, `carrier`, and `state`; the
|
||||
[API reference](API.md#web-session-enumeration) defines their exact formatting
|
||||
and length limits. Query values are URL-encoded individually. The client does
|
||||
not auto-page an unbounded session list. `refs` closes 1..200 unique references;
|
||||
`filter` requires a non-null filter; `all` remains subject to the server's
|
||||
issuance-disabled gate.
|
||||
|
||||
Every WEB POST sends exactly `Content-Type: application/json`, no query, and a
|
||||
JSON object with the caller's process reference. The client caps these bodies
|
||||
at 64 KiB; the configured server body limit can be lower. A close waiter stops
|
||||
at `completed`, `cancelled`, or `failed`. A drain waiter reads WEB status until
|
||||
the same drain is `completed` or `cancelled`, preserving `force_closing` as a
|
||||
pending phase; a changed/missing process or drain fails with
|
||||
`operation_mismatch`.
|
||||
|
||||
## Errors and credential exposure
|
||||
|
||||
`TelemtAPIError` exposes `code`, `http_status`, `request_id`, `details`, and an
|
||||
optional `last_response` for polling diagnostics. JSON success envelopes with
|
||||
HTTP `503` readiness or `410` tombstone are accepted only by those dedicated
|
||||
methods. Other error envelopes raise, including feature-gate and stale-process
|
||||
failures. CLI errors go to stderr with field details and request correlation.
|
||||
|
||||
For peers outside the API whitelist, `gray_action="drop"` closes without HTTP,
|
||||
`"api"` returns structured `403 forbidden`, and `"200"` returns an empty
|
||||
`200 OK`. An empty/non-JSON body raises `invalid_response`; it is never reported
|
||||
as a successful mutation. Allowed peers still undergo authentication and
|
||||
read-only checks.
|
||||
|
||||
Config GET, user lists, creation and rotation may reveal credentials or
|
||||
credential-bearing links. Their library/CLI outputs retain the server contract;
|
||||
`--json-output` does not redact them. Use the redacted state endpoint for
|
||||
inspection where appropriate. All credentials and references in this guide
|
||||
are synthetic examples.
|
||||
|
||||
Run the local mock HTTP and CLI contract suite from the repository root:
|
||||
|
||||
```bash
|
||||
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s tools/tests -v
|
||||
python3 tools/generate_api_openapi.py --check
|
||||
```
|
||||
|
||||
These checks need no live proxy, Telegram connection or deployment credentials.
|
||||
@@ -1903,11 +1903,12 @@ Gültige öffentliche SOCKS-Werte `BND.ADDR/BND.PORT` mit einem Port ungleich nu
|
||||
cache_public_ip_path = "cache/public_ip.txt"
|
||||
```
|
||||
## dns_overrides
|
||||
- **Einschränkungen / Validierung**: `String[]`. Jeder Eintrag muss das Format `host:port:ip` verwenden.
|
||||
– `host`: Domänenname (darf nicht leer sein und darf nicht `:` enthalten)
|
||||
– `port`: `u16`
|
||||
– `ip`: IPv4 (`1.2.3.4`) oder in Klammern IPv6 (`[2001:db8::1]`). **Ungeklammertes IPv6 wird abgelehnt**.
|
||||
- **Beschreibung**: Runtime DNS-Overrideen für `host:port`-Ziele. Nützlich, um bestimmte IP-Adressen für bestimmte Upstream-Domänen zu erzwingen, ohne das System-DNS zu berühren.
|
||||
- **Einschränkungen / Validierung**: `String[]`, höchstens `4096` Einträge. Jeder Eintrag muss das Format `host:port:ip` verwenden.
|
||||
- `host`: nichtleerer Domainname ohne `:`.
|
||||
- `port`: `u16`.
|
||||
- `ip`: IPv4 (`1.2.3.4`) oder IPv6 in eckigen Klammern (`[2001:db8::1]`). IPv6 ohne Klammern wird abgelehnt.
|
||||
- **Beschreibung**: Überschreibt künftige `host:port`-Auflösungen über den Resolver der Generation, ohne das System-DNS zu ändern. Hostnamen werden ohne Beachtung der Groß-/Kleinschreibung verglichen; der Port muss übereinstimmen. Bei mehrfacher Angabe desselben Hosts und Ports gilt der letzte Eintrag. Der bestehende Dateiwächter veröffentlicht Änderungen; bereits aufgebaute Verbindungen behalten ihre Zieladressen.
|
||||
- **Control API**: `GET /v1/config` liefert aus `[network]` nur `network.dns_overrides`, einschließlich des Standardwerts `[]`. `PATCH /v1/config` und `POST /v1/config/validate` akzeptieren dieses Feld; andere Netzwerkfelder werden weiterhin abgelehnt. Das Array ersetzt die gesamte Liste; `[]` leert sie, `null` dagegen nicht. Beim Speichern wird nur der Wert ersetzt oder die Schlüsselzuweisung in die zuständige Quelldatei eingefügt. Benachbarte Einstellungen und andere Include-Dateien bleiben erhalten. Uneindeutige Zuständigkeit oder mehrere betroffene Quelldateien führen zu `409 config_patch_not_atomic`. PATCH wartet nicht auf die Veröffentlichung durch den Dateiwächter; `GET /v1/config/state?sections=network` zeigt den Veröffentlichungsstand. Siehe [DNS overrides in der API](../Architecture/API/API.md#dns-overrides).
|
||||
- **Beispiel**:
|
||||
|
||||
```toml
|
||||
@@ -2216,8 +2217,39 @@ Hinweis: Der conntrack-control Worker wird **nur auf Linux** ausgeführt. Auf an
|
||||
|
||||
# [server.api]
|
||||
|
||||
Hinweis: Dieser Abschnitt akzeptiert auch den Legacy-Alias `[server.admin_api]` (gleiches Schema wie `[server.api]`).
|
||||
Der ältere Alias `[server.admin_api]` verwendet dasselbe Schema.
|
||||
|
||||
Alle Felder dieses Abschnitts sind mit `Hot-Reload = ✘` gekennzeichnet: Der
|
||||
Dateiwächter behält die aktiven API-Einstellungen bei. Ein expliziter
|
||||
Generationsreload übernimmt `whitelist`, `gray_action`, `auth_header`,
|
||||
`request_body_limit_bytes`, `minimal_runtime_enabled`,
|
||||
`minimal_runtime_cache_ttl_ms`, `runtime_edge_enabled`,
|
||||
`runtime_edge_cache_ttl_ms`, `runtime_edge_top_n` und `read_only`.
|
||||
`enabled`, `listen` und `runtime_edge_events_capacity` erfordern einen
|
||||
Neustart des Prozesses.
|
||||
|
||||
`GET /v1/config`, `PATCH /v1/config` und `POST /v1/config/validate` stellen unter
|
||||
`server.api` nur `minimal_runtime_enabled`, `minimal_runtime_cache_ttl_ms`,
|
||||
`runtime_edge_enabled`, `runtime_edge_cache_ttl_ms` und `runtime_edge_top_n`
|
||||
bereit, zusätzlich zu `server.listeners`. GET enthält die Standardwerte;
|
||||
PATCH erhält benachbarte API-Einstellungen. Beide TTLs erlauben `0..60000` ms
|
||||
(`0` deaktiviert das Caching), top-N erlaubt `1..1000`. Ausgelassene Felder und
|
||||
zulässige Felder mit `null` behalten ihre Werte. Verbotene Felder werden auch
|
||||
bei `null` abgelehnt. Ein server-Patch ohne konkreten bearbeitbaren Wert wird
|
||||
abgelehnt. Speichern allein aktiviert diese Einstellungen nicht: Verwenden Sie
|
||||
`?reload=instant`, `?reload=drain` oder `POST /v1/system/reload` und warten Sie
|
||||
auf die Aktivierung der Generation. Auch bei gemischten Änderungen behält der
|
||||
Dateiwächter die bisherigen Werte bei. API-Listener und Ereignispufferkapazität
|
||||
bleiben an den Prozess gebunden; verspätete Cache-Schreibvorgänge können einer
|
||||
Anfrage keine Daten einer anderen Generation liefern. Andere API-Einstellungen
|
||||
müssen weiterhin in der zuständigen TOML-Datei geändert werden. Siehe
|
||||
[API-Diagnoseeinstellungen](../Architecture/API/API.md#api-observability-settings).
|
||||
`GET /v1/config/schema` beschreibt für jedes
|
||||
Feld die API-Verfügbarkeit und das Übernahmeverhalten. `GET /v1/config/state`
|
||||
zeigt Unterschiede zwischen Sollzustand und veröffentlichtem Zustand, ohne zu
|
||||
bestätigen, dass alle Verbraucher die Einstellungen bereits übernommen haben.
|
||||
Siehe [API-Referenz](../Architecture/API/API.md) und
|
||||
[Python-Client-Anleitung](../Architecture/API/PYTHON_CLIENT.md).
|
||||
|
||||
| Schlüssel | Typ | Default | Hot-Reload |
|
||||
| --- | --- | --- | --- |
|
||||
@@ -2246,7 +2278,7 @@ Hinweis: Dieser Abschnitt akzeptiert auch den Legacy-Alias `[server.admin_api]`
|
||||
```
|
||||
## gray_action
|
||||
- **Einschränkungen / Validierung**: `"drop"`, `"api"` oder `"200"`.
|
||||
- **Beschreibung**: API-Antwortrichtlinie für graue/eingeschränkte Staaten: Anfrage verwerfen, normale API-Antwort bereitstellen oder `200 OK` erzwingen.
|
||||
- **Beschreibung**: Gilt nur für direkte TCP-Peers außerhalb von `whitelist`: `"drop"` schließt die Verbindung ohne HTTP-Antwort, `"api"` liefert ein strukturiertes `403 forbidden`, und `"200"` liefert ein leeres `200 OK` mit `text/html; charset=utf-8`. Die Einstellung gewährt keinen API-Zugriff. Erlaubte Peers durchlaufen weiterhin die Authentifizierung und die Prüfung des read-only-Modus; eine leere Antwort ist kein JSON-Erfolgsnachweis.
|
||||
- **Beispiel**:
|
||||
|
||||
```toml
|
||||
@@ -2281,7 +2313,7 @@ Hinweis: Dieser Abschnitt akzeptiert auch den Legacy-Alias `[server.admin_api]`
|
||||
auth_header = "Bearer MY_TOKEN"
|
||||
```
|
||||
## request_body_limit_bytes
|
||||
- **Einschränkungen / Validierung**: Muss `> 0` (Byte) sein.
|
||||
- **Einschränkungen / Validierung**: `1..=1048576` (Bytes).
|
||||
- **Beschreibung**: Maximal akzeptierte HTTP-Anfragetextgröße (Byte).
|
||||
- **Beispiel**:
|
||||
|
||||
@@ -2616,11 +2648,11 @@ Der WEB-Modus transportiert MTProxy-Datenverkehr von Telegram Desktop über HTTP
|
||||
| `timeouts` | Tabelle | begrenzte Defaults | `✔` |
|
||||
| `vhosts` | Tabellen-Array | `[]` | `✔` |
|
||||
|
||||
`enabled = true` erfordert mindestens einen durch die Netzwerkrichtlinie zugelassenen WEB-Listener, einen vhost und mindestens ein Profil in jedem vhost. `https` behält den serialisierten HTTPS-Transport bei und erfordert `max_http_handlers >= 2`. Mit `https-lanes` erhalten Stream null und jeder logische Stream eigene Uplink-Sequenzen, Downlink-Cursor, Wiederholungen und Long Polls; dieser Carrier erfordert `max_http_handlers >= 4` und öffentliches HTTP/2 am TLS-Terminator. `websocket` transportiert alle logischen Streams über eine geordnete RFC-6455-Verbindung, während `websocket-lanes` jedem Stream ungleich null eine eigene Verbindung zuweist und Lane-Fehler isoliert. Beide WebSocket-Carrier verwenden nach der HTTPS-Sitzungserstellung `GET /api/v1/ws` und erfordern, dass der TLS-Terminator die HTTP/1.1-Upgrade-Header unverändert weiterleitet.
|
||||
`enabled = true` erfordert mindestens einen durch die Netzwerkrichtlinie zugelassenen WEB-Listener, einen vhost und mindestens ein Profil in jedem vhost. `https` verwendet eine gemeinsame HTTPS-Uplink-Sequenz mit einem ausgehandelten Upload-Fenster von 1–4 und erfordert `max_http_handlers >= 2`. Mit `https-lanes` erhalten Stream null und jeder logische Stream eigene Uplink-Sequenzen, Downlink-Cursor, Wiederholungen und Long Polls; dieser Carrier erfordert `max_http_handlers >= 4` und öffentliches HTTP/2 am TLS-Terminator. `websocket` transportiert alle logischen Streams über eine geordnete RFC-6455-Verbindung, während `websocket-lanes` jedem Stream ungleich null eine eigene Verbindung zuweist und Lane-Fehler isoliert. Beide WebSocket-Carrier verwenden nach der HTTPS-Sitzungserstellung `GET /api/v1/ws` und erfordern, dass der TLS-Terminator die HTTP/1.1-Upgrade-Header unverändert weiterleitet.
|
||||
|
||||
Fehlt `carriers` oder ist es `false`, sind Auto-Negotiation und Lernen deaktiviert und `carrier` ist der einzige Modus. Ein nicht leeres `carriers`-Array aktiviert die Start-Negotiation in der konfigurierten Reihenfolge; `carrier` wird genau einmal als letzter Fallback angehängt. Leere Arrays, Duplikate und `true` werden abgelehnt. Der Client darf nur vor dem Carrier-Commit zum nächsten Kandidaten wechseln; nach dem Commit erfordert ein Carrier-Wechsel eine neue Sitzung. Ein nativer Client ohne Metadaten, einschließlich Telegram iOS, verwendet immer den konfigurierten festen `carrier`, auch bei aktivierter Negotiation. Das aktuelle iOS unterstützt nur `https`; solche Bereitstellungen müssen daher `carrier = "https"` setzen. Die CFNetwork- und Darwin-User-Agent-Klassifizierung leitet keine Carrier-Unterstützung ab. Explizite native iOS-Capabilities werden mit `{https}` geschnitten; andere explizite Client-Capabilities gelten wie gemeldet.
|
||||
|
||||
`http_connection_capacity_action` gilt erst, nachdem Telemt eine private WEB-TCP-Verbindung akzeptiert hat und `max_http_connections` ausgeschöpft ist. `drop` schließt wie bisher sofort. `respond` sendet eine leere wiederholbare `503 Service Unavailable` mit `Retry-After: 1`, `Cache-Control: no-store` und `Connection: close`. `wait` wartet höchstens `http_overload_timeout_ms` auf normale Kapazität und beginnt danach die übliche HTTP-Verarbeitung; bei Timeout wird dieselbe begrenzte `503` gesendet. Höchstens `max_http_overload_connections` akzeptierte Sockets dürfen außerhalb der normalen Kapazität warten oder antworten.
|
||||
`http_connection_capacity_action` gilt erst, nachdem Telemt eine private WEB-TCP-Verbindung akzeptiert hat und `max_http_connections` ausgeschöpft ist. `drop` schließt wie bisher sofort. `respond` sendet eine leere wiederholbare `503 Service Unavailable` mit `Retry-After: 1`, `X-Telemt-Retry-After-Ms: 250`, `Cache-Control: no-store` und `Connection: close`. `wait` wartet höchstens `http_overload_timeout_ms` auf normale Kapazität und beginnt danach die übliche HTTP-Verarbeitung; bei Timeout wird dieselbe begrenzte `503` gesendet. Höchstens `max_http_overload_connections` akzeptierte Sockets dürfen außerhalb der normalen Kapazität warten oder antworten.
|
||||
|
||||
`decoy_fasttrack_mode` ist restart-only und betrifft nur Capability-Arbeit für `GET/HEAD` am konfigurierten Basis-Root. `off` behält den vollständigen Scan bei, `shadow` zählt geeignete Requests ohne den Scan zu überspringen, und `enforce` überspringt ihn nur für `HEAD` oder eine fehlende/nicht kanonische `bridge`-Query. Ein kanonisch geformtes Bridge-`GET` scannt immer alle Profile des ausgewählten vhost. Die Optimierung begrenzt keine feindlichen kanonischen Probes; `enforce` muss hinter dem produktiven TLS-Terminator auf Timing-Unterscheidbarkeit geprüft werden.
|
||||
|
||||
@@ -2704,6 +2736,38 @@ Diese prozessweiten Obergrenzen begrenzen alle WEB-Register, Warteschlangen, Req
|
||||
| `new_streams_per_minute` | `u32` | `6000` | Nachhaltige Erstellungsrate für logische Streams. |
|
||||
| `new_streams_burst` | `u32` | `512` | Prozessweiter Burst für die Stream-Erstellung. |
|
||||
|
||||
# [web.retry_jitter]
|
||||
|
||||
| Schlüssel | Typ | Standard | Beschreibung |
|
||||
| --- | --- | --- | --- |
|
||||
| `enabled` | `bool` | `false` | Aktiviert additiven Retry-Jitter. |
|
||||
| `min_ms` | `u32` | `0` | Inklusiver minimaler Zuschlag in Millisekunden. |
|
||||
| `max_ms` | `u32` | `250` | Inklusiver maximaler Zuschlag in Millisekunden; höchstens `30000`. |
|
||||
| `distribution` | `string` | `"uniform"` | `uniform` oder `triangular`. |
|
||||
| `peak_ms` | `Option<u32>` | `—` | Spitze der Dreiecksverteilung; ohne Angabe die Intervallmitte. |
|
||||
|
||||
`[web.retry_jitter]` ergänzt jeden bestehenden HTTP-Retry der Bridge um eine unabhängig gewählte Verzögerung: Netzwerkfehler und Antworten mit 408/429/502/503/504. Telegram-Anwendungen müssen nicht geändert werden. Ohne diesen Abschnitt oder mit `enabled = false` bleiben der 250-ms-Hinweis von Telemt und das bisherige Backoff/Jitter-Verhalten erhalten.
|
||||
|
||||
```toml
|
||||
[web.retry_jitter]
|
||||
enabled = true
|
||||
min_ms = 0
|
||||
max_ms = 250
|
||||
distribution = "uniform"
|
||||
# Only for distribution = "triangular":
|
||||
# peak_ms = 125
|
||||
```
|
||||
|
||||
Der Bereich beschreibt einen **Zuschlag**, nicht die gesamte Pause: Zusammen mit dem Telemt-Hinweis von 250 ms ergibt dieses Beispiel 250–500 ms. Ohne positiven Serverhinweis bleibt die Basis bei 250, 500, 1000, dann 2000 ms. Aktivierter Jitter ersetzt den bisherigen Jitter von bis zu 25%. Ein gültiger standardmäßiger `Retry-After` wird im aktivierten Modus nicht auf die bisherige Grenze von 30 Sekunden verkürzt. Übersteigt die Pause das verbleibende Operationsbudget, läuft das Budget ohne vorzeitigen Retry ab.
|
||||
|
||||
Standardwerte: `enabled = false`, `min_ms = 0`, `max_ms = 250`, `distribution = "uniform"`, ohne `peak_ms`. Es gilt `0 <= min_ms <= max_ms <= 30000`. `uniform` verteilt ganze Millisekunden gleichmäßig; `triangular` verwendet eine Dreiecksverteilung mit Rundung auf Millisekunden. Der optionale Gipfel liegt standardmäßig in der Mitte und muss innerhalb des Intervalls liegen. Ein expliziter Gipfel bei `uniform`, unbekannte Schlüssel/Verteilungen und ungültige Grenzen werden auch im deaktivierten Zustand abgelehnt. Gleiche Grenzen ergeben einen konstanten Zuschlag.
|
||||
|
||||
Die Richtlinie wird pro Bridge-Seite festgeschrieben. Konfigurations-/API-Reload wirkt auf neu geladene Seiten; bestehende Seiten behalten ihre Einstellungen bei Recovery. Recovery-JSON und HTTP-Kompatibilitätsheader bleiben unverändert. Die Auswahl bevorzugt `crypto.getRandomValues`, mit `Math.random` als Kompatibilitätsfallback. Erfolgreicher Datenverkehr wird nicht verzögert. Versuchslimits, absolute Budgets, Abbruch und unveränderte Payload-/Sequence-Wiederholung bleiben erhalten; längere Pausen können die Anzahl der Versuche innerhalb eines Startup-/Recovery-Budgets reduzieren.
|
||||
|
||||
Dies streut feste Retry-Intervalle, garantiert aber keinen Schutz vor DPI. Browser-Scheduling, Netzwerkwarteschlangen und andere Protokollzeiten bleiben beobachtbar. Bestehende Zeitleisten zeigen den deaktivierten Standardmodus. Bei aktiviertem Modus wird zu jeder Retry-Pause eine gezogene Verzögerung addiert, nicht zum ersten Verbindungsaufbau oder zu jedem Datenframe.
|
||||
|
||||
Die Richtlinie ändert nur bereits vorhandene Retry-Pausen. Strengere Limits einzelner Aufrufe bleiben erhalten: Reguläre `/down`-Polls und `/up`-Aufrufe nach dem Commit führen einen Versuch aus; ihr Recovery-Replay erlaubt zwei. Die Option erzeugt keine neuen Retry-Schleifen. Sie verlängert weder `web.timeouts.bridge_retry_secs` noch Start- oder Recovery-Deadlines.
|
||||
|
||||
# [web.timeouts]
|
||||
|
||||
Sofern eine Zeile nichts anderes angibt, werden Timeouts in Sekunden angegeben und müssen im Bereich `1..=3600` liegen. Konfigurierte serverseitige Deadlines einzelner HTTP-Phasen müssen kleiner als `http_idle_secs` sein; geschützte Phasen behalten ihre eigenen Deadlines, sodass der Idle-Timer keine Gesamtdeadline für einen Request ist. Das clientseitige Bridge-Retry-Fenster hat eigene Grenzen.
|
||||
@@ -3557,6 +3621,7 @@ Wenn Backend oder Netzwerk stark bandbreitenbeschränkt sind, reduzieren Sie zue
|
||||
alice = 500
|
||||
```
|
||||
## user_max_tcp_conns_global_each
|
||||
- **API**: Das Feld ist über `GET/PATCH /v1/access/policy` verfügbar. Auslassen behält den Wert bei; `null` setzt ihn auf den Typstandard zurück. Die Veröffentlichung erfolgt über den Watcher; die Antwort trennt die Snapshots `desired` und `effective`.
|
||||
- **Einschränkungen / Validierung**: `usize`. `0` deaktiviert das geerbte Limit.
|
||||
- **Beschreibung**: Globale maximale Anzahl gleichzeitiger TCP-Verbindungen pro User, angewendet, wenn ein User **keinen positiven** Eintrag in `[access.user_max_tcp_conns]` hat (ein fehlender Schlüssel oder ein Wert von `0`, beides fällt auf diese Einstellung). Grenzwerte pro User, die größer als `0` in `user_max_tcp_conns` sind, haben Vorrang.
|
||||
- **Beispiel**:
|
||||
@@ -3619,6 +3684,7 @@ Wenn Backend oder Netzwerk stark bandbreitenbeschränkt sind, reduzieren Sie zue
|
||||
alice = 16
|
||||
```
|
||||
## user_max_unique_ips_global_each
|
||||
- **API**: Das Feld ist über `GET/PATCH /v1/access/policy` verfügbar. Auslassen behält den Wert bei; `null` setzt ihn auf den Typstandard zurück. Die Veröffentlichung erfolgt über den Watcher; die Antwort trennt die Snapshots `desired` und `effective`.
|
||||
- **Einschränkungen / Validierung**: `usize`. `0` deaktiviert das geerbte Limit.
|
||||
- **Beschreibung**: Globales eindeutiges IP-Limit pro User, das angewendet wird, wenn ein User in `[access.user_max_unique_ips]` keine individuelle Override hat.
|
||||
- **Beispiel**:
|
||||
@@ -3628,6 +3694,7 @@ Wenn Backend oder Netzwerk stark bandbreitenbeschränkt sind, reduzieren Sie zue
|
||||
user_max_unique_ips_global_each = 8
|
||||
```
|
||||
## user_max_unique_ips_mode
|
||||
- **API**: Das Feld ist über `GET/PATCH /v1/access/policy` verfügbar. Auslassen behält den Wert bei; `null` setzt ihn auf den Typstandard zurück. Die Veröffentlichung erfolgt über den Watcher; die Antwort trennt die Snapshots `desired` und `effective`.
|
||||
- **Einschränkungen / Validierung**: Muss einer von `"active_window"`, `"time_window"`, `"combined"` sein.
|
||||
- **Beschreibung**: Eindeutiger Source-IP-Limit-Abrechnungsmodus.
|
||||
- **Beispiel**:
|
||||
@@ -3637,6 +3704,7 @@ Wenn Backend oder Netzwerk stark bandbreitenbeschränkt sind, reduzieren Sie zue
|
||||
user_max_unique_ips_mode = "active_window"
|
||||
```
|
||||
## user_max_unique_ips_window_secs
|
||||
- **API**: Das Feld ist über `GET/PATCH /v1/access/policy` verfügbar. Auslassen behält den Wert bei; `null` setzt ihn auf den Typstandard zurück. Die Veröffentlichung erfolgt über den Watcher; die Antwort trennt die Snapshots `desired` und `effective`.
|
||||
- **Einschränkungen / Validierung**: Muss `> 0` sein.
|
||||
- **Beschreibung**: Fenstergröße (Sekunden), die von Abrechnungsmodi mit eindeutiger IP verwendet wird, die ein Zeitfenster enthalten (`"time_window"` und `"combined"`).
|
||||
- **Beispiel**:
|
||||
@@ -3646,6 +3714,7 @@ Wenn Backend oder Netzwerk stark bandbreitenbeschränkt sind, reduzieren Sie zue
|
||||
user_max_unique_ips_window_secs = 30
|
||||
```
|
||||
## user_source_deny
|
||||
- **API**: `source_deny` in Benutzer-GET/create/PATCH stellt diese Liste bereit. Auslassen behält sie bei, ein Array ersetzt sie vollständig und `null` entfernt den konfigurierten Eintrag. Die strikte Validierung akzeptiert diese Map. `source_deny_status.runtime_reload_required` vergleicht gewünschte und veröffentlichte Regeln; angewendet werden sie mit `POST /v1/system/reload`. Der Watcher aktualisiert diese Regeln nicht; Speichern beendet keine Sitzungen. Beim Löschen eines Benutzers bleibt die Regel erhalten. Ein erneut angelegter Name übernimmt sie, sofern nicht ausdrücklich `source_deny=null` angegeben wird.
|
||||
- **Einschränkungen / Validierung**: Tabelle `username -> IpNetwork[]`. Jedes Netzwerk muss als CIDR parsen (zum Beispiel `203.0.113.0/24` oder `2001:db8::/32`).
|
||||
- **Beschreibung**: Source-IP/CIDR-Verweigerungsliste pro User wird **nach erfolgreicher Authentifizierung** in den Handshake-Pfaden TLS und MTProto angewendet. Eine übereinstimmende Source-IP wird über denselben Fail-Closed-Pfad wie eine ungültige Authentifizierung abgelehnt.
|
||||
- **Beispiel**:
|
||||
@@ -3698,6 +3767,7 @@ Wenn Backend oder Netzwerk stark bandbreitenbeschränkt sind, reduzieren Sie zue
|
||||
alice = { up_bps = 1048576, down_bps = 2097152 }
|
||||
```
|
||||
## cidr_rate_limits
|
||||
- **API**: Das Feld ist über `GET/PATCH /v1/access/policy` verfügbar. Auslassen behält den Wert bei; `null` setzt einen Skalar auf den Typstandard zurück. Bei `cidr_rate_limits` werden Schlüssel zusammengeführt, ein null-Eintrag löscht eine Regel und `null` für die gesamte Map löscht alle Regeln. Ratenobjekte ersetzen beide Richtungen, angegeben in Bit pro Sekunde. Die Veröffentlichung erfolgt über den Watcher; die Antwort trennt die Snapshots `desired` und `effective`.
|
||||
- **Einschränkungen / Validierung**: Tabelle `CIDR oder Auto-Template -> { up_bps, down_bps }`. Jede Richtung muss in `0..=100000000000` liegen; `0` bedeutet für diese Richtung unbegrenzt, und mindestens eine Richtung muss ungleich Null sein. Explizite CIDR-Schlüssel müssen als `IpNetwork` parsbar sein; Auto-Template-Schlüssel müssen `*4/N` (`N=0..32`), `*6/N` (`N=0..128`) oder `*/N` (`N=0..32`) verwenden. Doppelte normalisierte Auto-Templates werden abgelehnt.
|
||||
- **Beschreibung**: Source-Subnetz-Bandbreitenlimits, die zusätzlich zu Per-User-Limits greifen. Explizite CIDR-Regeln verwenden Longest-Prefix-Wins und haben Vorrang vor Auto-Templates. Auto-Templates erzeugen Buckets lazy pro passendem Source-Subnetz: `*4/N` für IPv4, `*6/N` für IPv6 und `*/N` als Dual-Stack-Shorthand, bei dem IPv4 `/N` und IPv6 `/(N * 4)` nutzt.
|
||||
- **Beispiel**:
|
||||
|
||||
@@ -1903,11 +1903,12 @@ A valid public SOCKS `BND.ADDR/BND.PORT` with a nonzero port supplies the comple
|
||||
cache_public_ip_path = "cache/public_ip.txt"
|
||||
```
|
||||
## dns_overrides
|
||||
- **Constraints / validation**: `String[]`. Each entry must use `host:port:ip` format.
|
||||
- `host`: domain name (must be non-empty and must not contain `:`)
|
||||
- `port`: `u16`
|
||||
- `ip`: IPv4 (`1.2.3.4`) or bracketed IPv6 (`[2001:db8::1]`). **Unbracketed IPv6 is rejected**.
|
||||
- **Description**: Runtime DNS overrides for `host:port` targets. Useful for forcing specific IPs for given upstream domains without touching system DNS.
|
||||
- **Constraints / validation**: `String[]`, at most `4096` entries. Each entry must use `host:port:ip` format.
|
||||
- `host`: domain name (must be nonempty and must not contain `:`).
|
||||
- `port`: `u16`.
|
||||
- `ip`: IPv4 (`1.2.3.4`) or bracketed IPv6 (`[2001:db8::1]`). Unbracketed IPv6 is rejected.
|
||||
- **Description**: Overrides future `host:port` lookups through the generation resolver without changing system DNS. Host matching is case-insensitive and port-specific; the last duplicate host/port entry wins. The existing watcher publishes changes, while established connections keep their endpoints.
|
||||
- **Control API**: `GET /v1/config` exposes only `network.dns_overrides` from `[network]`, including the default `[]`. `PATCH /v1/config` and `POST /v1/config/validate` accept this field; other network fields remain rejected. The array replaces the complete list; `[]` clears it, while `null` does not. Persistence changes only the value or inserts its declaration in the owning source, preserving sibling settings and other include files. Ambiguous or multiple source owners return `409 config_patch_not_atomic`. PATCH does not wait for watcher publication; inspect `GET /v1/config/state?sections=network` for publication evidence. See [DNS overrides in the API](../Architecture/API/API.md#dns-overrides).
|
||||
- **Example**:
|
||||
|
||||
```toml
|
||||
@@ -2216,8 +2217,33 @@ Note: The conntrack-control worker runs **only on Linux**. On other operating sy
|
||||
|
||||
# [server.api]
|
||||
|
||||
Note: This section also accepts the legacy alias `[server.admin_api]` (same schema as `[server.api]`).
|
||||
The legacy alias `[server.admin_api]` uses the same schema.
|
||||
|
||||
All fields in this section have `Hot-Reload = ✘`: the file watcher retains the
|
||||
active API settings. Explicit generation reload applies `whitelist`,
|
||||
`gray_action`, `auth_header`, `request_body_limit_bytes`,
|
||||
`minimal_runtime_enabled`, `minimal_runtime_cache_ttl_ms`,
|
||||
`runtime_edge_enabled`, `runtime_edge_cache_ttl_ms`, `runtime_edge_top_n`, and
|
||||
`read_only`. `enabled`, `listen`, and `runtime_edge_events_capacity` require a
|
||||
process restart.
|
||||
|
||||
`GET /v1/config`, `PATCH /v1/config`, and `POST /v1/config/validate` expose only
|
||||
`minimal_runtime_enabled`, `minimal_runtime_cache_ttl_ms`, `runtime_edge_enabled`,
|
||||
`runtime_edge_cache_ttl_ms`, and `runtime_edge_top_n` under `server.api`, alongside
|
||||
`server.listeners`. GET includes defaults; sparse PATCH preserves API siblings.
|
||||
Both TTLs accept `0..60000` ms (`0` disables caching); top-N accepts `1..1000`.
|
||||
Omission and allowed `null` members retain values. Forbidden fields are rejected
|
||||
even when `null`. A server patch without a concrete editable value is rejected.
|
||||
Saving alone leaves these settings pending: use `?reload=instant`, `?reload=drain`,
|
||||
or `POST /v1/system/reload` and wait for activation. The watcher retains them even
|
||||
in mixed changes. The API listener and event-ring capacity remain process-owned;
|
||||
late cache writes cannot cross request-generation boundaries. Other API settings
|
||||
still require editing the owning TOML source. See
|
||||
[API observability settings](../Architecture/API/API.md#api-observability-settings).
|
||||
`GET /v1/config/schema` describes each field's exposure and application policy.
|
||||
`GET /v1/config/state` reports desired/published differences without claiming
|
||||
complete consumer convergence. See the [API reference](../Architecture/API/API.md)
|
||||
and [Python client guide](../Architecture/API/PYTHON_CLIENT.md).
|
||||
|
||||
| Key | Type | Default | Hot-Reload |
|
||||
| --- | ---- | ------- | ---------- |
|
||||
@@ -2246,7 +2272,7 @@ Note: This section also accepts the legacy alias `[server.admin_api]` (same sche
|
||||
```
|
||||
## gray_action
|
||||
- **Constraints / validation**: `"drop"`, `"api"`, or `"200"`.
|
||||
- **Description**: API response policy for gray/limited states: drop request, serve normal API response, or force `200 OK`.
|
||||
- **Description**: Applies only to direct peers outside `whitelist`: `"drop"` closes the connection without an HTTP response, `"api"` returns structured `403 forbidden`, and `"200"` returns an empty `200 OK` with `text/html; charset=utf-8`. It never grants API access. Allowed peers still undergo authentication and read-only checks; an empty gray response is not a JSON success envelope.
|
||||
- **Example**:
|
||||
|
||||
```toml
|
||||
@@ -2281,7 +2307,7 @@ Note: This section also accepts the legacy alias `[server.admin_api]` (same sche
|
||||
auth_header = "Bearer MY_TOKEN"
|
||||
```
|
||||
## request_body_limit_bytes
|
||||
- **Constraints / validation**: Must be `> 0` (bytes).
|
||||
- **Constraints / validation**: `1..=1048576` (bytes).
|
||||
- **Description**: Maximum accepted HTTP request body size (bytes).
|
||||
- **Example**:
|
||||
|
||||
@@ -2616,11 +2642,11 @@ WEB mode carries Telegram Desktop MTProxy traffic through HTTPS terminated by an
|
||||
| `timeouts` | table | bounded defaults | `✔` |
|
||||
| `vhosts` | array of tables | `[]` | `✔` |
|
||||
|
||||
`enabled = true` requires at least one network-eligible WEB listener, at least one vhost, and at least one profile in every vhost. `https` preserves the serialized HTTPS transport and requires `max_http_handlers >= 2`. `https-lanes` gives stream zero and every logical stream independent uplink sequencing, downlink cursors, retries, and long polls; it requires `max_http_handlers >= 4` and public HTTP/2 on the TLS terminator. `websocket` carries all logical streams over one ordered RFC 6455 connection, while `websocket-lanes` owns one connection per non-zero logical stream and isolates lane failures. Both WebSocket carriers use `GET /api/v1/ws` after HTTPS session creation and require the TLS terminator to preserve HTTP/1.1 Upgrade headers.
|
||||
`enabled = true` requires at least one network-eligible WEB listener, at least one vhost, and at least one profile in every vhost. `https` uses a shared HTTPS uplink sequence with a negotiated upload window of 1–4 and requires `max_http_handlers >= 2`. `https-lanes` gives stream zero and every logical stream independent uplink sequencing, downlink cursors, retries, and long polls; it requires `max_http_handlers >= 4` and public HTTP/2 on the TLS terminator. `websocket` carries all logical streams over one ordered RFC 6455 connection, while `websocket-lanes` owns one connection per non-zero logical stream and isolates lane failures. Both WebSocket carriers use `GET /api/v1/ws` after HTTPS session creation and require the TLS terminator to preserve HTTP/1.1 Upgrade headers.
|
||||
|
||||
When `carriers` is missing or `false`, auto-negotiation and learning are disabled and `carrier` is the only mode. A non-empty `carriers` array enables startup-only negotiation in its configured order; `carrier` is appended exactly once as the final fallback. Empty arrays, duplicates, and `true` are rejected. The client advances candidates only before carrier commit and must create a new session to change carrier after commit. A metadata-free native client, including Telegram iOS, always uses the configured fixed `carrier`, even when negotiation is enabled. Current iOS supports only `https`, so such deployments must configure `carrier = "https"`. CFNetwork and Darwin User-Agent classification does not infer carrier support. Explicit native iOS capabilities are intersected with `{https}`; other explicit client capabilities participate as reported.
|
||||
|
||||
`http_connection_capacity_action` applies only after Telemt has accepted a private WEB TCP connection and `max_http_connections` is exhausted. `drop` preserves the legacy immediate close. `respond` emits an empty `503 Service Unavailable` with `Retry-After: 1`, `Cache-Control: no-store`, and `Connection: close`. `wait` waits for ordinary connection capacity for at most `http_overload_timeout_ms`, then enters normal HTTP handling; timeout emits the same bounded `503`. At most `max_http_overload_connections` accepted sockets may wait or respond outside ordinary connection capacity. This policy cannot observe or cause a TCP connect refusal before Telemt accepts the socket.
|
||||
`http_connection_capacity_action` applies only after Telemt has accepted a private WEB TCP connection and `max_http_connections` is exhausted. `drop` preserves the legacy immediate close. `respond` emits an empty `503 Service Unavailable` with `Retry-After: 1`, `X-Telemt-Retry-After-Ms: 250`, `Cache-Control: no-store`, and `Connection: close`. `wait` waits for ordinary connection capacity for at most `http_overload_timeout_ms`, then enters normal HTTP handling; timeout emits the same bounded `503`. At most `max_http_overload_connections` accepted sockets may wait or respond outside ordinary connection capacity. This policy cannot observe or cause a TCP connect refusal before Telemt accepts the socket.
|
||||
|
||||
`decoy_fasttrack_mode` is restart-only. `off` preserves legacy root-request scanning and collects no fast-track decisions. `shadow` records eligible requests while preserving the full scan. `enforce` skips scans only for `HEAD` or absent/noncanonical bridge queries. A canonical bridge-shaped `GET`, including an unknown capability, always scans every profile in the selected vhost. The optimization does not bound hostile canonical probes and enforce mode must be validated for request-shape timing distinguishability behind the production TLS terminator.
|
||||
|
||||
@@ -2704,6 +2730,38 @@ These process-wide ceilings make every WEB registry, queue, request body, capabi
|
||||
| `new_streams_per_minute` | `u32` | `6000` | Sustained logical-stream creation rate. |
|
||||
| `new_streams_burst` | `u32` | `512` | Process-wide logical-stream creation burst. |
|
||||
|
||||
# [web.retry_jitter]
|
||||
|
||||
| Key | Type | Default | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| `enabled` | `bool` | `false` | Enable additive retry jitter. |
|
||||
| `min_ms` | `u32` | `0` | Inclusive minimum addition in milliseconds. |
|
||||
| `max_ms` | `u32` | `250` | Inclusive maximum addition in milliseconds; at most `30000`. |
|
||||
| `distribution` | `string` | `"uniform"` | `uniform` or `triangular`. |
|
||||
| `peak_ms` | `Option<u32>` | `—` | Triangular peak; omitted means the interval midpoint. |
|
||||
|
||||
`[web.retry_jitter]` adds an independently sampled delay to every existing bridge HTTP retry (network errors and 408/429/502/503/504). It requires no Telegram application changes. Without this section, or with `enabled = false`, the existing 250 ms Telemt hint and legacy backoff/jitter remain unchanged.
|
||||
|
||||
```toml
|
||||
[web.retry_jitter]
|
||||
enabled = true
|
||||
min_ms = 0
|
||||
max_ms = 250
|
||||
distribution = "uniform"
|
||||
# Only for distribution = "triangular":
|
||||
# peak_ms = 125
|
||||
```
|
||||
|
||||
The range describes an **addition**, not the total pause: the Telemt 250 ms hint plus this example gives 250–500 ms. Without a positive server hint, the base remains 250, 500, 1000, then 2000 ms. Enabled jitter replaces the legacy 25% jitter. A valid standard `Retry-After` is not shortened to the legacy 30-second cap in enabled mode. If the pause exceeds the remaining operation budget, the budget expires without an early retry.
|
||||
|
||||
Defaults are `enabled = false`, `min_ms = 0`, `max_ms = 250`, `distribution = "uniform"`, and no `peak_ms`. Require `0 <= min_ms <= max_ms <= 30000`. `uniform` samples integer milliseconds; `triangular` samples a triangular density and rounds to milliseconds. Its optional peak defaults to the midpoint and must be within the interval. An explicit peak with `uniform`, unknown keys/distributions and invalid ranges are rejected even when disabled. Equal bounds produce a constant addition.
|
||||
|
||||
The policy is frozen into each bridge page. Config/API reload affects newly loaded pages; existing pages retain it through recovery. Recovery JSON and HTTP compatibility headers remain unchanged. Sampling prefers `crypto.getRandomValues`, with `Math.random` as a compatibility fallback. Successful traffic is not delayed. Attempt limits, absolute budgets, cancellation and payload/sequence replay remain intact; longer pauses can exhaust a startup/recovery budget sooner in terms of completed attempts.
|
||||
|
||||
This reduces fixed retry timing, without guaranteeing resistance to DPI. Browser scheduling, network queues and other protocol timing remain observable. Existing timeline examples describe the default disabled mode. To evaluate enabled mode, add a sampled delay to each retry pause, not to the initial connection or every data frame.
|
||||
|
||||
The policy changes existing retry waits only. Stricter per-call limits still apply: ordinary `/down` polls and committed `/up` calls use one attempt; their recovery replay permits two. This option does not create new retry loops. It neither extends `web.timeouts.bridge_retry_secs` nor any startup/recovery deadline.
|
||||
|
||||
# [web.timeouts]
|
||||
|
||||
Unless a row states otherwise, timeouts are measured in seconds and must be within `1..=3600`. Configured server-side HTTP phase deadlines must be lower than `http_idle_secs`; protected phases retain their own deadlines, so the idle timer is not an aggregate request deadline. The bridge retry window is client-side and follows its own bound.
|
||||
@@ -3540,6 +3598,7 @@ If your backend or network is very bandwidth-constrained, reduce cap first. If p
|
||||
alice = 500
|
||||
```
|
||||
## user_max_tcp_conns_global_each
|
||||
- **API**: `GET/PATCH /v1/access/policy` exposes this field. Omission preserves it; scalar `null` restores the type default. Publication uses the watcher; the response separates `desired` and `effective` snapshots.
|
||||
- **Constraints / validation**: `usize`. `0` disables the inherited limit.
|
||||
- **Description**: Global per-user maximum concurrent TCP connections, applied when a user has **no positive** entry in `[access.user_max_tcp_conns]` (a missing key, or a value of `0`, both fall through to this setting). Per-user limits greater than `0` in `user_max_tcp_conns` take precedence.
|
||||
- **Example**:
|
||||
@@ -3602,6 +3661,7 @@ If your backend or network is very bandwidth-constrained, reduce cap first. If p
|
||||
alice = 16
|
||||
```
|
||||
## user_max_unique_ips_global_each
|
||||
- **API**: `GET/PATCH /v1/access/policy` exposes this field. Omission preserves it; scalar `null` restores the type default. Publication uses the watcher; the response separates `desired` and `effective` snapshots.
|
||||
- **Constraints / validation**: `usize`. `0` disables the inherited limit.
|
||||
- **Description**: Global per-user unique IP limit applied when a user has no individual override in `[access.user_max_unique_ips]`.
|
||||
- **Example**:
|
||||
@@ -3611,6 +3671,7 @@ If your backend or network is very bandwidth-constrained, reduce cap first. If p
|
||||
user_max_unique_ips_global_each = 8
|
||||
```
|
||||
## user_max_unique_ips_mode
|
||||
- **API**: `GET/PATCH /v1/access/policy` exposes this field. Omission preserves it; scalar `null` restores the type default. Publication uses the watcher; the response separates `desired` and `effective` snapshots.
|
||||
- **Constraints / validation**: Must be one of `"active_window"`, `"time_window"`, `"combined"`.
|
||||
- **Description**: Unique source IP limit accounting mode.
|
||||
- **Example**:
|
||||
@@ -3620,6 +3681,7 @@ If your backend or network is very bandwidth-constrained, reduce cap first. If p
|
||||
user_max_unique_ips_mode = "active_window"
|
||||
```
|
||||
## user_max_unique_ips_window_secs
|
||||
- **API**: `GET/PATCH /v1/access/policy` exposes this field. Omission preserves it; scalar `null` restores the type default. Publication uses the watcher; the response separates `desired` and `effective` snapshots.
|
||||
- **Constraints / validation**: Must be `> 0`.
|
||||
- **Description**: Window size (seconds) used by unique-IP accounting modes that include a time window (`"time_window"` and `"combined"`).
|
||||
- **Example**:
|
||||
@@ -3629,6 +3691,7 @@ If your backend or network is very bandwidth-constrained, reduce cap first. If p
|
||||
user_max_unique_ips_window_secs = 30
|
||||
```
|
||||
## user_source_deny
|
||||
- **API**: `source_deny` in user GET/create/PATCH exposes this list. Omission retains it, an array replaces it, and `null` removes the authored entry. Strict validation accepts this map. `source_deny_status.runtime_reload_required` compares desired and published rules; apply with `POST /v1/system/reload`. The watcher does not update these rules, and saving does not cancel sessions. Deleting a user retains the rule; recreation inherits it unless `source_deny=null` is explicit.
|
||||
- **Constraints / validation**: Table `username -> IpNetwork[]`. Each network must parse as CIDR (for example `203.0.113.0/24` or `2001:db8::/32`).
|
||||
- **Description**: Per-user source IP/CIDR deny-list applied **after successful auth** in TLS and MTProto handshake paths. A matched source IP is rejected via the same fail-closed path as invalid auth.
|
||||
- **Example**:
|
||||
@@ -3681,6 +3744,7 @@ If your backend or network is very bandwidth-constrained, reduce cap first. If p
|
||||
alice = { up_bps = 1048576, down_bps = 2097152 }
|
||||
```
|
||||
## cidr_rate_limits
|
||||
- **API**: `GET/PATCH /v1/access/policy` exposes this field. Omission preserves it; scalar `null` restores the type default. For `cidr_rate_limits`, a map merges keys, a null entry deletes one rule, and whole-map `null` clears all rules. Rate objects replace both directions, in bits per second. Publication uses the watcher; the response separates `desired` and `effective` snapshots.
|
||||
- **Constraints / validation**: Table `CIDR or auto-template -> { up_bps, down_bps }`. Each direction must be within `0..=100000000000`; `0` means unlimited for that direction, and at least one direction must be non-zero. Explicit CIDR keys must parse as `IpNetwork`; auto-template keys must be `*4/N` (`N=0..32`), `*6/N` (`N=0..128`), or `*/N` (`N=0..32`). Duplicate normalized auto-templates are rejected.
|
||||
- **Description**: Source-subnet bandwidth caps applied alongside per-user limits. Explicit CIDR rules use longest-prefix-wins and take priority over auto-templates. Auto-templates create buckets lazily per matched source subnet: `*4/N` for IPv4, `*6/N` for IPv6, and `*/N` as a dual-stack shorthand where IPv4 uses `/N` and IPv6 uses `/(N * 4)`.
|
||||
- **Example**:
|
||||
|
||||
@@ -1905,11 +1905,12 @@
|
||||
cache_public_ip_path = "cache/public_ip.txt"
|
||||
```
|
||||
## dns_overrides
|
||||
- **Ограничения / валидация**: `String[]`. Каждая запись должна использовать формат `host:port:ip`.
|
||||
- `host`: доменное имя (не должно быть пустым и не должно содержать `:`)
|
||||
- `port`: `u16`
|
||||
- `ip`: IPv4 (`1.2.3.4`) или IPv6 в квадратных скобках (`[2001:db8::1]`). **Значения IPv6 без скобок отклоняются!**
|
||||
- **Описание**: Переопределение DNS во время работы для `host:port`-соединений. Позволяет принудительно задавать IP для указанных доменов, не изменяя системный DNS.
|
||||
- **Ограничения / валидация**: `String[]`, не более `4096` записей. Каждая запись задаётся в формате `host:port:ip`.
|
||||
- `host`: доменное имя, непустое и без `:`.
|
||||
- `port`: `u16`.
|
||||
- `ip`: IPv4 (`1.2.3.4`) или IPv6 в квадратных скобках (`[2001:db8::1]`). IPv6 без скобок отклоняется.
|
||||
- **Описание**: Переопределяет будущие запросы `host:port` через резолвер поколения, не меняя системный DNS. Имена сравниваются без учёта регистра, порт должен совпадать; при повторении пары имя/порт действует последняя запись. Изменения публикует существующий watcher, а установленные соединения сохраняют свои адреса назначения.
|
||||
- **Control API**: `GET /v1/config` возвращает из `[network]` только `network.dns_overrides`, включая значение по умолчанию `[]`. `PATCH /v1/config` и `POST /v1/config/validate` принимают это поле; остальные поля network по-прежнему отклоняются. Массив заменяет весь список; `[]` очищает его, а `null` — нет. При сохранении заменяется только значение или добавляется объявление ключа в файле-владельце; соседние настройки и другие include-файлы сохраняются. Неоднозначное владение или несколько файлов-владельцев дают `409 config_patch_not_atomic`. PATCH не ждёт публикации watcher’ом; её состояние доступно через `GET /v1/config/state?sections=network`. См. [DNS overrides в API](../Architecture/API/API.md#dns-overrides).
|
||||
- **Пример**:
|
||||
|
||||
```toml
|
||||
@@ -2222,8 +2223,36 @@
|
||||
|
||||
# [server.api]
|
||||
|
||||
Примечание: В этом разделе также задается устаревший параметр `[server.admin_api]` (аналогично `[server.api]`).
|
||||
Устаревший алиас `[server.admin_api]` использует ту же схему.
|
||||
|
||||
Для всех полей этого раздела указано `Hot-Reload = ✘`: watcher сохраняет
|
||||
действующие настройки API. Явный reload поколения применяет `whitelist`,
|
||||
`gray_action`, `auth_header`, `request_body_limit_bytes`,
|
||||
`minimal_runtime_enabled`, `minimal_runtime_cache_ttl_ms`,
|
||||
`runtime_edge_enabled`, `runtime_edge_cache_ttl_ms`, `runtime_edge_top_n` и
|
||||
`read_only`. Для `enabled`, `listen` и `runtime_edge_events_capacity` нужен
|
||||
перезапуск процесса.
|
||||
|
||||
`GET /v1/config`, `PATCH /v1/config` и `POST /v1/config/validate` открывают внутри
|
||||
`server.api` только `minimal_runtime_enabled`, `minimal_runtime_cache_ttl_ms`,
|
||||
`runtime_edge_enabled`, `runtime_edge_cache_ttl_ms` и `runtime_edge_top_n`,
|
||||
в дополнение к `server.listeners`. GET включает значения по умолчанию; PATCH
|
||||
сохраняет соседние настройки API. Оба TTL допускают `0..60000` мс (`0` отключает
|
||||
кэширование), top-N — `1..1000`. Пропущенные поля и допустимые поля со значением
|
||||
`null` сохраняют прежние значения. Запрещённые поля отклоняются даже при `null`.
|
||||
PATCH объекта server без конкретного редактируемого значения отклоняется.
|
||||
Одного сохранения недостаточно: используйте `?reload=instant`, `?reload=drain`
|
||||
или `POST /v1/system/reload` и дождитесь активации поколения. Watcher сохраняет
|
||||
прежние значения этих полей даже при смешанных изменениях. Listener API и ёмкость
|
||||
кольцевого буфера событий остаются общими для процесса; поздняя запись в кэш
|
||||
не позволяет выдать запросу данные другого поколения. Остальные настройки API
|
||||
по-прежнему меняются в TOML-файле-владельце. См.
|
||||
[настройки диагностики API](../Architecture/API/API.md#api-observability-settings).
|
||||
`GET /v1/config/schema` описывает
|
||||
доступность и способ применения каждого поля. `GET /v1/config/state` показывает
|
||||
различия между желаемым и опубликованным состоянием, без обещания, что все
|
||||
потребители уже применили настройки. См. [справочник API](../Architecture/API/API.md)
|
||||
и [руководство по Python-клиенту](../Architecture/API/PYTHON_CLIENT.md).
|
||||
|
||||
| Ключ | Тип | По умолчанию | Hot-Reload |
|
||||
| --- | ---- | ------- | ---------- |
|
||||
@@ -2252,7 +2281,7 @@
|
||||
```
|
||||
## gray_action
|
||||
- **Ограничения / валидация**: `"drop"`, `"api"` или `"200"`.
|
||||
- **Описание**: Политика ответа API в «серых» (ограниченных) состояниях: сброс, обычный API-ответ, либо `200 OK`.
|
||||
- **Описание**: Действует только для прямых TCP-клиентов вне `whitelist`: `"drop"` закрывает соединение без HTTP-ответа, `"api"` возвращает структурированный `403 forbidden`, а `"200"` — пустой `200 OK` с `text/html; charset=utf-8`. Этот параметр не разрешает доступ к API. Клиенты из whitelist по-прежнему проходят аутентификацию и проверку режима read-only; пустой ответ не является JSON-подтверждением успеха.
|
||||
- **Example**:
|
||||
|
||||
```toml
|
||||
@@ -2287,7 +2316,7 @@
|
||||
auth_header = "Bearer MY_TOKEN"
|
||||
```
|
||||
## request_body_limit_bytes
|
||||
- **Ограничения / валидация**: Должно быть `> 0` (байт).
|
||||
- **Ограничения / валидация**: `1..=1048576` (байт).
|
||||
- **Описание**: Максимальный принимаемый размер тела HTTP-запроса (в байтах).
|
||||
- **Пример**:
|
||||
|
||||
@@ -2622,11 +2651,11 @@ WEB-режим переносит MTProxy-трафик Telegram Desktop внут
|
||||
| `timeouts` | таблица | ограниченные defaults | `✔` |
|
||||
| `vhosts` | массив таблиц | `[]` | `✔` |
|
||||
|
||||
Для `enabled = true` нужен как минимум один доступный по сетевой политике WEB-listener, один vhost и один профиль в каждом vhost. `https` сохраняет сериализованный HTTPS transport и требует `max_http_handlers >= 2`. В `https-lanes` stream zero и каждый logical stream получают независимые uplink sequence, downlink cursor, retry и long poll; carrier требует `max_http_handlers >= 4` и публичного HTTP/2 на TLS-терминаторе. `websocket` переносит все logical streams через одно упорядоченное RFC 6455 connection, а `websocket-lanes` выделяет отдельное connection каждому ненулевому stream и изолирует сбои lane. Оба WebSocket carrier используют `GET /api/v1/ws` после создания HTTPS-сессии и требуют от TLS-терминатора сохранять HTTP/1.1 Upgrade headers.
|
||||
Для `enabled = true` нужен как минимум один доступный по сетевой политике WEB-listener, один vhost и один профиль в каждом vhost. `https` использует общую последовательность HTTPS uplink с согласуемым окном upload 1–4 и требует `max_http_handlers >= 2`. В `https-lanes` stream zero и каждый logical stream получают независимые uplink sequence, downlink cursor, retry и long poll; carrier требует `max_http_handlers >= 4` и публичного HTTP/2 на TLS-терминаторе. `websocket` переносит все logical streams через одно упорядоченное RFC 6455 connection, а `websocket-lanes` выделяет отдельное connection каждому ненулевому stream и изолирует сбои lane. Оба WebSocket carrier используют `GET /api/v1/ws` после создания HTTPS-сессии и требуют от TLS-терминатора сохранять HTTP/1.1 Upgrade headers.
|
||||
|
||||
Если `carriers` отсутствует или равен `false`, auto-negotiation и обучение выключены, а `carrier` задаёт единственный режим. Непустой массив `carriers` включает стартовый перебор в заданном порядке; `carrier` ровно один раз добавляется последним fallback-вариантом. Пустой массив, дубликаты и `true` запрещены. Клиент может перейти к следующему кандидату только до commit carrier; для смены carrier после commit нужна новая сессия. Native-клиент без метаданных, включая Telegram iOS, всегда использует настроенный фиксированный `carrier`, даже при включённом auto-negotiation. Текущий iOS поддерживает только `https`, поэтому такой deployment должен задавать `carrier = "https"`. Классификация User-Agent CFNetwork и Darwin не определяет поддержку carrier. Явные capabilities нативного iOS пересекаются с `{https}`; capabilities остальных явных клиентов применяются как переданы.
|
||||
|
||||
`http_connection_capacity_action` применяется только после того, как Telemt принял приватное WEB TCP connection и исчерпал `max_http_connections`. `drop` сохраняет немедленное закрытие. `respond` отправляет пустой повторяемый `503 Service Unavailable` с `Retry-After: 1`, `Cache-Control: no-store` и `Connection: close`. `wait` ожидает обычную capacity не более `http_overload_timeout_ms`, затем переходит к нормальной HTTP-обработке; по timeout отправляется тот же ограниченный `503`. Вне обычной capacity могут ожидать или отвечать не более `max_http_overload_connections` принятых sockets.
|
||||
`http_connection_capacity_action` применяется только после того, как Telemt принял приватное WEB TCP connection и исчерпал `max_http_connections`. `drop` сохраняет немедленное закрытие. `respond` отправляет пустой повторяемый `503 Service Unavailable` с `Retry-After: 1`, `X-Telemt-Retry-After-Ms: 250`, `Cache-Control: no-store` и `Connection: close`. `wait` ожидает обычную capacity не более `http_overload_timeout_ms`, затем переходит к нормальной HTTP-обработке; по timeout отправляется тот же ограниченный `503`. Вне обычной capacity могут ожидать или отвечать не более `max_http_overload_connections` принятых sockets.
|
||||
|
||||
`decoy_fasttrack_mode` требует перезапуска и управляет только capability work для `GET/HEAD` на настроенном base root. `off` сохраняет полный scan, `shadow` считает подходящие requests, но не пропускает scan, а `enforce` пропускает его только для `HEAD` или отсутствующего/неканонического параметра `bridge`. Канонический bridge-shaped `GET` всегда сканирует все профили выбранного vhost. Оптимизация не ограничивает враждебные канонические probes; `enforce` необходимо проверять на различимость timing за production TLS-терминатором.
|
||||
|
||||
@@ -2710,6 +2739,38 @@ WEB-режим переносит MTProxy-трафик Telegram Desktop внут
|
||||
| `new_streams_per_minute` | `u32` | `6000` | Устойчивая скорость создания logical streams. |
|
||||
| `new_streams_burst` | `u32` | `512` | Process-wide burst создания logical streams. |
|
||||
|
||||
# [web.retry_jitter]
|
||||
|
||||
| Ключ | Тип | По умолчанию | Описание |
|
||||
| --- | --- | --- | --- |
|
||||
| `enabled` | `bool` | `false` | Включает добавочный jitter повторов. |
|
||||
| `min_ms` | `u32` | `0` | Минимальная добавка в миллисекундах включительно. |
|
||||
| `max_ms` | `u32` | `250` | Максимальная добавка в миллисекундах включительно; не более `30000`. |
|
||||
| `distribution` | `string` | `"uniform"` | `uniform` или `triangular`. |
|
||||
| `peak_ms` | `Option<u32>` | `—` | Пик треугольного распределения; при отсутствии — середина диапазона. |
|
||||
|
||||
`[web.retry_jitter]` добавляет независимо выбранную задержку к каждому существующему HTTP-повтору бриджа: сетевым ошибкам и ответам 408/429/502/503/504. Менять приложения Telegram не требуется. Без секции или при `enabled = false` сохраняются подсказка Telemt на 250 мс и прежний backoff/jitter.
|
||||
|
||||
```toml
|
||||
[web.retry_jitter]
|
||||
enabled = true
|
||||
min_ms = 0
|
||||
max_ms = 250
|
||||
distribution = "uniform"
|
||||
# Only for distribution = "triangular":
|
||||
# peak_ms = 125
|
||||
```
|
||||
|
||||
Диапазон задаёт **добавку**, а не полную паузу: подсказка Telemt 250 мс с этим примером даёт 250–500 мс. Без положительной серверной подсказки база остаётся 250, 500, 1000, затем 2000 мс. Включённый jitter заменяет прежний jitter до 25%. Корректный стандартный `Retry-After` во включённом режиме не сокращается прежним пределом в 30 секунд. Если пауза не помещается в оставшийся бюджет операции, бюджет истекает без раннего повтора.
|
||||
|
||||
Значения по умолчанию: `enabled = false`, `min_ms = 0`, `max_ms = 250`, `distribution = "uniform"`, `peak_ms` отсутствует. Требуется `0 <= min_ms <= max_ms <= 30000`. `uniform` выбирает целые миллисекунды равномерно; `triangular` использует треугольную плотность с округлением до миллисекунд. Необязательный пик по умолчанию находится посередине и должен входить в диапазон. Явный пик для `uniform`, неизвестные ключи/распределения и неверные границы отклоняются даже при выключенной опции. Одинаковые границы дают постоянную добавку.
|
||||
|
||||
Политика фиксируется в каждой странице бриджа. Reload через конфиг/API влияет на новые страницы; активные сохраняют настройки при recovery. Recovery JSON и HTTP-заголовки совместимости не меняются. Используется `crypto.getRandomValues`, при недоступности — `Math.random` для совместимости. Успешный трафик не задерживается. Лимиты попыток, общий бюджет, отмена и повтор неизменных payload/sequence сохраняются; более длинные паузы могут уменьшить число попыток, помещающихся в startup/recovery-бюджет.
|
||||
|
||||
Это размывает фиксированные интервалы повторов, но не гарантирует защиту от DPI. Планирование браузера, сетевые очереди и другие временные характеристики протокола остаются наблюдаемыми. Существующие примеры временной шкалы описывают выключенную опцию. Для включённого режима добавляйте выбранную задержку к каждой паузе повтора, а не к первому соединению или каждому кадру данных.
|
||||
|
||||
Политика меняет только уже предусмотренные паузы перед повтором. Более строгие ограничения отдельных вызовов сохраняются: обычный poll `/down` и вызов `/up` после commit выполняют одну попытку; их replay при восстановлении допускает две. Опция не создаёт новых циклов повторов. Она не продлевает `web.timeouts.bridge_retry_secs` и сроки запуска или восстановления.
|
||||
|
||||
# [web.timeouts]
|
||||
|
||||
Если в строке не указано иное, таймауты задаются в секундах и должны входить в диапазон `1..=3600`. Настроенные серверные deadlines отдельных HTTP-фаз должны быть меньше `http_idle_secs`; защищённые фазы сохраняют собственные deadlines, поэтому idle-таймер не является общим deadline запроса. Client-side окно повторов bridge имеет отдельные границы.
|
||||
@@ -3563,6 +3624,7 @@ bootstrap переживает reload только при сохранении
|
||||
alice = 500
|
||||
```
|
||||
## user_max_tcp_conns_global_each
|
||||
- **API**: Поле доступно через `GET/PATCH /v1/access/policy`. Пропуск сохраняет значение; `null` восстанавливает значение типа по умолчанию. Публикация идёт через watcher; ответ разделяет снимки `desired` и `effective`.
|
||||
- **Ограничения / валидация**: `usize`. `0` - отключает лимит.
|
||||
- **Описание**: Глобальное максимальное количество одновременных TCP-соединений для каждого пользователя, применяется, когда у пользователя **нет** записи в `[access.user_max_tcp_conns]` (отсутствующее или равное `0` значения подпадают под это условие). Ограничения на пользователя, превышающие `0` в параметре `user_max_tcp_conns`, имеют приоритет.
|
||||
- **Пример**:
|
||||
@@ -3625,6 +3687,7 @@ bootstrap переживает reload только при сохранении
|
||||
alice = 16
|
||||
```
|
||||
## user_max_unique_ips_global_each
|
||||
- **API**: Поле доступно через `GET/PATCH /v1/access/policy`. Пропуск сохраняет значение; `null` восстанавливает значение типа по умолчанию. Публикация идёт через watcher; ответ разделяет снимки `desired` и `effective`.
|
||||
- **Ограничения / валидация**: `usize`. `0` - отключает лимит.
|
||||
- **Описание**: Глобальный лимит на количество уникальных IP-адресов, с которых выполняется подключение, для каждого пользователя, когда у пользователя нет индивидуального переопределения в `[access.user_max_unique_ips]`.
|
||||
- **Пример**:
|
||||
@@ -3634,6 +3697,7 @@ bootstrap переживает reload только при сохранении
|
||||
user_max_unique_ips_global_each = 8
|
||||
```
|
||||
## user_max_unique_ips_mode
|
||||
- **API**: Поле доступно через `GET/PATCH /v1/access/policy`. Пропуск сохраняет значение; `null` восстанавливает значение типа по умолчанию. Публикация идёт через watcher; ответ разделяет снимки `desired` и `effective`.
|
||||
- **Ограничения / валидация**: `"active_window"`, `"time_window"`, `"combined"`.
|
||||
- **Описание**: Режим учета лимита уникальных IP-адресов.
|
||||
- **Пример**:
|
||||
@@ -3643,6 +3707,7 @@ bootstrap переживает reload только при сохранении
|
||||
user_max_unique_ips_mode = "active_window"
|
||||
```
|
||||
## user_max_unique_ips_window_secs
|
||||
- **API**: Поле доступно через `GET/PATCH /v1/access/policy`. Пропуск сохраняет значение; `null` восстанавливает значение типа по умолчанию. Публикация идёт через watcher; ответ разделяет снимки `desired` и `effective`.
|
||||
- **Ограничения / валидация**: Должно быть `> 0`.
|
||||
- **Описание**: Размер временного окна (в секундах), используемого режимами учёта уникальных IP, которые работают с ограничением по времени (значения `"time_window"` и `"combined"`).
|
||||
- **Пример**:
|
||||
@@ -3652,6 +3717,7 @@ bootstrap переживает reload только при сохранении
|
||||
user_max_unique_ips_window_secs = 30
|
||||
```
|
||||
## user_source_deny
|
||||
- **API**: Список доступен как `source_deny` в GET/create/PATCH пользователя. Пропуск сохраняет список, массив заменяет его целиком, а `null` удаляет запись из конфигурации. Строгая валидация принимает эту таблицу. `source_deny_status.runtime_reload_required` сравнивает сохранённые и опубликованные правила; для применения нужен `POST /v1/system/reload`. Watcher эти правила не обновляет; сохранение не отменяет сессии. Удаление пользователя сохраняет правило, которое наследуется при повторном создании имени, если явно не передать `source_deny=null`.
|
||||
- **Ограничения / валидация**: Таблица `username -> IpNetwork[]`. Каждая сеть должна разбираться как CIDR, например `203.0.113.0/24` или `2001:db8::/32`.
|
||||
- **Описание**: Deny-list исходных IP/CIDR для конкретного пользователя, применяемый **после успешной аутентификации** в TLS- и MTProto-handshake путях. Совпавший source IP отклоняется тем же fail-closed путём, что и невалидная аутентификация.
|
||||
- **Пример**:
|
||||
@@ -3704,6 +3770,7 @@ bootstrap переживает reload только при сохранении
|
||||
alice = { up_bps = 1048576, down_bps = 2097152 }
|
||||
```
|
||||
## cidr_rate_limits
|
||||
- **API**: Поле доступно через `GET/PATCH /v1/access/policy`. Пропуск сохраняет значение; `null` для скаляра восстанавливает значение типа по умолчанию. Для `cidr_rate_limits` объект объединяется по ключам, запись со значением null удаляет правило, а `null` вместо всего объекта очищает правила. Объект скорости заменяет оба направления; единица — бит в секунду. Публикация идёт через watcher; ответ разделяет снимки `desired` и `effective`.
|
||||
- **Ограничения / валидация**: Таблица `CIDR или auto-template -> { up_bps, down_bps }`. Каждое направление должно быть в диапазоне `0..=100000000000`; `0` означает отсутствие лимита в этом направлении, при этом хотя бы одно направление должно быть ненулевым. Explicit CIDR-ключи должны корректно разбираться как `IpNetwork`; auto-template ключи должны иметь вид `*4/N` (`N=0..32`), `*6/N` (`N=0..128`) или `*/N` (`N=0..32`). Дублирующиеся нормализованные auto-template отклоняются.
|
||||
- **Описание**: Лимиты скорости для подсетей источников, применяются поверх пользовательских ограничений. Explicit CIDR-правила используют longest-prefix-wins и имеют приоритет над auto-template. Auto-template создают bucket’ы лениво по matched source subnet: `*4/N` для IPv4, `*6/N` для IPv6, а `*/N` является dual-stack shorthand, где IPv4 использует `/N`, а IPv6 — `/(N * 4)`.
|
||||
- **Example**:
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
# Ping in der Proxyliste: RPC Ping/Pong und WEB-Latenz
|
||||
|
||||
[English](PROXY_PING.en.md) | [Русский](PROXY_PING.ru.md) | [Deutsch](PROXY_PING.de.md)
|
||||
|
||||
Die beobachteten **1000–1500 ms für WEB gegenüber 50–150 ms für Classic/DD/EE** können auf unterschiedlichen Messgrenzen beruhen. Bei der WEB-Prüfung unter Android ist der lokale Socket bereits bereit, bevor der entfernte WEB-Stream zwingend bereit ist. Der verbleibende Streamaufbau und die Übertragung können deshalb in den angezeigten Wert eingehen. Der Code schreibt keinen festen Zuschlag von einer Sekunde für jeden erfolgreichen WEB-Ping vor.
|
||||
|
||||
Diese Zahlen stammen aus Betreiberbeobachtungen und wurden für dieses Dokument nicht reproduziert. Die Quellcodeanalyse belegt Mechanismen, aber nicht die Ursache einer Verzögerung in einer bestimmten Installation.
|
||||
|
||||
## Clients und Messungen
|
||||
|
||||
Geprüft am **2026-10-31** anhand von DrKLO Android `3de37c8cfb039452be7398909461da6288babf15` und Telegram iOS `279f89e4d4f63f17227bf877dc3d8990f22ecd58`. Installierte Versionen und Forks können abweichen.
|
||||
|
||||
| Messung | Erfasster Bereich | Verhalten bei WEB |
|
||||
| --- | --- | --- |
|
||||
| Ping in der Android-Proxyliste | Verschlüsseltes MTProto `TL_ping` / `TL_pong` über den geprüften Proxy | Separater WEB-Testtransport, anschließend native Prüfung über einen lokalen Socket. |
|
||||
| Ping in der iOS-Proxyliste | Erreichbarkeitsprüfung mit `req_pq` / `resPQ`; Messbeginn bei `connectionOpened` | `.web`-Einträge sind von der Ping-Prüfung ausgeschlossen; ein inaktiver WEB-Eintrag erscheint als nicht getestet. |
|
||||
| ICMP-Ping | IP-Echo zum gewählten Host unter den jeweiligen ICMP-Routingregeln | Misst weder die Anwendungsweiterleitung noch das Telegram-DC. |
|
||||
| WEB-Transport `FRAME_PING` / `FRAME_PONG` oder WebSocket-Keepalive | Erreichbarkeit des Transports bzw. der Sitzung | Nicht das in Android angezeigte MTProto-Ergebnis. |
|
||||
| Telemt ME RPC Ping/Pong | Ein Writer-Pfad von Telemt zum ME einschließlich lokaler Warteschlange und Flush-Planung | Ohne Client, WebView und öffentliches TLS-Frontend. |
|
||||
|
||||
Quellen: [Android-Einstieg][android-entry], [native Anfragen][android-native], [iOS-Filter][ios-filter], [iOS-Prüfung][ios-probe], [iOS-Oberfläche][ios-ui]. Die Android-Formel für WEB-Ping lässt sich somit nicht auf den WEB-Eintrag im geprüften iOS übertragen.
|
||||
|
||||
Android zeigt das letzte Prüfergebnis ohne Median oder EMA an und überspringt eine erneute Prüfung, wenn die vorherige weniger als zwei Minuten zurückliegt. Auch ein verbundener Proxy kann diesen gespeicherten Wert anzeigen: Er ist keine laufende RTT-Messung der aktiven Sitzung. Die WEB-Prüfung erstellt einen eigenen Transport, statt den aktiven Anwendungstransport direkt wiederzuverwenden. Siehe [Aktualisierung der Proxyliste][android-ui] und [WEB-Transport][android-transport].
|
||||
|
||||
## Beginn und Ende der Android-Messung
|
||||
|
||||
Bei Classic/DD/EE erfolgt der native Bereitschafts-Callback nach dem entfernten TCP-Verbindungsaufbau und der erforderlichen Einrichtung des Proxytransports, einschließlich EE FakeTLS. Die Anfrageverarbeitung aktualisiert den Zeitstempel vor dem Senden bzw. erneuten Senden der Prüfung. Die übliche erfolgreiche Messung schließt diesen anfänglichen Transportaufbau daher aus, erfasst aber die anschließende Weiterleitung und den Rückweg. Siehe [Socket-Bereitschaft][android-socket] und [Anfrageverarbeitung][android-native].
|
||||
|
||||
Bei WEB liegen der Bridge-Start, das anfängliche Laden über HTTPS, HELLO/WELCOME und weitere **500 ms** Wartezeit vor `native_checkProxy`; diese Wartezeit wird nicht zum angezeigten Ping addiert. WELCOME bestätigt eine WEB-Sitzung, keinen bereiten Stream zum Telegram-DC. Anschließend verbindet sich die native Prüfung mit `127.0.0.1`. Dessen Bereitschaft wartet nicht auf den Abschluss des entfernten OPEN. Java-Accept/OPEN und die Aktualisierung des nativen Zeitstempels können in unterschiedlicher Reihenfolge erfolgen. Nur die innerhalb des Messintervalls noch ausstehende Arbeit trägt zum Ergebnis bei. Siehe [Prüfablauf][android-tester], [lokaler Socket und WELCOME][android-transport], [serverseitige Sitzungserstellung][session] und [Stream-Backend][backend].
|
||||
|
||||
Die Diagramme zeigen den üblichen erfolgreichen Ablauf, garantieren jedoch keine threadübergreifende Ereignisreihenfolge:
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as Android native checker
|
||||
participant P as Classic/DD/EE proxy
|
||||
participant D as Telegram DC
|
||||
C->>P: DNS / TCP / proxy transport setup
|
||||
Note over C,P: Remote transport ready, measurement timestamp refreshed
|
||||
C->>P: Encrypted TL_ping
|
||||
P->>D: Relay
|
||||
D->>P: TL_pong
|
||||
P->>C: Relay
|
||||
Note over C: Display elapsed time from latest request timestamp
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as Android native checker
|
||||
participant B as Local socket / Java / WebView
|
||||
participant T as TLS frontend / Telemt
|
||||
participant D as Telegram DC
|
||||
B->>T: Bridge load, HELLO / session creation
|
||||
T->>B: WELCOME
|
||||
Note over B: Wait 500 ms before native_checkProxy
|
||||
C->>B: Connect to 127.0.0.1
|
||||
Note over C,B: Local socket ready, measurement timestamp refreshed
|
||||
Note over B,T: OPEN may race with the native timestamp update
|
||||
C->>B: MTProxy header and encrypted TL_ping
|
||||
B->>T: OPEN / DATA over selected carrier
|
||||
T->>D: Stream setup and relay via Direct / ME
|
||||
D->>T: TL_pong
|
||||
T->>B: Downlink DATA
|
||||
B->>C: Local socket delivery
|
||||
Note over C: Display elapsed time from latest request timestamp
|
||||
```
|
||||
|
||||
`TL_pong` beendet die Messung relativ zum letzten Anfragezeitstempel. Erzwungene Verarbeitung oder erneutes Senden können diesen zurücksetzen. Der angezeigte Wert entspricht daher nicht zwingend der gesamten Dauer eines fehlgeschlagenen oder wiederholten Versuchs. Die Prüfung verwendet einen [vorhandenen DC-Autorisierungsschlüssel][android-key]; ein vollständiger Austausch zur Erstellung eines neuen MTProto-Schlüssels gehört nicht obligatorisch zu jeder Prüfung.
|
||||
|
||||
## Einfluss von TLS
|
||||
|
||||
Die öffentliche TLS-Verbindung endet bei NGINX, HAProxy oder Caddy. Telemt empfängt unverschlüsseltes HTTP/1.1 am privaten Listener. Öffentliches HTTP/2 und internes HTTP/1.1 sind getrennte Verbindungen; ihre Protokollversionen müssen nicht übereinstimmen. EE FakeTLS ist ein MTProxy-Tarntransport, nicht die HTTPS-Verbindung des Browsers mit Zertifikatsprüfung. WEB transportiert plain/DD-MTProxy; EE ist kein WEB-Secret-Format. Siehe [WEB-Betriebsanleitung](WEB_PROXY.de.md).
|
||||
|
||||
Bei einer neuen Verbindung ohne Paketverlust benötigt der übliche TCP-Handshake ungefähr einen RTT zwischen Client und Frontend. Ein vollständiger TLS-1.3-Handshake fügt normalerweise einen RTT hinzu, ein vollständiger TLS-1.2-Handshake zwei. Das sind Schätzungen der Protokollrunden ohne DNS, Verarbeitung, Zertifikatsprüfung, Scheduling und erneute Übertragungen, kein gemessenes WEB-Latenzbudget. Sitzungswiederaufnahme kann den Ablauf verändern. Siehe [TLS 1.3][tls13] und [TLS 1.2][tls12].
|
||||
|
||||
Das anfängliche TLS für die Bridge liegt normalerweise vor der Android-Messung. Zusätzliche HTTP-Verbindungen oder ein WebSocket-Upgrade können noch innerhalb des Intervalls stattfinden; Verbindungswiederverwendung muss anhand eines Traces belegt werden. Persistente HTTPS-Verbindungen und bestehende WebSockets führen nicht für jeden Ping einen neuen TLS-Handshake aus. `cache: 'no-store'` steuert Caching, nicht die Wiederverwendung von TCP/TLS. Weder das Abschalten der Zertifikatsprüfung noch TLS 0-RTT ist zur Erklärung oder Diagnose erforderlich. Siehe [persistente HTTP-Verbindungen][http1] und [Bridge-Anfragen][request].
|
||||
|
||||
## Zusätzliche Arbeit bei WEB gegenüber nativem MTProxy
|
||||
|
||||
Die Darstellung trennt Arbeit vor dem Android-Timer von Arbeit, die in den angezeigten Wert eingehen kann. Als Basis dient Classic/DD über TCP. Bei EE gehört FakeTLS zum Aufbau des nativen Transports. Die Größe der Kästen und die Länge der Pfeile stellen keine Zeitdauer dar.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph N["Natives MTProxy: Classic/DD"]
|
||||
direction TB
|
||||
N0["Vor der Messung<br/>DNS + TCP + nativer Transportaufbau"] --> N1["Entfernter Transport bereit<br/>Anfragezeitstempel aktualisiert"]
|
||||
N1 --> N2["MTProxy-Anfrage und Antwort<br/>Ausstehender Relay-Aufbau, Netzwerk, Warteschlangen, Telegram-DC"] --> N3["TL_pong empfangen<br/>Angezeigte Messung beendet"]
|
||||
end
|
||||
subgraph W["WEB: MTProxy in HTTPS oder WebSocket"]
|
||||
direction TB
|
||||
W0["Vor der Messung<br/>DNS + TCP + echtes TLS<br/>HTTP-Bridge + HELLO/WELCOME + 500 ms"] --> W1["Lokaler Socket bereit<br/>Anfragezeitstempel aktualisiert"]
|
||||
W1 --> W2["Zusätzliche Client-Arbeit<br/>Java / WebView / JavaScript-Warteschlangen<br/>Entferntes OPEN eventuell noch ausstehend"] --> W3["Uplink-Verarbeitung<br/>HTTP-Upload oder WebSocket-Frame<br/>Frontend-Verarbeitung und mögliche Pufferung"]
|
||||
W3 --> W4["Innere MTProxy-Anfrage und Antwort<br/>Ausstehender Relay-Aufbau, Netzwerk, Warteschlangen, Telegram-DC"] --> W5["Downlink-Verarbeitung<br/>HTTP-Poll oder WebSocket-Frame<br/>ACK/Commit-Freigabe und native Zustellwarteschlangen"]
|
||||
W5 --> W6["TL_pong empfangen<br/>Angezeigte Messung beendet"]
|
||||
X["Nur wenn eine weitere Verbindung nötig ist<br/>TCP + TLS, eventuell WebSocket-Upgrade<br/>Kein Handshake pro Ping bei Wiederverwendung"] -.-> W3
|
||||
X -.-> W5
|
||||
R["Nur bei Fehlern oder Überlastung<br/>Retries und Backoff<br/>Telemt-Basis 250 ms<br/>Plus optionaler Jitter"] -.-> W3
|
||||
R -.-> W5
|
||||
end
|
||||
classDef preparation fill:#eeeeee,stroke:#666666,color:#111111
|
||||
classDef boundary fill:#dbeafe,stroke:#2563eb,color:#111111
|
||||
classDef shared fill:#dcfce7,stroke:#15803d,color:#111111
|
||||
classDef extra fill:#ffedd5,stroke:#c2410c,color:#111111
|
||||
class N0,W0 preparation
|
||||
class N1,N3,W1,W6 boundary
|
||||
class N2,W4 shared
|
||||
class W2,W3,W5,X,R extra
|
||||
```
|
||||
|
||||
**Grau:** Arbeit vor der angezeigten Messung. **Blau:** Timer-Grenzen. **Grün:** MTProxy-Relay/DC-Arbeit in beiden Pfaden, deren tatsächliche Dauer abweichen kann. **Orange:** WEB-Transport- und Client-Arbeit innerhalb der Messung. **Gestrichelte Pfeile:** bedingter Verbindungsaufbau oder Retries, keine obligatorischen Phasen.
|
||||
|
||||
Bei Wiederverwendung des Carriers entfällt der bedingte TCP/TLS/Upgrade-Aufwand. Framing, HTTP- oder WebSocket-Verarbeitung und Client-Warteschlangen bleiben bestehen. HTTP kann Up- und Downlink überlappen, sodass nicht jede Anfrage zwingend einen ganzen RTT hinzufügt. Polling wird bei verfügbaren Daten geweckt, und Frontend-Pufferung hängt von der Installation ab. Paketverlust, Netzwerküberlastung und Upstream-Aufbau können auch natives MTProxy verzögern.
|
||||
|
||||
Die sichtbare Differenz kann somit verbleibenden WEB-Streamaufbau, zusätzliche Verbindungen, Transportverarbeitung und Scheduling sowie belegte Retries enthalten. Sie ist weder ein fester TLS-Zuschlag noch die arithmetische Summe aller Kästen. Der erste echte TLS-Handshake steht bewusst vor dem Android-Timer: Er beeinflusst die Gesamtdauer der Prüfung, normalerweise aber nicht den angezeigten Messwert. Da die Prüfung einen separaten Transport verwendet, garantiert eine aktive App-Verbindung auch keine warme Prüfung in der Proxyliste.
|
||||
|
||||
### Konfigurierbarer Jitter für HTTP-Wiederholungen
|
||||
|
||||
`[web.retry_jitter]` ergänzt jeden bestehenden HTTP-Retry der Bridge um eine unabhängig gewählte Verzögerung: Netzwerkfehler und Antworten mit 408/429/502/503/504. Telegram-Anwendungen müssen nicht geändert werden. Ohne diesen Abschnitt oder mit `enabled = false` bleiben der 250-ms-Hinweis von Telemt und das bisherige Backoff/Jitter-Verhalten erhalten.
|
||||
|
||||
```toml
|
||||
[web.retry_jitter]
|
||||
enabled = true
|
||||
min_ms = 0
|
||||
max_ms = 250
|
||||
distribution = "uniform"
|
||||
# Only for distribution = "triangular":
|
||||
# peak_ms = 125
|
||||
```
|
||||
|
||||
Der Bereich beschreibt einen **Zuschlag**, nicht die gesamte Pause: Zusammen mit dem Telemt-Hinweis von 250 ms ergibt dieses Beispiel 250–500 ms. Ohne positiven Serverhinweis bleibt die Basis bei 250, 500, 1000, dann 2000 ms. Aktivierter Jitter ersetzt den bisherigen Jitter von bis zu 25%. Ein gültiger standardmäßiger `Retry-After` wird im aktivierten Modus nicht auf die bisherige Grenze von 30 Sekunden verkürzt. Übersteigt die Pause das verbleibende Operationsbudget, läuft das Budget ohne vorzeitigen Retry ab.
|
||||
|
||||
Standardwerte: `enabled = false`, `min_ms = 0`, `max_ms = 250`, `distribution = "uniform"`, ohne `peak_ms`. Es gilt `0 <= min_ms <= max_ms <= 30000`. `uniform` verteilt ganze Millisekunden gleichmäßig; `triangular` verwendet eine Dreiecksverteilung mit Rundung auf Millisekunden. Der optionale Gipfel liegt standardmäßig in der Mitte und muss innerhalb des Intervalls liegen. Ein expliziter Gipfel bei `uniform`, unbekannte Schlüssel/Verteilungen und ungültige Grenzen werden auch im deaktivierten Zustand abgelehnt. Gleiche Grenzen ergeben einen konstanten Zuschlag.
|
||||
|
||||
Die Richtlinie wird pro Bridge-Seite festgeschrieben. Konfigurations-/API-Reload wirkt auf neu geladene Seiten; bestehende Seiten behalten ihre Einstellungen bei Recovery. Recovery-JSON und HTTP-Kompatibilitätsheader bleiben unverändert. Die Auswahl bevorzugt `crypto.getRandomValues`, mit `Math.random` als Kompatibilitätsfallback. Erfolgreicher Datenverkehr wird nicht verzögert. Versuchslimits, absolute Budgets, Abbruch und unveränderte Payload-/Sequence-Wiederholung bleiben erhalten; längere Pausen können die Anzahl der Versuche innerhalb eines Startup-/Recovery-Budgets reduzieren.
|
||||
|
||||
Dies streut feste Retry-Intervalle, garantiert aber keinen Schutz vor DPI. Browser-Scheduling, Netzwerkwarteschlangen und andere Protokollzeiten bleiben beobachtbar. Bestehende Zeitleisten zeigen den deaktivierten Standardmodus. Bei aktiviertem Modus wird zu jeder Retry-Pause eine gezogene Verzögerung addiert, nicht zum ersten Verbindungsaufbau oder zu jedem Datenframe.
|
||||
|
||||
Die Richtlinie ändert nur bereits vorhandene Retry-Pausen. Strengere Limits einzelner Aufrufe bleiben erhalten: Reguläre `/down`-Polls und `/up`-Aufrufe nach dem Commit führen einen Versuch aus; ihr Recovery-Replay erlaubt zwei. Die Option erzeugt keine neuen Retry-Schleifen. Sie verlängert weder `web.timeouts.bridge_retry_secs` noch Start- oder Recovery-Deadlines.
|
||||
|
||||
## Beispielhafte Zeitleiste mit ungefähren Dauern
|
||||
|
||||
**Ein Erklärungsmodell, kein Benchmark und kein erwarteter Latenzbereich.** Die Zahlen sollen das Zusammenspiel der Phasen zeigen. Sie rekonstruieren nicht die beobachteten 1000–1500 ms. Annahmen: DNS ist bereits zwischengespeichert, der RTT zwischen Client und Frontend beträgt 40 ms, die TCP-Verbindung ist neu, bei Bedarf erfolgt ein vollständiger TLS-1.3-Handshake, ein DC-Autorisierungsschlüssel ist vorhanden, und es gibt weder Paketverlust noch ein Zurücksetzen des nativen Anfragezeitstempels. Als Basis dient Classic/DD. Bei EE kommt der eigene FakeTLS-Aufbau vor dem nativen Timer hinzu.
|
||||
|
||||
In diesem Beispiel benötigt natives MTProxy 40 ms Vorbereitung für TCP. Die WEB-Vorbereitung dauert 750 ms: 50 ms Client-/Bridge-Start + 40 ms TCP + 40 ms TLS + 120 ms HTTP-Austausch für Bridge und Sitzung + 500 ms Wartezeit des Android-Checkers. Hier werden aufeinanderfolgende Dauern angenommen; reale Phasen können überlappen. Das anfängliche TLS und die 500 ms Wartezeit liegen außerhalb des angezeigten Pings.
|
||||
|
||||
Die Darstellung beginnt beim **letzten Anfragezeitstempel** der jeweiligen Prüfung, nicht beim App-Start oder ersten Verbindungsversuch. Die horizontale Achse zeigt Sekunden mit Millisekundengenauigkeit (0.200 = 200 ms). Die Balkenbreite ist proportional zur Dauer. Jeder Abschnitt ist ein separates Szenario; seine Phasen folgen aufeinander und laufen nicht parallel. Die anfängliche Vorbereitung liegt außerhalb der Darstellung.
|
||||
|
||||
```mermaid
|
||||
%%{init: {"theme": "neutral", "gantt": {"leftPadding": 200, "rightPadding": 100, "barHeight": 24, "barGap": 8, "fontSize": 14, "sectionFontSize": 14}}}%%
|
||||
gantt
|
||||
dateFormat x
|
||||
axisFormat %S.%L
|
||||
tickInterval 100millisecond
|
||||
todayMarker off
|
||||
title Angezeigter Ping - Jitter aus
|
||||
accTitle: Angezeigter Ping - Jitter aus
|
||||
accDescr: Sekunden seit Anfragezeitstempel, Beschriftungen in Millisekunden
|
||||
section Classic/DD - 100 ms
|
||||
R 100 ms :n_r, 0, 100ms
|
||||
section WEB ohne Fehler - 200 ms
|
||||
U 40 ms :w_u, 0, 40ms
|
||||
R 100 ms :w_r, after w_u, 100ms
|
||||
D 60 ms :w_d, after w_r, 60ms
|
||||
section WEB mit Retry - 490 ms
|
||||
F 40 ms :crit, f_u, 0, 40ms
|
||||
Warten 250 ms :crit, retry_wait, after f_u, 250ms
|
||||
U 40 ms :retry_u, after retry_wait, 40ms
|
||||
R 100 ms :retry_r, after retry_u, 100ms
|
||||
D 60 ms :retry_d, after retry_r, 60ms
|
||||
```
|
||||
|
||||
Dauer der einzelnen Phasen: `R` = 100 ms grundlegende MTProxy-Relay-/Netzwerk-/DC-Arbeit für Anfrage und Antwort. `U` = 40 ms zusätzliche WEB-Uplink-/OPEN-/Client-Arbeit. `D` = 60 ms zusätzliche WEB-Downlink-/Zustellarbeit. `F` = 40 ms für einen fehlgeschlagenen Upload-Versuch. `Warten` = 250 ms Wartezeit gemäß `X-Telemt-Retry-After-Ms: 250`. `U` und `D` sind beispielhafte Zusatzkosten gegenüber `R`, keine erneute Anrechnung des gesamten Netzwerk-RTT. Die ACK/Commit-Freigabe wird nur berücksichtigt, soweit sie die Zustellung tatsächlich verzögert.
|
||||
|
||||
| Szenario | Vor dem Ping-Timer | Angezeigter Ping | Gesamtdauer der Prüfung im Modell |
|
||||
| --- | --- | --- | --- |
|
||||
| Classic/DD | 40 ms | 100 ms | 140 ms |
|
||||
| WEB ohne Fehler | 750 ms | 40 + 100 + 60 = 200 ms | 950 ms |
|
||||
| WEB mit einem fehlgeschlagenen Upload und einer Retry-Pause | 750 ms | 40 + 250 + 40 + 100 + 60 = 490 ms | 1240 ms |
|
||||
| WEB, gleicher Retry mit uniformem Jitter 0–250 ms | 750 ms | 490–740 ms | 1240–1490 ms |
|
||||
|
||||
Eine weitere TCP- und TLS-1.3-Verbindung **innerhalb** der Messung könnte hier bei vollständig sequenziellem Ablauf ungefähr 80 ms hinzufügen: Aus 200 ms würden 280 ms. Bei Verbindungswiederverwendung entfällt dieser zusätzliche Handshake-Aufwand. Ein anfänglicher vollständiger TLS-1.2- statt TLS-1.3-Handshake verlängert unter diesen Annahmen die Vorbereitung um etwa 40 ms, nicht den angezeigten Ping. Die Beispiele lassen TLS-Verarbeitung, Sitzungswiederaufnahme und Paketverlust unberücksichtigt.
|
||||
|
||||
Die Zeile mit 490 ms und das Diagramm zeigen einen Retry bei deaktiviertem Jitter. Die zusätzliche Tabellenzeile wendet `enabled = true`, `min_ms = 0`, `max_ms = 250`, `distribution = "uniform"` auf denselben Retry an; ihr Bereich stammt aus dem Modell, nicht aus Messungen. Eine frühere JavaScript-Bridge ohne Millisekundenerweiterung oder ein Vermittler, der diesen Hinweis bei deaktiviertem Jitter entfernt, behält die standardmäßige Sekundenpause bei: Der angezeigte Ping beträgt im selben Modell dann 1240 ms. Keines der Szenarien bestimmt die Ursache der ursprünglichen Beobachtung. Ohne belegte Retries andere Verzögerungen wie Warteschlangen, Frontend-Pufferung, Verbindungsaufbau oder Upstream-Arbeit untersuchen. Timeouts dürfen nicht als Wartepausen eingesetzt und überlappende Phasen nicht ungeprüft in dieses sequenzielle Modell übertragen werden.
|
||||
|
||||
## HTTP, WebSocket und weitere Verzögerungen
|
||||
|
||||
Überlastungsantworten von Telemt enthalten `Retry-After: 1` und `X-Telemt-Retry-After-Ms: 250`. Nur Status `503` mit diesem exakten Header-Paar legt in der generierten Bridge eine **Basispause von 250 ms** fest. Bei `web.retry_jitter.enabled = false` beträgt die Pause 250 ms; bei aktiviertem Jitter kommt der konfigurierte zufällige Zuschlag hinzu. Andere Antworten verwenden die unten beschriebene Standardbehandlung von `Retry-After` oder den Backoff ohne Serverhinweis. Frühere JavaScript-Bridge-Seiten ohne Unterstützung des Millisekundenhinweises verwenden bis zum Laden einer neuen Seite die Sekundenpause; ein Update der Telegram-App ist dafür nicht erforderlich. Versuchslimits, absolute Budgets, Abbruchverhalten und Zulassungsgrenzen bleiben unverändert.
|
||||
|
||||
| Faktor | Auswirkung und Beleg |
|
||||
| --- | --- |
|
||||
| HTTP-Uplink | Die generierte Bridge bietet `X-Telemt-Up-Window: 4` an; der Server akzeptiert 1–4, ohne Aushandlung gilt 1. Fenster 1 wartet vor dem nächsten Upload auf ein ACK; Fenster 4 erlaubt begrenzte Parallelität. Nicht jeder HTTP-Pfad arbeitet nach Stop-and-Wait. Siehe [Aushandlung][runtime] und [Sitzungshandler][session]. |
|
||||
| Erster Downlink | `/down` kann gleichzeitig mit `/up` starten; es gibt keinen obligatorischen zusätzlichen sequenziellen ACK-RTT. Die erste Zustellung an den nativen Client wartet auf das erste gültige Upload-ACK/Commit. Frames werden schrittweise zugestellt. Siehe [Conveyor][conveyor] und [Downlink][downlink]. |
|
||||
| Long Polling | `long_poll_secs=25` begrenzt das Warten ohne Daten. Verfügbare Daten wecken den Poll sofort. Lücken zwischen Polls oder belegte Browser-Verbindungsslots können die Zustellung dennoch verzögern. Siehe [serverseitiges Polling][poll]. |
|
||||
| Gemeinsame Transportressourcen | `https` teilt eine Upload-Warteschlange; `https-lanes` trennt logische Lanes. WebSocket überträgt nach dem Upgrade Frames ohne POST pro Frame; `websocket-lanes` trennt Sockets. Netzwerk, Flow Control und WebView-Ressourcen bleiben gemeinsam genutzt. HTTP/2 multiplexiert Streams, beseitigt aber nicht alle Verzögerungen durch Überlastung und Flow Control. Siehe [HTTP/2][http2] und [Transportanleitung](WEB_PROXY.de.md). |
|
||||
| Frontend-Pufferung | Pufferung von Anfragen/Antworten oder fehlende Streaming-/Upgrade-Unterstützung kann kleine Nachrichten verzögern. Mit dem bestehenden NGINX-Beispiel vergleichen; Routing, Authentifizierung und Limits beibehalten. |
|
||||
| Client-Scheduling | Java-Accept/Read-Threads, UI-Dispatch, WebView/JavaScript und die Rückgabe an nativen Code erzeugen Warteschlangen. CPU-Last, mobiles Energiesparen und Netzwechsel können dies verstärken. |
|
||||
| Weiterleitung und Netzwerk | Verbleibende Stream-Zulassung, innerer MTProxy-Handshake, Direct-Verbindungsaufbau oder ME-Registrierung, Telegram-Antwort, Paketverluste/Wiederholungen und Warteschlangen können beitragen. Eine bereite WEB-Sitzung belegt keinen bereiten Upstream. |
|
||||
| Fehler und Wiederholungen | Wiederholbare Statuscodes sind 408/429/502/503/504. Bei deaktiviertem Jitter ergibt der exakte Telemt-Hinweis eine Pause von 250 ms; ohne positiven Serverhinweis beginnt der Backoff bei 250 ms und verdoppelt sich bis zu einer Basis von 2000 ms zuzüglich des bisherigen Jitters unter 25%. Bei aktiviertem Jitter ist die Pause der positive Serverhinweis oder diese Basis **plus** der konfigurierte Zufallswert, der den bisherigen Jitter ersetzt. Budgets und aufrufspezifische Versuchslimits gelten weiterhin. Die Richtlinie der geladenen Bridge und tatsächliche Retry-Zeitpunkte festhalten. Siehe [Antworten][response] und [Retry-Logik][request]. |
|
||||
|
||||
Fristen sind keine obligatorischen Pausen. Die Standardwerte von 10 s für Bridge-Anfragen, 90 s Retry-Budget, 30 s bis zum ersten Stream-Byte und 10 s für den Stream-Handshake dürfen nicht zum normalen Ping addiert werden. `carrier_probe_coalesce_ms=0` deaktiviert diese optionale Verzögerung zur Zusammenfassung von Probes. Carrier-Fallback-Fristen betreffen fehlgeschlagene Versuche, nicht jeden erfolgreichen Austausch. Siehe [Standardwerte](../../src/config/types/web/defaults.rs).
|
||||
|
||||
Vereinfacht umfasst eine WEB-Messung **verbleibenden Aufbau + Transport-/Netzwerkübertragung + Warteschlangen + Telegram-Antwort + Retry-Pausen innerhalb des Timers**. Die Phasen überlappen; alle Timeouts zu addieren oder jedem HTTP-Endpunkt einen eigenen RTT zuzuordnen wäre falsch. Bereite Carrier können Aufbaukosten reduzieren, die Android-Proxyprüfung verwendet jedoch weiterhin einen separaten Transport. WebSocket ist nicht grundsätzlich schneller; nur vom tatsächlichen Client unterstützte Carrier verwenden. Die aktuelle iOS-Kompatibilitätskonfiguration nutzt `https`.
|
||||
|
||||
## Diagnose unter Beibehaltung der Schutzmechanismen
|
||||
|
||||
1. Client/Build, Android-WebView-Version, die `web.retry_jitter`-Richtlinie der geladenen Bridge, Carrier, öffentlichen Endpunkt, IP-Familie, Netzwerk, Direct/ME-Route, DC und Last erfassen. Unter gleichen Bedingungen vergleichen. Den zwei Minuten lang gespeicherten Android-Wert beachten: Wiederholtes Ablesen liefert keine neuen Messungen.
|
||||
2. Drei Experimente unterscheiden: neue Prüfung in der Proxyliste; neuer logischer Stream auf einem bereiten Carrier; Anwendungs-RPC in einer bestehenden MTProto-Sitzung. Die letzten beiden benötigen geeignete Client-Instrumentierung und werden nicht automatisch von der Proxyliste bereitgestellt. Einzelwerte und Verteilungen erfassen, statt einen kalten mit einem warmen Einzelwert zu vergleichen.
|
||||
3. Das authentifizierte `GET /web-status` und vorhandene `[web.debug]`-Einstellungen mit `capture_timings=true`, `capture_frames=true`, `body_capture="metadata"` verwenden. Begrenzte Erfassung gemäß [WEB-Diagnoseanleitung](WEB_PROXY.de.md) aktivieren und danach den vorherigen Zustand wiederherstellen. Payloads, Capabilities und Secrets sind hierfür unnötig.
|
||||
4. Sitzungserstellung, Carrier-Auswahl/Commit/Fehler, `stream_admitted`, `stream_first_byte`, `handshake_succeeded`, OPEN/DATA, HTTP-Statuscodes und Retries korrelieren. `relay_started` liegt vor der Upstream-Arbeit und ist kein DC-Bereitschaftszeitpunkt. `GET /v1/runtime/web/status` und `GET /v1/runtime/web/sessions` liefern Kapazitäts- und Warteschlangenkontext, keinen Ende-zu-Ende-RTT.
|
||||
5. `request_body_us`, `response_ready_us` und `response_body_us` sind Zeitabstände seit Eintritt in den Service. Sie sind weder unabhängige, zu addierende Dauern noch Zeitpunkte eines Netzwerk-Flushs oder TCP-ACKs der Gegenstelle. Nur vorhandene und sinnvoll vergleichbare Werte gegenüberstellen. Siehe [Timing-Definitionen][timings].
|
||||
6. Verbindungs-/TLS-/Anfragezeiten des Frontends und Client-Zeitstempel ergänzen, um Verzögerungen außerhalb von Telemt zu lokalisieren. Wiederverwendung von Verbindungen, ausgehandelte HTTP-Version, Pufferung und Upgrade prüfen. Sideband-Ereignisse zum Bridge-Start/HELLO ergeben keine vollständige Client-Zeitleiste. Für Vergleiche zwischen Hosts Uhren synchronisieren oder lokale Dauern verwenden.
|
||||
7. Bei ME den vorhandenen Trace `ME RTT sample` (`rtt_ms`, `ema_ms`, `base_ms`, `degraded`) vergleichen. Der Zeitstempel liegt vor Writer-Warteschlange/Flush; die EMA besteht aus 80% vorherigem Wert und 20% neuer Messung. Keepalive-Scheduling vor diesem Zeitstempel ist ausgeschlossen. Ein niedriger ME-Wert bei hohem Android-Ping weist auf Arbeit außerhalb dieses ME-Messbereichs hin, benennt aber keine konkrete Ursache. Siehe [Writer][writer] und [Reader][reader].
|
||||
|
||||
Interpretationsbeispiele: Schnelle Telemt-Verarbeitung bei später Client-Zustellung lenkt die Untersuchung auf Frontend, Netzwerk und Client-Warteschlangen; `503` und die Retry-Header bestimmen die Basispause, während die geladene Jitter-Richtlinie und Client-Zeitstempel die tatsächliche Pause belegen; lange Upstream-Arbeit erfordert eine Direct/ME-Untersuchung. Keines dieser Muster beweist allein, dass TLS-Kryptografie 1000–1500 ms verursacht. Kompatibilität, Zertifikatsprüfung, Zulassungslimits und Backpressure während der Untersuchung beibehalten.
|
||||
|
||||
## Grenzen der Belege
|
||||
|
||||
Dieses Dokument beschreibt geprüften Quellcode, keinen Ende-zu-Ende-Gerätebenchmark. Android-/iOS-Links verweisen auf die genannten festen Revisionen; Telemt-Links auf die begleitende Implementierung im Arbeitsverzeichnis einschließlich lokaler WEB-Änderungen. Daraus folgt keine Gleichheit aller veröffentlichten Pakete. Die Dokumentation ändert weder Client noch Server, Timeouts oder Sicherheitseinstellungen.
|
||||
|
||||
[android-entry]: https://github.com/DrKLO/Telegram/blob/3de37c8cfb039452be7398909461da6288babf15/TMessagesProj/src/main/java/org/telegram/tgnet/ConnectionsManager.java#L752-L765
|
||||
[android-tester]: https://github.com/DrKLO/Telegram/blob/3de37c8cfb039452be7398909461da6288babf15/TMessagesProj/src/main/java/org/telegram/utils/proxy/WebProxyConnectionTester.java#L111-L172
|
||||
[android-transport]: https://github.com/DrKLO/Telegram/blob/3de37c8cfb039452be7398909461da6288babf15/TMessagesProj/src/main/java/org/telegram/utils/proxy/WebProxyTransport.java
|
||||
[android-native]: https://github.com/DrKLO/Telegram/blob/3de37c8cfb039452be7398909461da6288babf15/TMessagesProj/jni/tgnet/ConnectionsManager.cpp
|
||||
[android-socket]: https://github.com/DrKLO/Telegram/blob/3de37c8cfb039452be7398909461da6288babf15/TMessagesProj/jni/tgnet/ConnectionSocket.cpp
|
||||
[android-key]: https://github.com/DrKLO/Telegram/blob/3de37c8cfb039452be7398909461da6288babf15/TMessagesProj/jni/tgnet/Datacenter.cpp#L1312-L1323
|
||||
[android-ui]: https://github.com/DrKLO/Telegram/blob/3de37c8cfb039452be7398909461da6288babf15/TMessagesProj/src/main/java/org/telegram/ui/ProxyListActivity.java#L671-L687
|
||||
[ios-filter]: https://github.com/TelegramMessenger/Telegram-iOS/blob/279f89e4d4f63f17227bf877dc3d8990f22ecd58/submodules/TelegramCore/Sources/Network/ProxyServersStatuses.swift#L54-L65
|
||||
[ios-probe]: https://github.com/TelegramMessenger/Telegram-iOS/blob/279f89e4d4f63f17227bf877dc3d8990f22ecd58/submodules/MtProtoKit/Sources/MTProxyConnectivity.m#L57-L99
|
||||
[ios-ui]: https://github.com/TelegramMessenger/Telegram-iOS/blob/279f89e4d4f63f17227bf877dc3d8990f22ecd58/submodules/SettingsUI/Sources/Data%20and%20Storage/ProxyListSettingsController.swift#L273-L310
|
||||
[tls13]: https://datatracker.ietf.org/doc/html/rfc8446#section-2
|
||||
[tls12]: https://datatracker.ietf.org/doc/html/rfc5246#section-7.3
|
||||
[http1]: https://www.rfc-editor.org/rfc/rfc9112#section-9.3
|
||||
[http2]: https://datatracker.ietf.org/doc/html/rfc9113#section-5
|
||||
[session]: ../../src/web/http/session.rs
|
||||
[backend]: ../../src/web/session/backend.rs
|
||||
[runtime]: ../../src/web/bridge/runtime.js
|
||||
[conveyor]: ../../src/web/bridge/conveyor.js
|
||||
[downlink]: ../../src/web/bridge/downlink.js
|
||||
[poll]: ../../src/web/session/downlink.rs
|
||||
[request]: ../../src/web/bridge/request.js
|
||||
[response]: ../../src/web/http/response.rs
|
||||
[timings]: ../../src/web/trace/types.rs
|
||||
[writer]: ../../src/transport/middle_proxy/pool_writer.rs
|
||||
[reader]: ../../src/transport/middle_proxy/reader.rs
|
||||
@@ -0,0 +1,244 @@
|
||||
# Proxy-list ping: RPC Ping/Pong and WEB latency
|
||||
|
||||
[English](PROXY_PING.en.md) | [Русский](PROXY_PING.ru.md) | [Deutsch](PROXY_PING.de.md)
|
||||
|
||||
The reported **1000–1500 ms for WEB versus 50–150 ms for Classic/DD/EE** can compare different measurement boundaries. Android's WEB checker sees a local socket become ready before the remote WEB stream is necessarily ready. Remaining stream setup and carrier work can therefore enter the displayed result. The code does not impose a fixed one-second penalty on every successful WEB ping.
|
||||
|
||||
These numbers are operator observations, not measurements reproduced for this document. Source inspection establishes mechanisms; it does not identify the cause of an individual deployment's delay.
|
||||
|
||||
## Clients and measurements
|
||||
|
||||
Checked on **2026-10-31** against DrKLO Android `3de37c8cfb039452be7398909461da6288babf15` and Telegram iOS `279f89e4d4f63f17227bf877dc3d8990f22ecd58`. Installed releases and forks may differ.
|
||||
|
||||
| Measurement | What it covers | WEB behavior |
|
||||
| --- | --- | --- |
|
||||
| Android proxy-list ping | Encrypted MTProto `TL_ping` / `TL_pong` through the checked proxy | Separate WEB test transport, then native checker through a local socket. |
|
||||
| iOS proxy-list ping | `req_pq` / `resPQ` connectivity probe; timing starts at `connectionOpened` | `.web` entries are excluded from ping contexts; an inactive WEB row is shown as not tested. |
|
||||
| ICMP ping | IP echo to the selected host, subject to ICMP routing and policy | Does not measure the application relay or Telegram DC. |
|
||||
| WEB transport `FRAME_PING` / `FRAME_PONG` or WebSocket keepalive | Carrier/session liveness | Not Android's displayed MTProto result. |
|
||||
| Telemt ME RPC Ping/Pong | One Telemt-to-ME writer path, including local queue/flush scheduling | Excludes the client, WebView and public TLS frontend. |
|
||||
|
||||
Sources: [Android entry point][android-entry], [native requests][android-native], [iOS filter][ios-filter], [iOS probe][ios-probe], [iOS UI][ios-ui]. The current iOS WEB row therefore cannot be interpreted using Android's WEB ping formula.
|
||||
|
||||
Android displays the last checker result, without a median or EMA, and skips a new check when the previous check is less than two minutes old. A connected row can still show that stored result: it is not continuous RTT monitoring of the active session. The WEB checker creates its own transport rather than directly reusing the active app transport. See [proxy-list refresh][android-ui] and [WEB transport][android-transport].
|
||||
|
||||
## Where Android starts and stops the clock
|
||||
|
||||
For Classic/DD/EE, the native connection-ready callback follows remote TCP and the applicable proxy transport setup, including EE FakeTLS. Request processing refreshes the timestamp before sending/re-sending the probe. The normal successful sample therefore excludes that initial transport establishment. It includes subsequent relay work and the response path. See [socket readiness][android-socket] and [request processing][android-native].
|
||||
|
||||
For WEB, bridge startup, its initial HTTPS load, HELLO/WELCOME and an additional **500 ms** wait precede `native_checkProxy`; that wait is not added to its reported ping. WELCOME confirms a WEB session, not a ready Telegram DC stream. The native checker then connects to `127.0.0.1`, whose readiness does not wait for remote OPEN completion. Java acceptance/OPEN and the native timestamp update can race. Only work still pending inside the measured interval contributes. See [test sequencing][android-tester], [local socket and WELCOME][android-transport], [server session creation][session] and [stream backend][backend].
|
||||
|
||||
The diagrams show the normal successful path, not a guarantee of event ordering across threads:
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as Android native checker
|
||||
participant P as Classic/DD/EE proxy
|
||||
participant D as Telegram DC
|
||||
C->>P: DNS / TCP / proxy transport setup
|
||||
Note over C,P: Remote transport ready, measurement timestamp refreshed
|
||||
C->>P: Encrypted TL_ping
|
||||
P->>D: Relay
|
||||
D->>P: TL_pong
|
||||
P->>C: Relay
|
||||
Note over C: Display elapsed time from latest request timestamp
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as Android native checker
|
||||
participant B as Local socket / Java / WebView
|
||||
participant T as TLS frontend / Telemt
|
||||
participant D as Telegram DC
|
||||
B->>T: Bridge load, HELLO / session creation
|
||||
T->>B: WELCOME
|
||||
Note over B: Wait 500 ms before native_checkProxy
|
||||
C->>B: Connect to 127.0.0.1
|
||||
Note over C,B: Local socket ready, measurement timestamp refreshed
|
||||
Note over B,T: OPEN may race with the native timestamp update
|
||||
C->>B: MTProxy header and encrypted TL_ping
|
||||
B->>T: OPEN / DATA over selected carrier
|
||||
T->>D: Stream setup and relay via Direct / ME
|
||||
D->>T: TL_pong
|
||||
T->>B: Downlink DATA
|
||||
B->>C: Local socket delivery
|
||||
Note over C: Display elapsed time from latest request timestamp
|
||||
```
|
||||
|
||||
`TL_pong` completes the sample using the latest request timestamp. Force processing or resend can reset that timestamp, so the displayed value is not necessarily the full wall time of a failed/retried attempt. The checker uses an [existing DC authorization key][android-key]; do not count a complete new MTProto authorization-key exchange as an obligatory part of every check.
|
||||
|
||||
## What TLS contributes
|
||||
|
||||
The public TLS connection terminates at NGINX, HAProxy or Caddy. Telemt receives plain HTTP/1.1 on its private listener. Frontend HTTP/2 and the internal HTTP/1.1 hop are separate connections; their protocol versions need not match. EE FakeTLS is an MTProxy camouflage transport, not the browser's certificate-authenticated HTTPS connection. WEB carries plain/DD MTProxy streams; EE is not a WEB secret format. See the [WEB deployment guide](WEB_PROXY.en.md).
|
||||
|
||||
For a new connection without loss, the usual TCP handshake costs about one client-to-frontend RTT. A full TLS 1.3 handshake normally adds one RTT; a full TLS 1.2 handshake normally adds two. These are protocol-flight estimates excluding DNS, processing, certificate validation, scheduling and retransmissions, not a measured WEB latency budget. Resumption can change the exchange. See [TLS 1.3][tls13] and [TLS 1.2][tls12].
|
||||
|
||||
Initial bridge TLS normally occurs before Android's measurement. Additional HTTP connections or a WebSocket Upgrade can still occur inside it; connection reuse must be established from a trace. Persistent HTTPS and an established WebSocket do not perform a new TLS handshake for every ping. `cache: 'no-store'` controls caching, not TCP/TLS reuse. Neither disabling certificate checks nor enabling TLS 0-RTT is required to explain or diagnose this behavior. See [HTTP persistence][http1] and [bridge requests][request].
|
||||
|
||||
## Where WEB adds work compared with native MTProxy
|
||||
|
||||
The comparison below separates work before the Android timer from work that can enter the displayed sample. The baseline is Classic/DD over TCP. For EE, FakeTLS belongs to native transport setup. Box sizes and arrow lengths do not represent elapsed time.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph N["Native MTProxy: Classic/DD"]
|
||||
direction TB
|
||||
N0["Before measurement<br/>DNS + TCP + native transport setup"] --> N1["Remote transport ready<br/>Request timestamp refreshed"]
|
||||
N1 --> N2["MTProxy request and response<br/>Relay setup still pending, network, queues, Telegram DC"] --> N3["TL_pong received<br/>Displayed sample ends"]
|
||||
end
|
||||
subgraph W["WEB: MTProxy inside HTTPS or WebSocket"]
|
||||
direction TB
|
||||
W0["Before measurement<br/>DNS + TCP + real TLS<br/>HTTP bridge + HELLO/WELCOME + 500 ms"] --> W1["Local socket ready<br/>Request timestamp refreshed"]
|
||||
W1 --> W2["Extra client work<br/>Java / WebView / JavaScript queues<br/>Remote OPEN may still be pending"] --> W3["Uplink carrier work<br/>HTTP upload or WebSocket frame<br/>Frontend handling and possible buffering"]
|
||||
W3 --> W4["Inner MTProxy request and response<br/>Relay setup still pending, network, queues, Telegram DC"] --> W5["Downlink carrier work<br/>HTTP poll or WebSocket frame<br/>ACK/commit gate, native delivery queues"]
|
||||
W5 --> W6["TL_pong received<br/>Displayed sample ends"]
|
||||
X["Only if another connection is needed<br/>TCP + TLS, possible WebSocket Upgrade<br/>No handshake per ping on a reused connection"] -.-> W3
|
||||
X -.-> W5
|
||||
R["Only on errors or overload<br/>Retries and backoff<br/>Telemt base 250 ms<br/>Plus optional jitter"] -.-> W3
|
||||
R -.-> W5
|
||||
end
|
||||
classDef preparation fill:#eeeeee,stroke:#666666,color:#111111
|
||||
classDef boundary fill:#dbeafe,stroke:#2563eb,color:#111111
|
||||
classDef shared fill:#dcfce7,stroke:#15803d,color:#111111
|
||||
classDef extra fill:#ffedd5,stroke:#c2410c,color:#111111
|
||||
class N0,W0 preparation
|
||||
class N1,N3,W1,W6 boundary
|
||||
class N2,W4 shared
|
||||
class W2,W3,W5,X,R extra
|
||||
```
|
||||
|
||||
**Gray:** work before the displayed sample. **Blue:** timer boundaries. **Green:** MTProxy relay/DC work present in both paths, whose actual cost can differ. **Orange:** WEB carrier and client work inside the sample. **Dashed arrows:** conditional connection setup or retries, not obligatory stages.
|
||||
|
||||
On a reused carrier, the conditional TCP/TLS/Upgrade cost disappears, while framing, HTTP or WebSocket handling and client queues remain. HTTP can overlap uplink and downlink; it does not necessarily add a whole RTT for every request. Polling wakes on data, and frontend buffering is deployment-dependent. Any delay from loss, congestion or upstream setup may also affect native MTProxy.
|
||||
|
||||
Thus the visible difference can include remaining WEB stream setup, additional connection setup, carrier handling and scheduling, plus retries when observed. It is not a fixed TLS surcharge or an arithmetic sum of all boxes. The initial real TLS handshake is shown outside the Android timer deliberately: it affects total time to check, but normally not the displayed sample. The separate checker transport also means that an active app connection does not guarantee a warm proxy-list check.
|
||||
|
||||
### Configurable HTTP retry jitter
|
||||
|
||||
`[web.retry_jitter]` adds an independently sampled delay to every existing bridge HTTP retry (network errors and 408/429/502/503/504). It requires no Telegram application changes. Without this section, or with `enabled = false`, the existing 250 ms Telemt hint and legacy backoff/jitter remain unchanged.
|
||||
|
||||
```toml
|
||||
[web.retry_jitter]
|
||||
enabled = true
|
||||
min_ms = 0
|
||||
max_ms = 250
|
||||
distribution = "uniform"
|
||||
# Only for distribution = "triangular":
|
||||
# peak_ms = 125
|
||||
```
|
||||
|
||||
The range describes an **addition**, not the total pause: the Telemt 250 ms hint plus this example gives 250–500 ms. Without a positive server hint, the base remains 250, 500, 1000, then 2000 ms. Enabled jitter replaces the legacy 25% jitter. A valid standard `Retry-After` is not shortened to the legacy 30-second cap in enabled mode. If the pause exceeds the remaining operation budget, the budget expires without an early retry.
|
||||
|
||||
Defaults are `enabled = false`, `min_ms = 0`, `max_ms = 250`, `distribution = "uniform"`, and no `peak_ms`. Require `0 <= min_ms <= max_ms <= 30000`. `uniform` samples integer milliseconds; `triangular` samples a triangular density and rounds to milliseconds. Its optional peak defaults to the midpoint and must be within the interval. An explicit peak with `uniform`, unknown keys/distributions and invalid ranges are rejected even when disabled. Equal bounds produce a constant addition.
|
||||
|
||||
The policy is frozen into each bridge page. Config/API reload affects newly loaded pages; existing pages retain it through recovery. Recovery JSON and HTTP compatibility headers remain unchanged. Sampling prefers `crypto.getRandomValues`, with `Math.random` as a compatibility fallback. Successful traffic is not delayed. Attempt limits, absolute budgets, cancellation and payload/sequence replay remain intact; longer pauses can exhaust a startup/recovery budget sooner in terms of completed attempts.
|
||||
|
||||
This reduces fixed retry timing, without guaranteeing resistance to DPI. Browser scheduling, network queues and other protocol timing remain observable. Existing timeline examples describe the default disabled mode. To evaluate enabled mode, add a sampled delay to each retry pause, not to the initial connection or every data frame.
|
||||
|
||||
The policy changes existing retry waits only. Stricter per-call limits still apply: ordinary `/down` polls and committed `/up` calls use one attempt; their recovery replay permits two. This option does not create new retry loops. It neither extends `web.timeouts.bridge_retry_secs` nor any startup/recovery deadline.
|
||||
|
||||
## Illustrative timeline with approximate durations
|
||||
|
||||
**An explanatory model, not a benchmark or an expected latency range.** The numbers below are chosen to show how the stages combine. They do not reconstruct the reported 1000–1500 ms. Assume cached DNS, a 40 ms client-to-frontend RTT, a new TCP connection, a full TLS 1.3 handshake where required, an existing DC authorization key, and no loss or native request-timestamp reset. The baseline is Classic/DD. EE adds its own FakeTLS setup before the native timer.
|
||||
|
||||
For this example, native preparation takes 40 ms for TCP. WEB preparation takes 750 ms: 50 ms client/bridge startup + 40 ms TCP + 40 ms TLS + 120 ms HTTP bridge/session exchange + the Android checker's 500 ms wait. These are chosen serial durations for this example; real stages can overlap. The initial TLS and the 500 ms wait are outside the displayed ping.
|
||||
|
||||
The diagram starts at each checker's **latest request timestamp**, not at app launch or the first connection attempt. The horizontal axis shows seconds with millisecond precision (0.200 = 200 ms). Bar widths are proportional to duration. Each section is a separate scenario; its stages are successive, not parallel. Initial preparation remains outside the diagram.
|
||||
|
||||
```mermaid
|
||||
%%{init: {"theme": "neutral", "gantt": {"leftPadding": 200, "rightPadding": 100, "barHeight": 24, "barGap": 8, "fontSize": 14, "sectionFontSize": 14}}}%%
|
||||
gantt
|
||||
dateFormat x
|
||||
axisFormat %S.%L
|
||||
tickInterval 100millisecond
|
||||
todayMarker off
|
||||
title Displayed ping - jitter off
|
||||
accTitle: Displayed ping - jitter off
|
||||
accDescr: Seconds from the request timestamp, labels show milliseconds
|
||||
section Classic/DD - 100 ms
|
||||
R 100 ms :n_r, 0, 100ms
|
||||
section WEB without errors - 200 ms
|
||||
U 40 ms :w_u, 0, 40ms
|
||||
R 100 ms :w_r, after w_u, 100ms
|
||||
D 60 ms :w_d, after w_r, 60ms
|
||||
section WEB with retry - 490 ms
|
||||
F 40 ms :crit, f_u, 0, 40ms
|
||||
Wait 250 ms :crit, retry_wait, after f_u, 250ms
|
||||
U 40 ms :retry_u, after retry_wait, 40ms
|
||||
R 100 ms :retry_r, after retry_u, 100ms
|
||||
D 60 ms :retry_d, after retry_r, 60ms
|
||||
```
|
||||
|
||||
Stage durations: `R` = 100 ms of baseline MTProxy relay/network/DC request-response work. `U` = 40 ms of additional WEB uplink/OPEN/client work. `D` = 60 ms of additional WEB downlink/delivery work. `F` = 40 ms spent on one failed upload attempt. `Wait` = the 250 ms wait requested by `X-Telemt-Retry-After-Ms: 250`. `U` and `D` are illustrative incremental costs beyond `R`, not a second count of the full network round trip. ACK/commit gating is included only insofar as it actually delays delivery.
|
||||
|
||||
| Scenario | Before ping timer | Displayed ping | Total check time in this model |
|
||||
| --- | --- | --- | --- |
|
||||
| Classic/DD | 40 ms | 100 ms | 140 ms |
|
||||
| WEB, no errors | 750 ms | 40 + 100 + 60 = 200 ms | 950 ms |
|
||||
| WEB, one failed upload and one retry wait | 750 ms | 40 + 250 + 40 + 100 + 60 = 490 ms | 1240 ms |
|
||||
| WEB, same retry with uniform jitter 0–250 ms | 750 ms | 490–740 ms | 1240–1490 ms |
|
||||
|
||||
A further TCP + TLS 1.3 connection opened **inside** the measured interval could add approximately 80 ms here, if fully sequential: the 200 ms sample would become 280 ms. With connection reuse, that extra handshake cost is zero. Switching the initial full handshake from TLS 1.3 to TLS 1.2 adds about 40 ms to preparation under these assumptions, not to the displayed ping. These examples omit TLS processing, resumption and packet loss.
|
||||
|
||||
The 490 ms row and diagram illustrate one retry with jitter disabled. The extra table row applies `enabled = true`, `min_ms = 0`, `max_ms = 250`, `distribution = "uniform"` to that same retry; its range comes from this model, not measurements. An earlier JavaScript bridge without the millisecond extension, or an intermediary removing that hint when jitter is disabled, retains the standard one-second fallback: the same model then gives a displayed ping of 1240 ms. Neither scenario identifies the cause of the original observation. Without trace evidence of retries, locate other delays such as queues, frontend buffering, connection setup or upstream work. Do not insert timeouts as waiting periods or force overlapping stages into this serial model.
|
||||
|
||||
## HTTP, WebSocket and other delay sources
|
||||
|
||||
Telemt overload responses carry `Retry-After: 1` and `X-Telemt-Retry-After-Ms: 250`. Only status `503` with that exact header pair selects a **250 ms base delay** in the generated bridge. With `web.retry_jitter.enabled = false`, the pause is 250 ms; when enabled, the configured random addition applies. Other responses use the standard `Retry-After` handling or fallback backoff described below. Earlier JavaScript bridge pages without support for the millisecond hint use the one-second fallback until replaced by a newly loaded page; this does not require updating the Telegram application. Attempt limits, absolute budgets, cancellation and admission limits remain unchanged.
|
||||
|
||||
| Factor | Effect and evidence |
|
||||
| --- | --- |
|
||||
| HTTP uplink | The generated bridge offers `X-Telemt-Up-Window: 4`; the server accepts 1–4, with legacy fallback 1. Window 1 waits for an ACK before the next upload; window 4 permits bounded concurrency. Not all HTTP traffic is stop-and-wait. See [negotiation][runtime] and [session handler][session]. |
|
||||
| First downlink | `/down` can start alongside `/up`; there is no unconditional extra sequential ACK RTT. Initial native delivery is gated by the first valid upload ACK/commit. Frames are delivered incrementally. See [conveyor][conveyor] and [downlink][downlink]. |
|
||||
| Long polling | `long_poll_secs=25` bounds an empty wait. Available data wakes the poll immediately. Gaps between polls or occupied browser connection slots can still delay delivery. See [server polling][poll]. |
|
||||
| Carrier sharing | `https` shares its upload queue; `https-lanes` separates logical lanes. WebSocket carries frames after Upgrade, without a POST per frame; `websocket-lanes` separates sockets. Shared network, flow-control and WebView resources remain. HTTP/2 multiplexes streams but does not remove all congestion or flow-control stalls. See [HTTP/2][http2] and the [carrier guide](WEB_PROXY.en.md). |
|
||||
| Frontend buffering | Request/response buffering or missing streaming/Upgrade support can delay small messages. Compare with the existing NGINX example; preserve routing, authentication and limits. |
|
||||
| Client scheduling | Java accept/read threads, UI dispatch, WebView/JavaScript and delivery back to native code add queues. CPU pressure, mobile power management and network transitions can amplify them. |
|
||||
| Relay and network | Remaining stream admission, inner MTProxy handshake, Direct connection or ME registration, Telegram response, loss/retransmission and queue pressure can contribute. A ready WEB session does not prove a ready upstream. |
|
||||
| Errors and retries | Retryable statuses are 408/429/502/503/504. With jitter disabled, the exact Telemt overload hint gives a 250 ms pause; without a positive server hint, backoff starts at 250 ms and doubles to a 2000 ms base plus legacy jitter below 25%. With jitter enabled, the pause is the positive server hint or that base **plus** the configured sample, replacing legacy jitter. Budgets and per-call attempt limits still apply. Record the loaded bridge policy and actual retry timestamps. See [responses][response] and [retry logic][request]. |
|
||||
|
||||
Deadlines are not mandatory sleeps. The default 10 s bridge-request deadline, 90 s retry budget, 30 s stream-first-byte deadline and 10 s stream-handshake deadline must not be summed into normal ping. `carrier_probe_coalesce_ms=0` disables that optional coalescing delay. Carrier fallback deadlines affect failed attempts, not every successful exchange. See [timeout defaults](../../src/config/types/web/defaults.rs).
|
||||
|
||||
A conceptual WEB sample is **remaining setup + carrier/network transit + queues + Telegram response + any retry delays still inside the timer**. These stages overlap; adding all configured timeouts or counting one RTT per HTTP endpoint is incorrect. Warm carriers can reduce setup costs, but the Android proxy checker still uses a separate transport. WebSocket is not universally faster; use only carriers supported by the actual client. The current iOS compatibility configuration uses `https`.
|
||||
|
||||
## Diagnosis without changing protections
|
||||
|
||||
1. Record client/build, Android WebView version, the loaded bridge’s `web.retry_jitter` policy, carrier, public endpoint, IP family, network, Direct/ME route, DC and load. Match these conditions for comparison. Respect Android's two-minute cached result; do not treat repeated UI reads as new samples.
|
||||
2. Separate three experiments: a new proxy-list check; a new logical stream on a ready carrier; application RPC on an established MTProto session. The latter two require suitable client instrumentation and are not automatically provided by the proxy-list display. Record individual samples and distributions rather than comparing one cold sample with one warm sample.
|
||||
3. Use the authenticated `GET /web-status` and existing `[web.debug]` controls with `capture_timings=true`, `capture_frames=true`, `body_capture="metadata"`. Enable bounded capture as described in the [WEB diagnostics guide](WEB_PROXY.en.md), then restore its prior state. Payloads, capabilities and secrets are unnecessary for this investigation.
|
||||
4. Correlate session creation, carrier selection/commit/failure, `stream_admitted`, `stream_first_byte`, `handshake_succeeded`, OPEN/DATA, HTTP status and retries. `relay_started` precedes upstream work and is not a DC-ready timestamp. Use `GET /v1/runtime/web/status` and `GET /v1/runtime/web/sessions` for capacity and queue-pressure context, not end-to-end RTT.
|
||||
5. Interpret `request_body_us`, `response_ready_us` and `response_body_us` as offsets from service entry. They are not independent durations to add, nor timestamps of wire flush or peer TCP ACK. Compare offsets only where recorded and meaningful. See [trace timing definitions][timings].
|
||||
6. Add frontend connection/TLS/request timing and client timestamps to locate delays outside Telemt. Establish connection reuse, negotiated HTTP version, buffering and Upgrade behavior. Bridge startup/HELLO sideband events do not provide a complete client timeline. Synchronize clocks for cross-host comparisons or use durations on each host.
|
||||
7. If ME is involved, compare the existing `ME RTT sample` trace (`rtt_ms`, `ema_ms`, `base_ms`, `degraded`). The timestamp precedes the writer queue/flush, and the EMA uses 80% previous value plus 20% new sample. Keepalive scheduling before that timestamp is excluded. A low ME value with high Android ping points to work outside that measured ME segment, without identifying one particular cause. See [writer][writer] and [reader][reader].
|
||||
|
||||
Evidence patterns: fast Telemt handling with late client delivery suggests investigating frontend/network/client queues; `503` and its retry headers identify the base delay, while the loaded jitter policy and client timestamps establish the actual pause; long upstream work calls for Direct/ME investigation. None alone proves that TLS cryptography causes 1000–1500 ms. Keep compatibility, certificate verification, admission limits and backpressure intact while collecting evidence.
|
||||
|
||||
## Evidence scope
|
||||
|
||||
This document describes inspected source behavior, not an end-to-end device benchmark. Android/iOS links pin the revisions above; Telemt links refer to the accompanying working-tree implementation, including local WEB changes, rather than claiming every published package has identical behavior. No client, server, timeout or security setting is changed by this documentation.
|
||||
|
||||
[android-entry]: https://github.com/DrKLO/Telegram/blob/3de37c8cfb039452be7398909461da6288babf15/TMessagesProj/src/main/java/org/telegram/tgnet/ConnectionsManager.java#L752-L765
|
||||
[android-tester]: https://github.com/DrKLO/Telegram/blob/3de37c8cfb039452be7398909461da6288babf15/TMessagesProj/src/main/java/org/telegram/utils/proxy/WebProxyConnectionTester.java#L111-L172
|
||||
[android-transport]: https://github.com/DrKLO/Telegram/blob/3de37c8cfb039452be7398909461da6288babf15/TMessagesProj/src/main/java/org/telegram/utils/proxy/WebProxyTransport.java
|
||||
[android-native]: https://github.com/DrKLO/Telegram/blob/3de37c8cfb039452be7398909461da6288babf15/TMessagesProj/jni/tgnet/ConnectionsManager.cpp
|
||||
[android-socket]: https://github.com/DrKLO/Telegram/blob/3de37c8cfb039452be7398909461da6288babf15/TMessagesProj/jni/tgnet/ConnectionSocket.cpp
|
||||
[android-key]: https://github.com/DrKLO/Telegram/blob/3de37c8cfb039452be7398909461da6288babf15/TMessagesProj/jni/tgnet/Datacenter.cpp#L1312-L1323
|
||||
[android-ui]: https://github.com/DrKLO/Telegram/blob/3de37c8cfb039452be7398909461da6288babf15/TMessagesProj/src/main/java/org/telegram/ui/ProxyListActivity.java#L671-L687
|
||||
[ios-filter]: https://github.com/TelegramMessenger/Telegram-iOS/blob/279f89e4d4f63f17227bf877dc3d8990f22ecd58/submodules/TelegramCore/Sources/Network/ProxyServersStatuses.swift#L54-L65
|
||||
[ios-probe]: https://github.com/TelegramMessenger/Telegram-iOS/blob/279f89e4d4f63f17227bf877dc3d8990f22ecd58/submodules/MtProtoKit/Sources/MTProxyConnectivity.m#L57-L99
|
||||
[ios-ui]: https://github.com/TelegramMessenger/Telegram-iOS/blob/279f89e4d4f63f17227bf877dc3d8990f22ecd58/submodules/SettingsUI/Sources/Data%20and%20Storage/ProxyListSettingsController.swift#L273-L310
|
||||
[tls13]: https://datatracker.ietf.org/doc/html/rfc8446#section-2
|
||||
[tls12]: https://datatracker.ietf.org/doc/html/rfc5246#section-7.3
|
||||
[http1]: https://www.rfc-editor.org/rfc/rfc9112#section-9.3
|
||||
[http2]: https://datatracker.ietf.org/doc/html/rfc9113#section-5
|
||||
[session]: ../../src/web/http/session.rs
|
||||
[backend]: ../../src/web/session/backend.rs
|
||||
[runtime]: ../../src/web/bridge/runtime.js
|
||||
[conveyor]: ../../src/web/bridge/conveyor.js
|
||||
[downlink]: ../../src/web/bridge/downlink.js
|
||||
[poll]: ../../src/web/session/downlink.rs
|
||||
[request]: ../../src/web/bridge/request.js
|
||||
[response]: ../../src/web/http/response.rs
|
||||
[timings]: ../../src/web/trace/types.rs
|
||||
[writer]: ../../src/transport/middle_proxy/pool_writer.rs
|
||||
[reader]: ../../src/transport/middle_proxy/reader.rs
|
||||
@@ -0,0 +1,244 @@
|
||||
# Ping в списке прокси: RPC Ping/Pong и задержки WEB
|
||||
|
||||
[English](PROXY_PING.en.md) | [Русский](PROXY_PING.ru.md) | [Deutsch](PROXY_PING.de.md)
|
||||
|
||||
Наблюдаемые **1000–1500 мс для WEB против 50–150 мс для Classic/DD/EE** могут относиться к измерениям с разными границами. В Android локальный сокет WEB-проверки становится готов раньше, чем обязательно готов удалённый WEB-поток. Оставшееся открытие потока и работа транспорта могут попасть в показанный результат. Код не задаёт фиксированный секундный штраф для каждого успешного WEB-ping.
|
||||
|
||||
Эти числа предоставлены оператором и не воспроизведены при подготовке документа. Анализ исходников подтверждает механизмы, но не устанавливает причину задержки в конкретном развёртывании.
|
||||
|
||||
## Клиенты и измерения
|
||||
|
||||
Проверено **2026-10-31** по DrKLO Android `3de37c8cfb039452be7398909461da6288babf15` и Telegram iOS `279f89e4d4f63f17227bf877dc3d8990f22ecd58`. Установленные релизы и форки могут отличаться.
|
||||
|
||||
| Измерение | Что охватывает | Поведение WEB |
|
||||
| --- | --- | --- |
|
||||
| Ping в списке прокси Android | Зашифрованный MTProto `TL_ping` / `TL_pong` через проверяемый прокси | Отдельный WEB-транспорт проверки, затем нативная проверка через локальный сокет. |
|
||||
| Ping в списке прокси iOS | Проверка связности `req_pq` / `resPQ`; отсчёт от `connectionOpened` | Записи `.web` исключены из проверки; неактивный WEB-прокси отображается как непроверенный. |
|
||||
| ICMP ping | IP echo до выбранного хоста с учётом маршрутизации и политики ICMP | Не измеряет прикладную пересылку и Telegram DC. |
|
||||
| WEB transport `FRAME_PING` / `FRAME_PONG` или WebSocket keepalive | Жизнеспособность транспорта/сессии | Это не отображаемый Android результат MTProto. |
|
||||
| Telemt ME RPC Ping/Pong | Один путь от Telemt до ME, включая локальную очередь writer и планирование flush | Не включает клиент, WebView и публичный TLS-фронтенд. |
|
||||
|
||||
Источники: [точка входа Android][android-entry], [нативные запросы][android-native], [фильтр iOS][ios-filter], [проверка iOS][ios-probe], [интерфейс iOS][ios-ui]. Поэтому формулу WEB-ping Android нельзя переносить на WEB-строку текущего iOS.
|
||||
|
||||
Android показывает последний результат проверки без медианы или EMA и пропускает новую проверку, если предыдущая была менее двух минут назад. У подключённого прокси тоже может отображаться сохранённый результат: это не непрерывное измерение RTT активной сессии. WEB-проверка создаёт собственный транспорт, а не использует напрямую активный транспорт приложения. См. [обновление списка][android-ui] и [WEB-транспорт][android-transport].
|
||||
|
||||
## Где Android запускает и останавливает таймер
|
||||
|
||||
Для Classic/DD/EE нативный callback готовности приходит после удалённого TCP-соединения и необходимой подготовки транспорта прокси, включая EE FakeTLS. Обработка запроса обновляет временную метку перед отправкой или повторной отправкой проверки. Поэтому обычный успешный замер исключает это начальное установление транспорта, но включает последующую пересылку и обратный путь. См. [готовность сокета][android-socket] и [обработку запросов][android-native].
|
||||
|
||||
Для WEB запуск моста, начальная HTTPS-загрузка, HELLO/WELCOME и дополнительные **500 мс** ожидания предшествуют `native_checkProxy`; эти 500 мс не прибавляются к показанному ping. WELCOME подтверждает WEB-сессию, а не готовность потока до Telegram DC. Затем нативная проверка подключается к `127.0.0.1`: готовность этого сокета не ждёт завершения удалённого OPEN. Java accept/OPEN и обновление нативной временной метки могут выполняться в разном порядке. Учитывается только работа, оставшаяся внутри интервала измерения. См. [порядок проверки][android-tester], [локальный сокет и WELCOME][android-transport], [создание серверной сессии][session] и [обработку потока][backend].
|
||||
|
||||
Схемы показывают обычный успешный путь, но не гарантируют порядок событий между потоками выполнения:
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as Android native checker
|
||||
participant P as Classic/DD/EE proxy
|
||||
participant D as Telegram DC
|
||||
C->>P: DNS / TCP / proxy transport setup
|
||||
Note over C,P: Remote transport ready, measurement timestamp refreshed
|
||||
C->>P: Encrypted TL_ping
|
||||
P->>D: Relay
|
||||
D->>P: TL_pong
|
||||
P->>C: Relay
|
||||
Note over C: Display elapsed time from latest request timestamp
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as Android native checker
|
||||
participant B as Local socket / Java / WebView
|
||||
participant T as TLS frontend / Telemt
|
||||
participant D as Telegram DC
|
||||
B->>T: Bridge load, HELLO / session creation
|
||||
T->>B: WELCOME
|
||||
Note over B: Wait 500 ms before native_checkProxy
|
||||
C->>B: Connect to 127.0.0.1
|
||||
Note over C,B: Local socket ready, measurement timestamp refreshed
|
||||
Note over B,T: OPEN may race with the native timestamp update
|
||||
C->>B: MTProxy header and encrypted TL_ping
|
||||
B->>T: OPEN / DATA over selected carrier
|
||||
T->>D: Stream setup and relay via Direct / ME
|
||||
D->>T: TL_pong
|
||||
T->>B: Downlink DATA
|
||||
B->>C: Local socket delivery
|
||||
Note over C: Display elapsed time from latest request timestamp
|
||||
```
|
||||
|
||||
`TL_pong` завершает замер относительно последней временной метки запроса. Принудительная обработка или повторная отправка могут обновить её: результат не обязательно равен полному времени неудачной попытки с повторами. Проверка использует [существующий ключ авторизации DC][android-key]; полный обмен для создания нового ключа MTProto не является обязательной частью каждой проверки.
|
||||
|
||||
## Вклад TLS
|
||||
|
||||
Публичное TLS-соединение завершается в NGINX, HAProxy или Caddy. Telemt получает обычный HTTP/1.1 на приватном listener. Внешний HTTP/2 и внутренний HTTP/1.1 — разные соединения; версии протокола на этих участках могут различаться. EE FakeTLS — маскирующий транспорт MTProxy, а не браузерное HTTPS-соединение с проверкой сертификата. WEB переносит plain/DD MTProxy; EE не является форматом секрета WEB. См. [руководство WEB](WEB_PROXY.ru.md).
|
||||
|
||||
Для нового соединения без потерь обычный TCP-handshake занимает примерно один RTT между клиентом и фронтендом. Полный TLS 1.3 handshake обычно добавляет один RTT, полный TLS 1.2 — два. Это оценка обменов протокола без DNS, обработки, проверки сертификата, планирования и повторной передачи, а не измеренный бюджет задержки WEB. Возобновление TLS-сессии может изменить обмен. См. [TLS 1.3][tls13] и [TLS 1.2][tls12].
|
||||
|
||||
Начальный TLS для загрузки моста обычно происходит до измерения Android. Дополнительные HTTP-соединения или WebSocket Upgrade могут оказаться внутри него; повторное использование соединений нужно подтверждать трассировкой. Постоянное HTTPS-соединение и установленный WebSocket не выполняют новый TLS-handshake для каждого ping. `cache: 'no-store'` управляет кешированием, а не повторным использованием TCP/TLS. Для объяснения и диагностики не требуется отключать проверку сертификатов или включать TLS 0-RTT. См. [постоянные HTTP-соединения][http1] и [запросы моста][request].
|
||||
|
||||
## Где WEB добавляет работу относительно обычного MTProxy
|
||||
|
||||
На схеме разделены этапы до запуска таймера Android и работа, которая может попасть в показанный результат. Базовый вариант — Classic/DD поверх TCP. Для EE FakeTLS относится к подготовке нативного транспорта. Размеры блоков и длины стрелок не обозначают длительность.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph N["Обычный MTProxy: Classic/DD"]
|
||||
direction TB
|
||||
N0["До измерения<br/>DNS + TCP + подготовка нативного транспорта"] --> N1["Удалённый транспорт готов<br/>Временная метка запроса обновлена"]
|
||||
N1 --> N2["Запрос и ответ MTProxy<br/>Оставшаяся подготовка relay, сеть, очереди, Telegram DC"] --> N3["Получен TL_pong<br/>Отображаемый замер завершён"]
|
||||
end
|
||||
subgraph W["WEB: MTProxy внутри HTTPS или WebSocket"]
|
||||
direction TB
|
||||
W0["До измерения<br/>DNS + TCP + настоящий TLS<br/>HTTP-мост + HELLO/WELCOME + 500 мс"] --> W1["Локальный сокет готов<br/>Временная метка запроса обновлена"]
|
||||
W1 --> W2["Дополнительная работа клиента<br/>Очереди Java / WebView / JavaScript<br/>Удалённый OPEN ещё может быть не завершён"] --> W3["Работа транспорта на отправке<br/>HTTP upload или кадр WebSocket<br/>Обработка фронтендом и возможная буферизация"]
|
||||
W3 --> W4["Внутренний запрос и ответ MTProxy<br/>Оставшаяся подготовка relay, сеть, очереди, Telegram DC"] --> W5["Работа транспорта на приёме<br/>HTTP poll или кадр WebSocket<br/>Ожидание ACK/commit и очереди доставки в native"]
|
||||
W5 --> W6["Получен TL_pong<br/>Отображаемый замер завершён"]
|
||||
X["Только если нужно ещё одно соединение<br/>TCP + TLS, возможный WebSocket Upgrade<br/>При переиспользовании нет handshake на каждый ping"] -.-> W3
|
||||
X -.-> W5
|
||||
R["Только при ошибках или перегрузке<br/>Повторы и backoff<br/>База Telemt 250 мс<br/>Плюс опциональный jitter"] -.-> W3
|
||||
R -.-> W5
|
||||
end
|
||||
classDef preparation fill:#eeeeee,stroke:#666666,color:#111111
|
||||
classDef boundary fill:#dbeafe,stroke:#2563eb,color:#111111
|
||||
classDef shared fill:#dcfce7,stroke:#15803d,color:#111111
|
||||
classDef extra fill:#ffedd5,stroke:#c2410c,color:#111111
|
||||
class N0,W0 preparation
|
||||
class N1,N3,W1,W6 boundary
|
||||
class N2,W4 shared
|
||||
class W2,W3,W5,X,R extra
|
||||
```
|
||||
|
||||
**Серый:** работа до отображаемого замера. **Синий:** границы таймера. **Зелёный:** работа MTProxy relay/DC, присутствующая в обоих путях, но не обязательно одинаковая по длительности. **Оранжевый:** работа WEB-транспорта и клиента внутри замера. **Пунктир:** условные затраты на соединения или повторы, а не обязательные этапы.
|
||||
|
||||
При повторном использовании транспорта условные затраты на TCP/TLS/Upgrade исчезают, но остаются формирование кадров, обработка HTTP или WebSocket и очереди клиента. HTTP может совмещать отправку и приём: каждый запрос не обязательно добавляет целый RTT. Polling пробуждается при появлении данных, а буферизация фронтенда зависит от развёртывания. Потери, перегрузка сети и подготовка upstream могут задерживать и обычный MTProxy.
|
||||
|
||||
Таким образом, в видимую разницу могут войти оставшееся открытие WEB-потока, дополнительные соединения, обработка транспорта, планирование и подтверждённые повторы. Это не фиксированная надбавка TLS и не арифметическая сумма блоков. Начальный настоящий TLS намеренно показан до таймера Android: он влияет на полное время проверки, но обычно не на отображаемый замер. Отдельный транспорт проверки также означает, что активное соединение приложения не гарантирует прогретую проверку в списке прокси.
|
||||
|
||||
### Настраиваемый jitter HTTP-повторов
|
||||
|
||||
`[web.retry_jitter]` добавляет независимо выбранную задержку к каждому существующему HTTP-повтору бриджа: сетевым ошибкам и ответам 408/429/502/503/504. Менять приложения Telegram не требуется. Без секции или при `enabled = false` сохраняются подсказка Telemt на 250 мс и прежний backoff/jitter.
|
||||
|
||||
```toml
|
||||
[web.retry_jitter]
|
||||
enabled = true
|
||||
min_ms = 0
|
||||
max_ms = 250
|
||||
distribution = "uniform"
|
||||
# Only for distribution = "triangular":
|
||||
# peak_ms = 125
|
||||
```
|
||||
|
||||
Диапазон задаёт **добавку**, а не полную паузу: подсказка Telemt 250 мс с этим примером даёт 250–500 мс. Без положительной серверной подсказки база остаётся 250, 500, 1000, затем 2000 мс. Включённый jitter заменяет прежний jitter до 25%. Корректный стандартный `Retry-After` во включённом режиме не сокращается прежним пределом в 30 секунд. Если пауза не помещается в оставшийся бюджет операции, бюджет истекает без раннего повтора.
|
||||
|
||||
Значения по умолчанию: `enabled = false`, `min_ms = 0`, `max_ms = 250`, `distribution = "uniform"`, `peak_ms` отсутствует. Требуется `0 <= min_ms <= max_ms <= 30000`. `uniform` выбирает целые миллисекунды равномерно; `triangular` использует треугольную плотность с округлением до миллисекунд. Необязательный пик по умолчанию находится посередине и должен входить в диапазон. Явный пик для `uniform`, неизвестные ключи/распределения и неверные границы отклоняются даже при выключенной опции. Одинаковые границы дают постоянную добавку.
|
||||
|
||||
Политика фиксируется в каждой странице бриджа. Reload через конфиг/API влияет на новые страницы; активные сохраняют настройки при recovery. Recovery JSON и HTTP-заголовки совместимости не меняются. Используется `crypto.getRandomValues`, при недоступности — `Math.random` для совместимости. Успешный трафик не задерживается. Лимиты попыток, общий бюджет, отмена и повтор неизменных payload/sequence сохраняются; более длинные паузы могут уменьшить число попыток, помещающихся в startup/recovery-бюджет.
|
||||
|
||||
Это размывает фиксированные интервалы повторов, но не гарантирует защиту от DPI. Планирование браузера, сетевые очереди и другие временные характеристики протокола остаются наблюдаемыми. Существующие примеры временной шкалы описывают выключенную опцию. Для включённого режима добавляйте выбранную задержку к каждой паузе повтора, а не к первому соединению или каждому кадру данных.
|
||||
|
||||
Политика меняет только уже предусмотренные паузы перед повтором. Более строгие ограничения отдельных вызовов сохраняются: обычный poll `/down` и вызов `/up` после commit выполняют одну попытку; их replay при восстановлении допускает две. Опция не создаёт новых циклов повторов. Она не продлевает `web.timeouts.bridge_retry_secs` и сроки запуска или восстановления.
|
||||
|
||||
## Ориентировочная временная шкала
|
||||
|
||||
**Поясняющая модель, а не бенчмарк и не норматив задержки.** Числа подобраны, чтобы показать сложение этапов. Они не восстанавливают наблюдавшиеся 1000–1500 мс. Условия примера: DNS уже закеширован, RTT от клиента до фронтенда — 40 мс, TCP-соединение новое, при необходимости выполняется полный TLS 1.3 handshake, ключ авторизации DC уже есть, потерь и сброса нативной временной метки запроса нет. Базовый вариант — Classic/DD. Для EE собственная подготовка FakeTLS добавляется до нативного таймера.
|
||||
|
||||
В этом примере подготовка обычного MTProxy занимает 40 мс на TCP. Подготовка WEB занимает 750 мс: 50 мс на запуск клиента/моста + 40 мс TCP + 40 мс TLS + 120 мс HTTP-обмена загрузки моста/создания сессии + 500 мс ожидания Android checker. Здесь выбраны последовательные длительности; в действительности этапы могут перекрываться. Начальный TLS и ожидание 500 мс находятся вне отображаемого ping.
|
||||
|
||||
Диаграмма начинается с **последней временной метки запроса** каждой проверки, а не с запуска приложения или первой попытки соединения. Горизонтальная ось показывает секунды с точностью до миллисекунд (0.200 = 200 мс). Ширина полос пропорциональна длительности. Каждая секция — отдельный сценарий; его этапы выполняются последовательно, а не параллельно. Начальная подготовка остаётся за пределами диаграммы.
|
||||
|
||||
```mermaid
|
||||
%%{init: {"theme": "neutral", "gantt": {"leftPadding": 200, "rightPadding": 100, "barHeight": 24, "barGap": 8, "fontSize": 14, "sectionFontSize": 14}}}%%
|
||||
gantt
|
||||
dateFormat x
|
||||
axisFormat %S.%L
|
||||
tickInterval 100millisecond
|
||||
todayMarker off
|
||||
title Отображаемый ping - jitter выключен
|
||||
accTitle: Отображаемый ping - jitter выключен
|
||||
accDescr: Секунды от метки запроса, подписи этапов в миллисекундах
|
||||
section Classic/DD - 100 мс
|
||||
R 100 мс :n_r, 0, 100ms
|
||||
section WEB без ошибок - 200 мс
|
||||
U 40 мс :w_u, 0, 40ms
|
||||
R 100 мс :w_r, after w_u, 100ms
|
||||
D 60 мс :w_d, after w_r, 60ms
|
||||
section WEB с повтором - 490 мс
|
||||
F 40 мс :crit, f_u, 0, 40ms
|
||||
Ожидание 250 мс :crit, retry_wait, after f_u, 250ms
|
||||
U 40 мс :retry_u, after retry_wait, 40ms
|
||||
R 100 мс :retry_r, after retry_u, 100ms
|
||||
D 60 мс :retry_d, after retry_r, 60ms
|
||||
```
|
||||
|
||||
Длительности этапов: `R` = 100 мс базовой работы MTProxy relay/сети/DC для запроса и ответа. `U` = 40 мс дополнительной работы WEB на отправке/OPEN/клиенте. `D` = 60 мс дополнительной работы WEB на приёме и доставке. `F` = 40 мс одной неудачной попытки upload. `Ожидание` = 250 мс ожидания по `X-Telemt-Retry-After-Ms: 250`. `U` и `D` — условные дополнительные затраты сверх `R`, а не повторный учёт полного сетевого RTT. Ожидание ACK/commit учитывается лишь в той мере, в какой оно действительно задержало доставку.
|
||||
|
||||
| Сценарий | До таймера ping | Отображаемый ping | Полное время проверки в модели |
|
||||
| --- | --- | --- | --- |
|
||||
| Classic/DD | 40 мс | 100 мс | 140 мс |
|
||||
| WEB без ошибок | 750 мс | 40 + 100 + 60 = 200 мс | 950 мс |
|
||||
| WEB с одной неудачной загрузкой и одним ожиданием повтора | 750 мс | 40 + 250 + 40 + 100 + 60 = 490 мс | 1240 мс |
|
||||
| WEB, тот же повтор с uniform jitter 0–250 мс | 750 мс | 490–740 мс | 1240–1490 мс |
|
||||
|
||||
Ещё одно TCP + TLS 1.3 соединение, открытое **внутри** замера, могло бы добавить здесь около 80 мс при полностью последовательном выполнении: замер 200 мс превратился бы в 280 мс. При переиспользовании соединения затраты на этот дополнительный handshake равны нулю. Замена начального полного TLS 1.3 handshake на TLS 1.2 при этих условиях добавляет примерно 40 мс к подготовке, а не к показанному ping. В примерах не учтены обработка TLS, возобновление сессии и потери пакетов.
|
||||
|
||||
Строка с 490 мс и диаграмма показывают один повтор при выключенном jitter. Дополнительная строка таблицы применяет к тому же повтору `enabled = true`, `min_ms = 0`, `max_ms = 250`, `distribution = "uniform"`; её диапазон получен из модели, а не измерений. Прежний JavaScript-мост без миллисекундного расширения или посредник, удаляющий эту подсказку при выключенном jitter, сохраняет стандартную секундную паузу: отображаемый ping в той же модели составит 1240 мс. Ни один сценарий не устанавливает причину исходного наблюдения. Если повторы не подтверждены трассировкой, ищите другие задержки: очереди, буферизацию фронтенда, открытие соединений или upstream. Не подставляйте таймауты вместо пауз и не переносите перекрывающиеся этапы в эту последовательную модель без проверки.
|
||||
|
||||
## HTTP, WebSocket и другие источники задержки
|
||||
|
||||
Ответы Telemt при перегрузке содержат `Retry-After: 1` и `X-Telemt-Retry-After-Ms: 250`. Только статус `503` с этой точной парой заголовков задаёт сгенерированному мосту **базовую паузу 250 мс**. При `web.retry_jitter.enabled = false` пауза равна 250 мс; при включении добавляется настроенная случайная задержка. Для остальных ответов действуют стандартная обработка `Retry-After` или резервный backoff, описанные ниже. Ранее загруженные страницы JavaScript-моста без поддержки миллисекундной подсказки используют секундную паузу до загрузки новой страницы; обновлять приложение Telegram для этого не нужно. Лимиты попыток, абсолютные бюджеты, отмена и ограничения admission не меняются.
|
||||
|
||||
| Фактор | Влияние и подтверждение |
|
||||
| --- | --- |
|
||||
| HTTP uplink | Генерируемый мост предлагает `X-Telemt-Up-Window: 4`; сервер принимает 1–4, при отсутствии согласования используется 1. Окно 1 ждёт ACK перед следующей загрузкой, окно 4 допускает ограниченный параллелизм. Не весь HTTP работает по схеме «отправить и ждать». См. [согласование][runtime] и [обработчик сессии][session]. |
|
||||
| Первый downlink | `/down` может запускаться одновременно с `/up`; обязательного дополнительного последовательного ACK RTT нет. Первичная доставка в нативный клиент ждёт первого корректного upload ACK/commit. Кадры доставляются по мере поступления. См. [conveyor][conveyor] и [downlink][downlink]. |
|
||||
| Long polling | `long_poll_secs=25` ограничивает ожидание при отсутствии данных. Готовые данные немедленно будят poll. Промежутки между запросами и занятые слоты соединений браузера всё же могут задержать доставку. См. [серверный polling][poll]. |
|
||||
| Общие ресурсы транспорта | `https` использует общую очередь загрузки; `https-lanes` разделяет логические линии. WebSocket после Upgrade передаёт кадры без POST на каждый кадр; `websocket-lanes` разделяет сокеты. Сеть, flow control и ресурсы WebView остаются общими. HTTP/2 мультиплексирует потоки, но не устраняет все задержки от перегрузки и flow control. См. [HTTP/2][http2] и [руководство по транспортам](WEB_PROXY.ru.md). |
|
||||
| Буферизация фронтенда | Буферизация запросов/ответов или отсутствие поддержки streaming/Upgrade могут задерживать короткие сообщения. Сверьте настройки с существующим примером NGINX, сохраняя маршрутизацию, аутентификацию и лимиты. |
|
||||
| Планирование клиента | Java accept/read, UI dispatch, WebView/JavaScript и возврат в нативный код добавляют очереди. Нагрузка CPU, энергосбережение и смена мобильной сети могут усиливать задержки. |
|
||||
| Пересылка и сеть | Могут учитываться оставшийся admission потока, внутренний MTProxy-handshake, подключение Direct или регистрация ME, ответ Telegram, потери/повторная передача и очереди. Готовая WEB-сессия не доказывает готовность upstream. |
|
||||
| Ошибки и повторы | Повторяемые статусы: 408/429/502/503/504. При выключенном jitter точная подсказка Telemt задаёт паузу 250 мс; без положительной подсказки сервера backoff начинается с 250 мс и удваивается до базовых 2000 мс плюс прежний jitter менее 25%. При включённом jitter пауза равна положительной подсказке сервера или этой базе **плюс** настроенная случайная добавка, заменяющая прежний jitter. Бюджеты и ограничения попыток отдельных вызовов сохраняются. Фиксируйте политику загруженного моста и фактическое время повторов. См. [ответы][response] и [повторы][request]. |
|
||||
|
||||
Дедлайны не являются обязательными паузами. Стандартные 10 с для запроса моста, 90 с бюджета повторов, 30 с ожидания первого байта потока и 10 с handshake потока нельзя складывать в обычный ping. `carrier_probe_coalesce_ms=0` отключает соответствующую дополнительную задержку объединения проб. Дедлайны переключения транспорта относятся к неудачным попыткам, а не к каждому успешному обмену. См. [значения по умолчанию](../../src/config/types/web/defaults.rs).
|
||||
|
||||
Условно WEB-замер включает **оставшуюся подготовку + передачу через транспорт и сеть + очереди + ответ Telegram + задержки повторов, попавшие внутрь таймера**. Этапы перекрываются; складывать все таймауты или назначать отдельный RTT каждому HTTP endpoint некорректно. Готовый транспорт может сократить подготовку, но Android проверяет прокси через отдельный транспорт. WebSocket не всегда быстрее; используйте только поддерживаемые клиентом транспорты. Для совместимости с текущим iOS используется `https`.
|
||||
|
||||
## Диагностика с сохранением защит
|
||||
|
||||
1. Запишите клиент/сборку, версию Android WebView, политику `web.retry_jitter` загруженного моста, транспорт, публичный endpoint, семейство IP, сеть, маршрут Direct/ME, DC и нагрузку. Сравнивайте при одинаковых условиях. Учитывайте двухминутное кеширование Android: повторное чтение интерфейса не означает новый замер.
|
||||
2. Разделяйте три эксперимента: новую проверку в списке прокси; новый логический поток на готовом транспорте; прикладной RPC в установленной MTProto-сессии. Последние два требуют подходящих средств измерения в клиенте и не предоставляются автоматически списком прокси. Собирайте отдельные замеры и распределения, а не сравнивайте единичный холодный замер с прогретым.
|
||||
3. Используйте аутентифицированный `GET /web-status` и существующие настройки `[web.debug]`: `capture_timings=true`, `capture_frames=true`, `body_capture="metadata"`. Включите ограниченный сбор по [руководству диагностики WEB](WEB_PROXY.ru.md), затем восстановите предыдущее состояние. Payload, capabilities и секреты для этой задачи не нужны.
|
||||
4. Сопоставьте создание сессии, выбор/commit/ошибку транспорта, `stream_admitted`, `stream_first_byte`, `handshake_succeeded`, OPEN/DATA, HTTP-статусы и повторы. `relay_started` предшествует работе с upstream и не означает готовность DC. `GET /v1/runtime/web/status` и `GET /v1/runtime/web/sessions` дают контекст ёмкости и давления очередей, а не сквозной RTT.
|
||||
5. `request_body_us`, `response_ready_us` и `response_body_us` — смещения от входа в обработчик. Это не независимые длительности для сложения и не моменты отправки в сеть или TCP ACK от другой стороны. Сравнивайте смещения там, где они записаны и имеют подходящий смысл. См. [определения timing-полей][timings].
|
||||
6. Добавьте измерения соединений/TLS/запросов фронтенда и временные метки клиента, чтобы найти задержку вне Telemt. Проверьте повторное использование соединений, согласованный HTTP, буферизацию и Upgrade. Sideband-события запуска моста/HELLO не дают полную временную шкалу клиента. Для сравнения разных хостов синхронизируйте часы либо используйте локальные длительности.
|
||||
7. При ME сопоставьте существующий trace `ME RTT sample` (`rtt_ms`, `ema_ms`, `base_ms`, `degraded`). Метка ставится до очереди writer/flush; EMA состоит из 80% прежнего значения и 20% нового замера. Планирование keepalive до этой метки не учитывается. Низкий ME RTT при высоком Android ping указывает на работу вне измеренного участка ME, но не определяет конкретную причину. См. [writer][writer] и [reader][reader].
|
||||
|
||||
Примеры интерпретации: быстрая обработка Telemt при поздней доставке клиенту направляет проверку к фронтенду, сети и очередям клиента; `503` и его retry-заголовки определяют базовую задержку, а политика jitter загруженного моста и клиентские отметки времени позволяют установить фактическую паузу; длительная работа upstream требует изучения Direct/ME. Ни один из признаков сам по себе не доказывает, что 1000–1500 мс вызваны криптографией TLS. При сборе данных сохраняйте совместимость, проверку сертификатов, лимиты admission и backpressure.
|
||||
|
||||
## Границы подтверждения
|
||||
|
||||
Документ описывает изученные исходники, а не сквозной тест на устройствах. Ссылки Android/iOS закрепляют указанные ревизии; ссылки Telemt ведут к сопровождающей документ реализации рабочего дерева, включая локальные WEB-изменения, и не утверждают идентичность всех опубликованных пакетов. Документация не меняет клиент, сервер, таймауты или настройки безопасности.
|
||||
|
||||
[android-entry]: https://github.com/DrKLO/Telegram/blob/3de37c8cfb039452be7398909461da6288babf15/TMessagesProj/src/main/java/org/telegram/tgnet/ConnectionsManager.java#L752-L765
|
||||
[android-tester]: https://github.com/DrKLO/Telegram/blob/3de37c8cfb039452be7398909461da6288babf15/TMessagesProj/src/main/java/org/telegram/utils/proxy/WebProxyConnectionTester.java#L111-L172
|
||||
[android-transport]: https://github.com/DrKLO/Telegram/blob/3de37c8cfb039452be7398909461da6288babf15/TMessagesProj/src/main/java/org/telegram/utils/proxy/WebProxyTransport.java
|
||||
[android-native]: https://github.com/DrKLO/Telegram/blob/3de37c8cfb039452be7398909461da6288babf15/TMessagesProj/jni/tgnet/ConnectionsManager.cpp
|
||||
[android-socket]: https://github.com/DrKLO/Telegram/blob/3de37c8cfb039452be7398909461da6288babf15/TMessagesProj/jni/tgnet/ConnectionSocket.cpp
|
||||
[android-key]: https://github.com/DrKLO/Telegram/blob/3de37c8cfb039452be7398909461da6288babf15/TMessagesProj/jni/tgnet/Datacenter.cpp#L1312-L1323
|
||||
[android-ui]: https://github.com/DrKLO/Telegram/blob/3de37c8cfb039452be7398909461da6288babf15/TMessagesProj/src/main/java/org/telegram/ui/ProxyListActivity.java#L671-L687
|
||||
[ios-filter]: https://github.com/TelegramMessenger/Telegram-iOS/blob/279f89e4d4f63f17227bf877dc3d8990f22ecd58/submodules/TelegramCore/Sources/Network/ProxyServersStatuses.swift#L54-L65
|
||||
[ios-probe]: https://github.com/TelegramMessenger/Telegram-iOS/blob/279f89e4d4f63f17227bf877dc3d8990f22ecd58/submodules/MtProtoKit/Sources/MTProxyConnectivity.m#L57-L99
|
||||
[ios-ui]: https://github.com/TelegramMessenger/Telegram-iOS/blob/279f89e4d4f63f17227bf877dc3d8990f22ecd58/submodules/SettingsUI/Sources/Data%20and%20Storage/ProxyListSettingsController.swift#L273-L310
|
||||
[tls13]: https://datatracker.ietf.org/doc/html/rfc8446#section-2
|
||||
[tls12]: https://datatracker.ietf.org/doc/html/rfc5246#section-7.3
|
||||
[http1]: https://www.rfc-editor.org/rfc/rfc9112#section-9.3
|
||||
[http2]: https://datatracker.ietf.org/doc/html/rfc9113#section-5
|
||||
[session]: ../../src/web/http/session.rs
|
||||
[backend]: ../../src/web/session/backend.rs
|
||||
[runtime]: ../../src/web/bridge/runtime.js
|
||||
[conveyor]: ../../src/web/bridge/conveyor.js
|
||||
[downlink]: ../../src/web/bridge/downlink.js
|
||||
[poll]: ../../src/web/session/downlink.rs
|
||||
[request]: ../../src/web/bridge/request.js
|
||||
[response]: ../../src/web/http/response.rs
|
||||
[timings]: ../../src/web/trace/types.rs
|
||||
[writer]: ../../src/transport/middle_proxy/pool_writer.rs
|
||||
[reader]: ../../src/transport/middle_proxy/reader.rs
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
[English](WEB_PROXY.en.md) | [Русский](WEB_PROXY.ru.md) | [Deutsch](WEB_PROXY.de.md)
|
||||
|
||||
[Ping in der Proxyliste, RPC Ping/Pong und WEB-Latenz](PROXY_PING.de.md)
|
||||
|
||||
Der WEB-Modus transportiert gewöhnliche MTProxy-Streams über begrenzte HTTPS- oder WebSocket-Carrier, die mit dem Proxy-Typ `WEB` von Telegram Desktop kompatibel sind. Telemt terminiert TLS nicht selbst: NGINX, HAProxy oder Caddy verwaltet das öffentliche Zertifikat und leitet unverschlüsseltes HTTP/1.1 an einen privaten Telemt-Listener weiter.
|
||||
|
||||
> [!IMPORTANT]
|
||||
@@ -40,7 +42,7 @@ Leiten Sie den vollständigen konfigurierten WEB-Bereich an Telemt weiter. Beim
|
||||
|
||||
- Bei leerem `base_path` lautet der öffentliche Endpunkt `https://HOST:443/`, andernfalls `https://HOST:443/BASE/`. Der Basispfad ist groß-/kleinschreibungssensitiv und exakt; Telemt leitet ihn nicht um, normalisiert ihn nicht und entfernt ihn nicht vor der Decoy-Weiterleitung.
|
||||
- Unterstützt werden 16-Byte-MTProxy-Secrets in den Modi `plain` und `dd`. FakeTLS-Secrets mit `ee` werden im WEB-Modus nicht unterstützt.
|
||||
- `web.carrier` wählt den einzigen Carrier bei deaktivierter Auto-Negotiation und den letzten Fallback bei aktivierter Negotiation. `https` verwendet serialisierte HTTPS-Uplinks und Long Polling. `https-lanes` verwendet unabhängige HTTPS-Sequenzen und Polls pro logischem Stream. `websocket` verwendet einen geordneten WebSocket für alle Streams. `websocket-lanes` verwendet einen unabhängig verwalteten WebSocket für jeden logischen Stream ungleich null.
|
||||
- `web.carrier` wählt den einzigen Carrier bei deaktivierter Auto-Negotiation und den letzten Fallback bei aktivierter Negotiation. `https` verwendet eine gemeinsame HTTPS-Uplink-Sequenz und Long Polling. `https-lanes` verwendet unabhängige HTTPS-Sequenzen und Polls pro logischem Stream. `websocket` verwendet einen geordneten WebSocket für alle Streams. `websocket-lanes` verwendet einen unabhängig verwalteten WebSocket für jeden logischen Stream ungleich null.
|
||||
- Ein fehlendes `web.carriers` oder `web.carriers = false` deaktiviert Auto-Negotiation und Lernen. Ein nicht leeres Array aktiviert ausschließlich die sequenzielle Start-Negotiation; eine bereits festgeschriebene Sitzung wird nie migriert.
|
||||
- Native Clients ohne kanonische Carrier-Negotiation-Header verwenden den konfigurierten festen `carrier`, auch wenn `carriers` die Negotiation für fähige Clients aktiviert. Das aktuelle Telegram iOS unterstützt nur `https`; für metadatafreies iOS muss der Betreiber daher `web.carrier = "https"` setzen, `https-lanes` wird nicht unterstützt. User-Agent-Werte einschließlich CFNetwork oder Darwin leiten niemals Capabilities ab. Sendet ein nativer iOS-Client explizite Negotiation-Metadaten, schneidet Telemt sie mit der serverautoritativen Obergrenze `{https}` und lehnt ein leeres Ergebnis ab; andere explizite Clients verwenden ihren angegebenen Capability-Satz.
|
||||
- Capability-, Bootstrap- und Session-Zugangsdaten sind getrennte Werte mit begrenzter Lebensdauer. Carrier-Zugangsdaten sind geheim und dürfen nicht in Access-Logs erscheinen.
|
||||
@@ -314,9 +316,11 @@ Versuche laufen streng sequenziell. Akzeptierter `OPEN`- oder `DATA`-Fortschritt
|
||||
|
||||
Nach dem Commit wiederholt ein HTTP-Fehler zunächst den exakten unveränderlichen Request mit dem aktuellen Bearer. Ein erfolgreicher Replay behält die aktuelle Sitzung. WebSocket-Verlust oder ein Foreground-, Online- oder natives Ereignis nach mindestens `reconnect_grace_secs` Scheduler-Lücke startet eine Recovery-Epoche. Die Bridge sendet genau einen GET an ihren ursprünglichen konfigurierten Basis-Root mit `bridge=<capability>`, `Accept: application/vnd.telemt.web-recovery+json` und optionaler aktueller Bearer-Authorization. Eine positive Antwort ist ein nicht cachebares JSON-Dokument mit höchstens 1024 Bytes, einem frischen Bootstrap und den aktuellen Limits, Timeouts sowie der Negotiation-Richtlinie. Telemt gibt diesen Bootstrap aus, bevor eine passende aktuelle Sitzung synchron beendet wird, sodass eine Neuerstellung auch bei Kapazität für nur eine Sitzung möglich bleibt. Unbekannte oder bereits beendete Bearer erhalten dieselbe positive Repräsentation; fehlerhafte Recovery-Header sowie deaktivierte Admission, Pause, Drain und Kapazitätsablehnung folgen dem bereinigten Decoy-Pfad.
|
||||
|
||||
Die Recovery-Epoche besitzt eine gemeinsame absolute Wall-/Monotonic-Deadline `bridge_recovery_secs`, genau einen Request für das Recovery-Dokument und begrenzte Carrier-Wiederholungen mit Backoff von 250 ms bis 2 s. Während der Recovery wird der Status höchstens alle 2,5 Sekunden wiederholt. Eine frische Inkarnation bricht alte Requests, Sockets, Lanes und Queues ab und gibt sie frei, sendet für jeden noch aktiven nativen Stream genau ein synthetisches `CLOSE`, unterdrückt ein zweites `WELCOME` und committed erst nach echtem Carrier-Fortschritt. Beendete Stream-IDs bleiben in einer begrenzten Menge, damit gültige verspätete Frames nicht in einen neuen Stream gelangen; die native Seite muss eine neue Stream-ID vergeben. Häufige native Reconnect-Versuche sind zulässig, verlängern aber weder die Recovery-Epoche noch halten sie alten Inkarnationszustand. Das Zerstören der WebView zerstört auch diesen Recovery-Owner; ein nativer Supervisor muss danach ein neues Bridge-Dokument erzeugen.
|
||||
Die Recovery-Epoche besitzt eine gemeinsame absolute Wall-/Monotonic-Deadline `bridge_recovery_secs`, genau einen Request für das Recovery-Dokument und begrenzte Carrier-Wiederholungen mit einer Backoff-Basis von 250 ms bis 2 s ohne Serverhinweis, unter Berücksichtigung von Serverhinweisen und der Jitter-Richtlinie der Seite. Während der Recovery wird der Status höchstens alle 2,5 Sekunden wiederholt. Eine frische Inkarnation bricht alte Requests, Sockets, Lanes und Queues ab und gibt sie frei, sendet für jeden noch aktiven nativen Stream genau ein synthetisches `CLOSE`, unterdrückt ein zweites `WELCOME` und committed erst nach echtem Carrier-Fortschritt. Beendete Stream-IDs bleiben in einer begrenzten Menge, damit gültige verspätete Frames nicht in einen neuen Stream gelangen; die native Seite muss eine neue Stream-ID vergeben. Häufige native Reconnect-Versuche sind zulässig, verlängern aber weder die Recovery-Epoche noch halten sie alten Inkarnationszustand. Das Zerstören der WebView zerstört auch diesen Recovery-Owner; ein nativer Supervisor muss danach ein neues Bridge-Dokument erzeugen.
|
||||
|
||||
Jede reguläre HTTP-Carrier-Operation der Bridge besitzt ein absolutes Budget `bridge_retry_secs` und höchstens neun Versuche. `bridge_request_secs` umfasst sowohl den Fetch-Response-Head als auch das vollständige Lesen des Response-Bodys; ein Downlink-Versuch erhält zusätzlich das konfigurierte Long-Poll-Intervall. Netzwerkfehler und Antworten mit `408`, `429`, `502`, `503` oder `504` verwenden begrenzten exponentiellen Backoff, während `Retry-After` das absolute Budget nicht verlängern kann. `carrier_probe_coalesce_ms = 0` sendet den ersten geordneten `OPEN`-Probe sofort. Ein Wert bis 10 ms kann passendes `DATA` aus diesem Fenster aufnehmen; multiplexierte Carrier bewahren die vollständige vorhergehende Frame-Reihenfolge, Lane-Carrier beanspruchen nur die ausgewählte Lane. Vor der Probe-Bestätigung startet kein HTTP-Downlink. Ein multiplexierter WebSocket-Upgrade kann unmittelbar nach seiner Auswahl durch `/session` beginnen und danach eingereihte Probe-Daten aufnehmen; ein Lane-WebSocket wartet auf die bekannte Stream-ID.
|
||||
Überlastungsantworten von Telemt enthalten `Retry-After: 1` und `X-Telemt-Retry-After-Ms: 250`. Nur Status `503` mit diesem exakten Header-Paar legt in der generierten Bridge eine **Basispause von 250 ms** fest. Bei `web.retry_jitter.enabled = false` beträgt die Pause 250 ms; bei aktiviertem Jitter kommt der konfigurierte zufällige Zuschlag hinzu. Andere Antworten verwenden die unten beschriebene Standardbehandlung von `Retry-After` oder den Backoff ohne Serverhinweis. Frühere JavaScript-Bridge-Seiten ohne Unterstützung des Millisekundenhinweises verwenden bis zum Laden einer neuen Seite die Sekundenpause; ein Update der Telegram-App ist dafür nicht erforderlich. Versuchslimits, absolute Budgets, Abbruchverhalten und Zulassungsgrenzen bleiben unverändert.
|
||||
|
||||
Jede reguläre HTTP-Carrier-Operation der Bridge besitzt ein absolutes Budget `bridge_retry_secs` und höchstens neun Versuche. `bridge_request_secs` umfasst sowohl den Fetch-Response-Head als auch das vollständige Lesen des Response-Bodys; ein Downlink-Versuch erhält zusätzlich das konfigurierte Long-Poll-Intervall. Netzwerkfehler und Antworten mit `408`, `429`, `502`, `503` oder `504` verwenden einen positiven Serverhinweis oder exponentiellen Backoff mit der jeweiligen Jitter-Richtlinie; `Retry-After` kann das absolute Budget nicht verlängern. `carrier_probe_coalesce_ms = 0` sendet den ersten geordneten `OPEN`-Probe sofort. Ein Wert bis 10 ms kann passendes `DATA` aus diesem Fenster aufnehmen; multiplexierte Carrier bewahren die vollständige vorhergehende Frame-Reihenfolge, Lane-Carrier beanspruchen nur die ausgewählte Lane. Der HTTP-Downlink kann parallel zum ersten Upload starten; die native Zustellung wartet auf dessen erste gültige ACK/Commit-Bestätigung. Ein multiplexierter WebSocket-Upgrade kann unmittelbar nach seiner Auswahl durch `/session` beginnen und danach eingereihte Probe-Daten aufnehmen; ein Lane-WebSocket wartet auf die bekannte Stream-ID.
|
||||
|
||||
Response-Bodys werden innerhalb expliziter Endpunktgrenzen gestreamt: `/session` enthält exakt acht Bytes, ein erfolgreicher `/down` höchstens `carrier_batch_bytes`, und bodylose Antworten akzeptieren null Bytes. Deklarierter Überlauf wird vor dem Lesen abgelehnt; ein Überlauf beim Streaming oder zu viele Chunks bricht den Reader ab, und Bodys wiederholbarer Antworten werden vor dem Backoff verworfen. Die terminale Bridge-Bereinigung sendet höchstens ein authentifiziertes `DELETE`. Kanonische Transportfehler werden für Diagnosen nach `X-Carrier-Failure` kopiert, Navigation und explizites Schließen bleiben nicht lernende Gründe.
|
||||
|
||||
@@ -326,7 +330,7 @@ Ein festgeschriebener Versuch wird erst healthy, wenn transportspezifische bidir
|
||||
|
||||
Das Lernen ist prozesslokal, speicherresident, ausschließlich positiv und durch `max_carrier_learning_entries` begrenzt. Es sortiert nur vom Client unterstützte konfigurierte Kandidaten, hält den konfigurierten Fallback stets zuletzt und bewahrt bei gleichen Scores die Konfigurationsreihenfolge. User-Agent- und Profilevidenz haben Primärgewicht; eine zulässige IP dient nur als Tie-Breaker. IP-Evidenz erfordert genau eine explizite, global routbare `X-Forwarded-For`-Adresse; private, Loopback-, Link-Local-, Carrier-Grade-NAT-, Dokumentations-, Multicast- und entsprechende IPv4-Mapped-Adressen sind ausgeschlossen. Vom Client gemeldete Fehlerkategorien und Request-Latenz sind ausschließlich diagnostisch und erzeugen weder negative noch Ranking-Evidenz. `conservative` erfordert 3 User-Agent-Ergebnisse oder 8 Profilergebnisse aus 4 Kohorten und deaktiviert IP-Evidenz; `balanced` verwendet 2, 6 aus 3 Kohorten und 3 zulässige IP-Ergebnisse; `aggressive` verwendet 1, 4 aus 2 Kohorten und 1 IP-Ergebnis. Ein Generationswechsel mit identischer Learning-Semantik bewahrt die Evidenz und veröffentlicht deren Generation-Fence atomar neu. Das Deaktivieren des Learnings oder eine Änderung von Aggressiveness, Evidenz-Lebensdauer oder Health-Fenster erhöht die Evidenz-Epoche und trennt inkompatiblen Zustand ab; veraltete Ergebnisse können ihn nicht erneut füllen.
|
||||
|
||||
`https` bleibt der Default und behält das ursprüngliche serialisierte Verhalten bei. Bei `https-lanes` ist Lane null für Session-Steuerung reserviert, und jeder logische Stream ungleich null erhält eine eigene Lane. Jede Lane besitzt eigene Uplink-Sequenzen, Retry-Digests, Downlink-Cursor, nicht bestätigte Replay-Batches, Queues und einen Newest-Poll-Wins-Lebenszyklus. Ein langsamer Stream blockiert daher keinen anderen Stream auf der WEB-Protokollebene.
|
||||
`https` bleibt der Default. Das Upload-Fenster wird zwischen 1 und 4 ausgehandelt; die generierte Bridge bietet `X-Telemt-Up-Window: 4` an, während Fenster 1 serielle Uploads beibehält. Bei `https-lanes` ist Lane null für Session-Steuerung reserviert, und jeder logische Stream ungleich null erhält eine eigene Lane. Jede Lane besitzt eigene Uplink-Sequenzen, Retry-Digests, Downlink-Cursor, nicht bestätigte Replay-Batches, Queues und einen Newest-Poll-Wins-Lebenszyklus. Ein langsamer Stream blockiert daher keinen anderen Stream auf der WEB-Protokollebene.
|
||||
|
||||
Damit entfällt die Serialisierung zwischen WEB-Streams auf Anwendungsebene. Öffentliches HTTP/2 läuft weiterhin über eine oder mehrere TCP-Verbindungen, sodass Paketverlust Head-of-Line-Blocking auf Transportebene verursachen kann; `https-lanes` ist kein HTTP/3- oder QUIC-Carrier.
|
||||
|
||||
@@ -361,6 +365,30 @@ Statische Dateien werden beim Start und bei einem erfolgreichen Konfigurations-R
|
||||
|
||||
Alle WEB-Schlüssel und Defaults sind in der [Konfigurationsreferenz](../Config_params/CONFIG_PARAMS.de.md#web) aufgeführt.
|
||||
|
||||
### Konfigurierbarer Jitter für HTTP-Wiederholungen
|
||||
|
||||
`[web.retry_jitter]` ergänzt jeden bestehenden HTTP-Retry der Bridge um eine unabhängig gewählte Verzögerung: Netzwerkfehler und Antworten mit 408/429/502/503/504. Telegram-Anwendungen müssen nicht geändert werden. Ohne diesen Abschnitt oder mit `enabled = false` bleiben der 250-ms-Hinweis von Telemt und das bisherige Backoff/Jitter-Verhalten erhalten.
|
||||
|
||||
```toml
|
||||
[web.retry_jitter]
|
||||
enabled = true
|
||||
min_ms = 0
|
||||
max_ms = 250
|
||||
distribution = "uniform"
|
||||
# Only for distribution = "triangular":
|
||||
# peak_ms = 125
|
||||
```
|
||||
|
||||
Der Bereich beschreibt einen **Zuschlag**, nicht die gesamte Pause: Zusammen mit dem Telemt-Hinweis von 250 ms ergibt dieses Beispiel 250–500 ms. Ohne positiven Serverhinweis bleibt die Basis bei 250, 500, 1000, dann 2000 ms. Aktivierter Jitter ersetzt den bisherigen Jitter von bis zu 25%. Ein gültiger standardmäßiger `Retry-After` wird im aktivierten Modus nicht auf die bisherige Grenze von 30 Sekunden verkürzt. Übersteigt die Pause das verbleibende Operationsbudget, läuft das Budget ohne vorzeitigen Retry ab.
|
||||
|
||||
Standardwerte: `enabled = false`, `min_ms = 0`, `max_ms = 250`, `distribution = "uniform"`, ohne `peak_ms`. Es gilt `0 <= min_ms <= max_ms <= 30000`. `uniform` verteilt ganze Millisekunden gleichmäßig; `triangular` verwendet eine Dreiecksverteilung mit Rundung auf Millisekunden. Der optionale Gipfel liegt standardmäßig in der Mitte und muss innerhalb des Intervalls liegen. Ein expliziter Gipfel bei `uniform`, unbekannte Schlüssel/Verteilungen und ungültige Grenzen werden auch im deaktivierten Zustand abgelehnt. Gleiche Grenzen ergeben einen konstanten Zuschlag.
|
||||
|
||||
Die Richtlinie wird pro Bridge-Seite festgeschrieben. Konfigurations-/API-Reload wirkt auf neu geladene Seiten; bestehende Seiten behalten ihre Einstellungen bei Recovery. Recovery-JSON und HTTP-Kompatibilitätsheader bleiben unverändert. Die Auswahl bevorzugt `crypto.getRandomValues`, mit `Math.random` als Kompatibilitätsfallback. Erfolgreicher Datenverkehr wird nicht verzögert. Versuchslimits, absolute Budgets, Abbruch und unveränderte Payload-/Sequence-Wiederholung bleiben erhalten; längere Pausen können die Anzahl der Versuche innerhalb eines Startup-/Recovery-Budgets reduzieren.
|
||||
|
||||
Dies streut feste Retry-Intervalle, garantiert aber keinen Schutz vor DPI. Browser-Scheduling, Netzwerkwarteschlangen und andere Protokollzeiten bleiben beobachtbar. Bestehende Zeitleisten zeigen den deaktivierten Standardmodus. Bei aktiviertem Modus wird zu jeder Retry-Pause eine gezogene Verzögerung addiert, nicht zum ersten Verbindungsaufbau oder zu jedem Datenframe.
|
||||
|
||||
Die Richtlinie ändert nur bereits vorhandene Retry-Pausen. Strengere Limits einzelner Aufrufe bleiben erhalten: Reguläre `/down`-Polls und `/up`-Aufrufe nach dem Commit führen einen Versuch aus; ihr Recovery-Replay erlaubt zwei. Die Option erzeugt keine neuen Retry-Schleifen. Sie verlängert weder `web.timeouts.bridge_retry_secs` noch Start- oder Recovery-Deadlines.
|
||||
|
||||
## TLS-Terminierung mit NGINX
|
||||
|
||||
```nginx
|
||||
@@ -508,9 +536,10 @@ Tragen Sie in `web_trusted_proxy_cidrs` die Adresse ein, von der aus Caddy Telem
|
||||
| Bestand der WEB-Listener, Bind-Adresse und Vertrauensrichtlinie | Prozesseigen; Telemt neu starten. |
|
||||
| `web.allow_wildcard_hosts` und jeder Wert in `[web.limits]` | Prozesseigener Speicher- und Ressourcenvertrag; Telemt neu starten. |
|
||||
| `web.enabled`, Carrier-/Negotiation-Richtlinie, `web.debug`, Timeouts, vhosts, Profile und Decoys | Werden vom Config-Watcher oder durch einen Runtime-Generations-Reload angewendet. |
|
||||
| `web.retry_jitter` | Reload gilt nur für neu erzeugte Bridge-Seiten. Geladene Seiten behalten ihre Richtlinie auch bei Recovery; Änderungen erfordern eine neue Seite. |
|
||||
| Änderung des `base_path` eines vhost | Schaltet Routing neuer HTTP-Requests und Capability-Ableitung atomar um. Geben Sie den generierten Link neu aus. Bereits hochgestufte WebSockets und laufende geroutete Austauschvorgänge laufen weiter. Spätere Requests an die alte Basis mit einem prozessauthentischen Bootstrap- oder Session-Token erhalten ein lokales, nicht cachebares `404`; die nun inaktive alte Capability folgt der gewöhnlichen Decoy-Behandlung. Ein bestehender Session-Bearer bleibt nur an der neuen exakten Basis verwendbar, während ein für die alte Capability ausgegebener ungenutzter Bootstrap an der neuen Basis keine Sitzung erstellen kann. |
|
||||
| Operator-Pause/-Drain-Zustand | Prozesseigen und flüchtig; übersteht einen Generations-Reload, schreibt niemals Konfiguration und wird nach einem Prozessneustart auf `running` zurückgesetzt. |
|
||||
| Bestehende HTTP-Verbindungen und WEB-Sitzungen | Behalten HTTP-Idle-Grenze, Carrier-Kandidaten, Grenzen, Body-Timeout, Lebensdauer des Replay-Markers geschlossener Token sowie absolute Session-/Negotiation-Deadlines ihres Erstellungszeitpunkts; jede ausgegebene Bridge enthält ihre Request-, Retry-, Recovery- und Probe-Coalescing-Werte. Eine Recovery-Epoche fixiert ihr aktuelles Bridge-Budget; eine erfolgreiche Recovery-Repräsentation aktualisiert die Richtlinie für spätere Epochen und die frische Sitzung. WebSocket-Upgrade-, Open-, Write-, Backpressure- und Eviction-Vorgänge verwenden die unveränderlichen Deadlines der Parent-Sitzung. Neue Bridges verwenden die aktive Richtlinie, neue logische Streams die aktive Relay-Generation. |
|
||||
| Bestehende HTTP-Verbindungen und WEB-Sitzungen | Behalten HTTP-Idle-Grenze, Carrier-Kandidaten, Grenzen, Body-Timeout, Lebensdauer des Replay-Markers geschlossener Token sowie absolute Session-/Negotiation-Deadlines ihres Erstellungszeitpunkts; jede ausgegebene Bridge enthält ihre Request-, Retry-, Recovery- und Probe-Coalescing-Werte. Eine Recovery-Epoche fixiert ihr aktuelles Bridge-Budget; eine erfolgreiche Recovery-Repräsentation aktualisiert die Richtlinie für spätere Epochen und die frische Sitzung. WebSocket-Upgrade-, Open-, Write-, Backpressure- und Eviction-Vorgänge verwenden die unveränderlichen Deadlines der Parent-Sitzung. Neue Bridges verwenden die aktive Richtlinie, neue logische Streams die aktive Relay-Generation. `web.retry_jitter` und die HTTP-Methode des Carriers bleiben an die Seite gebunden und werden durch Recovery nicht aktualisiert. |
|
||||
| Beenden des Prozesses | Erfasst den zuletzt geladenen Wert von `web.timeouts.shutdown_secs` einmalig und verwendet dieselbe absolute Deadline für Listener-Acceptoren und Verbindungen sowie WEB-Sitzungen und Hilfstasks. Aufeinanderfolgende Komponenten erhalten keine separaten vollständigen Budgets. |
|
||||
|
||||
Jeder logische Stream behält die Client-IP seiner Sitzung und besitzt während der gesamten Relay-Lebensdauer einen prozessweit eindeutigen, von null verschiedenen synthetischen Quellport. Damit bleibt für Direct- und Middle-End-KDF-Routing ein stabiles, kollisionsfreies Quell-/Ziel-Tupel erhalten.
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
[English](WEB_PROXY.en.md) | [Русский](WEB_PROXY.ru.md) | [Deutsch](WEB_PROXY.de.md)
|
||||
|
||||
[Proxy-list ping, RPC Ping/Pong and WEB latency](PROXY_PING.en.md)
|
||||
|
||||
WEB mode carries ordinary MTProxy streams through bounded HTTPS or WebSocket carriers compatible with Telegram Desktop's `WEB` proxy type. Telemt does not terminate TLS: NGINX, HAProxy, or Caddy owns the public certificate and forwards plain HTTP/1.1 to a private Telemt listener.
|
||||
|
||||
> [!IMPORTANT]
|
||||
@@ -40,7 +42,7 @@ Let `BASE` mean `/` for an empty `base_path`, or `/<base_path>/` otherwise. The
|
||||
|
||||
- The public endpoint is `https://HOST:443/` when `base_path` is empty and `https://HOST:443/BASE/` otherwise. The base is case-sensitive and exact; Telemt does not redirect, normalize, or strip it before decoy forwarding.
|
||||
- `plain` and `dd` 16-byte MTProxy secrets are supported. `ee` FakeTLS secrets are not supported by WEB mode.
|
||||
- `web.carrier` selects the sole carrier when auto-negotiation is disabled and the final fallback when it is enabled. `https` uses serialized HTTPS uplink and long polling. `https-lanes` uses independent HTTPS sequencing and polling per logical stream. `websocket` uses one ordered WebSocket for all streams. `websocket-lanes` uses one independently owned WebSocket per non-zero logical stream.
|
||||
- `web.carrier` selects the sole carrier when auto-negotiation is disabled and the final fallback when it is enabled. `https` uses a shared HTTPS uplink sequence and long polling. `https-lanes` uses independent HTTPS sequencing and polling per logical stream. `websocket` uses one ordered WebSocket for all streams. `websocket-lanes` uses one independently owned WebSocket per non-zero logical stream.
|
||||
- Missing `web.carriers` or `web.carriers = false` disables auto-negotiation and learning. A non-empty array enables startup-only sequential negotiation; it never migrates an already committed session.
|
||||
- Native clients without canonical carrier-negotiation headers use the configured fixed `carrier`, even when `carriers` enables negotiation for capable clients. Current Telegram iOS supports only `https`, so an operator serving metadata-free iOS clients must set `web.carrier = "https"`; it does not support `https-lanes`. User-Agent values, including CFNetwork or Darwin, never infer capabilities. When a native iOS request does send explicit negotiation metadata, Telemt intersects it with the server-authoritative `{https}` ceiling and rejects an empty result; other explicit clients use their advertised capability set.
|
||||
- Capability, bootstrap, and session credentials are separate bounded-lifetime values. Carrier credentials must be treated as secrets and must not appear in access logs.
|
||||
@@ -300,9 +302,11 @@ Attempts are strictly sequential. Accepted `OPEN` or `DATA` progress commits the
|
||||
|
||||
After commit, an HTTP failure first replays the exact frozen request against the current bearer. A successful replay keeps the current session. WebSocket loss, or a foreground/online/native event after at least `reconnect_grace_secs` of scheduler gap, starts one recovery epoch. The bridge performs exactly one GET at its original configured base root with `bridge=<capability>`, `Accept: application/vnd.telemt.web-recovery+json`, and optional current bearer authorization. A positive response is an uncacheable JSON document of at most 1024 bytes containing a fresh bootstrap plus current limits, timeouts, and negotiation policy. Telemt issues that bootstrap before synchronously retiring a matching current session, so recreation remains possible with a one-session capacity. Unknown or already retired bearer authorization receives the same positive representation; malformed recovery headers, disabled admission, pause, drain, and capacity rejection follow the sanitized decoy path.
|
||||
|
||||
The recovery epoch has one dual wall/monotonic absolute `bridge_recovery_secs` deadline, a single recovery-document request, and bounded carrier retries with 250 ms through 2 s backoff. Recovery status is repeated at most every 2.5 seconds while active. A fresh incarnation aborts and releases old requests, sockets, lanes, and queues, sends one synthetic `CLOSE` for each still-active native stream, suppresses a second `WELCOME`, and commits only after real carrier progress. Retired stream IDs are retained in a bounded set so valid late frames cannot enter a new stream; the native side must allocate a new stream ID. Frequent native reconnect attempts are valid, but they neither extend the recovery epoch nor retain old incarnation state. Destroying the WebView destroys this recovery owner; a native supervisor must then create a new bridge document.
|
||||
The recovery epoch has one dual wall/monotonic absolute `bridge_recovery_secs` deadline, a single recovery-document request, and bounded carrier retries with a 250 ms through 2 s fallback base, subject to server hints and the page’s jitter policy. Recovery status is repeated at most every 2.5 seconds while active. A fresh incarnation aborts and releases old requests, sockets, lanes, and queues, sends one synthetic `CLOSE` for each still-active native stream, suppresses a second `WELCOME`, and commits only after real carrier progress. Retired stream IDs are retained in a bounded set so valid late frames cannot enter a new stream; the native side must allocate a new stream ID. Frequent native reconnect attempts are valid, but they neither extend the recovery epoch nor retain old incarnation state. Destroying the WebView destroys this recovery owner; a native supervisor must then create a new bridge document.
|
||||
|
||||
Each ordinary bridge carrier HTTP operation has an absolute `bridge_retry_secs` budget and at most nine attempts. `bridge_request_secs` covers both the Fetch response head and complete response body; a downlink attempt additionally receives the configured long-poll interval. Network failures and `408`, `429`, `502`, `503`, or `504` responses use bounded exponential backoff, while `Retry-After` cannot extend the absolute budget. `carrier_probe_coalesce_ms = 0` sends the first ordered `OPEN` probe immediately. A value up to 10 ms may include matching `DATA` that arrives in that window; multiplexed carriers preserve the complete preceding frame order, while lane carriers claim only the selected lane. No HTTP downlink starts before the probe acknowledgement. Multiplexed WebSocket Upgrade may begin as soon as `/session` selects it and then absorbs queued probe data; a lane WebSocket waits until its stream ID is known.
|
||||
Telemt overload responses carry `Retry-After: 1` and `X-Telemt-Retry-After-Ms: 250`. Only status `503` with that exact header pair selects a **250 ms base delay** in the generated bridge. With `web.retry_jitter.enabled = false`, the pause is 250 ms; when enabled, the configured random addition applies. Other responses use the standard `Retry-After` handling or fallback backoff described below. Earlier JavaScript bridge pages without support for the millisecond hint use the one-second fallback until replaced by a newly loaded page; this does not require updating the Telegram application. Attempt limits, absolute budgets, cancellation and admission limits remain unchanged.
|
||||
|
||||
Each ordinary bridge carrier HTTP operation has an absolute `bridge_retry_secs` budget and at most nine attempts. `bridge_request_secs` covers both the Fetch response head and complete response body; a downlink attempt additionally receives the configured long-poll interval. Network failures and `408`, `429`, `502`, `503`, or `504` responses use a positive server hint or exponential fallback backoff, with the applicable jitter policy; `Retry-After` cannot extend the absolute budget. `carrier_probe_coalesce_ms = 0` sends the first ordered `OPEN` probe immediately. A value up to 10 ms may include matching `DATA` that arrives in that window; multiplexed carriers preserve the complete preceding frame order, while lane carriers claim only the selected lane. HTTP downlink can start alongside the first upload; native delivery waits for the first valid upload ACK/commit. Multiplexed WebSocket Upgrade may begin as soon as `/session` selects it and then absorbs queued probe data; a lane WebSocket waits until its stream ID is known.
|
||||
|
||||
Response bodies are streamed into explicit endpoint bounds: `/session` is exactly eight bytes, a successful `/down` is at most `carrier_batch_bytes`, and bodyless responses accept zero bytes. Declared overflow is rejected before reading, streamed overflow or excessive chunk count cancels the reader, and retryable response bodies are canceled before backoff. Terminal bridge cleanup sends at most one authenticated `DELETE`; canonical transport failures are copied to `X-Carrier-Failure` for diagnostics, while navigation and explicit close remain non-learning reasons.
|
||||
|
||||
@@ -312,7 +316,7 @@ A committed attempt becomes healthy only after transport-specific bidirectional
|
||||
|
||||
Learning is process-local, in-memory, positive-only, and bounded by `max_carrier_learning_entries`. It ranks only client-supported configured candidates, keeps the configured fallback last, and uses configured order for equal scores. User-Agent and profile evidence have primary weight; an eligible IP is only a tie-breaker. IP evidence requires exactly one explicit, globally routable `X-Forwarded-For` address; private, loopback, link-local, carrier-grade NAT, documentation, multicast, and IPv4-mapped equivalents are excluded. Client-reported failure categories and request latency are diagnostics, not negative or ranking evidence. `conservative` requires 3 User-Agent outcomes or 8 profile outcomes across 4 cohorts and disables IP evidence; `balanced` uses 2, 6 across 3, and 3 eligible-IP outcomes; `aggressive` uses 1, 4 across 2, and 1 eligible-IP outcome. A generation change with identical learning semantics preserves evidence and atomically republishes its generation fence. Disabling learning or changing aggressiveness, evidence lifetime, or health window advances the evidence epoch and detaches incompatible state; stale outcomes cannot repopulate it.
|
||||
|
||||
`https` remains the default and preserves the original serialized behavior. `https-lanes` assigns lane zero to session control and one lane to every non-zero logical stream. Each lane has its own uplink sequence, retry digest, downlink cursor, unacknowledged replay batch, queue, and newest-poll-wins lifecycle. A slow stream therefore does not block another stream at the WEB protocol layer.
|
||||
`https` remains the default. Its upload window is negotiated from 1 to 4; the generated bridge advertises `X-Telemt-Up-Window: 4`, while window 1 retains serialized uploads. `https-lanes` assigns lane zero to session control and one lane to every non-zero logical stream. Each lane has its own uplink sequence, retry digest, downlink cursor, unacknowledged replay batch, queue, and newest-poll-wins lifecycle. A slow stream therefore does not block another stream at the WEB protocol layer.
|
||||
|
||||
This removes application-level serialization between WEB streams. Public HTTP/2 still runs over one or more TCP connections, so packet loss can cause transport-level head-of-line blocking; `https-lanes` is not an HTTP/3 or QUIC carrier.
|
||||
|
||||
@@ -347,6 +351,30 @@ Static files are read at startup and successful configuration reload. Entry coun
|
||||
|
||||
All WEB keys and defaults are listed in the [configuration reference](../Config_params/CONFIG_PARAMS.en.md#web).
|
||||
|
||||
### Configurable HTTP retry jitter
|
||||
|
||||
`[web.retry_jitter]` adds an independently sampled delay to every existing bridge HTTP retry (network errors and 408/429/502/503/504). It requires no Telegram application changes. Without this section, or with `enabled = false`, the existing 250 ms Telemt hint and legacy backoff/jitter remain unchanged.
|
||||
|
||||
```toml
|
||||
[web.retry_jitter]
|
||||
enabled = true
|
||||
min_ms = 0
|
||||
max_ms = 250
|
||||
distribution = "uniform"
|
||||
# Only for distribution = "triangular":
|
||||
# peak_ms = 125
|
||||
```
|
||||
|
||||
The range describes an **addition**, not the total pause: the Telemt 250 ms hint plus this example gives 250–500 ms. Without a positive server hint, the base remains 250, 500, 1000, then 2000 ms. Enabled jitter replaces the legacy 25% jitter. A valid standard `Retry-After` is not shortened to the legacy 30-second cap in enabled mode. If the pause exceeds the remaining operation budget, the budget expires without an early retry.
|
||||
|
||||
Defaults are `enabled = false`, `min_ms = 0`, `max_ms = 250`, `distribution = "uniform"`, and no `peak_ms`. Require `0 <= min_ms <= max_ms <= 30000`. `uniform` samples integer milliseconds; `triangular` samples a triangular density and rounds to milliseconds. Its optional peak defaults to the midpoint and must be within the interval. An explicit peak with `uniform`, unknown keys/distributions and invalid ranges are rejected even when disabled. Equal bounds produce a constant addition.
|
||||
|
||||
The policy is frozen into each bridge page. Config/API reload affects newly loaded pages; existing pages retain it through recovery. Recovery JSON and HTTP compatibility headers remain unchanged. Sampling prefers `crypto.getRandomValues`, with `Math.random` as a compatibility fallback. Successful traffic is not delayed. Attempt limits, absolute budgets, cancellation and payload/sequence replay remain intact; longer pauses can exhaust a startup/recovery budget sooner in terms of completed attempts.
|
||||
|
||||
This reduces fixed retry timing, without guaranteeing resistance to DPI. Browser scheduling, network queues and other protocol timing remain observable. Existing timeline examples describe the default disabled mode. To evaluate enabled mode, add a sampled delay to each retry pause, not to the initial connection or every data frame.
|
||||
|
||||
The policy changes existing retry waits only. Stricter per-call limits still apply: ordinary `/down` polls and committed `/up` calls use one attempt; their recovery replay permits two. This option does not create new retry loops. It neither extends `web.timeouts.bridge_retry_secs` nor any startup/recovery deadline.
|
||||
|
||||
## NGINX TLS termination
|
||||
|
||||
```nginx
|
||||
@@ -494,9 +522,10 @@ Set `web_trusted_proxy_cidrs` to the address Caddy uses to connect to Telemt, fo
|
||||
| WEB listener inventory, bind address, and trust policy | Process-owned; restart Telemt. |
|
||||
| `web.allow_wildcard_hosts` and any `[web.limits]` value | Process-owned memory/resource contract; restart Telemt. |
|
||||
| `web.enabled`, carrier/negotiation policy, `web.debug`, timeouts, vhosts, profiles, and decoys | Applied by the config watcher or a runtime generation reload. |
|
||||
| `web.retry_jitter` | Reload applies to newly rendered bridge pages only. Existing pages retain their policy through recovery; load a new page to adopt changes. |
|
||||
| A vhost `base_path` change | Atomically switches new HTTP routing and capability derivation. Reissue the generated link. Already upgraded WebSockets and in-flight routed exchanges continue. Later old-base requests carrying a process-authentic bootstrap or session token receive a local no-store `404`; the now-inactive old capability follows ordinary decoy handling. An existing session bearer remains usable only on the new exact base, while an unused bootstrap issued for the old capability cannot create a session on the new base. |
|
||||
| Operator pause/drain state | Process-owned and ephemeral; survives generation reload, never writes config, and resets to `running` after process restart. |
|
||||
| Existing HTTP connections and WEB sessions | Keep their acquisition-time HTTP idle limit, carrier candidates, limits, body timeout, closed-token replay lifetime, and absolute session/negotiation deadlines; each issued bridge embeds its request, retry, recovery, and probe-coalescing values. A recovery epoch freezes its current bridge budget, while a successful recovery representation refreshes the policy used by later epochs and the fresh session. WebSocket upgrade, open, write, backpressure, and eviction operations use the parent session's frozen deadlines. Newly issued bridges use the active policy, while new logical streams use the active relay generation. |
|
||||
| Existing HTTP connections and WEB sessions | Keep their acquisition-time HTTP idle limit, carrier candidates, limits, body timeout, closed-token replay lifetime, and absolute session/negotiation deadlines; each issued bridge embeds its request, retry, recovery, and probe-coalescing values. A recovery epoch freezes its current bridge budget, while a successful recovery representation refreshes the policy used by later epochs and the fresh session. WebSocket upgrade, open, write, backpressure, and eviction operations use the parent session's frozen deadlines. Newly issued bridges use the active policy, while new logical streams use the active relay generation. `web.retry_jitter` and the HTTP carrier method remain page-owned and are not refreshed by recovery. |
|
||||
| Process shutdown | Captures the latest reloaded `web.timeouts.shutdown_secs` once and shares that single absolute deadline across listener acceptors and connections plus WEB sessions and auxiliary tasks. The waits do not receive sequential per-component budgets. |
|
||||
|
||||
Each logical stream keeps its session's creation-time client IP and owns a process-unique, non-zero synthetic source port for the complete relay lifetime. This preserves one stable, non-colliding source/destination tuple for Direct and Middle-End KDF routing.
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
[English](WEB_PROXY.en.md) | [Русский](WEB_PROXY.ru.md) | [Deutsch](WEB_PROXY.de.md)
|
||||
|
||||
[Ping в списке прокси, RPC Ping/Pong и задержки WEB](PROXY_PING.ru.md)
|
||||
|
||||
WEB-режим переносит обычные MTProxy-потоки через bounded HTTPS или WebSocket carriers, совместимые с типом прокси `WEB` в Telegram Desktop. Telemt не терминирует TLS: публичный сертификат обслуживает NGINX, HAProxy или Caddy, который передаёт обычный HTTP/1.1 на приватный listener Telemt.
|
||||
|
||||
> [!IMPORTANT]
|
||||
@@ -40,7 +42,7 @@ WEB-listener Telemt
|
||||
|
||||
- При пустом `base_path` публичный endpoint имеет вид `https://HOST:443/`, иначе — `https://HOST:443/BASE/`. Base path регистрозависим и проверяется точно; Telemt не перенаправляет, не нормализует и не удаляет его перед отправкой в decoy.
|
||||
- Поддерживаются 16-байтовые MTProxy-секреты `plain` и `dd`. FakeTLS-секреты `ee` в WEB-режиме не поддерживаются.
|
||||
- `web.carrier` выбирает единственный carrier при выключенном auto-negotiation и последний fallback при включённом. `https` использует сериализованные HTTPS uplink и long polling. `https-lanes` использует независимые HTTPS sequencing и polling для каждого logical stream. `websocket` использует один упорядоченный WebSocket для всех streams. `websocket-lanes` использует отдельный WebSocket с независимым ownership для каждого ненулевого logical stream.
|
||||
- `web.carrier` выбирает единственный carrier при выключенном auto-negotiation и последний fallback при включённом. `https` использует общую последовательность HTTPS uplink и long polling. `https-lanes` использует независимые HTTPS sequencing и polling для каждого logical stream. `websocket` использует один упорядоченный WebSocket для всех streams. `websocket-lanes` использует отдельный WebSocket с независимым ownership для каждого ненулевого logical stream.
|
||||
- Отсутствующий `web.carriers` или `web.carriers = false` отключает auto-negotiation и обучение. Непустой массив включает только стартовый последовательный перебор; уже committed session никогда не мигрирует.
|
||||
- Нативные клиенты без канонических headers carrier negotiation используют настроенный фиксированный `carrier`, даже когда `carriers` включает negotiation для поддерживающих его клиентов. Текущий Telegram iOS поддерживает только `https`, поэтому для metadata-free iOS оператор должен задать `web.carrier = "https"`; `https-lanes` этим клиентом не поддерживается. User-Agent, включая CFNetwork или Darwin, никогда не выводит capabilities неявно. Если нативный iOS всё же отправляет явные negotiation metadata, Telemt пересекает их с server-authoritative ceiling `{https}` и отклоняет пустой результат; остальные явные клиенты используют заявленный capability set.
|
||||
- Capability, bootstrap и session credentials — отдельные значения с ограниченным сроком жизни. Carrier credentials считаются секретами и не должны попадать в access logs.
|
||||
@@ -307,9 +309,11 @@ Bridge отправляет additive status objects v1 с полями `state`,
|
||||
|
||||
После commit при HTTP failure сначала точно повторяется замороженный request с текущим bearer. Успешный replay сохраняет текущую session. Потеря WebSocket либо событие foreground, online или native после scheduler gap не короче `reconnect_grace_secs` запускает одну recovery epoch. Bridge выполняет ровно один GET к исходному настроенному base root с `bridge=<capability>`, `Accept: application/vnd.telemt.web-recovery+json` и необязательной authorization текущим bearer. Положительный ответ — не кэшируемый JSON document размером не более 1024 байт со свежим bootstrap и текущими limits, timeouts и negotiation policy. Telemt выдаёт этот bootstrap до синхронного завершения совпавшей текущей session, поэтому пересоздание остаётся возможным при capacity в одну session. Неизвестный или уже retired bearer получает то же положительное representation; malformed recovery headers, выключенная admission, pause, drain и capacity rejection следуют по очищенному decoy path.
|
||||
|
||||
Recovery epoch имеет единый абсолютный wall/monotonic deadline `bridge_recovery_secs`, один request recovery document и bounded carrier retries с backoff от 250 мс до 2 с. Активный recovery status повторяется не чаще одного раза в 2,5 секунды. Новая incarnation прерывает и освобождает старые requests, sockets, lanes и queues, отправляет один synthetic `CLOSE` для каждого ещё активного native stream, подавляет второй `WELCOME` и выполняет commit только после реального carrier progress. Retired stream IDs сохраняются в bounded set, чтобы корректные поздние frames не попали в новый stream; native side должна выделить новый stream ID. Частые native reconnect attempts допустимы, но не продлевают recovery epoch и не удерживают старое состояние incarnation. Уничтожение WebView уничтожает этого recovery owner; после этого native supervisor должен создать новый bridge document.
|
||||
Recovery epoch имеет единый абсолютный wall/monotonic deadline `bridge_recovery_secs`, один request recovery document и bounded carrier retries с резервной базовой паузой от 250 мс до 2 с с учётом подсказок сервера и политики jitter страницы. Активный recovery status повторяется не чаще одного раза в 2,5 секунды. Новая incarnation прерывает и освобождает старые requests, sockets, lanes и queues, отправляет один synthetic `CLOSE` для каждого ещё активного native stream, подавляет второй `WELCOME` и выполняет commit только после реального carrier progress. Retired stream IDs сохраняются в bounded set, чтобы корректные поздние frames не попали в новый stream; native side должна выделить новый stream ID. Частые native reconnect attempts допустимы, но не продлевают recovery epoch и не удерживают старое состояние incarnation. Уничтожение WebView уничтожает этого recovery owner; после этого native supervisor должен создать новый bridge document.
|
||||
|
||||
Каждая обычная carrier HTTP-операция bridge имеет абсолютный budget `bridge_retry_secs` и не более девяти attempts. `bridge_request_secs` охватывает Fetch response head и полное чтение response body; для downlink attempt дополнительно разрешён настроенный long-poll interval. Network failures и ответы `408`, `429`, `502`, `503` или `504` используют bounded exponential backoff, а `Retry-After` не может расширить абсолютный budget. При `carrier_probe_coalesce_ms = 0` первый упорядоченный probe с `OPEN` отправляется немедленно. Значение до 10 мс позволяет включить соответствующий `DATA`, пришедший в этом окне; multiplexed carriers сохраняют весь предшествующий порядок frames, а lane carriers забирают только выбранную lane. HTTP downlink не запускается до acknowledgement probe. Multiplexed WebSocket Upgrade может начаться сразу после его выбора ответом `/session` и затем включить queued probe data; lane WebSocket ждёт известного stream ID.
|
||||
Ответы Telemt при перегрузке содержат `Retry-After: 1` и `X-Telemt-Retry-After-Ms: 250`. Только статус `503` с этой точной парой заголовков задаёт сгенерированному мосту **базовую паузу 250 мс**. При `web.retry_jitter.enabled = false` пауза равна 250 мс; при включении добавляется настроенная случайная задержка. Для остальных ответов действуют стандартная обработка `Retry-After` или резервный backoff, описанные ниже. Ранее загруженные страницы JavaScript-моста без поддержки миллисекундной подсказки используют секундную паузу до загрузки новой страницы; обновлять приложение Telegram для этого не нужно. Лимиты попыток, абсолютные бюджеты, отмена и ограничения admission не меняются.
|
||||
|
||||
Каждая обычная carrier HTTP-операция bridge имеет абсолютный budget `bridge_retry_secs` и не более девяти attempts. `bridge_request_secs` охватывает Fetch response head и полное чтение response body; для downlink attempt дополнительно разрешён настроенный long-poll interval. Network failures и ответы `408`, `429`, `502`, `503` или `504` используют положительную подсказку сервера или экспоненциальный backoff с действующей политикой jitter; `Retry-After` не может расширить абсолютный budget. При `carrier_probe_coalesce_ms = 0` первый упорядоченный probe с `OPEN` отправляется немедленно. Значение до 10 мс позволяет включить соответствующий `DATA`, пришедший в этом окне; multiplexed carriers сохраняют весь предшествующий порядок frames, а lane carriers забирают только выбранную lane. HTTP downlink может запускаться одновременно с первым upload; доставка в native-клиент ждёт первого корректного ACK/commit upload. Multiplexed WebSocket Upgrade может начаться сразу после его выбора ответом `/session` и затем включить queued probe data; lane WebSocket ждёт известного stream ID.
|
||||
|
||||
Response bodies читаются потоково с явными bounds endpoint: `/session` содержит ровно восемь байт, успешный `/down` — не более `carrier_batch_bytes`, а bodyless responses допускают ноль байт. Заявленный overflow отклоняется до чтения; overflow при streaming или избыточное число chunks отменяет reader, а bodies retryable responses отменяются до backoff. Финальный cleanup bridge отправляет не более одного аутентифицированного `DELETE`; канонические transport failures копируются в `X-Carrier-Failure` для диагностики, а navigation и explicit close остаются non-learning reasons.
|
||||
|
||||
@@ -319,7 +323,7 @@ Committed attempt становится healthy, только когда transpor
|
||||
|
||||
Обучение process-local, in-memory, positive-only и ограничено `max_carrier_learning_entries`. Оно ранжирует только поддерживаемые клиентом настроенные candidates, всегда оставляет fallback последним и сохраняет настроенный порядок при равных scores. Evidence User-Agent и профиля имеет основной вес; допустимый IP служит только tie-breaker. Для IP evidence требуется ровно один явный глобально маршрутизируемый `X-Forwarded-For`; private, loopback, link-local, carrier-grade NAT, documentation, multicast и их IPv4-mapped эквиваленты исключаются. Категории ошибок от клиента и request latency используются только для диагностики и не создают отрицательный или ranking evidence. `conservative` требует 3 outcomes User-Agent или 8 outcomes профиля в 4 cohorts и отключает IP evidence; `balanced` использует соответственно 2, 6 в 3 cohorts и 3 outcomes допустимого IP; `aggressive` — 1, 4 в 2 cohorts и 1 outcome IP. Смена generation при неизменной learning semantics сохраняет evidence и атомарно перепубликует его generation fence. Выключение обучения или изменение aggressiveness, lifetime evidence либо health window увеличивает evidence epoch и отсоединяет несовместимое состояние; stale outcomes не могут заполнить его снова.
|
||||
|
||||
`https` остаётся default и сохраняет исходное сериализованное поведение. В `https-lanes` lane zero отведена под session control, а каждому ненулевому logical stream соответствует своя lane. У каждой lane собственные uplink sequence, retry digest, downlink cursor, unacknowledged replay batch, очередь и lifecycle newest-poll-wins. Поэтому медленный stream не блокирует другой stream на уровне WEB-протокола.
|
||||
`https` остаётся default. Окно upload согласуется в диапазоне от 1 до 4; сгенерированный мост предлагает `X-Telemt-Up-Window: 4`, а окно 1 сохраняет последовательную отправку. В `https-lanes` lane zero отведена под session control, а каждому ненулевому logical stream соответствует своя lane. У каждой lane собственные uplink sequence, retry digest, downlink cursor, unacknowledged replay batch, очередь и lifecycle newest-poll-wins. Поэтому медленный stream не блокирует другой stream на уровне WEB-протокола.
|
||||
|
||||
Это устраняет сериализацию между WEB-streams на уровне приложения. Публичный HTTP/2 всё ещё работает поверх одного или нескольких TCP-connections, поэтому потеря пакетов может вызвать transport-level head-of-line blocking; `https-lanes` не является HTTP/3- или QUIC-carrier.
|
||||
|
||||
@@ -354,6 +358,30 @@ index = "index.html"
|
||||
|
||||
Все WEB-ключи и defaults перечислены в [справочнике конфигурации](../Config_params/CONFIG_PARAMS.ru.md#web).
|
||||
|
||||
### Настраиваемый jitter HTTP-повторов
|
||||
|
||||
`[web.retry_jitter]` добавляет независимо выбранную задержку к каждому существующему HTTP-повтору бриджа: сетевым ошибкам и ответам 408/429/502/503/504. Менять приложения Telegram не требуется. Без секции или при `enabled = false` сохраняются подсказка Telemt на 250 мс и прежний backoff/jitter.
|
||||
|
||||
```toml
|
||||
[web.retry_jitter]
|
||||
enabled = true
|
||||
min_ms = 0
|
||||
max_ms = 250
|
||||
distribution = "uniform"
|
||||
# Only for distribution = "triangular":
|
||||
# peak_ms = 125
|
||||
```
|
||||
|
||||
Диапазон задаёт **добавку**, а не полную паузу: подсказка Telemt 250 мс с этим примером даёт 250–500 мс. Без положительной серверной подсказки база остаётся 250, 500, 1000, затем 2000 мс. Включённый jitter заменяет прежний jitter до 25%. Корректный стандартный `Retry-After` во включённом режиме не сокращается прежним пределом в 30 секунд. Если пауза не помещается в оставшийся бюджет операции, бюджет истекает без раннего повтора.
|
||||
|
||||
Значения по умолчанию: `enabled = false`, `min_ms = 0`, `max_ms = 250`, `distribution = "uniform"`, `peak_ms` отсутствует. Требуется `0 <= min_ms <= max_ms <= 30000`. `uniform` выбирает целые миллисекунды равномерно; `triangular` использует треугольную плотность с округлением до миллисекунд. Необязательный пик по умолчанию находится посередине и должен входить в диапазон. Явный пик для `uniform`, неизвестные ключи/распределения и неверные границы отклоняются даже при выключенной опции. Одинаковые границы дают постоянную добавку.
|
||||
|
||||
Политика фиксируется в каждой странице бриджа. Reload через конфиг/API влияет на новые страницы; активные сохраняют настройки при recovery. Recovery JSON и HTTP-заголовки совместимости не меняются. Используется `crypto.getRandomValues`, при недоступности — `Math.random` для совместимости. Успешный трафик не задерживается. Лимиты попыток, общий бюджет, отмена и повтор неизменных payload/sequence сохраняются; более длинные паузы могут уменьшить число попыток, помещающихся в startup/recovery-бюджет.
|
||||
|
||||
Это размывает фиксированные интервалы повторов, но не гарантирует защиту от DPI. Планирование браузера, сетевые очереди и другие временные характеристики протокола остаются наблюдаемыми. Существующие примеры временной шкалы описывают выключенную опцию. Для включённого режима добавляйте выбранную задержку к каждой паузе повтора, а не к первому соединению или каждому кадру данных.
|
||||
|
||||
Политика меняет только уже предусмотренные паузы перед повтором. Более строгие ограничения отдельных вызовов сохраняются: обычный poll `/down` и вызов `/up` после commit выполняют одну попытку; их replay при восстановлении допускает две. Опция не создаёт новых циклов повторов. Она не продлевает `web.timeouts.bridge_retry_secs` и сроки запуска или восстановления.
|
||||
|
||||
## Терминация TLS на NGINX
|
||||
|
||||
```nginx
|
||||
@@ -501,9 +529,10 @@ log {
|
||||
| Состав WEB-listeners, bind address и trust policy | Принадлежат процессу; перезапустите Telemt. |
|
||||
| `web.allow_wildcard_hosts` и любое значение `[web.limits]` | Process-owned контракт памяти и ресурсов; перезапустите Telemt. |
|
||||
| `web.enabled`, policy carrier/negotiation, `web.debug`, timeouts, vhosts, profiles и decoys | Применяются config watcher или runtime generation reload. |
|
||||
| `web.retry_jitter` | Reload действует только для новых страниц моста. Уже загруженные страницы сохраняют политику при recovery; для применения изменений нужна новая страница. |
|
||||
| Изменение `base_path` vhost | Атомарно переключает маршрутизацию новых HTTP-запросов и derivation capability. Выпустите новую сгенерированную ссылку. Уже upgraded WebSockets и начатые маршрутизированные обмены продолжаются. Последующие запросы к старому base с подлинным для процесса bootstrap- или session-token получают локальный no-store `404`, а ставшая неактивной прежняя capability обрабатывается как обычный decoy traffic. Существующий session bearer остаётся пригодным только на новом точном base, а неиспользованный bootstrap, выданный для старой capability, не может создать session на новом base. |
|
||||
| Operator pause/drain state | Process-owned и ephemeral; переживает generation reload, никогда не записывает конфигурацию и после перезапуска процесса возвращается в `running`. |
|
||||
| Существующие HTTP connections и WEB sessions | Сохраняют HTTP idle limit, carrier candidates, лимиты, body timeout, lifetime replay-marker закрытого token и абсолютные session/negotiation deadlines своего момента создания; каждый выданный bridge содержит собственные request, retry, recovery и probe-coalescing значения. Recovery epoch фиксирует текущий bridge budget, а успешное recovery representation обновляет policy для последующих epochs и новой session. WebSocket Upgrade, open, write, backpressure и eviction operations используют замороженные deadlines parent session. Новые bridges получают активную policy, а новые logical streams используют активное relay generation. |
|
||||
| Существующие HTTP connections и WEB sessions | Сохраняют HTTP idle limit, carrier candidates, лимиты, body timeout, lifetime replay-marker закрытого token и абсолютные session/negotiation deadlines своего момента создания; каждый выданный bridge содержит собственные request, retry, recovery и probe-coalescing значения. Recovery epoch фиксирует текущий bridge budget, а успешное recovery representation обновляет policy для последующих epochs и новой session. WebSocket Upgrade, open, write, backpressure и eviction operations используют замороженные deadlines parent session. Новые bridges получают активную policy, а новые logical streams используют активное relay generation. `web.retry_jitter` и HTTP-метод carrier остаются свойствами страницы и не обновляются при recovery. |
|
||||
| Завершение процесса | Один раз фиксирует последнее применённое значение `web.timeouts.shutdown_secs` и использует единый абсолютный deadline для listener acceptors и connections, WEB sessions и auxiliary tasks. Последовательные компоненты не получают отдельные полные бюджеты. |
|
||||
|
||||
Каждый logical stream сохраняет client IP своей сессии и владеет уникальным в пределах процесса ненулевым synthetic source port до завершения relay. Это сохраняет один стабильный непересекающийся source/destination tuple для Direct и Middle-End KDF routing.
|
||||
|
||||
@@ -0,0 +1,350 @@
|
||||
//! Administrative access defaults and CIDR shaping; publication uses the watcher.
|
||||
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::ApiShared;
|
||||
use super::config_edit::{RuntimeBaseline, RuntimeFence};
|
||||
use super::config_store::{
|
||||
FieldEdit, compute_snapshot_revision, load_candidate_snapshot, load_config_snapshot,
|
||||
prepare_field_edits, write_atomic_with_runtime_check,
|
||||
};
|
||||
use super::model::ApiFailure;
|
||||
use super::patch::{Patch, patch_field};
|
||||
use crate::config::{
|
||||
AccessConfig, CidrRateLimitKey, ProxyConfig, RateLimitBps, UserMaxUniqueIpsMode,
|
||||
};
|
||||
|
||||
pub(super) const FIELDS: &[&str] = &[
|
||||
"user_max_tcp_conns_global_each",
|
||||
"user_max_unique_ips_global_each",
|
||||
"user_max_unique_ips_mode",
|
||||
"user_max_unique_ips_window_secs",
|
||||
"cidr_rate_limits",
|
||||
];
|
||||
|
||||
#[derive(Debug, Serialize, PartialEq)]
|
||||
pub(super) struct Policy {
|
||||
user_max_tcp_conns_global_each: usize,
|
||||
user_max_unique_ips_global_each: usize,
|
||||
user_max_unique_ips_mode: UserMaxUniqueIpsMode,
|
||||
user_max_unique_ips_window_secs: u64,
|
||||
cidr_rate_limits: BTreeMap<String, RateLimitBps>,
|
||||
}
|
||||
|
||||
impl From<&AccessConfig> for Policy {
|
||||
fn from(access: &AccessConfig) -> Self {
|
||||
Self {
|
||||
user_max_tcp_conns_global_each: access.user_max_tcp_conns_global_each,
|
||||
user_max_unique_ips_global_each: access.user_max_unique_ips_global_each,
|
||||
user_max_unique_ips_mode: access.user_max_unique_ips_mode,
|
||||
user_max_unique_ips_window_secs: access.user_max_unique_ips_window_secs,
|
||||
cidr_rate_limits: access
|
||||
.cidr_rate_limits
|
||||
.iter()
|
||||
.map(|(key, value)| (key.to_string(), *value))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub(super) struct PolicyState {
|
||||
desired: Policy,
|
||||
effective: Policy,
|
||||
runtime: RuntimeBaseline,
|
||||
published_match: bool,
|
||||
effective_scope: &'static str,
|
||||
subsystem_convergence: &'static str,
|
||||
apply_mode: &'static str,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
changed_paths: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
fn view(
|
||||
desired: &ProxyConfig,
|
||||
fence: &RuntimeFence,
|
||||
changed_paths: Option<Vec<String>>,
|
||||
) -> PolicyState {
|
||||
let desired = Policy::from(&desired.access);
|
||||
let effective = Policy::from(&fence.config.access);
|
||||
PolicyState {
|
||||
published_match: desired == effective,
|
||||
desired,
|
||||
effective,
|
||||
runtime: fence.baseline(),
|
||||
effective_scope: "active_config_snapshot",
|
||||
subsystem_convergence: "unknown",
|
||||
apply_mode: "watcher",
|
||||
changed_paths,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(super) struct PolicyPatch {
|
||||
#[serde(default, deserialize_with = "patch_field")]
|
||||
user_max_tcp_conns_global_each: Patch<usize>,
|
||||
#[serde(default, deserialize_with = "patch_field")]
|
||||
user_max_unique_ips_global_each: Patch<usize>,
|
||||
#[serde(default, deserialize_with = "patch_field")]
|
||||
user_max_unique_ips_mode: Patch<UserMaxUniqueIpsMode>,
|
||||
#[serde(default, deserialize_with = "patch_field")]
|
||||
user_max_unique_ips_window_secs: Patch<u64>,
|
||||
#[serde(default, deserialize_with = "patch_field")]
|
||||
cidr_rate_limits: Patch<BTreeMap<String, Option<RateInput>>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct RateInput {
|
||||
#[serde(default)]
|
||||
up_bps: u64,
|
||||
#[serde(default)]
|
||||
down_bps: u64,
|
||||
}
|
||||
|
||||
fn scalar<T: Serialize>(
|
||||
field: &str,
|
||||
patch: Patch<T>,
|
||||
current: &mut T,
|
||||
default: T,
|
||||
edits: &mut Vec<FieldEdit>,
|
||||
) -> Result<(), ApiFailure> {
|
||||
let value = match patch {
|
||||
Patch::Unchanged => return Ok(()),
|
||||
Patch::Remove => {
|
||||
*current = default;
|
||||
None
|
||||
}
|
||||
Patch::Set(value) => {
|
||||
let rendered = toml::Value::try_from(&value).map_err(|_| {
|
||||
ApiFailure::bad_request("Policy value cannot be represented in TOML")
|
||||
})?;
|
||||
*current = value;
|
||||
Some(rendered)
|
||||
}
|
||||
};
|
||||
edits.push(FieldEdit::new(&["access", field], value));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_key(key: &str) -> Result<CidrRateLimitKey, ApiFailure> {
|
||||
serde_json::from_value(serde_json::Value::String(key.to_owned())).map_err(|_| {
|
||||
ApiFailure::bad_request("cidr_rate_limits keys must be CIDRs or *4/N, *6/N, */N templates")
|
||||
})
|
||||
}
|
||||
|
||||
fn apply(
|
||||
loaded: &crate::config::ParsedConfigSource,
|
||||
body: PolicyPatch,
|
||||
) -> Result<(ProxyConfig, Vec<FieldEdit>), ApiFailure> {
|
||||
let mut config = loaded.config.clone();
|
||||
let defaults = AccessConfig::default();
|
||||
let access = &mut config.access;
|
||||
let mut edits = Vec::new();
|
||||
scalar(
|
||||
"user_max_tcp_conns_global_each",
|
||||
body.user_max_tcp_conns_global_each,
|
||||
&mut access.user_max_tcp_conns_global_each,
|
||||
defaults.user_max_tcp_conns_global_each,
|
||||
&mut edits,
|
||||
)?;
|
||||
scalar(
|
||||
"user_max_unique_ips_global_each",
|
||||
body.user_max_unique_ips_global_each,
|
||||
&mut access.user_max_unique_ips_global_each,
|
||||
defaults.user_max_unique_ips_global_each,
|
||||
&mut edits,
|
||||
)?;
|
||||
scalar(
|
||||
"user_max_unique_ips_mode",
|
||||
body.user_max_unique_ips_mode,
|
||||
&mut access.user_max_unique_ips_mode,
|
||||
defaults.user_max_unique_ips_mode,
|
||||
&mut edits,
|
||||
)?;
|
||||
scalar(
|
||||
"user_max_unique_ips_window_secs",
|
||||
body.user_max_unique_ips_window_secs,
|
||||
&mut access.user_max_unique_ips_window_secs,
|
||||
defaults.user_max_unique_ips_window_secs,
|
||||
&mut edits,
|
||||
)?;
|
||||
match body.cidr_rate_limits {
|
||||
Patch::Unchanged => {}
|
||||
Patch::Remove => {
|
||||
access.cidr_rate_limits.clear();
|
||||
edits.push(FieldEdit::new(&["access", "cidr_rate_limits"], None));
|
||||
}
|
||||
Patch::Set(changes) => {
|
||||
let sources = loaded
|
||||
.source_contents
|
||||
.values()
|
||||
.map(|source| {
|
||||
toml::from_str::<toml::Value>(source).map_err(|_| {
|
||||
ApiFailure::new(
|
||||
hyper::StatusCode::CONFLICT,
|
||||
"config_patch_not_atomic",
|
||||
"Invalid independent policy source",
|
||||
)
|
||||
})
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let mut authored: HashMap<CidrRateLimitKey, Vec<String>> = HashMap::new();
|
||||
for source in &sources {
|
||||
if let Some(rows) = source
|
||||
.get("access")
|
||||
.and_then(|v| v.get("cidr_rate_limits"))
|
||||
.and_then(toml::Value::as_table)
|
||||
{
|
||||
for raw in rows.keys() {
|
||||
authored
|
||||
.entry(parse_key(raw)?)
|
||||
.or_default()
|
||||
.push(raw.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
for (key, rate) in changes {
|
||||
let parsed = parse_key(&key)?;
|
||||
if !seen.insert(parsed.clone()) {
|
||||
return Err(ApiFailure::bad_request(
|
||||
"Duplicate normalized CIDR policy key",
|
||||
));
|
||||
}
|
||||
let mut names = authored.remove(&parsed).unwrap_or_default();
|
||||
if names.len() > 1 {
|
||||
return Err(ApiFailure::new(
|
||||
hyper::StatusCode::CONFLICT,
|
||||
"config_patch_not_atomic",
|
||||
"CIDR policy key has ambiguous source ownership",
|
||||
));
|
||||
}
|
||||
let raw_key = names.pop().unwrap_or_else(|| parsed.to_string());
|
||||
let value = if let Some(rate) = rate {
|
||||
let rate = RateLimitBps {
|
||||
up_bps: rate.up_bps,
|
||||
down_bps: rate.down_bps,
|
||||
};
|
||||
access.cidr_rate_limits.insert(parsed, rate);
|
||||
Some(
|
||||
toml::Value::try_from(rate)
|
||||
.map_err(|_| ApiFailure::internal("Cannot render CIDR rate"))?,
|
||||
)
|
||||
} else {
|
||||
access.cidr_rate_limits.remove(&parsed);
|
||||
None
|
||||
};
|
||||
edits.push(FieldEdit::new(
|
||||
&["access", "cidr_rate_limits", &raw_key],
|
||||
value,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
if edits.is_empty() {
|
||||
return Err(ApiFailure::bad_request("Empty access policy patch"));
|
||||
}
|
||||
config.validate().map_err(|_| ApiFailure::bad_request("Access policy violates configuration constraints; rates require at least one positive direction, at most 100000000000 bps, and unique auto templates; window_secs must be positive"))?;
|
||||
Ok((config, edits))
|
||||
}
|
||||
|
||||
pub(super) async fn read(shared: &ApiShared) -> Result<(PolicyState, String), ApiFailure> {
|
||||
let loaded = load_config_snapshot(&shared.config_path, false)
|
||||
.await
|
||||
.map_err(|_| ApiFailure::internal("Cannot load access policy source"))?;
|
||||
let fence = RuntimeFence::capture(shared, None)?;
|
||||
Ok((
|
||||
view(&loaded.config, &fence, None),
|
||||
compute_snapshot_revision(&loaded.source_contents),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn patch(
|
||||
body: PolicyPatch,
|
||||
expected: Option<String>,
|
||||
runtime: Option<String>,
|
||||
shared: &ApiShared,
|
||||
) -> Result<(PolicyState, String), ApiFailure> {
|
||||
let shared = shared.clone();
|
||||
shared
|
||||
.clone()
|
||||
.run_mutation_completion(async move {
|
||||
let _guard = shared.mutation_lock.lock().await;
|
||||
let fence = RuntimeFence::capture(&shared, runtime.as_deref())?;
|
||||
let path = shared.config_path.clone();
|
||||
let (loaded, desired, owned, changed) = tokio::task::spawn_blocking(move || {
|
||||
let loaded = ProxyConfig::parse_source(&path)
|
||||
.map_err(|_| ApiFailure::internal("Cannot load access policy source"))?;
|
||||
let revision = compute_snapshot_revision(&loaded.source_contents);
|
||||
if expected.is_some_and(|value| value != revision) {
|
||||
return Err(ApiFailure::new(
|
||||
hyper::StatusCode::CONFLICT,
|
||||
"revision_conflict",
|
||||
"Config revision mismatch",
|
||||
));
|
||||
}
|
||||
let (desired, edits) = apply(&loaded, body)?;
|
||||
let owned = prepare_field_edits(&loaded, &path, &edits)?;
|
||||
// Project only the five public policy fields, off the async executor.
|
||||
let projection = |config: &ProxyConfig| {
|
||||
serde_json::to_value(BTreeMap::from([("access", Policy::from(&config.access))]))
|
||||
.map_err(|_| ApiFailure::internal("Cannot project access policy"))
|
||||
};
|
||||
let changed = super::config_projection::changed_paths(
|
||||
&projection(&loaded.config)?,
|
||||
&projection(&desired)?,
|
||||
);
|
||||
Ok::<_, ApiFailure>((loaded, desired, owned, changed))
|
||||
})
|
||||
.await
|
||||
.map_err(|_| ApiFailure::internal("Policy preparation worker failed"))??;
|
||||
let base_revision = compute_snapshot_revision(&loaded.source_contents);
|
||||
let revision = if let Some(owned) = owned {
|
||||
let candidate = load_candidate_snapshot(
|
||||
&shared.config_path,
|
||||
&loaded.source_contents,
|
||||
owned.owner_path.clone(),
|
||||
owned.owner_contents.clone(),
|
||||
)
|
||||
.await
|
||||
.map_err(|error| {
|
||||
ApiFailure::new(
|
||||
error.status,
|
||||
error.code,
|
||||
"Cannot prepare access policy candidate",
|
||||
)
|
||||
})?;
|
||||
if Policy::from(&candidate.config.access) != Policy::from(&desired.access) {
|
||||
return Err(ApiFailure::internal(
|
||||
"Persisted policy candidate differs from requested policy",
|
||||
));
|
||||
}
|
||||
fence.ensure_current()?;
|
||||
write_atomic_with_runtime_check(
|
||||
shared.config_path.clone(),
|
||||
base_revision,
|
||||
owned.owner_path,
|
||||
owned.expected_owner_contents,
|
||||
owned.owner_contents,
|
||||
Some(fence.commit_check()),
|
||||
)
|
||||
.await?
|
||||
} else {
|
||||
fence.ensure_current()?;
|
||||
base_revision
|
||||
};
|
||||
shared.runtime_events.record(
|
||||
"api.access.policy.patch.ok",
|
||||
format!("changed_paths={}", changed.len()),
|
||||
);
|
||||
Ok((view(&desired, &fence, Some(changed)), revision))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,546 @@
|
||||
use super::*;
|
||||
use crate::api::discovery::http_tests::Fixture;
|
||||
use crate::maestro::generation::test_runtime_generation;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const ROUTE: &str = "/v1/access/policy";
|
||||
|
||||
pub(in crate::api) fn fixture(source: &str) -> Fixture {
|
||||
let fixture = Fixture::new(false);
|
||||
std::fs::write(&fixture.shared.config_path, source).unwrap();
|
||||
let mut config = ProxyConfig::load(&fixture.shared.config_path).unwrap();
|
||||
config.server.api = fixture
|
||||
.shared
|
||||
.active_runtime
|
||||
.load()
|
||||
.config()
|
||||
.server
|
||||
.api
|
||||
.clone();
|
||||
config.server.api.read_only = false;
|
||||
fixture
|
||||
.shared
|
||||
.active_runtime
|
||||
.store(test_runtime_generation(1, config));
|
||||
fixture
|
||||
}
|
||||
|
||||
async fn write(fixture: &Fixture, body: Value) -> (u16, Value) {
|
||||
let (status, _, data) = fixture
|
||||
.request_body("PATCH", ROUTE, true, Some(&body), &[])
|
||||
.await;
|
||||
(status, data)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn policy_http_gates_methods_queries_and_secret_exclusion() {
|
||||
let fixture = Fixture::new(false);
|
||||
for method in ["GET", "PATCH"] {
|
||||
assert_eq!(fixture.request(method, ROUTE, false).await.0, 401);
|
||||
}
|
||||
assert_eq!(
|
||||
write(&fixture, json!({"user_max_tcp_conns_global_each": 2}))
|
||||
.await
|
||||
.0,
|
||||
403
|
||||
);
|
||||
let (status, allow, _) = fixture.request("POST", ROUTE, true).await;
|
||||
assert_eq!((status, allow.as_str()), (405, "GET, PATCH"));
|
||||
assert_eq!(
|
||||
fixture
|
||||
.request("GET", "/v1/access/policy?reload=instant", true)
|
||||
.await
|
||||
.0,
|
||||
400
|
||||
);
|
||||
let denied = Fixture::new(true);
|
||||
assert_eq!(denied.request("GET", ROUTE, true).await.0, 403);
|
||||
let (status, _, data) = fixture.request("GET", ROUTE, true).await;
|
||||
assert_eq!(status, 200);
|
||||
assert_eq!(
|
||||
data["data"]["desired"].as_object().unwrap().len(),
|
||||
FIELDS.len()
|
||||
);
|
||||
assert_eq!(data["data"]["effective_scope"], "active_config_snapshot");
|
||||
assert_eq!(data["data"]["subsystem_convergence"], "unknown");
|
||||
assert!(!data.to_string().contains("discovery-test"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn scalar_defaults_reset_and_revision_runtime_fences() {
|
||||
let fixture = fixture("# preserve comment\n");
|
||||
let (_, _, before) = fixture.request("GET", ROUTE, true).await;
|
||||
let body = json!({"user_max_tcp_conns_global_each": 7, "user_max_unique_ips_global_each": 3,
|
||||
"user_max_unique_ips_mode": "time_window", "user_max_unique_ips_window_secs": 91});
|
||||
let (status, _, after) = fixture
|
||||
.request_body(
|
||||
"PATCH",
|
||||
ROUTE,
|
||||
true,
|
||||
Some(&body),
|
||||
&[
|
||||
("If-Match", before["revision"].as_str().unwrap()),
|
||||
(
|
||||
"If-Runtime-Match",
|
||||
before["data"]["runtime"]["runtime_match"].as_str().unwrap(),
|
||||
),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 200, "{after}");
|
||||
assert_eq!(
|
||||
after["data"]["desired"]["user_max_tcp_conns_global_each"],
|
||||
7
|
||||
);
|
||||
assert_eq!(
|
||||
after["data"]["effective"]["user_max_tcp_conns_global_each"],
|
||||
0
|
||||
);
|
||||
assert_eq!(after["data"]["published_match"], false);
|
||||
let source = std::fs::read(&fixture.shared.config_path).unwrap();
|
||||
for (header, token, code) in [
|
||||
(
|
||||
"If-Match",
|
||||
before["revision"].as_str().unwrap(),
|
||||
"revision_conflict",
|
||||
),
|
||||
("If-Runtime-Match", "dead:1:1", "runtime_conflict"),
|
||||
] {
|
||||
let (status, _, error) = fixture
|
||||
.request_body("PATCH", ROUTE, true, Some(&body), &[(header, token)])
|
||||
.await;
|
||||
assert_eq!(status, 409);
|
||||
assert_eq!(error["error"]["code"], code);
|
||||
assert_eq!(std::fs::read(&fixture.shared.config_path).unwrap(), source);
|
||||
}
|
||||
let (status, after) = write(
|
||||
&fixture,
|
||||
json!({"user_max_tcp_conns_global_each": null,
|
||||
"user_max_unique_ips_global_each": null, "user_max_unique_ips_mode": null,
|
||||
"user_max_unique_ips_window_secs": null}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 200, "{after}");
|
||||
assert_eq!(after["data"]["desired"], before["data"]["desired"]);
|
||||
let text = std::fs::read_to_string(&fixture.shared.config_path).unwrap();
|
||||
assert!(!text.contains("user_max_"));
|
||||
assert!(text.contains("# preserve comment"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cidr_map_updates_replace_rows_and_null_removes_or_clears() {
|
||||
let fixture = fixture("[access.cidr_rate_limits]\n'192.0.2.0/24'={up_bps=123, down_bps=456}\n");
|
||||
let (status, body) = write(
|
||||
&fixture,
|
||||
json!({"cidr_rate_limits": {
|
||||
"192.0.2.0/24": {"up_bps": 8000}, "2001:db8::/32": {"down_bps": 9000},
|
||||
"*4/16": {"up_bps": 80}, "*6/64": {"down_bps": 160}, "*/24": {"up_bps": 320}}}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 200, "{body}");
|
||||
let rates = &body["data"]["desired"]["cidr_rate_limits"];
|
||||
assert_eq!(rates.as_object().unwrap().len(), 5);
|
||||
assert_eq!(rates["192.0.2.0/24"], json!({"up_bps": 8000,"down_bps": 0}));
|
||||
let (status, body) = write(
|
||||
&fixture,
|
||||
json!({"cidr_rate_limits": {"192.0.2.0/24": null,"*4/16": null,"203.0.113.0/24": null}}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 200, "{body}");
|
||||
assert_eq!(
|
||||
body["data"]["desired"]["cidr_rate_limits"]
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.len(),
|
||||
3
|
||||
);
|
||||
let (status, body) = write(&fixture, json!({"cidr_rate_limits": null})).await;
|
||||
assert_eq!(status, 200, "{body}");
|
||||
assert_eq!(body["data"]["desired"]["cidr_rate_limits"], json!({}));
|
||||
assert!(
|
||||
!std::fs::read_to_string(&fixture.shared.config_path)
|
||||
.unwrap()
|
||||
.contains("cidr_rate_limits")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_and_non_policy_patches_never_write() {
|
||||
let fixture = fixture("");
|
||||
let before = std::fs::read(&fixture.shared.config_path).unwrap();
|
||||
for body in [
|
||||
json!({}),
|
||||
json!({"users": null}),
|
||||
json!({"replay_check": false}),
|
||||
json!({"user_max_unique_ips_window_secs":0}),
|
||||
json!({"user_max_unique_ips_mode":"other"}),
|
||||
json!({"user_max_tcp_conns_global_each":-1}),
|
||||
json!({"user_max_tcp_conns_global_each":u64::MAX}),
|
||||
json!({"cidr_rate_limits":[]}),
|
||||
json!({"cidr_rate_limits":{"invalid":{"up_bps":1}}}),
|
||||
json!({"cidr_rate_limits":{"*4/33":{"up_bps":1}}}),
|
||||
json!({"cidr_rate_limits":{"*6/129":{"up_bps":1}}}),
|
||||
json!({"cidr_rate_limits":{"*/33":{"up_bps":1}}}),
|
||||
json!({"cidr_rate_limits":{"*/24":{"up_bps":1},"*4/24":{"up_bps":2}}}),
|
||||
json!({"cidr_rate_limits":{"192.0.2.0/24":{}}}),
|
||||
json!({"cidr_rate_limits":{"192.0.2.0/24":{"up_bps":100_000_000_001_u64}}}),
|
||||
json!({"cidr_rate_limits":{"192.0.2.0/24":{"up_bps":1,"typo":null}}}),
|
||||
] {
|
||||
let (status, error) = write(&fixture, body.clone()).await;
|
||||
assert_eq!(status, 400, "{body}: {error}");
|
||||
assert_eq!(std::fs::read(&fixture.shared.config_path).unwrap(), before);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn structural_edits_preserve_unrelated_values_and_literal_keys() {
|
||||
for source in [
|
||||
"access = { user_max_tcp_conns_global_each=4, ignore_time_skew=false } # keep\n",
|
||||
"access.user_max_tcp_conns_global_each=4\naccess.ignore_time_skew=false # keep\n",
|
||||
"['access']\nuser_max_tcp_conns_global_each=4\nignore_time_skew=false # keep\n",
|
||||
] {
|
||||
let fixture = fixture(source);
|
||||
let (status, result) = write(
|
||||
&fixture,
|
||||
json!({"user_max_tcp_conns_global_each": null,
|
||||
"cidr_rate_limits":{"192.0.2.0/24":{"up_bps":8000}}}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 200, "{result}");
|
||||
let cfg = ProxyConfig::load(&fixture.shared.config_path).unwrap();
|
||||
assert!(!cfg.access.ignore_time_skew);
|
||||
assert_eq!(cfg.access.cidr_rate_limits.len(), 1);
|
||||
assert!(
|
||||
std::fs::read_to_string(&fixture.shared.config_path)
|
||||
.unwrap()
|
||||
.contains("# keep")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn include_owner_selection_and_cross_source_rejection() {
|
||||
let fixture = fixture("");
|
||||
let root = &fixture.shared.config_path;
|
||||
let include = root.with_file_name("policy.toml");
|
||||
let root_text = "include=\"policy.toml\"\n[access]\nuser_max_tcp_conns_global_each=5\n";
|
||||
let include_text = "[access.cidr_rate_limits]\n'192.0.2.0/24'={up_bps=8000}\n";
|
||||
std::fs::write(root, root_text).unwrap();
|
||||
std::fs::write(&include, include_text).unwrap();
|
||||
let (status, body) = write(
|
||||
&fixture,
|
||||
json!({"user_max_tcp_conns_global_each":null,"cidr_rate_limits":null}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 409, "{body}");
|
||||
assert_eq!(body["error"]["code"], "config_patch_not_atomic");
|
||||
assert_eq!(std::fs::read_to_string(root).unwrap(), root_text);
|
||||
assert_eq!(std::fs::read_to_string(&include).unwrap(), include_text);
|
||||
let (status, body) = write(
|
||||
&fixture,
|
||||
json!({"cidr_rate_limits":{"2001:db8::/32":{"up_bps":16000}}}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 200, "{body}");
|
||||
assert_eq!(std::fs::read_to_string(root).unwrap(), root_text);
|
||||
assert!(
|
||||
std::fs::read_to_string(include)
|
||||
.unwrap()
|
||||
.contains("2001:db8::/32")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn concurrent_policy_writers_with_same_revision_have_one_winner() {
|
||||
let fixture = fixture("");
|
||||
let (_, revision) = read(&fixture.shared).await.unwrap();
|
||||
let one = patch(
|
||||
serde_json::from_value(json!({"user_max_tcp_conns_global_each":7})).unwrap(),
|
||||
Some(revision.clone()),
|
||||
None,
|
||||
&fixture.shared,
|
||||
);
|
||||
let two = patch(
|
||||
serde_json::from_value(json!({"user_max_unique_ips_global_each":3})).unwrap(),
|
||||
Some(revision),
|
||||
None,
|
||||
&fixture.shared,
|
||||
);
|
||||
let (one, two) = tokio::join!(one, two);
|
||||
assert_ne!(one.is_ok(), two.is_ok());
|
||||
let error = one.err().or(two.err()).unwrap();
|
||||
assert_eq!(error.code, "revision_conflict");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn user_limit_origins_separate_desired_from_published_values() {
|
||||
let fixture = fixture(
|
||||
"[access]\nuser_max_tcp_conns_global_each=7\nuser_max_unique_ips_global_each=3\n[access.users]\nalice='0123456789abcdef0123456789abcdef'\n",
|
||||
);
|
||||
for (override_value, origin, value) in [
|
||||
(json!(9), "user_override", json!(9)),
|
||||
(json!(0), "global_default", json!(7)),
|
||||
(Value::Null, "global_default", json!(7)),
|
||||
] {
|
||||
let (status, _, body) = fixture
|
||||
.request_body(
|
||||
"PATCH",
|
||||
"/v1/users/alice",
|
||||
true,
|
||||
Some(&json!({"max_tcp_conns":override_value,"max_unique_ips":override_value})),
|
||||
&[],
|
||||
)
|
||||
.await;
|
||||
assert!([200, 202].contains(&status), "{body}");
|
||||
let desired = &body["data"]["limits"]["desired"]["max_tcp_conns"];
|
||||
assert_eq!(desired["origin"], origin);
|
||||
assert_eq!(desired["value"], value);
|
||||
assert_eq!(desired["configured_override"], override_value);
|
||||
let ips = &body["data"]["limits"]["desired"]["max_unique_ips"];
|
||||
assert_eq!(ips["origin"], origin);
|
||||
assert_eq!(ips["configured_override"], override_value);
|
||||
assert_eq!(
|
||||
ips["value"],
|
||||
if origin == "user_override" {
|
||||
json!(9)
|
||||
} else {
|
||||
json!(3)
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
body["data"]["limits"]["effective"]["max_unique_ips"]["value"],
|
||||
3
|
||||
);
|
||||
assert_eq!(
|
||||
body["data"]["limits"]["effective"]["max_tcp_conns"]["value"],
|
||||
7
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
write(&fixture, json!({"user_max_tcp_conns_global_each":0}))
|
||||
.await
|
||||
.0,
|
||||
200
|
||||
);
|
||||
let (_, _, body) = fixture.request("GET", "/v1/users/alice", true).await;
|
||||
assert_eq!(
|
||||
body["data"]["limits"]["desired"]["max_tcp_conns"]["origin"],
|
||||
"unlimited"
|
||||
);
|
||||
assert_eq!(
|
||||
body["data"]["limits"]["desired"]["max_tcp_conns"]["value"],
|
||||
Value::Null
|
||||
);
|
||||
assert_eq!(
|
||||
body["data"]["limits"]["effective"]["max_tcp_conns"]["value"],
|
||||
7
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn persisted_cidr_policy_retains_precedence_units_and_unlimited_direction() {
|
||||
use crate::proxy::traffic_limiter::{RateDirection, TrafficLimiter};
|
||||
let fixture = fixture("");
|
||||
let (status, body) = write(
|
||||
&fixture,
|
||||
json!({"cidr_rate_limits":{
|
||||
"192.0.2.0/24":{"up_bps":8000}, "192.0.2.7/32":{"up_bps":16000},
|
||||
"2001:db8::/32":{"up_bps":24000}, "2001:db8:1::/48":{"up_bps":32000},
|
||||
"*4/32":{"up_bps":40000}, "*6/64":{"up_bps":48000}, "*/8":{"up_bps":56000}
|
||||
}}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 200, "{body}");
|
||||
let cfg = ProxyConfig::load(&fixture.shared.config_path).unwrap();
|
||||
// A fresh bucket grants exactly one 20 ms epoch, expressed in bytes.
|
||||
for (ip, grant) in [
|
||||
("192.0.2.1", 20),
|
||||
("192.0.2.7", 40),
|
||||
("2001:db8::1", 60),
|
||||
("2001:db8:1::1", 80),
|
||||
("203.0.113.1", 100),
|
||||
("2001:db9::1", 120),
|
||||
] {
|
||||
let limiter = TrafficLimiter::new();
|
||||
limiter.apply_policy(HashMap::new(), cfg.access.cidr_rate_limits.clone());
|
||||
let lease = limiter.acquire_lease("alice", ip.parse().unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
lease
|
||||
.try_reserve(RateDirection::Up, 10_000)
|
||||
.result()
|
||||
.granted,
|
||||
grant,
|
||||
"{ip}"
|
||||
);
|
||||
assert_eq!(
|
||||
lease
|
||||
.try_reserve(RateDirection::Down, 10_000)
|
||||
.result()
|
||||
.granted,
|
||||
10_000,
|
||||
"{ip}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
write(
|
||||
&fixture,
|
||||
json!({"cidr_rate_limits":{"*4/32":null,"*6/64":null}})
|
||||
)
|
||||
.await
|
||||
.0,
|
||||
200
|
||||
);
|
||||
let cfg = ProxyConfig::load(&fixture.shared.config_path).unwrap();
|
||||
for ip in ["203.0.113.1", "2001:db9::1"] {
|
||||
let limiter = TrafficLimiter::new();
|
||||
limiter.apply_policy(HashMap::new(), cfg.access.cidr_rate_limits.clone());
|
||||
let lease = limiter.acquire_lease("alice", ip.parse().unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
lease
|
||||
.try_reserve(RateDirection::Up, 10_000)
|
||||
.result()
|
||||
.granted,
|
||||
140
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn watcher_publishes_policy_without_quota_reset_or_session_cancellation() {
|
||||
use crate::config::hot_reload::spawn_config_watcher;
|
||||
use std::{sync::Arc, time::Duration};
|
||||
use tokio::sync::watch;
|
||||
let mut fixture = fixture(
|
||||
"[server.api]\nenabled=true\nread_only=false\nauth_header='Bearer discovery-test'\n[access.users]\nalice='0123456789abcdef0123456789abcdef'\n",
|
||||
);
|
||||
let config = fixture.shared.active_runtime.load().config();
|
||||
let cancellation = tokio_util::sync::CancellationToken::new();
|
||||
let _cancel_on_drop = cancellation.clone().drop_guard();
|
||||
let (activation, activated) = watch::channel(false);
|
||||
let (mut receiver, _, watcher) = spawn_config_watcher(
|
||||
fixture.shared.config_path.clone(),
|
||||
config.clone(),
|
||||
None,
|
||||
None,
|
||||
cancellation.clone(),
|
||||
None,
|
||||
Some(activated),
|
||||
Some(fixture.shared.mutation_lock.clone()),
|
||||
None,
|
||||
);
|
||||
let mut runtime = test_runtime_generation(1, (*config).clone());
|
||||
Arc::get_mut(&mut runtime).unwrap().config_rx = receiver.clone();
|
||||
runtime.stats.load_user_quota_state("alice", 12345, 6789);
|
||||
runtime.stats.increment_user_curr_connects("alice");
|
||||
let stats = runtime.stats.clone();
|
||||
let quota_path = fixture.shared.quota_state.path().to_path_buf();
|
||||
Arc::get_mut(&mut fixture.shared).unwrap().quota_state =
|
||||
crate::quota_state::QuotaStateOwner::new(quota_path.clone(), stats.quota_store());
|
||||
let checkpoint_before = std::fs::read("a_path).ok();
|
||||
fixture.shared.active_runtime.store(runtime);
|
||||
let task = tokio::spawn(watcher);
|
||||
for limit in [7, 2, 0] {
|
||||
let (status, body) = write(
|
||||
&fixture,
|
||||
json!({"user_max_tcp_conns_global_each":limit,"user_max_unique_ips_global_each":limit}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 200, "{body}");
|
||||
activation.send_replace(true);
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
receiver.wait_for(|cfg| cfg.access.user_max_tcp_conns_global_each == limit),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let (_, _, body) = fixture.request("GET", ROUTE, true).await;
|
||||
assert_eq!(body["data"]["published_match"], true);
|
||||
assert_eq!(
|
||||
body["data"]["effective"]["user_max_unique_ips_global_each"],
|
||||
limit
|
||||
);
|
||||
assert_eq!(stats.get_user_quota_used("alice"), 12345);
|
||||
assert_eq!(
|
||||
stats.user_quota_snapshot()["alice"].last_reset_epoch_secs,
|
||||
6789
|
||||
);
|
||||
assert_eq!(stats.get_user_curr_connects("alice"), 1);
|
||||
}
|
||||
assert_eq!(std::fs::read("a_path).ok(), checkpoint_before);
|
||||
cancellation.cancel();
|
||||
tokio::time::timeout(Duration::from_secs(5), task)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn prepared_policy_write_rechecks_external_source_and_runtime_publications() {
|
||||
for runtime_change in [false, true] {
|
||||
let fixture = fixture("");
|
||||
let fence = RuntimeFence::capture(&fixture.shared, None).unwrap();
|
||||
let loaded = ProxyConfig::parse_source(&fixture.shared.config_path).unwrap();
|
||||
let revision = compute_snapshot_revision(&loaded.source_contents);
|
||||
let (_, edits) = apply(
|
||||
&loaded,
|
||||
serde_json::from_value(json!({"user_max_tcp_conns_global_each":7})).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let owned = prepare_field_edits(&loaded, &fixture.shared.config_path, &edits)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
if runtime_change {
|
||||
fixture
|
||||
.shared
|
||||
.active_runtime
|
||||
.store(test_runtime_generation(2, (*fence.config).clone()));
|
||||
} else {
|
||||
std::fs::write(&fixture.shared.config_path, "# external operator edit\n").unwrap();
|
||||
}
|
||||
let before = std::fs::read(&fixture.shared.config_path).unwrap();
|
||||
let error = write_atomic_with_runtime_check(
|
||||
fixture.shared.config_path.clone(),
|
||||
revision,
|
||||
owned.owner_path,
|
||||
owned.expected_owner_contents,
|
||||
owned.owner_contents,
|
||||
Some(fence.commit_check()),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
error.code,
|
||||
if runtime_change {
|
||||
"runtime_conflict"
|
||||
} else {
|
||||
"revision_conflict"
|
||||
}
|
||||
);
|
||||
assert_eq!(std::fs::read(&fixture.shared.config_path).unwrap(), before);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unreadable_policy_source_does_not_echo_credentials_or_source_excerpts() {
|
||||
let fixture = fixture("");
|
||||
let secret = "private-source-credential";
|
||||
std::fs::write(
|
||||
&fixture.shared.config_path,
|
||||
format!("[access]\nuser_max_tcp_conns_global_each='{secret}'\n"),
|
||||
)
|
||||
.unwrap();
|
||||
for method in ["GET", "PATCH"] {
|
||||
let (status, _, body) = fixture
|
||||
.request_body(
|
||||
method,
|
||||
ROUTE,
|
||||
true,
|
||||
Some(&json!({"user_max_tcp_conns_global_each":1})),
|
||||
&[],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 500);
|
||||
assert!(!body.to_string().contains(secret));
|
||||
}
|
||||
}
|
||||
+138
-167
@@ -1,19 +1,19 @@
|
||||
//! Config-editing API: read managed sections and apply sparse field patches.
|
||||
//! `access.*` is intentionally not editable here (owned by the users API).
|
||||
//! `[server]` is only partially editable — see [`EDITABLE_SERVER_FIELDS`].
|
||||
//! `[network]` exposes only [`EDITABLE_NETWORK_FIELDS`].
|
||||
|
||||
use serde_json::Value as Json;
|
||||
use toml::Value as Toml;
|
||||
|
||||
use super::ApiShared;
|
||||
#[cfg(test)]
|
||||
use super::config_store::write_atomic;
|
||||
use super::config_store::{
|
||||
EDITABLE_SECTIONS, EDITABLE_SERVER_FIELDS, compute_snapshot_revision, is_editable_section,
|
||||
load_candidate_snapshot, load_config_snapshot, render_server_listeners,
|
||||
render_top_level_section, resolve_single_source_owner, upsert_toml_table,
|
||||
write_atomic_if_unchanged,
|
||||
EDITABLE_NETWORK_FIELDS, EDITABLE_SECTIONS, EDITABLE_SERVER_API_FIELDS, EDITABLE_SERVER_FIELDS,
|
||||
compute_snapshot_revision, is_editable_section, load_config_snapshot, render_server_listeners,
|
||||
render_top_level_section, resolve_single_source_owner, upsert_dns_overrides, upsert_toml_table,
|
||||
};
|
||||
#[cfg(test)]
|
||||
use super::config_store::{write_atomic, write_atomic_if_unchanged};
|
||||
use super::model::ApiFailure;
|
||||
use crate::config::ProxyConfig;
|
||||
use crate::config::hot_reload::classify_config_changes;
|
||||
@@ -25,6 +25,15 @@ use serde::Serialize;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[cfg(test)]
|
||||
mod api_observability_tests;
|
||||
mod diagnostics;
|
||||
mod preflight;
|
||||
mod preparation;
|
||||
pub(super) use preflight::{RuntimeBaseline, RuntimeFence};
|
||||
pub(super) use preflight::{parse_runtime_match, validate_config};
|
||||
use preparation::prepare_patch_to_path;
|
||||
|
||||
/// Result of one validated managed-config mutation.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub(super) struct PatchConfigResponse {
|
||||
@@ -40,6 +49,9 @@ pub(super) struct PatchConfigResponse {
|
||||
pub deferred_process_fields: Vec<String>,
|
||||
/// Top-level managed sections changed by the mutation.
|
||||
pub changed: Vec<String>,
|
||||
/// Canonical changed leaf paths, without configuration values.
|
||||
pub changed_paths: Vec<String>,
|
||||
pub normalization_effects: Vec<diagnostics::NormalizationEffect>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
/// Accepted runtime reload when one was requested and required.
|
||||
pub reload: Option<ReloadAccepted>,
|
||||
@@ -53,6 +65,8 @@ struct PreparedConfigPatch {
|
||||
owner_contents: String,
|
||||
desired_config: Arc<ProxyConfig>,
|
||||
response: PatchConfigResponse,
|
||||
touched: Vec<String>,
|
||||
_guard: preparation::PreparationLease,
|
||||
}
|
||||
|
||||
/// Serializes config mutations behind `mutation_lock`, commits them, and records
|
||||
@@ -60,6 +74,7 @@ struct PreparedConfigPatch {
|
||||
pub(super) async fn patch_config(
|
||||
patch_json: Json,
|
||||
expected_revision: Option<String>,
|
||||
expected_runtime: Option<String>,
|
||||
reload_request: Option<ReloadRequest>,
|
||||
shared: &ApiShared,
|
||||
) -> Result<PatchConfigResponse, ApiFailure> {
|
||||
@@ -67,7 +82,14 @@ pub(super) async fn patch_config(
|
||||
shared
|
||||
.clone()
|
||||
.run_mutation_completion(async move {
|
||||
patch_config_to_completion(patch_json, expected_revision, reload_request, &shared).await
|
||||
patch_config_to_completion(
|
||||
patch_json,
|
||||
expected_revision,
|
||||
expected_runtime,
|
||||
reload_request,
|
||||
&shared,
|
||||
)
|
||||
.await
|
||||
})
|
||||
.await
|
||||
}
|
||||
@@ -75,18 +97,27 @@ pub(super) async fn patch_config(
|
||||
async fn patch_config_to_completion(
|
||||
patch_json: Json,
|
||||
expected_revision: Option<String>,
|
||||
expected_runtime: Option<String>,
|
||||
reload_request: Option<ReloadRequest>,
|
||||
shared: &ApiShared,
|
||||
) -> Result<PatchConfigResponse, ApiFailure> {
|
||||
let _guard = shared.mutation_lock.lock().await;
|
||||
let active_config = shared.active_runtime.load_full().config();
|
||||
let mut prepared =
|
||||
let fence = preflight::RuntimeFence::capture(shared, expected_runtime.as_deref())?;
|
||||
let prepared =
|
||||
prepare_patch_to_path(&shared.config_path, &patch_json, expected_revision).await?;
|
||||
let resolved = reconcile_runtime_effect(
|
||||
&mut prepared.response,
|
||||
&active_config,
|
||||
&prepared.desired_config,
|
||||
)?;
|
||||
let active_config = fence.config.clone();
|
||||
let (mut prepared, resolved) = tokio::task::spawn_blocking(move || {
|
||||
let mut prepared = prepared;
|
||||
let resolved = reconcile_runtime_effect(
|
||||
&mut prepared.response,
|
||||
&active_config,
|
||||
&prepared.desired_config,
|
||||
)?;
|
||||
Ok::<_, ApiFailure>((prepared, resolved))
|
||||
})
|
||||
.await
|
||||
.map_err(|_| ApiFailure::internal("Mutation classification worker failed"))??;
|
||||
fence.ensure_current()?;
|
||||
let reservation = if let Some(request) = reload_request.filter(|_| resolved.runtime_changed) {
|
||||
Some(
|
||||
shared
|
||||
@@ -98,12 +129,13 @@ async fn patch_config_to_completion(
|
||||
} else {
|
||||
None
|
||||
};
|
||||
prepared.response.revision = write_atomic_if_unchanged(
|
||||
prepared.response.revision = super::config_store::write_atomic_with_runtime_check(
|
||||
prepared.config_path,
|
||||
prepared.expected_revision,
|
||||
prepared.owner_path,
|
||||
prepared.expected_owner_contents,
|
||||
prepared.owner_contents,
|
||||
Some(fence.commit_check()),
|
||||
)
|
||||
.await?;
|
||||
if let Some(reservation) = reservation {
|
||||
@@ -122,8 +154,8 @@ fn reconcile_runtime_effect(
|
||||
active_config: &ProxyConfig,
|
||||
desired_config: &ProxyConfig,
|
||||
) -> Result<ResolvedReloadConfig, ApiFailure> {
|
||||
let resolved =
|
||||
resolve_reload_config(active_config, desired_config).map_err(ApiFailure::bad_request)?;
|
||||
let resolved = resolve_reload_config(active_config, desired_config)
|
||||
.map_err(|error| diagnostics::validation_error("effective_config_invalid", "web", error))?;
|
||||
response.runtime_reload_required = resolved.runtime_changed;
|
||||
response.process_restart_required = !resolved.deferred_process_fields.is_empty();
|
||||
response.deferred_process_fields = resolved.deferred_process_fields.clone();
|
||||
@@ -151,145 +183,6 @@ pub(super) async fn apply_patch_to_path(
|
||||
Ok(prepared.response)
|
||||
}
|
||||
|
||||
async fn prepare_patch_to_path(
|
||||
config_path: &Path,
|
||||
patch_json: &Json,
|
||||
expected_revision: Option<String>,
|
||||
) -> Result<PreparedConfigPatch, ApiFailure> {
|
||||
// 1. optimistic concurrency
|
||||
let loaded = load_config_snapshot(config_path, false).await?;
|
||||
let current = compute_snapshot_revision(&loaded.source_contents);
|
||||
if expected_revision.is_some_and(|expected| expected != current) {
|
||||
return Err(ApiFailure::new(
|
||||
hyper::StatusCode::CONFLICT,
|
||||
"revision_conflict",
|
||||
"Config revision mismatch",
|
||||
));
|
||||
}
|
||||
|
||||
// 2. convert + reject access / unknown sections / forbidden server fields
|
||||
let patch_toml = json_to_toml(patch_json)
|
||||
.map_err(|e| ApiFailure::bad_request(format!("invalid patch: {}", e)))?;
|
||||
let patch_table = patch_toml
|
||||
.as_table()
|
||||
.ok_or_else(|| ApiFailure::bad_request("patch must be a JSON object"))?;
|
||||
if patch_table.contains_key("access") {
|
||||
return Err(ApiFailure::new(
|
||||
hyper::StatusCode::BAD_REQUEST,
|
||||
"access_not_editable",
|
||||
"access.* is managed via the users API, not editable here",
|
||||
));
|
||||
}
|
||||
for (key, value) in patch_table {
|
||||
if !is_editable_section(key.as_str()) {
|
||||
return Err(ApiFailure::new(
|
||||
hyper::StatusCode::BAD_REQUEST,
|
||||
"section_not_editable",
|
||||
format!("section not editable: {}", key),
|
||||
));
|
||||
}
|
||||
if key == "server" {
|
||||
validate_server_patch(value)?;
|
||||
}
|
||||
}
|
||||
let touched: Vec<&str> = patch_table
|
||||
.keys()
|
||||
.map(|k| k.as_str())
|
||||
.filter(|k| is_editable_section(k))
|
||||
.collect();
|
||||
if touched.is_empty() {
|
||||
return Err(ApiFailure::bad_request("empty patch: no editable sections"));
|
||||
}
|
||||
|
||||
// 3. Merge against the fully expanded and normalized desired config. The
|
||||
// source owner is resolved separately so included sections stay in their
|
||||
// original file and unrelated source files remain byte-identical.
|
||||
let old_cfg = loaded.config.clone();
|
||||
let mut merged = Toml::try_from(&old_cfg)
|
||||
.map_err(|e| ApiFailure::internal(format!("failed to serialize config: {}", e)))?;
|
||||
deep_merge(&mut merged, &patch_toml);
|
||||
ProxyConfig::validate_decoy_source_keys(&merged)
|
||||
.map_err(|error| ApiFailure::bad_request(format!("invalid patched config: {error}")))?;
|
||||
|
||||
let requested_cfg: ProxyConfig = merged
|
||||
.clone()
|
||||
.try_into()
|
||||
.map_err(|e| ApiFailure::bad_request(format!("config does not deserialize: {}", e)))?;
|
||||
requested_cfg
|
||||
.validate()
|
||||
.map_err(|e| ApiFailure::bad_request(format!("config validation failed: {}", e)))?;
|
||||
|
||||
let ownership_targets: Vec<&str> = touched
|
||||
.iter()
|
||||
.map(|section| {
|
||||
if *section == "server" {
|
||||
"server.listeners"
|
||||
} else {
|
||||
*section
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let owner_path = resolve_single_source_owner(&loaded, config_path, &ownership_targets)?;
|
||||
let mut owner_contents = loaded
|
||||
.source_contents
|
||||
.get(&owner_path)
|
||||
.cloned()
|
||||
.ok_or_else(|| ApiFailure::internal("config source owner is missing from snapshot"))?;
|
||||
let expected_owner_contents = owner_contents.clone();
|
||||
for section in &touched {
|
||||
if *section == "server" {
|
||||
let rendered = render_server_listeners(&requested_cfg)?;
|
||||
owner_contents = upsert_toml_table(&owner_contents, "server.listeners", &rendered);
|
||||
} else {
|
||||
let rendered = render_top_level_section(&requested_cfg, section)?;
|
||||
owner_contents = upsert_toml_table(&owner_contents, section, &rendered);
|
||||
}
|
||||
}
|
||||
|
||||
let candidate = load_candidate_snapshot(
|
||||
config_path,
|
||||
&loaded.source_contents,
|
||||
owner_path.clone(),
|
||||
owner_contents.clone(),
|
||||
)
|
||||
.await?;
|
||||
if touched.contains(&"server")
|
||||
&& serde_json::to_value(&candidate.config.server.listeners).ok()
|
||||
!= serde_json::to_value(&requested_cfg.server.listeners).ok()
|
||||
{
|
||||
return Err(ApiFailure::new(
|
||||
hyper::StatusCode::BAD_REQUEST,
|
||||
"ambiguous_listeners",
|
||||
"server.listeners normalizes to a different effective listener set",
|
||||
));
|
||||
}
|
||||
|
||||
// 4. classify the validated, normalized candidate.
|
||||
let revision = compute_snapshot_revision(&candidate.source_contents);
|
||||
let new_cfg = candidate.config;
|
||||
let class = classify_config_changes(&old_cfg, &new_cfg);
|
||||
let deferred_process_fields =
|
||||
deferred_process_fields(&old_cfg, &new_cfg).map_err(ApiFailure::bad_request)?;
|
||||
|
||||
Ok(PreparedConfigPatch {
|
||||
config_path: config_path.to_path_buf(),
|
||||
expected_revision: current,
|
||||
owner_path,
|
||||
expected_owner_contents,
|
||||
owner_contents,
|
||||
desired_config: Arc::new(new_cfg),
|
||||
response: PatchConfigResponse {
|
||||
revision,
|
||||
restart_required: class.restart_required,
|
||||
runtime_reload_required: class.restart_required,
|
||||
process_restart_required: !deferred_process_fields.is_empty(),
|
||||
deferred_process_fields,
|
||||
changed: class.changed,
|
||||
reload: None,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
fn reload_submit_failure(error: ReloadSubmitError) -> ApiFailure {
|
||||
match error {
|
||||
ReloadSubmitError::InProgress(reload_id) => ApiFailure::new(
|
||||
@@ -318,8 +211,7 @@ pub(super) async fn read_managed_config(config_path: &Path) -> Result<(Toml, Str
|
||||
.unwrap_or_else(toml::value::Table::new);
|
||||
// Whitelist: return ONLY the editable sections. A blacklist (just removing
|
||||
// `access`) would leak `server.api` (auth_header) and `network` (per-node
|
||||
// addresses). Mirror the PATCH contract, including the nested server
|
||||
// field-level allowlist.
|
||||
// addresses). Mirror the PATCH contract, including both nested allowlists.
|
||||
let mut table = toml::value::Table::new();
|
||||
for section in EDITABLE_SECTIONS {
|
||||
if let Some(value) = parsed_table.get(*section) {
|
||||
@@ -331,6 +223,14 @@ pub(super) async fn read_managed_config(config_path: &Path) -> Result<(Toml, Str
|
||||
table.insert("server".to_string(), filtered);
|
||||
}
|
||||
}
|
||||
if let Some(network) = parsed_table.get("network").and_then(Toml::as_table) {
|
||||
let filtered = network
|
||||
.iter()
|
||||
.filter(|(key, _)| EDITABLE_NETWORK_FIELDS.contains(&key.as_str()))
|
||||
.map(|(key, value)| (key.clone(), value.clone()))
|
||||
.collect();
|
||||
table.insert("network".to_owned(), Toml::Table(filtered));
|
||||
}
|
||||
|
||||
Ok((Toml::Table(table), revision))
|
||||
}
|
||||
@@ -352,7 +252,23 @@ fn filter_server_for_read(server: &Toml) -> Option<Toml> {
|
||||
}
|
||||
}
|
||||
}
|
||||
out.insert((*field).to_string(), value.clone());
|
||||
if *field == "api" {
|
||||
if let Some(api) = value.as_table() {
|
||||
out.insert(
|
||||
"api".to_owned(),
|
||||
Toml::Table(
|
||||
api.iter()
|
||||
.filter(|(key, _)| {
|
||||
EDITABLE_SERVER_API_FIELDS.contains(&key.as_str())
|
||||
})
|
||||
.map(|(key, value)| (key.clone(), value.clone()))
|
||||
.collect(),
|
||||
),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
out.insert((*field).to_string(), value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
if out.is_empty() {
|
||||
@@ -363,20 +279,15 @@ fn filter_server_for_read(server: &Toml) -> Option<Toml> {
|
||||
}
|
||||
|
||||
/// Reject any `[server]` patch keys outside [`EDITABLE_SERVER_FIELDS`].
|
||||
fn validate_server_patch(server: &Toml) -> Result<(), ApiFailure> {
|
||||
let Some(table) = server.as_table() else {
|
||||
fn validate_server_patch(server: &Json) -> Result<(), ApiFailure> {
|
||||
let Some(table) = server.as_object() else {
|
||||
return Err(ApiFailure::new(
|
||||
hyper::StatusCode::BAD_REQUEST,
|
||||
"section_not_editable",
|
||||
"server patch must be a JSON object",
|
||||
));
|
||||
};
|
||||
if table.is_empty() {
|
||||
return Err(ApiFailure::bad_request(
|
||||
"empty server patch: provide at least one editable field \
|
||||
(currently: listeners)",
|
||||
));
|
||||
}
|
||||
// Validate original keys before null removal, including forbidden siblings.
|
||||
for key in table.keys() {
|
||||
if !EDITABLE_SERVER_FIELDS.contains(&key.as_str()) {
|
||||
return Err(ApiFailure::new(
|
||||
@@ -390,6 +301,60 @@ fn validate_server_patch(server: &Toml) -> Result<(), ApiFailure> {
|
||||
));
|
||||
}
|
||||
}
|
||||
if let Some(api) = table.get("api").filter(|api| !api.is_null()) {
|
||||
let fields = api
|
||||
.as_object()
|
||||
.ok_or_else(|| ApiFailure::bad_request("server.api patch must be a JSON object"))?;
|
||||
for key in fields.keys() {
|
||||
if !EDITABLE_SERVER_API_FIELDS.contains(&key.as_str()) {
|
||||
return Err(ApiFailure::new(
|
||||
hyper::StatusCode::BAD_REQUEST,
|
||||
"field_not_editable",
|
||||
format!("server.api.{key} is not editable via the config API"),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
let has_listeners = table.get("listeners").is_some_and(|value| !value.is_null());
|
||||
let has_api_fields = table
|
||||
.get("api")
|
||||
.and_then(Json::as_object)
|
||||
.is_some_and(|fields| fields.values().any(|value| !value.is_null()));
|
||||
if !has_listeners && !has_api_fields {
|
||||
return Err(ApiFailure::bad_request(
|
||||
"empty server patch: provide listeners or an editable server.api field",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_network_patch(network: &Json) -> Result<(), ApiFailure> {
|
||||
let Some(table) = network.as_object() else {
|
||||
return Err(ApiFailure::new(
|
||||
hyper::StatusCode::BAD_REQUEST,
|
||||
"section_not_editable",
|
||||
"network patch must be a JSON object",
|
||||
));
|
||||
};
|
||||
// Check the original keys so even a forbidden null member cannot bypass
|
||||
// the network allowlist during JSON-to-TOML null removal.
|
||||
for key in table.keys() {
|
||||
if !EDITABLE_NETWORK_FIELDS.contains(&key.as_str()) {
|
||||
return Err(ApiFailure::new(
|
||||
hyper::StatusCode::BAD_REQUEST,
|
||||
"field_not_editable",
|
||||
format!(
|
||||
"network.{key} is not editable via the config API; allowed network fields: {}",
|
||||
EDITABLE_NETWORK_FIELDS.join(", ")
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
if table.values().all(Json::is_null) {
|
||||
return Err(ApiFailure::bad_request(
|
||||
"empty network patch: provide dns_overrides (use [] to clear)",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -470,3 +435,9 @@ mod host_list_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod quota_period_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod preflight_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod dns_overrides_tests;
|
||||
|
||||
@@ -0,0 +1,508 @@
|
||||
use super::*;
|
||||
use crate::api::discovery::http_tests::Fixture;
|
||||
use crate::config::hot_reload::spawn_config_watcher;
|
||||
use crate::maestro::{generation::test_runtime_generation, reload::ReloadControl};
|
||||
use serde_json::json;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::watch;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
const API: &str = "[server.api] # keep API perimeter\nenabled=true\nlisten='127.0.0.1:9092'\nread_only=false\nauth_header='Bearer discovery-test' # keep secret\nwhitelist=['127.0.0.1/32']\ngray_action='api'\nrequest_body_limit_bytes=4096\nruntime_edge_events_capacity=64\nminimal_runtime_enabled=false\nruntime_edge_enabled=false\n";
|
||||
|
||||
fn patch(fields: Json) -> Json {
|
||||
json!({"server": {"api": fields}})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn get_exposes_exactly_five_settings_and_defaults_without_api_secrets() {
|
||||
for source in ["", API] {
|
||||
let (path, _directory) = tests::temp_config(source);
|
||||
let (managed, _) = read_managed_config(&path).await.unwrap();
|
||||
let fields = managed["server"]["api"].as_table().unwrap();
|
||||
let config = ProxyConfig::load(&path).unwrap();
|
||||
let typed = toml::Value::try_from(&config.server.api).unwrap();
|
||||
assert_eq!(fields.len(), 5);
|
||||
for (key, value) in fields {
|
||||
assert!(EDITABLE_SERVER_API_FIELDS.contains(&key.as_str()));
|
||||
assert_eq!(*value, typed[key]);
|
||||
}
|
||||
assert!(!managed.to_string().contains("discovery-test"));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn every_forbidden_api_sibling_and_alias_is_rejected_even_when_null() {
|
||||
let (path, _directory) = tests::temp_config(API);
|
||||
let original = std::fs::read(&path).unwrap();
|
||||
let api = serde_json::to_value(ProxyConfig::default().server.api).unwrap();
|
||||
for (key, value) in api.as_object().unwrap() {
|
||||
if EDITABLE_SERVER_API_FIELDS.contains(&key.as_str()) {
|
||||
continue;
|
||||
}
|
||||
for value in [value.clone(), Json::Null] {
|
||||
let error = apply_patch_to_path(
|
||||
&path,
|
||||
&patch(json!({key: value, "runtime_edge_enabled": true})),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.code, "field_not_editable", "{key}: {error:?}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), original);
|
||||
}
|
||||
}
|
||||
for body in [
|
||||
patch(json!({"typo": null, "runtime_edge_enabled": true})),
|
||||
json!({"server": {"admin_api": null, "api": {"runtime_edge_enabled": true}}}),
|
||||
json!({"server": {"port": null, "api": {"runtime_edge_enabled": true}}}),
|
||||
] {
|
||||
assert_eq!(
|
||||
apply_patch_to_path(&path, &body, None)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.code,
|
||||
"field_not_editable"
|
||||
);
|
||||
assert_eq!(std::fs::read(&path).unwrap(), original);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn observability_bounds_and_types_are_checked_before_persistence() {
|
||||
let (path, _directory) = tests::temp_config(API);
|
||||
for (key, good, bad) in [
|
||||
(
|
||||
"minimal_runtime_cache_ttl_ms",
|
||||
vec![json!(0), json!(60_000)],
|
||||
vec![json!(-1), json!(60_001), json!(1.5), json!(false)],
|
||||
),
|
||||
(
|
||||
"runtime_edge_cache_ttl_ms",
|
||||
vec![json!(0), json!(60_000)],
|
||||
vec![json!(-1), json!(60_001), json!("0")],
|
||||
),
|
||||
(
|
||||
"runtime_edge_top_n",
|
||||
vec![json!(1), json!(1000)],
|
||||
vec![json!(0), json!(1001), json!(-1), json!([])],
|
||||
),
|
||||
(
|
||||
"minimal_runtime_enabled",
|
||||
vec![json!(true), json!(false)],
|
||||
vec![json!(0), json!("true")],
|
||||
),
|
||||
(
|
||||
"runtime_edge_enabled",
|
||||
vec![json!(true), json!(false)],
|
||||
vec![json!(1), json!({})],
|
||||
),
|
||||
] {
|
||||
for value in good {
|
||||
apply_patch_to_path(&path, &patch(json!({key: value})), None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
serde_json::to_value(ProxyConfig::load(&path).unwrap().server.api).unwrap()[key],
|
||||
value
|
||||
);
|
||||
}
|
||||
let original = std::fs::read(&path).unwrap();
|
||||
for value in bad {
|
||||
let error = apply_patch_to_path(&path, &patch(json!({key: value})), None)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
error.status,
|
||||
hyper::StatusCode::BAD_REQUEST,
|
||||
"{key}: {error:?}"
|
||||
);
|
||||
assert_eq!(std::fs::read(&path).unwrap(), original);
|
||||
}
|
||||
}
|
||||
let original = std::fs::read(&path).unwrap();
|
||||
for value in [
|
||||
json!(null),
|
||||
json!({}),
|
||||
json!([]),
|
||||
json!(false),
|
||||
json!({"runtime_edge_top_n": null}),
|
||||
] {
|
||||
assert!(
|
||||
apply_patch_to_path(&path, &patch(value), None)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(std::fs::read(&path).unwrap(), original);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sparse_observability_patch_preserves_perimeter_listeners_and_comments() {
|
||||
let source = format!("{API}\n[[server.listeners]]\nip='127.0.0.1'\nport=443\n");
|
||||
let (path, _directory) = tests::temp_config(&source);
|
||||
let before = ProxyConfig::load(&path).unwrap();
|
||||
let mut response = apply_patch_to_path(
|
||||
&path,
|
||||
&patch(json!({
|
||||
"minimal_runtime_enabled": true, "minimal_runtime_cache_ttl_ms": 0,
|
||||
"runtime_edge_enabled": true, "runtime_edge_cache_ttl_ms": 60_000,
|
||||
"runtime_edge_top_n": 1,
|
||||
})),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let after = ProxyConfig::load(&path).unwrap();
|
||||
reconcile_runtime_effect(&mut response, &before, &after).unwrap();
|
||||
assert!(response.restart_required);
|
||||
assert!(response.runtime_reload_required);
|
||||
assert!(!response.process_restart_required);
|
||||
assert!(response.deferred_process_fields.is_empty());
|
||||
assert_eq!(response.changed_paths.len(), 5);
|
||||
let mut restored = after.clone();
|
||||
for field in EDITABLE_SERVER_API_FIELDS {
|
||||
let mut api = serde_json::to_value(&restored.server.api).unwrap();
|
||||
api[*field] = serde_json::to_value(&before.server.api).unwrap()[*field].clone();
|
||||
restored.server.api = serde_json::from_value(api).unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
serde_json::to_value(restored).unwrap(),
|
||||
serde_json::to_value(&before).unwrap()
|
||||
);
|
||||
let written = std::fs::read_to_string(&path).unwrap();
|
||||
for line in source.lines().filter(|line| {
|
||||
!line.starts_with("minimal_runtime_enabled=") && !line.starts_with("runtime_edge_enabled=")
|
||||
}) {
|
||||
assert!(written.contains(line), "{line}: {written}");
|
||||
}
|
||||
let response = apply_patch_to_path(
|
||||
&path,
|
||||
&patch(json!({"runtime_edge_top_n": 2, "runtime_edge_enabled": null})),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.changed_paths, ["server.api.runtime_edge_top_n"]);
|
||||
assert!(
|
||||
ProxyConfig::load(&path)
|
||||
.unwrap()
|
||||
.server
|
||||
.api
|
||||
.runtime_edge_enabled
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn precise_api_edits_preserve_inline_dotted_quoted_and_legacy_source_shapes() {
|
||||
for source in [
|
||||
"server = { api = { auth_header = 'secret', runtime_edge_top_n = 10 } }\n",
|
||||
"server.api.auth_header = 'secret'\nserver.api.runtime_edge_top_n = 10\n",
|
||||
"['server'.'api']\nauth_header='secret'\nruntime_edge_top_n=10 # retain\n",
|
||||
"[server.admin_api]\nauth_header='secret'\nruntime_edge_top_n=10 # retain\n",
|
||||
] {
|
||||
let (path, _directory) = tests::temp_config(source);
|
||||
let before = ProxyConfig::load(&path).unwrap();
|
||||
apply_patch_to_path(
|
||||
&path,
|
||||
&patch(json!({"runtime_edge_top_n": 3, "minimal_runtime_cache_ttl_ms": 0})),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let after = ProxyConfig::load(&path).unwrap();
|
||||
assert_eq!(after.server.api.auth_header, before.server.api.auth_header);
|
||||
assert_eq!(after.server.api.runtime_edge_top_n, 3);
|
||||
assert_eq!(after.server.api.minimal_runtime_cache_ttl_ms, 0);
|
||||
let written = std::fs::read_to_string(&path).unwrap();
|
||||
if source.contains("admin_api") {
|
||||
assert!(written.contains("[server.admin_api]"));
|
||||
assert!(!written.contains("[server.api]"));
|
||||
}
|
||||
if source.contains("# retain") {
|
||||
assert!(written.contains("# retain"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn included_api_owner_is_updated_and_multiple_owners_are_rejected_atomically() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = directory.path().join("config.toml");
|
||||
let included = directory.path().join("api.toml");
|
||||
let root_text = "include=\"api.toml\"\n[general]\nlog_level='normal'\n[server]\nport=443\n";
|
||||
std::fs::write(&root, root_text).unwrap();
|
||||
std::fs::write(&included, API).unwrap();
|
||||
apply_patch_to_path(&root, &patch(json!({"runtime_edge_top_n": 3})), None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&root).unwrap(), root_text);
|
||||
assert_eq!(
|
||||
ProxyConfig::load(&root)
|
||||
.unwrap()
|
||||
.server
|
||||
.api
|
||||
.runtime_edge_top_n,
|
||||
3
|
||||
);
|
||||
for (root_text, included_text, body) in [
|
||||
(
|
||||
root_text.to_owned(),
|
||||
std::fs::read_to_string(&included).unwrap(),
|
||||
json!({"server":{"api":{"runtime_edge_top_n": 4}}, "general":{"log_level":"debug"}}),
|
||||
),
|
||||
(
|
||||
"include=\"api.toml\"\nserver.api.minimal_runtime_enabled=false\n".to_owned(),
|
||||
"server.api.runtime_edge_enabled=false\n".to_owned(),
|
||||
patch(json!({"minimal_runtime_enabled":true,"runtime_edge_enabled":true})),
|
||||
),
|
||||
(
|
||||
"include=\"api.toml\"\nserver.api.minimal_runtime_enabled=false\n".to_owned(),
|
||||
"server.api.runtime_edge_enabled=false\n".to_owned(),
|
||||
patch(json!({"runtime_edge_top_n":3})),
|
||||
),
|
||||
] {
|
||||
std::fs::write(&root, &root_text).unwrap();
|
||||
std::fs::write(&included, &included_text).unwrap();
|
||||
let error = apply_patch_to_path(&root, &body, None).await.unwrap_err();
|
||||
assert_eq!(error.code, "config_patch_not_atomic", "{error:?}");
|
||||
assert_eq!(std::fs::read_to_string(&root).unwrap(), root_text);
|
||||
assert_eq!(std::fs::read_to_string(&included).unwrap(), included_text);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn http_preview_watcher_and_reload_keep_diagnostics_pending_until_activation() {
|
||||
let mut fixture = Fixture::new(false);
|
||||
std::fs::write(
|
||||
&fixture.shared.config_path,
|
||||
format!("[general]\nlog_level='normal'\n{API}"),
|
||||
)
|
||||
.unwrap();
|
||||
let config = Arc::new(ProxyConfig::load(&fixture.shared.config_path).unwrap());
|
||||
let (control, mut commands) = ReloadControl::channel(1);
|
||||
Arc::get_mut(&mut fixture.shared).unwrap().reload_control = control;
|
||||
let cancellation = CancellationToken::new();
|
||||
let _cancel_on_drop = cancellation.clone().drop_guard();
|
||||
let (activation, activated) = watch::channel(false);
|
||||
let (mut receiver, _log_receiver, watcher) = spawn_config_watcher(
|
||||
fixture.shared.config_path.clone(),
|
||||
config.clone(),
|
||||
None,
|
||||
None,
|
||||
cancellation.clone(),
|
||||
None,
|
||||
Some(activated),
|
||||
Some(fixture.shared.mutation_lock.clone()),
|
||||
None,
|
||||
);
|
||||
let mut runtime = test_runtime_generation(1, (*config).clone());
|
||||
Arc::get_mut(&mut runtime).unwrap().config_rx = receiver.clone();
|
||||
fixture.shared.active_runtime.store(runtime);
|
||||
let task = tokio::spawn(watcher);
|
||||
let body = json!({"general": {"log_level": "debug"}, "server": {"api": {
|
||||
"minimal_runtime_enabled":true, "runtime_edge_enabled":true,
|
||||
"minimal_runtime_cache_ttl_ms":0, "runtime_edge_cache_ttl_ms":0, "runtime_edge_top_n":1,
|
||||
}}});
|
||||
let original = std::fs::read(&fixture.shared.config_path).unwrap();
|
||||
let preview = fixture
|
||||
.request_body("POST", "/v1/config/validate", true, Some(&body), &[])
|
||||
.await;
|
||||
assert_eq!(preview.0, 200, "{}", preview.2);
|
||||
let data = &preview.2["data"];
|
||||
assert_eq!(data["apply"]["watcher_paths"], json!(["general.log_level"]));
|
||||
assert_eq!(
|
||||
data["apply"]["generation_paths"].as_array().unwrap().len(),
|
||||
5
|
||||
);
|
||||
assert_eq!(data["apply"]["process_restart_paths"], json!([]));
|
||||
assert_eq!(
|
||||
std::fs::read(&fixture.shared.config_path).unwrap(),
|
||||
original
|
||||
);
|
||||
assert_eq!(
|
||||
fixture
|
||||
.request_body("PATCH", "/v1/config", false, Some(&body), &[])
|
||||
.await
|
||||
.0,
|
||||
401
|
||||
);
|
||||
let response = fixture
|
||||
.request_body(
|
||||
"PATCH",
|
||||
"/v1/config",
|
||||
true,
|
||||
Some(&body),
|
||||
&[
|
||||
("If-Match", data["base_revision"].as_str().unwrap()),
|
||||
(
|
||||
"If-Runtime-Match",
|
||||
data["runtime"]["runtime_match"].as_str().unwrap(),
|
||||
),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.0, 200, "{}", response.2);
|
||||
assert_eq!(response.2["data"]["runtime_reload_required"], true);
|
||||
assert_eq!(response.2["data"]["process_restart_required"], false);
|
||||
activation.send_replace(true);
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
receiver.wait_for(|cfg| cfg.general.log_level == crate::config::LogLevel::Debug),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(receiver.borrow().server.api, config.server.api);
|
||||
assert_diagnostics(&fixture, false).await;
|
||||
|
||||
// Even an unchanged desired patch can explicitly request the pending reload.
|
||||
let accepted = fixture
|
||||
.request_body(
|
||||
"PATCH",
|
||||
"/v1/config?reload=instant",
|
||||
true,
|
||||
Some(&patch(body["server"]["api"].clone())),
|
||||
&[],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(accepted.0, 202, "{}", accepted.2);
|
||||
let command = tokio::time::timeout(Duration::from_secs(5), commands.recv())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_diagnostics(&fixture, false).await;
|
||||
let resolved = resolve_reload_config(&config, &command.config).unwrap();
|
||||
assert_eq!(
|
||||
resolved.effective.server.api.listen,
|
||||
config.server.api.listen
|
||||
);
|
||||
assert_eq!(
|
||||
resolved.effective.server.api.runtime_edge_events_capacity,
|
||||
64
|
||||
);
|
||||
fixture
|
||||
.shared
|
||||
.active_runtime
|
||||
.store(test_runtime_generation(2, resolved.effective));
|
||||
assert_diagnostics(&fixture, true).await;
|
||||
assert_eq!(
|
||||
fixture
|
||||
.request("GET", "/v1/runtime/events/recent", true)
|
||||
.await
|
||||
.2["data"]["data"]["capacity"],
|
||||
64
|
||||
);
|
||||
fixture
|
||||
.shared
|
||||
.reload_control
|
||||
.fail(command.reload_id, "fixture completed")
|
||||
.await;
|
||||
let disabled = patch(json!({"minimal_runtime_enabled": false, "runtime_edge_enabled": false}));
|
||||
let accepted = fixture
|
||||
.request_body(
|
||||
"PATCH",
|
||||
"/v1/config?reload=drain&timeout_secs=30",
|
||||
true,
|
||||
Some(&disabled),
|
||||
&[],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(accepted.0, 202, "{}", accepted.2);
|
||||
assert_diagnostics(&fixture, true).await;
|
||||
let command = commands.recv().await.unwrap();
|
||||
fixture
|
||||
.shared
|
||||
.active_runtime
|
||||
.store(test_runtime_generation(3, (*command.config).clone()));
|
||||
assert_diagnostics(&fixture, false).await;
|
||||
assert_eq!(fixture.request("GET", "/v1/health", true).await.0, 200);
|
||||
cancellation.cancel();
|
||||
tokio::time::timeout(Duration::from_secs(5), task)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
async fn assert_diagnostics(fixture: &Fixture, enabled: bool) {
|
||||
for path in [
|
||||
"/v1/stats/minimal/all",
|
||||
"/v1/runtime/connections/summary",
|
||||
"/v1/runtime/events/recent",
|
||||
] {
|
||||
let (status, _, body) = fixture.request("GET", path, true).await;
|
||||
assert_eq!(status, 200, "{body}");
|
||||
assert_eq!(body["data"]["enabled"], enabled, "{body}");
|
||||
if !enabled {
|
||||
assert_eq!(body["data"]["reason"], "feature_disabled");
|
||||
}
|
||||
}
|
||||
let (_, _, caps) = fixture.request("GET", "/v1/capabilities", true).await;
|
||||
for path in ["/v1/stats/minimal/all", "/v1/runtime/connections/summary"] {
|
||||
let operation = caps["data"]["operations"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|op| op["path"] == path)
|
||||
.unwrap();
|
||||
assert_eq!(operation["enabled"], enabled);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn observability_patch_obeys_read_only_and_source_revision_fences() {
|
||||
let fixture = Fixture::new(false);
|
||||
let body = patch(json!({"runtime_edge_enabled": true}));
|
||||
let original = std::fs::read(&fixture.shared.config_path).unwrap();
|
||||
let preview = fixture
|
||||
.request_body("POST", "/v1/config/validate", true, Some(&body), &[])
|
||||
.await;
|
||||
assert_eq!(preview.0, 200, "{}", preview.2);
|
||||
let rejected = fixture
|
||||
.request_body("PATCH", "/v1/config", true, Some(&body), &[])
|
||||
.await;
|
||||
assert_eq!(rejected.0, 403);
|
||||
assert_eq!(rejected.2["error"]["code"], "read_only");
|
||||
assert_eq!(
|
||||
std::fs::read(&fixture.shared.config_path).unwrap(),
|
||||
original
|
||||
);
|
||||
let prepared = prepare_patch_to_path(&fixture.shared.config_path, &body, None)
|
||||
.await
|
||||
.unwrap();
|
||||
let external = "# external source change\n";
|
||||
std::fs::write(&fixture.shared.config_path, external).unwrap();
|
||||
let conflict = write_atomic_if_unchanged(
|
||||
prepared.config_path,
|
||||
prepared.expected_revision,
|
||||
prepared.owner_path,
|
||||
prepared.expected_owner_contents,
|
||||
prepared.owner_contents,
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(conflict.code, "revision_conflict");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&fixture.shared.config_path).unwrap(),
|
||||
external
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn listeners_and_observability_in_one_owner_preserve_each_other() {
|
||||
let (path, _directory) = tests::temp_config(API);
|
||||
apply_patch_to_path(
|
||||
&path,
|
||||
&json!({"server": {
|
||||
"listeners": [{"ip": "127.0.0.1", "port": 8443}],
|
||||
"api": {"runtime_edge_enabled": true},
|
||||
}}),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let config = ProxyConfig::load(&path).unwrap();
|
||||
assert_eq!(config.server.listeners.len(), 1);
|
||||
assert_eq!(config.server.listeners[0].port, Some(8443));
|
||||
assert!(config.server.api.runtime_edge_enabled);
|
||||
assert_eq!(config.server.api.auth_header, "Bearer discovery-test");
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
use super::*;
|
||||
use crate::api::model::FieldIssue;
|
||||
|
||||
pub(super) use crate::api::config_projection::{MAX_PATHS, changed_paths};
|
||||
|
||||
pub(super) fn issue(
|
||||
path: impl Into<String>,
|
||||
code: &'static str,
|
||||
message: impl Into<String>,
|
||||
) -> FieldIssue {
|
||||
FieldIssue {
|
||||
path: path.into(),
|
||||
code,
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Raw validators can quote credentials, origins and source excerpts. Only known
|
||||
/// metadata paths and fixed explanations are projected into an API error.
|
||||
pub(super) fn validation_error(
|
||||
code: &'static str,
|
||||
fallback: &str,
|
||||
error: impl std::fmt::Display,
|
||||
) -> ApiFailure {
|
||||
let text = error.to_string();
|
||||
let canonical = regex::Regex::new(r"\[\d+\]")
|
||||
.map(|pattern| pattern.replace_all(&text, "[]").into_owned())
|
||||
.unwrap_or_default();
|
||||
let path = crate::api::discovery::config_field_paths()
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter(|path| canonical.contains(path))
|
||||
.max_by_key(|path| path.len())
|
||||
.unwrap_or(fallback);
|
||||
let explanation = if text.contains("overlaps WEB listener") {
|
||||
"Decoy origin overlaps WEB listener"
|
||||
} else if text.contains("only valid for mode=http_upstream") {
|
||||
"Field is only valid for mode=http_upstream"
|
||||
} else if text.contains("allow_wildcard_hosts") {
|
||||
"Wildcard selectors require web.allow_wildcard_hosts=true in the active process"
|
||||
} else {
|
||||
match code {
|
||||
"source_load_failed" => "Cannot load the desired configuration source",
|
||||
"deserialization_failed" => "Value has an invalid type or enum variant",
|
||||
"preparation_failed" => "DNS or static-asset preparation failed",
|
||||
"effective_config_invalid" => {
|
||||
"Candidate is incompatible with retained process configuration"
|
||||
}
|
||||
_ => "Value violates configuration or dependent-field constraints",
|
||||
}
|
||||
};
|
||||
let message = format!("{path}: {explanation}");
|
||||
let mut failure = if code == "source_load_failed" {
|
||||
// Preserve PATCH's existing server-error status for an unreadable or
|
||||
// invalid current source, while keeping its raw excerpt private.
|
||||
ApiFailure::internal(message)
|
||||
} else {
|
||||
ApiFailure::bad_request(message)
|
||||
};
|
||||
failure.details.push(issue(path, code, explanation));
|
||||
failure
|
||||
}
|
||||
|
||||
/// This document carries key structure only. Null members must be checked even
|
||||
/// though normal PATCH merging omits them; values never enter key diagnostics.
|
||||
fn key_document(value: &Json) -> Toml {
|
||||
match value {
|
||||
Json::Object(object) => Toml::Table(
|
||||
object
|
||||
.iter()
|
||||
.map(|(key, value)| {
|
||||
let key = if key.len() > 128 {
|
||||
"{unknown}".to_owned()
|
||||
} else {
|
||||
key.clone()
|
||||
};
|
||||
(key, key_document(value))
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
Json::Array(items) => Toml::Array(items.iter().map(key_document).collect()),
|
||||
_ => Toml::Boolean(false),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn reject_unknown(patch: &Json) -> Result<(), ApiFailure> {
|
||||
let paths = ProxyConfig::unknown_source_paths(&key_document(patch));
|
||||
if paths.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut error = ApiFailure::bad_request("Unknown configuration fields");
|
||||
error.details = paths
|
||||
.into_iter()
|
||||
.take(64)
|
||||
.map(|path| {
|
||||
let path = if path.len() <= 256
|
||||
&& path
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || "_.[]".contains(c))
|
||||
{
|
||||
path
|
||||
} else {
|
||||
"$".to_owned()
|
||||
};
|
||||
issue(
|
||||
path,
|
||||
"unknown_field",
|
||||
"Field is not part of the configuration contract",
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
Err(error)
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub(in crate::api) struct NormalizationEffect {
|
||||
pub(super) path: String,
|
||||
pub(super) code: &'static str,
|
||||
}
|
||||
|
||||
pub(super) fn source_conflict(mut error: ApiFailure) -> ApiFailure {
|
||||
error.message = "Patch requires one independently writable config source".into();
|
||||
error.details.push(issue(
|
||||
"$",
|
||||
"source_ownership_conflict",
|
||||
error.message.clone(),
|
||||
));
|
||||
error
|
||||
}
|
||||
|
||||
pub(super) fn canonicalize_aliases(
|
||||
patch: &mut Toml,
|
||||
) -> Result<Vec<NormalizationEffect>, ApiFailure> {
|
||||
let mut effects = Vec::new();
|
||||
if let Some(vhosts) = patch
|
||||
.get("web")
|
||||
.and_then(|web| web.get("vhosts"))
|
||||
.and_then(Toml::as_array)
|
||||
{
|
||||
for (index, vhost) in vhosts.iter().enumerate() {
|
||||
let Some(decoy) = vhost.get("decoy").and_then(Toml::as_table) else {
|
||||
continue;
|
||||
};
|
||||
let allowed: &[&str] = match decoy.get("mode").and_then(Toml::as_str) {
|
||||
Some("http_upstream") => &["mode", "upstream", "resolve"],
|
||||
Some("static_directory") => &["mode", "directory", "index"],
|
||||
_ => continue,
|
||||
};
|
||||
for key in decoy.keys().filter(|key| !allowed.contains(&key.as_str())) {
|
||||
let message = if key == "resolve" {
|
||||
"Field is only valid for mode=http_upstream"
|
||||
} else {
|
||||
"Field does not apply to the selected decoy mode"
|
||||
};
|
||||
let mut error = ApiFailure::bad_request(message);
|
||||
error.details.push(issue(
|
||||
format!("web.vhosts[{index}].decoy.{key}"),
|
||||
"field_not_applicable",
|
||||
message,
|
||||
));
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(upstreams) = patch.get_mut("upstreams").and_then(Toml::as_array_mut) {
|
||||
for (index, upstream) in upstreams.iter_mut().enumerate() {
|
||||
let Some(table) = upstream.as_table_mut() else {
|
||||
continue;
|
||||
};
|
||||
if let Some(value) = table.remove("force_bind") {
|
||||
if table.contains_key("bindtodevice") {
|
||||
let mut error = ApiFailure::bad_request(
|
||||
"Alias and canonical field cannot be supplied together",
|
||||
);
|
||||
error.details.push(issue(
|
||||
format!("upstreams[{index}].bindtodevice"),
|
||||
"duplicate_alias",
|
||||
error.message.clone(),
|
||||
));
|
||||
return Err(error);
|
||||
}
|
||||
table.insert("bindtodevice".into(), value);
|
||||
effects.push(NormalizationEffect {
|
||||
path: format!("upstreams[{index}].bindtodevice"),
|
||||
code: "alias_canonicalized",
|
||||
});
|
||||
}
|
||||
let variant_fields: &[&str] = match table.get("type").and_then(Toml::as_str) {
|
||||
Some("direct") => &["interface", "bind_addresses", "bindtodevice"],
|
||||
Some("socks4") => &["address", "interface", "user_id"],
|
||||
Some("socks5") => &["address", "interface", "username", "password"],
|
||||
Some("shadowsocks") => &["url", "interface"],
|
||||
_ => continue,
|
||||
};
|
||||
for key in table.keys() {
|
||||
if ![
|
||||
"type", "weight", "enabled", "scopes", "ipv4", "ipv6", "prefer",
|
||||
]
|
||||
.contains(&key.as_str())
|
||||
&& !variant_fields.contains(&key.as_str())
|
||||
{
|
||||
let mut error = ApiFailure::bad_request(
|
||||
"Field does not apply to the selected upstream type",
|
||||
);
|
||||
error.details.push(issue(
|
||||
format!("upstreams[{index}].{key}"),
|
||||
"field_not_applicable",
|
||||
error.message.clone(),
|
||||
));
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(effects)
|
||||
}
|
||||
|
||||
pub(super) fn normalization(
|
||||
patch: &Json,
|
||||
requested: &ProxyConfig,
|
||||
candidate: &ProxyConfig,
|
||||
) -> Result<Vec<NormalizationEffect>, ApiFailure> {
|
||||
let before = serde_json::to_value(requested)
|
||||
.map_err(|_| ApiFailure::internal("Cannot project candidate fields"))?;
|
||||
let after = serde_json::to_value(candidate)
|
||||
.map_err(|_| ApiFailure::internal("Cannot project candidate fields"))?;
|
||||
let mut effects: Vec<_> = changed_paths(&before, &after)
|
||||
.into_iter()
|
||||
.map(|path| NormalizationEffect {
|
||||
path,
|
||||
code: "normalized",
|
||||
})
|
||||
.collect();
|
||||
fn ignored(value: &Json, path: &str, effects: &mut Vec<NormalizationEffect>) {
|
||||
if effects.len() > MAX_PATHS {
|
||||
return;
|
||||
}
|
||||
match value {
|
||||
Json::Object(object) => {
|
||||
for (key, value) in object {
|
||||
let key = if path == "dc_overrides" {
|
||||
"{dc}"
|
||||
} else if path == "censorship.exclusive_mask" {
|
||||
"{hostname}"
|
||||
} else {
|
||||
key.as_str()
|
||||
};
|
||||
let next = if path.is_empty() {
|
||||
key.to_string()
|
||||
} else {
|
||||
format!("{path}.{key}")
|
||||
};
|
||||
if value.is_null() {
|
||||
effects.push(NormalizationEffect {
|
||||
path: next,
|
||||
code: "null_ignored",
|
||||
});
|
||||
} else {
|
||||
ignored(value, &next, effects);
|
||||
}
|
||||
}
|
||||
}
|
||||
Json::Array(array) => {
|
||||
for (index, value) in array.iter().enumerate() {
|
||||
ignored(value, &format!("{path}[{index}]"), effects);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
ignored(patch, "", &mut effects);
|
||||
Ok(effects)
|
||||
}
|
||||
@@ -0,0 +1,420 @@
|
||||
use super::*;
|
||||
use crate::api::discovery::http_tests::Fixture;
|
||||
use crate::config::hot_reload::spawn_config_watcher;
|
||||
use crate::maestro::generation::test_runtime_generation;
|
||||
use crate::network::dns_overrides::GenerationDnsResolver;
|
||||
use serde_json::json;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::watch;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
const OLD: &str = "old.example:443:192.0.2.1";
|
||||
const NEW: &str = "new.example:443:192.0.2.2";
|
||||
|
||||
fn patch(entries: Json) -> Json {
|
||||
json!({"network": {"dns_overrides": entries}})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn get_exposes_only_dns_overrides_including_the_empty_default() {
|
||||
for entries in [vec![], vec![OLD.to_owned()]] {
|
||||
let source = format!(
|
||||
"[network]\nipv4 = true\ncache_public_ip_path = 'private-path'\ndns_overrides = {}\n",
|
||||
json!(entries)
|
||||
);
|
||||
let (path, _directory) = tests::temp_config(&source);
|
||||
let (managed, _) = read_managed_config(&path).await.unwrap();
|
||||
assert_eq!(
|
||||
serde_json::to_value(&managed["network"]).unwrap(),
|
||||
patch(json!(entries))["network"]
|
||||
);
|
||||
assert!(
|
||||
!serde_json::to_string(&managed)
|
||||
.unwrap()
|
||||
.contains("private-path")
|
||||
);
|
||||
}
|
||||
let (path, _directory) = tests::temp_config("");
|
||||
let (managed, _) = read_managed_config(&path).await.unwrap();
|
||||
assert_eq!(
|
||||
serde_json::to_value(&managed["network"]).unwrap(),
|
||||
json!({"dns_overrides": []})
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn every_network_sibling_is_rejected_even_as_null_without_writing() {
|
||||
let (path, _directory) = tests::temp_config("[network]\nipv4 = true\n");
|
||||
let original = std::fs::read(&path).unwrap();
|
||||
let network = serde_json::to_value(ProxyConfig::default().network).unwrap();
|
||||
for (key, value) in network.as_object().unwrap() {
|
||||
if key == "dns_overrides" {
|
||||
continue;
|
||||
}
|
||||
for value in [value.clone(), Json::Null] {
|
||||
let body = json!({"network": {key: value, "dns_overrides": [NEW]}});
|
||||
let error = apply_patch_to_path(&path, &body, None).await.unwrap_err();
|
||||
assert_eq!(error.code, "field_not_editable", "{key}: {error:?}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), original);
|
||||
}
|
||||
}
|
||||
for value in [
|
||||
json!([]),
|
||||
json!("bad"),
|
||||
json!({}),
|
||||
json!({"dns_overrides": null}),
|
||||
json!({"typo": []}),
|
||||
] {
|
||||
assert!(
|
||||
apply_patch_to_path(&path, &json!({"network": value}), None)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(std::fs::read(&path).unwrap(), original);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn malformed_dns_arrays_never_change_source_or_revision() {
|
||||
let (path, _directory) = tests::temp_config(&format!("[network]\ndns_overrides = ['{OLD}']\n"));
|
||||
let original = std::fs::read(&path).unwrap();
|
||||
let revision = super::super::config_store::current_revision(&path)
|
||||
.await
|
||||
.unwrap();
|
||||
for entries in [
|
||||
json!(NEW),
|
||||
json!([12]),
|
||||
json!([""]),
|
||||
json!(["host:443:bad-ip"]),
|
||||
json!(["host:65536:192.0.2.1"]),
|
||||
json!([":443:192.0.2.1"]),
|
||||
json!(["host:443:2001:db8::1"]),
|
||||
json!([null]),
|
||||
json!(vec![OLD; 4097]),
|
||||
] {
|
||||
let error = apply_patch_to_path(&path, &patch(entries), None)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.status, hyper::StatusCode::BAD_REQUEST);
|
||||
assert_eq!(std::fs::read(&path).unwrap(), original);
|
||||
assert_eq!(
|
||||
super::super::config_store::current_revision(&path)
|
||||
.await
|
||||
.unwrap(),
|
||||
revision
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn add_replace_and_clear_preserve_unrelated_source_bytes() {
|
||||
let sources = [
|
||||
"# root without network\n[general]\nlog_level = 'normal'\n".to_owned(),
|
||||
"[network] # identity\nipv4 = true # keep\n[general]\nlog_level = 'normal'\n".to_owned(),
|
||||
"network = { ipv4 = true } # keep\n[general]\nlog_level = 'normal'\n".to_owned(),
|
||||
"network = {}\n".to_owned(),
|
||||
"network.ipv4 = true # keep\n[general]\nlog_level = 'normal'\n".to_owned(),
|
||||
"['network'] # quoted\nipv4 = true\n".to_owned(),
|
||||
"[network] # no final newline".to_owned(),
|
||||
"[network]\r\nipv4 = true # keep\r\n".to_owned(),
|
||||
];
|
||||
for source in sources {
|
||||
let (path, _directory) = tests::temp_config(&source);
|
||||
let initial_network = ProxyConfig::load(&path).unwrap().network;
|
||||
for entries in [
|
||||
json!([OLD, "v6.example:8443:[2001:db8::1]"]),
|
||||
json!([NEW]),
|
||||
json!([]),
|
||||
] {
|
||||
let (before, revision) = read_managed_config(&path).await.unwrap();
|
||||
let response = apply_patch_to_path(&path, &patch(entries.clone()), Some(revision))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!response.restart_required);
|
||||
assert!(!response.process_restart_required);
|
||||
assert_eq!(response.changed, ["network"]);
|
||||
let expected_paths = if entries == json!([]) {
|
||||
vec!["network.dns_overrides[0]"]
|
||||
} else {
|
||||
vec!["network.dns_overrides[0]", "network.dns_overrides[1]"]
|
||||
};
|
||||
assert_eq!(response.changed_paths, expected_paths);
|
||||
let (managed, revision) = read_managed_config(&path).await.unwrap();
|
||||
assert_eq!(
|
||||
serde_json::to_value(&managed["network"]["dns_overrides"]).unwrap(),
|
||||
entries
|
||||
);
|
||||
assert_eq!(response.revision, revision);
|
||||
assert_eq!(managed["general"], before["general"]);
|
||||
let mut network = ProxyConfig::load(&path).unwrap().network;
|
||||
network.dns_overrides = initial_network.dns_overrides.clone();
|
||||
assert_eq!(
|
||||
serde_json::to_value(network).unwrap(),
|
||||
serde_json::to_value(&initial_network).unwrap()
|
||||
);
|
||||
}
|
||||
let written = std::fs::read_to_string(&path).unwrap();
|
||||
// New declarations can be inserted, but every original line survives.
|
||||
for line in source.lines() {
|
||||
if line.starts_with("network = {") {
|
||||
assert!(
|
||||
written.contains(&line.replace("{", "{dns_overrides = [], "))
|
||||
|| written.contains(&line.replace("{}", "{dns_overrides = []}")),
|
||||
"{written}"
|
||||
);
|
||||
} else {
|
||||
assert!(written.contains(line), "{source:?}: {written}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn replacement_uses_parser_spans_for_multiline_dotted_and_inline_values() {
|
||||
let old_value = format!("[\n '{OLD}', # replace only this value\n]");
|
||||
for (prefix, value, suffix) in [
|
||||
(
|
||||
"# Unicode: ü\n[network]\n\"dns_overrides\" = ",
|
||||
old_value.as_str(),
|
||||
" # trailing\nipv4=true\n",
|
||||
),
|
||||
(
|
||||
"network = { ipv4=true, dns_overrides=",
|
||||
"['old.example:443:192.0.2.1']",
|
||||
" } # trailing\n",
|
||||
),
|
||||
(
|
||||
"'network'.'dns_overrides' = ",
|
||||
"['old.example:443:192.0.2.1']",
|
||||
"\nnetwork.ipv4=true\n",
|
||||
),
|
||||
] {
|
||||
let source = format!("{prefix}{value}{suffix}");
|
||||
let (path, _directory) = tests::temp_config(&source);
|
||||
apply_patch_to_path(&path, &patch(json!([NEW])), None)
|
||||
.await
|
||||
.unwrap();
|
||||
let written = std::fs::read_to_string(&path).unwrap();
|
||||
assert_eq!(written, format!("{prefix}[\"{NEW}\"]{suffix}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn included_parent_owns_new_dns_key_and_leaf_owner_precedes_other_network_fields() {
|
||||
for existing in [false, true] {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = directory.path().join("config.toml");
|
||||
let included = directory.path().join("network.toml");
|
||||
let root_text = if existing {
|
||||
"include = \"network.toml\"\nnetwork.ipv4 = true # keep root identity\n[general]\nlog_level='normal'\n"
|
||||
} else {
|
||||
"include = \"network.toml\"\n[general]\nlog_level='normal'\n"
|
||||
};
|
||||
let included_text = if existing {
|
||||
format!("network.dns_overrides = ['{OLD}'] # retain\n")
|
||||
} else {
|
||||
"[network] # retain\nipv4 = true # identity\n".to_owned()
|
||||
};
|
||||
std::fs::write(&root, root_text).unwrap();
|
||||
std::fs::write(&included, &included_text).unwrap();
|
||||
for entries in [json!([NEW]), json!([])] {
|
||||
apply_patch_to_path(&root, &patch(entries.clone()), None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&root).unwrap(), root_text);
|
||||
assert_eq!(
|
||||
serde_json::to_value(ProxyConfig::load(&root).unwrap().network.dns_overrides)
|
||||
.unwrap(),
|
||||
entries
|
||||
);
|
||||
let written = std::fs::read_to_string(&included).unwrap();
|
||||
assert!(written.contains("# retain"));
|
||||
if !existing {
|
||||
assert!(written.contains("ipv4 = true # identity"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cross_source_and_ambiguous_parent_edits_are_atomic_rejections() {
|
||||
for (root_text, included_text, body) in [
|
||||
(
|
||||
"include = \"network.toml\"\n[censorship]\ntls_domain='old.example'\n".to_owned(),
|
||||
format!("[network]\ndns_overrides=['{OLD}']\n"),
|
||||
json!({"network":{"dns_overrides":[NEW]},"censorship":{"tls_domain":"new.example"}}),
|
||||
),
|
||||
(
|
||||
"include = \"network.toml\"\nnetwork.ipv4 = true\n".to_owned(),
|
||||
"network.stun_use = false\n".to_owned(),
|
||||
patch(json!([NEW])),
|
||||
),
|
||||
] {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = directory.path().join("config.toml");
|
||||
let included = directory.path().join("network.toml");
|
||||
std::fs::write(&root, &root_text).unwrap();
|
||||
std::fs::write(&included, &included_text).unwrap();
|
||||
let error = apply_patch_to_path(&root, &body, None).await.unwrap_err();
|
||||
assert_eq!(error.code, "config_patch_not_atomic");
|
||||
assert_eq!(std::fs::read_to_string(&root).unwrap(), root_text);
|
||||
assert_eq!(std::fs::read_to_string(&included).unwrap(), included_text);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn prepared_dns_patch_retains_source_revision_fencing() {
|
||||
let (path, _directory) = tests::temp_config(&format!("[network]\ndns_overrides=['{OLD}']\n"));
|
||||
let prepared = prepare_patch_to_path(&path, &patch(json!([NEW])), None)
|
||||
.await
|
||||
.unwrap();
|
||||
let external = "[network]\ndns_overrides=[]\n# external edit\n";
|
||||
std::fs::write(&path, external).unwrap();
|
||||
let error = write_atomic_if_unchanged(
|
||||
prepared.config_path,
|
||||
prepared.expected_revision,
|
||||
prepared.owner_path,
|
||||
prepared.expected_owner_contents,
|
||||
prepared.owner_contents,
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.code, "revision_conflict");
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), external);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn http_preflight_commit_and_watcher_update_future_generation_resolutions() {
|
||||
let fixture = Fixture::new(false);
|
||||
let source = "[network]\nipv4 = true # retain\n[server.api]\nenabled=true\nread_only=false\nauth_header='Bearer discovery-test'\n";
|
||||
std::fs::write(&fixture.shared.config_path, source).unwrap();
|
||||
let config = Arc::new(
|
||||
ProxyConfig::load_prepared(fixture.shared.config_path.clone())
|
||||
.await
|
||||
.unwrap()
|
||||
.config,
|
||||
);
|
||||
let resolver = Arc::new(GenerationDnsResolver::from_entries(&[]).unwrap());
|
||||
let cancellation = CancellationToken::new();
|
||||
let _cancel_on_drop = cancellation.clone().drop_guard();
|
||||
let (activation, activated) = watch::channel(false);
|
||||
let (mut receiver, _log_receiver, watcher) = spawn_config_watcher(
|
||||
fixture.shared.config_path.clone(),
|
||||
config.clone(),
|
||||
None,
|
||||
None,
|
||||
cancellation.clone(),
|
||||
Some(resolver.clone()),
|
||||
Some(activated),
|
||||
Some(fixture.shared.mutation_lock.clone()),
|
||||
None,
|
||||
);
|
||||
let mut runtime = test_runtime_generation(1, (*config).clone());
|
||||
Arc::get_mut(&mut runtime).unwrap().config_rx = receiver.clone();
|
||||
fixture.shared.active_runtime.store(runtime);
|
||||
let task = tokio::spawn(watcher);
|
||||
|
||||
for entries in [
|
||||
json!([OLD]),
|
||||
json!([NEW, "v6.example:8443:[2001:db8::1]"]),
|
||||
json!([]),
|
||||
] {
|
||||
let body = patch(entries.clone());
|
||||
let before = std::fs::read(&fixture.shared.config_path).unwrap();
|
||||
let preview = fixture
|
||||
.request_body("POST", "/v1/config/validate", true, Some(&body), &[])
|
||||
.await;
|
||||
assert_eq!(preview.0, 200, "{}", preview.2);
|
||||
let data = &preview.2["data"];
|
||||
let expected_paths = if entries == json!([OLD]) {
|
||||
json!(["network.dns_overrides[0]"])
|
||||
} else {
|
||||
json!(["network.dns_overrides[0]", "network.dns_overrides[1]"])
|
||||
};
|
||||
assert_eq!(data["apply"]["watcher_paths"], expected_paths);
|
||||
assert_eq!(data["changed_paths"], expected_paths);
|
||||
assert_eq!(std::fs::read(&fixture.shared.config_path).unwrap(), before);
|
||||
let response = fixture
|
||||
.request_body(
|
||||
"PATCH",
|
||||
"/v1/config",
|
||||
true,
|
||||
Some(&body),
|
||||
&[
|
||||
("If-Match", data["base_revision"].as_str().unwrap()),
|
||||
(
|
||||
"If-Runtime-Match",
|
||||
data["runtime"]["runtime_match"].as_str().unwrap(),
|
||||
),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.0, 200, "{}", response.2);
|
||||
assert_eq!(response.2["data"]["restart_required"], false);
|
||||
assert_eq!(response.2["data"]["process_restart_required"], false);
|
||||
activation.send_replace(true);
|
||||
let wanted: Vec<String> = serde_json::from_value(entries.clone()).unwrap();
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
receiver.wait_for(|config| config.network.dns_overrides == wanted),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
resolver.resolve_socket_addr("OLD.EXAMPLE", 443),
|
||||
if entries == json!([OLD]) {
|
||||
Some("192.0.2.1:443".parse().unwrap())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
resolver.resolve_socket_addr("new.example", 443),
|
||||
if wanted.iter().any(|entry| entry == NEW) {
|
||||
Some("192.0.2.2:443".parse().unwrap())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
resolver.resolve_socket_addr("v6.example", 8443),
|
||||
if wanted.len() == 2 {
|
||||
Some("[2001:db8::1]:8443".parse().unwrap())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
);
|
||||
assert!(resolver.resolve_socket_addr("new.example", 444).is_none());
|
||||
let get = fixture.request("GET", "/v1/config", true).await;
|
||||
assert_eq!(get.0, 200);
|
||||
assert_eq!(get.2["data"]["network"], body["network"]);
|
||||
assert!(fixture.shared.reload_control.in_progress().await.is_none());
|
||||
let current = std::fs::read(&fixture.shared.config_path).unwrap();
|
||||
for invalid in [
|
||||
patch(json!(["invalid"])),
|
||||
json!({"network":{"ipv4":false,"dns_overrides":[]}}),
|
||||
] {
|
||||
for method in ["POST", "PATCH"] {
|
||||
let route = if method == "POST" {
|
||||
"/v1/config/validate"
|
||||
} else {
|
||||
"/v1/config"
|
||||
};
|
||||
assert_eq!(
|
||||
fixture
|
||||
.request_body(method, route, true, Some(&invalid), &[])
|
||||
.await
|
||||
.0,
|
||||
400
|
||||
);
|
||||
assert_eq!(std::fs::read(&fixture.shared.config_path).unwrap(), current);
|
||||
}
|
||||
}
|
||||
}
|
||||
cancellation.cancel();
|
||||
tokio::time::timeout(Duration::from_secs(5), task)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
}
|
||||
@@ -141,3 +141,50 @@ async fn grouped_hosts_cannot_bypass_frozen_process_limits() {
|
||||
// Effective process policy must reject patterns until the explicit restart has happened.
|
||||
#[path = "wildcard_tests.rs"]
|
||||
mod wildcard_tests;
|
||||
|
||||
#[tokio::test]
|
||||
async fn retry_jitter_patch_validates_and_reloads_without_restart() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("config.toml");
|
||||
std::fs::write(&path, source()).unwrap();
|
||||
let initial = ProxyConfig::load(&path).unwrap();
|
||||
let (_, revision) = read_managed_config(&path).await.unwrap();
|
||||
let patch = serde_json::json!({"web":{"retry_jitter":{
|
||||
"enabled":true,"min_ms":10,"max_ms":300,"distribution":"triangular","peak_ms":100
|
||||
}}});
|
||||
let mut response = apply_patch_to_path(&path, &patch, Some(revision))
|
||||
.await
|
||||
.unwrap();
|
||||
let desired = ProxyConfig::load(&path).unwrap();
|
||||
let resolved = reconcile_runtime_effect(&mut response, &initial, &desired).unwrap();
|
||||
assert!(resolved.runtime_changed);
|
||||
assert!(!response.process_restart_required);
|
||||
assert_eq!(
|
||||
resolved.effective.web.retry_jitter,
|
||||
desired.web.retry_jitter
|
||||
);
|
||||
assert!(!initial.web.retry_jitter.enabled);
|
||||
let (managed, revision) = read_managed_config(&path).await.unwrap();
|
||||
assert_eq!(
|
||||
managed["web"]["retry_jitter"]["peak_ms"].as_integer(),
|
||||
Some(100)
|
||||
);
|
||||
let before = std::fs::read(&path).unwrap();
|
||||
for invalid in [
|
||||
serde_json::json!({"max_ms":30001}),
|
||||
serde_json::json!({"peak_ms":301}),
|
||||
serde_json::json!({"distribution":"uniform"}),
|
||||
serde_json::json!({"typo":1}),
|
||||
] {
|
||||
assert!(
|
||||
apply_patch_to_path(
|
||||
&path,
|
||||
&serde_json::json!({"web":{"retry_jitter":invalid}}),
|
||||
Some(revision.clone())
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(std::fs::read(&path).unwrap(), before);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
use std::sync::OnceLock;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::api::config_store::CommitCheck;
|
||||
use crate::api::model::FieldIssue;
|
||||
use crate::config::hot_reload::overlay_hot_fields;
|
||||
use crate::maestro::generation::RuntimeGeneration;
|
||||
use hyper::{HeaderMap, StatusCode};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub(in crate::api) struct RuntimeBaseline {
|
||||
pub(in crate::api) active_generation: u64,
|
||||
pub(in crate::api) config_epoch: u64,
|
||||
pub(in crate::api) runtime_match: String,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(in crate::api) struct RuntimeFence {
|
||||
active: Arc<arc_swap::ArcSwap<RuntimeGeneration>>,
|
||||
generation: Arc<RuntimeGeneration>,
|
||||
pub(in crate::api) config: Arc<ProxyConfig>,
|
||||
}
|
||||
|
||||
impl RuntimeFence {
|
||||
pub(in crate::api) fn capture(
|
||||
shared: &ApiShared,
|
||||
expected: Option<&str>,
|
||||
) -> Result<Self, ApiFailure> {
|
||||
let generation = shared.active_runtime.load_full();
|
||||
let config = generation.config();
|
||||
let fence = Self {
|
||||
active: shared.active_runtime.clone(),
|
||||
generation,
|
||||
config,
|
||||
};
|
||||
fence.ensure_current()?;
|
||||
if expected.is_some_and(|expected| expected != fence.baseline().runtime_match) {
|
||||
return Err(runtime_conflict());
|
||||
}
|
||||
Ok(fence)
|
||||
}
|
||||
|
||||
pub(in crate::api) fn baseline(&self) -> RuntimeBaseline {
|
||||
static PROCESS: OnceLock<String> = OnceLock::new();
|
||||
let process = PROCESS.get_or_init(|| {
|
||||
let mut bytes = [0_u8; 16];
|
||||
crate::crypto::SecureRandom::new().fill(&mut bytes);
|
||||
hex::encode(bytes)
|
||||
});
|
||||
RuntimeBaseline {
|
||||
active_generation: self.generation.id,
|
||||
config_epoch: self.config.runtime_config_epoch,
|
||||
runtime_match: format!(
|
||||
"{process}:{}:{}",
|
||||
self.generation.id, self.config.runtime_config_epoch
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn matches(&self) -> bool {
|
||||
let current = self.active.load_full();
|
||||
Arc::ptr_eq(¤t, &self.generation)
|
||||
&& Arc::ptr_eq(¤t.config(), &self.config)
|
||||
&& Arc::ptr_eq(&self.active.load_full(), &self.generation)
|
||||
}
|
||||
|
||||
pub(in crate::api) fn ensure_current(&self) -> Result<(), ApiFailure> {
|
||||
if self.matches() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(runtime_conflict())
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::api) fn commit_check(&self) -> CommitCheck {
|
||||
let fence = self.clone();
|
||||
Arc::new(move || fence.matches())
|
||||
}
|
||||
}
|
||||
|
||||
fn runtime_conflict() -> ApiFailure {
|
||||
let mut error = ApiFailure::new(
|
||||
StatusCode::CONFLICT,
|
||||
"runtime_conflict",
|
||||
"Runtime configuration changed; validate against a fresh baseline",
|
||||
);
|
||||
error.details.push(diagnostics::issue(
|
||||
"$",
|
||||
"runtime_conflict",
|
||||
error.message.clone(),
|
||||
));
|
||||
error
|
||||
}
|
||||
|
||||
pub(in crate::api) fn parse_runtime_match(
|
||||
headers: &HeaderMap,
|
||||
) -> Result<Option<String>, ApiFailure> {
|
||||
let mut values = headers.get_all("if-runtime-match").iter();
|
||||
let Some(value) = values.next() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let value = value
|
||||
.to_str()
|
||||
.map_err(|_| ApiFailure::bad_request("Invalid If-Runtime-Match header"))?
|
||||
.trim()
|
||||
.trim_matches('"');
|
||||
if values.next().is_some()
|
||||
|| value.is_empty()
|
||||
|| value.len() > 128
|
||||
|| !value
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_hexdigit() || byte == b':')
|
||||
{
|
||||
return Err(ApiFailure::bad_request("Invalid If-Runtime-Match header"));
|
||||
}
|
||||
Ok(Some(value.to_owned()))
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub(super) struct ApplyImpact {
|
||||
pub(super) watcher_paths: Vec<String>,
|
||||
pub(super) generation_paths: Vec<String>,
|
||||
pub(super) process_restart_paths: Vec<String>,
|
||||
pub(super) restart_required: bool,
|
||||
pub(super) runtime_reload_required: bool,
|
||||
pub(super) process_restart_required: bool,
|
||||
pub(super) deferred_process_fields: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub(in crate::api) struct ValidationResponse {
|
||||
pub(super) valid: bool,
|
||||
pub(in crate::api) base_revision: String,
|
||||
pub(super) candidate_revision: String,
|
||||
pub(super) runtime: RuntimeBaseline,
|
||||
pub(super) changed_paths: Vec<String>,
|
||||
pub(super) normalization_effects: Vec<diagnostics::NormalizationEffect>,
|
||||
pub(super) apply: ApplyImpact,
|
||||
pub(super) source_ownership: &'static str,
|
||||
pub(super) touched_sections: Vec<String>,
|
||||
pub(super) reload: Option<ReloadRequest>,
|
||||
pub(super) warnings: Vec<FieldIssue>,
|
||||
}
|
||||
|
||||
/// All blocking workers retain the same lease. Dropping this future cannot
|
||||
/// publish data, reserve a reload, or let an abandoned worker bypass the budget.
|
||||
pub(in crate::api) async fn validate_config(
|
||||
patch: Json,
|
||||
expected_revision: Option<String>,
|
||||
expected_runtime: Option<String>,
|
||||
reload: Option<ReloadRequest>,
|
||||
shared: &ApiShared,
|
||||
) -> Result<ValidationResponse, ApiFailure> {
|
||||
if let Some(request) = &reload {
|
||||
request.validate().map_err(ApiFailure::bad_request)?;
|
||||
}
|
||||
let permit = shared
|
||||
.config_preflight_slots
|
||||
.clone()
|
||||
.try_acquire_owned()
|
||||
.map_err(|_| {
|
||||
ApiFailure::new(
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
"config_preflight_busy",
|
||||
"Both configuration preparation slots are occupied",
|
||||
)
|
||||
})?;
|
||||
let guard = Arc::new(Some(permit));
|
||||
let fence = RuntimeFence::capture(shared, expected_runtime.as_deref())?;
|
||||
let preparation = async {
|
||||
let prepared =
|
||||
preparation::prepare_guarded(&shared.config_path, &patch, expected_revision, guard)
|
||||
.await?;
|
||||
let active = fence.config.clone();
|
||||
let (prepared, apply) = tokio::task::spawn_blocking(move || {
|
||||
let mut prepared = prepared;
|
||||
let resolved = reconcile_runtime_effect(
|
||||
&mut prepared.response,
|
||||
&active,
|
||||
&prepared.desired_config,
|
||||
)?;
|
||||
let hot = overlay_hot_fields(&active, &prepared.desired_config);
|
||||
let json = |config: &ProxyConfig| {
|
||||
serde_json::to_value(config)
|
||||
.map_err(|_| ApiFailure::internal("Cannot project application paths"))
|
||||
};
|
||||
let active = json(&active)?;
|
||||
let hot = json(&hot)?;
|
||||
let effective = json(&resolved.effective)?;
|
||||
let desired = json(&prepared.desired_config)?;
|
||||
let apply = ApplyImpact {
|
||||
watcher_paths: diagnostics::changed_paths(&active, &hot),
|
||||
generation_paths: diagnostics::changed_paths(&hot, &effective),
|
||||
process_restart_paths: diagnostics::changed_paths(&effective, &desired),
|
||||
restart_required: prepared.response.restart_required,
|
||||
runtime_reload_required: prepared.response.runtime_reload_required,
|
||||
process_restart_required: prepared.response.process_restart_required,
|
||||
deferred_process_fields: prepared.response.deferred_process_fields.clone(),
|
||||
};
|
||||
if [
|
||||
&apply.watcher_paths,
|
||||
&apply.generation_paths,
|
||||
&apply.process_restart_paths,
|
||||
]
|
||||
.into_iter()
|
||||
.any(|paths| paths.len() > diagnostics::MAX_PATHS)
|
||||
{
|
||||
return Err(ApiFailure::bad_request(
|
||||
"Preview exceeds the 4096-path feedback limit",
|
||||
));
|
||||
}
|
||||
// Keep the preparation lease in this worker through the final source
|
||||
// read, including when its awaiting HTTP request has been cancelled.
|
||||
let graph = ProxyConfig::read_source_graph(&prepared.config_path)
|
||||
.map_err(|error| diagnostics::validation_error("source_load_failed", "$", error))?;
|
||||
if compute_snapshot_revision(&graph.source_contents) != prepared.expected_revision {
|
||||
return Err(ApiFailure::new(
|
||||
StatusCode::CONFLICT,
|
||||
"revision_conflict",
|
||||
"Config revision changed during validation",
|
||||
));
|
||||
}
|
||||
Ok((prepared, apply))
|
||||
})
|
||||
.await
|
||||
.map_err(|_| ApiFailure::internal("Preview classification worker failed"))??;
|
||||
fence.ensure_current()?;
|
||||
let mut warnings = vec![diagnostics::issue(
|
||||
"$",
|
||||
"preparation_reads",
|
||||
"Preparation may read DNS and static assets; listener binding and runtime startup are not tested",
|
||||
)];
|
||||
if !apply.generation_paths.is_empty() && reload.is_none() {
|
||||
warnings.push(diagnostics::issue(
|
||||
"$",
|
||||
"reload_not_requested",
|
||||
"Generation-owned changes require an explicit reload",
|
||||
));
|
||||
}
|
||||
if apply.process_restart_required {
|
||||
warnings.push(diagnostics::issue(
|
||||
"$",
|
||||
"process_restart_required",
|
||||
"Some desired fields remain deferred until process restart",
|
||||
));
|
||||
}
|
||||
Ok(ValidationResponse {
|
||||
valid: true,
|
||||
base_revision: prepared.expected_revision,
|
||||
candidate_revision: prepared.response.revision,
|
||||
runtime: fence.baseline(),
|
||||
changed_paths: prepared.response.changed_paths,
|
||||
normalization_effects: prepared.response.normalization_effects,
|
||||
apply,
|
||||
source_ownership: "single_source",
|
||||
touched_sections: prepared.touched,
|
||||
reload,
|
||||
warnings,
|
||||
})
|
||||
};
|
||||
tokio::time::timeout(Duration::from_secs(30), preparation)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
ApiFailure::new(
|
||||
StatusCode::GATEWAY_TIMEOUT,
|
||||
"config_preflight_timeout",
|
||||
"Configuration preparation exceeded 30 seconds",
|
||||
)
|
||||
})?
|
||||
}
|
||||
@@ -0,0 +1,734 @@
|
||||
use super::*;
|
||||
use crate::api::discovery::http_tests::Fixture;
|
||||
use crate::maestro::generation::test_runtime_generation;
|
||||
use serde_json::json;
|
||||
use tokio::sync::watch;
|
||||
|
||||
async fn fixture(source: &str, read_only: bool) -> (Fixture, watch::Sender<Arc<ProxyConfig>>) {
|
||||
let fixture = Fixture::new(false);
|
||||
std::fs::write(&fixture.shared.config_path, format!("{source}\n[server.api]\nenabled = true\nread_only = {read_only}\nauth_header = \"Bearer discovery-test\"\n")).unwrap();
|
||||
let config = ProxyConfig::load_prepared(fixture.shared.config_path.clone())
|
||||
.await
|
||||
.unwrap()
|
||||
.config;
|
||||
let mut runtime = test_runtime_generation(1, config);
|
||||
let (sender, receiver) = watch::channel(runtime.config());
|
||||
Arc::get_mut(&mut runtime).unwrap().config_rx = receiver;
|
||||
fixture.shared.active_runtime.store(runtime);
|
||||
(fixture, sender)
|
||||
}
|
||||
|
||||
fn files(fixture: &Fixture) -> std::collections::BTreeMap<PathBuf, Vec<u8>> {
|
||||
std::fs::read_dir(fixture.shared.config_path.parent().unwrap())
|
||||
.unwrap()
|
||||
.map(|entry| {
|
||||
let path = entry.unwrap().path();
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
(path, bytes)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn preview(fixture: &Fixture, patch: Json) -> preflight::ValidationResponse {
|
||||
validate_config(patch, None, None, None, &fixture.shared)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unknown_nested_patch_key_is_rejected_before_serde_discards_it() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("config.toml");
|
||||
let source = "[general]\nconfig_strict = true\n";
|
||||
std::fs::write(&path, source).unwrap();
|
||||
let result = apply_patch_to_path(
|
||||
&path,
|
||||
&serde_json::json!({"general": {"me_keepalive_enabld": true}}),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
result.is_err(),
|
||||
"unknown nested key must not become a successful write"
|
||||
);
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), source);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preflight_http_auth_read_only_queries_and_no_side_effects() {
|
||||
let (fixture, _sender) = fixture("", true).await;
|
||||
let before = files(&fixture);
|
||||
let active = fixture.shared.active_runtime.load_full();
|
||||
let patch = json!({"general":{"log_level":"debug"}});
|
||||
for (method, path, authorized, status, code) in [
|
||||
("POST", "/v1/config/validate", false, 401, "unauthorized"),
|
||||
(
|
||||
"GET",
|
||||
"/v1/config/validate",
|
||||
true,
|
||||
405,
|
||||
"method_not_allowed",
|
||||
),
|
||||
(
|
||||
"POST",
|
||||
"/v1/config/validate?timeout_secs=1",
|
||||
true,
|
||||
400,
|
||||
"bad_request",
|
||||
),
|
||||
(
|
||||
"POST",
|
||||
"/v1/config/validate?reload=drain",
|
||||
true,
|
||||
400,
|
||||
"bad_request",
|
||||
),
|
||||
("PATCH", "/v1/config", true, 403, "read_only"),
|
||||
] {
|
||||
let response = fixture
|
||||
.request_body(method, path, authorized, Some(&patch), &[])
|
||||
.await;
|
||||
assert_eq!(response.0, status, "{}", response.2);
|
||||
assert_eq!(response.2["error"]["code"], code);
|
||||
if status == 405 {
|
||||
assert_eq!(response.1, "POST");
|
||||
}
|
||||
}
|
||||
let response = fixture
|
||||
.request_body(
|
||||
"POST",
|
||||
"/v1/config/validate?reload=drain&timeout_secs=10",
|
||||
true,
|
||||
Some(&patch),
|
||||
&[],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.0, 200, "{}", response.2);
|
||||
assert_eq!(response.2["data"]["valid"], true);
|
||||
assert_eq!(response.2["data"]["reload"]["mode"], "drain");
|
||||
assert_eq!(response.2["revision"], response.2["data"]["base_revision"]);
|
||||
assert_eq!(files(&fixture), before);
|
||||
assert!(Arc::ptr_eq(
|
||||
&fixture.shared.active_runtime.load_full(),
|
||||
&active
|
||||
));
|
||||
assert!(Arc::ptr_eq(
|
||||
&fixture.shared.active_runtime.load().config(),
|
||||
&active.config()
|
||||
));
|
||||
assert!(fixture.shared.reload_control.in_progress().await.is_none());
|
||||
assert!(fixture.shared.reload_control.status(1).await.is_none());
|
||||
assert!(fixture.shared.runtime_events.snapshot(64).events.is_empty());
|
||||
let denied = Fixture::new(true);
|
||||
assert_eq!(
|
||||
denied
|
||||
.request_body("POST", "/v1/config/validate", true, Some(&patch), &[])
|
||||
.await
|
||||
.0,
|
||||
403
|
||||
);
|
||||
let caps = fixture.request("GET", "/v1/capabilities", true).await.2;
|
||||
let operation = caps["data"]["operations"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|op| op["id"] == "config_validate")
|
||||
.unwrap();
|
||||
assert_eq!(operation["mutable"], false);
|
||||
assert_eq!(operation["available"], true);
|
||||
assert!(operation["mutation_blocked_reason"].is_null());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preflight_commit_parity_for_hot_generation_and_process_changes() {
|
||||
let (fixture, _sender) = fixture("", false).await;
|
||||
let active = fixture.shared.active_runtime.load().config();
|
||||
let patch = json!({"general":{
|
||||
"log_level":"debug", "me_keepalive_interval_secs":active.general.me_keepalive_interval_secs + 5,
|
||||
"disable_colors":!active.general.disable_colors
|
||||
}});
|
||||
let before = files(&fixture);
|
||||
let response = preview(&fixture, patch.clone()).await;
|
||||
assert_eq!(response.apply.watcher_paths, ["general.log_level"]);
|
||||
assert_eq!(
|
||||
response.apply.generation_paths,
|
||||
["general.me_keepalive_interval_secs"]
|
||||
);
|
||||
assert_eq!(
|
||||
response.apply.process_restart_paths,
|
||||
["general.disable_colors"]
|
||||
);
|
||||
assert_eq!(
|
||||
response.apply.deferred_process_fields,
|
||||
["general.disable_colors"]
|
||||
);
|
||||
assert_eq!(files(&fixture), before);
|
||||
let committed = fixture
|
||||
.request_body(
|
||||
"PATCH",
|
||||
"/v1/config",
|
||||
true,
|
||||
Some(&patch),
|
||||
&[
|
||||
("If-Match", &response.base_revision),
|
||||
("If-Runtime-Match", &response.runtime.runtime_match),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(committed.0, 200, "{}", committed.2);
|
||||
let data = &committed.2["data"];
|
||||
assert_eq!(data["revision"], response.candidate_revision);
|
||||
assert_eq!(data["changed_paths"], json!(response.changed_paths));
|
||||
assert_eq!(data["restart_required"], response.apply.restart_required);
|
||||
assert_eq!(
|
||||
data["runtime_reload_required"],
|
||||
response.apply.runtime_reload_required
|
||||
);
|
||||
assert_eq!(
|
||||
data["process_restart_required"],
|
||||
response.apply.process_restart_required
|
||||
);
|
||||
assert_eq!(data["changed"], json!(["general"]));
|
||||
assert_eq!(
|
||||
data["deferred_process_fields"],
|
||||
json!(response.apply.deferred_process_fields)
|
||||
);
|
||||
assert!(Arc::ptr_eq(
|
||||
&fixture.shared.active_runtime.load().config(),
|
||||
&active
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preflight_stale_source_and_runtime_tokens_reject_without_writes() {
|
||||
let (fixture, sender) = fixture("", false).await;
|
||||
let patch = json!({"general":{"log_level":"debug"}});
|
||||
let response = preview(&fixture, patch.clone()).await;
|
||||
let before = files(&fixture);
|
||||
for method in ["POST", "PATCH"] {
|
||||
let path = if method == "POST" {
|
||||
"/v1/config/validate"
|
||||
} else {
|
||||
"/v1/config"
|
||||
};
|
||||
let rejected = fixture
|
||||
.request_body(method, path, true, Some(&patch), &[("If-Match", "stale")])
|
||||
.await;
|
||||
assert_eq!(rejected.0, 409);
|
||||
assert_eq!(rejected.2["error"]["code"], "revision_conflict");
|
||||
let rejected = fixture
|
||||
.request_body(
|
||||
method,
|
||||
path,
|
||||
true,
|
||||
Some(&patch),
|
||||
&[("If-Runtime-Match", "invalid token")],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(rejected.0, 400);
|
||||
}
|
||||
// A -> B -> A retains the same generation and source bytes, but not its epoch.
|
||||
let original = (*sender.borrow()).as_ref().clone();
|
||||
let mut hot = original.clone();
|
||||
hot.general.log_level = crate::config::LogLevel::Verbose;
|
||||
sender.send(Arc::new(hot.with_publication_epoch())).unwrap();
|
||||
sender
|
||||
.send(Arc::new(original.with_publication_epoch()))
|
||||
.unwrap();
|
||||
for method in ["POST", "PATCH"] {
|
||||
let path = if method == "POST" {
|
||||
"/v1/config/validate"
|
||||
} else {
|
||||
"/v1/config"
|
||||
};
|
||||
let rejected = fixture
|
||||
.request_body(
|
||||
method,
|
||||
path,
|
||||
true,
|
||||
Some(&patch),
|
||||
&[
|
||||
("If-Match", &response.base_revision),
|
||||
("If-Runtime-Match", &response.runtime.runtime_match),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(rejected.0, 409, "{}", rejected.2);
|
||||
assert_eq!(rejected.2["error"]["code"], "runtime_conflict");
|
||||
}
|
||||
let fresh = preview(&fixture, patch.clone()).await;
|
||||
assert_eq!(
|
||||
fresh.runtime.active_generation,
|
||||
response.runtime.active_generation
|
||||
);
|
||||
assert!(fresh.runtime.config_epoch > response.runtime.config_epoch);
|
||||
let config = fixture.shared.active_runtime.load().config();
|
||||
fixture
|
||||
.shared
|
||||
.active_runtime
|
||||
.store(test_runtime_generation(2, (*config).clone()));
|
||||
assert_eq!(
|
||||
validate_config(
|
||||
patch,
|
||||
None,
|
||||
Some(fresh.runtime.runtime_match),
|
||||
None,
|
||||
&fixture.shared
|
||||
)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.code,
|
||||
"runtime_conflict"
|
||||
);
|
||||
assert_eq!(files(&fixture), before);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unknown_nested_and_variant_fields_never_silently_disappear() {
|
||||
let (fixture, _sender) = fixture("[general]\nconfig_strict = false\n", false).await;
|
||||
let before = files(&fixture);
|
||||
for (patch, expected) in [
|
||||
(
|
||||
json!({"general":{"me_keepalive_enabld":null,"log_level":"debug"}}),
|
||||
"general.me_keepalive_enabld",
|
||||
),
|
||||
(
|
||||
json!({"web":{"limits":{"max_boddy_bytes":123}}}),
|
||||
"web.limits.max_boddy_bytes",
|
||||
),
|
||||
(
|
||||
json!({"web":{"vhosts":[{"profiles":[{"unknwon":true}]}]}}),
|
||||
"web.vhosts[0].profiles[0].unknwon",
|
||||
),
|
||||
(
|
||||
json!({"upstreams":[{"type":"direct","password":"synthetic-credential"}]}),
|
||||
"upstreams[0].password",
|
||||
),
|
||||
(
|
||||
json!({"web":{"vhosts":[{"decoy":{"mode":"http_upstream","directory":"synthetic-credential"}}]}}),
|
||||
"web.vhosts[0].decoy.directory",
|
||||
),
|
||||
] {
|
||||
for method in ["POST", "PATCH"] {
|
||||
let path = if method == "POST" {
|
||||
"/v1/config/validate"
|
||||
} else {
|
||||
"/v1/config"
|
||||
};
|
||||
let response = fixture
|
||||
.request_body(method, path, true, Some(&patch), &[])
|
||||
.await;
|
||||
assert_eq!(response.0, 400, "{}", response.2);
|
||||
assert_eq!(response.2["error"]["details"][0]["path"], expected);
|
||||
assert!(!response.2.to_string().contains("synthetic-credential"));
|
||||
}
|
||||
assert_eq!(files(&fixture), before);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preflight_aliases_open_maps_nulls_and_credentials_are_redacted() {
|
||||
let (fixture, _sender) = fixture("", false).await;
|
||||
let patch = json!({
|
||||
"upstreams":[{"type":"direct","force_bind":"lo"}],
|
||||
"general":{"log_level":null},
|
||||
"dc_overrides":{"2":["149.154.167.50:443"]},
|
||||
"censorship":{"exclusive_mask":{"private-sentinel.example":"private-origin.example:443"}}
|
||||
});
|
||||
let response = preview(&fixture, patch.clone()).await;
|
||||
let encoded = serde_json::to_value(&response).unwrap();
|
||||
assert!(
|
||||
encoded["normalization_effects"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.contains(&json!({"path":"upstreams[0].bindtodevice","code":"alias_canonicalized"}))
|
||||
);
|
||||
assert!(
|
||||
encoded["normalization_effects"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.contains(&json!({"path":"general.log_level","code":"null_ignored"}))
|
||||
);
|
||||
assert!(
|
||||
response
|
||||
.changed_paths
|
||||
.contains(&"dc_overrides.{dc}[0]".into())
|
||||
);
|
||||
assert!(
|
||||
response
|
||||
.changed_paths
|
||||
.contains(&"censorship.exclusive_mask.{hostname}".into())
|
||||
);
|
||||
assert!(!encoded.to_string().contains("private-"));
|
||||
let credential_change = preview(
|
||||
&fixture,
|
||||
json!({"upstreams":[{
|
||||
"type":"socks5", "address":"127.0.0.1:1080", "password":"synthetic-diff-credential"
|
||||
}]}),
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
credential_change
|
||||
.changed_paths
|
||||
.contains(&"upstreams[0].password".into())
|
||||
);
|
||||
assert!(
|
||||
!serde_json::to_string(&credential_change)
|
||||
.unwrap()
|
||||
.contains("synthetic-diff-credential")
|
||||
);
|
||||
// The strict-key facade must leave open user maps to their owner API.
|
||||
let open_users: Toml =
|
||||
toml::from_str("[access.users]\n'arbitrary.user-name' = 'synthetic-user-secret'\n")
|
||||
.unwrap();
|
||||
assert!(ProxyConfig::unknown_source_paths(&open_users).is_empty());
|
||||
let committed = patch_config(
|
||||
patch,
|
||||
Some(response.base_revision),
|
||||
None,
|
||||
None,
|
||||
&fixture.shared,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(committed.revision, response.candidate_revision);
|
||||
assert!(
|
||||
std::fs::read_to_string(&fixture.shared.config_path)
|
||||
.unwrap()
|
||||
.contains("bindtodevice")
|
||||
);
|
||||
for patch in [
|
||||
json!({"general":{"me_writer_pick_mode":"synthetic-credential"}}),
|
||||
json!({"upstreams":[{"type":"shadowsocks","url":"ss://synthetic-credential@private-sentinel.example"}]}),
|
||||
json!({"web":{"carrier_method":"synthetic-credential"}}),
|
||||
] {
|
||||
let error = validate_config(patch, None, None, None, &fixture.shared)
|
||||
.await
|
||||
.unwrap_err();
|
||||
let public = format!(
|
||||
"{} {}",
|
||||
error.message,
|
||||
serde_json::to_string(&error.details).unwrap()
|
||||
);
|
||||
assert!(!public.contains("synthetic-credential"), "{public}");
|
||||
assert!(!public.contains("private-sentinel"));
|
||||
assert!(!error.details.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preflight_multi_source_conflict_and_conditional_web_capacity() {
|
||||
let (fixture, _sender) = fixture("", false).await;
|
||||
let path = &fixture.shared.config_path;
|
||||
let old = std::fs::read_to_string(path).unwrap();
|
||||
std::fs::write(path, format!("include = \"censorship.toml\"\n{old}")).unwrap();
|
||||
std::fs::write(
|
||||
path.parent().unwrap().join("censorship.toml"),
|
||||
"[censorship]\ntls_domain = \"old.example\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
let before = files(&fixture);
|
||||
let patch = json!({"general":{"log_level":"debug"},"censorship":{"tls_domain":"new.example"}});
|
||||
for commit in [false, true] {
|
||||
let error = if commit {
|
||||
patch_config(patch.clone(), None, None, None, &fixture.shared)
|
||||
.await
|
||||
.err()
|
||||
.unwrap()
|
||||
} else {
|
||||
validate_config(patch.clone(), None, None, None, &fixture.shared)
|
||||
.await
|
||||
.unwrap_err()
|
||||
};
|
||||
assert_eq!(error.code, "config_patch_not_atomic");
|
||||
assert_eq!(error.details[0].code, "source_ownership_conflict");
|
||||
assert_eq!(files(&fixture), before);
|
||||
}
|
||||
let (fixture, _sender) =
|
||||
self::fixture("[web.limits]\ndebug_bytes_global = 4096\n", false).await;
|
||||
let hot = preview(&fixture, json!({"web":{"debug":{"body_prefix_bytes":128}}})).await;
|
||||
assert!(
|
||||
hot.apply
|
||||
.watcher_paths
|
||||
.contains(&"web.debug.body_prefix_bytes".into())
|
||||
);
|
||||
let deferred = preview(
|
||||
&fixture,
|
||||
json!({"web":{"limits":{"debug_bytes_global":8192},"debug":{"body_prefix_bytes":6144}}}),
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
!deferred
|
||||
.apply
|
||||
.watcher_paths
|
||||
.contains(&"web.debug.body_prefix_bytes".into())
|
||||
);
|
||||
assert!(
|
||||
deferred
|
||||
.apply
|
||||
.process_restart_paths
|
||||
.contains(&"web.debug.body_prefix_bytes".into())
|
||||
);
|
||||
assert!(
|
||||
deferred
|
||||
.apply
|
||||
.deferred_process_fields
|
||||
.contains(&"web.debug".into())
|
||||
);
|
||||
let result = patch_config(
|
||||
json!({"web":{"limits":{"debug_bytes_global":8192},"debug":{"body_prefix_bytes":6144}}}),
|
||||
Some(deferred.base_revision),
|
||||
None,
|
||||
None,
|
||||
&fixture.shared,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
result.deferred_process_fields,
|
||||
deferred.apply.deferred_process_fields
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preflight_runtime_fence_rejects_at_atomic_persistence_and_removes_staging_file() {
|
||||
let (fixture, sender) = fixture("", false).await;
|
||||
let fence = preflight::RuntimeFence::capture(&fixture.shared, None).unwrap();
|
||||
let patch = json!({"general":{"log_level":"debug"}});
|
||||
let prepared = prepare_patch_to_path(&fixture.shared.config_path, &patch, None)
|
||||
.await
|
||||
.unwrap();
|
||||
let before = std::fs::read(&fixture.shared.config_path).unwrap();
|
||||
let mut changed = (*fence.config).clone();
|
||||
changed.general.log_level = crate::config::LogLevel::Verbose;
|
||||
sender
|
||||
.send(Arc::new(changed.with_publication_epoch()))
|
||||
.unwrap();
|
||||
let error = crate::api::config_store::write_atomic_with_runtime_check(
|
||||
prepared.config_path,
|
||||
prepared.expected_revision,
|
||||
prepared.owner_path,
|
||||
prepared.expected_owner_contents,
|
||||
prepared.owner_contents,
|
||||
Some(fence.commit_check()),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.code, "runtime_conflict");
|
||||
assert_eq!(std::fs::read(&fixture.shared.config_path).unwrap(), before);
|
||||
assert!(
|
||||
files(&fixture)
|
||||
.keys()
|
||||
.all(|path| path.ends_with("config.toml") || path.ends_with("config.toml.lock"))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preflight_concurrency_budget_does_not_block_or_reserve_reload() {
|
||||
let (fixture, _sender) = fixture("", false).await;
|
||||
let permits = fixture
|
||||
.shared
|
||||
.config_preflight_slots
|
||||
.clone()
|
||||
.acquire_many_owned(2)
|
||||
.await
|
||||
.unwrap();
|
||||
let response = fixture
|
||||
.request_body(
|
||||
"POST",
|
||||
"/v1/config/validate",
|
||||
true,
|
||||
Some(&json!({"general":{"log_level":"debug"}})),
|
||||
&[],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.0, 429);
|
||||
assert_eq!(response.2["error"]["code"], "config_preflight_busy");
|
||||
drop(permits);
|
||||
let _ = preview(&fixture, json!({"general":{"log_level":"debug"}})).await;
|
||||
assert!(fixture.shared.reload_control.in_progress().await.is_none());
|
||||
}
|
||||
|
||||
fn abandoned_preflight_retains_budget(timeout: bool) {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.max_blocking_threads(1)
|
||||
.build()
|
||||
.unwrap();
|
||||
runtime.block_on(async {
|
||||
let (fixture, _sender) = fixture("", false).await;
|
||||
let before = files(&fixture);
|
||||
let active = fixture.shared.active_runtime.load().config();
|
||||
let (release, wait) = std::sync::mpsc::channel();
|
||||
let (started, ready) = tokio::sync::oneshot::channel();
|
||||
let blocker = tokio::task::spawn_blocking(move || {
|
||||
started.send(()).unwrap();
|
||||
wait.recv().unwrap();
|
||||
});
|
||||
ready.await.unwrap();
|
||||
tokio::time::pause();
|
||||
let shared = fixture.shared.clone();
|
||||
let task = tokio::spawn(async move {
|
||||
validate_config(
|
||||
json!({"general":{"log_level":"debug"}}),
|
||||
None,
|
||||
None,
|
||||
Some(ReloadRequest::default()),
|
||||
&shared,
|
||||
)
|
||||
.await
|
||||
});
|
||||
// The only blocking thread is occupied; candidate parsing is queued.
|
||||
while fixture.shared.config_preflight_slots.available_permits() == 2 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
if timeout {
|
||||
tokio::time::advance(std::time::Duration::from_secs(31)).await;
|
||||
let error = task.await.unwrap().unwrap_err();
|
||||
assert_eq!(error.status, hyper::StatusCode::GATEWAY_TIMEOUT);
|
||||
assert_eq!(error.code, "config_preflight_timeout");
|
||||
} else {
|
||||
task.abort();
|
||||
assert!(task.await.unwrap_err().is_cancelled());
|
||||
}
|
||||
assert_eq!(fixture.shared.config_preflight_slots.available_permits(), 1);
|
||||
tokio::time::resume();
|
||||
release.send(()).unwrap();
|
||||
blocker.await.unwrap();
|
||||
let _permits = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(5),
|
||||
fixture
|
||||
.shared
|
||||
.config_preflight_slots
|
||||
.clone()
|
||||
.acquire_many_owned(2),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(files(&fixture), before);
|
||||
assert!(Arc::ptr_eq(
|
||||
&fixture.shared.active_runtime.load().config(),
|
||||
&active
|
||||
));
|
||||
assert!(fixture.shared.reload_control.status(1).await.is_none());
|
||||
assert!(fixture.shared.runtime_events.snapshot(64).events.is_empty());
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_cancellation_retains_budget_until_abandoned_worker_finishes() {
|
||||
abandoned_preflight_retains_budget(false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_timeout_retains_budget_until_abandoned_worker_finishes() {
|
||||
abandoned_preflight_retains_budget(true);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preflight_dns_failure_and_normalization_share_commit_preparation() {
|
||||
let source = r#"
|
||||
[access.users]
|
||||
alice = "000102030405060708090a0b0c0d0e0f"
|
||||
[[server.listeners]]
|
||||
ip = "127.0.0.1"
|
||||
port = 18080
|
||||
transport = "web"
|
||||
web_trusted_proxy_cidrs = ["127.0.0.1/32"]
|
||||
[web]
|
||||
enabled = true
|
||||
[[web.vhosts]]
|
||||
host = "proxy.example.com"
|
||||
public_addr = "203.0.113.10:443"
|
||||
[web.vhosts.decoy]
|
||||
mode = "http_upstream"
|
||||
upstream = "http://127.0.0.1:18081"
|
||||
[[web.vhosts.profiles]]
|
||||
user = "alice"
|
||||
secret_mode = "dd"
|
||||
"#;
|
||||
let (fixture, _sender) = fixture(source, false).await;
|
||||
let mut vhosts =
|
||||
serde_json::to_value(&fixture.shared.active_runtime.load().config().web.vhosts).unwrap();
|
||||
vhosts[0]["host"] = json!("MixedCase.Example.COM");
|
||||
let patch = json!({"web":{"vhosts":vhosts}});
|
||||
let normalized = preview(&fixture, patch.clone()).await;
|
||||
assert!(
|
||||
normalized
|
||||
.normalization_effects
|
||||
.iter()
|
||||
.any(|effect| effect.path == "web.vhosts[0].host" && effect.code == "normalized")
|
||||
);
|
||||
let committed = patch_config(
|
||||
patch,
|
||||
Some(normalized.base_revision),
|
||||
None,
|
||||
None,
|
||||
&fixture.shared,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(committed.revision, normalized.candidate_revision);
|
||||
let before = files(&fixture);
|
||||
// The reserved .invalid TLD cannot yield a usable decoy origin. DNS itself
|
||||
// remains bounded by the configured one-second preparation timeout.
|
||||
vhosts[0]["decoy"] = json!({"mode":"http_upstream", "upstream":"http://preflight-unresolvable.invalid:18081", "resolve":"startup"});
|
||||
let patch = json!({"web":{"vhosts":vhosts,"timeouts":{"decoy_resolve_secs":1}}});
|
||||
for commit in [false, true] {
|
||||
let error = if commit {
|
||||
patch_config(patch.clone(), None, None, None, &fixture.shared)
|
||||
.await
|
||||
.err()
|
||||
.unwrap()
|
||||
} else {
|
||||
validate_config(patch.clone(), None, None, None, &fixture.shared)
|
||||
.await
|
||||
.unwrap_err()
|
||||
};
|
||||
assert_eq!(error.status, hyper::StatusCode::BAD_REQUEST);
|
||||
assert_eq!(error.details[0].code, "preparation_failed");
|
||||
assert!(!error.message.contains("preflight-unresolvable"));
|
||||
assert_eq!(files(&fixture), before);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preflight_invalid_current_source_preserves_status_and_hides_source_excerpt() {
|
||||
let (fixture, _sender) = fixture("", false).await;
|
||||
std::fs::write(
|
||||
&fixture.shared.config_path,
|
||||
"[general]\nme_writer_pick_mode = 'synthetic-source-credential'\n",
|
||||
)
|
||||
.unwrap();
|
||||
let before = files(&fixture);
|
||||
for method in ["POST", "PATCH"] {
|
||||
let path = if method == "POST" {
|
||||
"/v1/config/validate"
|
||||
} else {
|
||||
"/v1/config"
|
||||
};
|
||||
let response = fixture
|
||||
.request_body(
|
||||
method,
|
||||
path,
|
||||
true,
|
||||
Some(&json!({"general":{"log_level":"debug"}})),
|
||||
&[],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.0, 500);
|
||||
assert_eq!(response.2["error"]["code"], "internal_error");
|
||||
assert_eq!(
|
||||
response.2["error"]["details"][0]["code"],
|
||||
"source_load_failed"
|
||||
);
|
||||
assert!(
|
||||
!response
|
||||
.2
|
||||
.to_string()
|
||||
.contains("synthetic-source-credential")
|
||||
);
|
||||
assert_eq!(files(&fixture), before);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
//! One source-preserving candidate pipeline shared by preview and commit.
|
||||
use super::*;
|
||||
use crate::api::config_store::{FieldEdit, prepare_field_edits};
|
||||
use crate::config::{LoadedConfig, ParsedConfigSource};
|
||||
use tokio::sync::OwnedSemaphorePermit;
|
||||
|
||||
pub(super) type PreparationLease = Arc<Option<OwnedSemaphorePermit>>;
|
||||
|
||||
struct PatchSource {
|
||||
config_path: PathBuf,
|
||||
expected_revision: String,
|
||||
owner_path: PathBuf,
|
||||
expected_owner_contents: String,
|
||||
owner_contents: String,
|
||||
old_config: ProxyConfig,
|
||||
requested_config: ProxyConfig,
|
||||
patch: Json,
|
||||
touched: Vec<String>,
|
||||
alias_effects: Vec<diagnostics::NormalizationEffect>,
|
||||
}
|
||||
|
||||
pub(super) async fn prepare_patch_to_path(
|
||||
config_path: &Path,
|
||||
patch: &Json,
|
||||
expected: Option<String>,
|
||||
) -> Result<PreparedConfigPatch, ApiFailure> {
|
||||
prepare_guarded(config_path, patch, expected, Arc::new(None)).await
|
||||
}
|
||||
|
||||
pub(super) async fn prepare_guarded(
|
||||
config_path: &Path,
|
||||
patch: &Json,
|
||||
expected: Option<String>,
|
||||
guard: PreparationLease,
|
||||
) -> Result<PreparedConfigPatch, ApiFailure> {
|
||||
let config_path = config_path.to_path_buf();
|
||||
let patch = patch.clone();
|
||||
let worker_guard = guard.clone();
|
||||
let (source, details) = tokio::task::spawn_blocking(move || {
|
||||
let _guard = worker_guard;
|
||||
parse_patch(&config_path, &patch, expected)
|
||||
})
|
||||
.await
|
||||
.map_err(|_| ApiFailure::internal("Candidate source worker failed"))??;
|
||||
let candidate = source
|
||||
.prepare_guarded(guard.clone())
|
||||
.await
|
||||
.map_err(|error| {
|
||||
diagnostics::validation_error("preparation_failed", "web.vhosts[].decoy", error)
|
||||
})?;
|
||||
tokio::task::spawn_blocking(move || finish(details, candidate, guard))
|
||||
.await
|
||||
.map_err(|_| ApiFailure::internal("Candidate classification worker failed"))?
|
||||
}
|
||||
|
||||
fn parse_patch(
|
||||
config_path: &Path,
|
||||
patch_json: &Json,
|
||||
expected_revision: Option<String>,
|
||||
) -> Result<(ParsedConfigSource, PatchSource), ApiFailure> {
|
||||
// 1. optimistic concurrency
|
||||
let loaded = ProxyConfig::parse_source(config_path)
|
||||
.map_err(|error| diagnostics::validation_error("source_load_failed", "$", error))?;
|
||||
let current = compute_snapshot_revision(&loaded.source_contents);
|
||||
if expected_revision.is_some_and(|expected| expected != current) {
|
||||
return Err(ApiFailure::new(
|
||||
hyper::StatusCode::CONFLICT,
|
||||
"revision_conflict",
|
||||
"Config revision mismatch",
|
||||
));
|
||||
}
|
||||
|
||||
// 2. Reject access, unknown sections and forbidden partial-section fields.
|
||||
let mut patch_toml = json_to_toml(patch_json)
|
||||
.map_err(|e| ApiFailure::bad_request(format!("invalid patch: {}", e)))?;
|
||||
let patch_table = patch_toml
|
||||
.as_table()
|
||||
.ok_or_else(|| ApiFailure::bad_request("patch must be a JSON object"))?;
|
||||
if patch_table.contains_key("access") {
|
||||
return Err(ApiFailure::new(
|
||||
hyper::StatusCode::BAD_REQUEST,
|
||||
"access_not_editable",
|
||||
"access.* is managed via the users API, not editable here",
|
||||
));
|
||||
}
|
||||
for key in patch_table.keys() {
|
||||
if !is_editable_section(key.as_str()) {
|
||||
return Err(ApiFailure::new(
|
||||
hyper::StatusCode::BAD_REQUEST,
|
||||
"section_not_editable",
|
||||
format!("section not editable: {}", key),
|
||||
));
|
||||
}
|
||||
if key == "server" {
|
||||
validate_server_patch(&patch_json["server"])?;
|
||||
} else if key == "network" {
|
||||
validate_network_patch(&patch_json["network"])?;
|
||||
}
|
||||
}
|
||||
let touched: Vec<String> = patch_table
|
||||
.keys()
|
||||
.map(|k| k.as_str())
|
||||
.filter(|k| is_editable_section(k))
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
if touched.is_empty() {
|
||||
return Err(ApiFailure::bad_request("empty patch: no editable sections"));
|
||||
}
|
||||
|
||||
diagnostics::reject_unknown(patch_json)?;
|
||||
let alias_effects = diagnostics::canonicalize_aliases(&mut patch_toml)?;
|
||||
|
||||
// 3. Merge against the fully expanded and normalized desired config. The
|
||||
// source owner is resolved separately so included sections stay in their
|
||||
// original file and unrelated source files remain byte-identical.
|
||||
let old_cfg = loaded.config.clone();
|
||||
let mut merged = Toml::try_from(&old_cfg)
|
||||
.map_err(|e| ApiFailure::internal(format!("failed to serialize config: {}", e)))?;
|
||||
deep_merge(&mut merged, &patch_toml);
|
||||
ProxyConfig::validate_decoy_source_keys(&merged)
|
||||
.map_err(|error| diagnostics::validation_error("constraint_violation", "$", error))?;
|
||||
|
||||
let requested_cfg: ProxyConfig = merged
|
||||
.clone()
|
||||
.try_into()
|
||||
.map_err(|error| diagnostics::validation_error("deserialization_failed", "$", error))?;
|
||||
requested_cfg
|
||||
.validate()
|
||||
.map_err(|error| diagnostics::validation_error("constraint_violation", "$", error))?;
|
||||
|
||||
let api_edits = api_field_edits(&loaded, &patch_toml)?;
|
||||
let api_source = prepare_field_edits(&loaded, config_path, &api_edits)
|
||||
.map_err(diagnostics::source_conflict)?;
|
||||
let patch_listeners = patch_toml
|
||||
.get("server")
|
||||
.is_some_and(|server| server.get("listeners").is_some());
|
||||
let ownership_targets: Vec<&str> = touched
|
||||
.iter()
|
||||
.filter_map(|section| {
|
||||
if section == "server" {
|
||||
patch_listeners.then_some("server.listeners")
|
||||
} else if section == "network" {
|
||||
Some("network.dns_overrides")
|
||||
} else {
|
||||
Some(section.as_str())
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let section_owner = if ownership_targets.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(
|
||||
resolve_single_source_owner(&loaded, config_path, &ownership_targets)
|
||||
.map_err(diagnostics::source_conflict)?,
|
||||
)
|
||||
};
|
||||
if let (Some(owner), Some(api)) = (§ion_owner, &api_source) {
|
||||
if *owner != api.owner_path {
|
||||
return Err(ApiFailure::new(
|
||||
hyper::StatusCode::CONFLICT,
|
||||
"config_patch_not_atomic",
|
||||
"Mutation requires one independently writable config source",
|
||||
));
|
||||
}
|
||||
}
|
||||
let owner_path = section_owner
|
||||
.or_else(|| api_source.as_ref().map(|source| source.owner_path.clone()))
|
||||
.ok_or_else(|| ApiFailure::bad_request("empty patch: no editable fields"))?;
|
||||
let mut owner_contents = loaded
|
||||
.source_contents
|
||||
.get(&owner_path)
|
||||
.cloned()
|
||||
.ok_or_else(|| ApiFailure::internal("config source owner is missing from snapshot"))?;
|
||||
let expected_owner_contents = owner_contents.clone();
|
||||
if let Some(api) = api_source {
|
||||
owner_contents = api.owner_contents;
|
||||
}
|
||||
for section in &touched {
|
||||
if *section == "server" {
|
||||
if patch_listeners {
|
||||
let rendered = render_server_listeners(&requested_cfg)?;
|
||||
owner_contents = upsert_toml_table(&owner_contents, "server.listeners", &rendered);
|
||||
}
|
||||
} else if *section == "network" {
|
||||
owner_contents =
|
||||
upsert_dns_overrides(&owner_contents, &requested_cfg.network.dns_overrides)?;
|
||||
} else {
|
||||
let rendered = render_top_level_section(&requested_cfg, section)?;
|
||||
owner_contents = upsert_toml_table(&owner_contents, section, &rendered);
|
||||
}
|
||||
}
|
||||
|
||||
let mut overrides = loaded.source_contents.clone();
|
||||
overrides.insert(owner_path.clone(), owner_contents.clone());
|
||||
let candidate = ProxyConfig::parse_source_with_overrides(config_path, &overrides)
|
||||
.map_err(|error| diagnostics::validation_error("constraint_violation", "$", error))?;
|
||||
if patch_listeners
|
||||
&& serde_json::to_value(&candidate.config.server.listeners).ok()
|
||||
!= serde_json::to_value(&requested_cfg.server.listeners).ok()
|
||||
{
|
||||
return Err(ApiFailure::new(
|
||||
hyper::StatusCode::BAD_REQUEST,
|
||||
"ambiguous_listeners",
|
||||
"server.listeners normalizes to a different effective listener set",
|
||||
));
|
||||
}
|
||||
Ok((
|
||||
candidate,
|
||||
PatchSource {
|
||||
config_path: config_path.to_path_buf(),
|
||||
expected_revision: current,
|
||||
owner_path,
|
||||
expected_owner_contents,
|
||||
owner_contents,
|
||||
old_config: old_cfg,
|
||||
requested_config: requested_cfg,
|
||||
patch: patch_json.clone(),
|
||||
touched,
|
||||
alias_effects,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
fn api_field_edits(
|
||||
loaded: &ParsedConfigSource,
|
||||
patch: &Toml,
|
||||
) -> Result<Vec<FieldEdit>, ApiFailure> {
|
||||
let Some(fields) = patch
|
||||
.get("server")
|
||||
.and_then(|server| server.get("api"))
|
||||
.and_then(Toml::as_table)
|
||||
else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
if fields.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
// PATCH uses canonical paths, while an authored legacy table keeps its name.
|
||||
let mut table_name = "api";
|
||||
for source in loaded.source_contents.values() {
|
||||
let document: Toml = toml::from_str(source).map_err(|_| {
|
||||
ApiFailure::new(
|
||||
hyper::StatusCode::CONFLICT,
|
||||
"config_patch_not_atomic",
|
||||
"Mutation requires one independently writable config source",
|
||||
)
|
||||
})?;
|
||||
if document
|
||||
.get("server")
|
||||
.and_then(|server| server.get("admin_api"))
|
||||
.is_some()
|
||||
{
|
||||
table_name = "admin_api";
|
||||
}
|
||||
}
|
||||
Ok(fields
|
||||
.iter()
|
||||
.map(|(field, value)| FieldEdit::new(&["server", table_name, field], Some(value.clone())))
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn finish(
|
||||
source: PatchSource,
|
||||
candidate: LoadedConfig,
|
||||
guard: PreparationLease,
|
||||
) -> Result<PreparedConfigPatch, ApiFailure> {
|
||||
let revision = compute_snapshot_revision(&candidate.source_contents);
|
||||
let new_config = candidate.config;
|
||||
let class = classify_config_changes(&source.old_config, &new_config);
|
||||
let deferred_process_fields = deferred_process_fields(&source.old_config, &new_config)
|
||||
.map_err(|error| diagnostics::validation_error("effective_config_invalid", "web", error))?;
|
||||
let old = serde_json::to_value(&source.old_config)
|
||||
.map_err(|_| ApiFailure::internal("Cannot project source fields"))?;
|
||||
let new = serde_json::to_value(&new_config)
|
||||
.map_err(|_| ApiFailure::internal("Cannot project candidate fields"))?;
|
||||
let changed_paths = diagnostics::changed_paths(&old, &new);
|
||||
let mut normalization_effects =
|
||||
diagnostics::normalization(&source.patch, &source.requested_config, &new_config)?;
|
||||
normalization_effects.extend(source.alias_effects);
|
||||
if changed_paths.len() > diagnostics::MAX_PATHS
|
||||
|| normalization_effects.len() > diagnostics::MAX_PATHS
|
||||
{
|
||||
return Err(ApiFailure::bad_request(
|
||||
"Mutation exceeds the 4096-path feedback limit",
|
||||
));
|
||||
}
|
||||
Ok(PreparedConfigPatch {
|
||||
config_path: source.config_path,
|
||||
expected_revision: source.expected_revision,
|
||||
owner_path: source.owner_path,
|
||||
expected_owner_contents: source.expected_owner_contents,
|
||||
owner_contents: source.owner_contents,
|
||||
desired_config: Arc::new(new_config),
|
||||
touched: source.touched,
|
||||
_guard: guard,
|
||||
response: PatchConfigResponse {
|
||||
revision,
|
||||
restart_required: class.restart_required,
|
||||
runtime_reload_required: class.restart_required,
|
||||
process_restart_required: !deferred_process_fields.is_empty(),
|
||||
deferred_process_fields,
|
||||
changed: class.changed,
|
||||
changed_paths,
|
||||
normalization_effects,
|
||||
reload: None,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -73,7 +73,7 @@ fn deep_merge_overlays_tables_and_replaces_scalars() {
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn temp_config(body: &str) -> (PathBuf, tempfile::TempDir) {
|
||||
pub(super) fn temp_config(body: &str) -> (PathBuf, tempfile::TempDir) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("config.toml");
|
||||
std::fs::write(&path, body).unwrap();
|
||||
@@ -228,8 +228,7 @@ async fn invalid_web_patch_does_not_modify_the_source() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_managed_config_returns_only_editable_sections() {
|
||||
// Full server (api/port) and network must not leak. Listeners-only server
|
||||
// is returned via the nested allowlist (covered in a dedicated test).
|
||||
// Server identity and network siblings must not leak through nested allowlists.
|
||||
let (path, _d) = temp_config(concat!(
|
||||
"[censorship]\ntls_domain = \"a\"\n",
|
||||
"[server]\nport = 443\n[server.api]\nauth_header = \"SECRET\"\n",
|
||||
@@ -241,14 +240,18 @@ async fn read_managed_config_returns_only_editable_sections() {
|
||||
assert!(table.contains_key("censorship"));
|
||||
let server = table["server"].as_table().unwrap();
|
||||
assert!(server.contains_key("listeners"));
|
||||
assert!(!server.contains_key("api"));
|
||||
assert_eq!(server["api"].as_table().unwrap().len(), 5);
|
||||
assert!(server["api"].get("auth_header").is_none());
|
||||
assert!(!server.contains_key("port"));
|
||||
assert!(!table.contains_key("network"));
|
||||
assert_eq!(
|
||||
serde_json::to_value(&table["network"]).unwrap(),
|
||||
serde_json::json!({"dns_overrides": []})
|
||||
);
|
||||
assert!(!table.contains_key("access"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_managed_config_returns_server_listeners_only() {
|
||||
async fn read_managed_config_returns_server_listeners_and_api_observability() {
|
||||
let (path, _d) = temp_config(concat!(
|
||||
"[censorship]\ntls_domain = \"a\"\n",
|
||||
"[server]\nport = 443\n",
|
||||
@@ -263,7 +266,8 @@ async fn read_managed_config_returns_server_listeners_only() {
|
||||
.as_table()
|
||||
.unwrap();
|
||||
assert!(server.contains_key("listeners"));
|
||||
assert!(!server.contains_key("api"));
|
||||
assert_eq!(server["api"].as_table().unwrap().len(), 5);
|
||||
assert!(server["api"].get("auth_header").is_none());
|
||||
assert!(!server.contains_key("port"));
|
||||
let listeners = server["listeners"].as_array().unwrap();
|
||||
assert_eq!(listeners.len(), 1);
|
||||
|
||||
@@ -0,0 +1,350 @@
|
||||
//! Shared value-free differences and conservative read-only config projections.
|
||||
|
||||
use serde::Serialize;
|
||||
use serde_json::Value as Json;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use super::model::ApiFailure;
|
||||
use crate::config::{ProxyConfig, observation::ConfigProvenance};
|
||||
|
||||
pub(super) const MAX_PATHS: usize = 4096;
|
||||
|
||||
pub(super) const SECTIONS: &[&str] = &[
|
||||
"general",
|
||||
"network",
|
||||
"server",
|
||||
"timeouts",
|
||||
"censorship",
|
||||
"upstreams",
|
||||
"dc_overrides",
|
||||
"web",
|
||||
"access",
|
||||
"logging",
|
||||
"root",
|
||||
];
|
||||
const MAX_FIELDS: usize = 1024;
|
||||
|
||||
pub(super) fn selected(path: &str, sections: &BTreeSet<String>) -> bool {
|
||||
let root = path.split(['.', '[']).next().unwrap_or_default();
|
||||
sections.contains(if SECTIONS.contains(&root) {
|
||||
root
|
||||
} else {
|
||||
"root"
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn retain_sections(value: &mut Json, sections: &BTreeSet<String>) {
|
||||
if let Some(object) = value.as_object_mut() {
|
||||
object.retain(|key, _| selected(key, sections));
|
||||
}
|
||||
}
|
||||
|
||||
struct Rule {
|
||||
public: bool,
|
||||
schema: Json,
|
||||
default: Option<Json>,
|
||||
}
|
||||
fn rules() -> Result<&'static BTreeMap<String, Rule>, ApiFailure> {
|
||||
static RULES: OnceLock<Result<BTreeMap<String, Rule>, String>> = OnceLock::new();
|
||||
RULES
|
||||
.get_or_init(|| {
|
||||
super::discovery::projection_rules()
|
||||
.map(|fields| {
|
||||
fields
|
||||
.into_iter()
|
||||
.map(|(path, public, schema, default)| {
|
||||
(
|
||||
path,
|
||||
Rule {
|
||||
public,
|
||||
schema,
|
||||
default,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.map_err(|_| "Cannot load configuration projection policy".to_owned())
|
||||
})
|
||||
.as_ref()
|
||||
.map_err(|error| ApiFailure::internal(error.clone()))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub(super) struct FieldProjection {
|
||||
pub(super) path: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
value: Option<Json>,
|
||||
redacted: bool,
|
||||
present: bool,
|
||||
entries: Option<usize>,
|
||||
differs: Option<bool>,
|
||||
origin: &'static str,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
inherited_from: Option<&'static str>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub(super) struct Projection {
|
||||
pub(super) fields: Vec<FieldProjection>,
|
||||
pub(super) truncated: bool,
|
||||
provenance: &'static str,
|
||||
/// Input provenance only; this is deliberately not named applied_revision.
|
||||
source_revision: Option<String>,
|
||||
source_count: Option<usize>,
|
||||
}
|
||||
|
||||
pub(super) fn project(
|
||||
config: &ProxyConfig,
|
||||
value: &Json,
|
||||
other: Option<&Json>,
|
||||
sections: &BTreeSet<String>,
|
||||
desired: bool,
|
||||
) -> Result<Projection, ApiFailure> {
|
||||
let rules = rules()?;
|
||||
let (provenance, source_revision, source_count) = match &config.provenance {
|
||||
ConfigProvenance::Source(source) => (
|
||||
"normalized_source",
|
||||
Some(source.revision.clone()),
|
||||
Some(source.source_count),
|
||||
),
|
||||
ConfigProvenance::Mixed => ("mixed_publication", None, None),
|
||||
ConfigProvenance::Unknown => ("unknown", None, None),
|
||||
};
|
||||
let mut output = Projection {
|
||||
fields: Vec::new(),
|
||||
truncated: false,
|
||||
provenance,
|
||||
source_revision,
|
||||
source_count,
|
||||
};
|
||||
struct Walk<'a> {
|
||||
config: &'a ProxyConfig,
|
||||
rules: &'a BTreeMap<String, Rule>,
|
||||
desired: bool,
|
||||
comparing: bool,
|
||||
}
|
||||
impl Walk<'_> {
|
||||
fn visit(
|
||||
&self,
|
||||
value: &Json,
|
||||
other: Option<&Json>,
|
||||
path: &str,
|
||||
canonical: &str,
|
||||
output: &mut Projection,
|
||||
) {
|
||||
if output.fields.len() >= MAX_FIELDS || path.len() > 256 {
|
||||
output.truncated = true;
|
||||
return;
|
||||
}
|
||||
let rule = self.rules.get(canonical);
|
||||
let public = rule.is_some_and(|rule| rule.public);
|
||||
let open_map = rule.is_some_and(|rule| {
|
||||
rule.schema
|
||||
.get("additionalProperties")
|
||||
.is_some_and(|value| value != &Json::Bool(false))
|
||||
}) || path == "dc_overrides"
|
||||
|| path == "censorship.exclusive_mask";
|
||||
if public
|
||||
&& !open_map
|
||||
&& let Some(object) = value.as_object()
|
||||
{
|
||||
if !object.is_empty() {
|
||||
for (key, child) in object {
|
||||
self.visit(
|
||||
child,
|
||||
other.and_then(|value| value.get(key)),
|
||||
&format!("{path}.{key}"),
|
||||
&format!("{canonical}.{key}"),
|
||||
output,
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
if public
|
||||
&& let Some(array) = value.as_array()
|
||||
&& rule.is_some_and(|rule| rule.schema["items"]["type"] == "object")
|
||||
{
|
||||
if !array.is_empty() {
|
||||
for (index, child) in array.iter().enumerate() {
|
||||
if let Some(object) = child.as_object() {
|
||||
for (key, field) in object {
|
||||
self.visit(
|
||||
field,
|
||||
other.and_then(|v| v.get(index)).and_then(|v| v.get(key)),
|
||||
&format!("{path}[{index}].{key}"),
|
||||
&format!("{canonical}[].{key}"),
|
||||
output,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Arbitrary strings and all dynamic identities are private, including
|
||||
// URL userinfo in a field whose static metadata says "public".
|
||||
let safe_scalar = |value: &Json, schema: &Json| {
|
||||
value.is_null()
|
||||
|| value.is_boolean()
|
||||
|| value.is_number()
|
||||
|| schema
|
||||
.get("enum")
|
||||
.and_then(Json::as_array)
|
||||
.is_some_and(|allowed| allowed.contains(value))
|
||||
};
|
||||
let runtime_derived = path == "censorship.fake_cert_len"
|
||||
&& matches!(&self.config.provenance, ConfigProvenance::Source(source) if source.generated_fake_cert_len);
|
||||
let generated = self.desired && runtime_derived;
|
||||
let visible = public
|
||||
&& !open_map
|
||||
&& !generated
|
||||
&& rule.is_some_and(|rule| {
|
||||
safe_scalar(value, &rule.schema)
|
||||
|| value.as_array().is_some_and(|array| {
|
||||
array.len() <= 32
|
||||
&& array
|
||||
.iter()
|
||||
.all(|item| safe_scalar(item, &rule.schema["items"]))
|
||||
})
|
||||
});
|
||||
let (origin, inherited_from) = if runtime_derived {
|
||||
("runtime_derived", None)
|
||||
} else if canonical == "upstreams[].prefer" && value.is_null() {
|
||||
("inherited", Some("network.prefer"))
|
||||
} else {
|
||||
(
|
||||
match &self.config.provenance {
|
||||
ConfigProvenance::Source(source)
|
||||
if source.explicit_paths.contains(path) =>
|
||||
{
|
||||
"source"
|
||||
}
|
||||
ConfigProvenance::Source(source) if !source.complete => "unknown",
|
||||
ConfigProvenance::Source(_)
|
||||
if rule.and_then(|rule| rule.default.as_ref()) == Some(value) =>
|
||||
{
|
||||
"type_default"
|
||||
}
|
||||
ConfigProvenance::Source(_) => "default_or_derived",
|
||||
ConfigProvenance::Mixed => "mixed_unknown",
|
||||
ConfigProvenance::Unknown => "unknown",
|
||||
},
|
||||
None,
|
||||
)
|
||||
};
|
||||
let present = !value.is_null()
|
||||
&& value.as_str().is_none_or(|v| !v.is_empty())
|
||||
&& value.as_object().is_none_or(|v| !v.is_empty())
|
||||
&& value.as_array().is_none_or(|v| !v.is_empty());
|
||||
output.fields.push(FieldProjection {
|
||||
path: path.to_owned(),
|
||||
value: visible.then(|| value.clone()),
|
||||
redacted: !visible,
|
||||
present,
|
||||
entries: value
|
||||
.as_object()
|
||||
.map(|v| v.len())
|
||||
.or_else(|| value.as_array().map(Vec::len)),
|
||||
differs: (self.comparing && !runtime_derived).then(|| other != Some(value)),
|
||||
origin,
|
||||
inherited_from,
|
||||
});
|
||||
}
|
||||
}
|
||||
let walk = Walk {
|
||||
config,
|
||||
rules,
|
||||
desired,
|
||||
comparing: other.is_some(),
|
||||
};
|
||||
if let Some(object) = value.as_object() {
|
||||
for (key, child) in object {
|
||||
if selected(key, sections) {
|
||||
walk.visit(
|
||||
child,
|
||||
other.and_then(|value| value.get(key)),
|
||||
key,
|
||||
key,
|
||||
&mut output,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// Paths only: no before/after values or dynamic keys are returned. Arrays use
|
||||
/// indices, open maps use their documented placeholder to avoid leaking identities.
|
||||
pub(super) fn changed_paths(old: &Json, new: &Json) -> Vec<String> {
|
||||
fn walk(old: Option<&Json>, new: Option<&Json>, path: &str, out: &mut BTreeSet<String>) {
|
||||
if old == new {
|
||||
return;
|
||||
}
|
||||
if out.len() > MAX_PATHS {
|
||||
return;
|
||||
}
|
||||
let map_key = if path == "dc_overrides" {
|
||||
Some("{dc}")
|
||||
} else if path == "censorship.exclusive_mask" {
|
||||
Some("{hostname}")
|
||||
} else if path.starts_with("access.") {
|
||||
Some("{entry}")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
match (old, new) {
|
||||
(Some(Json::Object(_)), _) | (_, Some(Json::Object(_))) => {
|
||||
let a = old.and_then(Json::as_object);
|
||||
let b = new.and_then(Json::as_object);
|
||||
let keys: BTreeSet<_> = a
|
||||
.into_iter()
|
||||
.flat_map(|v| v.keys())
|
||||
.chain(b.into_iter().flat_map(|v| v.keys()))
|
||||
.collect();
|
||||
if keys.is_empty() {
|
||||
out.insert(path.to_string());
|
||||
}
|
||||
for key in keys {
|
||||
let key_path = map_key.unwrap_or(key);
|
||||
let next = if path.is_empty() {
|
||||
key_path.to_string()
|
||||
} else {
|
||||
format!("{path}.{key_path}")
|
||||
};
|
||||
walk(
|
||||
a.and_then(|v| v.get(key)),
|
||||
b.and_then(|v| v.get(key)),
|
||||
&next,
|
||||
out,
|
||||
);
|
||||
}
|
||||
}
|
||||
(Some(Json::Array(_)), _) | (_, Some(Json::Array(_))) => {
|
||||
let a = old
|
||||
.and_then(Json::as_array)
|
||||
.map(Vec::as_slice)
|
||||
.unwrap_or_default();
|
||||
let b = new
|
||||
.and_then(Json::as_array)
|
||||
.map(Vec::as_slice)
|
||||
.unwrap_or_default();
|
||||
if a.is_empty() && b.is_empty() {
|
||||
out.insert(path.to_string());
|
||||
}
|
||||
for index in 0..a.len().max(b.len()) {
|
||||
walk(a.get(index), b.get(index), &format!("{path}[{index}]"), out);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
out.insert(path.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut paths = BTreeSet::new();
|
||||
walk(Some(old), Some(new), "", &mut paths);
|
||||
paths.into_iter().collect()
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
//! Bounded inspection of desired source and actual owner publications.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use http_body_util::Full;
|
||||
use hyper::{Response, StatusCode, body::Bytes};
|
||||
use serde::Serialize;
|
||||
use serde_json::Value as Json;
|
||||
|
||||
use super::config_edit::{RuntimeBaseline, RuntimeFence};
|
||||
use super::model::{ApiFailure, FieldIssue};
|
||||
use super::{ApiShared, config_projection as projection};
|
||||
use crate::config::{
|
||||
ProxyConfig,
|
||||
observation::{ConfigProvenance, WatchOutcome},
|
||||
};
|
||||
use crate::maestro::{reload::ReloadObservation, runtime_build::project_reload_config};
|
||||
|
||||
const MAX_RESPONSE_BYTES: usize = 512 * 1024;
|
||||
const MAX_STATE_PATHS: usize = 512;
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct Comparison {
|
||||
scope: &'static str,
|
||||
status: &'static str,
|
||||
pending_paths: Vec<String>,
|
||||
watcher_pending_paths: Vec<String>,
|
||||
generation_pending_paths: Vec<String>,
|
||||
process_deferred_paths: Vec<String>,
|
||||
deferred_process_fields: Vec<String>,
|
||||
runtime_derived_paths: Vec<String>,
|
||||
truncated: bool,
|
||||
}
|
||||
|
||||
impl Default for Comparison {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
scope: "selected_sections",
|
||||
status: "unknown",
|
||||
pending_paths: Vec::new(),
|
||||
watcher_pending_paths: Vec::new(),
|
||||
generation_pending_paths: Vec::new(),
|
||||
process_deferred_paths: Vec::new(),
|
||||
deferred_process_fields: Vec::new(),
|
||||
runtime_derived_paths: Vec::new(),
|
||||
truncated: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub(super) struct ConfigState {
|
||||
scope: &'static str,
|
||||
sections: BTreeSet<String>,
|
||||
runtime: RuntimeBaseline,
|
||||
runtime_sample_current: bool,
|
||||
pub(super) desired_revision: Option<String>,
|
||||
desired_status: &'static str,
|
||||
desired_error: Option<FieldIssue>,
|
||||
desired: Option<projection::Projection>,
|
||||
effective: Option<projection::Projection>,
|
||||
projection_error: Option<FieldIssue>,
|
||||
comparison: Comparison,
|
||||
watcher: Option<WatchOutcome>,
|
||||
watcher_matches_desired: Option<bool>,
|
||||
reload: Option<ReloadObservation>,
|
||||
reload_observation: &'static str,
|
||||
reload_matches_desired: Option<bool>,
|
||||
subsystem_convergence: &'static str,
|
||||
}
|
||||
|
||||
fn issue(code: &'static str, message: &'static str) -> FieldIssue {
|
||||
FieldIssue {
|
||||
path: "$".into(),
|
||||
code,
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn sections(query: Option<&str>) -> Result<BTreeSet<String>, ApiFailure> {
|
||||
let Some(query) = query.filter(|query| !query.is_empty()) else {
|
||||
return Ok(projection::SECTIONS
|
||||
.iter()
|
||||
.map(|section| (*section).to_owned())
|
||||
.collect());
|
||||
};
|
||||
if query.len() > 256 {
|
||||
return Err(ApiFailure::bad_request(
|
||||
"Config state query exceeds 256 bytes",
|
||||
));
|
||||
}
|
||||
let mut parsed = url::form_urlencoded::parse(query.as_bytes());
|
||||
let Some((key, value)) = parsed.next() else {
|
||||
return Err(ApiFailure::bad_request("Expected sections query"));
|
||||
};
|
||||
if key != "sections" || parsed.next().is_some() {
|
||||
return Err(ApiFailure::bad_request(
|
||||
"Only one sections query parameter is supported",
|
||||
));
|
||||
}
|
||||
let mut sections = BTreeSet::new();
|
||||
for section in value.split(',') {
|
||||
if !projection::SECTIONS.contains(§ion) || !sections.insert(section.to_owned()) {
|
||||
return Err(ApiFailure::bad_request(
|
||||
"Unknown, empty or repeated configuration section",
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(sections)
|
||||
}
|
||||
|
||||
fn json(config: &ProxyConfig) -> Result<Json, ApiFailure> {
|
||||
serde_json::to_value(config)
|
||||
.map_err(|_| ApiFailure::internal("Cannot project configuration snapshot"))
|
||||
}
|
||||
|
||||
struct Desired {
|
||||
revision: Option<String>,
|
||||
status: &'static str,
|
||||
error: Option<FieldIssue>,
|
||||
projection: Option<projection::Projection>,
|
||||
effective: Option<projection::Projection>,
|
||||
comparison: Comparison,
|
||||
}
|
||||
|
||||
fn unavailable(revision: Option<String>, status: &'static str, code: &'static str) -> Desired {
|
||||
Desired {
|
||||
revision,
|
||||
status,
|
||||
error: Some(issue(
|
||||
code,
|
||||
"Desired configuration is unavailable; effective publication remains readable",
|
||||
)),
|
||||
projection: None,
|
||||
effective: None,
|
||||
comparison: Comparison::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_desired(
|
||||
path: &std::path::Path,
|
||||
active: &ProxyConfig,
|
||||
sections: &BTreeSet<String>,
|
||||
) -> Result<Desired, ApiFailure> {
|
||||
let graph = match ProxyConfig::read_source_graph(path) {
|
||||
Ok(graph) => graph,
|
||||
Err(_) => return Ok(unavailable(None, "unreadable", "desired_source_unreadable")),
|
||||
};
|
||||
let revision = super::config_store::compute_source_revision(&graph);
|
||||
let mut desired = match ProxyConfig::parse_captured_source(graph) {
|
||||
Ok(parsed) => parsed.config,
|
||||
Err(_) => {
|
||||
return Ok(unavailable(
|
||||
Some(revision),
|
||||
"invalid",
|
||||
"desired_config_invalid",
|
||||
));
|
||||
}
|
||||
};
|
||||
let mut derived = Vec::new();
|
||||
if matches!(&desired.provenance, ConfigProvenance::Source(source) if source.generated_fake_cert_len)
|
||||
{
|
||||
desired.censorship.fake_cert_len = active.censorship.fake_cert_len;
|
||||
if projection::selected("censorship.fake_cert_len", sections) {
|
||||
derived.push("censorship.fake_cert_len".into());
|
||||
}
|
||||
}
|
||||
let mut active_json = json(active)?;
|
||||
let mut desired_json = json(&desired)?;
|
||||
let effective =
|
||||
projection::project(active, &active_json, Some(&desired_json), sections, false)?;
|
||||
let desired_projection =
|
||||
projection::project(&desired, &desired_json, Some(&active_json), sections, true)?;
|
||||
let hot = crate::config::hot_reload::overlay_hot_fields(active, &desired);
|
||||
let projected = project_reload_config(active, &desired);
|
||||
let mut hot_json = json(&hot)?;
|
||||
let mut projected_json = json(&projected.effective)?;
|
||||
for value in [
|
||||
&mut active_json,
|
||||
&mut desired_json,
|
||||
&mut hot_json,
|
||||
&mut projected_json,
|
||||
] {
|
||||
projection::retain_sections(value, sections);
|
||||
}
|
||||
let mut comparison = Comparison {
|
||||
pending_paths: projection::changed_paths(&active_json, &desired_json),
|
||||
watcher_pending_paths: projection::changed_paths(&active_json, &hot_json),
|
||||
generation_pending_paths: projection::changed_paths(&hot_json, &projected_json),
|
||||
process_deferred_paths: projection::changed_paths(&projected_json, &desired_json),
|
||||
deferred_process_fields: projected
|
||||
.deferred_process_fields
|
||||
.into_iter()
|
||||
.filter(|path| projection::selected(path, sections))
|
||||
.collect(),
|
||||
runtime_derived_paths: derived,
|
||||
..Comparison::default()
|
||||
};
|
||||
comparison.status = if comparison.pending_paths.is_empty() {
|
||||
"published_match"
|
||||
} else if comparison.watcher_pending_paths.is_empty()
|
||||
&& comparison.generation_pending_paths.is_empty()
|
||||
{
|
||||
"process_deferred"
|
||||
} else {
|
||||
"pending_publication"
|
||||
};
|
||||
for paths in [
|
||||
&mut comparison.pending_paths,
|
||||
&mut comparison.watcher_pending_paths,
|
||||
&mut comparison.generation_pending_paths,
|
||||
&mut comparison.process_deferred_paths,
|
||||
] {
|
||||
comparison.truncated |= paths.len() > MAX_STATE_PATHS;
|
||||
paths.truncate(MAX_STATE_PATHS);
|
||||
}
|
||||
Ok(Desired {
|
||||
revision: Some(revision),
|
||||
status: "valid",
|
||||
error: None,
|
||||
projection: Some(desired_projection),
|
||||
effective: Some(effective),
|
||||
comparison,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) async fn state(
|
||||
shared: &ApiShared,
|
||||
query: Option<&str>,
|
||||
) -> Result<ConfigState, ApiFailure> {
|
||||
let sections = sections(query)?;
|
||||
let fence = RuntimeFence::capture(shared, None)?;
|
||||
let mut data = ConfigState {
|
||||
scope: "published_configuration_not_subsystem_acknowledgment",
|
||||
sections: sections.clone(),
|
||||
runtime: fence.baseline(),
|
||||
runtime_sample_current: true,
|
||||
desired_revision: None,
|
||||
desired_status: "busy",
|
||||
desired_error: None,
|
||||
desired: None,
|
||||
effective: None,
|
||||
projection_error: None,
|
||||
comparison: Comparison::default(),
|
||||
watcher: None,
|
||||
watcher_matches_desired: None,
|
||||
reload: None,
|
||||
reload_observation: "unknown",
|
||||
reload_matches_desired: None,
|
||||
subsystem_convergence: "unknown",
|
||||
};
|
||||
if let Ok(permit) = shared.config_state_slots.clone().try_acquire_owned() {
|
||||
let permit = Arc::new(permit);
|
||||
let guard = permit.clone();
|
||||
let active = fence.config.clone();
|
||||
let scope = sections.clone();
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
|
||||
let effective = tokio::task::spawn_blocking(move || {
|
||||
let _guard = guard;
|
||||
projection::project(&active, &json(&active)?, None, &scope, false)
|
||||
});
|
||||
match tokio::time::timeout_at(deadline, effective).await {
|
||||
Ok(Ok(Ok(effective))) => data.effective = Some(effective),
|
||||
_ => {
|
||||
data.projection_error = Some(issue(
|
||||
"effective_projection_unavailable",
|
||||
"Runtime identity is available but its projection could not complete",
|
||||
))
|
||||
}
|
||||
}
|
||||
if data.effective.is_some() {
|
||||
let active = fence.config.clone();
|
||||
let path = shared.config_path.clone();
|
||||
let desired = tokio::task::spawn_blocking(move || {
|
||||
let _guard = permit;
|
||||
read_desired(&path, &active, §ions)
|
||||
});
|
||||
let desired = match tokio::time::timeout_at(deadline, desired).await {
|
||||
Ok(Ok(Ok(desired))) => desired,
|
||||
Ok(_) => unavailable(None, "unavailable", "desired_projection_failed"),
|
||||
Err(_) => unavailable(None, "timeout", "desired_read_timeout"),
|
||||
};
|
||||
data.desired_revision = desired.revision;
|
||||
data.desired_status = desired.status;
|
||||
data.desired_error = desired.error;
|
||||
data.desired = desired.projection;
|
||||
if desired.effective.is_some() {
|
||||
data.effective = desired.effective;
|
||||
}
|
||||
data.comparison = desired.comparison;
|
||||
} else {
|
||||
data.desired_status = "unavailable";
|
||||
data.desired_error = Some(issue(
|
||||
"state_projection_unavailable",
|
||||
"Configuration projection could not complete within the read budget",
|
||||
));
|
||||
}
|
||||
} else {
|
||||
data.desired_error = Some(issue(
|
||||
"config_state_busy",
|
||||
"Both configuration inspection slots are occupied",
|
||||
));
|
||||
}
|
||||
data.runtime_sample_current = fence.ensure_current().is_ok();
|
||||
data.watcher = fence
|
||||
.config
|
||||
.watcher_observation
|
||||
.as_ref()
|
||||
.and_then(|observer| observer.snapshot())
|
||||
.map(|outcome| (*outcome).clone());
|
||||
data.watcher_matches_desired = data.desired_revision.as_ref().and_then(|revision| {
|
||||
data.watcher
|
||||
.as_ref()?
|
||||
.source_revision
|
||||
.as_ref()
|
||||
.map(|source| source == revision)
|
||||
});
|
||||
match shared.reload_control.observation() {
|
||||
Some(reload) => {
|
||||
data.reload = reload;
|
||||
data.reload_observation = "sampled";
|
||||
}
|
||||
None => data.reload_observation = "busy",
|
||||
}
|
||||
data.reload_matches_desired = data.desired_revision.as_ref().and_then(|revision| {
|
||||
data.reload
|
||||
.as_ref()
|
||||
.map(|reload| &reload.source_revision == revision)
|
||||
});
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
pub(super) async fn response(
|
||||
shared: &ApiShared,
|
||||
query: Option<&str>,
|
||||
) -> Result<Response<Full<Bytes>>, ApiFailure> {
|
||||
let mut data = state(shared, query).await?;
|
||||
loop {
|
||||
let body = serde_json::to_vec(
|
||||
&serde_json::json!({"ok": true, "revision": data.desired_revision, "data": data}),
|
||||
)
|
||||
.map_err(|_| ApiFailure::internal("Cannot encode configuration state"))?;
|
||||
if body.len() <= MAX_RESPONSE_BYTES {
|
||||
return Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header("content-type", "application/json; charset=utf-8")
|
||||
.body(Full::new(Bytes::from(body)))
|
||||
.map_err(|_| ApiFailure::internal("Cannot build configuration state response"));
|
||||
}
|
||||
// Each list was already capped. Shrinking the two projections guarantees
|
||||
// that oversized deployment shapes cannot exceed the response envelope.
|
||||
let mut shrunk = false;
|
||||
for projection in [&mut data.desired, &mut data.effective]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
shrunk |= !projection.fields.is_empty();
|
||||
projection.fields.truncate(projection.fields.len() / 2);
|
||||
projection.truncated = true;
|
||||
}
|
||||
if !shrunk {
|
||||
return Err(ApiFailure::internal(
|
||||
"Configuration state metadata exceeded the response bound",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,198 @@
|
||||
use super::*;
|
||||
use http_body_util::BodyExt;
|
||||
|
||||
#[tokio::test]
|
||||
async fn busy_state_preserves_runtime_identity_and_does_not_queue_more_work() {
|
||||
let (fixture, _sender) = fixture("", true).await;
|
||||
let permits = fixture
|
||||
.shared
|
||||
.config_state_slots
|
||||
.clone()
|
||||
.acquire_many_owned(2)
|
||||
.await
|
||||
.unwrap();
|
||||
let data = inspect(&fixture, None).await;
|
||||
assert_eq!(data["desired_status"], "busy");
|
||||
assert_eq!(data["desired_error"]["code"], "config_state_busy");
|
||||
assert_eq!(data["runtime"]["active_generation"], 1);
|
||||
assert!(data["effective"].is_null());
|
||||
assert_eq!(data["comparison"]["status"], "unknown");
|
||||
drop(permits);
|
||||
assert_eq!(inspect(&fixture, None).await["desired_status"], "valid");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn large_deployment_bounds_fields_paths_bytes_and_dynamic_identities() {
|
||||
let (fixture, _sender) = fixture("", true).await;
|
||||
let mut text =
|
||||
String::from("[access.users]\nprivate_identity='000102030405060708090a0b0c0d0e0f'\n");
|
||||
for _ in 0..1200 {
|
||||
text.push_str("[[upstreams]]\ntype='socks5'\naddress='127.0.0.1:1080'\nusername='private_socks_user'\npassword='private_socks_password'\n");
|
||||
}
|
||||
source(&fixture, &text, true);
|
||||
let response = response(&fixture.shared, None).await.unwrap();
|
||||
let bytes = response.into_body().collect().await.unwrap().to_bytes();
|
||||
assert!(bytes.len() <= MAX_RESPONSE_BYTES);
|
||||
let data: Json = serde_json::from_slice(&bytes).unwrap();
|
||||
assert_eq!(data["data"]["desired_status"], "valid");
|
||||
assert_eq!(data["data"]["desired"]["truncated"], true);
|
||||
assert!(data["data"]["desired"]["fields"].as_array().unwrap().len() <= 1024);
|
||||
assert_eq!(data["data"]["comparison"]["truncated"], true);
|
||||
assert!(
|
||||
data["data"]["comparison"]["pending_paths"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.len()
|
||||
<= MAX_STATE_PATHS
|
||||
);
|
||||
let encoded = String::from_utf8(bytes.to_vec()).unwrap();
|
||||
for private in [
|
||||
"private_identity",
|
||||
"private_socks_user",
|
||||
"private_socks_password",
|
||||
"000102030405060708090a0b0c0d0e0f",
|
||||
"Bearer discovery-test",
|
||||
] {
|
||||
assert!(!encoded.contains(private));
|
||||
}
|
||||
}
|
||||
|
||||
fn abandoned_state_retains_budget(timeout: bool) {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.max_blocking_threads(1)
|
||||
.build()
|
||||
.unwrap();
|
||||
runtime.block_on(async {
|
||||
let (fixture, _sender) = fixture("", true).await;
|
||||
let original = std::fs::read(&fixture.shared.config_path).unwrap();
|
||||
let active = fixture.shared.active_runtime.load_full();
|
||||
let (release, wait) = std::sync::mpsc::channel();
|
||||
let (started, ready) = tokio::sync::oneshot::channel();
|
||||
let blocker = tokio::task::spawn_blocking(move || {
|
||||
started.send(()).unwrap();
|
||||
wait.recv().unwrap();
|
||||
});
|
||||
ready.await.unwrap();
|
||||
tokio::time::pause();
|
||||
let shared = fixture.shared.clone();
|
||||
let task = tokio::spawn(async move { state(&shared, None).await });
|
||||
while fixture.shared.config_state_slots.available_permits() == 2 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
if timeout {
|
||||
fixture
|
||||
.shared
|
||||
.active_runtime
|
||||
.store(test_runtime_generation(2, active.config().as_ref().clone()));
|
||||
tokio::time::advance(Duration::from_secs(6)).await;
|
||||
let data = serde_json::to_value(task.await.unwrap().unwrap()).unwrap();
|
||||
assert_eq!(data["runtime"]["active_generation"], 1);
|
||||
assert_eq!(data["runtime_sample_current"], false);
|
||||
assert_eq!(data["desired_status"], "unavailable");
|
||||
assert_eq!(
|
||||
data["projection_error"]["code"],
|
||||
"effective_projection_unavailable"
|
||||
);
|
||||
} else {
|
||||
task.abort();
|
||||
assert!(task.await.unwrap_err().is_cancelled());
|
||||
}
|
||||
assert_eq!(fixture.shared.config_state_slots.available_permits(), 1);
|
||||
tokio::time::resume();
|
||||
release.send(()).unwrap();
|
||||
blocker.await.unwrap();
|
||||
let _permits = tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
fixture
|
||||
.shared
|
||||
.config_state_slots
|
||||
.clone()
|
||||
.acquire_many_owned(2),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
std::fs::read(&fixture.shared.config_path).unwrap(),
|
||||
original
|
||||
);
|
||||
assert!(fixture.shared.reload_control.status(1).await.is_none());
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancellation_retains_read_slot_until_detached_worker_finishes() {
|
||||
abandoned_state_retains_budget(false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timeout_retains_read_slot_and_reports_a_stale_runtime_sample() {
|
||||
abandoned_state_retains_budget(true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn desired_worker_timeout_preserves_effective_and_retains_its_read_slot() {
|
||||
use std::future::Future;
|
||||
use std::task::Poll;
|
||||
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.max_blocking_threads(1)
|
||||
.build()
|
||||
.unwrap();
|
||||
runtime.block_on(async {
|
||||
let (fixture, _sender) = fixture("", true).await;
|
||||
let (release_initial, wait_initial) = std::sync::mpsc::channel();
|
||||
let (initial_started, initial_ready) = tokio::sync::oneshot::channel();
|
||||
let initial_blocker = tokio::task::spawn_blocking(move || {
|
||||
initial_started.send(()).unwrap();
|
||||
wait_initial.recv().unwrap();
|
||||
});
|
||||
initial_ready.await.unwrap();
|
||||
let mut read = Box::pin(state(&fixture.shared, None));
|
||||
// Queue effective projection, then occupy the only blocking thread once
|
||||
// it completes. The desired-source worker will have to wait behind it.
|
||||
std::future::poll_fn(|context| {
|
||||
assert!(read.as_mut().poll(context).is_pending());
|
||||
Poll::Ready(())
|
||||
})
|
||||
.await;
|
||||
let (release, wait) = std::sync::mpsc::channel();
|
||||
let (started, ready) = tokio::sync::oneshot::channel();
|
||||
let blocker = tokio::task::spawn_blocking(move || {
|
||||
started.send(()).unwrap();
|
||||
wait.recv().unwrap();
|
||||
});
|
||||
release_initial.send(()).unwrap();
|
||||
initial_blocker.await.unwrap();
|
||||
ready.await.unwrap();
|
||||
tokio::time::pause();
|
||||
std::future::poll_fn(|context| {
|
||||
assert!(read.as_mut().poll(context).is_pending());
|
||||
Poll::Ready(())
|
||||
})
|
||||
.await;
|
||||
tokio::time::advance(Duration::from_secs(6)).await;
|
||||
let data = serde_json::to_value(read.await.unwrap()).unwrap();
|
||||
assert_eq!(data["desired_status"], "timeout");
|
||||
assert_eq!(data["desired_error"]["code"], "desired_read_timeout");
|
||||
assert!(!data["effective"].is_null());
|
||||
assert_eq!(data["comparison"]["status"], "unknown");
|
||||
assert_eq!(fixture.shared.config_state_slots.available_permits(), 1);
|
||||
tokio::time::resume();
|
||||
release.send(()).unwrap();
|
||||
blocker.await.unwrap();
|
||||
let _permits = tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
fixture
|
||||
.shared
|
||||
.config_state_slots
|
||||
.clone()
|
||||
.acquire_many_owned(2),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
use super::*;
|
||||
|
||||
const WEB: &str = r#"
|
||||
[access.users]
|
||||
alice = "000102030405060708090a0b0c0d0e0f"
|
||||
[[server.listeners]]
|
||||
ip = "127.0.0.1"
|
||||
port = 18080
|
||||
transport = "web"
|
||||
web_trusted_proxy_cidrs = ["127.0.0.1/32"]
|
||||
[web]
|
||||
enabled = true
|
||||
[[web.vhosts]]
|
||||
host = "proxy.example.com"
|
||||
public_addr = "203.0.113.10:443"
|
||||
[web.vhosts.decoy]
|
||||
mode = "http_upstream"
|
||||
upstream = "http://127.0.0.1:18081"
|
||||
[[web.vhosts.profiles]]
|
||||
user = "alice"
|
||||
secret_mode = "dd"
|
||||
"#;
|
||||
|
||||
#[tokio::test]
|
||||
async fn inspection_does_not_acquire_decoy_dns_or_static_files() {
|
||||
let (fixture, _sender) = fixture(WEB, true).await;
|
||||
source(
|
||||
&fixture,
|
||||
&WEB.replace(
|
||||
"http://127.0.0.1:18081",
|
||||
"http://unresolvable.invalid:18081",
|
||||
)
|
||||
.replace(
|
||||
"[[web.vhosts.profiles]]",
|
||||
"resolve = 'startup'\n[[web.vhosts.profiles]]",
|
||||
),
|
||||
true,
|
||||
);
|
||||
let data = inspect(&fixture, Some("sections=web")).await;
|
||||
assert_eq!(data["desired_status"], "valid");
|
||||
assert_eq!(
|
||||
field(&data, "desired", "web.vhosts[0].decoy.upstream")["redacted"],
|
||||
true
|
||||
);
|
||||
assert_eq!(data["comparison"]["status"], "pending_publication");
|
||||
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
std::fs::write(
|
||||
directory.path().join("index.html"),
|
||||
"private synthetic asset",
|
||||
)
|
||||
.unwrap();
|
||||
let static_source = WEB.replace(
|
||||
"mode = \"http_upstream\"\nupstream = \"http://127.0.0.1:18081\"",
|
||||
&format!(
|
||||
"mode = 'static_directory'\ndirectory = '{}'\nindex = 'index.html'",
|
||||
directory.path().display()
|
||||
),
|
||||
);
|
||||
let (fixture, _sender) = self::fixture(&static_source, true).await;
|
||||
directory.close().unwrap();
|
||||
assert!(
|
||||
ProxyConfig::load_prepared(fixture.shared.config_path.clone())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
let data = inspect(&fixture, None).await;
|
||||
assert_eq!(data["desired_status"], "valid");
|
||||
assert_eq!(data["comparison"]["status"], "published_match");
|
||||
assert_eq!(data["subsystem_convergence"], "unknown");
|
||||
assert!(!data.to_string().contains("private synthetic asset"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn conditional_web_capacity_and_includes_preserve_source_evidence() {
|
||||
let (fixture, _sender) = fixture("[web.limits]\ndebug_bytes_global=4096", true).await;
|
||||
source(
|
||||
&fixture,
|
||||
"[web.limits]\ndebug_bytes_global=8192\n[web.debug]\nbody_prefix_bytes=6144",
|
||||
true,
|
||||
);
|
||||
let data = inspect(&fixture, Some("sections=web")).await;
|
||||
assert_eq!(data["comparison"]["status"], "process_deferred");
|
||||
assert!(
|
||||
data["comparison"]["process_deferred_paths"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.contains(&json!("web.debug.body_prefix_bytes"))
|
||||
);
|
||||
assert!(
|
||||
data["comparison"]["deferred_process_fields"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.contains(&json!("web.debug"))
|
||||
);
|
||||
source(&fixture, "include = \"extra.toml\"", true);
|
||||
std::fs::write(
|
||||
fixture
|
||||
.shared
|
||||
.config_path
|
||||
.parent()
|
||||
.unwrap()
|
||||
.join("extra.toml"),
|
||||
"[general]\nlog_level='debug'",
|
||||
)
|
||||
.unwrap();
|
||||
let data = inspect(&fixture, Some("sections=general")).await;
|
||||
assert_eq!(data["desired"]["source_count"], 2);
|
||||
assert_eq!(
|
||||
field(&data, "desired", "general.log_level")["origin"],
|
||||
"source"
|
||||
);
|
||||
assert!(!data.to_string().contains("extra.toml"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projection_fails_closed_for_arbitrary_strings_unknown_fields_and_private_maps() {
|
||||
let config = ProxyConfig::default();
|
||||
let raw = json!({"general":{"proxy_secret_url":"https://private-user:private-pass@example.invalid/key", "unknown_field":"private-value"},
|
||||
"access":{"user_rate_limits":{"private-name":{"up_bps":12345}}},
|
||||
"dc_overrides":{"private-dc":{"address":"private-value"}}});
|
||||
let scope = sections(None).unwrap();
|
||||
let projection = projection::project(&config, &raw, Some(&json!({})), &scope, false).unwrap();
|
||||
let result = serde_json::to_value(projection).unwrap();
|
||||
for value in [
|
||||
"private-user",
|
||||
"private-pass",
|
||||
"example.invalid",
|
||||
"private-value",
|
||||
"private-name",
|
||||
"private-dc",
|
||||
"12345",
|
||||
] {
|
||||
assert!(!result.to_string().contains(value));
|
||||
}
|
||||
assert!(
|
||||
result["fields"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.all(|field| field["redacted"] == true && field.get("value").is_none())
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
use super::*;
|
||||
use crate::api::discovery::http_tests::Fixture;
|
||||
use crate::config::observation::WatchObservation;
|
||||
use crate::maestro::generation::test_runtime_generation;
|
||||
use crate::maestro::reload::{ReloadControl, ReloadPhase, ReloadRequest};
|
||||
use serde_json::json;
|
||||
use tokio::sync::watch;
|
||||
|
||||
#[path = "bounds_tests.rs"]
|
||||
mod bounds;
|
||||
|
||||
#[path = "preparation_tests.rs"]
|
||||
mod preparation;
|
||||
|
||||
fn source(fixture: &Fixture, text: &str, read_only: bool) {
|
||||
std::fs::write(&fixture.shared.config_path, format!("{text}\n[server.api]\nenabled = true\nread_only = {read_only}\nauth_header = \"Bearer discovery-test\"\n")).unwrap();
|
||||
}
|
||||
|
||||
async fn fixture(text: &str, read_only: bool) -> (Fixture, watch::Sender<Arc<ProxyConfig>>) {
|
||||
let fixture = Fixture::new(false);
|
||||
source(&fixture, text, read_only);
|
||||
let mut config = ProxyConfig::load_prepared(fixture.shared.config_path.clone())
|
||||
.await
|
||||
.unwrap()
|
||||
.config;
|
||||
config.watcher_observation = Some(Arc::new(WatchObservation::default()));
|
||||
let mut runtime = test_runtime_generation(1, config);
|
||||
let (sender, receiver) = watch::channel(runtime.config());
|
||||
Arc::get_mut(&mut runtime).unwrap().config_rx = receiver;
|
||||
fixture.shared.active_runtime.store(runtime);
|
||||
(fixture, sender)
|
||||
}
|
||||
|
||||
async fn inspect(fixture: &Fixture, query: Option<&str>) -> Json {
|
||||
serde_json::to_value(state(&fixture.shared, query).await.unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn field<'a>(data: &'a Json, projection: &str, path: &str) -> &'a Json {
|
||||
data[projection]["fields"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|field| field["path"] == path)
|
||||
.unwrap_or_else(|| panic!("missing {projection} field {path}"))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn state_http_auth_scope_queries_read_only_and_no_mutation() {
|
||||
let (fixture, _sender) = fixture("", true).await;
|
||||
let bytes = std::fs::read(&fixture.shared.config_path).unwrap();
|
||||
let active = fixture.shared.active_runtime.load_full();
|
||||
for (method, path, authorized, expected) in [
|
||||
("GET", "/v1/config/state", false, 401),
|
||||
("POST", "/v1/config/state", true, 405),
|
||||
(
|
||||
"GET",
|
||||
"/v1/config/state?sections=general,general",
|
||||
true,
|
||||
400,
|
||||
),
|
||||
("GET", "/v1/config/state?sections=", true, 400),
|
||||
("GET", "/v1/config/state?sections=unknown", true, 400),
|
||||
(
|
||||
"GET",
|
||||
"/v1/config/state?sections=general§ions=web",
|
||||
true,
|
||||
400,
|
||||
),
|
||||
("GET", "/v1/config/state?debug=true", true, 400),
|
||||
] {
|
||||
let (status, allow, _) = fixture.request(method, path, authorized).await;
|
||||
assert_eq!(status, expected, "{method} {path}");
|
||||
if status == 405 {
|
||||
assert_eq!(allow, "GET");
|
||||
}
|
||||
}
|
||||
assert!(sections(Some(&format!("sections={}", "a".repeat(256)))).is_err());
|
||||
let (status, _, response) = fixture
|
||||
.request("GET", "/v1/config/state?sections=general,access", true)
|
||||
.await;
|
||||
assert_eq!(status, 200, "{response}");
|
||||
let data = &response["data"];
|
||||
assert_eq!(response["revision"], data["desired_revision"]);
|
||||
assert_eq!(data["sections"], json!(["access", "general"]));
|
||||
assert_eq!(data["comparison"]["status"], "published_match");
|
||||
assert_eq!(data["runtime"]["active_generation"], 1);
|
||||
assert_eq!(data["runtime_sample_current"], true);
|
||||
assert_eq!(data["subsystem_convergence"], "unknown");
|
||||
assert!(
|
||||
data["effective"]["fields"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.all(|field| {
|
||||
let path = field["path"].as_str().unwrap();
|
||||
path.starts_with("general.") || path.starts_with("access.")
|
||||
})
|
||||
);
|
||||
assert_eq!(std::fs::read(&fixture.shared.config_path).unwrap(), bytes);
|
||||
assert!(Arc::ptr_eq(
|
||||
&active,
|
||||
&fixture.shared.active_runtime.load_full()
|
||||
));
|
||||
assert!(fixture.shared.reload_control.status(1).await.is_none());
|
||||
assert!(fixture.shared.runtime_events.snapshot(64).events.is_empty());
|
||||
let denied = Fixture::new(true);
|
||||
assert_eq!(denied.request("GET", "/v1/config/state", true).await.0, 403);
|
||||
let caps = fixture.request("GET", "/v1/capabilities", true).await.2;
|
||||
let operation = caps["data"]["operations"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|op| op["id"] == "config_state")
|
||||
.unwrap();
|
||||
assert_eq!(operation["available"], true);
|
||||
assert_eq!(operation["mutable"], false);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_or_unreadable_desired_preserves_effective_and_hides_errors() {
|
||||
let (fixture, _sender) = fixture("[general]\nlog_level='debug'", true).await;
|
||||
let epoch = fixture
|
||||
.shared
|
||||
.active_runtime
|
||||
.load()
|
||||
.config()
|
||||
.runtime_config_epoch;
|
||||
for invalid in [
|
||||
"[general]\nme_writer_pick_mode='synthetic-private-value'",
|
||||
"[broken synthetic-private-value",
|
||||
] {
|
||||
std::fs::write(&fixture.shared.config_path, invalid).unwrap();
|
||||
let (status, _, response) = fixture.request("GET", "/v1/config/state", true).await;
|
||||
assert_eq!(status, 200);
|
||||
let data = &response["data"];
|
||||
assert_eq!(data["desired_status"], "invalid");
|
||||
assert!(response["revision"].is_string());
|
||||
assert_eq!(data["desired_error"]["code"], "desired_config_invalid");
|
||||
assert_eq!(data["runtime"]["config_epoch"], epoch);
|
||||
assert_eq!(
|
||||
field(data, "effective", "general.log_level")["value"],
|
||||
"debug"
|
||||
);
|
||||
assert!(data["desired"].is_null());
|
||||
assert_eq!(data["comparison"]["status"], "unknown");
|
||||
assert!(!response.to_string().contains("synthetic-private-value"));
|
||||
}
|
||||
std::fs::remove_file(&fixture.shared.config_path).unwrap();
|
||||
let response = fixture.request("GET", "/v1/config/state", true).await.2;
|
||||
assert!(response["revision"].is_null());
|
||||
assert_eq!(response["data"]["desired_status"], "unreadable");
|
||||
assert!(!response["data"]["effective"].is_null());
|
||||
assert!(
|
||||
!response
|
||||
.to_string()
|
||||
.contains(fixture.shared.config_path.to_str().unwrap())
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn secret_rotation_stays_pending_until_publication_and_never_claims_convergence() {
|
||||
const OLD: &str = "000102030405060708090a0b0c0d0e0f";
|
||||
const NEW: &str = "f0e0d0c0b0a090807060504030201000";
|
||||
let (fixture, sender) =
|
||||
fixture(&format!("[access.users]\nprivate_account='{OLD}'"), false).await;
|
||||
let before = inspect(&fixture, None).await;
|
||||
let (status, _, response) = fixture
|
||||
.request_body(
|
||||
"POST",
|
||||
"/v1/users/private_account/rotate-secret",
|
||||
true,
|
||||
Some(&json!({"secret": NEW})),
|
||||
&[],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 200, "{response}");
|
||||
let pending = inspect(&fixture, None).await;
|
||||
assert_ne!(pending["desired_revision"], before["desired_revision"]);
|
||||
assert_eq!(pending["runtime"], before["runtime"]);
|
||||
assert_eq!(pending["comparison"]["status"], "pending_publication");
|
||||
assert!(
|
||||
pending["comparison"]["watcher_pending_paths"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.contains(&json!("access.users.{entry}"))
|
||||
);
|
||||
let users = field(&pending, "effective", "access.users");
|
||||
assert_eq!(users["differs"], true);
|
||||
assert_eq!(users["present"], true);
|
||||
assert_eq!(users["entries"], 1);
|
||||
assert_eq!(users["redacted"], true);
|
||||
assert!(users.get("value").is_none());
|
||||
for private in [OLD, NEW, "private_account", "Bearer discovery-test"] {
|
||||
assert!(!pending.to_string().contains(private));
|
||||
}
|
||||
let mut published = ProxyConfig::load_prepared(fixture.shared.config_path.clone())
|
||||
.await
|
||||
.unwrap()
|
||||
.config
|
||||
.with_publication_epoch();
|
||||
published.watcher_observation = sender.borrow().watcher_observation.clone();
|
||||
published.watcher_observation.as_ref().unwrap().record(
|
||||
"published",
|
||||
published.provenance.revision().map(str::to_owned),
|
||||
Some(published.runtime_config_epoch),
|
||||
None,
|
||||
);
|
||||
sender.send(Arc::new(published)).unwrap();
|
||||
let after = inspect(&fixture, None).await;
|
||||
assert_eq!(after["comparison"]["status"], "published_match");
|
||||
assert_ne!(
|
||||
after["runtime"]["config_epoch"],
|
||||
before["runtime"]["config_epoch"]
|
||||
);
|
||||
assert_eq!(after["watcher_matches_desired"], true);
|
||||
assert_eq!(after["subsystem_convergence"], "unknown");
|
||||
assert_eq!(field(&after, "effective", "access.users")["differs"], false);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn hot_generation_and_process_changes_have_distinct_paths() {
|
||||
let (fixture, _sender) = fixture("", true).await;
|
||||
source(
|
||||
&fixture,
|
||||
"[general]\nlog_level='debug'\ndisable_colors=true\n[network]\nipv6=true",
|
||||
true,
|
||||
);
|
||||
let data = inspect(&fixture, None).await;
|
||||
let comparison = &data["comparison"];
|
||||
assert!(
|
||||
comparison["watcher_pending_paths"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.contains(&json!("general.log_level"))
|
||||
);
|
||||
assert!(
|
||||
comparison["generation_pending_paths"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.contains(&json!("network.ipv6"))
|
||||
);
|
||||
assert!(
|
||||
comparison["process_deferred_paths"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.contains(&json!("general.disable_colors"))
|
||||
);
|
||||
source(&fixture, "[general]\ndisable_colors=true", true);
|
||||
let data = inspect(&fixture, None).await;
|
||||
assert_eq!(data["comparison"]["status"], "process_deferred");
|
||||
assert_eq!(
|
||||
data["comparison"]["deferred_process_fields"],
|
||||
json!(["general.disable_colors"])
|
||||
);
|
||||
let scoped = inspect(&fixture, Some("sections=network")).await;
|
||||
assert_eq!(scoped["comparison"]["status"], "published_match");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn known_source_default_inheritance_and_runtime_derived_provenance() {
|
||||
let text = "[general]\nlog_level='debug'\n[[upstreams]]\ntype='direct'\n[censorship]\ntls_emulation=false";
|
||||
let (fixture, _sender) = fixture(text, true).await;
|
||||
let data = inspect(&fixture, None).await;
|
||||
assert_eq!(
|
||||
field(&data, "desired", "general.log_level")["origin"],
|
||||
"source"
|
||||
);
|
||||
assert_eq!(
|
||||
field(&data, "desired", "general.disable_colors")["origin"],
|
||||
"type_default"
|
||||
);
|
||||
assert_eq!(
|
||||
field(&data, "desired", "upstreams[0].prefer")["origin"],
|
||||
"inherited"
|
||||
);
|
||||
assert_eq!(
|
||||
field(&data, "desired", "upstreams[0].prefer")["inherited_from"],
|
||||
"network.prefer"
|
||||
);
|
||||
assert_eq!(
|
||||
field(&data, "desired", "censorship.fake_cert_len")["origin"],
|
||||
"runtime_derived"
|
||||
);
|
||||
assert!(
|
||||
field(&data, "desired", "censorship.fake_cert_len")
|
||||
.get("value")
|
||||
.is_none()
|
||||
);
|
||||
assert_eq!(data["comparison"]["status"], "published_match");
|
||||
assert_eq!(
|
||||
data["comparison"]["runtime_derived_paths"],
|
||||
json!(["censorship.fake_cert_len"])
|
||||
);
|
||||
assert_eq!(data["desired"]["source_revision"], data["desired_revision"]);
|
||||
assert_eq!(data["desired"]["source_count"], 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reload_metadata_distinguishes_acceptance_failure_and_rollback_without_raw_errors() {
|
||||
let (mut fixture, _sender) = fixture("", true).await;
|
||||
let (control, mut commands) = ReloadControl::channel(1);
|
||||
Arc::get_mut(&mut fixture.shared).unwrap().reload_control = control.clone();
|
||||
let revision = inspect(&fixture, None).await["desired_revision"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
for terminal in [ReloadPhase::Failed, ReloadPhase::RolledBack] {
|
||||
let accepted = control
|
||||
.submit(
|
||||
fixture.shared.active_runtime.load().config(),
|
||||
revision.clone(),
|
||||
ReloadRequest::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let _ = commands.recv().await.unwrap();
|
||||
let data = inspect(&fixture, None).await;
|
||||
assert_eq!(data["reload"]["phase"], "accepted");
|
||||
assert_eq!(data["reload_matches_desired"], true);
|
||||
assert!(data["reload"]["activated_generation"].is_null());
|
||||
control.record_source_generation(accepted.reload_id, 1);
|
||||
control
|
||||
.mark_phase(accepted.reload_id, ReloadPhase::Preparing)
|
||||
.await;
|
||||
control
|
||||
.add_warning(accepted.reload_id, "synthetic-private-warning")
|
||||
.await;
|
||||
match terminal {
|
||||
ReloadPhase::Failed => {
|
||||
control
|
||||
.fail(accepted.reload_id, "synthetic-private-error")
|
||||
.await
|
||||
}
|
||||
ReloadPhase::RolledBack => {
|
||||
control
|
||||
.rolled_back(accepted.reload_id, "synthetic-private-error")
|
||||
.await
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
let data = inspect(&fixture, None).await;
|
||||
assert_eq!(
|
||||
data["reload"]["phase"],
|
||||
serde_json::to_value(terminal).unwrap()
|
||||
);
|
||||
assert_eq!(data["reload"]["source_generation"], 1);
|
||||
assert_eq!(data["reload"]["error_present"], true);
|
||||
assert_eq!(data["reload"]["warning_count"], 1);
|
||||
assert!(data["reload"]["retiring_generation"].is_null());
|
||||
assert!(!data.to_string().contains("synthetic-private"));
|
||||
}
|
||||
}
|
||||
+42
-27
@@ -9,15 +9,24 @@ use crate::config::{ConfigSourceGraph, LoadedConfig, ParsedConfigSource, ProxyCo
|
||||
use super::model::ApiFailure;
|
||||
|
||||
// Source-preserving TOML rendering and atomic persistence helpers.
|
||||
mod dns_overrides;
|
||||
mod field_edits;
|
||||
mod persistence;
|
||||
// Compare-and-replace file persistence and metadata preservation.
|
||||
mod atomic;
|
||||
|
||||
pub(in crate::api) use atomic::{write_atomic, write_atomic_if_unchanged};
|
||||
pub(in crate::api) use atomic::write_atomic;
|
||||
#[cfg(test)]
|
||||
pub(in crate::api) use atomic::write_atomic_if_unchanged;
|
||||
pub(in crate::api) use atomic::{CommitCheck, write_atomic_with_runtime_check};
|
||||
pub(in crate::api) use dns_overrides::upsert_dns_overrides;
|
||||
pub(in crate::api) use field_edits::{FieldEdit, prepare_field_edits};
|
||||
#[cfg(test)]
|
||||
pub(in crate::api) use persistence::save_access_sections_to_disk;
|
||||
#[cfg(test)]
|
||||
use persistence::{find_toml_table_bounds, render_access_section, save_sections_to_disk};
|
||||
pub(in crate::api) use persistence::{
|
||||
render_server_listeners, render_top_level_section, save_access_sections_to_disk,
|
||||
render_server_listeners, render_top_level_section, save_access_sections_and_fields_if_revision,
|
||||
save_access_sections_to_disk_if_revision, upsert_toml_table,
|
||||
};
|
||||
|
||||
@@ -103,23 +112,11 @@ pub(super) fn compute_revision(content: &str) -> String {
|
||||
|
||||
/// Hashes source documents only; prepared DNS answers never change a revision.
|
||||
pub(super) fn compute_snapshot_revision(source_contents: &BTreeMap<PathBuf, String>) -> String {
|
||||
compute_source_revision(&ConfigSourceGraph {
|
||||
source_contents: source_contents.clone(),
|
||||
rendered: String::new(),
|
||||
})
|
||||
crate::config::observation::source_revision(source_contents)
|
||||
}
|
||||
|
||||
pub(super) fn compute_source_revision(graph: &ConfigSourceGraph) -> String {
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(b"telemt-config-manifest-v1\0");
|
||||
for (path, content) in &graph.source_contents {
|
||||
let path = path.as_os_str().as_encoded_bytes();
|
||||
hasher.update((path.len() as u64).to_le_bytes());
|
||||
hasher.update(path);
|
||||
hasher.update((content.len() as u64).to_le_bytes());
|
||||
hasher.update(content.as_bytes());
|
||||
}
|
||||
hex::encode(hasher.finalize())
|
||||
compute_snapshot_revision(&graph.source_contents)
|
||||
}
|
||||
|
||||
/// Reads a normalized source snapshot without resolving decoys or loading static assets.
|
||||
@@ -163,6 +160,7 @@ pub(super) fn resolve_single_source_owner(
|
||||
|
||||
for target in targets {
|
||||
let mut owners = BTreeSet::new();
|
||||
let mut parent_owners = BTreeSet::new();
|
||||
for (path, content) in &loaded.source_contents {
|
||||
let parsed: toml::Value = toml::from_str(content).map_err(|error| {
|
||||
ApiFailure::new(
|
||||
@@ -177,6 +175,14 @@ pub(super) fn resolve_single_source_owner(
|
||||
if toml_path_exists(&parsed, target) {
|
||||
owners.insert(path.clone());
|
||||
}
|
||||
if *target == "network.dns_overrides" && toml_path_exists(&parsed, "network") {
|
||||
parent_owners.insert(path.clone());
|
||||
}
|
||||
}
|
||||
// A new DNS key belongs to the existing network table, which may live
|
||||
// in an include. Existing leaf ownership takes precedence over siblings.
|
||||
if owners.is_empty() && *target == "network.dns_overrides" {
|
||||
owners = parent_owners;
|
||||
}
|
||||
match owners.len() {
|
||||
0 => {
|
||||
@@ -313,7 +319,6 @@ pub(super) async fn save_config_to_disk(
|
||||
/// identity invariant at the Telemt layer too):
|
||||
///
|
||||
/// - `access` : owned by the users API.
|
||||
/// - `network` : carries per-node identity (`ipv4`/`ipv6`).
|
||||
/// - `show_link` : legacy top-level scalar/array (not a `[table]`), superseded
|
||||
/// by the editable `general.links.show` sub-table. The
|
||||
/// section-upsert machinery here only handles `[table]` /
|
||||
@@ -321,12 +326,10 @@ pub(super) async fn save_config_to_disk(
|
||||
/// located or replaced safely, so it is edited via `general`.
|
||||
///
|
||||
/// `server` is partially editable: only the nested fields listed in
|
||||
/// [`EDITABLE_SERVER_FIELDS`] (currently `listeners`) may appear in GET/PATCH.
|
||||
/// Secrets and bind identity (`api`/`admin_api`, `port`, unix sockets, …) stay
|
||||
/// blocked. See also the field-level allowlist note below for `network.*`.
|
||||
///
|
||||
/// A future field-level allowlist can re-admit specific safe fields
|
||||
/// (e.g. `network.dns_overrides`) without opening the whole section.
|
||||
/// [`EDITABLE_SERVER_FIELDS`] may appear in GET/PATCH; `api` is further restricted
|
||||
/// to [`EDITABLE_SERVER_API_FIELDS`]. Secrets and bind identity stay blocked.
|
||||
/// `network` is also partial: only [`EDITABLE_NETWORK_FIELDS`] are
|
||||
/// exposed, retaining the boundary around per-node identity and routing policy.
|
||||
pub(super) const EDITABLE_SECTIONS: &[&str] = &[
|
||||
"general",
|
||||
"timeouts",
|
||||
@@ -340,14 +343,26 @@ pub(super) const EDITABLE_SECTIONS: &[&str] = &[
|
||||
///
|
||||
/// Arrays (e.g. `listeners`) replace wholesale on PATCH, matching the existing
|
||||
/// merge semantics for non-table values.
|
||||
pub(super) const EDITABLE_SERVER_FIELDS: &[&str] = &["listeners"];
|
||||
pub(super) const EDITABLE_SERVER_FIELDS: &[&str] = &["listeners", "api"];
|
||||
|
||||
/// Diagnostics settings applied by explicit generation reload, not the watcher.
|
||||
pub(super) const EDITABLE_SERVER_API_FIELDS: &[&str] = &[
|
||||
"minimal_runtime_enabled",
|
||||
"minimal_runtime_cache_ttl_ms",
|
||||
"runtime_edge_enabled",
|
||||
"runtime_edge_cache_ttl_ms",
|
||||
"runtime_edge_top_n",
|
||||
];
|
||||
|
||||
/// Only the generation resolver's overrides may be read/patched under `network`.
|
||||
pub(super) const EDITABLE_NETWORK_FIELDS: &[&str] = &["dns_overrides"];
|
||||
|
||||
/// Whether `key` is an allowed top-level PATCH/GET section name.
|
||||
///
|
||||
/// Fully editable sections from [`EDITABLE_SECTIONS`], plus `server` which is
|
||||
/// further restricted by [`EDITABLE_SERVER_FIELDS`].
|
||||
/// Fully editable sections plus `server` and `network`, each further restricted
|
||||
/// by its nested field allowlist.
|
||||
pub(super) fn is_editable_section(key: &str) -> bool {
|
||||
EDITABLE_SECTIONS.contains(&key) || key == "server"
|
||||
EDITABLE_SECTIONS.contains(&key) || matches!(key, "server" | "network")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use std::fs::File;
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[cfg(unix)]
|
||||
use std::os::unix::fs::{MetadataExt, PermissionsExt};
|
||||
@@ -26,8 +27,20 @@ enum AtomicWriteError {
|
||||
Conflict,
|
||||
ReadGraph(String),
|
||||
Io(std::io::Error),
|
||||
RuntimeConflict,
|
||||
}
|
||||
|
||||
pub(in crate::api) type CommitCheck = Arc<dyn Fn() -> bool + Send + Sync>;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct RuntimeConflict;
|
||||
impl std::fmt::Display for RuntimeConflict {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter.write_str("Runtime configuration changed before persistence")
|
||||
}
|
||||
}
|
||||
impl std::error::Error for RuntimeConflict {}
|
||||
|
||||
struct ExistingTarget {
|
||||
contents: String,
|
||||
metadata: std::fs::Metadata,
|
||||
@@ -36,6 +49,7 @@ struct ExistingTarget {
|
||||
struct GraphFence<'a> {
|
||||
config_path: &'a Path,
|
||||
expected_revision: &'a str,
|
||||
runtime_check: Option<&'a CommitCheck>,
|
||||
}
|
||||
|
||||
struct ConfigWriteLock {
|
||||
@@ -98,6 +112,27 @@ pub(in crate::api) async fn write_atomic_if_unchanged(
|
||||
path: PathBuf,
|
||||
expected_contents: String,
|
||||
contents: String,
|
||||
) -> Result<String, ApiFailure> {
|
||||
write_atomic_with_runtime_check(
|
||||
config_path,
|
||||
expected_revision,
|
||||
path,
|
||||
expected_contents,
|
||||
contents,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// The runtime check runs after source fencing, immediately before the rename.
|
||||
/// It is an optimistic check, not a lock against later runtime publication.
|
||||
pub(in crate::api) async fn write_atomic_with_runtime_check(
|
||||
config_path: PathBuf,
|
||||
expected_revision: String,
|
||||
path: PathBuf,
|
||||
expected_contents: String,
|
||||
contents: String,
|
||||
runtime_check: Option<CommitCheck>,
|
||||
) -> Result<String, ApiFailure> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let config_path = normalize_path(&config_path);
|
||||
@@ -116,10 +151,16 @@ pub(in crate::api) async fn write_atomic_if_unchanged(
|
||||
Some(GraphFence {
|
||||
config_path: &config_path,
|
||||
expected_revision: &expected_revision,
|
||||
runtime_check: runtime_check.as_ref(),
|
||||
}),
|
||||
)
|
||||
.map_err(|error| {
|
||||
if error.kind() == std::io::ErrorKind::AlreadyExists {
|
||||
if error
|
||||
.get_ref()
|
||||
.is_some_and(|inner| inner.is::<RuntimeConflict>())
|
||||
{
|
||||
AtomicWriteError::RuntimeConflict
|
||||
} else if error.kind() == std::io::ErrorKind::AlreadyExists {
|
||||
AtomicWriteError::Conflict
|
||||
} else {
|
||||
AtomicWriteError::Io(error)
|
||||
@@ -135,6 +176,11 @@ pub(in crate::api) async fn write_atomic_if_unchanged(
|
||||
.map_err(|error| ApiFailure::internal(format!("failed to join writer: {error}")))?
|
||||
.map_err(|error| match error {
|
||||
AtomicWriteError::Conflict => revision_conflict(),
|
||||
AtomicWriteError::RuntimeConflict => ApiFailure::new(
|
||||
hyper::StatusCode::CONFLICT,
|
||||
"runtime_conflict",
|
||||
"Runtime configuration changed before persistence",
|
||||
),
|
||||
AtomicWriteError::ReadGraph(error) => {
|
||||
ApiFailure::internal(format!("failed to verify config graph: {error}"))
|
||||
}
|
||||
@@ -203,7 +249,14 @@ fn fenced_post_commit_revision(
|
||||
));
|
||||
};
|
||||
*owner = contents.to_string();
|
||||
Ok(compute_source_revision(&graph))
|
||||
let revision = compute_source_revision(&graph);
|
||||
if fence.runtime_check.is_some_and(|check| !check()) {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::WouldBlock,
|
||||
RuntimeConflict,
|
||||
));
|
||||
}
|
||||
Ok(revision)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -393,9 +446,16 @@ fn write_atomic_sync(
|
||||
"config target changed during persistence",
|
||||
));
|
||||
}
|
||||
let committed_revision = graph_fence
|
||||
let committed_revision = match graph_fence
|
||||
.map(|fence| fenced_post_commit_revision(fence, path, contents))
|
||||
.transpose()?;
|
||||
.transpose()
|
||||
{
|
||||
Ok(revision) => revision,
|
||||
Err(error) => {
|
||||
let _ = std::fs::remove_file(&temp);
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
std::fs::rename(temp, path)?;
|
||||
Ok(committed_revision)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
//! Preserve sibling source bytes when editing the one API-owned network key.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::Deserialize;
|
||||
use toml::{Spanned, Value};
|
||||
|
||||
use crate::api::model::ApiFailure;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Source {
|
||||
network: Option<Spanned<BTreeMap<String, Spanned<Value>>>>,
|
||||
}
|
||||
|
||||
pub(in crate::api) fn upsert_dns_overrides(
|
||||
source: &str,
|
||||
entries: &[String],
|
||||
) -> Result<String, ApiFailure> {
|
||||
let parsed: Source = toml::from_str(source)
|
||||
.map_err(|_| ApiFailure::internal("Cannot locate network.dns_overrides in its source"))?;
|
||||
let value = Value::Array(entries.iter().cloned().map(Value::String).collect()).to_string();
|
||||
let newline = if source.contains("\r\n") {
|
||||
"\r\n"
|
||||
} else {
|
||||
"\n"
|
||||
};
|
||||
let mut out = source.to_owned();
|
||||
match parsed.network {
|
||||
Some(network) => {
|
||||
if let Some(existing) = network.get_ref().get("dns_overrides") {
|
||||
// Parser byte spans cover the value, including multiline arrays,
|
||||
// but exclude the key, surrounding comments and sibling fields.
|
||||
out.replace_range(existing.span(), &value);
|
||||
} else {
|
||||
let span = network.span();
|
||||
let representation = &source[span.clone()];
|
||||
if representation.starts_with('{') {
|
||||
let separator = if network.get_ref().is_empty() {
|
||||
""
|
||||
} else {
|
||||
", "
|
||||
};
|
||||
out.insert_str(
|
||||
span.start + 1,
|
||||
&format!("dns_overrides = {value}{separator}"),
|
||||
);
|
||||
} else if representation.starts_with('[') {
|
||||
// The table span ends at ']', before any trailing comment.
|
||||
let end = source[span.end..]
|
||||
.find('\n')
|
||||
.map(|offset| span.end + offset + 1);
|
||||
if let Some(end) = end {
|
||||
out.insert_str(end, &format!("dns_overrides = {value}{newline}"));
|
||||
} else {
|
||||
out.push_str(&format!("{newline}dns_overrides = {value}{newline}"));
|
||||
}
|
||||
} else {
|
||||
// A dotted network key creates an implicit table at root.
|
||||
// Insert beside that declaration, not inside a later table.
|
||||
let start = source[..span.start]
|
||||
.rfind('\n')
|
||||
.map_or(0, |offset| offset + 1);
|
||||
out.insert_str(start, &format!("network.dns_overrides = {value}{newline}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if !out.is_empty() && !out.ends_with('\n') {
|
||||
out.push_str(newline);
|
||||
}
|
||||
out.push_str(&format!(
|
||||
"[network]{newline}dns_overrides = {value}{newline}"
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
//! Structural edits to allowlisted scalar fields and literal map keys.
|
||||
|
||||
use super::*;
|
||||
use toml_edit::{DocumentMut, Item, Table};
|
||||
|
||||
pub(in crate::api) struct FieldEdit {
|
||||
pub path: Vec<String>,
|
||||
pub value: Option<toml::Value>,
|
||||
}
|
||||
|
||||
impl FieldEdit {
|
||||
pub fn new(path: &[&str], value: Option<toml::Value>) -> Self {
|
||||
Self {
|
||||
path: path.iter().map(|part| (*part).to_owned()).collect(),
|
||||
value,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::api) struct OwnedSourceEdit {
|
||||
pub owner_path: PathBuf,
|
||||
pub expected_owner_contents: String,
|
||||
pub owner_contents: String,
|
||||
}
|
||||
|
||||
fn conflict() -> ApiFailure {
|
||||
ApiFailure::new(
|
||||
hyper::StatusCode::CONFLICT,
|
||||
"config_patch_not_atomic",
|
||||
"Mutation requires one independently writable config source",
|
||||
)
|
||||
}
|
||||
|
||||
fn at_path<'a>(document: &'a DocumentMut, path: &[String]) -> Option<&'a Item> {
|
||||
path.iter()
|
||||
.try_fold(document.as_item(), |item, key| item.get(key))
|
||||
}
|
||||
|
||||
fn edit(item: &mut Item, path: &[String], value: Option<&toml::Value>) -> Result<(), ApiFailure> {
|
||||
let Some((key, rest)) = path.split_first() else {
|
||||
return Err(ApiFailure::internal("Empty configuration edit path"));
|
||||
};
|
||||
let table = item.as_table_like_mut().ok_or_else(conflict)?;
|
||||
if rest.is_empty() {
|
||||
if let Some(value) = value {
|
||||
let mut value = value
|
||||
.to_string()
|
||||
.parse::<toml_edit::Value>()
|
||||
.map_err(|_| ApiFailure::internal("Cannot render configuration value"))?;
|
||||
if let Some(old) = table.get(key).and_then(Item::as_value) {
|
||||
*value.decor_mut() = old.decor().clone();
|
||||
}
|
||||
table.insert(key, Item::Value(value));
|
||||
} else {
|
||||
table.remove(key);
|
||||
}
|
||||
} else {
|
||||
if !table.contains_key(key) {
|
||||
if value.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
table.insert(key, Item::Table(Table::new()));
|
||||
}
|
||||
edit(table.get_mut(key).ok_or_else(conflict)?, rest, value)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Exact leaf ownership wins; insertion uses the nearest existing parent.
|
||||
/// Literal map keys are separate path components, including dots and CIDRs.
|
||||
pub(in crate::api) fn prepare_field_edits(
|
||||
loaded: &ParsedConfigSource,
|
||||
config_path: &Path,
|
||||
edits: &[FieldEdit],
|
||||
) -> Result<Option<OwnedSourceEdit>, ApiFailure> {
|
||||
if edits.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
if loaded
|
||||
.source_contents
|
||||
.values()
|
||||
.any(|source| has_include_inside_table(source))
|
||||
{
|
||||
return Err(conflict());
|
||||
}
|
||||
let mut sources = loaded
|
||||
.source_contents
|
||||
.iter()
|
||||
.map(|(path, source)| {
|
||||
source
|
||||
.parse::<DocumentMut>()
|
||||
.map(|document| (path.clone(), document))
|
||||
.map_err(|_| conflict())
|
||||
})
|
||||
.collect::<Result<BTreeMap<_, _>, _>>()?;
|
||||
let mut owners = BTreeSet::new();
|
||||
let mut effective = Vec::new();
|
||||
for change in edits {
|
||||
if change.path.is_empty() {
|
||||
return Err(ApiFailure::internal("Empty configuration edit path"));
|
||||
}
|
||||
let mut found = BTreeSet::new();
|
||||
for length in (1..=change.path.len()).rev() {
|
||||
found = sources
|
||||
.iter()
|
||||
.filter(|(_, document)| at_path(document, &change.path[..length]).is_some())
|
||||
.map(|(path, _)| path.clone())
|
||||
.collect();
|
||||
if !found.is_empty() {
|
||||
break;
|
||||
}
|
||||
// Removing an absent field is a no-op, not an insertion into a parent.
|
||||
if change.value.is_none() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if found.len() > 1 {
|
||||
return Err(conflict());
|
||||
}
|
||||
if found.is_empty() && change.value.is_none() {
|
||||
continue;
|
||||
}
|
||||
owners.insert(
|
||||
found
|
||||
.into_iter()
|
||||
.next()
|
||||
.unwrap_or_else(|| normalize_source_path(config_path)),
|
||||
);
|
||||
effective.push(change);
|
||||
}
|
||||
if effective.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
if owners.len() != 1 {
|
||||
return Err(conflict());
|
||||
}
|
||||
let owner_path = owners.into_iter().next().ok_or_else(conflict)?;
|
||||
let document = sources.get_mut(&owner_path).ok_or_else(conflict)?;
|
||||
for change in effective {
|
||||
edit(document.as_item_mut(), &change.path, change.value.as_ref())?;
|
||||
}
|
||||
let expected_owner_contents = loaded
|
||||
.source_contents
|
||||
.get(&owner_path)
|
||||
.ok_or_else(conflict)?
|
||||
.clone();
|
||||
Ok(Some(OwnedSourceEdit {
|
||||
owner_path,
|
||||
expected_owner_contents,
|
||||
owner_contents: document.to_string(),
|
||||
}))
|
||||
}
|
||||
@@ -12,8 +12,8 @@ use super::atomic::write_atomic_if_unchanged;
|
||||
#[cfg(test)]
|
||||
use super::compute_revision;
|
||||
use super::{
|
||||
AccessSection, compute_snapshot_revision, load_candidate_snapshot, load_config_snapshot,
|
||||
resolve_single_source_owner, toml_path_exists,
|
||||
AccessSection, FieldEdit, compute_snapshot_revision, load_candidate_snapshot,
|
||||
load_config_snapshot, prepare_field_edits, resolve_single_source_owner, toml_path_exists,
|
||||
};
|
||||
use crate::api::model::ApiFailure;
|
||||
|
||||
@@ -97,6 +97,7 @@ pub(in crate::api) fn render_server_listeners(cfg: &ProxyConfig) -> Result<Strin
|
||||
}
|
||||
|
||||
/// Validates and atomically writes access tables to their single source owner.
|
||||
#[cfg(test)]
|
||||
pub(in crate::api) async fn save_access_sections_to_disk(
|
||||
config_path: &Path,
|
||||
cfg: &ProxyConfig,
|
||||
@@ -111,6 +112,24 @@ pub(in crate::api) async fn save_access_sections_to_disk_if_revision(
|
||||
cfg: &ProxyConfig,
|
||||
sections: &[AccessSection],
|
||||
expected_revision: Option<&str>,
|
||||
) -> Result<String, ApiFailure> {
|
||||
save_access_sections_and_fields_if_revision(
|
||||
config_path,
|
||||
cfg,
|
||||
sections,
|
||||
Vec::new(),
|
||||
expected_revision,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Commits legacy user tables and precise source-deny edits in one owner file.
|
||||
pub(in crate::api) async fn save_access_sections_and_fields_if_revision(
|
||||
config_path: &Path,
|
||||
cfg: &ProxyConfig,
|
||||
sections: &[AccessSection],
|
||||
fields: Vec<FieldEdit>,
|
||||
expected_revision: Option<&str>,
|
||||
) -> Result<String, ApiFailure> {
|
||||
let loaded = load_config_snapshot(config_path, false).await?;
|
||||
let loaded_revision = compute_snapshot_revision(&loaded.source_contents);
|
||||
@@ -132,7 +151,17 @@ pub(in crate::api) async fn save_access_sections_to_disk_if_revision(
|
||||
.is_some_and(|value| toml_path_exists(&value, section.table_name()))
|
||||
})
|
||||
});
|
||||
if applied.is_empty() {
|
||||
let compare_source_deny = !fields.is_empty();
|
||||
let precise = if fields.is_empty() {
|
||||
None
|
||||
} else {
|
||||
let source = loaded.clone();
|
||||
let path = config_path.to_path_buf();
|
||||
tokio::task::spawn_blocking(move || prepare_field_edits(&source, &path, &fields))
|
||||
.await
|
||||
.map_err(|_| ApiFailure::internal("Source edit worker failed"))??
|
||||
};
|
||||
if applied.is_empty() && precise.is_none() {
|
||||
return Ok(loaded_revision);
|
||||
}
|
||||
|
||||
@@ -140,13 +169,31 @@ pub(in crate::api) async fn save_access_sections_to_disk_if_revision(
|
||||
.iter()
|
||||
.map(|section| section.table_name())
|
||||
.collect::<Vec<_>>();
|
||||
let owner_path = resolve_single_source_owner(&loaded, config_path, &targets)?;
|
||||
let mut owner_contents = loaded
|
||||
let table_owner = if targets.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(resolve_single_source_owner(&loaded, config_path, &targets)?)
|
||||
};
|
||||
if let (Some(table_owner), Some(precise)) = (&table_owner, &precise)
|
||||
&& table_owner != &precise.owner_path
|
||||
{
|
||||
return Err(ApiFailure::new(
|
||||
hyper::StatusCode::CONFLICT,
|
||||
"config_patch_not_atomic",
|
||||
"User tables and source-deny rule require different source owners",
|
||||
));
|
||||
}
|
||||
let owner_path = table_owner
|
||||
.or_else(|| precise.as_ref().map(|edit| edit.owner_path.clone()))
|
||||
.ok_or_else(|| ApiFailure::internal("Missing user mutation owner"))?;
|
||||
let expected_owner_contents = loaded
|
||||
.source_contents
|
||||
.get(&owner_path)
|
||||
.cloned()
|
||||
.ok_or_else(|| ApiFailure::internal("config source owner is missing from snapshot"))?;
|
||||
let expected_owner_contents = owner_contents.clone();
|
||||
let mut owner_contents = precise
|
||||
.map(|edit| edit.owner_contents)
|
||||
.unwrap_or_else(|| expected_owner_contents.clone());
|
||||
for section in applied {
|
||||
let rendered = render_access_section(cfg, section)?;
|
||||
owner_contents = upsert_toml_table(&owner_contents, section.table_name(), &rendered);
|
||||
@@ -158,7 +205,25 @@ pub(in crate::api) async fn save_access_sections_to_disk_if_revision(
|
||||
owner_path.clone(),
|
||||
owner_contents.clone(),
|
||||
)
|
||||
.await?;
|
||||
.await
|
||||
.map_err(|error| {
|
||||
if compare_source_deny {
|
||||
ApiFailure::new(
|
||||
error.status,
|
||||
error.code,
|
||||
"Cannot prepare user policy candidate",
|
||||
)
|
||||
} else {
|
||||
error
|
||||
}
|
||||
})?;
|
||||
if compare_source_deny
|
||||
&& candidate.config.access.user_source_deny != cfg.access.user_source_deny
|
||||
{
|
||||
return Err(ApiFailure::internal(
|
||||
"Persisted source-deny rules differ from requested policy",
|
||||
));
|
||||
}
|
||||
let _candidate_revision = compute_snapshot_revision(&candidate.source_contents);
|
||||
let revision = write_atomic_if_unchanged(
|
||||
config_path.to_path_buf(),
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
//! Read-only discovery of implemented operations and configuration contracts.
|
||||
//!
|
||||
//! Field defaults come from unconfigured types, never the active or disk config.
|
||||
//! Availability samples only existing control-plane publications without waiting.
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::config::ProxyConfig;
|
||||
use crate::web::control::WebRuntimeLifecycle;
|
||||
|
||||
use super::ApiShared;
|
||||
use super::model::ApiFailure;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(in crate::api) mod http_tests;
|
||||
mod schema;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
pub(super) use schema::config_schema;
|
||||
|
||||
pub(super) fn config_field_paths() -> Result<Vec<&'static str>, ApiFailure> {
|
||||
schema::field_paths()
|
||||
}
|
||||
|
||||
pub(super) use schema::projection_rules;
|
||||
|
||||
pub(super) const SCHEMA_VERSION: u32 = 1;
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(super) struct Operation {
|
||||
pub(super) id: String,
|
||||
pub(super) method: String,
|
||||
pub(super) path: String,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub(super) aliases: Vec<String>,
|
||||
pub(super) gate: Gate,
|
||||
pub(super) success: Vec<u16>,
|
||||
#[serde(default)]
|
||||
pub(super) credential_bearing: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(super) body: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(super) optional_body: bool,
|
||||
#[serde(default)]
|
||||
pub(super) exact_json_content_type: bool,
|
||||
#[serde(default)]
|
||||
pub(super) if_match: bool,
|
||||
#[serde(default)]
|
||||
pub(super) if_runtime_match: bool,
|
||||
#[serde(default)]
|
||||
pub(super) read_only_operation: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(super) enum Gate {
|
||||
Always,
|
||||
Minimal,
|
||||
MinimalMe,
|
||||
MiddleProxy,
|
||||
Upstream,
|
||||
Edge,
|
||||
WebRead,
|
||||
WebControl,
|
||||
}
|
||||
|
||||
pub(super) fn operations() -> Result<&'static [Operation], ApiFailure> {
|
||||
static CATALOG: OnceLock<Result<Vec<Operation>, String>> = OnceLock::new();
|
||||
CATALOG
|
||||
.get_or_init(|| {
|
||||
serde_json::from_str(include_str!("discovery/operations.json"))
|
||||
.map_err(|error| format!("invalid compiled operation catalog: {error}"))
|
||||
})
|
||||
.as_deref()
|
||||
.map_err(|error| ApiFailure::internal(error.clone()))
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub(super) struct CapabilitiesData {
|
||||
api_version: &'static str,
|
||||
schema_version: u32,
|
||||
software_version: &'static str,
|
||||
config_schema: &'static str,
|
||||
read_only: bool,
|
||||
availability_scope: &'static str,
|
||||
operations: Vec<OperationCapability>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct OperationCapability {
|
||||
#[serde(flatten)]
|
||||
operation: &'static Operation,
|
||||
supported: bool,
|
||||
enabled: bool,
|
||||
/// Null means an optional runtime source was not sampled or its lock was busy.
|
||||
available: Option<bool>,
|
||||
mutable: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
disabled_reason: Option<&'static str>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
unavailable_reason: Option<&'static str>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
mutation_blocked_reason: Option<&'static str>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Availability {
|
||||
pub(super) me_pool: Option<bool>,
|
||||
pub(super) web_read: bool,
|
||||
pub(super) web_control: bool,
|
||||
}
|
||||
|
||||
pub(super) fn capabilities(
|
||||
shared: &ApiShared,
|
||||
config: &ProxyConfig,
|
||||
) -> Result<CapabilitiesData, ApiFailure> {
|
||||
let me_pool = shared.me_pool.try_read().ok().map(|pool| pool.is_some());
|
||||
let availability = {
|
||||
let publication = shared.web_runtime_rx.borrow();
|
||||
let web_alive = publication.runtime.upgrade().is_some();
|
||||
Availability {
|
||||
me_pool,
|
||||
web_read: web_alive
|
||||
&& matches!(
|
||||
publication.lifecycle,
|
||||
WebRuntimeLifecycle::Running | WebRuntimeLifecycle::Draining
|
||||
),
|
||||
web_control: web_alive && publication.lifecycle == WebRuntimeLifecycle::Running,
|
||||
}
|
||||
};
|
||||
build_capabilities(config, availability)
|
||||
}
|
||||
|
||||
fn build_capabilities(
|
||||
config: &ProxyConfig,
|
||||
availability: Availability,
|
||||
) -> Result<CapabilitiesData, ApiFailure> {
|
||||
let mut entries = Vec::with_capacity(operations()?.len());
|
||||
for operation in operations()? {
|
||||
let feature_enabled = match operation.gate {
|
||||
Gate::Minimal | Gate::MinimalMe => config.server.api.minimal_runtime_enabled,
|
||||
Gate::Edge => config.server.api.runtime_edge_enabled,
|
||||
_ => true,
|
||||
};
|
||||
let enabled = config.server.api.enabled && feature_enabled;
|
||||
let (available, unavailable_reason) = if !enabled {
|
||||
(Some(false), None)
|
||||
} else {
|
||||
match operation.gate {
|
||||
Gate::MinimalMe | Gate::MiddleProxy => match availability.me_pool {
|
||||
Some(true) => (Some(true), None),
|
||||
Some(false) => (Some(false), Some("source_unavailable")),
|
||||
None => (None, Some("snapshot_busy")),
|
||||
},
|
||||
Gate::WebRead if !availability.web_read => {
|
||||
(Some(false), Some("web_runtime_unavailable"))
|
||||
}
|
||||
Gate::WebControl if !availability.web_control => {
|
||||
(Some(false), Some("web_runtime_unavailable"))
|
||||
}
|
||||
// These handlers perform their own bounded aggregation. Discovery
|
||||
// does not repeat it or claim a sampled health/lock result.
|
||||
Gate::Minimal | Gate::Upstream => (None, Some("availability_not_sampled")),
|
||||
Gate::Edge if operation.id == "runtime_connections_summary" => {
|
||||
(None, Some("availability_not_sampled"))
|
||||
}
|
||||
_ => (Some(true), None),
|
||||
}
|
||||
};
|
||||
let mutation = operation.method != "GET" && !operation.read_only_operation;
|
||||
entries.push(OperationCapability {
|
||||
operation,
|
||||
supported: true,
|
||||
enabled,
|
||||
available,
|
||||
mutable: mutation && config.server.api.enabled && !config.server.api.read_only,
|
||||
disabled_reason: if !config.server.api.enabled {
|
||||
Some("api_disabled")
|
||||
} else if !feature_enabled {
|
||||
Some("feature_disabled")
|
||||
} else {
|
||||
None
|
||||
},
|
||||
unavailable_reason,
|
||||
mutation_blocked_reason: if mutation && config.server.api.read_only {
|
||||
Some("read_only")
|
||||
} else {
|
||||
None
|
||||
},
|
||||
});
|
||||
}
|
||||
Ok(CapabilitiesData {
|
||||
api_version: "v1",
|
||||
schema_version: SCHEMA_VERSION,
|
||||
software_version: env!("CARGO_PKG_VERSION"),
|
||||
config_schema: "/v1/config/schema",
|
||||
read_only: config.server.api.read_only,
|
||||
availability_scope: "feature_and_runtime_source_prerequisites_not_request_success",
|
||||
operations: entries,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn reject_query(query: Option<&str>) -> Result<(), ApiFailure> {
|
||||
if query.is_some_and(|query| !query.is_empty()) {
|
||||
return Err(ApiFailure::bad_request(
|
||||
"discovery endpoints do not accept query parameters",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,476 @@
|
||||
[
|
||||
{"path":"access","value":{"type":"object"},"default_kind":"nested_fields","sensitivity":"public","description":"User authentication secrets and admission policy.","apply":{"watcher":"mixed","reload":"mixed","effect":"see_child_fields"}},
|
||||
{"path":"access.cidr_rate_limits","value":{"type":"object","additionalProperties":{"type":"object"}},"default_kind":"type_default","sensitivity":"public","description":"Per-CIDR aggregate transport rate limits in bits-per-second. Explicit CIDR keys use longest-prefix-wins semantics. Auto-template keys (`*4/N`, `*6/N`, `*/N`) lazily create per-source-subnet buckets after explicit CIDR matching misses. A value of `0` in one direction means \"unlimited\" for that direction. Limits are amortized with the same bounded-burst contract as per-user rate limits.","apply":{"watcher":"supported","reload":"supported","effect":"admission_or_accounting_policy_consumption_no_implicit_quota_reset"}},
|
||||
{"path":"access.cidr_rate_limits.{cidr}","value":{"type":"object"},"default_kind":"map_entry","sensitivity":"public","description":"Configuration value for access.cidr_rate_limits.{cidr}.","apply":{"watcher":"supported","reload":"supported","effect":"admission_or_accounting_policy_consumption_no_implicit_quota_reset"}},
|
||||
{"path":"access.cidr_rate_limits.{cidr}.down_bps","value":{"type":"integer","minimum":0,"maximum":100000000000},"default_kind":"map_entry","sensitivity":"public","description":"Download limit in bits-per-second within `0..=100_000_000_000`; `0` means unlimited.","unit":"bits_per_second","apply":{"watcher":"supported","reload":"supported","effect":"admission_or_accounting_policy_consumption_no_implicit_quota_reset"},"constraints":["At least one direction must be nonzero; zero means unlimited for that direction."]},
|
||||
{"path":"access.cidr_rate_limits.{cidr}.up_bps","value":{"type":"integer","minimum":0,"maximum":100000000000},"default_kind":"map_entry","sensitivity":"public","description":"Upload limit in bits-per-second within `0..=100_000_000_000`; `0` means unlimited.","unit":"bits_per_second","apply":{"watcher":"supported","reload":"supported","effect":"admission_or_accounting_policy_consumption_no_implicit_quota_reset"},"constraints":["At least one direction must be nonzero; zero means unlimited for that direction."]},
|
||||
{"path":"access.ignore_time_skew","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for access.ignore_time_skew.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"access.replay_check_len","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for access.replay_check_len.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"access.replay_window_secs","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for access.replay_window_secs.","unit":"seconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"access.user_ad_tags","value":{"type":"object","additionalProperties":{"type":"string"}},"default_kind":"type_default","sensitivity":"public","description":"Per-user ad_tag (32 hex chars from @MTProxybot).","apply":{"watcher":"supported","reload":"supported","effect":"admission_or_accounting_policy_consumption_no_implicit_quota_reset"}},
|
||||
{"path":"access.user_ad_tags.{username}","value":{"type":"string"},"default_kind":"map_entry","sensitivity":"public","description":"Configuration value for access.user_ad_tags.{username}.","apply":{"watcher":"supported","reload":"supported","effect":"admission_or_accounting_policy_consumption_no_implicit_quota_reset"}},
|
||||
{"path":"access.user_data_quota","value":{"type":"object","additionalProperties":{"type":"integer","minimum":0,"maximum":18446744073709551615}},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for access.user_data_quota.","apply":{"watcher":"supported","reload":"supported","effect":"admission_or_accounting_policy_consumption_no_implicit_quota_reset"}},
|
||||
{"path":"access.user_data_quota.{username}","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"map_entry","sensitivity":"public","description":"Configuration value for access.user_data_quota.{username}.","unit":"bytes","apply":{"watcher":"supported","reload":"supported","effect":"admission_or_accounting_policy_consumption_no_implicit_quota_reset"}},
|
||||
{"path":"access.user_enabled","value":{"type":"object","additionalProperties":{"type":"boolean"}},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for access.user_enabled.","apply":{"watcher":"supported","reload":"supported","effect":"admission_or_accounting_policy_consumption_no_implicit_quota_reset"}},
|
||||
{"path":"access.user_enabled.{username}","value":{"type":"boolean"},"default_kind":"map_entry","sensitivity":"public","description":"Configuration value for access.user_enabled.{username}.","apply":{"watcher":"supported","reload":"supported","effect":"admission_or_accounting_policy_consumption_no_implicit_quota_reset"}},
|
||||
{"path":"access.user_expirations","value":{"type":"object","additionalProperties":{"type":"string","format":"date-time"}},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for access.user_expirations.","apply":{"watcher":"supported","reload":"supported","effect":"admission_or_accounting_policy_consumption_no_implicit_quota_reset"}},
|
||||
{"path":"access.user_expirations.{username}","value":{"type":"string","format":"date-time"},"default_kind":"map_entry","sensitivity":"public","description":"Configuration value for access.user_expirations.{username}.","apply":{"watcher":"supported","reload":"supported","effect":"admission_or_accounting_policy_consumption_no_implicit_quota_reset"}},
|
||||
{"path":"access.user_max_tcp_conns","value":{"type":"object","additionalProperties":{"type":"integer","minimum":0,"maximum":18446744073709551615}},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for access.user_max_tcp_conns.","apply":{"watcher":"supported","reload":"supported","effect":"admission_or_accounting_policy_consumption_no_implicit_quota_reset"}},
|
||||
{"path":"access.user_max_tcp_conns.{username}","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"map_entry","sensitivity":"public","description":"Configuration value for access.user_max_tcp_conns.{username}.","apply":{"watcher":"supported","reload":"supported","effect":"admission_or_accounting_policy_consumption_no_implicit_quota_reset"}},
|
||||
{"path":"access.user_max_tcp_conns_global_each","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Global per-user TCP connection limit applied when a user has no positive individual override. `0` disables the inherited limit.","apply":{"watcher":"supported","reload":"supported","effect":"admission_or_accounting_policy_consumption_no_implicit_quota_reset"}},
|
||||
{"path":"access.user_max_unique_ips","value":{"type":"object","additionalProperties":{"type":"integer","minimum":0,"maximum":18446744073709551615}},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for access.user_max_unique_ips.","apply":{"watcher":"supported","reload":"supported","effect":"admission_or_accounting_policy_consumption_no_implicit_quota_reset"}},
|
||||
{"path":"access.user_max_unique_ips.{username}","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"map_entry","sensitivity":"public","description":"Configuration value for access.user_max_unique_ips.{username}.","apply":{"watcher":"supported","reload":"supported","effect":"admission_or_accounting_policy_consumption_no_implicit_quota_reset"}},
|
||||
{"path":"access.user_max_unique_ips_global_each","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Global per-user unique IP limit applied when a user has no individual override. `0` disables the inherited limit.","apply":{"watcher":"supported","reload":"supported","effect":"admission_or_accounting_policy_consumption_no_implicit_quota_reset"}},
|
||||
{"path":"access.user_max_unique_ips_mode","value":{"type":"string","enum":["active_window","time_window","combined"]},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for access.user_max_unique_ips_mode.","apply":{"watcher":"supported","reload":"supported","effect":"admission_or_accounting_policy_consumption_no_implicit_quota_reset"}},
|
||||
{"path":"access.user_max_unique_ips_window_secs","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for access.user_max_unique_ips_window_secs.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"admission_or_accounting_policy_consumption_no_implicit_quota_reset"}},
|
||||
{"path":"access.user_quota_periods","value":{"type":"object","additionalProperties":{"type":"string","enum":["daily","weekly","monthly"]}},"default_kind":"type_default","sensitivity":"public","description":"Optional UTC calendar for users with a positive data quota.","apply":{"watcher":"supported","reload":"supported","effect":"admission_or_accounting_policy_consumption_no_implicit_quota_reset"},"constraints":["An existing user with a positive data quota is required; calendars use UTC."]},
|
||||
{"path":"access.user_quota_periods.{username}","value":{"type":"string","enum":["daily","weekly","monthly"]},"default_kind":"map_entry","sensitivity":"public","description":"Configuration value for access.user_quota_periods.{username}.","apply":{"watcher":"supported","reload":"supported","effect":"admission_or_accounting_policy_consumption_no_implicit_quota_reset"},"constraints":["An existing user with a positive data quota is required; calendars use UTC."]},
|
||||
{"path":"access.user_rate_limits","value":{"type":"object","additionalProperties":{"type":"object"}},"default_kind":"type_default","sensitivity":"public","description":"Per-user transport rate limits in bits-per-second. Each entry supports independent upload (`up_bps`) and download (`down_bps`) ceilings. A value of `0` in one direction means \"unlimited\" for that direction. Limits are amortized: a relay quantum may pass as a bounded burst, and the limiter applies the resulting wait before later traffic in the same direction proceeds.","apply":{"watcher":"supported","reload":"supported","effect":"admission_or_accounting_policy_consumption_no_implicit_quota_reset"}},
|
||||
{"path":"access.user_rate_limits.{username}","value":{"type":"object"},"default_kind":"map_entry","sensitivity":"public","description":"Configuration value for access.user_rate_limits.{username}.","apply":{"watcher":"supported","reload":"supported","effect":"admission_or_accounting_policy_consumption_no_implicit_quota_reset"}},
|
||||
{"path":"access.user_rate_limits.{username}.down_bps","value":{"type":"integer","minimum":0,"maximum":100000000000},"default_kind":"map_entry","sensitivity":"public","description":"Download limit in bits-per-second within `0..=100_000_000_000`; `0` means unlimited.","unit":"bits_per_second","apply":{"watcher":"supported","reload":"supported","effect":"admission_or_accounting_policy_consumption_no_implicit_quota_reset"},"constraints":["At least one direction must be nonzero; zero means unlimited for that direction."]},
|
||||
{"path":"access.user_rate_limits.{username}.up_bps","value":{"type":"integer","minimum":0,"maximum":100000000000},"default_kind":"map_entry","sensitivity":"public","description":"Upload limit in bits-per-second within `0..=100_000_000_000`; `0` means unlimited.","unit":"bits_per_second","apply":{"watcher":"supported","reload":"supported","effect":"admission_or_accounting_policy_consumption_no_implicit_quota_reset"},"constraints":["At least one direction must be nonzero; zero means unlimited for that direction."]},
|
||||
{"path":"access.user_source_deny","value":{"type":"object","additionalProperties":{"type":"array","items":{"type":"string","format":"cidr"}}},"default_kind":"type_default","sensitivity":"public","description":"Per-username client source IP/CIDR deny list. Checked after successful authentication; matching IPs get the same rejection path as invalid auth (handshake fails closed for that connection).","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"constraints":["Strict-key validation accepts this map. Generation reload is required; no watcher overlay. Deleting a user retains its rule."]},
|
||||
{"path":"access.user_source_deny.{username}","value":{"type":"array","items":{"type":"string","format":"cidr"}},"default_kind":"map_entry","sensitivity":"public","description":"Configuration value for access.user_source_deny.{username}.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"constraints":["Strict-key validation accepts this map. Generation reload is required; no watcher overlay. Deleting a user retains its rule."]},
|
||||
{"path":"access.users","value":{"type":"object","additionalProperties":{"type":"string"}},"default_kind":"redacted","sensitivity":"credential","description":"Configuration value for access.users.","apply":{"watcher":"supported","reload":"supported","effect":"admission_or_accounting_policy_consumption_no_implicit_quota_reset"}},
|
||||
{"path":"access.users.{username}","value":{"type":"string","minLength":32,"maxLength":32,"pattern":"^[0-9A-Fa-f]{32}$"},"default_kind":"redacted","sensitivity":"credential","description":"Configuration value for access.users.{username}.","apply":{"watcher":"supported","reload":"supported","effect":"admission_or_accounting_policy_consumption_no_implicit_quota_reset"}},
|
||||
{"path":"censorship","value":{"type":"object"},"default_kind":"nested_fields","sensitivity":"public","description":"Anti-censorship behavior and traffic shaping configuration.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.alpn_enforce","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Enforce ALPN echo of client preference.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.exclusive_mask","value":{"type":"object","additionalProperties":{"type":"string"}},"default_kind":"type_default","sensitivity":"public","description":"Per-SNI TCP mask targets. Keys are SNI domains, values are `host:port`.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.exclusive_mask.{hostname}","value":{"type":"string"},"default_kind":"map_entry","sensitivity":"public","description":"Configuration value for censorship.exclusive_mask.{hostname}.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.fake_cert_len","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for censorship.fake_cert_len.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"unit":"bytes"},
|
||||
{"path":"censorship.mask","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for censorship.mask.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.mask_classifier_prefetch_timeout_ms","value":{"type":"integer","minimum":5,"maximum":50},"default_kind":"type_default","sensitivity":"public","description":"Prefetch timeout (ms) for extending fragmented masking classifier window.","unit":"milliseconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.mask_dynamic","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Use the ClientHello SNI as the mask TCP target for configured TLS domains.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.mask_host","value":{"type":"string"},"default_kind":"unset","sensitivity":"public","description":"Configuration value for censorship.mask_host.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.mask_port","value":{"type":"integer","minimum":0,"maximum":65535},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for censorship.mask_port.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.mask_proxy_protocol","value":{"type":"integer","minimum":0,"maximum":255},"default_kind":"type_default","sensitivity":"public","description":"Send PROXY protocol header when connecting to mask_host. 0 = disabled, 1 = v1 (text), 2 = v2 (binary). Allows the backend to see the real client IP.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.mask_relay_idle_timeout_ms","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Per-read idle timeout on masking relay and drain paths. Limits resource consumption by slow-loris attacks and port scanners. A read call stalling beyond this is treated as an abandoned connection. Default: 5 000 ms (5 s).","unit":"milliseconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.mask_relay_max_bytes","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Maximum bytes relayed per direction on unauthenticated masking fallback paths. Set to 0 to disable byte cap (unlimited within relay/idle timeouts).","unit":"bytes","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.mask_relay_timeout_ms","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Wall-clock cap for the full masking relay on non-MTProto fallback paths. Raise when the mask target is a long-lived service (e.g. WebSocket). Default: 60 000 ms (60 s).","unit":"milliseconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.mask_shape_above_cap_blur","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Add bounded random tail bytes even when total bytes already exceed mask_shape_bucket_cap_bytes.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.mask_shape_above_cap_blur_max_bytes","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Maximum random bytes appended above cap when above-cap blur is enabled.","unit":"bytes","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.mask_shape_bucket_cap_bytes","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Maximum bucket size for mask shape hardening padding.","unit":"bytes","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.mask_shape_bucket_floor_bytes","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Minimum bucket size for mask shape hardening padding.","unit":"bytes","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.mask_shape_hardening","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Enable shape-channel hardening on mask backend path by padding client->mask stream tail to configured buckets on stream end.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.mask_shape_hardening_aggressive_mode","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Opt-in aggressive shape hardening mode. When enabled, masking may shape some backend-silent timeout paths and enforces strictly positive above-cap blur when blur is enabled.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.mask_timing_normalization_ceiling_ms","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Upper bound (ms) for masking outcome timing envelope.","unit":"milliseconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.mask_timing_normalization_enabled","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Enable outcome-time normalization envelope for masking fallback.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.mask_timing_normalization_floor_ms","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Lower bound (ms) for masking outcome timing envelope.","unit":"milliseconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.mask_unix_sock","value":{"type":"string"},"default_kind":"unset","sensitivity":"public","description":"Configuration value for censorship.mask_unix_sock.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.server_hello_delay_max_ms","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Maximum server_hello delay in milliseconds.","unit":"milliseconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.server_hello_delay_min_ms","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Minimum server_hello delay in milliseconds (anti-fingerprint).","unit":"milliseconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.serverhello_compact","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Enable compact ServerHello payload mode. When false, FakeTLS always uses full ServerHello payload behavior. When true, compact certificate payload mode can be used by TTL policy.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.tls_domain","value":{"type":"string"},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for censorship.tls_domain.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.tls_domains","value":{"type":"array","items":{"type":"string"}},"default_kind":"type_default","sensitivity":"public","description":"Additional TLS domains for generating multiple proxy links.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.tls_emulation","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Enable TLS certificate emulation using cached real certificates.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.tls_fetch","value":{"type":"object"},"default_kind":"nested_fields","sensitivity":"public","description":"Fetch strategy for TLS front metadata bootstrap and periodic refresh.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.tls_fetch.attempt_timeout_ms","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Timeout per one profile attempt in milliseconds.","unit":"milliseconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.tls_fetch.deterministic","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Produces deterministic ClientHello randomness for debugging/tests.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.tls_fetch.grease_enabled","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Adds GREASE-style values into selected ClientHello extensions.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.tls_fetch.profile_cache_ttl_secs","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"TTL for winner-profile cache entries in seconds. Set to 0 to disable profile cache.","unit":"seconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.tls_fetch.profiles","value":{"type":"array","items":{"type":"string","enum":["modern_chrome_like","modern_firefox_like","compat_tls12","legacy_minimal"]}},"default_kind":"type_default","sensitivity":"public","description":"Ordered list of ClientHello profiles used for adaptive fallback.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.tls_fetch.strict_route","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"When true and upstream route is configured, TLS fetch fails closed on upstream connect errors and does not fallback to direct TCP.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.tls_fetch.total_budget_ms","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Total wall-clock budget in milliseconds across all profile attempts.","unit":"milliseconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.tls_fetch_scope","value":{"type":"string"},"default_kind":"type_default","sensitivity":"public","description":"Upstream scope used for TLS front metadata fetches. Empty value keeps default upstream routing behavior.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.tls_front_dir","value":{"type":"string"},"default_kind":"type_default","sensitivity":"public","description":"Directory to store TLS front cache (on disk).","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.tls_full_cert_ttl_secs","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"TTL in seconds for sending full certificate payload per client IP. First client connection per (SNI domain, client IP) gets full cert payload. Subsequent handshakes within TTL use compact cert metadata payload. Applied only when `serverhello_compact` is enabled.","unit":"seconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.tls_new_session_tickets","value":{"type":"integer","minimum":0,"maximum":255},"default_kind":"type_default","sensitivity":"public","description":"Number of NewSessionTicket messages to emit post-handshake.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"censorship.unknown_sni_action","value":{"type":"string","enum":["drop","mask","accept","reject_handshake"]},"default_kind":"type_default","sensitivity":"public","description":"Policy for TLS ClientHello with unknown (non-configured) SNI.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"dc_overrides","value":{"type":"object","additionalProperties":{"type":"array","items":{"type":"string"}}},"default_kind":"type_default","sensitivity":"public","description":"DC address overrides for non-standard DCs (CDN, media, test, etc.) Keys are DC indices as strings, values are one or more \"ip:port\" addresses. Matches the C implementation's `proxy_for <dc_id> <ip>:<port>` config directive. Example in config.toml: [dc_overrides] \"203\" = [\"149.154.175.100:443\", \"91.105.192.100:443\"]","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"dc_overrides.{dc}","value":{"type":"array","items":{"type":"string"}},"default_kind":"map_entry","sensitivity":"public","description":"Configuration value for dc_overrides.{dc}.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"default_dc","value":{"type":"integer","minimum":0,"maximum":255},"default_kind":"unset","sensitivity":"public","description":"Default DC index (1-5) for unmapped non-standard DCs. Matches the C implementation's `default <dc_id>` config directive. If not set, defaults to 2 (matching Telegram's official `default 2;` in proxy-multi.conf).","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general","value":{"type":"object"},"default_kind":"nested_fields","sensitivity":"public","description":"General runtime options shared across proxy subsystems.","apply":{"watcher":"mixed","reload":"mixed","effect":"see_child_fields"}},
|
||||
{"path":"general.ad_tag","value":{"type":"string"},"default_kind":"unset","sensitivity":"public","description":"Global ad_tag (32 hex chars from @MTProxybot). Fallback when user has no per-user tag in access.user_ad_tags.","apply":{"watcher":"supported","reload":"supported","effect":"watcher_publication_then_subsystem_policy_consumption"}},
|
||||
{"path":"general.auto_degradation_enabled","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Enable auto-degradation from ME to Direct-DC.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.beobachten","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Enable per-IP forensic observation buckets for scanners and handshake failures.","aliases":["beobachten"],"apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.beobachten_file","value":{"type":"string"},"default_kind":"type_default","sensitivity":"deployment","description":"Snapshot file path for beob output.","aliases":["beobachten_file"],"apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.beobachten_flush_secs","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Snapshot flush interval in seconds for beob output file.","aliases":["beobachten_flush_secs"],"unit":"seconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.beobachten_minutes","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Observation retention window in minutes for per-IP forensic buckets.","aliases":["beobachten_minutes"],"unit":"minutes","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.config_strict","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Reject unknown TOML config keys during load. Startup fails fast; hot-reload rejects the new snapshot and keeps the current config.","apply":{"watcher":"not_applicable","reload":"not_applicable","effect":"source_validation_on_next_load"}},
|
||||
{"path":"general.crypto_pending_buffer","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Max pending ciphertext buffer per client writer (bytes). Controls FakeTLS backpressure vs throughput.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"unit":"bytes"},
|
||||
{"path":"general.data_path","value":{"type":"string"},"default_kind":"unset","sensitivity":"deployment","description":"Configuration value for general.data_path.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"general.degradation_min_unavailable_dc_groups","value":{"type":"integer","minimum":0,"maximum":255},"default_kind":"type_default","sensitivity":"public","description":"Minimum unavailable ME DC groups before degrading.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.desync_all_full","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Emit full crypto-desync forensic logs for every event. When false, full forensic details are emitted once per key window.","apply":{"watcher":"supported","reload":"supported","effect":"watcher_publication_then_subsystem_policy_consumption"}},
|
||||
{"path":"general.direct_relay_buffer_budget_max_bytes","value":{"oneOf":[{"const":0},{"type":"integer","minimum":16777216,"maximum":2147483648,"multipleOf":4096}]},"default_kind":"type_default","sensitivity":"public","description":"Process-wide hard ceiling for Direct relay copy buffers. `0` derives the ceiling from host and cgroup memory limits.","unit":"bytes","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"general.direct_relay_copy_buf_c2s_bytes","value":{"type":"integer","minimum":4096,"maximum":1048576},"default_kind":"type_default","sensitivity":"public","description":"Copy buffer ceiling for client->DC direction in direct relay. This is also the upper bound for one amortized upload rate-limit burst: upload debt is settled before the next relay read instead of blocking inside the completed read path.","unit":"bytes","apply":{"watcher":"supported","reload":"supported","effect":"new_direct_relay_connections_keep_existing_buffers"}},
|
||||
{"path":"general.direct_relay_copy_buf_s2c_bytes","value":{"type":"integer","minimum":8192,"maximum":2097152},"default_kind":"type_default","sensitivity":"public","description":"Copy buffer ceiling for DC->client direction in direct relay. This bounds one direct download rate-limit grant because writes are clipped to the currently available shaper budget.","unit":"bytes","apply":{"watcher":"supported","reload":"supported","effect":"new_direct_relay_connections_keep_existing_buffers"}},
|
||||
{"path":"general.disable_colors","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Disable colored output in logs (useful for files/systemd).","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"general.fast_mode","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for general.fast_mode.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.fast_mode_min_tls_record","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Minimum TLS record size when fast_mode coalescing is enabled (0 = disabled).","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"unit":"bytes"},
|
||||
{"path":"general.hardswap","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Enable C-like hard-swap for ME pool generations. When true, Telemt prewarms a new generation and switches once full coverage is reached.","apply":{"watcher":"supported","reload":"supported","effect":"watcher_publication_then_subsystem_policy_consumption"}},
|
||||
{"path":"general.links","value":{"type":"object"},"default_kind":"nested_fields","sensitivity":"public","description":"[general.links] — proxy link generation overrides.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.links.public_host","value":{"type":"string"},"default_kind":"unset","sensitivity":"public","description":"Public hostname/IP for tg:// link generation (overrides detected IP).","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.links.public_port","value":{"type":"integer","minimum":0,"maximum":65535},"default_kind":"unset","sensitivity":"public","description":"Public port for tg:// link generation. Overrides listener ports and legacy `server.port`.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.links.show","value":{"oneOf":[{"const":"*"},{"type":"array","items":{"type":"string"}}]},"default_kind":"type_default","sensitivity":"public","description":"List of usernames whose tg:// links to display at startup. `\"*\"` = all users, `[\"alice\", \"bob\"]` = specific users.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.log_level","value":{"type":"string","enum":["debug","verbose","normal","silent"]},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for general.log_level.","apply":{"watcher":"supported","reload":"supported","effect":"log_filter_update"}},
|
||||
{"path":"general.max_client_frame","value":{"type":"integer","minimum":4096,"maximum":16777216},"default_kind":"type_default","sensitivity":"public","description":"Maximum allowed client MTProto frame size (bytes).","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"unit":"bytes"},
|
||||
{"path":"general.me2dc_fallback","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Allow fallback from Middle-End mode to direct DC when ME startup cannot be initialized.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.me2dc_fast","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Fast ME->Direct fallback mode for new sessions. Active only when both `use_middle_proxy=true` and `me2dc_fallback=true`.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.me_adaptive_floor_cpu_cores_override","value":{"type":"integer","minimum":0,"maximum":65535},"default_kind":"type_default","sensitivity":"public","description":"Override logical CPU core count for adaptive floor calculations. Set to 0 to use runtime auto-detection.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_adaptive_floor_idle_secs","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Idle time in seconds before adaptive floor can reduce single-endpoint writer target.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_adaptive_floor_max_active_writers_global","value":{"type":"integer","minimum":1,"maximum":4294967295},"default_kind":"type_default","sensitivity":"public","description":"Hard global cap for active ME writers.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_adaptive_floor_max_active_writers_per_core","value":{"type":"integer","minimum":1,"maximum":65535},"default_kind":"type_default","sensitivity":"public","description":"Hard cap for active ME writers per logical CPU core.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_adaptive_floor_max_extra_writers_multi_per_core","value":{"type":"integer","minimum":0,"maximum":65535},"default_kind":"type_default","sensitivity":"public","description":"Per-core max extra writers above base required floor for multi-endpoint DC groups.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_adaptive_floor_max_extra_writers_single_per_core","value":{"type":"integer","minimum":0,"maximum":65535},"default_kind":"type_default","sensitivity":"public","description":"Per-core max extra writers above base required floor for single-endpoint DC groups.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_adaptive_floor_max_warm_writers_global","value":{"type":"integer","minimum":1,"maximum":4294967295},"default_kind":"type_default","sensitivity":"public","description":"Hard global cap for warm ME writers.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_adaptive_floor_max_warm_writers_per_core","value":{"type":"integer","minimum":1,"maximum":65535},"default_kind":"type_default","sensitivity":"public","description":"Hard cap for warm ME writers per logical CPU core.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_adaptive_floor_min_writers_multi_endpoint","value":{"type":"integer","minimum":1,"maximum":32},"default_kind":"type_default","sensitivity":"public","description":"Minimum writer target for multi-endpoint DC groups in adaptive floor mode.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_adaptive_floor_min_writers_single_endpoint","value":{"type":"integer","minimum":1,"maximum":32},"default_kind":"type_default","sensitivity":"public","description":"Minimum writer target for single-endpoint DC groups in adaptive floor mode.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_adaptive_floor_recover_grace_secs","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Grace period in seconds to hold static floor after activity in adaptive mode.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_adaptive_floor_writers_per_core_total","value":{"type":"integer","minimum":1,"maximum":65535},"default_kind":"type_default","sensitivity":"public","description":"Global ME writer budget per logical CPU core in adaptive mode.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_admission_poll_ms","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Poll interval in milliseconds for conditional-admission state checks.","unit":"milliseconds","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_bind_stale_mode","value":{"type":"string","enum":["never","ttl","always"]},"default_kind":"type_default","sensitivity":"public","description":"Policy for new binds on stale draining writers.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_bind_stale_ttl_secs","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"TTL for stale bind allowance when `me_bind_stale_mode = \\\"ttl\\\"`.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_c2me_channel_capacity","value":{"type":"integer","minimum":1,"maximum":8192},"default_kind":"type_default","sensitivity":"public","description":"Capacity of per-client command queue from client reader to ME sender task.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_c2me_send_timeout_ms","value":{"type":"integer","minimum":0,"maximum":60000},"default_kind":"type_default","sensitivity":"public","description":"Maximum wait in milliseconds for enqueueing C2ME commands when the queue is full. `0` keeps legacy unbounded wait behavior.","unit":"milliseconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_config_apply_cooldown_secs","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Cooldown in seconds between applied ME map updates.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_config_stable_snapshots","value":{"type":"integer","minimum":1,"maximum":255},"default_kind":"type_default","sensitivity":"public","description":"Number of identical getProxyConfig snapshots required before applying ME map updates.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_d2c_ack_flush_immediate","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Flush client writer immediately after quick-ack write.","apply":{"watcher":"supported","reload":"supported","effect":"new_me_sessions_keep_existing_relay_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_d2c_flush_batch_max_bytes","value":{"type":"integer","minimum":4096,"maximum":2097152},"default_kind":"type_default","sensitivity":"public","description":"Maximum total payload bytes coalesced before flush.","unit":"bytes","apply":{"watcher":"supported","reload":"supported","effect":"new_me_sessions_keep_existing_relay_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_d2c_flush_batch_max_delay_us","value":{"type":"integer","minimum":0,"maximum":5000},"default_kind":"type_default","sensitivity":"public","description":"Maximum wait in microseconds to coalesce additional ME->Client responses. `0` disables timed coalescing.","unit":"microseconds","apply":{"watcher":"supported","reload":"supported","effect":"new_me_sessions_keep_existing_relay_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_d2c_flush_batch_max_frames","value":{"type":"integer","minimum":1,"maximum":512},"default_kind":"type_default","sensitivity":"public","description":"Maximum number of ME->Client responses coalesced before flush.","apply":{"watcher":"supported","reload":"supported","effect":"new_me_sessions_keep_existing_relay_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_d2c_frame_buf_shrink_threshold_bytes","value":{"type":"integer","minimum":4096,"maximum":16777216},"default_kind":"type_default","sensitivity":"public","description":"Shrink threshold for reusable ME->Client frame assembly buffer.","unit":"bytes","apply":{"watcher":"supported","reload":"supported","effect":"new_me_sessions_keep_existing_relay_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_deterministic_writer_sort","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Deterministic candidate sort for ME writer binding path.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_floor_mode","value":{"type":"string","enum":["static","adaptive"]},"default_kind":"type_default","sensitivity":"public","description":"Floor policy mode for ME writer targets.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_hardswap_warmup_delay_max_ms","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Maximum delay in ms between hardswap warmup connect attempts.","unit":"milliseconds","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_hardswap_warmup_delay_min_ms","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Minimum delay in ms between hardswap warmup connect attempts.","unit":"milliseconds","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_hardswap_warmup_extra_passes","value":{"type":"integer","minimum":0,"maximum":10},"default_kind":"type_default","sensitivity":"public","description":"Additional warmup passes in the same hardswap cycle after the base pass.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_hardswap_warmup_pass_backoff_base_ms","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Base backoff in ms between hardswap warmup passes when floor is still incomplete.","unit":"milliseconds","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_health_interval_ms_healthy","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Health monitor interval in milliseconds while writer coverage is stable.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_health_interval_ms_unhealthy","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Health monitor interval in milliseconds while writer coverage is degraded.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_init_retry_attempts","value":{"type":"integer","minimum":0,"maximum":1000000},"default_kind":"type_default","sensitivity":"public","description":"Startup retries for Middle-End pool initialization before ME→Direct fallback. 0 means unlimited retries.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_instadrain","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Force-remove any draining writer on the next cleanup tick, regardless of age/deadline.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_keepalive_enabled","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Enable ME keepalive padding frames.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_keepalive_interval_secs","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Keepalive interval in seconds.","unit":"seconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_keepalive_jitter_secs","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Keepalive jitter in seconds.","unit":"seconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_keepalive_payload_random","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Keepalive payload randomized (4 bytes); otherwise zeros.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_pool_drain_soft_evict_budget_per_core","value":{"type":"integer","minimum":1,"maximum":64},"default_kind":"type_default","sensitivity":"public","description":"Soft-eviction budget per CPU core for one health tick.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_pool_drain_soft_evict_cooldown_ms","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Cooldown for repetitive soft-eviction on the same writer in milliseconds.","unit":"milliseconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_pool_drain_soft_evict_enabled","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Enable staged client eviction for draining ME writers that remain non-empty past TTL.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_pool_drain_soft_evict_grace_secs","value":{"type":"integer","minimum":0,"maximum":3600},"default_kind":"type_default","sensitivity":"public","description":"Extra grace in seconds after drain TTL before soft-eviction stage starts.","unit":"seconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_pool_drain_soft_evict_per_writer","value":{"type":"integer","minimum":1,"maximum":16},"default_kind":"type_default","sensitivity":"public","description":"Maximum number of client sessions to evict from one draining writer per health tick.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_pool_drain_threshold","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Maximum allowed number of draining ME writers before oldest ones are force-closed in batches. Set to 0 to disable threshold-based draining cleanup and keep timeout-only behavior.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_pool_drain_ttl_secs","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Drain-TTL in seconds for stale ME writers after endpoint map changes. During TTL, stale writers may be used only as fallback for new bindings.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_pool_min_fresh_ratio","value":{"type":"number","minimum":0.0,"maximum":1.0},"default_kind":"type_default","sensitivity":"public","description":"Minimum desired-DC coverage ratio required before draining stale writers. Range: 0.0..=1.0.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_quota_soft_overshoot_bytes","value":{"type":"integer","minimum":0,"maximum":16777216},"default_kind":"type_default","sensitivity":"public","description":"Additional bytes above strict per-user quota allowed in hot-path soft mode.","unit":"bytes","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_reader_route_data_wait_ms","value":{"type":"integer","minimum":0,"maximum":20},"default_kind":"type_default","sensitivity":"public","description":"Bounded wait in milliseconds for routing ME DATA to per-connection queue. `0` keeps non-blocking routing; values >0 enable bounded wait for compatibility.","unit":"milliseconds","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_reconnect_backoff_base_ms","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Base backoff in ms for reconnect.","unit":"milliseconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_reconnect_backoff_cap_ms","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Cap backoff in ms for reconnect.","unit":"milliseconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_reconnect_fast_retry_count","value":{"type":"integer","minimum":0,"maximum":4294967295},"default_kind":"type_default","sensitivity":"public","description":"Fast retry attempts before backoff.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_reconnect_max_concurrent_per_dc","value":{"type":"integer","minimum":0,"maximum":4294967295},"default_kind":"type_default","sensitivity":"public","description":"Max concurrent reconnect attempts per DC.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_reinit_coalesce_window_ms","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Trigger coalescing window before starting a reinit cycle.","unit":"milliseconds","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_reinit_drain_timeout_secs","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Drain timeout in seconds for stale ME writers after endpoint map changes. Set to 0 to use the runtime safety fallback timeout.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_reinit_every_secs","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Periodic ME pool reinitialization interval in seconds.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_reinit_max_concurrency","value":{"type":"integer","minimum":1,"maximum":8},"default_kind":"type_default","sensitivity":"public","description":"Maximum concurrent ME reinit warmups when single-flight mode is disabled.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_reinit_singleflight","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Serialize ME reinit cycles across all trigger sources.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_reinit_trigger_channel","value":{"type":"integer","minimum":1,"maximum":4096},"default_kind":"type_default","sensitivity":"public","description":"Trigger queue capacity for reinit scheduler.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_route_backpressure_base_timeout_ms","value":{"type":"integer","minimum":1,"maximum":5000},"default_kind":"type_default","sensitivity":"public","description":"Base backpressure timeout in milliseconds for ME route channel send.","unit":"milliseconds","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_route_backpressure_enabled","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Enable route-level ME backpressure controls in reader fairness path.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_route_backpressure_high_timeout_ms","value":{"type":"integer","minimum":1,"maximum":5000},"default_kind":"type_default","sensitivity":"public","description":"High backpressure timeout in milliseconds when queue occupancy is above watermark.","unit":"milliseconds","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_route_backpressure_high_watermark_pct","value":{"type":"integer","minimum":1,"maximum":100},"default_kind":"type_default","sensitivity":"public","description":"Queue occupancy percent threshold for high backpressure timeout.","unit":"percent","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_route_blocking_send_timeout_ms","value":{"type":"integer","minimum":1,"maximum":5000},"default_kind":"type_default","sensitivity":"public","description":"Maximum wait in milliseconds for blocking ME writer channel send fallback. Must be within [1, 5000].","unit":"milliseconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_route_channel_capacity","value":{"type":"integer","minimum":1,"maximum":8192},"default_kind":"type_default","sensitivity":"public","description":"Capacity of per-connection ME response route channel.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_route_fairshare_enabled","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Enable worker-local fairshare scheduler for ME reader routing.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_route_hybrid_max_wait_ms","value":{"type":"integer","minimum":50,"maximum":60000},"default_kind":"type_default","sensitivity":"public","description":"Maximum cumulative wait in milliseconds for hybrid no-writer mode before failfast.","unit":"milliseconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_route_inline_recovery_attempts","value":{"type":"integer","minimum":1,"maximum":4294967295},"default_kind":"type_default","sensitivity":"public","description":"Number of inline recovery attempts in legacy mode.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_route_inline_recovery_wait_ms","value":{"type":"integer","minimum":10,"maximum":30000},"default_kind":"type_default","sensitivity":"public","description":"Maximum wait time in milliseconds for inline recovery in legacy mode.","unit":"milliseconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_route_no_writer_mode","value":{"type":"string","enum":["async_recovery_failfast","inline_recovery_legacy","hybrid_async_persistent"]},"default_kind":"type_default","sensitivity":"public","description":"ME route behavior when no writer is immediately available.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_route_no_writer_wait_ms","value":{"type":"integer","minimum":10,"maximum":5000},"default_kind":"type_default","sensitivity":"public","description":"Maximum wait time in milliseconds for async-recovery failfast mode.","unit":"milliseconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_secret_atomic_snapshot","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Keep key-selector and secret bytes from one snapshot during ME handshake.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_single_endpoint_outage_backoff_max_ms","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Maximum reconnect backoff in ms for single-endpoint outage mode.","unit":"milliseconds","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_single_endpoint_outage_backoff_min_ms","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Minimum reconnect backoff in ms for single-endpoint outage mode.","unit":"milliseconds","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_single_endpoint_outage_disable_quarantine","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Ignore endpoint quarantine while in single-endpoint outage mode.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_single_endpoint_outage_mode_enabled","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Enable aggressive outage recovery mode for single-endpoint DC groups.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_single_endpoint_shadow_rotate_every_secs","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Periodic shadow writer rotation interval in seconds for single-endpoint DC groups. Set to 0 to disable periodic shadow rotation.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_single_endpoint_shadow_writers","value":{"type":"integer","minimum":0,"maximum":32},"default_kind":"type_default","sensitivity":"public","description":"Number of additional reserve writers for DC groups with exactly one endpoint.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_snapshot_min_proxy_for_lines","value":{"type":"integer","minimum":1,"maximum":4294967295},"default_kind":"type_default","sensitivity":"public","description":"Minimum parsed `proxy_for` rows required to accept a snapshot.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_snapshot_reject_empty_map","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Reject empty getProxyConfig snapshots instead of marking them applied.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_snapshot_require_http_2xx","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Ensure getProxyConfig snapshots are applied only for 2xx HTTP responses.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_socks_kdf_policy","value":{"type":"string","enum":["strict","compat"]},"default_kind":"type_default","sensitivity":"public","description":"SOCKS-bound KDF policy for Middle-End handshake.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_warmup_stagger_enabled","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Enable staggered warmup of extra ME writers.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_warmup_step_delay_ms","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Base delay between warmup connections in ms.","unit":"milliseconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_warmup_step_jitter_ms","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Jitter for warmup delay in ms.","unit":"milliseconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_warn_rate_limit_ms","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Cooldown for repetitive ME warning logs in milliseconds.","unit":"milliseconds","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_writer_byte_budget_bytes","value":{"type":"integer","minimum":16384,"maximum":268435456,"multipleOf":16384},"default_kind":"type_default","sensitivity":"public","description":"Resident-memory budget in bytes for each ME writer data queue.","unit":"bytes","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy","general.max_client_frame"],"constraints":["Must be at least ceil((2 * general.max_client_frame + 256) / 16384) * 16384 bytes."]},
|
||||
{"path":"general.me_writer_cmd_channel_capacity","value":{"type":"integer","minimum":1,"maximum":16384},"default_kind":"type_default","sensitivity":"public","description":"Capacity of per-ME writer command channel.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_writer_pick_mode","value":{"type":"string","enum":["sorted_rr","p2c"]},"default_kind":"type_default","sensitivity":"public","description":"Writer selection mode for ME route bind path.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.me_writer_pick_sample_size","value":{"type":"integer","minimum":2,"maximum":4},"default_kind":"type_default","sensitivity":"public","description":"Number of candidates sampled by writer picker in `p2c` mode.","apply":{"watcher":"supported","reload":"supported","effect":"next_subsystem_policy_consumption_or_me_update"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.middle_proxy_nat_ip","value":{"type":"string","format":"ip-address"},"default_kind":"unset","sensitivity":"deployment","description":"Public IP override for middle-proxy NAT environments. When set, this IP is used in ME key derivation and local address translation.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.middle_proxy_nat_probe","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Enable STUN-based NAT probing to discover public IP:port for ME KDF.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.middle_proxy_nat_stun","value":{"type":"string"},"default_kind":"type_default","sensitivity":"public","description":"Deprecated legacy single STUN server for NAT probing. Use `network.stun_servers` instead.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.middle_proxy_nat_stun_servers","value":{"type":"array","items":{"type":"string"}},"default_kind":"type_default","sensitivity":"public","description":"Deprecated legacy STUN list for NAT probing fallback. Use `network.stun_servers` instead.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.middle_proxy_pool_size","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Desired size of active Middle-Proxy writer pool.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.middle_proxy_warm_standby","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Number of warm standby ME connections kept pre-initialized.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["general.use_middle_proxy"]},
|
||||
{"path":"general.modes","value":{"type":"object"},"default_kind":"nested_fields","sensitivity":"public","description":"Configuration value for general.modes.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.modes.classic","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for general.modes.classic.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.modes.secure","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for general.modes.secure.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.modes.tls","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for general.modes.tls.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.ntp_check","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Enable NTP drift check at startup.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.ntp_servers","value":{"type":"array","items":{"type":"string"}},"default_kind":"type_default","sensitivity":"public","description":"NTP servers for drift check.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.prefer_ipv6","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for general.prefer_ipv6.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.proxy_config_auto_reload_secs","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Deprecated legacy setting; kept for backward compatibility fallback. Use `update_every` instead.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"watcher_publication_then_subsystem_policy_consumption"}},
|
||||
{"path":"general.proxy_config_v4_cache_path","value":{"type":"string"},"default_kind":"type_default","sensitivity":"deployment","description":"Optional path to cache raw getProxyConfig (IPv4) snapshot for startup fallback.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.proxy_config_v4_url","value":{"type":"string"},"default_kind":"unset","sensitivity":"deployment","description":"Optional custom URL for getProxyConfig (https://core.telegram.org/getProxyConfig if absent).","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.proxy_config_v6_cache_path","value":{"type":"string"},"default_kind":"type_default","sensitivity":"deployment","description":"Optional path to cache raw getProxyConfigV6 snapshot for startup fallback.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.proxy_config_v6_url","value":{"type":"string"},"default_kind":"unset","sensitivity":"deployment","description":"Optional custom URL for getProxyConfigV6 (https://core.telegram.org/getProxyConfigV6 if absent).","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.proxy_secret_auto_reload_secs","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Deprecated legacy setting; kept for backward compatibility fallback. Use `update_every` instead.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"watcher_publication_then_subsystem_policy_consumption"}},
|
||||
{"path":"general.proxy_secret_len_max","value":{"type":"integer","minimum":32,"maximum":4096},"default_kind":"type_default","sensitivity":"public","description":"Maximum allowed proxy-secret length in bytes for startup and runtime refresh.","apply":{"watcher":"supported","reload":"supported","effect":"watcher_publication_then_subsystem_policy_consumption"}},
|
||||
{"path":"general.proxy_secret_path","value":{"type":"string"},"default_kind":"type_default","sensitivity":"deployment","description":"Path to proxy-secret binary file (auto-downloaded if absent). Infrastructure secret from https://core.telegram.org/getProxySecret.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.proxy_secret_rotate_runtime","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Enable runtime proxy-secret rotation from getProxySecret.","apply":{"watcher":"supported","reload":"supported","effect":"watcher_publication_then_subsystem_policy_consumption"}},
|
||||
{"path":"general.proxy_secret_stable_snapshots","value":{"type":"integer","minimum":1,"maximum":255},"default_kind":"type_default","sensitivity":"public","description":"Number of identical getProxySecret snapshots required before runtime secret rotation.","apply":{"watcher":"supported","reload":"supported","effect":"watcher_publication_then_subsystem_policy_consumption"}},
|
||||
{"path":"general.proxy_secret_url","value":{"type":"string"},"default_kind":"unset","sensitivity":"deployment","description":"Optional custom URL for infrastructure secret (https://core.telegram.org/getProxySecret if absent).","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.quota_state_path","value":{"type":"string"},"default_kind":"type_default","sensitivity":"deployment","description":"JSON state file for runtime per-user quota consumption.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"general.rpc_proxy_req_every","value":{"oneOf":[{"const":0},{"type":"integer","minimum":10,"maximum":300}]},"default_kind":"type_default","sensitivity":"public","description":"Interval in seconds for service RPC_PROXY_REQ activity signals to ME. 0 disables service activity signals.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.rst_on_close","value":{"type":"string","enum":["off","errors","always"]},"default_kind":"type_default","sensitivity":"public","description":"RST-on-close mode for accepted client sockets. `off` — normal FIN on all closes (default). `errors` — SO_LINGER(0) on accept, cleared after successful auth; pre-handshake failures send RST, relayed sessions close gracefully. `always` — SO_LINGER(0) on accept, never cleared; all closes send RST.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.stun_iface_mismatch_ignore","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Ignore STUN/interface IP mismatch (keep using Middle Proxy even if NAT detected).","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.stun_nat_probe_concurrency","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Maximum number of concurrent STUN probes during NAT detection.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.telemetry","value":{"type":"object"},"default_kind":"nested_fields","sensitivity":"public","description":"Runtime telemetry controls for counters/metrics in hot paths.","apply":{"watcher":"supported","reload":"supported","effect":"watcher_publication_then_subsystem_policy_consumption"}},
|
||||
{"path":"general.telemetry.core_enabled","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for general.telemetry.core_enabled.","apply":{"watcher":"supported","reload":"supported","effect":"watcher_publication_then_subsystem_policy_consumption"}},
|
||||
{"path":"general.telemetry.me_level","value":{"type":"string","enum":["normal","silent","debug"]},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for general.telemetry.me_level.","apply":{"watcher":"supported","reload":"supported","effect":"watcher_publication_then_subsystem_policy_consumption"}},
|
||||
{"path":"general.telemetry.user_enabled","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for general.telemetry.user_enabled.","apply":{"watcher":"supported","reload":"supported","effect":"watcher_publication_then_subsystem_policy_consumption"}},
|
||||
{"path":"general.tg_connect","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Per-attempt TCP connect timeout to Telegram DC (seconds).","unit":"seconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.unknown_dc_file_log_enabled","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"deployment","description":"Enable unknown-DC file logging.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.unknown_dc_log_path","value":{"type":"string"},"default_kind":"type_default","sensitivity":"deployment","description":"Log unknown (non-standard) DC requests to a file (default: unknown-dc.txt). Set to null to disable.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.update_every","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Unified ME updater interval in seconds for getProxyConfig/getProxyConfigV6/getProxySecret. When omitted, effective value falls back to legacy proxy_*_auto_reload_secs fields.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"watcher_publication_then_subsystem_policy_consumption"}},
|
||||
{"path":"general.upstream_connect_budget_ms","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Total wall-clock budget in milliseconds for one upstream connect request across retries.","unit":"milliseconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.upstream_connect_failfast_hard_errors","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Skip additional retries for hard non-transient upstream connect errors.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.upstream_connect_retry_attempts","value":{"type":"integer","minimum":1,"maximum":4294967295},"default_kind":"type_default","sensitivity":"public","description":"Connect attempts for the selected upstream before returning error/fallback.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.upstream_connect_retry_backoff_ms","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Delay in milliseconds between upstream connect attempts.","unit":"milliseconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.upstream_unhealthy_fail_threshold","value":{"type":"integer","minimum":1,"maximum":4294967295},"default_kind":"type_default","sensitivity":"public","description":"Consecutive failed requests before upstream is marked unhealthy.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"general.use_middle_proxy","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for general.use_middle_proxy.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"include","value":{"oneOf":[{"type":"string"},{"type":"array","items":{"type":"string"}}]},"default_kind":"unset","sensitivity":"public","description":"Source include path or list of paths; resolved before typed configuration.","apply":{"watcher":"conditional","reload":"conditional","effect":"depends_on_included_field_changes_and_source_ownership"}},
|
||||
{"path":"logging","value":{"type":"object"},"default_kind":"nested_fields","sensitivity":"public","description":"Runtime logging destination, rotation, and retention configuration.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"logging.destination","value":{"type":"string","enum":["stderr","syslog","file"]},"default_kind":"type_default","sensitivity":"public","description":"Effective logging destination.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"logging.max_age_secs","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Maximum age for rotated log files in seconds. `0` disables age retention.","unit":"seconds","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"logging.max_files","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"deployment","description":"Maximum number of matching log files to keep. `0` disables count retention.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"logging.max_size_bytes","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Maximum active log file size before rotating. `0` disables size rotation.","unit":"bytes","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"logging.path","value":{"type":"string"},"default_kind":"unset","sensitivity":"public","description":"File path used when `destination = \"file\"`.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"logging.rotation","value":{"type":"string","enum":["never","minutely","hourly","daily","weekly"]},"default_kind":"type_default","sensitivity":"public","description":"Time rotation interval for file logs.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"network","value":{"type":"object"},"default_kind":"nested_fields","sensitivity":"public","description":"Network binding, routing, and socket-level configuration.","apply":{"watcher":"mixed","reload":"mixed","effect":"see_child_fields"}},
|
||||
{"path":"network.cache_public_ip_path","value":{"type":"string"},"default_kind":"type_default","sensitivity":"deployment","description":"Cache file path for detected public IP.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"network.dns_overrides","value":{"type":"array","items":{"type":"string"},"maxItems":4096},"default_kind":"type_default","sensitivity":"public","description":"Runtime DNS overrides in `host:port:ip` format. IPv6 IP values must be bracketed: `[2001:db8::1]`.","apply":{"watcher":"supported","reload":"supported","effect":"future_resolutions_existing_connections_unchanged"}},
|
||||
{"path":"network.http_ip_detect_urls","value":{"type":"array","items":{"type":"string"}},"default_kind":"type_default","sensitivity":"deployment","description":"HTTP-based public IP detection endpoints (fallback after STUN).","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"network.ipv4","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for network.ipv4.","apply":{"watcher":"unsupported","reload":"conditional","effect":"listener_identity_and_bind_policy_dependent"}},
|
||||
{"path":"network.ipv6","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"None = auto-detect IPv6 availability.","apply":{"watcher":"unsupported","reload":"conditional","effect":"listener_identity_and_bind_policy_dependent"}},
|
||||
{"path":"network.multipath","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for network.multipath.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"network.prefer","value":{"type":"integer","minimum":0,"maximum":255,"enum":[4,6]},"default_kind":"type_default","sensitivity":"public","description":"4 or 6.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"constraints":["Loader may normalize the preference when a family is explicitly disabled."]},
|
||||
{"path":"network.stun_servers","value":{"type":"array","items":{"type":"string"}},"default_kind":"type_default","sensitivity":"public","description":"STUN servers list for public IP discovery.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"network.stun_tcp_fallback","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Enable TCP STUN fallback when UDP is blocked.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"network.stun_use","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Global switch for STUN probing. When false, STUN is fully disabled and only non-STUN detection remains.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"server","value":{"type":"object"},"default_kind":"nested_fields","sensitivity":"public","description":"Server-side listener, fallback, and API configuration.","apply":{"watcher":"mixed","reload":"mixed","effect":"see_child_fields"}},
|
||||
{"path":"server.accept_permit_timeout_ms","value":{"type":"integer","minimum":0,"maximum":60000},"default_kind":"type_default","sensitivity":"public","description":"Maximum wait in milliseconds while acquiring a connection slot permit. `0` keeps legacy unbounded wait behavior.","unit":"milliseconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"server.api","value":{"type":"object"},"default_kind":"nested_fields","sensitivity":"public","description":"Configuration value for server.api.","aliases":["server.admin_api"],"apply":{"watcher":"mixed","reload":"mixed","effect":"see_child_fields"}},
|
||||
{"path":"server.api.auth_header","value":{"type":"string"},"default_kind":"redacted","sensitivity":"credential","description":"Optional static value for `Authorization` header validation. Empty string disables header auth.","aliases":["server.admin_api.auth_header"],"apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"server.api.enabled","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Enable or disable REST API.","aliases":["server.admin_api.enabled"],"apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"server.api.gray_action","value":{"type":"string","enum":["api","200","drop"]},"default_kind":"type_default","sensitivity":"public","description":"Behavior for requests from source IPs outside `whitelist`. - `api`: return structured API forbidden response. - `200`: return `200 OK` with an empty body. - `drop`: close the connection without HTTP response.","aliases":["server.admin_api.gray_action"],"apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"server.api.listen","value":{"type":"string"},"default_kind":"type_default","sensitivity":"public","description":"Listen address for API in `IP:PORT` format.","aliases":["server.admin_api.listen"],"apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"server.api.minimal_runtime_cache_ttl_ms","value":{"type":"integer","minimum":0,"maximum":60000},"default_kind":"type_default","sensitivity":"public","description":"Cache TTL for minimal runtime snapshots in milliseconds (0 disables caching).","aliases":["server.admin_api.minimal_runtime_cache_ttl_ms"],"unit":"milliseconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"server.api.minimal_runtime_enabled","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Enable runtime snapshots that require read-lock aggregation on API request path.","aliases":["server.admin_api.minimal_runtime_enabled"],"apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"server.api.read_only","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Read-only mode: mutating endpoints are rejected.","aliases":["server.admin_api.read_only"],"apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"server.api.request_body_limit_bytes","value":{"type":"integer","minimum":1,"maximum":1048576},"default_kind":"type_default","sensitivity":"public","description":"Maximum accepted HTTP request body size in bytes.","aliases":["server.admin_api.request_body_limit_bytes"],"unit":"bytes","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"server.api.runtime_edge_cache_ttl_ms","value":{"type":"integer","minimum":0,"maximum":60000},"default_kind":"type_default","sensitivity":"public","description":"Cache TTL for runtime edge aggregation payloads in milliseconds.","aliases":["server.admin_api.runtime_edge_cache_ttl_ms"],"unit":"milliseconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"server.api.runtime_edge_enabled","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Enables runtime edge endpoints with optional cached aggregation.","aliases":["server.admin_api.runtime_edge_enabled"],"apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"server.api.runtime_edge_events_capacity","value":{"type":"integer","minimum":16,"maximum":4096},"default_kind":"type_default","sensitivity":"public","description":"Ring-buffer capacity for runtime edge control-plane events.","aliases":["server.admin_api.runtime_edge_events_capacity"],"apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"server.api.runtime_edge_top_n","value":{"type":"integer","minimum":1,"maximum":1000},"default_kind":"type_default","sensitivity":"public","description":"Top-N limit for edge connection leaderboard payloads.","aliases":["server.admin_api.runtime_edge_top_n"],"apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"server.api.whitelist","value":{"type":"array","items":{"type":"string","format":"cidr"}},"default_kind":"type_default","sensitivity":"public","description":"CIDR whitelist allowed to access API.","aliases":["server.admin_api.whitelist"],"apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"server.client_mss","value":{"type":"string"},"default_kind":"unset","sensitivity":"public","description":"Client-facing TCP MSS preset or custom value for all TCP listeners. Empty string or omitted value keeps the kernel default.","apply":{"watcher":"unsupported","reload":"conditional","effect":"listener_identity_and_bind_policy_dependent"}},
|
||||
{"path":"server.client_mss_bulk","value":{"type":"string"},"default_kind":"unset","sensitivity":"public","description":"Experimental Linux-only bulk MSS used with best-effort userspace chunking of the authenticated FakeTLS response. TCP offloads, loss, and retransmission may coalesce write boundaries. Empty or omitted keeps `client_mss` connection-wide. Uses the same preset/integer grammar as `client_mss`.","apply":{"watcher":"unsupported","reload":"conditional","effect":"listener_identity_and_bind_policy_dependent"}},
|
||||
{"path":"server.conntrack_control","value":{"type":"object"},"default_kind":"nested_fields","sensitivity":"public","description":"Runtime conntrack control and pressure policy.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"server.conntrack_control.backend","value":{"type":"string","enum":["auto","nftables","iptables"]},"default_kind":"type_default","sensitivity":"public","description":"Netfilter backend used to reconcile notrack rules.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"server.conntrack_control.delete_budget_per_sec","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Maximum conntrack delete operations per second.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"server.conntrack_control.hybrid_listener_ips","value":{"type":"array","items":{"type":"string","format":"ip-address"}},"default_kind":"type_default","sensitivity":"public","description":"Listener IP allow-list for hybrid mode. Ignored in tracked/notrack mode.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"server.conntrack_control.inline_conntrack_control","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Enables runtime conntrack-control worker for pressure mitigation.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"server.conntrack_control.mode","value":{"type":"string","enum":["tracked","notrack","hybrid"]},"default_kind":"type_default","sensitivity":"public","description":"Conntrack mode for listener ingress traffic.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"server.conntrack_control.pressure_high_watermark_pct","value":{"type":"integer","minimum":1,"maximum":100},"default_kind":"type_default","sensitivity":"public","description":"Pressure high watermark as percentage.","unit":"percent","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"server.conntrack_control.pressure_low_watermark_pct","value":{"type":"integer","minimum":0,"maximum":255},"default_kind":"type_default","sensitivity":"public","description":"Pressure low watermark as percentage.","unit":"percent","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"server.conntrack_control.profile","value":{"type":"string","enum":["conservative","balanced","aggressive"]},"default_kind":"type_default","sensitivity":"public","description":"Pressure profile for timeout caps under resource saturation.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"server.listen_addr_ipv4","value":{"type":"string"},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for server.listen_addr_ipv4.","apply":{"watcher":"unsupported","reload":"conditional","effect":"listener_identity_and_bind_policy_dependent"}},
|
||||
{"path":"server.listen_addr_ipv6","value":{"type":"string"},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for server.listen_addr_ipv6.","apply":{"watcher":"unsupported","reload":"conditional","effect":"listener_identity_and_bind_policy_dependent"}},
|
||||
{"path":"server.listen_backlog","value":{"type":"integer","minimum":0,"maximum":2147483647},"default_kind":"type_default","sensitivity":"public","description":"TCP `listen(2)` backlog for client-facing sockets (also used for the metrics HTTP listener). The effective queue is capped by the kernel (for example `somaxconn` on Linux).","apply":{"watcher":"unsupported","reload":"conditional","effect":"listener_identity_and_bind_policy_dependent"}},
|
||||
{"path":"server.listen_tcp","value":{"type":"boolean"},"default_kind":"unset","sensitivity":"public","description":"Enable TCP listening. Default: true when no unix socket, false when listen_unix_sock is set. Set explicitly to override auto-detection.","apply":{"watcher":"unsupported","reload":"conditional","effect":"listener_identity_and_bind_policy_dependent"}},
|
||||
{"path":"server.listen_unix_sock","value":{"type":"string"},"default_kind":"unset","sensitivity":"public","description":"Configuration value for server.listen_unix_sock.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"server.listen_unix_sock_perm","value":{"type":"string"},"default_kind":"unset","sensitivity":"public","description":"Unix socket file permissions (octal, e.g. \"0666\" or \"0777\"). Applied via chmod after bind. Default: no change (inherits umask).","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"server.listeners","value":{"type":"array","items":{"type":"object"}},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for server.listeners.","apply":{"watcher":"unsupported","reload":"conditional","effect":"listener_identity_and_bind_policy_dependent"}},
|
||||
{"path":"server.listeners[].announce","value":{"type":"string"},"default_kind":"unset","sensitivity":"public","description":"IP address or hostname to announce in proxy links. Takes precedence over `announce_ip` if both are set.","apply":{"watcher":"unsupported","reload":"conditional","effect":"listener_identity_and_bind_policy_dependent"}},
|
||||
{"path":"server.listeners[].announce_ip","value":{"type":"string","format":"ip-address"},"default_kind":"unset","sensitivity":"public","description":"Deprecated: Use `announce` instead. IP address to announce in proxy links. Migrated to `announce` automatically if `announce` is not set.","apply":{"watcher":"unsupported","reload":"conditional","effect":"listener_identity_and_bind_policy_dependent"}},
|
||||
{"path":"server.listeners[].client_mss","value":{"type":"string"},"default_kind":"unset","sensitivity":"public","description":"Per-listener client-facing TCP MSS preset or custom value. Empty string disables MSS shaping for this listener.","apply":{"watcher":"unsupported","reload":"conditional","effect":"listener_identity_and_bind_policy_dependent"}},
|
||||
{"path":"server.listeners[].ip","value":{"type":"string","format":"ip-address"},"default_kind":"required","sensitivity":"public","description":"Configuration value for server.listeners[].ip.","apply":{"watcher":"unsupported","reload":"conditional","effect":"listener_identity_and_bind_policy_dependent"}},
|
||||
{"path":"server.listeners[].port","value":{"type":"integer","minimum":0,"maximum":65535},"default_kind":"unset","sensitivity":"public","description":"Per-listener TCP port. If omitted, falls back to legacy `server.port`.","apply":{"watcher":"unsupported","reload":"conditional","effect":"listener_identity_and_bind_policy_dependent"}},
|
||||
{"path":"server.listeners[].proxy_protocol","value":{"type":"boolean"},"default_kind":"unset","sensitivity":"public","description":"Per-listener PROXY protocol override. When set, overrides global server.proxy_protocol.","apply":{"watcher":"unsupported","reload":"conditional","effect":"listener_identity_and_bind_policy_dependent"}},
|
||||
{"path":"server.listeners[].reuse_allow","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Allow multiple telemt instances to listen on the same IP:port (SO_REUSEPORT). Default is false for safety.","apply":{"watcher":"unsupported","reload":"conditional","effect":"listener_identity_and_bind_policy_dependent"}},
|
||||
{"path":"server.listeners[].synlimit","value":{"oneOf":[{"const":false},{"type":"string","enum":["iptables","nftables","pf","false","off","disabled","none"]}]},"default_kind":"type_default","sensitivity":"public","description":"Per-listener SYN limiter mode.","apply":{"watcher":"unsupported","reload":"conditional","effect":"listener_identity_and_bind_policy_dependent"},"constraints":["String tokens are trimmed and ASCII-case-insensitive; disabled aliases serialize as false. Boolean true is rejected."]},
|
||||
{"path":"server.listeners[].synlimit_burst","value":{"type":"integer","minimum":1,"maximum":4294967295},"default_kind":"type_default","sensitivity":"public","description":"Generic SYN-fix token-bucket burst size.","apply":{"watcher":"unsupported","reload":"conditional","effect":"listener_identity_and_bind_policy_dependent"}},
|
||||
{"path":"server.listeners[].synlimit_hashlimit_expire_ms","value":{"type":"integer","minimum":1,"maximum":4294967295},"default_kind":"type_default","sensitivity":"public","description":"Hashlimit entry expiration in milliseconds for iptables/ip6tables rules.","unit":"milliseconds","apply":{"watcher":"unsupported","reload":"conditional","effect":"listener_identity_and_bind_policy_dependent"}},
|
||||
{"path":"server.listeners[].synlimit_hashlimit_size","value":{"type":"integer","minimum":1,"maximum":4294967295},"default_kind":"type_default","sensitivity":"public","description":"Hashlimit table size for iptables/ip6tables rules.","apply":{"watcher":"unsupported","reload":"conditional","effect":"listener_identity_and_bind_policy_dependent"}},
|
||||
{"path":"server.listeners[].synlimit_hitcount","value":{"type":"integer","minimum":1,"maximum":4294967295},"default_kind":"type_default","sensitivity":"public","description":"Generic SYN-fix token-bucket rate amount.","apply":{"watcher":"unsupported","reload":"conditional","effect":"listener_identity_and_bind_policy_dependent"}},
|
||||
{"path":"server.listeners[].synlimit_ios_burst","value":{"type":"integer","minimum":1,"maximum":4294967295},"default_kind":"type_default","sensitivity":"public","description":"iOS-like SYN-fix token-bucket burst size.","apply":{"watcher":"unsupported","reload":"conditional","effect":"listener_identity_and_bind_policy_dependent"}},
|
||||
{"path":"server.listeners[].synlimit_ios_hitcount","value":{"type":"integer","minimum":1,"maximum":4294967295},"default_kind":"type_default","sensitivity":"public","description":"iOS-like SYN-fix token-bucket rate amount.","apply":{"watcher":"unsupported","reload":"conditional","effect":"listener_identity_and_bind_policy_dependent"}},
|
||||
{"path":"server.listeners[].synlimit_ios_seconds","value":{"type":"integer","minimum":1,"maximum":4294967295},"default_kind":"type_default","sensitivity":"public","description":"iOS-like SYN-fix token-bucket rate interval.","unit":"seconds","apply":{"watcher":"unsupported","reload":"conditional","effect":"listener_identity_and_bind_policy_dependent"}},
|
||||
{"path":"server.listeners[].synlimit_seconds","value":{"type":"integer","minimum":1,"maximum":4294967295},"default_kind":"type_default","sensitivity":"public","description":"Generic SYN-fix token-bucket rate interval.","unit":"seconds","apply":{"watcher":"unsupported","reload":"conditional","effect":"listener_identity_and_bind_policy_dependent"}},
|
||||
{"path":"server.listeners[].transport","value":{"type":"string","enum":["mtproxy","web"]},"default_kind":"type_default","sensitivity":"public","description":"Application protocol accepted by this listener.","apply":{"watcher":"unsupported","reload":"conditional","effect":"listener_identity_and_bind_policy_dependent"}},
|
||||
{"path":"server.listeners[].web_client_ip_source","value":{"type":"string","enum":["x_forwarded_for"]},"default_kind":"type_default","sensitivity":"public","description":"L7 header policy used only by WEB listeners.","apply":{"watcher":"unsupported","reload":"conditional","effect":"listener_identity_and_bind_policy_dependent"}},
|
||||
{"path":"server.listeners[].web_trusted_proxy_cidrs","value":{"type":"array","items":{"type":"string","format":"cidr"}},"default_kind":"type_default","sensitivity":"public","description":"Immediate socket peers allowed to provide the WEB client identity header.","apply":{"watcher":"unsupported","reload":"conditional","effect":"listener_identity_and_bind_policy_dependent"}},
|
||||
{"path":"server.max_connections","value":{"type":"integer","minimum":0,"maximum":4294967295},"default_kind":"type_default","sensitivity":"public","description":"Maximum number of concurrent client connections. 0 means unlimited.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"server.metrics_listen","value":{"type":"string"},"default_kind":"unset","sensitivity":"public","description":"Listen address for metrics in `IP:PORT` format (e.g. `\"127.0.0.1:9090\"`). When set, takes precedence over `metrics_port` and binds on the specified address only. Docker port publishing requires an explicit container-reachable listen address.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"server.metrics_port","value":{"type":"integer","minimum":0,"maximum":65535},"default_kind":"unset","sensitivity":"public","description":"Port for the Prometheus-compatible metrics endpoint. Enables metrics when set; binds on IPv4 and IPv6 loopback by default.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"server.metrics_whitelist","value":{"type":"array","items":{"type":"string","format":"cidr"}},"default_kind":"type_default","sensitivity":"public","description":"CIDR whitelist for the metrics endpoint.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"server.port","value":{"type":"integer","minimum":0,"maximum":65535},"default_kind":"type_default","sensitivity":"public","description":"Legacy listener port used for backward compatibility. For new configs prefer `[[server.listeners]].port`.","apply":{"watcher":"unsupported","reload":"conditional","effect":"listener_identity_and_bind_policy_dependent"}},
|
||||
{"path":"server.proxy_protocol","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Accept HAProxy PROXY protocol headers on incoming connections. When enabled, real client IPs are extracted from PROXY v1/v2 headers.","apply":{"watcher":"unsupported","reload":"conditional","effect":"listener_identity_and_bind_policy_dependent"}},
|
||||
{"path":"server.proxy_protocol_header_timeout_ms","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Timeout in milliseconds for reading and parsing PROXY protocol headers.","unit":"milliseconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"server.proxy_protocol_trusted_cidrs","value":{"type":"array","items":{"type":"string","format":"cidr"}},"default_kind":"type_default","sensitivity":"public","description":"Trusted source CIDRs allowed to send incoming PROXY protocol headers. If this field is omitted in config, it defaults to trust-all CIDRs (`0.0.0.0/0` and `::/0`). If it is explicitly set to an empty list, all PROXY protocol headers are rejected.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"show_link","value":{"oneOf":[{"const":"*"},{"type":"array","items":{"type":"string"}}]},"default_kind":"type_default","sensitivity":"public","description":"Optional proxy link rendering controls.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"timeouts","value":{"type":"object"},"default_kind":"nested_fields","sensitivity":"public","description":"Timeout values used by client, fallback, and upstream operations.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"timeouts.client_ack","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for timeouts.client_ack.","unit":"seconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"timeouts.client_first_byte_idle_secs","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Maximum idle wait in seconds for the first client byte before handshake parsing starts. `0` disables the separate idle phase and keeps legacy timeout behavior.","unit":"seconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"timeouts.client_handshake","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Maximum active handshake duration in seconds after the first client byte is received.","unit":"seconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"timeouts.client_keepalive","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for timeouts.client_keepalive.","unit":"seconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"timeouts.me_one_retry","value":{"type":"integer","minimum":0,"maximum":255},"default_kind":"type_default","sensitivity":"public","description":"Number of quick ME reconnect attempts for single-address DC.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"timeouts.me_one_timeout_ms","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Timeout per quick attempt in milliseconds for single-address DC.","unit":"milliseconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"timeouts.relay_client_idle_hard_secs","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Hard idle threshold for middle-relay client uplink activity in seconds. Hitting this threshold closes the session.","unit":"seconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"timeouts.relay_client_idle_soft_secs","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Soft idle threshold for middle-relay client uplink activity in seconds. Hitting this threshold marks the session as idle-candidate, but does not close it.","unit":"seconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"timeouts.relay_idle_grace_after_downstream_activity_secs","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Additional grace in seconds added to hard idle window after recent downstream activity.","unit":"seconds","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"timeouts.relay_idle_policy_v2_enabled","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Enables soft/hard relay client idle policy for middle-relay sessions.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"upstreams","value":{"type":"array","items":{"type":"object"}},"default_kind":"type_default","sensitivity":"public","description":"Telegram upstream endpoint configuration.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"upstreams[].address","value":{"type":"string"},"default_kind":"required","sensitivity":"deployment","description":"Configuration value for upstreams[].address.","constraints":["Applies when upstreams[].type is socks4, socks5."],"apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["upstreams[].type"]},
|
||||
{"path":"upstreams[].bind_addresses","value":{"type":"array","items":{"type":"string"}},"default_kind":"unset","sensitivity":"deployment","description":"Configuration value for upstreams[].bind_addresses.","constraints":["Applies when upstreams[].type is direct."],"apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["upstreams[].type"]},
|
||||
{"path":"upstreams[].bindtodevice","value":{"type":"string"},"default_kind":"unset","sensitivity":"public","description":"Configuration value for upstreams[].bindtodevice.","aliases":["upstreams[].force_bind"],"constraints":["Applies when upstreams[].type is direct."],"apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["upstreams[].type"]},
|
||||
{"path":"upstreams[].enabled","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for upstreams[].enabled.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"upstreams[].interface","value":{"type":"string"},"default_kind":"unset","sensitivity":"public","description":"Configuration value for upstreams[].interface.","constraints":["Applies when upstreams[].type is direct, socks4, socks5, shadowsocks."],"apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["upstreams[].type"]},
|
||||
{"path":"upstreams[].ipv4","value":{"type":"boolean"},"default_kind":"unset","sensitivity":"public","description":"Allow IPv4 DC targets for this upstream. `None` means auto-detect from runtime connectivity state.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"upstreams[].ipv6","value":{"type":"boolean"},"default_kind":"unset","sensitivity":"public","description":"Allow IPv6 DC targets for this upstream. `None` means auto-detect from runtime connectivity state.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"upstreams[].password","value":{"type":"string"},"default_kind":"redacted","sensitivity":"credential","description":"Configuration value for upstreams[].password.","constraints":["Applies when upstreams[].type is socks5."],"apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["upstreams[].type"]},
|
||||
{"path":"upstreams[].prefer","value":{"type":"integer","minimum":0,"maximum":255,"enum":[4,6]},"default_kind":"unset","sensitivity":"public","description":"Per-upstream IP family preference for Telegram DC targets. `None` inherits the effective global `[network].prefer` decision.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"upstreams[].scopes","value":{"type":"string"},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for upstreams[].scopes.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"upstreams[].type","value":{"type":"string","enum":["direct","socks4","socks5","shadowsocks"]},"default_kind":"required","sensitivity":"public","description":"Configuration value for upstreams[].type.","constraints":["Selected by the enclosing upstream type."],"apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"upstreams[].url","value":{"type":"string"},"default_kind":"redacted","sensitivity":"credential","description":"Configuration value for upstreams[].url.","constraints":["Applies when upstreams[].type is shadowsocks."],"apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["upstreams[].type"]},
|
||||
{"path":"upstreams[].user_id","value":{"type":"string"},"default_kind":"redacted","sensitivity":"credential","description":"Configuration value for upstreams[].user_id.","constraints":["Applies when upstreams[].type is socks4."],"apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["upstreams[].type"]},
|
||||
{"path":"upstreams[].username","value":{"type":"string"},"default_kind":"redacted","sensitivity":"credential","description":"Configuration value for upstreams[].username.","constraints":["Applies when upstreams[].type is socks5."],"apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"},"dependencies":["upstreams[].type"]},
|
||||
{"path":"upstreams[].weight","value":{"type":"integer","minimum":0,"maximum":65535},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for upstreams[].weight.","apply":{"watcher":"unsupported","reload":"supported","effect":"new_generation_with_instant_or_drain_session_policy"}},
|
||||
{"path":"web","value":{"type":"object"},"default_kind":"nested_fields","sensitivity":"public","description":"WEB carrier ingress and public-site fallback configuration.","apply":{"watcher":"mixed","reload":"mixed","effect":"see_child_fields"}},
|
||||
{"path":"web.allow_wildcard_hosts","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Restart-only opt-in to automatic suffix and catch-all hostname selectors.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.carrier","value":{"type":"string","enum":["https","https-lanes","websocket","websocket-lanes"]},"default_kind":"type_default","sensitivity":"public","description":"Sole carrier when negotiation is disabled and final fallback when enabled.","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.carrier_learning","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Enables bounded process-local carrier learning for automatic sessions.","apply":{"watcher":"conditional","reload":"conditional","effect":"requires_compatible_active_process_limits"},"dependencies":["web.carrier","web.limits.max_carrier_learning_entries"]},
|
||||
{"path":"web.carrier_method","value":{"type":"string","enum":["post","put"]},"default_kind":"type_default","sensitivity":"public","description":"Page-owned HTTP method for HTTPS uplink and downlink, including retries.","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.carrier_negotiation_aggressiveness","value":{"type":"string","enum":["conservative","balanced","aggressive"]},"default_kind":"type_default","sensitivity":"public","description":"Controls the evidence thresholds used by automatic carrier ranking.","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.carriers","value":{"oneOf":[{"const":false},{"type":"array","items":{"type":"string","enum":["https","https-lanes","websocket","websocket-lanes"]},"minItems":1,"maxItems":4,"uniqueItems":true}]},"default_kind":"type_default","sensitivity":"public","description":"Ordered carriers considered by server-side negotiation before the fallback carrier.","apply":{"watcher":"conditional","reload":"conditional","effect":"requires_compatible_active_process_limits"},"dependencies":["web.carrier","web.limits.max_carrier_learning_entries"]},
|
||||
{"path":"web.conveyor","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Enables negotiated bounded HTTP uplink pipelining for new WEB sessions.","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.debug","value":{"type":"object"},"default_kind":"nested_fields","sensitivity":"public","description":"Hot-reloadable bounded server-side debug policy.","apply":{"watcher":"conditional","reload":"conditional","effect":"requires_compatible_active_process_limits"}},
|
||||
{"path":"web.debug.body_capture","value":{"type":"string","enum":["off","metadata","prefix","full"]},"default_kind":"type_default","sensitivity":"public","description":"Controls request and response body byte retention.","apply":{"watcher":"conditional","reload":"conditional","effect":"requires_compatible_active_process_limits"},"dependencies":["web.debug.enabled","web.limits"]},
|
||||
{"path":"web.debug.body_prefix_bytes","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Maximum retained body prefix for recognized WEB requests.","unit":"bytes","apply":{"watcher":"conditional","reload":"conditional","effect":"requires_compatible_active_process_limits"},"dependencies":["web.debug.enabled","web.limits"]},
|
||||
{"path":"web.debug.capture_frames","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Parses carrier bodies into bounded frame metadata.","apply":{"watcher":"conditional","reload":"conditional","effect":"requires_compatible_active_process_limits"},"dependencies":["web.debug.enabled","web.limits"]},
|
||||
{"path":"web.debug.capture_headers","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Retains allowlisted header values and names of all other headers.","apply":{"watcher":"conditional","reload":"conditional","effect":"requires_compatible_active_process_limits"},"dependencies":["web.debug.enabled","web.limits"]},
|
||||
{"path":"web.debug.capture_lifecycle","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Records typed bridge, session, stream, handshake, and relay events.","apply":{"watcher":"conditional","reload":"conditional","effect":"requires_compatible_active_process_limits"},"dependencies":["web.debug.enabled","web.limits"]},
|
||||
{"path":"web.debug.capture_timings","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Retains request service and body-consumption timing points.","apply":{"watcher":"conditional","reload":"conditional","effect":"requires_compatible_active_process_limits"},"dependencies":["web.debug.enabled","web.limits"]},
|
||||
{"path":"web.debug.decoy_body_prefix_bytes","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Maximum retained body prefix for ordinary decoy traffic.","unit":"bytes","apply":{"watcher":"conditional","reload":"conditional","effect":"requires_compatible_active_process_limits"},"dependencies":["web.debug.enabled","web.limits"]},
|
||||
{"path":"web.debug.default_window_secs","value":{"type":"integer","minimum":1,"maximum":86400},"default_kind":"type_default","sensitivity":"public","description":"Default observation window presented by the status page.","unit":"seconds","apply":{"watcher":"conditional","reload":"conditional","effect":"requires_compatible_active_process_limits"},"dependencies":["web.debug.enabled","web.limits"]},
|
||||
{"path":"web.debug.enabled","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Enables process-owned WEB debug collection.","apply":{"watcher":"conditional","reload":"conditional","effect":"requires_compatible_active_process_limits"},"dependencies":["web.debug.enabled","web.limits"]},
|
||||
{"path":"web.debug.max_window_secs","value":{"type":"integer","minimum":1,"maximum":86400},"default_kind":"type_default","sensitivity":"public","description":"Largest observation window accepted by the status page.","unit":"seconds","apply":{"watcher":"conditional","reload":"conditional","effect":"requires_compatible_active_process_limits"},"dependencies":["web.debug.enabled","web.limits"]},
|
||||
{"path":"web.debug.sideband","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Enables generated-bridge diagnostic reports over the HTTPS sideband.","apply":{"watcher":"conditional","reload":"conditional","effect":"requires_compatible_active_process_limits"},"dependencies":["web.debug.enabled","web.limits","web.debug.capture_lifecycle"]},
|
||||
{"path":"web.decoy_fasttrack_mode","value":{"type":"string","enum":["off","shadow","enforce"]},"default_kind":"type_default","sensitivity":"public","description":"Restart-only capability-scan policy for structurally impossible bridge requests.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.enabled","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Enables issuance of new WEB bridge and session credentials.","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"},"dependencies":["server.listeners","network.ipv4","network.ipv6"],"constraints":["Requires a network-eligible WEB listener and nonempty valid profiles; false stops new issuance without implicitly closing live sessions."]},
|
||||
{"path":"web.http_connection_capacity_action","value":{"type":"string","enum":["drop","wait","respond"]},"default_kind":"type_default","sensitivity":"public","description":"Action applied when accepted HTTP connection capacity is exhausted.","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.limits","value":{"type":"object"},"default_kind":"nested_fields","sensitivity":"public","description":"Hard process and protocol limits.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.carrier_batch_bytes","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Maximum encoded downlink batch returned by one poll.","unit":"bytes","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.control_bytes_global","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Process-wide byte reserve available only to control frames.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"},"unit":"bytes"},
|
||||
{"path":"web.limits.control_bytes_per_session","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Per-session byte reserve available only to control frames.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"},"unit":"bytes"},
|
||||
{"path":"web.limits.debug_bytes_global","value":{"type":"integer","minimum":4096,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Process-wide retained and in-flight WEB debug byte ceiling.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"},"unit":"bytes"},
|
||||
{"path":"web.limits.debug_records_capacity","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Maximum retained WEB debug record count.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.max_body_bytes","value":{"type":"integer","minimum":8,"maximum":16777216},"default_kind":"type_default","sensitivity":"public","description":"Maximum collected carrier request body size.","unit":"bytes","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.max_body_bytes_global","value":{"type":"integer","minimum":1,"maximum":4294967295},"default_kind":"type_default","sensitivity":"public","description":"Process-wide byte reservation for collected request bodies.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"},"unit":"bytes"},
|
||||
{"path":"web.limits.max_body_readers","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Process-wide concurrently collected request body ceiling.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.max_bootstraps_global","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Process-wide live bootstrap credential ceiling.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.max_bootstraps_per_ip","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Live bootstrap credential ceiling for one forwarded client address.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.max_carrier_learning_entries","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Process-wide bounded carrier-learning evidence entry ceiling.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.max_frame_payload_bytes","value":{"type":"integer","minimum":1,"maximum":1048576},"default_kind":"type_default","sensitivity":"public","description":"Maximum payload carried by one WEB frame.","unit":"bytes","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.max_frames_per_body","value":{"type":"integer","minimum":1,"maximum":4096},"default_kind":"type_default","sensitivity":"public","description":"Maximum frame count parsed or emitted in one carrier body.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.max_header_bytes","value":{"type":"integer","minimum":8192,"maximum":65536},"default_kind":"type_default","sensitivity":"public","description":"Maximum bytes accepted while parsing one HTTP request head.","unit":"bytes","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.max_http_connections","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Process-wide accepted WEB HTTP connection ceiling.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.max_http_handlers","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Process-wide concurrently executing HTTP handler ceiling.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.max_http_overload_connections","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Accepted overload sockets allowed to wait or emit a retryable response.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.max_lane_open_waits_per_session","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Per-session ceiling for downlink polls waiting for a lane OPEN.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.max_profiles","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Maximum exact bindings plus one shared profile set per wildcard group.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.max_sessions_global","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Process-wide live WEB session ceiling.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.max_sessions_per_ip","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Live WEB session ceiling for one forwarded client address.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.max_static_bytes","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Maximum static snapshot bytes, charged once per source group.","unit":"bytes","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.max_static_file_bytes","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"deployment","description":"Maximum bytes read from one static snapshot file.","unit":"bytes","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.max_static_files","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"deployment","description":"Maximum static snapshot entry count, charged once per source group.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.max_stream_handshakes","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Process-wide ceiling for inner MTProxy handshakes that received a first byte.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.max_streams_global","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Process-wide live logical-stream ceiling.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.max_streams_per_session","value":{"type":"integer","minimum":1,"maximum":65535},"default_kind":"type_default","sensitivity":"public","description":"Default live logical-stream ceiling for one WEB session.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.max_tombstones_per_session","value":{"type":"integer","minimum":1,"maximum":4096},"default_kind":"type_default","sensitivity":"public","description":"Closed stream identifiers retained by one session.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.max_vhosts","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Maximum concrete hostname count across all WEB groups.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.max_websocket_evictions_in_flight","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Concurrent pressure-eviction claims allowed process-wide.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.memory_envelope_bytes","value":{"type":"integer","minimum":1,"maximum":4294967296},"default_kind":"type_default","sensitivity":"public","description":"Declared process envelope for HTTP, queues, capabilities, learning, and static snapshots.","unit":"bytes","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.new_bootstraps_burst","value":{"type":"integer","minimum":1,"maximum":4294967295},"default_kind":"type_default","sensitivity":"public","description":"Process-wide bootstrap issuance burst.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.new_bootstraps_per_minute","value":{"type":"integer","minimum":1,"maximum":4294967295},"default_kind":"type_default","sensitivity":"public","description":"Sustained process-wide bootstrap issuance rate.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.new_sessions_burst","value":{"type":"integer","minimum":1,"maximum":4294967295},"default_kind":"type_default","sensitivity":"public","description":"Process-wide session creation burst.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.new_sessions_per_minute","value":{"type":"integer","minimum":1,"maximum":4294967295},"default_kind":"type_default","sensitivity":"public","description":"Sustained process-wide session creation rate.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.new_streams_burst","value":{"type":"integer","minimum":1,"maximum":4294967295},"default_kind":"type_default","sensitivity":"public","description":"Process-wide logical-stream creation burst.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.new_streams_per_minute","value":{"type":"integer","minimum":1,"maximum":4294967295},"default_kind":"type_default","sensitivity":"public","description":"Sustained process-wide logical-stream creation rate.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.pending_bytes_global","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Process-wide queued data and control byte ceiling.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"},"unit":"bytes"},
|
||||
{"path":"web.limits.pending_bytes_per_lane","value":{"type":"integer","minimum":265,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Queued and resident DATA bytes allowed for one independent lane.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"},"unit":"bytes"},
|
||||
{"path":"web.limits.pending_bytes_per_session","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Total queued data and control bytes allowed for one session.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"},"unit":"bytes"},
|
||||
{"path":"web.limits.pending_items_global","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Process-wide queued data and control item ceiling.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.pending_items_per_lane","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Queued and resident DATA items allowed for one independent lane.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.pending_items_per_session","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Total queued data and control item ceiling for one session.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.websocket_admission_watermark_pct","value":{"type":"integer","minimum":1,"maximum":99},"default_kind":"type_default","sensitivity":"public","description":"WebSocket usage percentage above which ordinary admission uses replacement.","unit":"percent","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.websocket_bytes_global","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Process-wide transient WebSocket byte sub-budget inside pending bytes.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"},"unit":"bytes"},
|
||||
{"path":"web.limits.websocket_eviction_watermark_pct","value":{"type":"integer","minimum":1,"maximum":99},"default_kind":"type_default","sensitivity":"public","description":"WebSocket usage percentage that triggers pressure eviction.","unit":"percent","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.websocket_http_connection_reserve","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Accepted HTTP connections that WebSocket upgrades must leave available.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.wildcard","value":{"type":"object"},"default_kind":"nested_fields","sensitivity":"public","description":"Bounds automatic wildcard derivation and positive capability retention.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.wildcard.cache_bytes","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Maximum charged bytes, including entries still borrowed after eviction.","unit":"bytes","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.wildcard.cache_hosts","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Maximum positively authenticated hosts retained; zero disables retention.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.wildcard.cold_hmac_burst","value":{"type":"integer","minimum":0,"maximum":4294967295},"default_kind":"type_default","sensitivity":"public","description":"Atomic cold-derivation burst measured in HMAC evaluations.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.wildcard.cold_hmac_per_minute","value":{"type":"integer","minimum":0,"maximum":4294967295},"default_kind":"type_default","sensitivity":"public","description":"Sustained process-wide HMAC evaluation budget per minute.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.wildcard.max_profiles_per_request","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Maximum complete profile scan and cold derivation cost for one request.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.limits.wildcard.max_rules","value":{"type":"integer","minimum":0,"maximum":18446744073709551615},"default_kind":"type_default","sensitivity":"public","description":"Maximum suffix and catch-all selectors across all source groups.","apply":{"watcher":"unsupported","reload":"process_restart","effect":"after_process_restart"}},
|
||||
{"path":"web.retry_jitter","value":{"type":"object"},"default_kind":"nested_fields","sensitivity":"public","description":"Additive HTTP retry jitter frozen into each generated bridge page.","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.retry_jitter.distribution","value":{"type":"string","enum":["uniform","triangular"]},"default_kind":"type_default","sensitivity":"public","description":"Probability distribution used independently for each retry.","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"},"dependencies":["web.retry_jitter.min_ms","web.retry_jitter.max_ms","web.retry_jitter.distribution"],"constraints":["0 <= min_ms <= max_ms <= 30000; peak_ms requires triangular distribution and an in-range value."]},
|
||||
{"path":"web.retry_jitter.enabled","value":{"type":"boolean"},"default_kind":"type_default","sensitivity":"public","description":"Replaces the legacy jitter while retaining the underlying retry delay.","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"},"dependencies":["web.retry_jitter.min_ms","web.retry_jitter.max_ms","web.retry_jitter.distribution"],"constraints":["0 <= min_ms <= max_ms <= 30000; peak_ms requires triangular distribution and an in-range value."]},
|
||||
{"path":"web.retry_jitter.max_ms","value":{"type":"integer","minimum":0,"maximum":30000},"default_kind":"type_default","sensitivity":"public","description":"Inclusive maximum additive delay, bounded to 30000 milliseconds.","unit":"milliseconds","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"},"dependencies":["web.retry_jitter.min_ms","web.retry_jitter.max_ms","web.retry_jitter.distribution"],"constraints":["0 <= min_ms <= max_ms <= 30000; peak_ms requires triangular distribution and an in-range value."]},
|
||||
{"path":"web.retry_jitter.min_ms","value":{"type":"integer","minimum":0,"maximum":30000},"default_kind":"type_default","sensitivity":"public","description":"Inclusive minimum additive delay in milliseconds.","unit":"milliseconds","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"},"dependencies":["web.retry_jitter.min_ms","web.retry_jitter.max_ms","web.retry_jitter.distribution"],"constraints":["0 <= min_ms <= max_ms <= 30000; peak_ms requires triangular distribution and an in-range value."]},
|
||||
{"path":"web.retry_jitter.peak_ms","value":{"type":"integer","minimum":0,"maximum":30000},"default_kind":"unset","sensitivity":"public","description":"Triangular mode; omission selects the midpoint of the interval.","unit":"milliseconds","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"},"dependencies":["web.retry_jitter.min_ms","web.retry_jitter.max_ms","web.retry_jitter.distribution"],"constraints":["0 <= min_ms <= max_ms <= 30000; peak_ms requires triangular distribution and an in-range value."]},
|
||||
{"path":"web.timeouts","value":{"type":"object"},"default_kind":"nested_fields","sensitivity":"public","description":"WEB lifecycle deadlines.","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.timeouts.body_secs","value":{"type":"integer","minimum":1,"maximum":3600},"default_kind":"type_default","sensitivity":"public","description":"Deadline for collecting one authenticated carrier request body.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.timeouts.bootstrap_lifetime_secs","value":{"type":"integer","minimum":1,"maximum":3600},"default_kind":"type_default","sensitivity":"public","description":"Lifetime of an unused bootstrap credential and closed-token replay marker.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.timeouts.bridge_recovery_secs","value":{"type":"integer","minimum":1,"maximum":60},"default_kind":"type_default","sensitivity":"public","description":"Absolute post-commit budget for one surviving bridge recovery epoch.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.timeouts.bridge_request_secs","value":{"type":"integer","minimum":1,"maximum":60},"default_kind":"type_default","sensitivity":"public","description":"Deadline for one generated-bridge HTTP attempt and response body.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.timeouts.bridge_retry_secs","value":{"type":"integer","minimum":1,"maximum":300},"default_kind":"type_default","sensitivity":"public","description":"Absolute generated-bridge budget for one retryable HTTP operation.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.timeouts.carrier_health_secs","value":{"type":"integer","minimum":1,"maximum":3600},"default_kind":"type_default","sensitivity":"public","description":"Post-commit observation interval required before learning succeeds.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.timeouts.carrier_learning_secs","value":{"type":"integer","minimum":2,"maximum":86400},"default_kind":"type_default","sensitivity":"public","description":"Fixed process-local carrier-learning evidence lifetime.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.timeouts.carrier_negotiation_deadlines_secs","value":{"type":"array","items":{"type":"integer","minimum":0,"maximum":18446744073709551615},"minItems":4,"maxItems":4},"default_kind":"type_default","sensitivity":"public","description":"Cumulative carrier-attempt deadlines for up to four unique candidates.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"},"constraints":["Four nonzero strictly increasing deadlines; final deadline plus health and cleanup must fit bootstrap_lifetime_secs."]},
|
||||
{"path":"web.timeouts.carrier_probe_coalesce_ms","value":{"type":"integer","minimum":0,"maximum":10},"default_kind":"type_default","sensitivity":"public","description":"Optional delay for coalescing the first OPEN with immediate DATA.","unit":"milliseconds","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.timeouts.decoy_header_secs","value":{"type":"integer","minimum":1,"maximum":3600},"default_kind":"type_default","sensitivity":"public","description":"Deadline for connecting to and receiving headers from an HTTP decoy.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.timeouts.decoy_resolve_secs","value":{"type":"integer","minimum":1,"maximum":3600},"default_kind":"type_default","sensitivity":"public","description":"Maximum wait for each unique HTTP decoy hostname during preparation.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.timeouts.header_secs","value":{"type":"integer","minimum":1,"maximum":3600},"default_kind":"type_default","sensitivity":"public","description":"Deadline for receiving one complete HTTP request head.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.timeouts.http_idle_secs","value":{"type":"integer","minimum":1,"maximum":3600},"default_kind":"type_default","sensitivity":"public","description":"Maximum idle lifetime of a WEB HTTP keep-alive connection.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.timeouts.http_overload_timeout_ms","value":{"type":"integer","minimum":1,"maximum":60000},"default_kind":"type_default","sensitivity":"public","description":"Per-phase wait or response deadline for accepted HTTP overload sockets.","unit":"milliseconds","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.timeouts.lane_open_wait_secs","value":{"type":"integer","minimum":1,"maximum":3600},"default_kind":"type_default","sensitivity":"public","description":"Grace for a canonical downlink poll that races its lane OPEN.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.timeouts.long_poll_secs","value":{"type":"integer","minimum":1,"maximum":3600},"default_kind":"type_default","sensitivity":"public","description":"Maximum wait for one empty downlink long poll.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.timeouts.reconnect_grace_secs","value":{"type":"integer","minimum":1,"maximum":3600},"default_kind":"type_default","sensitivity":"public","description":"Maximum validated peer inactivity before a session is closed.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.timeouts.shutdown_secs","value":{"type":"integer","minimum":1,"maximum":3600},"default_kind":"type_default","sensitivity":"public","description":"Maximum graceful wait for WEB connections and process-owned tasks.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.timeouts.stream_first_byte_secs","value":{"type":"integer","minimum":1,"maximum":300},"default_kind":"type_default","sensitivity":"public","description":"Absolute deadline for receiving the first inner MTProxy byte.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.timeouts.stream_handshake_secs","value":{"type":"integer","minimum":1,"maximum":3600},"default_kind":"type_default","sensitivity":"public","description":"Deadline from the first inner byte through MTProxy authentication.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.timeouts.websocket_backpressure_secs","value":{"type":"integer","minimum":1,"maximum":3600},"default_kind":"type_default","sensitivity":"public","description":"Maximum wait for WebSocket queue or byte-budget progress.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.timeouts.websocket_eviction_secs","value":{"type":"integer","minimum":1,"maximum":3600},"default_kind":"type_default","sensitivity":"public","description":"Maximum graceful close wait for an evicted WebSocket.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.timeouts.websocket_open_secs","value":{"type":"integer","minimum":1,"maximum":300},"default_kind":"type_default","sensitivity":"public","description":"Absolute deadline for the first carrier binary message after upgrade.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.timeouts.websocket_upgrade_secs","value":{"type":"integer","minimum":1,"maximum":60},"default_kind":"type_default","sensitivity":"public","description":"Maximum wait for Hyper to transfer an accepted WebSocket upgrade.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.timeouts.websocket_write_secs","value":{"type":"integer","minimum":1,"maximum":3600},"default_kind":"type_default","sensitivity":"public","description":"Maximum wait for one WebSocket write to complete.","unit":"seconds","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"}},
|
||||
{"path":"web.vhosts","value":{"type":"array","items":{"type":"object"}},"default_kind":"type_default","sensitivity":"public","description":"Exact hostname and opted-in wildcard groups served by WEB listeners.","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"},"dependencies":["access.users","web.limits"]},
|
||||
{"path":"web.vhosts[].base_path","value":{"type":"string","maxLength":128},"default_kind":"type_default","sensitivity":"deployment","description":"Optional canonical WEB endpoint prefix without surrounding slashes.","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"},"dependencies":["access.users","web.limits"]},
|
||||
{"path":"web.vhosts[].decoy","value":{"type":"object"},"default_kind":"required","sensitivity":"public","description":"Ordinary-site fallback shared by every hostname in this group.","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"},"dependencies":["access.users","web.limits"]},
|
||||
{"path":"web.vhosts[].decoy.directory","value":{"type":"string"},"default_kind":"required","sensitivity":"deployment","description":"Configuration value for web.vhosts[].decoy.directory.","constraints":["Applies when web.vhosts[].decoy.mode is static_directory."],"apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"},"dependencies":["access.users","web.limits","web.vhosts[].decoy.mode"]},
|
||||
{"path":"web.vhosts[].decoy.index","value":{"type":"string"},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for web.vhosts[].decoy.index.","constraints":["Applies when web.vhosts[].decoy.mode is static_directory."],"apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"},"dependencies":["access.users","web.limits","web.vhosts[].decoy.mode"]},
|
||||
{"path":"web.vhosts[].decoy.mode","value":{"type":"string","enum":["http_upstream","static_directory"]},"default_kind":"required","sensitivity":"public","description":"Configuration value for web.vhosts[].decoy.mode.","constraints":["Selected by the enclosing decoy mode."],"apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"},"dependencies":["access.users","web.limits"]},
|
||||
{"path":"web.vhosts[].decoy.resolve","value":{"type":"string","enum":["never","startup"]},"default_kind":"type_default","sensitivity":"public","description":"Configuration value for web.vhosts[].decoy.resolve.","constraints":["Applies when web.vhosts[].decoy.mode is http_upstream."],"apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"},"dependencies":["access.users","web.limits","web.vhosts[].decoy.mode"]},
|
||||
{"path":"web.vhosts[].decoy.upstream","value":{"type":"string"},"default_kind":"required","sensitivity":"public","description":"Configuration value for web.vhosts[].decoy.upstream.","constraints":["Applies when web.vhosts[].decoy.mode is http_upstream."],"apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"},"dependencies":["access.users","web.limits","web.vhosts[].decoy.mode"]},
|
||||
{"path":"web.vhosts[].host","value":{"type":"string"},"default_kind":"unset","sensitivity":"public","description":"Single exact or opted-in wildcard selector, mutually exclusive with `hosts`.","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"},"dependencies":["access.users","web.limits"],"constraints":["Exactly one of host or hosts; normalized host selectors must be unique and obey the active wildcard policy."]},
|
||||
{"path":"web.vhosts[].hosts","value":{"type":"array","items":{"type":"string"}},"default_kind":"unset","sensitivity":"public","description":"Non-empty selector list, normalized to lowercase ACE during validation.","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"},"dependencies":["access.users","web.limits"],"constraints":["Exactly one of host or hosts; normalized host selectors must be unique and obey the active wildcard policy."]},
|
||||
{"path":"web.vhosts[].profiles","value":{"type":"array","items":{"type":"object"}},"default_kind":"type_default","sensitivity":"public","description":"Access profiles whose limits apply independently to each hostname.","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"},"dependencies":["access.users","web.limits"]},
|
||||
{"path":"web.vhosts[].profiles[].max_sessions","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"unset","sensitivity":"public","description":"Optional per-profile live session ceiling.","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"},"dependencies":["access.users","web.limits"]},
|
||||
{"path":"web.vhosts[].profiles[].max_streams","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"unset","sensitivity":"public","description":"Optional per-profile live logical-stream ceiling.","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"},"dependencies":["access.users","web.limits"]},
|
||||
{"path":"web.vhosts[].profiles[].max_streams_per_session","value":{"type":"integer","minimum":1,"maximum":18446744073709551615},"default_kind":"unset","sensitivity":"public","description":"Optional per-profile stream ceiling for one session.","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"},"dependencies":["access.users","web.limits"]},
|
||||
{"path":"web.vhosts[].profiles[].secret_mode","value":{"type":"string","enum":["plain","dd"]},"default_kind":"required","sensitivity":"public","description":"Exact client-facing secret representation advertised in WEB links.","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"},"dependencies":["access.users","web.limits"]},
|
||||
{"path":"web.vhosts[].profiles[].user","value":{"type":"string","minLength":1,"maxLength":64},"default_kind":"required","sensitivity":"public","description":"Existing `[access.users]` key authenticated by the inner MTProxy handshake.","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"},"dependencies":["access.users","web.limits"]},
|
||||
{"path":"web.vhosts[].public_addr","value":{"type":"string","format":"ip-port"},"default_kind":"required","sensitivity":"deployment","description":"Stable public destination tuple used by inner relay routing and KDF metadata.","apply":{"watcher":"supported","reload":"supported","effect":"new_issuance_or_policy_consumption_existing_session_contracts_preserved"},"dependencies":["access.users","web.limits"],"constraints":["A concrete, non-unspecified socket address with port 443 is required."]}
|
||||
]
|
||||
@@ -0,0 +1,209 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64};
|
||||
use std::time::Duration;
|
||||
|
||||
use hyper::server::conn::http1;
|
||||
use hyper::service::service_fn;
|
||||
use serde_json::Value;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::sync::{Mutex, watch};
|
||||
|
||||
use crate::api::{ApiRuntimeState, ApiShared, events::ApiEventStore, handler};
|
||||
use crate::config::{ApiGrayAction, ProxyConfig};
|
||||
use crate::maestro::{
|
||||
control_plane::ProcessControlPlane, generation::test_runtime_generation, reload::ReloadControl,
|
||||
};
|
||||
use crate::quota_state::QuotaStateOwner;
|
||||
use crate::stats::QuotaStore;
|
||||
|
||||
pub(in crate::api) struct Fixture {
|
||||
_directory: tempfile::TempDir,
|
||||
pub(in crate::api) shared: Arc<ApiShared>,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
pub(in crate::api) fn new(whitelist_denied: bool) -> Self {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let config_path = directory.path().join("config.toml");
|
||||
std::fs::write(&config_path, "# discovery must not edit this source\n").unwrap();
|
||||
let mut config = ProxyConfig::default();
|
||||
config.server.api.enabled = true;
|
||||
config.server.api.read_only = true;
|
||||
config.server.api.auth_header = "Bearer discovery-test".into();
|
||||
config.server.api.gray_action = ApiGrayAction::Api;
|
||||
config.server.api.whitelist = vec![if whitelist_denied {
|
||||
"192.0.2.0/24".parse().unwrap()
|
||||
} else {
|
||||
"127.0.0.1/32".parse().unwrap()
|
||||
}];
|
||||
let runtime = test_runtime_generation(1, config.clone());
|
||||
let shared = ApiShared {
|
||||
runtime_generation: runtime.id,
|
||||
stats: runtime.stats.clone(),
|
||||
ip_tracker: runtime.ip_tracker.clone(),
|
||||
me_pool: runtime.me_pool_runtime.clone(),
|
||||
upstream_manager: runtime.upstream_manager.clone(),
|
||||
config_path,
|
||||
quota_state: QuotaStateOwner::new(
|
||||
directory.path().join("quota.json"),
|
||||
Arc::new(QuotaStore::default()),
|
||||
),
|
||||
detected_ips_rx: watch::channel((None, None)).1,
|
||||
mutation_lock: Arc::new(Mutex::new(())),
|
||||
config_preflight_slots: Arc::new(tokio::sync::Semaphore::new(2)),
|
||||
config_state_slots: Arc::new(tokio::sync::Semaphore::new(2)),
|
||||
minimal_cache: Arc::new(Mutex::new(None)),
|
||||
runtime_edge_connections_cache: Arc::new(Mutex::new(None)),
|
||||
runtime_edge_recompute_lock: Arc::new(Mutex::new(())),
|
||||
cache_generation: Arc::new(AtomicU64::new(1)),
|
||||
runtime_events: Arc::new(ApiEventStore::new(64)),
|
||||
request_id: Arc::new(AtomicU64::new(1)),
|
||||
runtime_state: Arc::new(ApiRuntimeState {
|
||||
process_started_at_epoch_secs: 0,
|
||||
config_reload_count: AtomicU64::new(0),
|
||||
last_config_reload_epoch_secs: AtomicU64::new(0),
|
||||
admission_open: AtomicBool::new(true),
|
||||
}),
|
||||
startup_tracker: Arc::new(crate::startup::StartupTracker::new(0)),
|
||||
route_runtime: runtime.route_runtime.clone(),
|
||||
proxy_shared: runtime.proxy_shared.clone(),
|
||||
reload_control: ReloadControl::channel(1).0,
|
||||
active_runtime: Arc::new(arc_swap::ArcSwap::from(runtime)),
|
||||
web_trace: crate::web::trace::WebTraceStore::new(config.web.debug, &config.web.limits),
|
||||
web_runtime_rx: crate::web::control::WebRuntimeControl::new().subscribe(),
|
||||
control_plane: ProcessControlPlane::new(),
|
||||
};
|
||||
Self {
|
||||
_directory: directory,
|
||||
shared: Arc::new(shared),
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::api) async fn request(
|
||||
&self,
|
||||
method: &str,
|
||||
path: &str,
|
||||
authorized: bool,
|
||||
) -> (u16, String, Value) {
|
||||
self.request_body(method, path, authorized, None, &[]).await
|
||||
}
|
||||
|
||||
pub(in crate::api) async fn request_body(
|
||||
&self,
|
||||
method: &str,
|
||||
path: &str,
|
||||
authorized: bool,
|
||||
body: Option<&Value>,
|
||||
headers: &[(&str, &str)],
|
||||
) -> (u16, String, Value) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let shared = self.shared.clone();
|
||||
let server = tokio::spawn(async move {
|
||||
let (stream, peer) = listener.accept().await.unwrap();
|
||||
http1::Builder::new()
|
||||
.serve_connection(
|
||||
hyper_util::rt::TokioIo::new(stream),
|
||||
service_fn(move |request| handler::handle(request, peer, shared.clone())),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
});
|
||||
let client = reqwest::Client::builder()
|
||||
.no_proxy()
|
||||
.timeout(Duration::from_secs(5))
|
||||
.build()
|
||||
.unwrap();
|
||||
let mut request = client
|
||||
.request(method.parse().unwrap(), format!("http://{address}{path}"))
|
||||
.header("Connection", "close");
|
||||
if authorized {
|
||||
request = request.header("Authorization", "Bearer discovery-test");
|
||||
}
|
||||
if let Some(body) = body {
|
||||
request = request
|
||||
.header("Content-Type", "application/json")
|
||||
.body(serde_json::to_vec(body).unwrap());
|
||||
}
|
||||
for (name, value) in headers {
|
||||
request = request.header(*name, *value);
|
||||
}
|
||||
let response = request.send().await.unwrap();
|
||||
let status = response.status().as_u16();
|
||||
let allow = response
|
||||
.headers()
|
||||
.get("allow")
|
||||
.map(|value| value.to_str().unwrap().to_owned())
|
||||
.unwrap_or_default();
|
||||
let body = serde_json::from_slice(&response.bytes().await.unwrap()).unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(5), server)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
(status, allow, body)
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn discovery_http_preserves_auth_read_only_and_method_contracts() {
|
||||
let fixture = Fixture::new(false);
|
||||
let original = std::fs::read(&fixture.shared.config_path).unwrap();
|
||||
for path in ["/v1/capabilities", "/v1/config/schema"] {
|
||||
let (status, _, body) = fixture.request("GET", path, false).await;
|
||||
assert_eq!(status, 401);
|
||||
assert_eq!(body["error"]["code"], "unauthorized");
|
||||
|
||||
let (status, _, body) = fixture.request("GET", path, true).await;
|
||||
assert_eq!(status, 200);
|
||||
assert_eq!(body["ok"], true);
|
||||
assert_eq!(body["data"]["schema_version"], 1);
|
||||
assert!(
|
||||
body["revision"]
|
||||
.as_str()
|
||||
.is_some_and(|value| !value.is_empty())
|
||||
);
|
||||
|
||||
let (status, allow, body) = fixture.request("POST", path, true).await;
|
||||
assert_eq!(status, 405);
|
||||
assert_eq!(allow, "GET");
|
||||
assert_eq!(body["error"]["code"], "method_not_allowed");
|
||||
|
||||
let (status, _, body) = fixture
|
||||
.request("GET", &format!("{path}?extra=1"), true)
|
||||
.await;
|
||||
assert_eq!(status, 400);
|
||||
assert_eq!(body["error"]["code"], "bad_request");
|
||||
}
|
||||
assert_eq!(
|
||||
std::fs::read(&fixture.shared.config_path).unwrap(),
|
||||
original
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn discovery_http_preserves_whitelist_gate() {
|
||||
let fixture = Fixture::new(true);
|
||||
for path in ["/v1/capabilities", "/v1/config/schema"] {
|
||||
let (status, _, body) = fixture.request("GET", path, true).await;
|
||||
assert_eq!(status, 403);
|
||||
assert_eq!(body["error"]["code"], "forbidden");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn capabilities_http_does_not_wait_for_contended_me_pool() {
|
||||
let fixture = Fixture::new(false);
|
||||
// Keep the writer alive until after the HTTP response: a blocking sample
|
||||
// would time out instead of describing the unknown prerequisite.
|
||||
let _guard = fixture.shared.me_pool.write().await;
|
||||
let (status, _, body) = fixture.request("GET", "/v1/capabilities", true).await;
|
||||
assert_eq!(status, 200);
|
||||
let operation = body["data"]["operations"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|operation| operation["id"] == "runtime_me_pool_state")
|
||||
.unwrap();
|
||||
assert!(operation["available"].is_null());
|
||||
assert_eq!(operation["unavailable_reason"], "snapshot_busy");
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
[
|
||||
{"id": "health","method": "GET","path": "/v1/health","gate": "always","success": [200]},
|
||||
{"id": "health_ready","method": "GET","path": "/v1/health/ready","gate": "always","success": [200,503]},
|
||||
{"id": "capabilities","method": "GET","path": "/v1/capabilities","gate": "always","success": [200]},
|
||||
{"id": "config_schema","method": "GET","path": "/v1/config/schema","gate": "always","success": [200]},
|
||||
{"id": "system_info","method": "GET","path": "/v1/system/info","gate": "always","success": [200]},
|
||||
{"id": "runtime_gates","method": "GET","path": "/v1/runtime/gates","gate": "always","success": [200]},
|
||||
{"id": "runtime_initialization","method": "GET","path": "/v1/runtime/initialization","gate": "always","success": [200]},
|
||||
{"id": "limits_effective","method": "GET","path": "/v1/limits/effective","gate": "always","success": [200]},
|
||||
{"id": "security_posture","method": "GET","path": "/v1/security/posture","gate": "always","success": [200]},
|
||||
{"id": "security_whitelist","method": "GET","path": "/v1/security/whitelist","gate": "always","success": [200]},
|
||||
{"id": "stats_summary","method": "GET","path": "/v1/stats/summary","gate": "always","success": [200]},
|
||||
{"id": "stats_zero_all","method": "GET","path": "/v1/stats/zero/all","gate": "always","success": [200]},
|
||||
{"id": "stats_upstreams","method": "GET","path": "/v1/stats/upstreams","gate": "minimal","success": [200]},
|
||||
{"id": "stats_minimal_all","method": "GET","path": "/v1/stats/minimal/all","gate": "minimal_me","success": [200]},
|
||||
{"id": "stats_me_writers","method": "GET","path": "/v1/stats/me-writers","gate": "minimal_me","success": [200]},
|
||||
{"id": "stats_dcs","method": "GET","path": "/v1/stats/dcs","gate": "minimal_me","success": [200]},
|
||||
{"id": "runtime_me_pool_state","method": "GET","path": "/v1/runtime/me_pool_state","gate": "middle_proxy","success": [200],"aliases": ["/v1/runtime/me-pool-state"]},
|
||||
{"id": "runtime_me_quality","method": "GET","path": "/v1/runtime/me_quality","gate": "middle_proxy","success": [200],"aliases": ["/v1/runtime/me-quality"]},
|
||||
{"id": "runtime_upstream_quality","method": "GET","path": "/v1/runtime/upstream_quality","gate": "upstream","success": [200],"aliases": ["/v1/runtime/upstream-quality"]},
|
||||
{"id": "runtime_nat_stun","method": "GET","path": "/v1/runtime/nat_stun","gate": "middle_proxy","success": [200],"aliases": ["/v1/runtime/nat-stun"]},
|
||||
{"id": "runtime_me_selftest","method": "GET","path": "/v1/runtime/me-selftest","gate": "middle_proxy","success": [200]},
|
||||
{"id": "runtime_connections_summary","method": "GET","path": "/v1/runtime/connections/summary","gate": "edge","success": [200]},
|
||||
{"id": "runtime_events_recent","method": "GET","path": "/v1/runtime/events/recent","gate": "edge","success": [200]},
|
||||
{"id": "runtime_tls_fingerprints","method": "GET","path": "/v1/runtime/tls-fingerprints","gate": "edge","success": [200]},
|
||||
{"id": "web_status","method": "GET","path": "/v1/runtime/web/status","gate": "always","success": [200]},
|
||||
{"id": "web_sessions","method": "GET","path": "/v1/runtime/web/sessions","gate": "web_read","success": [200]},
|
||||
{"id": "web_session","method": "GET","path": "/v1/runtime/web/sessions/{session_ref}","gate": "web_read","success": [200,410]},
|
||||
{"id": "web_sessions_close","method": "POST","path": "/v1/runtime/web/sessions/close","gate": "web_control","success": [202],"body": "CloseRequest","exact_json_content_type": true},
|
||||
{"id": "web_operation","method": "GET","path": "/v1/runtime/web/operations/{operation_id}","gate": "web_read","success": [200]},
|
||||
{"id": "web_debug_clear","method": "POST","path": "/v1/runtime/web/debug/clear","gate": "web_control","success": [200],"body": "RuntimeInstanceRequest","exact_json_content_type": true},
|
||||
{"id": "web_learning_reset","method": "POST","path": "/v1/runtime/web/carrier-learning/reset","gate": "web_control","success": [200],"body": "RuntimeInstanceRequest","exact_json_content_type": true},
|
||||
{"id": "web_pause","method": "POST","path": "/v1/runtime/web/lifecycle/pause","gate": "web_control","success": [200],"body": "RuntimeInstanceRequest","exact_json_content_type": true},
|
||||
{"id": "web_drain","method": "POST","path": "/v1/runtime/web/lifecycle/drain","gate": "web_control","success": [202],"body": "DrainRequest","exact_json_content_type": true},
|
||||
{"id": "web_resume","method": "POST","path": "/v1/runtime/web/lifecycle/resume","gate": "web_control","success": [200],"body": "RuntimeInstanceRequest","exact_json_content_type": true},
|
||||
{"id": "web_status_html","method": "GET","path": "/web-status","gate": "always","success": [200]},
|
||||
{"id": "users_active_ips","method": "GET","path": "/v1/stats/users/active-ips","gate": "always","success": [200]},
|
||||
{"id": "users_quota","method": "GET","path": "/v1/stats/users/quota","gate": "always","success": [200]},
|
||||
{"id": "config_get","method": "GET","path": "/v1/config","gate": "always","success": [200],"credential_bearing": true},
|
||||
{"id": "config_state","method": "GET","path": "/v1/config/state","gate": "always","success": [200]},
|
||||
{"id": "config_validate","method": "POST","path": "/v1/config/validate","gate": "always","success": [200],"body": "PatchConfigRequest","if_match": true,"if_runtime_match": true,"read_only_operation": true},
|
||||
{"id": "config_patch","if_runtime_match": true,"method": "PATCH","path": "/v1/config","gate": "always","success": [200,202],"body": "PatchConfigRequest","if_match": true},
|
||||
{"id": "access_policy_get","method": "GET","path": "/v1/access/policy","gate": "always","success": [200]},
|
||||
{"id": "access_policy_patch","method": "PATCH","path": "/v1/access/policy","gate": "always","success": [200],"body": "AccessPolicyPatch","if_match": true,"if_runtime_match": true},
|
||||
{"id": "reload","method": "POST","path": "/v1/system/reload","gate": "always","success": [202],"body": "ReloadRequest","optional_body": true,"if_match": true},
|
||||
{"id": "reload_status","method": "GET","path": "/v1/system/reload/{id}","gate": "always","success": [200]},
|
||||
{"id": "users_list","method": "GET","path": "/v1/users","gate": "always","success": [200],"aliases": ["/v1/stats/users"],"credential_bearing": true},
|
||||
{"id": "users_create","method": "POST","path": "/v1/users","gate": "always","success": [201,202],"body": "CreateUserRequest","if_match": true,"credential_bearing": true},
|
||||
{"id": "users_get","method": "GET","path": "/v1/users/{username}","gate": "always","success": [200],"credential_bearing": true},
|
||||
{"id": "users_patch","method": "PATCH","path": "/v1/users/{username}","gate": "always","success": [200,202],"body": "PatchUserRequest","if_match": true,"credential_bearing": true},
|
||||
{"id": "users_delete","method": "DELETE","path": "/v1/users/{username}","gate": "always","success": [200,202],"if_match": true},
|
||||
{"id": "users_rotate_secret","method": "POST","path": "/v1/users/{username}/rotate-secret","gate": "always","success": [200,202],"body": "RotateSecretRequest","optional_body": true,"if_match": true,"credential_bearing": true},
|
||||
{"id": "users_enable","method": "POST","path": "/v1/users/{username}/enable","gate": "always","success": [200,202],"if_match": true,"credential_bearing": true},
|
||||
{"id": "users_disable","method": "POST","path": "/v1/users/{username}/disable","gate": "always","success": [200,202],"if_match": true,"credential_bearing": true},
|
||||
{"id": "users_reset_quota","method": "POST","path": "/v1/users/{username}/reset-quota","gate": "always","success": [200],"if_match": true}
|
||||
]
|
||||
@@ -0,0 +1,297 @@
|
||||
//! Checked metadata projection over unconfigured, typed configuration defaults.
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::super::config_store::{
|
||||
EDITABLE_NETWORK_FIELDS, EDITABLE_SECTIONS, EDITABLE_SERVER_API_FIELDS, EDITABLE_SERVER_FIELDS,
|
||||
};
|
||||
use super::super::model::ApiFailure;
|
||||
use super::SCHEMA_VERSION;
|
||||
|
||||
mod defaults;
|
||||
#[cfg(test)]
|
||||
mod inventory_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(super) struct FieldSpec {
|
||||
pub(super) path: String,
|
||||
pub(super) value: Value,
|
||||
pub(super) default_kind: DefaultKind,
|
||||
pub(super) sensitivity: String,
|
||||
pub(super) description: String,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub(super) aliases: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(super) unit: Option<String>,
|
||||
pub(super) apply: ApplyPolicy,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub(super) dependencies: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub(super) constraints: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(super) enum DefaultKind {
|
||||
TypeDefault,
|
||||
Unset,
|
||||
Required,
|
||||
NestedFields,
|
||||
MapEntry,
|
||||
Redacted,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(super) struct ApplyPolicy {
|
||||
pub(super) watcher: String,
|
||||
pub(super) reload: String,
|
||||
pub(super) effect: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub(in crate::api) struct ConfigSchemaData {
|
||||
schema_version: u32,
|
||||
value_schema_dialect: &'static str,
|
||||
defaults_scope: &'static str,
|
||||
validation_scope: &'static str,
|
||||
path_notation: &'static str,
|
||||
config_patch: ConfigPatchSemantics,
|
||||
fields: Vec<FieldMetadata>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct ConfigPatchSemantics {
|
||||
objects: &'static str,
|
||||
arrays: &'static str,
|
||||
object_null_members: &'static str,
|
||||
reset: &'static str,
|
||||
source_ownership: &'static str,
|
||||
if_match: &'static str,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct FieldMetadata {
|
||||
#[serde(flatten)]
|
||||
spec: FieldSpec,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
default: Option<Value>,
|
||||
api: FieldApi,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct FieldApi {
|
||||
config_read: bool,
|
||||
config_write: bool,
|
||||
read_routes: Vec<&'static str>,
|
||||
write_routes: Vec<&'static str>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
request_field: Option<&'static str>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
non_editable_reason: Option<&'static str>,
|
||||
null_behavior: &'static str,
|
||||
}
|
||||
|
||||
pub(in crate::api) fn config_schema() -> Result<&'static ConfigSchemaData, ApiFailure> {
|
||||
static SCHEMA: OnceLock<Result<ConfigSchemaData, String>> = OnceLock::new();
|
||||
SCHEMA
|
||||
.get_or_init(build_schema)
|
||||
.as_ref()
|
||||
.map_err(|error| ApiFailure::internal(error.clone()))
|
||||
}
|
||||
|
||||
pub(super) fn field_paths() -> Result<Vec<&'static str>, ApiFailure> {
|
||||
Ok(config_schema()?
|
||||
.fields
|
||||
.iter()
|
||||
.map(|field| field.spec.path.as_str())
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub(in crate::api) fn projection_rules()
|
||||
-> Result<Vec<(String, bool, Value, Option<Value>)>, ApiFailure> {
|
||||
Ok(config_schema()?
|
||||
.fields
|
||||
.iter()
|
||||
.map(|field| {
|
||||
(
|
||||
field.spec.path.clone(),
|
||||
field.spec.sensitivity == "public",
|
||||
field.spec.value.clone(),
|
||||
field.default.clone(),
|
||||
)
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn field_specs() -> Result<Vec<FieldSpec>, String> {
|
||||
serde_json::from_str(include_str!("fields.json"))
|
||||
.map_err(|error| format!("invalid compiled config field catalog: {error}"))
|
||||
}
|
||||
|
||||
fn build_schema() -> Result<ConfigSchemaData, String> {
|
||||
let defaults = defaults::typed_defaults()?;
|
||||
let specs = field_specs()?;
|
||||
let mut fields = Vec::with_capacity(specs.len());
|
||||
for spec in specs {
|
||||
let default = match spec.default_kind {
|
||||
DefaultKind::TypeDefault if spec.path == "web.vhosts[].profiles" => {
|
||||
Some(Value::Array(Vec::new()))
|
||||
}
|
||||
DefaultKind::TypeDefault => Some(
|
||||
default_at(
|
||||
if spec.path.contains("[]") {
|
||||
&defaults["_elements"]
|
||||
} else {
|
||||
&defaults
|
||||
},
|
||||
&spec.path,
|
||||
)
|
||||
.ok_or_else(|| format!("compiled config default missing: {}", spec.path))?
|
||||
.clone(),
|
||||
),
|
||||
DefaultKind::Unset => Some(Value::Null),
|
||||
_ => None,
|
||||
};
|
||||
let api = field_api(&spec.path);
|
||||
fields.push(FieldMetadata { spec, default, api });
|
||||
}
|
||||
Ok(ConfigSchemaData {
|
||||
schema_version: SCHEMA_VERSION,
|
||||
value_schema_dialect: "https://json-schema.org/draft/2020-12/schema",
|
||||
defaults_scope: "unconfigured_type_defaults_before_loader_normalization",
|
||||
validation_scope: "value_constraints_are_not_a_substitute_for_full_config_validation",
|
||||
path_notation: "dot_members; []=array_element; {name}=dynamic_map_key",
|
||||
config_patch: ConfigPatchSemantics {
|
||||
objects: "recursive_merge",
|
||||
arrays: "replace_whole_array",
|
||||
object_null_members: "ignored_before_candidate_validation",
|
||||
reset: "not_supported",
|
||||
source_ownership: "one_independently_writable_source_per_mutation",
|
||||
if_match: "optional_source_manifest_revision",
|
||||
},
|
||||
fields,
|
||||
})
|
||||
}
|
||||
|
||||
fn default_at<'a>(value: &'a Value, path: &str) -> Option<&'a Value> {
|
||||
fn walk<'a>(value: &'a Value, segments: &[&str]) -> Option<&'a Value> {
|
||||
let Some((segment, rest)) = segments.split_first() else {
|
||||
return Some(value);
|
||||
};
|
||||
if let Some(key) = segment.strip_suffix("[]") {
|
||||
value
|
||||
.get(key)?
|
||||
.as_array()?
|
||||
.iter()
|
||||
.find_map(|item| walk(item, rest))
|
||||
} else {
|
||||
walk(value.get(*segment)?, rest)
|
||||
}
|
||||
}
|
||||
walk(value, &path.split('.').collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
fn field_api(path: &str) -> FieldApi {
|
||||
let top = path.split(['.', '[']).next().unwrap_or("");
|
||||
let config_editable = EDITABLE_SECTIONS.contains(&top)
|
||||
|| path
|
||||
.strip_prefix("network.")
|
||||
.is_some_and(|field| EDITABLE_NETWORK_FIELDS.contains(&field))
|
||||
|| path
|
||||
.strip_prefix("server.api.")
|
||||
.is_some_and(|field| EDITABLE_SERVER_API_FIELDS.contains(&field))
|
||||
|| (top == "server"
|
||||
&& EDITABLE_SERVER_FIELDS
|
||||
.iter()
|
||||
.filter(|field| **field != "api")
|
||||
.any(|field| {
|
||||
let prefix = format!("server.{field}");
|
||||
path == prefix
|
||||
|| path.starts_with(&format!("{prefix}["))
|
||||
|| path.starts_with(&format!("{prefix}."))
|
||||
}));
|
||||
let policy_field = path.strip_prefix("access.").and_then(|path| {
|
||||
let field = path.split('.').next()?;
|
||||
crate::api::access_policy::FIELDS
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|candidate| *candidate == field)
|
||||
});
|
||||
let user_field = path
|
||||
.strip_prefix("access.")
|
||||
.and_then(|path| path.split('.').next())
|
||||
.and_then(|field| match field {
|
||||
"users" => Some("secret"),
|
||||
"user_enabled" => Some("enabled"),
|
||||
"user_ad_tags" => Some("user_ad_tag"),
|
||||
"user_max_tcp_conns" => Some("max_tcp_conns"),
|
||||
"user_expirations" => Some("expiration_rfc3339"),
|
||||
"user_data_quota" => Some("data_quota_bytes"),
|
||||
"user_quota_periods" => Some("quota_period"),
|
||||
"user_max_unique_ips" => Some("max_unique_ips"),
|
||||
"user_source_deny" => Some("source_deny"),
|
||||
"user_rate_limits" if path.ends_with(".up_bps") => Some("rate_limit_up_bps"),
|
||||
"user_rate_limits" if path.ends_with(".down_bps") => Some("rate_limit_down_bps"),
|
||||
_ => None,
|
||||
});
|
||||
let mut api = FieldApi {
|
||||
config_read: config_editable,
|
||||
config_write: config_editable,
|
||||
read_routes: Vec::new(),
|
||||
write_routes: Vec::new(),
|
||||
request_field: user_field,
|
||||
non_editable_reason: None,
|
||||
null_behavior: "not_editable",
|
||||
};
|
||||
if config_editable {
|
||||
api.read_routes.push("GET /v1/config");
|
||||
api.write_routes.push("PATCH /v1/config");
|
||||
api.null_behavior = "ignored_member_then_validate_candidate";
|
||||
} else if let Some(field) = policy_field {
|
||||
api.read_routes.push("GET /v1/access/policy");
|
||||
api.write_routes.push("PATCH /v1/access/policy");
|
||||
api.request_field = Some(field);
|
||||
api.non_editable_reason = Some("managed_via_access_policy_api");
|
||||
api.null_behavior = if field == "cidr_rate_limits" {
|
||||
"clear_map_or_remove_null_entries"
|
||||
} else {
|
||||
"remove_authored_value_restore_type_default"
|
||||
};
|
||||
} else if let Some(field) = user_field {
|
||||
api.read_routes.push("GET /v1/users/{username}");
|
||||
api.write_routes
|
||||
.extend(["POST /v1/users", "PATCH /v1/users/{username}"]);
|
||||
api.null_behavior = if field == "secret" {
|
||||
"unchanged_on_user_patch"
|
||||
} else {
|
||||
"remove_user_override_on_patch"
|
||||
};
|
||||
api.non_editable_reason = Some("managed_via_users_api");
|
||||
} else {
|
||||
api.non_editable_reason = Some(match top {
|
||||
"access" => "access_policy_is_file_only",
|
||||
"network" => "network_field_not_in_config_api_allowlist",
|
||||
"server" => "server_field_not_in_config_api_allowlist",
|
||||
"logging" => "logging_section_is_file_only",
|
||||
"show_link" => "use_general_links_show",
|
||||
"include" => "source_graph_is_file_only",
|
||||
_ => "root_field_not_in_config_api_allowlist",
|
||||
});
|
||||
}
|
||||
if path.starts_with("access.user_max_unique_ips_")
|
||||
|| path == "access.user_max_tcp_conns_global_each"
|
||||
{
|
||||
api.read_routes.push("GET /v1/limits/effective");
|
||||
}
|
||||
if path == "server.api.whitelist" {
|
||||
api.read_routes.push("GET /v1/security/whitelist");
|
||||
}
|
||||
api
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::config::{ListenerConfig, ProxyConfig, UpstreamConfig, WebVhostConfig};
|
||||
|
||||
/// Supplies child defaults for otherwise empty collections. Required/example
|
||||
/// values are never projected; their catalog default kind excludes them.
|
||||
pub(super) fn typed_defaults() -> Result<Value, String> {
|
||||
let mut config = ProxyConfig::default();
|
||||
// Even the repository's built-in example credential is not schema data.
|
||||
config.access.users.clear();
|
||||
let mut root = serde_json::to_value(config).map_err(|error| error.to_string())?;
|
||||
let listener: ListenerConfig =
|
||||
serde_json::from_value(json!({"ip": "127.0.0.1"})).map_err(|error| error.to_string())?;
|
||||
let upstreams: Vec<UpstreamConfig> = serde_json::from_value(json!([
|
||||
{"type": "direct"},
|
||||
{"type": "socks4", "address": "127.0.0.1:1080"},
|
||||
{"type": "socks5", "address": "127.0.0.1:1080"},
|
||||
{"type": "shadowsocks", "url": "ss://schema-example"}
|
||||
]))
|
||||
.map_err(|error| error.to_string())?;
|
||||
let vhosts: Vec<WebVhostConfig> = serde_json::from_value(json!([
|
||||
{
|
||||
"host": "schema.example", "public_addr": "127.0.0.1:443",
|
||||
"decoy": {"mode": "http_upstream", "upstream": "http://127.0.0.1:8080"},
|
||||
"profiles": [{"user": "schema-example", "secret_mode": "plain"}]
|
||||
},
|
||||
{
|
||||
"hosts": ["schema.example"], "public_addr": "127.0.0.1:443",
|
||||
"decoy": {"mode": "static_directory", "directory": "/schema-example"}
|
||||
}
|
||||
]))
|
||||
.map_err(|error| error.to_string())?;
|
||||
// Collection roots retain their actual empty default. The separate child
|
||||
// tree is selected only by paths containing an array element marker.
|
||||
root["_elements"] = json!({
|
||||
"server": {"listeners": [listener]},
|
||||
"upstreams": upstreams,
|
||||
"web": {"vhosts": vhosts}
|
||||
});
|
||||
Ok(root)
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
//! Source inventory complements typed serialization for omitted Options and
|
||||
//! empty maps. This deliberately supports the repository's declaration style;
|
||||
//! an unfamiliar field declaration fails instead of silently losing coverage.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::Path;
|
||||
|
||||
use regex::Regex;
|
||||
|
||||
struct Field {
|
||||
name: String,
|
||||
ty: String,
|
||||
flattened: bool,
|
||||
}
|
||||
|
||||
fn read_sources(directory: &Path, sources: &mut Vec<String>) {
|
||||
for entry in std::fs::read_dir(directory).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
if path.is_dir() {
|
||||
read_sources(&path, sources);
|
||||
} else if path.extension().is_some_and(|extension| extension == "rs") {
|
||||
sources.push(std::fs::read_to_string(path).unwrap());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn declared_fields_including_omitted_options_and_maps_have_metadata() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/config");
|
||||
let mut sources = vec![std::fs::read_to_string(root.join("load.rs")).unwrap()];
|
||||
read_sources(&root.join("types"), &mut sources);
|
||||
let declaration = Regex::new(r"pub(?:\([^)]*\))? struct (\w+)\s*\{").unwrap();
|
||||
let field = Regex::new(r"^pub(?:\([^)]*\))? (\w+): (.+),$").unwrap();
|
||||
let skipped = Regex::new(r"\bskip\b").unwrap();
|
||||
let mut structs = BTreeMap::new();
|
||||
for source in &sources {
|
||||
for found in declaration.captures_iter(source) {
|
||||
let start = found.get(0).unwrap().end();
|
||||
let body = source[start..].split_once("\n}").unwrap().0;
|
||||
let mut attributes = String::new();
|
||||
let mut fields = Vec::new();
|
||||
for line in body.lines().map(str::trim) {
|
||||
if line.starts_with("#[") || (!attributes.is_empty() && !attributes.ends_with(']'))
|
||||
{
|
||||
attributes.push_str(line);
|
||||
} else if line.starts_with("pub ") || line.starts_with("pub(") {
|
||||
let entry = field.captures(line).unwrap_or_else(|| {
|
||||
panic!(
|
||||
"extend discovery source inventory for {}: {line}",
|
||||
&found[1]
|
||||
)
|
||||
});
|
||||
if !skipped.is_match(&attributes) {
|
||||
fields.push(Field {
|
||||
name: entry[1].to_string(),
|
||||
ty: entry[2].to_string(),
|
||||
flattened: attributes.contains("flatten"),
|
||||
});
|
||||
}
|
||||
attributes.clear();
|
||||
}
|
||||
}
|
||||
assert!(structs.insert(found[1].to_string(), fields).is_none());
|
||||
}
|
||||
}
|
||||
let catalog: BTreeSet<_> = super::config_schema()
|
||||
.unwrap()
|
||||
.fields
|
||||
.iter()
|
||||
.map(|field| field.spec.path.clone())
|
||||
.collect();
|
||||
let mut declared = BTreeSet::new();
|
||||
visit("ProxyConfig", "", &structs, &mut declared);
|
||||
// Empty collection defaults cannot reveal a new tagged variant. Check the
|
||||
// declarations as well as serializing every currently known variant.
|
||||
for (ty, path, tag, snake_case) in [
|
||||
("UpstreamType", "upstreams[]", "type", false),
|
||||
("WebDecoyConfig", "web.vhosts[].decoy", "mode", true),
|
||||
] {
|
||||
check_tagged_variants(&sources, ty, path, tag, snake_case, &structs, &mut declared);
|
||||
}
|
||||
let missing: Vec<_> = declared.difference(&catalog).collect();
|
||||
assert!(
|
||||
missing.is_empty(),
|
||||
"unclassified declared fields: {missing:?}"
|
||||
);
|
||||
assert!(
|
||||
declared.len() > 400,
|
||||
"source inventory unexpectedly incomplete"
|
||||
);
|
||||
}
|
||||
|
||||
fn check_tagged_variants(
|
||||
sources: &[String],
|
||||
ty: &str,
|
||||
path: &str,
|
||||
tag: &str,
|
||||
snake_case: bool,
|
||||
structs: &BTreeMap<String, Vec<Field>>,
|
||||
paths: &mut BTreeSet<String>,
|
||||
) {
|
||||
let marker = format!("pub enum {ty} {{");
|
||||
let body = sources
|
||||
.iter()
|
||||
.find_map(|source| source.split_once(&marker))
|
||||
.unwrap()
|
||||
.1
|
||||
.split_once("\n}")
|
||||
.unwrap()
|
||||
.0;
|
||||
let tag_path = format!("{path}.{tag}");
|
||||
paths.insert(tag_path.clone());
|
||||
let schema = super::config_schema().unwrap();
|
||||
let field = schema
|
||||
.fields
|
||||
.iter()
|
||||
.find(|field| field.spec.path == tag_path)
|
||||
.unwrap();
|
||||
let variants: BTreeSet<_> = field.spec.value["enum"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|value| value.as_str().unwrap().to_owned())
|
||||
.collect();
|
||||
let variant = Regex::new(r"(?m)^ (\w+)\s*(?:\{|,)").unwrap();
|
||||
let boundary = Regex::new(r"([a-z0-9])([A-Z])").unwrap();
|
||||
let declared: BTreeSet<_> = variant
|
||||
.captures_iter(body)
|
||||
.map(|value| {
|
||||
if snake_case {
|
||||
boundary.replace_all(&value[1], "${1}_${2}").to_lowercase()
|
||||
} else {
|
||||
value[1].to_lowercase()
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(variants, declared, "unclassified tagged variants in {ty}");
|
||||
let field = Regex::new(r"(?m)^ (\w+): (.+),$").unwrap();
|
||||
for field in field.captures_iter(body) {
|
||||
let path = format!("{path}.{}", &field[1]);
|
||||
paths.insert(path.clone());
|
||||
visit(&field[2], &path, structs, paths);
|
||||
}
|
||||
}
|
||||
|
||||
fn visit(
|
||||
ty: &str,
|
||||
path: &str,
|
||||
structs: &BTreeMap<String, Vec<Field>>,
|
||||
paths: &mut BTreeSet<String>,
|
||||
) {
|
||||
if let Some(inner) = ty
|
||||
.strip_prefix("Option<")
|
||||
.and_then(|ty| ty.strip_suffix('>'))
|
||||
{
|
||||
visit(inner, path, structs, paths);
|
||||
} else if let Some(inner) = ty.strip_prefix("Vec<").and_then(|ty| ty.strip_suffix('>')) {
|
||||
visit(inner, &format!("{path}[]"), structs, paths);
|
||||
} else if let Some(inner) = ty
|
||||
.strip_prefix("HashMap<")
|
||||
.and_then(|ty| ty.strip_suffix('>'))
|
||||
{
|
||||
let (_, value) = inner.split_once(',').unwrap();
|
||||
let key = match path {
|
||||
"dc_overrides" => "{dc}",
|
||||
"censorship.exclusive_mask" => "{hostname}",
|
||||
"access.cidr_rate_limits" => "{cidr}",
|
||||
_ => "{username}",
|
||||
};
|
||||
let path = format!("{path}.{key}");
|
||||
paths.insert(path.clone());
|
||||
visit(value.trim(), &path, structs, paths);
|
||||
} else if let Some(fields) = structs.get(ty) {
|
||||
for field in fields {
|
||||
let next = if field.flattened {
|
||||
path.to_string()
|
||||
} else if path.is_empty() {
|
||||
field.name.clone()
|
||||
} else {
|
||||
format!("{path}.{}", field.name)
|
||||
};
|
||||
if !field.flattened {
|
||||
paths.insert(next.clone());
|
||||
}
|
||||
visit(&field.ty, &next, structs, paths);
|
||||
}
|
||||
}
|
||||
// Tagged enum children are exercised through all typed variants by the
|
||||
// serialization inventory test; scalar custom deserializers have no children.
|
||||
}
|
||||
@@ -0,0 +1,403 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::*;
|
||||
use crate::config::ProxyConfig;
|
||||
|
||||
fn field<'a>(schema: &'a ConfigSchemaData, path: &str) -> &'a FieldMetadata {
|
||||
schema
|
||||
.fields
|
||||
.iter()
|
||||
.find(|field| field.spec.path == path)
|
||||
.unwrap_or_else(|| panic!("missing field {path}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schema_defaults_and_collection_templates_are_typed_and_secret_free() {
|
||||
let schema = config_schema().unwrap();
|
||||
let defaults = ProxyConfig::default();
|
||||
assert_eq!(
|
||||
field(schema, "general.me_keepalive_interval_secs").default,
|
||||
Some(json!(defaults.general.me_keepalive_interval_secs))
|
||||
);
|
||||
assert_eq!(
|
||||
field(schema, "server.api.gray_action").default,
|
||||
Some(json!("drop"))
|
||||
);
|
||||
assert_eq!(
|
||||
field(schema, "server.listeners[].synlimit").default,
|
||||
Some(json!(false))
|
||||
);
|
||||
assert_eq!(
|
||||
field(schema, "web.vhosts[].profiles").default,
|
||||
Some(json!([]))
|
||||
);
|
||||
assert_eq!(
|
||||
field(schema, "web.vhosts[].host").default,
|
||||
Some(Value::Null)
|
||||
);
|
||||
assert_eq!(
|
||||
field(schema, "web.vhosts[].decoy.index").default,
|
||||
Some(json!("index.html"))
|
||||
);
|
||||
assert!(field(schema, "web.vhosts[].public_addr").default.is_none());
|
||||
assert!(field(schema, "upstreams[].address").default.is_none());
|
||||
for path in [
|
||||
"access.users",
|
||||
"access.users.{username}",
|
||||
"server.api.auth_header",
|
||||
"upstreams[].password",
|
||||
"upstreams[].url",
|
||||
] {
|
||||
let field = field(schema, path);
|
||||
assert_eq!(field.spec.sensitivity, "credential");
|
||||
assert!(field.default.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
fn serialized_paths(value: &Value, path: &str, paths: &mut BTreeSet<String>) {
|
||||
if !path.is_empty() {
|
||||
paths.insert(path.to_string());
|
||||
}
|
||||
match value {
|
||||
Value::Object(object) => {
|
||||
for (key, value) in object {
|
||||
if key == "_elements" {
|
||||
continue;
|
||||
}
|
||||
let key = if path.is_empty() {
|
||||
key.clone()
|
||||
} else {
|
||||
format!("{path}.{key}")
|
||||
};
|
||||
serialized_paths(value, &key, paths);
|
||||
}
|
||||
}
|
||||
Value::Array(array) => {
|
||||
for item in array {
|
||||
if let Some(object) = item.as_object() {
|
||||
for (key, value) in object {
|
||||
serialized_paths(value, &format!("{path}[].{key}"), paths);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_serialized_field_has_metadata_including_all_collection_variants() {
|
||||
let schema = config_schema().unwrap();
|
||||
let mut actual = BTreeSet::new();
|
||||
let values = defaults::typed_defaults().unwrap();
|
||||
serialized_paths(&values, "", &mut actual);
|
||||
serialized_paths(&values["_elements"], "", &mut actual);
|
||||
let catalog: BTreeSet<_> = schema
|
||||
.fields
|
||||
.iter()
|
||||
.map(|field| field.spec.path.clone())
|
||||
.collect();
|
||||
assert_eq!(catalog.len(), schema.fields.len(), "duplicate config path");
|
||||
let missing: Vec<_> = actual.difference(&catalog).collect();
|
||||
assert!(
|
||||
missing.is_empty(),
|
||||
"unclassified serialized fields: {missing:?}"
|
||||
);
|
||||
// Omitted Options and dynamic maps are part of the contract too.
|
||||
for path in [
|
||||
"web.vhosts[].host",
|
||||
"web.vhosts[].hosts",
|
||||
"web.retry_jitter.peak_ms",
|
||||
"access.users.{username}",
|
||||
"access.user_rate_limits.{username}.up_bps",
|
||||
"access.cidr_rate_limits.{cidr}.down_bps",
|
||||
"dc_overrides.{dc}",
|
||||
] {
|
||||
assert!(catalog.contains(path), "missing {path}");
|
||||
}
|
||||
for entry in &schema.fields {
|
||||
if !entry.api.config_write && entry.api.write_routes.is_empty() {
|
||||
assert!(
|
||||
entry.api.non_editable_reason.is_some(),
|
||||
"{}",
|
||||
entry.spec.path
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn api_ownership_aliases_and_null_contracts_match_existing_surfaces() {
|
||||
let schema = config_schema().unwrap();
|
||||
assert!(field(schema, "web.vhosts[].base_path").api.config_write);
|
||||
assert!(field(schema, "server.listeners[].port").api.config_write);
|
||||
for entry in &schema.fields {
|
||||
if let Some(key) = entry.spec.path.strip_prefix("server.api.") {
|
||||
let editable = EDITABLE_SERVER_API_FIELDS.contains(&key);
|
||||
assert_eq!(entry.api.config_read, editable, "{key}");
|
||||
assert_eq!(entry.api.config_write, editable, "{key}");
|
||||
}
|
||||
}
|
||||
assert!(field(schema, "network.dns_overrides").api.config_read);
|
||||
assert!(field(schema, "network.dns_overrides").api.config_write);
|
||||
assert_eq!(
|
||||
field(schema, "network.dns_overrides")
|
||||
.api
|
||||
.non_editable_reason,
|
||||
None
|
||||
);
|
||||
for path in [
|
||||
"network",
|
||||
"network.ipv4",
|
||||
"network.ipv6",
|
||||
"network.prefer",
|
||||
"network.stun_servers",
|
||||
] {
|
||||
assert!(!field(schema, path).api.config_read);
|
||||
assert!(!field(schema, path).api.config_write);
|
||||
assert_eq!(
|
||||
field(schema, path).api.non_editable_reason,
|
||||
Some("network_field_not_in_config_api_allowlist")
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
field(schema, "access.user_rate_limits.{username}.up_bps")
|
||||
.api
|
||||
.request_field,
|
||||
Some("rate_limit_up_bps")
|
||||
);
|
||||
assert_eq!(
|
||||
field(schema, "access.user_quota_periods.{username}")
|
||||
.api
|
||||
.null_behavior,
|
||||
"remove_user_override_on_patch"
|
||||
);
|
||||
assert_eq!(
|
||||
field(schema, "access.user_source_deny").api.write_routes,
|
||||
["POST /v1/users", "PATCH /v1/users/{username}"]
|
||||
);
|
||||
assert!(
|
||||
field(schema, "server.api.listen")
|
||||
.spec
|
||||
.aliases
|
||||
.contains(&"server.admin_api.listen".into())
|
||||
);
|
||||
assert!(
|
||||
field(schema, "upstreams[].bindtodevice")
|
||||
.spec
|
||||
.aliases
|
||||
.contains(&"upstreams[].force_bind".into())
|
||||
);
|
||||
assert_eq!(
|
||||
field(schema, "network.dns_overrides").spec.apply.watcher,
|
||||
"supported"
|
||||
);
|
||||
assert_eq!(
|
||||
field(schema, "web.debug.body_capture").spec.apply.reload,
|
||||
"conditional"
|
||||
);
|
||||
assert_eq!(
|
||||
field(schema, "web.limits.max_sessions_global")
|
||||
.spec
|
||||
.apply
|
||||
.reload,
|
||||
"process_restart"
|
||||
);
|
||||
assert_eq!(
|
||||
schema.config_patch.object_null_members,
|
||||
"ignored_before_candidate_validation"
|
||||
);
|
||||
}
|
||||
|
||||
fn accepts(schema: &Value, value: &Value) -> bool {
|
||||
if let Some(options) = schema.get("oneOf").and_then(Value::as_array) {
|
||||
return options
|
||||
.iter()
|
||||
.filter(|option| accepts(option, value))
|
||||
.count()
|
||||
== 1;
|
||||
}
|
||||
if let Some(expected) = schema.get("const") {
|
||||
return value == expected;
|
||||
}
|
||||
if let Some(values) = schema.get("enum").and_then(Value::as_array) {
|
||||
if !values.contains(value) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
let correct_type = match schema["type"].as_str() {
|
||||
Some("string") => value.is_string(),
|
||||
Some("boolean") => value.is_boolean(),
|
||||
Some("integer") => value.is_u64() || value.is_i64(),
|
||||
Some("number") => value.is_number(),
|
||||
Some("array") => value.is_array(),
|
||||
Some("object") => value.is_object(),
|
||||
None => true,
|
||||
other => panic!("unsupported value schema type: {other:?}"),
|
||||
};
|
||||
if !correct_type {
|
||||
return false;
|
||||
}
|
||||
if let Some(number) = value.as_f64() {
|
||||
if schema
|
||||
.get("minimum")
|
||||
.and_then(Value::as_f64)
|
||||
.is_some_and(|min| number < min)
|
||||
|| schema
|
||||
.get("maximum")
|
||||
.and_then(Value::as_f64)
|
||||
.is_some_and(|max| number > max)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if let Some(array) = value.as_array() {
|
||||
if schema
|
||||
.get("minItems")
|
||||
.and_then(Value::as_u64)
|
||||
.is_some_and(|min| array.len() < min as usize)
|
||||
|| schema
|
||||
.get("maxItems")
|
||||
.and_then(Value::as_u64)
|
||||
.is_some_and(|max| array.len() > max as usize)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if let Some(items) = schema.get("items") {
|
||||
return array.iter().all(|value| accepts(items, value));
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn declared_value_types_enums_and_ranges_accept_typed_defaults() {
|
||||
for field in &config_schema().unwrap().fields {
|
||||
if let Some(default) = &field.default {
|
||||
if !default.is_null() {
|
||||
assert!(
|
||||
accepts(&field.spec.value, default),
|
||||
"{}: {default} violates {}",
|
||||
field.spec.path,
|
||||
field.spec.value
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn alternative(field: &FieldMetadata, current: &Value) -> Option<Value> {
|
||||
if let Some(values) = field.spec.value.get("enum").and_then(Value::as_array) {
|
||||
return values.iter().find(|value| *value != current).cloned();
|
||||
}
|
||||
if let Some(boolean) = current.as_bool() {
|
||||
return Some(json!(!boolean));
|
||||
}
|
||||
if let Some(number) = current.as_u64() {
|
||||
return number.checked_add(1).map(|number| json!(number));
|
||||
}
|
||||
if let Some(number) = current.as_f64() {
|
||||
return Some(json!(number + 0.01));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn application_metadata_matches_watcher_and_process_resolver() {
|
||||
let base = ProxyConfig::default();
|
||||
let baseline = serde_json::to_value(&base).unwrap();
|
||||
let schema = config_schema().unwrap();
|
||||
let mut watched = 0;
|
||||
let mut resolved = 0;
|
||||
let mut mismatches = Vec::new();
|
||||
for field in &schema.fields {
|
||||
let path = &field.spec.path;
|
||||
if path.contains('[') || path.contains('{') {
|
||||
continue;
|
||||
}
|
||||
let pointer = format!("/{}", path.replace('.', "/"));
|
||||
let Some(current) = baseline.pointer(&pointer) else {
|
||||
continue;
|
||||
};
|
||||
let Some(next) = alternative(field, current) else {
|
||||
continue;
|
||||
};
|
||||
let mut candidate = baseline.clone();
|
||||
*candidate.pointer_mut(&pointer).unwrap() = next;
|
||||
let Ok(candidate) = serde_json::from_value::<ProxyConfig>(candidate) else {
|
||||
continue;
|
||||
};
|
||||
let class = crate::config::hot_reload::classify_config_changes(&base, &candidate);
|
||||
match field.spec.apply.watcher.as_str() {
|
||||
"supported" => {
|
||||
if class.restart_required {
|
||||
mismatches.push(format!("watcher unexpectedly requires restart: {path}"));
|
||||
}
|
||||
watched += 1;
|
||||
}
|
||||
"unsupported" => {
|
||||
if !class.restart_required {
|
||||
mismatches.push(format!("watcher unexpectedly supports: {path}"));
|
||||
}
|
||||
watched += 1;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
// Independent runtime validation can reject a deliberately single-field
|
||||
// perturbation; only valid candidates classify the actual reload effect.
|
||||
if let Ok(effect) = crate::maestro::runtime_build::resolve_reload_config(&base, &candidate)
|
||||
{
|
||||
match field.spec.apply.reload.as_str() {
|
||||
"process_restart" => {
|
||||
if effect.deferred_process_fields.is_empty() {
|
||||
mismatches.push(format!("reload unexpectedly applies: {path}"));
|
||||
}
|
||||
}
|
||||
"supported" => {
|
||||
if !effect.deferred_process_fields.is_empty() {
|
||||
mismatches.push(format!("reload unexpectedly defers: {path}"));
|
||||
}
|
||||
}
|
||||
_ => continue,
|
||||
}
|
||||
resolved += 1;
|
||||
}
|
||||
}
|
||||
assert!(mismatches.is_empty(), "{}", mismatches.join("\n"));
|
||||
assert!(
|
||||
watched > 150,
|
||||
"only {watched} fields checked against watcher"
|
||||
);
|
||||
assert!(
|
||||
resolved > 150,
|
||||
"only {resolved} fields checked against runtime resolver"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn field_enums_round_trip_through_real_deserializers() {
|
||||
let baseline = defaults::typed_defaults().unwrap();
|
||||
let mut checked = BTreeMap::new();
|
||||
for field in &config_schema().unwrap().fields {
|
||||
let path = &field.spec.path;
|
||||
if path.contains('[') || path.contains('{') {
|
||||
continue;
|
||||
}
|
||||
let Some(variants) = field.spec.value.get("enum").and_then(Value::as_array) else {
|
||||
continue;
|
||||
};
|
||||
let pointer = format!("/{}", path.replace('.', "/"));
|
||||
for variant in variants {
|
||||
let mut candidate = baseline.clone();
|
||||
*candidate.pointer_mut(&pointer).unwrap() = variant.clone();
|
||||
let config: ProxyConfig = serde_json::from_value(candidate)
|
||||
.unwrap_or_else(|error| panic!("{path}={variant}: {error}"));
|
||||
let serialized = serde_json::to_value(config).unwrap();
|
||||
assert_eq!(serialized.pointer(&pointer), Some(variant), "{path}");
|
||||
}
|
||||
checked.insert(path, variants.len());
|
||||
}
|
||||
assert!(checked.len() >= 15);
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::*;
|
||||
use crate::api::allowed_methods_for_path;
|
||||
|
||||
fn unavailable() -> Availability {
|
||||
Availability {
|
||||
me_pool: Some(false),
|
||||
web_read: false,
|
||||
web_control: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn operation<'a>(data: &'a Value, id: &str) -> &'a Value {
|
||||
data["operations"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|entry| entry["id"] == id)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discovery_distinguishes_disabled_unavailable_and_read_only() {
|
||||
let mut config = ProxyConfig::default();
|
||||
config.server.api.read_only = true;
|
||||
config.server.api.minimal_runtime_enabled = false;
|
||||
config.server.api.runtime_edge_enabled = false;
|
||||
let data = serde_json::to_value(build_capabilities(&config, unavailable()).unwrap()).unwrap();
|
||||
let disabled = operation(&data, "stats_me_writers");
|
||||
assert_eq!(disabled["supported"], true);
|
||||
assert_eq!(disabled["enabled"], false);
|
||||
assert_eq!(disabled["disabled_reason"], "feature_disabled");
|
||||
assert_eq!(
|
||||
operation(&data, "runtime_upstream_quality")["enabled"],
|
||||
true
|
||||
);
|
||||
assert_eq!(operation(&data, "web_sessions")["enabled"], true);
|
||||
assert_eq!(operation(&data, "web_sessions")["available"], false);
|
||||
assert_eq!(operation(&data, "web_status")["available"], true);
|
||||
assert_eq!(operation(&data, "users_patch")["mutable"], false);
|
||||
assert_eq!(
|
||||
operation(&data, "users_patch")["mutation_blocked_reason"],
|
||||
"read_only"
|
||||
);
|
||||
assert_eq!(operation(&data, "config_schema")["available"], true);
|
||||
|
||||
config.server.api.read_only = false;
|
||||
config.server.api.minimal_runtime_enabled = true;
|
||||
config.server.api.runtime_edge_enabled = true;
|
||||
let available = Availability {
|
||||
me_pool: Some(true),
|
||||
web_read: true,
|
||||
web_control: false,
|
||||
};
|
||||
let data = serde_json::to_value(build_capabilities(&config, available).unwrap()).unwrap();
|
||||
assert_eq!(operation(&data, "stats_me_writers")["available"], true);
|
||||
assert_eq!(operation(&data, "web_sessions")["available"], true);
|
||||
assert_eq!(operation(&data, "web_drain")["available"], false);
|
||||
assert_eq!(operation(&data, "web_drain")["mutable"], true);
|
||||
assert_eq!(operation(&data, "users_patch")["mutable"], true);
|
||||
assert_eq!(operation(&data, "users_get")["mutable"], false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn busy_or_unsampled_sources_are_not_reported_as_healthy() {
|
||||
let config = ProxyConfig::default();
|
||||
let data = serde_json::to_value(
|
||||
build_capabilities(
|
||||
&config,
|
||||
Availability {
|
||||
me_pool: None,
|
||||
..unavailable()
|
||||
},
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(operation(&data, "runtime_me_quality")["available"].is_null());
|
||||
assert_eq!(
|
||||
operation(&data, "runtime_me_quality")["unavailable_reason"],
|
||||
"snapshot_busy"
|
||||
);
|
||||
assert!(operation(&data, "stats_upstreams")["available"].is_null());
|
||||
assert_eq!(
|
||||
operation(&data, "stats_upstreams")["unavailable_reason"],
|
||||
"availability_not_sampled"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discovery_does_not_serialize_configured_credentials_or_addresses() {
|
||||
let mut config = ProxyConfig::default();
|
||||
config.server.api.auth_header = "private-auth-sentinel".into();
|
||||
config.general.proxy_secret_url = Some("https://private-url-sentinel/secret".into());
|
||||
config.access.users.insert(
|
||||
"private-user-sentinel".into(),
|
||||
"private-secret-sentinel".into(),
|
||||
);
|
||||
config.upstreams = serde_json::from_value(json!([
|
||||
{"type":"socks5", "address":"private-address-sentinel:1080", "password":"private-password-sentinel"}
|
||||
])).unwrap();
|
||||
let caps = serde_json::to_string(&build_capabilities(&config, unavailable()).unwrap()).unwrap();
|
||||
let schema = serde_json::to_string(config_schema().unwrap()).unwrap();
|
||||
assert!(!caps.contains("sentinel"));
|
||||
assert!(!schema.contains("sentinel"));
|
||||
for secret in ProxyConfig::default().access.users.values() {
|
||||
assert!(!schema.contains(secret));
|
||||
}
|
||||
assert!(schema.len() < 1024 * 1024);
|
||||
assert!(caps.len() < 128 * 1024);
|
||||
}
|
||||
|
||||
fn example_path(path: &str) -> String {
|
||||
path.replace("{username}", "alice")
|
||||
.replace("{id}", "42")
|
||||
.replace(
|
||||
"{session_ref}",
|
||||
"ws1.00000000000000000000000000000000.0000000000000001",
|
||||
)
|
||||
.replace(
|
||||
"{operation_id}",
|
||||
"wo1.00000000000000000000000000000000.0000000000000001",
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn operation_catalog_matches_routing_methods() {
|
||||
let mut paths = BTreeMap::<String, BTreeSet<String>>::new();
|
||||
let mut ids = BTreeSet::new();
|
||||
for operation in operations().unwrap() {
|
||||
assert!(
|
||||
ids.insert(&operation.id),
|
||||
"duplicate operation: {}",
|
||||
operation.id
|
||||
);
|
||||
for path in std::iter::once(&operation.path).chain(&operation.aliases) {
|
||||
assert!(
|
||||
paths
|
||||
.entry(path.clone())
|
||||
.or_default()
|
||||
.insert(operation.method.clone())
|
||||
);
|
||||
let allowed = allowed_methods_for_path(&example_path(path))
|
||||
.unwrap_or_else(|| panic!("missing route: {path}"));
|
||||
assert!(
|
||||
allowed.split(", ").any(|method| method == operation.method),
|
||||
"{path}: {allowed}"
|
||||
);
|
||||
}
|
||||
}
|
||||
for (path, methods) in &paths {
|
||||
let allowed = allowed_methods_for_path(&example_path(path)).unwrap();
|
||||
assert_eq!(
|
||||
methods,
|
||||
&allowed.split(", ").map(str::to_owned).collect(),
|
||||
"{path}"
|
||||
);
|
||||
}
|
||||
// Both tables are independent: a newly dispatched fixed route cannot silently
|
||||
// disappear from discovery because a maintainer omitted its catalog entry.
|
||||
for source in [
|
||||
include_str!("../mod.rs"),
|
||||
include_str!("../handler.rs"),
|
||||
include_str!("../handler/read_routes.rs"),
|
||||
include_str!("../handler/fixed_routes.rs"),
|
||||
include_str!("../web_runtime.rs"),
|
||||
] {
|
||||
let pattern = regex::Regex::new(r#""(/v1/[^"{}]*|/web-status)""#).unwrap();
|
||||
for matched in pattern.captures_iter(source) {
|
||||
let path = &matched[1];
|
||||
if path.ends_with('/') || path.contains('*') {
|
||||
continue;
|
||||
}
|
||||
assert!(paths.contains_key(path), "unclassified route: {path}");
|
||||
}
|
||||
}
|
||||
assert_eq!(allowed_methods_for_path("/v1/config/schema"), Some("GET"));
|
||||
assert_eq!(allowed_methods_for_path("/v1/capabilities"), Some("GET"));
|
||||
assert!(reject_query(None).is_ok());
|
||||
assert!(reject_query(Some("include_secrets=true")).is_err());
|
||||
}
|
||||
@@ -15,6 +15,7 @@ pub(super) async fn handle(
|
||||
let runtime = shared.active_runtime.load_full();
|
||||
let previous_cache_generation = shared.cache_generation.swap(runtime.id, Ordering::AcqRel);
|
||||
if previous_cache_generation != runtime.id {
|
||||
// Entry generation checks also reject late writes from in-flight requests.
|
||||
*shared.minimal_cache.lock().await = None;
|
||||
*shared.runtime_edge_connections_cache.lock().await = None;
|
||||
}
|
||||
@@ -158,11 +159,45 @@ async fn dispatch(
|
||||
}
|
||||
|
||||
match (method.as_str(), normalized_path) {
|
||||
("GET" | "PATCH", "/v1/access/policy") => {
|
||||
if query.is_some_and(|query| !query.is_empty()) {
|
||||
return Err(ApiFailure::bad_request(
|
||||
"Access policy does not accept query parameters",
|
||||
));
|
||||
}
|
||||
let (data, revision) = if method == Method::GET {
|
||||
access_policy::read(shared).await?
|
||||
} else {
|
||||
if cfg.server.api.read_only {
|
||||
return Err(ApiFailure::new(
|
||||
StatusCode::FORBIDDEN,
|
||||
"read_only",
|
||||
"API runs in read-only mode",
|
||||
));
|
||||
}
|
||||
let expected = parse_if_match(req.headers());
|
||||
let runtime = config_edit::parse_runtime_match(req.headers())?;
|
||||
let body =
|
||||
read_json::<access_policy::PolicyPatch>(req.into_body(), body_limit).await?;
|
||||
access_policy::patch(body, expected, runtime, shared)
|
||||
.await
|
||||
.map_err(|error| {
|
||||
shared
|
||||
.runtime_events
|
||||
.record("api.access.policy.patch.failed", error.code);
|
||||
error
|
||||
})?
|
||||
};
|
||||
Ok(success_response(StatusCode::OK, data, revision))
|
||||
}
|
||||
("POST", "/v1/users") => {
|
||||
fixed_routes::create_user_route(req, shared, cfg, config_rx, request_id, body_limit)
|
||||
.await
|
||||
}
|
||||
("GET", "/v1/config") => fixed_routes::get_config_route(shared).await,
|
||||
("POST", "/v1/config/validate") => {
|
||||
fixed_routes::validate_config_route(req, shared, query, body_limit).await
|
||||
}
|
||||
("POST", "/v1/system/reload") => {
|
||||
fixed_routes::reload_route(req, shared, cfg, request_id, body_limit).await
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ pub(super) async fn create_user_route(
|
||||
}
|
||||
};
|
||||
let runtime_cfg = config_rx.borrow().clone();
|
||||
data.user.in_runtime = runtime_cfg.access.users.contains_key(&data.user.username);
|
||||
users::refresh_runtime_view(&mut data.user, &runtime_cfg);
|
||||
shared.runtime_events.record(
|
||||
"api.user.create.ok",
|
||||
format!("username={}", data.user.username),
|
||||
@@ -107,9 +107,18 @@ pub(super) async fn patch_config_route(
|
||||
));
|
||||
}
|
||||
let expected_revision = parse_if_match(req.headers());
|
||||
let expected_runtime = config_edit::parse_runtime_match(req.headers())?;
|
||||
let reload_request = ReloadRequest::from_query(query).map_err(ApiFailure::bad_request)?;
|
||||
let body = read_json::<serde_json::Value>(req.into_body(), body_limit).await?;
|
||||
match config_edit::patch_config(body, expected_revision, reload_request, shared).await {
|
||||
match config_edit::patch_config(
|
||||
body,
|
||||
expected_revision,
|
||||
expected_runtime,
|
||||
reload_request,
|
||||
shared,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(resp) => {
|
||||
let revision = resp.revision.clone();
|
||||
let status = if resp.reload.is_some() {
|
||||
@@ -127,3 +136,25 @@ pub(super) async fn patch_config_route(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn validate_config_route(
|
||||
req: Request<Incoming>,
|
||||
shared: &Arc<ApiShared>,
|
||||
query: Option<&str>,
|
||||
body_limit: usize,
|
||||
) -> Result<Response<Full<Bytes>>, ApiFailure> {
|
||||
let expected_revision = parse_if_match(req.headers());
|
||||
let expected_runtime = config_edit::parse_runtime_match(req.headers())?;
|
||||
let reload_request = ReloadRequest::from_query(query).map_err(ApiFailure::bad_request)?;
|
||||
let body = read_json::<serde_json::Value>(req.into_body(), body_limit).await?;
|
||||
let response = config_edit::validate_config(
|
||||
body,
|
||||
expected_revision,
|
||||
expected_runtime,
|
||||
reload_request,
|
||||
shared,
|
||||
)
|
||||
.await?;
|
||||
let revision = response.base_revision.clone();
|
||||
Ok(success_response(StatusCode::OK, response, revision))
|
||||
}
|
||||
|
||||
@@ -10,6 +10,24 @@ pub(super) async fn handle(
|
||||
) -> Result<Option<Response<Full<Bytes>>>, ApiFailure> {
|
||||
let api_cfg = &cfg.server.api;
|
||||
match (method.as_str(), normalized_path) {
|
||||
("GET", "/v1/config/state") => {
|
||||
Ok(super::super::config_state::response(shared, query).await?)
|
||||
}
|
||||
("GET", "/v1/capabilities") => {
|
||||
discovery::reject_query(query)?;
|
||||
let revision = current_revision(&shared.config_path).await?;
|
||||
let data = discovery::capabilities(shared, cfg)?;
|
||||
Ok(success_response(StatusCode::OK, data, revision))
|
||||
}
|
||||
("GET", "/v1/config/schema") => {
|
||||
discovery::reject_query(query)?;
|
||||
let revision = current_revision(&shared.config_path).await?;
|
||||
Ok(success_response(
|
||||
StatusCode::OK,
|
||||
discovery::config_schema()?,
|
||||
revision,
|
||||
))
|
||||
}
|
||||
("GET", "/web-status") => Ok(web_status::render(query, &shared.web_trace).await),
|
||||
("GET", "/v1/health") => {
|
||||
let revision = current_revision(&shared.config_path).await?;
|
||||
|
||||
@@ -60,7 +60,7 @@ pub(super) async fn handle(
|
||||
}
|
||||
};
|
||||
let runtime_cfg = config_rx.borrow().clone();
|
||||
data.in_runtime = runtime_cfg.access.users.contains_key(&data.username);
|
||||
users::refresh_runtime_view(&mut data, &runtime_cfg);
|
||||
shared
|
||||
.runtime_events
|
||||
.record("api.user.enable.ok", format!("username={}", base_user));
|
||||
@@ -102,7 +102,7 @@ pub(super) async fn handle(
|
||||
}
|
||||
};
|
||||
let runtime_cfg = config_rx.borrow().clone();
|
||||
data.in_runtime = runtime_cfg.access.users.contains_key(&data.username);
|
||||
users::refresh_runtime_view(&mut data, &runtime_cfg);
|
||||
shared
|
||||
.runtime_events
|
||||
.record("api.user.disable.ok", format!("username={}", base_user));
|
||||
@@ -229,7 +229,7 @@ pub(super) async fn handle(
|
||||
}
|
||||
};
|
||||
let runtime_cfg = config_rx.borrow().clone();
|
||||
data.user.in_runtime = runtime_cfg.access.users.contains_key(&data.user.username);
|
||||
users::refresh_runtime_view(&mut data.user, &runtime_cfg);
|
||||
shared.runtime_events.record(
|
||||
"api.user.rotate_secret.ok",
|
||||
format!("username={}", base_user),
|
||||
@@ -293,7 +293,7 @@ pub(super) async fn handle(
|
||||
}
|
||||
};
|
||||
let runtime_cfg = config_rx.borrow().clone();
|
||||
data.in_runtime = runtime_cfg.access.users.contains_key(&data.username);
|
||||
users::refresh_runtime_view(&mut data, &runtime_cfg);
|
||||
shared
|
||||
.runtime_events
|
||||
.record("api.user.patch.ok", format!("username={}", data.username));
|
||||
|
||||
@@ -33,6 +33,7 @@ pub(super) fn error_response(request_id: u64, failure: ApiFailure) -> hyper::Res
|
||||
error: ErrorBody {
|
||||
code: failure.code,
|
||||
message: failure.message,
|
||||
details: failure.details,
|
||||
},
|
||||
request_id,
|
||||
};
|
||||
|
||||
+21
-1
@@ -36,13 +36,19 @@ use crate::transport::middle_proxy::MePool;
|
||||
use crate::web::control::WebRuntimePublication;
|
||||
use crate::web::trace::WebTraceStore;
|
||||
|
||||
mod access_policy;
|
||||
mod config_edit;
|
||||
mod config_projection;
|
||||
mod config_state;
|
||||
pub(crate) mod config_store;
|
||||
mod discovery;
|
||||
mod events;
|
||||
mod http_utils;
|
||||
// Authenticated request admission and route dispatch.
|
||||
mod handler;
|
||||
mod model;
|
||||
#[cfg(test)]
|
||||
mod observability_cache_tests;
|
||||
mod patch;
|
||||
#[cfg(test)]
|
||||
mod reload_tests;
|
||||
@@ -112,6 +118,8 @@ pub(super) struct ApiRuntimeState {
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct ApiShared {
|
||||
/// Generation pinned by this request, including cache reads and publication.
|
||||
pub(super) runtime_generation: u64,
|
||||
pub(super) stats: Arc<Stats>,
|
||||
pub(super) ip_tracker: Arc<UserIpTracker>,
|
||||
pub(super) me_pool: Arc<RwLock<Option<Arc<MePool>>>>,
|
||||
@@ -120,6 +128,8 @@ pub(super) struct ApiShared {
|
||||
pub(super) quota_state: Arc<QuotaStateOwner>,
|
||||
pub(super) detected_ips_rx: watch::Receiver<(Option<IpAddr>, Option<IpAddr>)>,
|
||||
pub(super) mutation_lock: Arc<Mutex<()>>,
|
||||
pub(super) config_preflight_slots: Arc<Semaphore>,
|
||||
pub(super) config_state_slots: Arc<Semaphore>,
|
||||
pub(super) minimal_cache: Arc<Mutex<Option<MinimalCacheEntry>>>,
|
||||
pub(super) runtime_edge_connections_cache: Arc<Mutex<Option<EdgeConnectionsCacheEntry>>>,
|
||||
pub(super) runtime_edge_recompute_lock: Arc<Mutex<()>>,
|
||||
@@ -148,6 +158,7 @@ impl ApiShared {
|
||||
|
||||
fn for_runtime(&self, runtime: &RuntimeGeneration) -> Self {
|
||||
Self {
|
||||
runtime_generation: runtime.id,
|
||||
stats: runtime.stats.clone(),
|
||||
ip_tracker: runtime.ip_tracker.clone(),
|
||||
me_pool: runtime.me_pool_runtime.clone(),
|
||||
@@ -156,6 +167,8 @@ impl ApiShared {
|
||||
quota_state: self.quota_state.clone(),
|
||||
detected_ips_rx: self.detected_ips_rx.clone(),
|
||||
mutation_lock: self.mutation_lock.clone(),
|
||||
config_preflight_slots: self.config_preflight_slots.clone(),
|
||||
config_state_slots: self.config_state_slots.clone(),
|
||||
minimal_cache: self.minimal_cache.clone(),
|
||||
runtime_edge_connections_cache: self.runtime_edge_connections_cache.clone(),
|
||||
runtime_edge_recompute_lock: self.runtime_edge_recompute_lock.clone(),
|
||||
@@ -264,6 +277,9 @@ fn allowed_methods_for_path(path: &str) -> Option<&'static str> {
|
||||
}
|
||||
match path {
|
||||
"/v1/health"
|
||||
| "/v1/capabilities"
|
||||
| "/v1/config/schema"
|
||||
| "/v1/config/state"
|
||||
| "/v1/health/ready"
|
||||
| "/v1/system/info"
|
||||
| "/v1/runtime/gates"
|
||||
@@ -294,8 +310,9 @@ fn allowed_methods_for_path(path: &str) -> Option<&'static str> {
|
||||
| "/v1/stats/users"
|
||||
| "/web-status" => Some(ALLOW_GET),
|
||||
"/v1/system/reload" => Some(ALLOW_POST),
|
||||
"/v1/config/validate" => Some(ALLOW_POST),
|
||||
"/v1/users" => Some(ALLOW_GET_POST),
|
||||
"/v1/config" => Some(ALLOW_GET_PATCH),
|
||||
"/v1/config" | "/v1/access/policy" => Some(ALLOW_GET_PATCH),
|
||||
_ if user_action_route_matches(path, "/reset-quota") => Some(ALLOW_POST),
|
||||
_ if user_action_route_matches(path, "/rotate-secret") => Some(ALLOW_POST),
|
||||
_ if user_action_route_matches(path, "/enable") => Some(ALLOW_POST),
|
||||
@@ -365,6 +382,7 @@ pub(crate) async fn serve(
|
||||
});
|
||||
|
||||
let shared = Arc::new(ApiShared {
|
||||
runtime_generation: active_runtime.load().id,
|
||||
stats,
|
||||
ip_tracker,
|
||||
me_pool,
|
||||
@@ -373,6 +391,8 @@ pub(crate) async fn serve(
|
||||
quota_state,
|
||||
detected_ips_rx,
|
||||
mutation_lock: Arc::new(Mutex::new(())),
|
||||
config_preflight_slots: Arc::new(Semaphore::new(2)),
|
||||
config_state_slots: Arc::new(Semaphore::new(2)),
|
||||
minimal_cache: Arc::new(Mutex::new(None)),
|
||||
runtime_edge_connections_cache: Arc::new(Mutex::new(None)),
|
||||
runtime_edge_recompute_lock: Arc::new(Mutex::new(())),
|
||||
|
||||
@@ -16,6 +16,7 @@ pub(super) struct ApiFailure {
|
||||
pub(super) code: &'static str,
|
||||
pub(super) message: String,
|
||||
pub(super) allow: Option<&'static str>,
|
||||
pub(super) details: Vec<FieldIssue>,
|
||||
}
|
||||
|
||||
impl ApiFailure {
|
||||
@@ -25,6 +26,7 @@ impl ApiFailure {
|
||||
code,
|
||||
message: message.into(),
|
||||
allow: None,
|
||||
details: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,14 +44,25 @@ impl ApiFailure {
|
||||
code: "method_not_allowed",
|
||||
message: "Unsupported HTTP method for this route".to_string(),
|
||||
allow: Some(allow),
|
||||
details: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Value-free diagnostics shared by config preview, mutation and validation.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub(super) struct FieldIssue {
|
||||
pub(super) path: String,
|
||||
pub(super) code: &'static str,
|
||||
pub(super) message: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub(super) struct ErrorBody {
|
||||
pub(super) code: &'static str,
|
||||
pub(super) message: String,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub(super) details: Vec<FieldIssue>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
|
||||
@@ -28,6 +28,9 @@ pub(in crate::api) struct UserInfo {
|
||||
pub(in crate::api) rate_limit_up_bps: Option<u64>,
|
||||
pub(in crate::api) rate_limit_down_bps: Option<u64>,
|
||||
pub(in crate::api) max_unique_ips: Option<usize>,
|
||||
pub(in crate::api) limits: UserLimitState,
|
||||
pub(in crate::api) source_deny: Vec<ipnetwork::IpNetwork>,
|
||||
pub(in crate::api) source_deny_status: SourceDenyState,
|
||||
pub(in crate::api) current_connections: u64,
|
||||
pub(in crate::api) active_unique_ips: usize,
|
||||
pub(in crate::api) active_unique_ips_list: Vec<IpAddr>,
|
||||
@@ -37,6 +40,37 @@ pub(in crate::api) struct UserInfo {
|
||||
pub(in crate::api) links: UserLinks,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub(in crate::api) struct InheritedLimit {
|
||||
pub(in crate::api) value: Option<usize>,
|
||||
pub(in crate::api) configured_override: Option<usize>,
|
||||
pub(in crate::api) global_value: usize,
|
||||
pub(in crate::api) origin: &'static str,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub(in crate::api) struct UserLimitSnapshot {
|
||||
pub(in crate::api) max_tcp_conns: InheritedLimit,
|
||||
pub(in crate::api) max_unique_ips: InheritedLimit,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub(in crate::api) struct UserLimitState {
|
||||
pub(in crate::api) desired: UserLimitSnapshot,
|
||||
pub(in crate::api) effective: Option<UserLimitSnapshot>,
|
||||
pub(in crate::api) effective_scope: &'static str,
|
||||
pub(in crate::api) subsystem_convergence: &'static str,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub(in crate::api) struct SourceDenyState {
|
||||
pub(in crate::api) effective: Option<Vec<ipnetwork::IpNetwork>>,
|
||||
pub(in crate::api) runtime_reload_required: Option<bool>,
|
||||
pub(in crate::api) apply_mode: &'static str,
|
||||
pub(in crate::api) reload_endpoint: &'static str,
|
||||
pub(in crate::api) effective_scope: &'static str,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub(in crate::api) struct UserActiveIps {
|
||||
pub(in crate::api) username: String,
|
||||
@@ -94,6 +128,9 @@ pub(in crate::api) struct CreateUserRequest {
|
||||
pub(in crate::api) rate_limit_down_bps: Option<u64>,
|
||||
pub(in crate::api) max_unique_ips: Option<usize>,
|
||||
pub(in crate::api) enabled: Option<bool>,
|
||||
/// Omission retains any orphan rule; null explicitly removes it on recreation.
|
||||
#[serde(default, deserialize_with = "patch_field")]
|
||||
pub(in crate::api) source_deny: Patch<Vec<ipnetwork::IpNetwork>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -118,6 +155,8 @@ pub(in crate::api) struct PatchUserRequest {
|
||||
pub(in crate::api) max_unique_ips: Patch<usize>,
|
||||
#[serde(default, deserialize_with = "patch_field")]
|
||||
pub(in crate::api) enabled: Patch<bool>,
|
||||
#[serde(default, deserialize_with = "patch_field")]
|
||||
pub(in crate::api) source_deny: Patch<Vec<ipnetwork::IpNetwork>>,
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize)]
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
use super::*;
|
||||
use crate::api::discovery::http_tests::Fixture;
|
||||
use crate::maestro::generation::test_runtime_generation;
|
||||
use std::time::Instant;
|
||||
|
||||
fn enabled_config(fixture: &Fixture) -> ProxyConfig {
|
||||
let mut cfg = (*fixture
|
||||
.shared
|
||||
.active_runtime
|
||||
.load()
|
||||
.config_rx
|
||||
.borrow()
|
||||
.clone())
|
||||
.clone();
|
||||
cfg.server.api.minimal_runtime_enabled = true;
|
||||
cfg.server.api.minimal_runtime_cache_ttl_ms = 60_000;
|
||||
cfg.server.api.runtime_edge_enabled = true;
|
||||
cfg.server.api.runtime_edge_cache_ttl_ms = 60_000;
|
||||
cfg.server.api.runtime_edge_top_n = 7;
|
||||
cfg
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn late_edge_recompute_cannot_contaminate_new_generation_reads() {
|
||||
let fixture = Fixture::new(false);
|
||||
let old_cfg = enabled_config(&fixture);
|
||||
let old_runtime = test_runtime_generation(1, old_cfg.clone());
|
||||
let old_request = fixture.shared.for_runtime(&old_runtime);
|
||||
let (release, resume) = tokio::sync::oneshot::channel();
|
||||
// A request already pinned to generation 1 finishes after generation 2's
|
||||
// handler has invalidated the shared caches.
|
||||
let pending = tokio::spawn(async move {
|
||||
resume.await.unwrap();
|
||||
build_runtime_connections_summary_data(&old_request, &old_cfg).await
|
||||
});
|
||||
let mut new_cfg = enabled_config(&fixture);
|
||||
new_cfg.server.api.runtime_edge_top_n = 1;
|
||||
fixture
|
||||
.shared
|
||||
.active_runtime
|
||||
.store(test_runtime_generation(2, new_cfg));
|
||||
assert_eq!(fixture.request("GET", "/v1/health", true).await.0, 200);
|
||||
release.send(()).unwrap();
|
||||
assert_eq!(pending.await.unwrap().data.unwrap().top.limit, 7);
|
||||
|
||||
let mut reads = tokio::task::JoinSet::new();
|
||||
let fixture = Arc::new(fixture);
|
||||
for _ in 0..16 {
|
||||
let fixture = fixture.clone();
|
||||
reads.spawn(async move {
|
||||
let (status, _, body) = fixture
|
||||
.request("GET", "/v1/runtime/connections/summary", true)
|
||||
.await;
|
||||
assert_eq!(status, 200);
|
||||
assert_eq!(body["data"]["enabled"], true);
|
||||
if let Some(payload) = body["data"].get("data") {
|
||||
assert_eq!(payload["top"]["limit"], 1, "{body}");
|
||||
assert_eq!(payload["cache"]["ttl_ms"], 60_000);
|
||||
} else {
|
||||
assert_eq!(body["data"]["reason"], "source_unavailable");
|
||||
}
|
||||
});
|
||||
}
|
||||
while let Some(result) = reads.join_next().await {
|
||||
result.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn late_minimal_cache_publication_is_not_served_by_new_generation() {
|
||||
let fixture = Fixture::new(false);
|
||||
let cfg = enabled_config(&fixture);
|
||||
let old_request = fixture
|
||||
.shared
|
||||
.for_runtime(&test_runtime_generation(1, cfg.clone()));
|
||||
let payload = build_minimal_all_data(&old_request, &cfg.server.api)
|
||||
.await
|
||||
.data
|
||||
.unwrap();
|
||||
fixture
|
||||
.shared
|
||||
.active_runtime
|
||||
.store(test_runtime_generation(2, cfg));
|
||||
assert_eq!(fixture.request("GET", "/v1/health", true).await.0, 200);
|
||||
// Model the publication of a completed old-generation pool snapshot after
|
||||
// invalidation. The new generation has no pool and must report that fact.
|
||||
*fixture.shared.minimal_cache.lock().await = Some(MinimalCacheEntry {
|
||||
generation: 1,
|
||||
expires_at: Instant::now() + Duration::from_secs(60),
|
||||
payload,
|
||||
generated_at_epoch_secs: 42,
|
||||
});
|
||||
let (status, _, body) = fixture.request("GET", "/v1/stats/minimal/all", true).await;
|
||||
assert_eq!(status, 200);
|
||||
assert_eq!(body["data"]["reason"], "source_unavailable", "{body}");
|
||||
assert_ne!(body["data"]["generated_at_epoch_secs"], 42);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn edge_cache_respects_ttl_zero_expiry_top_n_and_recompute_contention() {
|
||||
let fixture = Fixture::new(false);
|
||||
let mut cfg = enabled_config(&fixture);
|
||||
cfg.server.api.runtime_edge_top_n = 1;
|
||||
let runtime = test_runtime_generation(1, cfg.clone());
|
||||
let request = fixture.shared.for_runtime(&runtime);
|
||||
request.stats.add_user_octets_from("alice", 20);
|
||||
request.stats.add_user_octets_from("bob", 10);
|
||||
let fresh = build_runtime_connections_summary_data(&request, &cfg)
|
||||
.await
|
||||
.data
|
||||
.unwrap();
|
||||
assert!(!fresh.cache.served_from_cache);
|
||||
assert_eq!(fresh.top.by_throughput.len(), 1);
|
||||
assert_eq!(fresh.top.by_throughput[0].username, "alice");
|
||||
request.stats.add_user_octets_from("bob", 100);
|
||||
let cached = build_runtime_connections_summary_data(&request, &cfg)
|
||||
.await
|
||||
.data
|
||||
.unwrap();
|
||||
assert!(cached.cache.served_from_cache);
|
||||
assert!(!cached.cache.stale_cache_used);
|
||||
assert_eq!(cached.top.by_throughput[0].username, "alice");
|
||||
request
|
||||
.runtime_edge_connections_cache
|
||||
.lock()
|
||||
.await
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.expires_at = Instant::now();
|
||||
let guard = request.runtime_edge_recompute_lock.lock().await;
|
||||
let stale = build_runtime_connections_summary_data(&request, &cfg)
|
||||
.await
|
||||
.data
|
||||
.unwrap();
|
||||
assert!(stale.cache.stale_cache_used);
|
||||
let new_request = fixture
|
||||
.shared
|
||||
.for_runtime(&test_runtime_generation(2, cfg.clone()));
|
||||
let unavailable = build_runtime_connections_summary_data(&new_request, &cfg).await;
|
||||
assert_eq!(unavailable.reason, Some("source_unavailable"));
|
||||
assert!(unavailable.data.is_none());
|
||||
cfg.server.api.runtime_edge_cache_ttl_ms = 0;
|
||||
let zero = build_runtime_connections_summary_data(&request, &cfg).await;
|
||||
assert_eq!(zero.reason, Some("source_unavailable"));
|
||||
assert!(zero.data.is_none());
|
||||
drop(guard);
|
||||
for _ in 0..2 {
|
||||
let uncached = build_runtime_connections_summary_data(&request, &cfg)
|
||||
.await
|
||||
.data
|
||||
.unwrap();
|
||||
assert_eq!(uncached.cache.ttl_ms, 0);
|
||||
assert!(!uncached.cache.served_from_cache);
|
||||
assert_eq!(uncached.top.by_throughput[0].username, "bob");
|
||||
}
|
||||
cfg.server.api.runtime_edge_cache_ttl_ms = 60_000;
|
||||
let refreshed = build_runtime_connections_summary_data(&request, &cfg)
|
||||
.await
|
||||
.data
|
||||
.unwrap();
|
||||
assert!(!refreshed.cache.served_from_cache);
|
||||
assert_eq!(refreshed.top.by_throughput[0].username, "bob");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn minimal_cache_checks_generation_expiry_and_zero_ttl() {
|
||||
let fixture = Fixture::new(false);
|
||||
let mut cfg = enabled_config(&fixture);
|
||||
let request = fixture
|
||||
.shared
|
||||
.for_runtime(&test_runtime_generation(1, cfg.clone()));
|
||||
let payload = build_minimal_all_data(&request, &cfg.server.api)
|
||||
.await
|
||||
.data
|
||||
.unwrap();
|
||||
*request.minimal_cache.lock().await = Some(MinimalCacheEntry {
|
||||
generation: 1,
|
||||
expires_at: Instant::now() + Duration::from_secs(60),
|
||||
payload,
|
||||
generated_at_epoch_secs: 42,
|
||||
});
|
||||
let cached = build_minimal_all_data(&request, &cfg.server.api).await;
|
||||
assert_eq!(cached.generated_at_epoch_secs, 42);
|
||||
assert!(cached.reason.is_none());
|
||||
cfg.server.api.minimal_runtime_cache_ttl_ms = 0;
|
||||
assert_eq!(
|
||||
build_minimal_all_data(&request, &cfg.server.api)
|
||||
.await
|
||||
.reason,
|
||||
Some("source_unavailable")
|
||||
);
|
||||
cfg.server.api.minimal_runtime_cache_ttl_ms = 60_000;
|
||||
request
|
||||
.minimal_cache
|
||||
.lock()
|
||||
.await
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.expires_at = Instant::now();
|
||||
assert_eq!(
|
||||
build_minimal_all_data(&request, &cfg.server.api)
|
||||
.await
|
||||
.reason,
|
||||
Some("source_unavailable")
|
||||
);
|
||||
}
|
||||
@@ -70,6 +70,7 @@ pub(super) struct RuntimeEdgeConnectionsSummaryData {
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct EdgeConnectionsCacheEntry {
|
||||
pub(super) generation: u64,
|
||||
pub(super) expires_at: Instant,
|
||||
pub(super) payload: RuntimeEdgeConnectionsSummaryPayload,
|
||||
pub(super) generated_at_epoch_secs: u64,
|
||||
@@ -270,6 +271,7 @@ async fn get_connections_payload_cached(
|
||||
let now = Instant::now();
|
||||
let cached = shared.runtime_edge_connections_cache.lock().await.clone();
|
||||
if let Some(entry) = cached
|
||||
&& entry.generation == shared.runtime_generation
|
||||
&& now < entry.expires_at
|
||||
{
|
||||
let mut payload = entry.payload;
|
||||
@@ -281,7 +283,10 @@ async fn get_connections_payload_cached(
|
||||
|
||||
let Ok(_guard) = shared.runtime_edge_recompute_lock.try_lock() else {
|
||||
let cached = shared.runtime_edge_connections_cache.lock().await.clone();
|
||||
if let Some(entry) = cached {
|
||||
if let Some(entry) = cached
|
||||
&& cache_ttl_ms > 0
|
||||
&& entry.generation == shared.runtime_generation
|
||||
{
|
||||
let mut payload = entry.payload;
|
||||
payload.cache.served_from_cache = true;
|
||||
payload.cache.stale_cache_used = true;
|
||||
@@ -295,6 +300,7 @@ async fn get_connections_payload_cached(
|
||||
|
||||
if cache_ttl_ms > 0 {
|
||||
let entry = EdgeConnectionsCacheEntry {
|
||||
generation: shared.runtime_generation,
|
||||
expires_at: Instant::now() + Duration::from_millis(cache_ttl_ms),
|
||||
payload: payload.clone(),
|
||||
generated_at_epoch_secs,
|
||||
|
||||
@@ -19,6 +19,7 @@ const SOURCE_UNAVAILABLE_REASON: &str = "source_unavailable";
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct MinimalCacheEntry {
|
||||
pub(super) generation: u64,
|
||||
pub(super) expires_at: Instant,
|
||||
pub(super) payload: MinimalAllPayload,
|
||||
pub(super) generated_at_epoch_secs: u64,
|
||||
@@ -342,6 +343,7 @@ async fn get_minimal_payload_cached(
|
||||
let now = Instant::now();
|
||||
let cached = shared.minimal_cache.lock().await.clone();
|
||||
if let Some(entry) = cached
|
||||
&& entry.generation == shared.runtime_generation
|
||||
&& now < entry.expires_at
|
||||
{
|
||||
return Some((entry.generated_at_epoch_secs, entry.payload));
|
||||
@@ -522,6 +524,7 @@ async fn get_minimal_payload_cached(
|
||||
|
||||
if cache_ttl_ms > 0 {
|
||||
let entry = MinimalCacheEntry {
|
||||
generation: shared.runtime_generation,
|
||||
expires_at: Instant::now() + Duration::from_millis(cache_ttl_ms),
|
||||
payload: payload.clone(),
|
||||
generated_at_epoch_secs,
|
||||
|
||||
+7
-2
@@ -11,7 +11,7 @@ use crate::stats::Stats;
|
||||
use super::ApiShared;
|
||||
use super::config_store::{
|
||||
AccessSection, current_revision, load_config_for_mutation,
|
||||
save_access_sections_to_disk_if_revision,
|
||||
save_access_sections_and_fields_if_revision, save_access_sections_to_disk_if_revision,
|
||||
};
|
||||
use super::model::{
|
||||
ApiFailure, CreateUserRequest, CreateUserResponse, PatchUserRequest, RotateSecretRequest,
|
||||
@@ -24,17 +24,22 @@ use super::patch::Patch;
|
||||
mod create;
|
||||
mod lifecycle;
|
||||
mod links;
|
||||
mod source_deny;
|
||||
mod update;
|
||||
mod view;
|
||||
|
||||
pub(super) use create::create_user;
|
||||
pub(super) use lifecycle::{delete_user, rotate_secret};
|
||||
use links::{build_user_links, empty_user_links};
|
||||
use source_deny::apply_source_deny;
|
||||
pub(super) use update::{patch_user, set_user_enabled};
|
||||
pub(super) use view::{build_user_quota_list, users_from_config};
|
||||
pub(super) use view::{build_user_quota_list, refresh_runtime_view, users_from_config};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod period_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod source_deny_tests;
|
||||
|
||||
+4
-28
@@ -119,6 +119,7 @@ async fn create_user_to_completion(
|
||||
.user_quota_periods
|
||||
.insert(body.username.clone(), period);
|
||||
}
|
||||
let source_deny_edits = apply_source_deny(&mut cfg, &body.username, body.source_deny)?;
|
||||
cfg.validate()
|
||||
.map_err(|e| ApiFailure::bad_request(format!("config validation failed: {}", e)))?;
|
||||
|
||||
@@ -154,10 +155,11 @@ async fn create_user_to_completion(
|
||||
.prepare_user_creation_locked(&body.username, quota_guard)
|
||||
.await
|
||||
.map_err(|error| ApiFailure::internal(format!("failed to prepare user quota: {error}")))?;
|
||||
let revision = save_access_sections_to_disk_if_revision(
|
||||
let revision = save_access_sections_and_fields_if_revision(
|
||||
&shared.config_path,
|
||||
&cfg,
|
||||
&touched_sections,
|
||||
source_deny_edits,
|
||||
Some(&base_revision),
|
||||
)
|
||||
.await?;
|
||||
@@ -196,33 +198,7 @@ async fn create_user_to_completion(
|
||||
let user = users
|
||||
.into_iter()
|
||||
.find(|entry| entry.username == body.username)
|
||||
.unwrap_or(UserInfo {
|
||||
username: body.username.clone(),
|
||||
enabled: cfg.access.is_user_enabled(&body.username),
|
||||
in_runtime: false,
|
||||
user_ad_tag: None,
|
||||
max_tcp_conns: cfg
|
||||
.access
|
||||
.user_max_tcp_conns
|
||||
.get(&body.username)
|
||||
.copied()
|
||||
.filter(|limit| *limit > 0)
|
||||
.or((cfg.access.user_max_tcp_conns_global_each > 0)
|
||||
.then_some(cfg.access.user_max_tcp_conns_global_each)),
|
||||
expiration_rfc3339: None,
|
||||
data_quota_bytes: None,
|
||||
quota_period: body.quota_period,
|
||||
rate_limit_up_bps: body.rate_limit_up_bps.filter(|limit| *limit > 0),
|
||||
rate_limit_down_bps: body.rate_limit_down_bps.filter(|limit| *limit > 0),
|
||||
max_unique_ips: updated_limit,
|
||||
current_connections: 0,
|
||||
active_unique_ips: 0,
|
||||
active_unique_ips_list: Vec::new(),
|
||||
recent_unique_ips: 0,
|
||||
recent_unique_ips_list: Vec::new(),
|
||||
total_octets: 0,
|
||||
links: build_user_links(&cfg, &secret, detected_ip_v4, detected_ip_v6),
|
||||
});
|
||||
.ok_or_else(|| ApiFailure::internal("Created user is missing from config view"))?;
|
||||
|
||||
Ok((CreateUserResponse { user, secret }, revision))
|
||||
}
|
||||
|
||||
@@ -49,6 +49,7 @@ impl Fixture {
|
||||
mutable.proxy_shared = proxy_shared.clone();
|
||||
mutable.config_rx = config_rx;
|
||||
let shared = ApiShared {
|
||||
runtime_generation: runtime.id,
|
||||
stats,
|
||||
ip_tracker: runtime.ip_tracker.clone(),
|
||||
me_pool: runtime.me_pool_runtime.clone(),
|
||||
@@ -57,6 +58,8 @@ impl Fixture {
|
||||
quota_state: QuotaStateOwner::new(dir.path().join("quota.json"), store.clone()),
|
||||
detected_ips_rx: watch::channel((None, None)).1,
|
||||
mutation_lock: Arc::new(Mutex::new(())),
|
||||
config_preflight_slots: Arc::new(tokio::sync::Semaphore::new(2)),
|
||||
config_state_slots: Arc::new(tokio::sync::Semaphore::new(2)),
|
||||
minimal_cache: Arc::new(Mutex::new(None)),
|
||||
runtime_edge_connections_cache: Arc::new(Mutex::new(None)),
|
||||
runtime_edge_recompute_lock: Arc::new(Mutex::new(())),
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
use super::*;
|
||||
use crate::api::config_store::FieldEdit;
|
||||
|
||||
/// Source-deny intent changes only desired TOML; generation admission remains untouched.
|
||||
pub(super) fn apply_source_deny(
|
||||
cfg: &mut ProxyConfig,
|
||||
username: &str,
|
||||
patch: Patch<Vec<ipnetwork::IpNetwork>>,
|
||||
) -> Result<Vec<FieldEdit>, ApiFailure> {
|
||||
let value = match patch {
|
||||
Patch::Unchanged => return Ok(Vec::new()),
|
||||
Patch::Remove => {
|
||||
cfg.access.user_source_deny.remove(username);
|
||||
None
|
||||
}
|
||||
Patch::Set(nets) => {
|
||||
let value = toml::Value::try_from(&nets)
|
||||
.map_err(|_| ApiFailure::internal("Cannot render source-deny list"))?;
|
||||
cfg.access
|
||||
.user_source_deny
|
||||
.insert(username.to_owned(), nets);
|
||||
Some(value)
|
||||
}
|
||||
};
|
||||
Ok(vec![FieldEdit::new(
|
||||
&["access", "user_source_deny", username],
|
||||
value,
|
||||
)])
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
use super::*;
|
||||
use crate::api::discovery::http_tests::Fixture;
|
||||
use crate::maestro::generation::test_runtime_generation;
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
|
||||
const USERS: &str = "[general]\nconfig_strict=true\n[access.users]\nalice='0123456789abcdef0123456789abcdef'\nbob='abcdef0123456789abcdef0123456789'\n";
|
||||
|
||||
fn fixture(extra: &str) -> Fixture {
|
||||
let fixture = Fixture::new(false);
|
||||
std::fs::write(&fixture.shared.config_path, format!("{USERS}{extra}")).unwrap();
|
||||
publish(&fixture, 1);
|
||||
fixture
|
||||
}
|
||||
|
||||
fn publish(fixture: &Fixture, generation: u64) {
|
||||
let mut config = ProxyConfig::load(&fixture.shared.config_path).unwrap();
|
||||
config.server.api = fixture
|
||||
.shared
|
||||
.active_runtime
|
||||
.load()
|
||||
.config()
|
||||
.server
|
||||
.api
|
||||
.clone();
|
||||
config.server.api.read_only = false;
|
||||
fixture
|
||||
.shared
|
||||
.active_runtime
|
||||
.store(test_runtime_generation(generation, config));
|
||||
}
|
||||
|
||||
async fn patch(fixture: &Fixture, username: &str, body: Value) -> Value {
|
||||
let (status, _, result) = fixture
|
||||
.request_body(
|
||||
"PATCH",
|
||||
&format!("/v1/users/{username}"),
|
||||
true,
|
||||
Some(&body),
|
||||
&[],
|
||||
)
|
||||
.await;
|
||||
assert!([200, 202].contains(&status), "{result}");
|
||||
result
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn source_deny_strict_create_get_replace_clear_and_reload_status() {
|
||||
let fixture = fixture("");
|
||||
let (status, _, created) = fixture
|
||||
.request_body(
|
||||
"POST",
|
||||
"/v1/users",
|
||||
true,
|
||||
Some(&json!({
|
||||
"username":"alice.two", "source_deny":["192.0.2.0/24","2001:db8::/32"]})),
|
||||
&[],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 202, "{created}");
|
||||
assert_eq!(
|
||||
created["data"]["user"]["source_deny_status"]["runtime_reload_required"],
|
||||
true
|
||||
);
|
||||
assert_eq!(
|
||||
created["data"]["user"]["source_deny_status"]["reload_endpoint"],
|
||||
"POST /v1/system/reload"
|
||||
);
|
||||
let (_, _, get) = fixture.request("GET", "/v1/users/alice.two", true).await;
|
||||
assert_eq!(
|
||||
get["data"]["source_deny"],
|
||||
json!(["192.0.2.0/24", "2001:db8::/32"])
|
||||
);
|
||||
let cfg = ProxyConfig::load(&fixture.shared.config_path).unwrap();
|
||||
assert!(
|
||||
cfg.access
|
||||
.is_user_source_ip_denied("alice.two", "192.0.2.12".parse().unwrap())
|
||||
);
|
||||
assert!(
|
||||
cfg.access
|
||||
.is_user_source_ip_denied("alice.two", "2001:db8::12".parse().unwrap())
|
||||
);
|
||||
assert!(
|
||||
!cfg.access
|
||||
.is_user_source_ip_denied("alice.two", "198.51.100.12".parse().unwrap())
|
||||
);
|
||||
publish(&fixture, 2);
|
||||
let (_, _, get) = fixture.request("GET", "/v1/users/alice.two", true).await;
|
||||
assert_eq!(
|
||||
get["data"]["source_deny_status"]["runtime_reload_required"],
|
||||
false
|
||||
);
|
||||
for value in [json!(["203.0.113.0/24"]), json!([]), Value::Null] {
|
||||
let body = patch(&fixture, "alice.two", json!({"source_deny":value})).await;
|
||||
assert_eq!(
|
||||
body["data"]["source_deny_status"]["runtime_reload_required"],
|
||||
true
|
||||
);
|
||||
let cfg = ProxyConfig::load(&fixture.shared.config_path).unwrap();
|
||||
assert_eq!(
|
||||
cfg.access.user_source_deny.contains_key("alice.two"),
|
||||
!value.is_null()
|
||||
);
|
||||
assert_eq!(
|
||||
body["data"]["source_deny"],
|
||||
if value.is_null() { json!([]) } else { value }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn source_deny_delete_retains_rules_and_recreation_can_remove_them_explicitly() {
|
||||
let fixture = fixture(
|
||||
"[access.user_source_deny]\nalice=['192.0.2.0/24']\nbob=['2001:db8::/32'] # retain bob\n",
|
||||
);
|
||||
for clear in [false, true] {
|
||||
let (status, _, deleted) = fixture.request("DELETE", "/v1/users/alice", true).await;
|
||||
assert!([200, 202].contains(&status), "{deleted}");
|
||||
let cfg = ProxyConfig::load(&fixture.shared.config_path).unwrap();
|
||||
assert_eq!(cfg.access.user_source_deny["alice"].len(), 1);
|
||||
let mut body = json!({"username":"alice"});
|
||||
if clear {
|
||||
body["source_deny"] = Value::Null;
|
||||
}
|
||||
let (status, _, created) = fixture
|
||||
.request_body("POST", "/v1/users", true, Some(&body), &[])
|
||||
.await;
|
||||
assert!([201, 202].contains(&status), "{created}");
|
||||
let user = &created["data"]["user"];
|
||||
assert_eq!(
|
||||
user["source_deny"],
|
||||
if clear {
|
||||
json!([])
|
||||
} else {
|
||||
json!(["192.0.2.0/24"])
|
||||
}
|
||||
);
|
||||
assert_eq!(user["source_deny_status"]["runtime_reload_required"], clear);
|
||||
assert!(
|
||||
std::fs::read_to_string(&fixture.shared.config_path)
|
||||
.unwrap()
|
||||
.contains("bob=['2001:db8::/32'] # retain bob")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn source_deny_edits_exact_included_owner_and_rejects_cross_file_user_patch() {
|
||||
let fixture = fixture("");
|
||||
let root = &fixture.shared.config_path;
|
||||
let include = root.with_file_name("deny.toml");
|
||||
let root_text = format!("include = \"deny.toml\"\n{USERS}");
|
||||
let include_text = "[access.user_source_deny]\nalice=['192.0.2.0/24']\n'bob'= ['2001:db8::/32'] # keep literal\n";
|
||||
std::fs::write(root, &root_text).unwrap();
|
||||
std::fs::write(&include, include_text).unwrap();
|
||||
patch(
|
||||
&fixture,
|
||||
"alice",
|
||||
json!({"source_deny":["198.51.100.0/24"]}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(std::fs::read_to_string(root).unwrap(), root_text);
|
||||
assert!(
|
||||
std::fs::read_to_string(&include)
|
||||
.unwrap()
|
||||
.contains("'bob'= ['2001:db8::/32'] # keep literal")
|
||||
);
|
||||
let before = std::fs::read(&include).unwrap();
|
||||
let (status, _, error) = fixture
|
||||
.request_body(
|
||||
"PATCH",
|
||||
"/v1/users/alice",
|
||||
true,
|
||||
Some(&json!({"secret":"11111111111111111111111111111111","source_deny":null})),
|
||||
&[],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 409, "{error}");
|
||||
assert_eq!(error["error"]["code"], "config_patch_not_atomic");
|
||||
assert_eq!(std::fs::read(root).unwrap(), root_text.as_bytes());
|
||||
assert_eq!(std::fs::read(&include).unwrap(), before);
|
||||
patch(&fixture, "alice", json!({"source_deny":null})).await;
|
||||
assert!(
|
||||
!ProxyConfig::load(root)
|
||||
.unwrap()
|
||||
.access
|
||||
.user_source_deny
|
||||
.contains_key("alice")
|
||||
);
|
||||
assert!(
|
||||
ProxyConfig::load(root)
|
||||
.unwrap()
|
||||
.access
|
||||
.user_source_deny
|
||||
.contains_key("bob")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn source_deny_literal_username_supports_inline_dotted_and_quoted_sources() {
|
||||
for declaration in [
|
||||
"access.user_source_deny = { 'alice.two'=['192.0.2.0/24'], bob=['2001:db8::/32'] } # keep\n",
|
||||
"access.user_source_deny.'alice.two'=['192.0.2.0/24']\naccess.user_source_deny.bob=['2001:db8::/32'] # keep\n",
|
||||
"[access.user_source_deny]\n'alice.two'=['192.0.2.0/24']\nbob=['2001:db8::/32'] # keep\n",
|
||||
] {
|
||||
let fixture = fixture("");
|
||||
let text = format!("{declaration}{}", USERS.replace("alice=", "'alice.two'="));
|
||||
std::fs::write(&fixture.shared.config_path, text).unwrap();
|
||||
patch(
|
||||
&fixture,
|
||||
"alice.two",
|
||||
json!({"source_deny":["203.0.113.0/24"]}),
|
||||
)
|
||||
.await;
|
||||
let cfg = ProxyConfig::load(&fixture.shared.config_path).unwrap();
|
||||
assert_eq!(cfg.access.user_source_deny.len(), 2);
|
||||
assert_eq!(
|
||||
cfg.access.user_source_deny["alice.two"][0].to_string(),
|
||||
"203.0.113.0/24"
|
||||
);
|
||||
patch(&fixture, "alice.two", json!({"source_deny":null})).await;
|
||||
let cfg = ProxyConfig::load(&fixture.shared.config_path).unwrap();
|
||||
assert_eq!(cfg.access.user_source_deny.len(), 1);
|
||||
assert_eq!(
|
||||
cfg.access.user_source_deny["bob"][0].to_string(),
|
||||
"2001:db8::/32"
|
||||
);
|
||||
assert!(
|
||||
std::fs::read_to_string(&fixture.shared.config_path)
|
||||
.unwrap()
|
||||
.contains("# keep")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn source_deny_invalid_values_and_stale_revision_leave_source_unchanged() {
|
||||
let fixture = fixture("");
|
||||
let before = std::fs::read(&fixture.shared.config_path).unwrap();
|
||||
for value in [
|
||||
json!("192.0.2.0/24"),
|
||||
json!([1]),
|
||||
json!(["192.0.2.0/33"]),
|
||||
json!(["2001:db8::/129"]),
|
||||
json!(["bad"]),
|
||||
json!([null]),
|
||||
] {
|
||||
let (status, _, error) = fixture
|
||||
.request_body(
|
||||
"PATCH",
|
||||
"/v1/users/alice",
|
||||
true,
|
||||
Some(&json!({"source_deny":value})),
|
||||
&[],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 400, "{error}");
|
||||
assert_eq!(std::fs::read(&fixture.shared.config_path).unwrap(), before);
|
||||
}
|
||||
let (status, _, error) = fixture
|
||||
.request_body(
|
||||
"PATCH",
|
||||
"/v1/users/alice",
|
||||
true,
|
||||
Some(&json!({"source_deny":[]})),
|
||||
&[("If-Match", "stale")],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, 409, "{error}");
|
||||
assert_eq!(error["error"]["code"], "revision_conflict");
|
||||
assert_eq!(std::fs::read(&fixture.shared.config_path).unwrap(), before);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn source_deny_prepared_reload_retains_old_rules_until_a_later_generation() {
|
||||
let fixture = fixture("");
|
||||
let (control, mut commands) = crate::maestro::reload::ReloadControl::channel(1);
|
||||
let (accepted, _) = crate::api::submit_reload_from_disk(
|
||||
&fixture.shared.config_path,
|
||||
&fixture.shared.mutation_lock,
|
||||
&control,
|
||||
None,
|
||||
crate::maestro::reload::ReloadRequest::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let captured_for_reload = (*commands.recv().await.unwrap().config).clone();
|
||||
let old_runtime = fixture.shared.active_runtime.load_full();
|
||||
let admission = old_runtime.proxy_shared.clone();
|
||||
let credential = credential_id_from_hex(&captured_for_reload.access.users["alice"]).unwrap();
|
||||
let incarnation = admission
|
||||
.stage_user_credential("alice", credential, true)
|
||||
.incarnation;
|
||||
let registration = admission
|
||||
.register_authenticated_user_session("alice", credential)
|
||||
.unwrap();
|
||||
// The generation being prepared has already captured source before the API write.
|
||||
let written = patch(&fixture, "alice", json!({"source_deny":["192.0.2.0/24"]})).await;
|
||||
assert_ne!(written["revision"], accepted.config_revision);
|
||||
assert!(!registration.is_cancelled());
|
||||
assert_eq!(registration.incarnation(), incarnation);
|
||||
let mut intermediate = captured_for_reload;
|
||||
intermediate.server.api = old_runtime.config().server.api.clone();
|
||||
fixture
|
||||
.shared
|
||||
.active_runtime
|
||||
.store(test_runtime_generation(2, intermediate));
|
||||
let (_, _, view) = fixture.request("GET", "/v1/users/alice", true).await;
|
||||
assert_eq!(view["data"]["source_deny_status"]["effective"], json!([]));
|
||||
assert_eq!(
|
||||
view["data"]["source_deny_status"]["runtime_reload_required"],
|
||||
true
|
||||
);
|
||||
publish(&fixture, 3);
|
||||
let (_, _, view) = fixture.request("GET", "/v1/users/alice", true).await;
|
||||
assert_eq!(
|
||||
view["data"]["source_deny_status"]["runtime_reload_required"],
|
||||
false
|
||||
);
|
||||
assert!(
|
||||
!old_runtime
|
||||
.config()
|
||||
.access
|
||||
.is_user_source_ip_denied("alice", "192.0.2.1".parse().unwrap())
|
||||
);
|
||||
assert!(!registration.is_cancelled());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn source_deny_watcher_retains_rules_and_preserves_quota_usage() {
|
||||
use crate::config::hot_reload::spawn_config_watcher;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::watch;
|
||||
let mut fixture = fixture(
|
||||
"[server.api]\nenabled=true\nread_only=false\nauth_header='Bearer discovery-test'\n",
|
||||
);
|
||||
let config = fixture.shared.active_runtime.load().config();
|
||||
let cancellation = tokio_util::sync::CancellationToken::new();
|
||||
let _cancel_on_drop = cancellation.clone().drop_guard();
|
||||
let (activation, activated) = watch::channel(false);
|
||||
let (mut receiver, _, watcher) = spawn_config_watcher(
|
||||
fixture.shared.config_path.clone(),
|
||||
config.clone(),
|
||||
None,
|
||||
None,
|
||||
cancellation.clone(),
|
||||
None,
|
||||
Some(activated),
|
||||
Some(fixture.shared.mutation_lock.clone()),
|
||||
None,
|
||||
);
|
||||
let mut runtime = test_runtime_generation(1, (*config).clone());
|
||||
Arc::get_mut(&mut runtime).unwrap().config_rx = receiver.clone();
|
||||
runtime.stats.load_user_quota_state("alice", 12345, 6789);
|
||||
let stats = runtime.stats.clone();
|
||||
let quota_path = fixture.shared.quota_state.path().to_path_buf();
|
||||
Arc::get_mut(&mut fixture.shared).unwrap().quota_state =
|
||||
crate::quota_state::QuotaStateOwner::new(quota_path.clone(), stats.quota_store());
|
||||
let checkpoint_before = std::fs::read("a_path).ok();
|
||||
fixture.shared.active_runtime.store(runtime);
|
||||
let task = tokio::spawn(watcher);
|
||||
patch(
|
||||
&fixture,
|
||||
"alice",
|
||||
json!({"source_deny":["192.0.2.0/24"],"max_tcp_conns":7}),
|
||||
)
|
||||
.await;
|
||||
activation.send_replace(true);
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
receiver.wait_for(|cfg| cfg.access.user_max_tcp_conns.get("alice") == Some(&7)),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(receiver.borrow().access.user_source_deny.is_empty());
|
||||
let (_, _, view) = fixture.request("GET", "/v1/users/alice", true).await;
|
||||
assert_eq!(
|
||||
view["data"]["source_deny_status"]["runtime_reload_required"],
|
||||
true
|
||||
);
|
||||
assert_eq!(stats.get_user_quota_used("alice"), 12345);
|
||||
assert_eq!(
|
||||
stats.user_quota_snapshot()["alice"].last_reset_epoch_secs,
|
||||
6789
|
||||
);
|
||||
assert_eq!(std::fs::read("a_path).ok(), checkpoint_before);
|
||||
cancellation.cancel();
|
||||
tokio::time::timeout(Duration::from_secs(5), task)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
}
|
||||
@@ -165,6 +165,7 @@ async fn patch_user_to_completion(
|
||||
}
|
||||
}
|
||||
|
||||
let source_deny_edits = apply_source_deny(&mut cfg, user, body.source_deny)?;
|
||||
cfg.validate()
|
||||
.map_err(|e| ApiFailure::bad_request(format!("config validation failed: {}", e)))?;
|
||||
let staged_credential =
|
||||
@@ -210,13 +211,14 @@ async fn patch_user_to_completion(
|
||||
touched_sections.push(AccessSection::UserEnabled);
|
||||
}
|
||||
|
||||
let revision = if touched_sections.is_empty() {
|
||||
let revision = if touched_sections.is_empty() && source_deny_edits.is_empty() {
|
||||
current_revision(&shared.config_path).await?
|
||||
} else {
|
||||
save_access_sections_to_disk_if_revision(
|
||||
save_access_sections_and_fields_if_revision(
|
||||
&shared.config_path,
|
||||
&cfg,
|
||||
&touched_sections,
|
||||
source_deny_edits,
|
||||
Some(&base_revision),
|
||||
)
|
||||
.await?
|
||||
|
||||
@@ -1,4 +1,64 @@
|
||||
use super::*;
|
||||
use crate::api::model::{InheritedLimit, SourceDenyState, UserLimitSnapshot, UserLimitState};
|
||||
|
||||
fn inherited_limit(configured_override: Option<usize>, global_value: usize) -> InheritedLimit {
|
||||
let positive_override = configured_override.filter(|value| *value > 0);
|
||||
InheritedLimit {
|
||||
value: positive_override.or((global_value > 0).then_some(global_value)),
|
||||
configured_override,
|
||||
global_value,
|
||||
origin: if positive_override.is_some() {
|
||||
"user_override"
|
||||
} else if global_value > 0 {
|
||||
"global_default"
|
||||
} else {
|
||||
"unlimited"
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn limit_snapshot(cfg: &ProxyConfig, username: &str) -> UserLimitSnapshot {
|
||||
UserLimitSnapshot {
|
||||
max_tcp_conns: inherited_limit(
|
||||
cfg.access.user_max_tcp_conns.get(username).copied(),
|
||||
cfg.access.user_max_tcp_conns_global_each,
|
||||
),
|
||||
max_unique_ips: inherited_limit(
|
||||
cfg.access.user_max_unique_ips.get(username).copied(),
|
||||
cfg.access.user_max_unique_ips_global_each,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::api) fn refresh_runtime_view(user: &mut UserInfo, runtime: &ProxyConfig) {
|
||||
user.in_runtime = runtime.access.users.contains_key(&user.username);
|
||||
user.limits.effective = user
|
||||
.in_runtime
|
||||
.then(|| limit_snapshot(runtime, &user.username));
|
||||
user.source_deny_status = source_deny_state(&user.username, &user.source_deny, Some(runtime));
|
||||
}
|
||||
|
||||
fn source_deny_state(
|
||||
username: &str,
|
||||
desired: &[ipnetwork::IpNetwork],
|
||||
runtime: Option<&ProxyConfig>,
|
||||
) -> SourceDenyState {
|
||||
// Retained rules can apply to a recreated user even before its membership is published.
|
||||
let effective = runtime.map(|cfg| {
|
||||
cfg.access
|
||||
.user_source_deny
|
||||
.get(username)
|
||||
.cloned()
|
||||
.unwrap_or_default()
|
||||
});
|
||||
SourceDenyState {
|
||||
runtime_reload_required: effective.as_ref().map(|nets| nets.as_slice() != desired),
|
||||
effective,
|
||||
apply_mode: "generation_reload",
|
||||
reload_endpoint: "POST /v1/system/reload",
|
||||
effective_scope: "request_generation_snapshot",
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::api) async fn users_from_config(
|
||||
cfg: &ProxyConfig,
|
||||
@@ -72,6 +132,29 @@ pub(in crate::api) async fn users_from_config(
|
||||
.filter(|limit| *limit > 0)
|
||||
.or((cfg.access.user_max_unique_ips_global_each > 0)
|
||||
.then_some(cfg.access.user_max_unique_ips_global_each)),
|
||||
limits: UserLimitState {
|
||||
desired: limit_snapshot(cfg, &username),
|
||||
effective: runtime_cfg
|
||||
.filter(|runtime| runtime.access.users.contains_key(&username))
|
||||
.map(|runtime| limit_snapshot(runtime, &username)),
|
||||
effective_scope: "active_config_snapshot",
|
||||
subsystem_convergence: "unknown",
|
||||
},
|
||||
source_deny: cfg
|
||||
.access
|
||||
.user_source_deny
|
||||
.get(&username)
|
||||
.cloned()
|
||||
.unwrap_or_default(),
|
||||
source_deny_status: source_deny_state(
|
||||
&username,
|
||||
cfg.access
|
||||
.user_source_deny
|
||||
.get(&username)
|
||||
.map(Vec::as_slice)
|
||||
.unwrap_or_default(),
|
||||
runtime_cfg,
|
||||
),
|
||||
current_connections: stats.get_process_user_curr_connects(&username),
|
||||
active_unique_ips: active_ip_list.len(),
|
||||
active_unique_ips_list: active_ip_list,
|
||||
|
||||
@@ -58,7 +58,7 @@ pub use fields::HotFields;
|
||||
pub use watcher::spawn_config_watcher;
|
||||
|
||||
use diff::{config_equal, warn_non_hot_changes};
|
||||
use fields::overlay_hot_fields;
|
||||
pub(crate) use fields::overlay_hot_fields;
|
||||
use reporting::log_changes;
|
||||
#[cfg(test)]
|
||||
use watcher::{ReloadState, reload_config};
|
||||
|
||||
@@ -229,7 +229,7 @@ impl HotFields {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn overlay_hot_fields(old: &ProxyConfig, new: &ProxyConfig) -> ProxyConfig {
|
||||
pub(crate) fn overlay_hot_fields(old: &ProxyConfig, new: &ProxyConfig) -> ProxyConfig {
|
||||
let mut cfg = old.clone();
|
||||
cfg.quota_source_read_at = new.quota_source_read_at;
|
||||
|
||||
|
||||
@@ -1,5 +1,32 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn watcher_publication_epoch_distinguishes_hot_round_trips_and_rejected_candidates() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("config.toml");
|
||||
let source = "[general]\nlog_level = 'normal'\n";
|
||||
std::fs::write(&path, source).unwrap();
|
||||
let initial = Arc::new(ProxyConfig::load(&path).unwrap().with_publication_epoch());
|
||||
let (sender, _receiver) = watch::channel(initial.clone());
|
||||
let (log_sender, _log_receiver) = watch::channel(initial.general.log_level.clone());
|
||||
let mut state = ReloadState::new(None);
|
||||
let mut last_epoch = initial.runtime_config_epoch;
|
||||
for level in ["debug", "normal"] {
|
||||
std::fs::write(&path, format!("[general]\nlog_level = '{level}'\n")).unwrap();
|
||||
assert!(reload_config(&path, &sender, &log_sender, None, None, &mut state).is_some());
|
||||
assert!(sender.borrow().runtime_config_epoch > last_epoch);
|
||||
last_epoch = sender.borrow().runtime_config_epoch;
|
||||
}
|
||||
assert_eq!(
|
||||
serde_json::to_value(initial.as_ref()).unwrap(),
|
||||
serde_json::to_value(sender.borrow().as_ref()).unwrap()
|
||||
);
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), source);
|
||||
std::fs::write(&path, "[general]\nlog_level = 'invalid'\n").unwrap();
|
||||
assert!(reload_config(&path, &sender, &log_sender, None, None, &mut state).is_none());
|
||||
assert_eq!(sender.borrow().runtime_config_epoch, last_epoch);
|
||||
}
|
||||
|
||||
fn sample_config() -> ProxyConfig {
|
||||
ProxyConfig::default()
|
||||
}
|
||||
|
||||
@@ -144,9 +144,26 @@ fn prepare_effective_config(
|
||||
let mut applied_cfg = overlay_hot_fields(old_cfg, new_cfg);
|
||||
applied_cfg.validate_effective_web()?;
|
||||
applied_cfg.rebuild_runtime_web()?;
|
||||
applied_cfg.provenance = if config_equal(&applied_cfg, new_cfg) {
|
||||
new_cfg.provenance.clone()
|
||||
} else {
|
||||
crate::config::observation::ConfigProvenance::Mixed
|
||||
};
|
||||
Ok(applied_cfg)
|
||||
}
|
||||
|
||||
fn record_outcome(
|
||||
config: &ProxyConfig,
|
||||
phase: &'static str,
|
||||
revision: Option<String>,
|
||||
epoch: Option<u64>,
|
||||
error: Option<&'static str>,
|
||||
) {
|
||||
if let Some(observation) = &config.watcher_observation {
|
||||
observation.record(phase, revision, epoch, error);
|
||||
}
|
||||
}
|
||||
|
||||
/// Diffs and publishes a fully prepared configuration on the watcher owner task.
|
||||
fn reload_config_with_resolver(
|
||||
prepared: (LoadedConfig, ProxyConfig),
|
||||
@@ -168,6 +185,7 @@ fn reload_config_with_resolver(
|
||||
let next_manifest = WatchManifest::from_source_files(&source_files);
|
||||
|
||||
let old_cfg = config_tx.borrow().clone();
|
||||
let revision = new_cfg.provenance.revision().map(str::to_owned);
|
||||
let old_hot = HotFields::from_config(&old_cfg);
|
||||
let applied_hot = HotFields::from_config(&applied_cfg);
|
||||
let non_hot_changed = !config_equal(&applied_cfg, &new_cfg);
|
||||
@@ -179,9 +197,24 @@ fn reload_config_with_resolver(
|
||||
}
|
||||
|
||||
if !hot_changed {
|
||||
if refresh_quota_source {
|
||||
config_tx.send(Arc::new(applied_cfg)).ok();
|
||||
}
|
||||
let published = !refresh_quota_source
|
||||
|| config_tx
|
||||
.send(Arc::new(applied_cfg.with_publication_epoch()))
|
||||
.is_ok();
|
||||
let epoch = config_tx.borrow().runtime_config_epoch;
|
||||
record_outcome(
|
||||
&old_cfg,
|
||||
if !published {
|
||||
"publication_failed"
|
||||
} else if non_hot_changed {
|
||||
"retained"
|
||||
} else {
|
||||
"unchanged"
|
||||
},
|
||||
revision,
|
||||
published.then_some(epoch),
|
||||
(!published).then_some("publication_closed"),
|
||||
);
|
||||
reload_state.mark_applied(rendered_hash);
|
||||
return Some(next_manifest);
|
||||
}
|
||||
@@ -194,6 +227,13 @@ fn reload_config_with_resolver(
|
||||
"config reload: invalid network.dns_overrides: {}; keeping old config",
|
||||
e
|
||||
);
|
||||
record_outcome(
|
||||
&old_cfg,
|
||||
"rejected",
|
||||
revision,
|
||||
None,
|
||||
Some("dns_overrides_rejected"),
|
||||
);
|
||||
return Some(next_manifest);
|
||||
}
|
||||
|
||||
@@ -205,7 +245,23 @@ fn reload_config_with_resolver(
|
||||
detected_ip_v4,
|
||||
detected_ip_v6,
|
||||
);
|
||||
config_tx.send(Arc::new(applied_cfg)).ok();
|
||||
let published = config_tx
|
||||
.send(Arc::new(applied_cfg.with_publication_epoch()))
|
||||
.is_ok();
|
||||
let epoch = config_tx.borrow().runtime_config_epoch;
|
||||
record_outcome(
|
||||
&old_cfg,
|
||||
if !published {
|
||||
"publication_failed"
|
||||
} else if non_hot_changed {
|
||||
"published_partial"
|
||||
} else {
|
||||
"published"
|
||||
},
|
||||
revision,
|
||||
published.then_some(epoch),
|
||||
(!published).then_some("publication_closed"),
|
||||
);
|
||||
reload_state.mark_applied(rendered_hash);
|
||||
Some(next_manifest)
|
||||
}
|
||||
@@ -261,7 +317,18 @@ pub fn spawn_config_watcher(
|
||||
impl std::future::Future<Output = ()> + Send + 'static,
|
||||
) {
|
||||
let initial_level = initial.general.log_level.clone();
|
||||
let (config_tx, config_rx) = watch::channel(initial);
|
||||
let mut initial = (*initial).clone().with_publication_epoch();
|
||||
initial.watcher_observation = Some(Arc::new(
|
||||
crate::config::observation::WatchObservation::default(),
|
||||
));
|
||||
record_outcome(
|
||||
&initial,
|
||||
"initial",
|
||||
initial.provenance.revision().map(str::to_owned),
|
||||
Some(initial.runtime_config_epoch),
|
||||
None,
|
||||
);
|
||||
let (config_tx, config_rx) = watch::channel(Arc::new(initial));
|
||||
let (log_tx, log_rx) = watch::channel(initial_level);
|
||||
|
||||
let config_path = normalize_watch_path(&config_path);
|
||||
@@ -282,6 +349,15 @@ pub fn spawn_config_watcher(
|
||||
}
|
||||
}
|
||||
let initial_loaded = preparation::read_source(&config_path).await;
|
||||
if initial_loaded.is_none() {
|
||||
record_outcome(
|
||||
&config_tx.borrow(),
|
||||
"rejected",
|
||||
None,
|
||||
None,
|
||||
Some("source_invalid_or_unreadable"),
|
||||
);
|
||||
}
|
||||
let initial_manifest = initial_loaded
|
||||
.as_ref()
|
||||
.map(|loaded| WatchManifest::from_source_files(&loaded.source_files))
|
||||
@@ -480,3 +556,6 @@ mod decoy_dns_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod quota_period_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod observation_tests;
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
use super::*;
|
||||
use crate::config::observation::{ConfigProvenance, WatchObservation};
|
||||
|
||||
#[tokio::test]
|
||||
async fn watcher_outcomes_follow_actual_publication_retention_and_rejection() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("config.toml");
|
||||
std::fs::write(&path, "").unwrap();
|
||||
let loaded = ProxyConfig::load_prepared(path.clone()).await.unwrap();
|
||||
let mut initial = loaded.config.with_publication_epoch();
|
||||
let observer = Arc::new(WatchObservation::default());
|
||||
initial.watcher_observation = Some(observer.clone());
|
||||
let (sender, mut receiver) = watch::channel(Arc::new(initial));
|
||||
let (log, _) = watch::channel(sender.borrow().general.log_level.clone());
|
||||
let mut state = ReloadState::new(Some(loaded.rendered_hash));
|
||||
for (text, phase, changed) in [
|
||||
("[general]\nlog_level='debug'", "published", true),
|
||||
(
|
||||
"[general]\nlog_level='debug'\ndisable_colors=true",
|
||||
"retained",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"[general]\nlog_level='verbose'\ndisable_colors=true",
|
||||
"published_partial",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"[general]\nlog_level='verbose'\ndisable_colors=true",
|
||||
"unchanged",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"[general]\nlog_level='private-invalid-log-level'",
|
||||
"rejected",
|
||||
false,
|
||||
),
|
||||
] {
|
||||
let old = receiver.borrow_and_update().clone();
|
||||
let sequence = observer.snapshot().map_or(0, |value| value.sequence);
|
||||
std::fs::write(&path, text).unwrap();
|
||||
preparation::reload(
|
||||
&path, &sender, &log, None, None, &mut state, None, false, None, None,
|
||||
)
|
||||
.await;
|
||||
let outcome = observer.snapshot().unwrap();
|
||||
assert!(outcome.sequence > sequence);
|
||||
assert_eq!(outcome.phase, phase);
|
||||
assert_eq!(receiver.has_changed().unwrap(), changed);
|
||||
if changed {
|
||||
assert!(receiver.borrow().runtime_config_epoch > old.runtime_config_epoch);
|
||||
assert_eq!(
|
||||
outcome.published_config_epoch,
|
||||
Some(receiver.borrow().runtime_config_epoch)
|
||||
);
|
||||
if phase == "published_partial" {
|
||||
assert!(matches!(
|
||||
&receiver.borrow().provenance,
|
||||
ConfigProvenance::Mixed
|
||||
));
|
||||
} else {
|
||||
assert_eq!(
|
||||
outcome.source_revision.as_deref(),
|
||||
receiver.borrow().provenance.revision()
|
||||
);
|
||||
}
|
||||
} else {
|
||||
assert!(Arc::ptr_eq(&old, &receiver.borrow()));
|
||||
}
|
||||
assert!(
|
||||
!serde_json::to_string(&*outcome)
|
||||
.unwrap()
|
||||
.contains("private-invalid-log-level")
|
||||
);
|
||||
}
|
||||
let rejected = observer.snapshot().unwrap();
|
||||
assert_eq!(rejected.error_code, Some("source_invalid_or_unreadable"));
|
||||
assert_eq!(rejected.published_config_epoch, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn lost_receivers_never_report_successful_publication() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("config.toml");
|
||||
std::fs::write(&path, "").unwrap();
|
||||
let mut initial = ProxyConfig::load_prepared(path.clone())
|
||||
.await
|
||||
.unwrap()
|
||||
.config;
|
||||
let observer = Arc::new(WatchObservation::default());
|
||||
initial.watcher_observation = Some(observer.clone());
|
||||
let (sender, receiver) = watch::channel(Arc::new(initial.with_publication_epoch()));
|
||||
let (log, _) = watch::channel(sender.borrow().general.log_level.clone());
|
||||
let original = sender.borrow().clone();
|
||||
drop(receiver);
|
||||
std::fs::write(&path, "[general]\nlog_level='debug'").unwrap();
|
||||
preparation::reload(
|
||||
&path,
|
||||
&sender,
|
||||
&log,
|
||||
None,
|
||||
None,
|
||||
&mut ReloadState::default(),
|
||||
None,
|
||||
false,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert!(Arc::ptr_eq(&sender.borrow(), &original));
|
||||
let outcome = observer.snapshot().unwrap();
|
||||
assert_eq!(outcome.phase, "publication_failed");
|
||||
assert_eq!(outcome.published_config_epoch, None);
|
||||
assert_eq!(outcome.error_code, Some("publication_closed"));
|
||||
}
|
||||
@@ -43,7 +43,17 @@ pub(super) async fn reload(
|
||||
Some(gate) => Some(gate.lock().await),
|
||||
None => None,
|
||||
};
|
||||
let source = read_source(path).await?;
|
||||
let Some(source) = read_source(path).await else {
|
||||
record_outcome(
|
||||
&config_tx.borrow(),
|
||||
"rejected",
|
||||
None,
|
||||
None,
|
||||
Some("source_invalid_or_unreadable"),
|
||||
);
|
||||
return None;
|
||||
};
|
||||
let revision = source.config.provenance.revision().map(str::to_owned);
|
||||
let manifest = WatchManifest::from_source_files(&source.source_files);
|
||||
// A new file edit can restore the exact pre-creation bytes. Refresh only source
|
||||
// evidence for fenced accounts, retaining prepared DNS and immutable WEB state.
|
||||
@@ -53,14 +63,43 @@ pub(super) async fn reload(
|
||||
{
|
||||
let mut refreshed = (**config_tx.borrow()).clone();
|
||||
refreshed.quota_source_read_at = source.config.quota_source_read_at;
|
||||
config_tx.send(Arc::new(refreshed)).ok();
|
||||
let published = config_tx
|
||||
.send(Arc::new(refreshed.with_publication_epoch()))
|
||||
.is_ok();
|
||||
let config = config_tx.borrow();
|
||||
record_outcome(
|
||||
&config,
|
||||
if published {
|
||||
"source_refreshed"
|
||||
} else {
|
||||
"publication_failed"
|
||||
},
|
||||
revision,
|
||||
published.then_some(config.runtime_config_epoch),
|
||||
(!published).then_some("publication_closed"),
|
||||
);
|
||||
reload_state.mark_applied(source.rendered_hash);
|
||||
return Some(manifest);
|
||||
}
|
||||
drop(guard);
|
||||
if !force && reload_state.is_applied(source.rendered_hash) {
|
||||
let config = config_tx.borrow();
|
||||
record_outcome(
|
||||
&config,
|
||||
"unchanged",
|
||||
revision,
|
||||
Some(config.runtime_config_epoch),
|
||||
None,
|
||||
);
|
||||
return Some(manifest);
|
||||
}
|
||||
record_outcome(
|
||||
&config_tx.borrow(),
|
||||
"preparing",
|
||||
revision.clone(),
|
||||
None,
|
||||
None,
|
||||
);
|
||||
let loaded = match source.prepare().await {
|
||||
Ok(loaded) => loaded,
|
||||
Err(error) => {
|
||||
@@ -68,6 +107,13 @@ pub(super) async fn reload(
|
||||
"config reload: preparation failed: {}; keeping old config",
|
||||
error
|
||||
);
|
||||
record_outcome(
|
||||
&config_tx.borrow(),
|
||||
"rejected",
|
||||
revision,
|
||||
None,
|
||||
Some("preparation_failed"),
|
||||
);
|
||||
return Some(manifest);
|
||||
}
|
||||
};
|
||||
@@ -94,6 +140,13 @@ pub(super) async fn reload(
|
||||
"config reload: effective WEB validation failed: {}; keeping old config",
|
||||
error
|
||||
);
|
||||
record_outcome(
|
||||
&config_tx.borrow(),
|
||||
"rejected",
|
||||
revision,
|
||||
None,
|
||||
Some("effective_config_invalid"),
|
||||
);
|
||||
Some(manifest)
|
||||
}
|
||||
Err(error) => {
|
||||
@@ -101,6 +154,13 @@ pub(super) async fn reload(
|
||||
"config reload: runtime builder failed: {}; keeping old config",
|
||||
error
|
||||
);
|
||||
record_outcome(
|
||||
&config_tx.borrow(),
|
||||
"rejected",
|
||||
revision,
|
||||
None,
|
||||
Some("preparation_worker_failed"),
|
||||
);
|
||||
Some(manifest)
|
||||
}
|
||||
}
|
||||
|
||||
+21
-3
@@ -29,6 +29,7 @@ mod runtime_web;
|
||||
mod decode;
|
||||
mod effective;
|
||||
mod pipeline;
|
||||
mod publication;
|
||||
// Candidate-owned DNS preparation is separate from pure runtime reconstruction.
|
||||
mod decoy_dns;
|
||||
mod validate_core;
|
||||
@@ -38,9 +39,9 @@ mod validate_server;
|
||||
mod validate_web;
|
||||
mod validation;
|
||||
|
||||
use self::includes::{
|
||||
hash_rendered_snapshot, normalize_config_path, preprocess_includes, read_config_source,
|
||||
};
|
||||
#[cfg(test)]
|
||||
use self::includes::normalize_config_path;
|
||||
use self::includes::{hash_rendered_snapshot, preprocess_includes, read_config_source};
|
||||
use self::normalize::{
|
||||
is_valid_ad_tag, is_valid_tls_domain_name, normalize_domain_to_ascii,
|
||||
normalize_exclusive_mask_target, normalize_mask_host_to_ascii, parse_exclusive_mask_target,
|
||||
@@ -156,6 +157,14 @@ pub struct ProxyConfig {
|
||||
#[serde(default)]
|
||||
pub default_dc: Option<u8>,
|
||||
|
||||
/// Process-local identity assigned by the owner of a published config snapshot.
|
||||
#[serde(skip)]
|
||||
pub(crate) runtime_config_epoch: u64,
|
||||
#[serde(skip)]
|
||||
pub(crate) provenance: super::observation::ConfigProvenance,
|
||||
#[serde(skip)]
|
||||
pub(crate) watcher_observation: Option<Arc<super::observation::WatchObservation>>,
|
||||
|
||||
/// Monotonic start of source acquisition, used only for cold quota policy fencing.
|
||||
#[serde(skip)]
|
||||
pub(crate) quota_source_read_at: Option<std::time::Instant>,
|
||||
@@ -167,16 +176,19 @@ pub struct ProxyConfig {
|
||||
|
||||
impl ProxyConfig {
|
||||
/// Loads runtime configuration from a TOML file.
|
||||
#[cfg(test)]
|
||||
pub fn load<P: AsRef<Path>>(path: P) -> Result<Self> {
|
||||
Self::load_with_metadata(path).map(|loaded| loaded.config)
|
||||
}
|
||||
|
||||
/// Loads typed configuration together with its source and rendered metadata.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn load_with_metadata<P: AsRef<Path>>(path: P) -> Result<LoadedConfig> {
|
||||
Self::load_with_source_overrides(path, &BTreeMap::new())
|
||||
}
|
||||
|
||||
/// Loads a typed snapshot while replacing selected captured source documents.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn load_with_source_overrides<P: AsRef<Path>>(
|
||||
path: P,
|
||||
source_overrides: &BTreeMap<PathBuf, String>,
|
||||
@@ -247,6 +259,7 @@ impl ProxyConfig {
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn load_source_graph(graph: ConfigSourceGraph) -> Result<LoadedConfig> {
|
||||
pipeline::load_source_graph(graph)
|
||||
}
|
||||
@@ -256,6 +269,11 @@ impl ProxyConfig {
|
||||
Self::parse_source_with_overrides(path, &BTreeMap::new())
|
||||
}
|
||||
|
||||
/// Parses an already captured source manifest without DNS or static-site reads.
|
||||
pub(crate) fn parse_captured_source(graph: ConfigSourceGraph) -> Result<ParsedConfigSource> {
|
||||
pipeline::parse_source_graph(graph)
|
||||
}
|
||||
|
||||
/// Checks decoy mode-specific keys before a source or API patch loses unknown fields.
|
||||
pub(crate) fn validate_decoy_source_keys(document: &toml::Value) -> Result<()> {
|
||||
decoy_dns::validate_mode_keys(document)
|
||||
|
||||
@@ -20,6 +20,8 @@ pub(super) fn decode_source_graph(graph: ConfigSourceGraph) -> Result<DecodedSou
|
||||
toml::from_str(&processed).map_err(|e| ProxyError::Config(e.to_string()))?;
|
||||
handle_unknown_config_keys(&parsed_toml)?;
|
||||
ProxyConfig::validate_decoy_source_keys(&parsed_toml)?;
|
||||
let source_evidence =
|
||||
crate::config::observation::SourceEvidence::capture(&parsed_toml, &source_contents);
|
||||
let general_table = parsed_toml
|
||||
.get("general")
|
||||
.and_then(|value| value.as_table());
|
||||
@@ -65,6 +67,7 @@ pub(super) fn decode_source_graph(graph: ConfigSourceGraph) -> Result<DecodedSou
|
||||
let mut config: ProxyConfig = parsed_toml
|
||||
.try_into()
|
||||
.map_err(|e| ProxyError::Config(e.to_string()))?;
|
||||
config.provenance = crate::config::observation::ConfigProvenance::Source(source_evidence);
|
||||
config
|
||||
.server
|
||||
.conntrack_control
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::*;
|
||||
|
||||
/// Completes legacy synchronous loads without performing hostname resolution.
|
||||
#[cfg(test)]
|
||||
pub(super) fn load_source_graph(graph: ConfigSourceGraph) -> Result<LoadedConfig> {
|
||||
finish(parse_source_graph(graph)?)
|
||||
}
|
||||
@@ -37,15 +38,36 @@ pub(super) fn finish(mut parsed: ParsedConfigSource) -> Result<LoadedConfig> {
|
||||
|
||||
impl ParsedConfigSource {
|
||||
/// Resolves each unique decoy origin once, then builds a fully validated candidate.
|
||||
pub(crate) async fn prepare(mut self) -> Result<LoadedConfig> {
|
||||
decoy_dns::prepare(&mut self.config, |host, port| async move {
|
||||
tokio::net::lookup_host((host.as_str(), port))
|
||||
pub(crate) async fn prepare(self) -> Result<LoadedConfig> {
|
||||
self.prepare_guarded(Arc::new(())).await
|
||||
}
|
||||
|
||||
/// Retains a caller's preparation budget inside blocking work even if the
|
||||
/// request or DNS timeout drops its future. No worker publishes this data.
|
||||
pub(crate) async fn prepare_guarded<G: Send + Sync + 'static>(
|
||||
mut self,
|
||||
guard: Arc<G>,
|
||||
) -> Result<LoadedConfig> {
|
||||
decoy_dns::prepare(&mut self.config, |host, port| {
|
||||
let guard = guard.clone();
|
||||
async move {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
use std::net::ToSocketAddrs;
|
||||
let _guard = guard;
|
||||
(host.as_str(), port)
|
||||
.to_socket_addrs()
|
||||
.map(|answers| answers.collect())
|
||||
})
|
||||
.await
|
||||
.map(|answers| answers.collect())
|
||||
.map_err(|_| std::io::Error::other("DNS preparation worker failed"))?
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
tokio::task::spawn_blocking(move || finish(self))
|
||||
.await
|
||||
.map_err(|error| ProxyError::Config(format!("config preparation failed: {error}")))?
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let _guard = guard;
|
||||
finish(self)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| ProxyError::Config(format!("config preparation failed: {error}")))?
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use super::ProxyConfig;
|
||||
|
||||
impl ProxyConfig {
|
||||
/// Identifies a publication, including a return to an earlier value. This is
|
||||
/// not a guarantee that asynchronous policy consumers have converged.
|
||||
pub(crate) fn with_publication_epoch(mut self) -> Self {
|
||||
static NEXT_EPOCH: AtomicU64 = AtomicU64::new(1);
|
||||
self.runtime_config_epoch = NEXT_EPOCH.fetch_add(1, Ordering::Relaxed);
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -128,6 +128,7 @@ pub(in crate::config::load) fn rebuild(config: &mut ProxyConfig) -> Result<()> {
|
||||
group_id: vhost_idx,
|
||||
profiles: shared_profiles,
|
||||
}),
|
||||
#[cfg(test)]
|
||||
host: String::new(),
|
||||
base: if vhost.base_path.is_empty() {
|
||||
"/".to_string()
|
||||
@@ -155,6 +156,7 @@ pub(in crate::config::load) fn rebuild(config: &mut ProxyConfig) -> Result<()> {
|
||||
host.clone(),
|
||||
Arc::new(WebRuntimeVhost {
|
||||
wildcard: None,
|
||||
#[cfg(test)]
|
||||
host: host.clone(),
|
||||
base: if vhost.base_path.is_empty() {
|
||||
"/".to_string()
|
||||
|
||||
@@ -260,7 +260,10 @@ const LISTENER_CONFIG_KEYS: &[&str] = &[
|
||||
"web_trusted_proxy_cidrs",
|
||||
];
|
||||
|
||||
const WEB_RETRY_JITTER_KEYS: &[&str] = &["enabled", "min_ms", "max_ms", "distribution", "peak_ms"];
|
||||
|
||||
const WEB_CONFIG_KEYS: &[&str] = &[
|
||||
"retry_jitter",
|
||||
"allow_wildcard_hosts",
|
||||
"enabled",
|
||||
"carrier",
|
||||
@@ -449,6 +452,7 @@ const TLS_FETCH_CONFIG_KEYS: &[&str] = &[
|
||||
|
||||
const ACCESS_CONFIG_KEYS: &[&str] = &[
|
||||
"users",
|
||||
"user_source_deny",
|
||||
"user_enabled",
|
||||
"user_ad_tags",
|
||||
"user_max_tcp_conns",
|
||||
@@ -502,6 +506,14 @@ const LOGGING_CONFIG_KEYS: &[&str] = &[
|
||||
// Recursive table traversal and key suggestion logic.
|
||||
mod check;
|
||||
|
||||
impl super::ProxyConfig {
|
||||
/// Checks sparse API input without permissive-mode logging or key suggestions.
|
||||
/// Dynamic map keys and accepted source aliases retain the source loader rules.
|
||||
pub(crate) fn unknown_source_paths(document: &toml::Value) -> Vec<String> {
|
||||
check::unknown_paths(document)
|
||||
}
|
||||
}
|
||||
|
||||
/// Rejects or reports unknown configuration keys according to strict mode.
|
||||
pub(super) fn handle_unknown_config_keys(parsed_toml: &toml::Value) -> Result<()> {
|
||||
let unknown = check::collect_unknown_config_keys(parsed_toml);
|
||||
|
||||
@@ -36,6 +36,7 @@ fn known_config_keys_for_suggestion() -> Vec<&'static str> {
|
||||
CONNTRACK_CONTROL_CONFIG_KEYS,
|
||||
LISTENER_CONFIG_KEYS,
|
||||
WEB_CONFIG_KEYS,
|
||||
WEB_RETRY_JITTER_KEYS,
|
||||
WEB_LIMITS_CONFIG_KEYS,
|
||||
WEB_WILDCARD_LIMITS_CONFIG_KEYS,
|
||||
WEB_DEBUG_CONFIG_KEYS,
|
||||
@@ -147,6 +148,20 @@ fn check_nested_table_value(
|
||||
/// Collects unknown keys across every supported nested configuration table.
|
||||
pub(super) fn collect_unknown_config_keys(parsed_toml: &toml::Value) -> Vec<UnknownConfigKey> {
|
||||
let known_for_suggestion = known_config_keys_for_suggestion();
|
||||
collect(parsed_toml, &known_for_suggestion)
|
||||
}
|
||||
|
||||
pub(super) fn unknown_paths(parsed_toml: &toml::Value) -> Vec<String> {
|
||||
collect(parsed_toml, &[])
|
||||
.into_iter()
|
||||
.map(|key| key.path)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn collect(
|
||||
parsed_toml: &toml::Value,
|
||||
known_for_suggestion: &[&'static str],
|
||||
) -> Vec<UnknownConfigKey> {
|
||||
let mut unknown = Vec::new();
|
||||
|
||||
if let Some(root) = parsed_toml.as_table() {
|
||||
@@ -236,6 +251,13 @@ pub(super) fn collect_unknown_config_keys(parsed_toml: &toml::Value) -> Vec<Unkn
|
||||
&["web"],
|
||||
WEB_CONFIG_KEYS,
|
||||
);
|
||||
check_known_table(
|
||||
parsed_toml,
|
||||
&mut unknown,
|
||||
&known_for_suggestion,
|
||||
&["web", "retry_jitter"],
|
||||
WEB_RETRY_JITTER_KEYS,
|
||||
);
|
||||
check_known_table(
|
||||
parsed_toml,
|
||||
&mut unknown,
|
||||
|
||||
@@ -75,6 +75,11 @@ pub(super) fn validate_source(config: &mut ProxyConfig) -> Result<()> {
|
||||
));
|
||||
}
|
||||
|
||||
config
|
||||
.web
|
||||
.retry_jitter
|
||||
.validate()
|
||||
.map_err(|message| ProxyError::Config(message.into()))?;
|
||||
validate_limits(&config.web.limits, config.web.allow_wildcard_hosts)?;
|
||||
debug::validate(&config.web.debug, &config.web.limits)?;
|
||||
let carriers = negotiation::validate(&config.web)?;
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
pub(crate) mod defaults;
|
||||
pub mod hot_reload;
|
||||
mod load;
|
||||
pub(crate) mod observation;
|
||||
mod types;
|
||||
|
||||
pub use load::ProxyConfig;
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
//! Bounded source evidence and owner-authored configuration observations.
|
||||
//! These records describe publication, never asynchronous consumer convergence.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use arc_swap::ArcSwapOption;
|
||||
use serde::Serialize;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
pub(crate) fn source_revision(sources: &BTreeMap<PathBuf, String>) -> String {
|
||||
let mut hash = Sha256::new();
|
||||
hash.update(b"telemt-config-manifest-v1\0");
|
||||
for (path, content) in sources {
|
||||
let path = path.as_os_str().as_encoded_bytes();
|
||||
hash.update((path.len() as u64).to_le_bytes());
|
||||
hash.update(path);
|
||||
hash.update((content.len() as u64).to_le_bytes());
|
||||
hash.update(content.as_bytes());
|
||||
}
|
||||
hex::encode(hash.finalize())
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub(crate) enum ConfigProvenance {
|
||||
#[default]
|
||||
Unknown,
|
||||
Source(Arc<SourceEvidence>),
|
||||
/// The published config combines sources or retained process policy. Do not
|
||||
/// attribute all its values to the last source read by the watcher.
|
||||
Mixed,
|
||||
}
|
||||
|
||||
impl ConfigProvenance {
|
||||
pub(crate) fn revision(&self) -> Option<&str> {
|
||||
match self {
|
||||
Self::Source(source) => Some(&source.revision),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct SourceEvidence {
|
||||
pub(crate) revision: String,
|
||||
pub(crate) explicit_paths: BTreeSet<String>,
|
||||
pub(crate) complete: bool,
|
||||
pub(crate) source_count: usize,
|
||||
pub(crate) generated_fake_cert_len: bool,
|
||||
}
|
||||
|
||||
impl SourceEvidence {
|
||||
pub(crate) fn capture(
|
||||
document: &toml::Value,
|
||||
sources: &BTreeMap<PathBuf, String>,
|
||||
) -> Arc<Self> {
|
||||
fn visit(
|
||||
value: &toml::Value,
|
||||
path: &str,
|
||||
paths: &mut BTreeSet<String>,
|
||||
complete: &mut bool,
|
||||
) {
|
||||
if paths.len() >= 4096 || path.len() > 256 {
|
||||
*complete = false;
|
||||
return;
|
||||
}
|
||||
if !path.is_empty() {
|
||||
paths.insert(path.to_owned());
|
||||
}
|
||||
// Open maps need only presence provenance, never their private keys.
|
||||
if path == "dc_overrides"
|
||||
|| path == "censorship.exclusive_mask"
|
||||
|| path.starts_with("access.")
|
||||
{
|
||||
return;
|
||||
}
|
||||
match value {
|
||||
toml::Value::Table(table) => {
|
||||
for (key, value) in table {
|
||||
let key = if path.starts_with("upstreams[")
|
||||
&& path.ends_with(']')
|
||||
&& key == "force_bind"
|
||||
{
|
||||
"bindtodevice"
|
||||
} else if path == "server" && key == "admin_api" {
|
||||
"api"
|
||||
} else {
|
||||
key
|
||||
};
|
||||
let child = if path.is_empty() {
|
||||
key.to_owned()
|
||||
} else {
|
||||
format!("{path}.{key}")
|
||||
};
|
||||
visit(value, &child, paths, complete);
|
||||
}
|
||||
}
|
||||
toml::Value::Array(array) => {
|
||||
for (index, value) in array.iter().enumerate() {
|
||||
visit(value, &format!("{path}[{index}]"), paths, complete);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut explicit_paths = BTreeSet::new();
|
||||
let mut complete = true;
|
||||
visit(document, "", &mut explicit_paths, &mut complete);
|
||||
let censorship = document.get("censorship");
|
||||
let generated_fake_cert_len = censorship
|
||||
.and_then(|v| v.get("tls_emulation"))
|
||||
.and_then(toml::Value::as_bool)
|
||||
== Some(false)
|
||||
&& censorship
|
||||
.and_then(|v| v.get("fake_cert_len"))
|
||||
.and_then(toml::Value::as_integer)
|
||||
.is_none_or(|value| value == super::defaults::default_fake_cert_len() as i64);
|
||||
Arc::new(Self {
|
||||
revision: source_revision(sources),
|
||||
explicit_paths,
|
||||
complete,
|
||||
source_count: sources.len(),
|
||||
generated_fake_cert_len,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub(crate) struct WatchOutcome {
|
||||
pub(crate) sequence: u64,
|
||||
pub(crate) observed_at_epoch_secs: u64,
|
||||
pub(crate) phase: &'static str,
|
||||
/// Source considered by this attempt, not a hash of applied runtime state.
|
||||
pub(crate) source_revision: Option<String>,
|
||||
pub(crate) published_config_epoch: Option<u64>,
|
||||
pub(crate) error_code: Option<&'static str>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct WatchObservation {
|
||||
next_sequence: AtomicU64,
|
||||
latest: ArcSwapOption<WatchOutcome>,
|
||||
}
|
||||
|
||||
impl WatchObservation {
|
||||
pub(crate) fn record(
|
||||
&self,
|
||||
phase: &'static str,
|
||||
revision: Option<String>,
|
||||
epoch: Option<u64>,
|
||||
error_code: Option<&'static str>,
|
||||
) {
|
||||
self.latest.store(Some(Arc::new(WatchOutcome {
|
||||
sequence: self
|
||||
.next_sequence
|
||||
.fetch_add(1, Ordering::Relaxed)
|
||||
.saturating_add(1),
|
||||
observed_at_epoch_secs: SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs(),
|
||||
phase,
|
||||
source_revision: revision,
|
||||
published_config_epoch: epoch,
|
||||
error_code,
|
||||
})));
|
||||
}
|
||||
|
||||
pub(crate) fn snapshot(&self) -> Option<Arc<WatchOutcome>> {
|
||||
self.latest.load_full()
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -58,7 +58,8 @@ pub use server::{
|
||||
pub use web::{
|
||||
WebCarrierNegotiationAggressiveness, WebConfig, WebDecoyConfig, WebDecoyFastTrackMode,
|
||||
WebDecoyResolve, WebHttpConnectionCapacityAction, WebLimitsConfig, WebProfileConfig,
|
||||
WebSecretMode, WebTimeoutsConfig, WebVhostConfig, WebWildcardLimitsConfig,
|
||||
WebRetryJitterConfig, WebRetryJitterDistribution, WebSecretMode, WebTimeoutsConfig,
|
||||
WebVhostConfig, WebWildcardLimitsConfig,
|
||||
};
|
||||
pub(crate) use web::{
|
||||
WebDecoyDnsSnapshot, WebRuntimeConfig, WebRuntimeDecoy, WebRuntimeProfile,
|
||||
|
||||
@@ -14,6 +14,9 @@ mod wildcard;
|
||||
pub use wildcard::WebWildcardLimitsConfig;
|
||||
|
||||
// Serialized WEB defaults remain separate from the runtime data model.
|
||||
mod retry;
|
||||
pub use retry::{WebRetryJitterConfig, WebRetryJitterDistribution};
|
||||
|
||||
mod defaults;
|
||||
use defaults::*;
|
||||
// Decoy fast-track policy remains isolated from the bulky WEB data model.
|
||||
@@ -469,6 +472,9 @@ pub struct WebConfig {
|
||||
/// WEB lifecycle deadlines.
|
||||
#[serde(default)]
|
||||
pub timeouts: WebTimeoutsConfig,
|
||||
/// Additive HTTP retry jitter frozen into each generated bridge page.
|
||||
#[serde(default)]
|
||||
pub retry_jitter: WebRetryJitterConfig,
|
||||
/// Exact hostname and opted-in wildcard groups served by WEB listeners.
|
||||
#[serde(default)]
|
||||
pub vhosts: Vec<WebVhostConfig>,
|
||||
@@ -517,6 +523,7 @@ impl Default for WebConfig {
|
||||
limits: WebLimitsConfig::default(),
|
||||
debug: WebDebugConfig::default(),
|
||||
timeouts: WebTimeoutsConfig::default(),
|
||||
retry_jitter: WebRetryJitterConfig::default(),
|
||||
vhosts: Vec::new(),
|
||||
runtime: None,
|
||||
decoy_dns: Arc::default(),
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Shape of the optional additive HTTP retry delay.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum WebRetryJitterDistribution {
|
||||
/// Equal probability for each integer delay in the configured interval.
|
||||
#[default]
|
||||
Uniform,
|
||||
/// Continuous triangular density rounded to milliseconds.
|
||||
Triangular,
|
||||
}
|
||||
|
||||
/// Page-owned retry policy; configuration reload affects newly rendered bridges.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct WebRetryJitterConfig {
|
||||
/// Replaces the legacy jitter while retaining the underlying retry delay.
|
||||
pub enabled: bool,
|
||||
/// Inclusive minimum additive delay in milliseconds.
|
||||
pub min_ms: u32,
|
||||
/// Inclusive maximum additive delay, bounded to 30000 milliseconds.
|
||||
pub max_ms: u32,
|
||||
/// Probability distribution used independently for each retry.
|
||||
pub distribution: WebRetryJitterDistribution,
|
||||
/// Triangular mode; omission selects the midpoint of the interval.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub peak_ms: Option<u32>,
|
||||
}
|
||||
|
||||
impl Default for WebRetryJitterConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: false,
|
||||
min_ms: 0,
|
||||
max_ms: 250,
|
||||
distribution: WebRetryJitterDistribution::Uniform,
|
||||
peak_ms: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WebRetryJitterConfig {
|
||||
/// Validates inactive policies too, so later activation cannot expose invalid values.
|
||||
pub(crate) fn validate(&self) -> Result<(), &'static str> {
|
||||
if self.min_ms > self.max_ms || self.max_ms > 30000 {
|
||||
return Err("web.retry_jitter requires 0 <= min_ms <= max_ms <= 30000");
|
||||
}
|
||||
if let Some(peak) = self.peak_ms {
|
||||
if self.distribution != WebRetryJitterDistribution::Triangular
|
||||
|| peak < self.min_ms
|
||||
|| peak > self.max_ms
|
||||
{
|
||||
return Err(
|
||||
"web.retry_jitter.peak_ms requires triangular distribution and an in-range peak",
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Emits only typed numeric and boolean literals, without user-controlled script text.
|
||||
pub(crate) fn bridge_policy(&self) -> String {
|
||||
let peak = self
|
||||
.peak_ms
|
||||
.map(f64::from)
|
||||
.unwrap_or((f64::from(self.min_ms) + f64::from(self.max_ms)) / 2.0);
|
||||
format!(
|
||||
"{{enabled:{},min:{},max:{},peak:{},triangular:{}}}",
|
||||
self.enabled,
|
||||
self.min_ms,
|
||||
self.max_ms,
|
||||
peak,
|
||||
self.distribution == WebRetryJitterDistribution::Triangular,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn retry_jitter_validation_and_roundtrip() {
|
||||
let default = WebRetryJitterConfig::default();
|
||||
assert!(!default.enabled);
|
||||
assert_eq!(default.validate(), Ok(()));
|
||||
for (min, max, peak, triangular, valid) in [
|
||||
(0, 250, None, false, true),
|
||||
(250, 250, Some(250), true, true),
|
||||
(0, 30000, Some(0), true, true),
|
||||
(0, 250, Some(250), true, true),
|
||||
(251, 250, None, false, false),
|
||||
(0, 30001, None, false, false),
|
||||
(0, 250, Some(125), false, false),
|
||||
(100, 250, Some(99), true, false),
|
||||
(0, 250, Some(251), true, false),
|
||||
] {
|
||||
for enabled in [false, true] {
|
||||
let policy = WebRetryJitterConfig {
|
||||
enabled,
|
||||
min_ms: min,
|
||||
max_ms: max,
|
||||
peak_ms: peak,
|
||||
distribution: if triangular {
|
||||
WebRetryJitterDistribution::Triangular
|
||||
} else {
|
||||
WebRetryJitterDistribution::Uniform
|
||||
},
|
||||
};
|
||||
assert_eq!(policy.validate().is_ok(), valid);
|
||||
let json = serde_json::to_string(&policy).unwrap();
|
||||
assert_eq!(
|
||||
serde_json::from_str::<WebRetryJitterConfig>(&json).unwrap(),
|
||||
policy
|
||||
);
|
||||
}
|
||||
}
|
||||
for json in [
|
||||
r#"{"min_ms":-1}"#,
|
||||
r#"{"max_ms":1.5}"#,
|
||||
r#"{"distribution":"normal"}"#,
|
||||
r#"{"unknown":1}"#,
|
||||
] {
|
||||
assert!(serde_json::from_str::<WebRetryJitterConfig>(json).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@ pub(crate) struct WebRuntimeVhost {
|
||||
/// Shared automatic-host policy; exact hosts keep their precomputed bindings.
|
||||
pub(crate) wildcard: Option<WebRuntimeWildcard>,
|
||||
/// Canonical lowercase ACE hostname; empty for a wildcard template.
|
||||
#[cfg(test)]
|
||||
pub(crate) host: String,
|
||||
/// Exact slash-delimited endpoint base, including the trailing slash.
|
||||
pub(crate) base: String,
|
||||
|
||||
@@ -57,6 +57,7 @@ impl PidFile {
|
||||
}
|
||||
|
||||
/// Checks whether the PID file names a running process without modifying either file.
|
||||
#[cfg(test)]
|
||||
pub fn check_running(&self) -> Result<Option<i32>, DaemonError> {
|
||||
let Some(pid) = read_pid_file_if_exists(&self.path, self.strict_runtime_paths)? else {
|
||||
return Ok(None);
|
||||
|
||||
+3
-1
@@ -1,6 +1,8 @@
|
||||
#[cfg(any(test, not(unix)))]
|
||||
use std::fs;
|
||||
use std::fs::File;
|
||||
#[cfg(not(unix))]
|
||||
use std::fs::OpenOptions;
|
||||
use std::fs::{self, File};
|
||||
use std::io::{self, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
@@ -207,6 +207,9 @@ pub(super) async fn bootstrap(
|
||||
validate_synlimit_privilege_drop(&config, privilege_drop_requested)?;
|
||||
|
||||
if let Some(p) = data_path {
|
||||
if config.general.data_path.as_ref() != Some(&p) {
|
||||
config.provenance = crate::config::observation::ConfigProvenance::Mixed;
|
||||
}
|
||||
config.general.data_path = Some(p);
|
||||
}
|
||||
|
||||
|
||||
@@ -74,6 +74,7 @@ impl SessionAdmission {
|
||||
.fetch_or(SESSION_ADMISSION_CLOSED, Ordering::AcqRel);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn reopen(&self) {
|
||||
self.state
|
||||
.fetch_and(!SESSION_ADMISSION_CLOSED, Ordering::AcqRel);
|
||||
@@ -379,7 +380,7 @@ pub(crate) fn test_runtime_generation_with_admission(
|
||||
config: ProxyConfig,
|
||||
admission_rx: watch::Receiver<bool>,
|
||||
) -> Arc<RuntimeGeneration> {
|
||||
let (config_tx, config_rx) = watch::channel(Arc::new(config.clone()));
|
||||
let (config_tx, config_rx) = watch::channel(Arc::new(config.clone().with_publication_epoch()));
|
||||
let stats = Arc::new(Stats::new());
|
||||
let upstream_manager = Arc::new(UpstreamManager::new(
|
||||
config.upstreams,
|
||||
|
||||
@@ -13,7 +13,7 @@ use crate::web::manager::{HttpConnectionAdmissionError, WebProcessRuntime};
|
||||
use crate::web::telemetry::{WebHttpConnectionOverloadOutcome, WebRejectionReason};
|
||||
|
||||
/// Exact bounded retryable response emitted before HTTP request parsing.
|
||||
pub(super) const SERVICE_UNAVAILABLE_RESPONSE: &[u8] = b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nCache-Control: no-store\r\nRetry-After: 1\r\nConnection: close\r\n\r\n";
|
||||
pub(super) const SERVICE_UNAVAILABLE_RESPONSE: &[u8] = b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nCache-Control: no-store\r\nRetry-After: 1\r\nX-Telemt-Retry-After-Ms: 250\r\nConnection: close\r\n\r\n";
|
||||
|
||||
/// Handles one accepted WEB socket outside ordinary connection capacity.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -164,6 +164,11 @@ mod tests {
|
||||
let mut bytes = Vec::new();
|
||||
client.read_to_end(&mut bytes).await.unwrap();
|
||||
assert_eq!(bytes, super::SERVICE_UNAVAILABLE_RESPONSE);
|
||||
assert!(
|
||||
bytes
|
||||
.windows(b"X-Telemt-Retry-After-Ms: 250\r\n".len())
|
||||
.any(|window| window == b"X-Telemt-Retry-After-Ms: 250\r\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -191,6 +196,11 @@ mod tests {
|
||||
let mut bytes = Vec::new();
|
||||
client.read_to_end(&mut bytes).await.unwrap();
|
||||
assert_eq!(bytes, super::SERVICE_UNAVAILABLE_RESPONSE);
|
||||
assert!(
|
||||
bytes
|
||||
.windows(b"X-Telemt-Retry-After-Ms: 250\r\n".len())
|
||||
.any(|window| window == b"X-Telemt-Retry-After-Ms: 250\r\n")
|
||||
);
|
||||
assert_eq!(
|
||||
runtime
|
||||
.telemetry()
|
||||
|
||||
@@ -51,6 +51,7 @@ pub(super) async fn run_telemt_core(
|
||||
if privilege_drop_requested && config.server.conntrack_control.inline_conntrack_control {
|
||||
warn!("Inline conntrack control is disabled when process privileges are dropped");
|
||||
config.server.conntrack_control.inline_conntrack_control = false;
|
||||
config.provenance = crate::config::observation::ConfigProvenance::Mixed;
|
||||
}
|
||||
|
||||
let quota_store = Arc::new(QuotaStore::default());
|
||||
|
||||
@@ -9,6 +9,10 @@ use tokio::sync::mpsc;
|
||||
|
||||
use crate::config::ProxyConfig;
|
||||
|
||||
#[path = "reload_observation.rs"]
|
||||
mod observation;
|
||||
pub(crate) use observation::ReloadObservation;
|
||||
|
||||
const RELOAD_HISTORY_CAPACITY: usize = 32;
|
||||
const RELOAD_COMMAND_CAPACITY: usize = 1;
|
||||
const MAX_DRAIN_TIMEOUT_SECS: u64 = 3_600;
|
||||
@@ -151,6 +155,16 @@ pub(crate) struct ReloadStatus {
|
||||
pub(crate) warnings: Vec<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub(crate) error: Option<String>,
|
||||
#[serde(skip)]
|
||||
source_generation: Option<u64>,
|
||||
#[serde(skip)]
|
||||
activated_generation: Option<u64>,
|
||||
#[serde(skip)]
|
||||
retiring_generation: Option<u64>,
|
||||
#[serde(skip)]
|
||||
retiring_config_epoch: Option<u64>,
|
||||
#[serde(skip)]
|
||||
retirement: Option<&'static str>,
|
||||
}
|
||||
|
||||
/// Accepted operation metadata returned before asynchronous preparation starts.
|
||||
@@ -395,6 +409,11 @@ impl ReloadStatusStore {
|
||||
deferred_fields: Vec::new(),
|
||||
warnings: Vec::new(),
|
||||
error: None,
|
||||
source_generation: None,
|
||||
activated_generation: None,
|
||||
retiring_generation: None,
|
||||
retiring_config_epoch: None,
|
||||
retirement: None,
|
||||
};
|
||||
state.active_reload_id = Some(reload_id);
|
||||
state.statuses.push_back(status.clone());
|
||||
@@ -416,6 +435,9 @@ impl ReloadStatusStore {
|
||||
fn mark_phase(&self, reload_id: u64, phase: ReloadPhase) {
|
||||
self.update(reload_id, |status| {
|
||||
status.state = phase;
|
||||
if phase == ReloadPhase::Draining {
|
||||
status.retirement = Some("draining");
|
||||
}
|
||||
if status.started_at_epoch_secs.is_none() && phase != ReloadPhase::Accepted {
|
||||
status.started_at_epoch_secs = Some(now_epoch_secs());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
use serde::Serialize;
|
||||
|
||||
use super::{ReloadControl, ReloadPhase};
|
||||
|
||||
/// Sanitized owner snapshot. Raw reload errors/warnings can contain source data.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub(crate) struct ReloadObservation {
|
||||
pub(crate) reload_id: u64,
|
||||
pub(crate) target_generation: u64,
|
||||
pub(crate) source_revision: String,
|
||||
pub(crate) phase: ReloadPhase,
|
||||
pub(crate) source_generation: Option<u64>,
|
||||
pub(crate) activated_generation: Option<u64>,
|
||||
pub(crate) retiring_generation: Option<u64>,
|
||||
pub(crate) retiring_config_epoch: Option<u64>,
|
||||
pub(crate) retirement: Option<&'static str>,
|
||||
pub(crate) error_present: bool,
|
||||
pub(crate) warning_count: usize,
|
||||
}
|
||||
|
||||
impl ReloadControl {
|
||||
/// Reads bounded owner metadata without waiting for a contended status lock.
|
||||
pub(crate) fn observation(&self) -> Option<Option<ReloadObservation>> {
|
||||
let state = self.status_store.state.try_lock()?;
|
||||
Some(state.statuses.back().map(|status| ReloadObservation {
|
||||
reload_id: status.reload_id,
|
||||
target_generation: status.target_generation,
|
||||
source_revision: status.config_revision.clone(),
|
||||
phase: status.state,
|
||||
source_generation: status.source_generation,
|
||||
activated_generation: status.activated_generation,
|
||||
retiring_generation: status.retiring_generation,
|
||||
retiring_config_epoch: status.retiring_config_epoch,
|
||||
retirement: status.retirement,
|
||||
error_present: status.error.is_some(),
|
||||
warning_count: status.warnings.len(),
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) fn record_source_generation(&self, id: u64, generation: u64) {
|
||||
self.status_store
|
||||
.update(id, |status| status.source_generation = Some(generation));
|
||||
}
|
||||
|
||||
pub(crate) fn record_activation(
|
||||
&self,
|
||||
id: u64,
|
||||
active: u64,
|
||||
retiring: u64,
|
||||
retiring_epoch: u64,
|
||||
) {
|
||||
self.status_store.update(id, |status| {
|
||||
status.activated_generation = Some(active);
|
||||
status.retiring_generation = Some(retiring);
|
||||
status.retiring_config_epoch = Some(retiring_epoch);
|
||||
status.retirement = Some("retiring");
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn record_retirement(&self, id: u64, timed_out: bool) {
|
||||
self.status_store.update(id, |status| {
|
||||
status.retirement = Some(if timed_out {
|
||||
"cleanup_timeout"
|
||||
} else {
|
||||
"retired"
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -163,6 +163,8 @@ impl ReloadSupervisor {
|
||||
.mark_phase(command.reload_id, ReloadPhase::Preparing)
|
||||
.await;
|
||||
let old_runtime = self.active_runtime.load_full();
|
||||
self.control
|
||||
.record_source_generation(command.reload_id, old_runtime.id);
|
||||
let resolved = match resolve_reload_config(&old_runtime.config(), &command.config) {
|
||||
Ok(resolved) => resolved,
|
||||
Err(error) => {
|
||||
@@ -351,6 +353,12 @@ impl ReloadSupervisor {
|
||||
old_runtime.stop_accepting_sessions();
|
||||
listener_manager.activate_runtime_generation(new_runtime.clone())
|
||||
};
|
||||
self.control.record_activation(
|
||||
command.reload_id,
|
||||
new_runtime.id,
|
||||
replaced.id,
|
||||
replaced.config().runtime_config_epoch,
|
||||
);
|
||||
// A rejected admission epoch must not be bypassed by reapplying the prepared
|
||||
// snapshot. Quota publication retains its credential and source checks.
|
||||
let config = new_runtime.config();
|
||||
@@ -422,7 +430,10 @@ impl ReloadSupervisor {
|
||||
}
|
||||
}
|
||||
|
||||
if stop_background_and_middle_end(&replaced).await {
|
||||
let retirement_timed_out = stop_background_and_middle_end(&replaced).await;
|
||||
self.control
|
||||
.record_retirement(command.reload_id, retirement_timed_out);
|
||||
if retirement_timed_out {
|
||||
let warning = format!(
|
||||
"generation {} Middle-End lifecycle shutdown timed out",
|
||||
replaced.id
|
||||
|
||||
@@ -158,6 +158,11 @@ async fn revision_rollback_keeps_old_generation_and_cleans_candidate() {
|
||||
assert!(fixture.old_runtime.spawn_session(async {}));
|
||||
let status = fixture.control.status(1).await.unwrap();
|
||||
assert_eq!(status.state, ReloadPhase::RolledBack);
|
||||
let observed = fixture.control.observation().unwrap().unwrap();
|
||||
assert_eq!(observed.phase, ReloadPhase::RolledBack);
|
||||
assert_eq!(observed.activated_generation, None);
|
||||
assert_eq!(observed.retiring_generation, None);
|
||||
assert_eq!(observed.retirement, None);
|
||||
fixture.old_runtime.stop_sessions().await;
|
||||
}
|
||||
|
||||
@@ -206,12 +211,33 @@ async fn drain_publishes_new_generation_before_old_sessions_finish() {
|
||||
assert!(!activation.is_finished());
|
||||
assert!(!fixture.old_runtime.spawn_session(async {}));
|
||||
|
||||
tokio::time::timeout(Duration::from_secs(1), async {
|
||||
while fixture.control.status(1).await.unwrap().state != ReloadPhase::Draining {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let observed = fixture.control.observation().unwrap().unwrap();
|
||||
assert_eq!(observed.phase, ReloadPhase::Draining);
|
||||
assert_eq!(observed.activated_generation, Some(2));
|
||||
assert_eq!(observed.retiring_generation, Some(1));
|
||||
assert_eq!(
|
||||
observed.retiring_config_epoch,
|
||||
Some(fixture.old_runtime.config().runtime_config_epoch)
|
||||
);
|
||||
assert_eq!(observed.retirement, Some("draining"));
|
||||
|
||||
old_release.notify_one();
|
||||
activation.await.unwrap();
|
||||
assert_eq!(
|
||||
fixture.control.status(1).await.unwrap().state,
|
||||
ReloadPhase::Succeeded
|
||||
);
|
||||
let observed = fixture.control.observation().unwrap().unwrap();
|
||||
assert_eq!(observed.phase, ReloadPhase::Succeeded);
|
||||
assert_eq!(observed.retiring_generation, Some(1));
|
||||
assert_eq!(observed.retirement, Some("retired"));
|
||||
fixture.new_runtime.stop_sessions().await;
|
||||
}
|
||||
|
||||
@@ -257,6 +283,23 @@ async fn drain_timeout_cancels_old_sessions_and_records_one_warning() {
|
||||
fixture.new_runtime.stop_sessions().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejected_reload_observes_source_generation_without_activation() {
|
||||
let mut fixture = fixture(ReloadRequest::default()).await;
|
||||
Arc::make_mut(&mut fixture.command.config).web.enabled = true;
|
||||
fixture.supervisor.reload(fixture.command).await;
|
||||
let observed = fixture.control.observation().unwrap().unwrap();
|
||||
assert_eq!(observed.phase, ReloadPhase::Failed);
|
||||
assert_eq!(observed.source_generation, Some(1));
|
||||
assert_eq!(observed.activated_generation, None);
|
||||
assert_eq!(observed.retiring_generation, None);
|
||||
assert!(observed.error_present);
|
||||
assert!(Arc::ptr_eq(
|
||||
&fixture.supervisor.active_runtime.load_full(),
|
||||
&fixture.old_runtime
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn quiesce_joins_idle_supervisor_and_rejects_later_submissions() {
|
||||
let runtime = test_runtime_generation(1, ProxyConfig::default());
|
||||
|
||||
@@ -48,6 +48,11 @@ fn status_uses_documented_deferred_process_fields_key() {
|
||||
deferred_fields: vec!["server.listeners".to_string()],
|
||||
warnings: Vec::new(),
|
||||
error: None,
|
||||
source_generation: Some(1),
|
||||
activated_generation: Some(2),
|
||||
retiring_generation: Some(1),
|
||||
retiring_config_epoch: Some(3),
|
||||
retirement: Some("retired"),
|
||||
};
|
||||
let value = serde_json::to_value(status).unwrap();
|
||||
|
||||
@@ -56,6 +61,27 @@ fn status_uses_documented_deferred_process_fields_key() {
|
||||
serde_json::json!(["server.listeners"])
|
||||
);
|
||||
assert!(value.get("deferred_fields").is_none());
|
||||
for field in [
|
||||
"source_generation",
|
||||
"activated_generation",
|
||||
"retiring_generation",
|
||||
"retiring_config_epoch",
|
||||
"retirement",
|
||||
] {
|
||||
assert!(
|
||||
value.get(field).is_none(),
|
||||
"Legacy reload response gained {field}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn state_observation_never_waits_on_the_reload_status_lock() {
|
||||
let (control, _receiver) = ReloadControl::channel(1);
|
||||
let guard = control.status_store.state.lock();
|
||||
assert!(control.observation().is_none());
|
||||
drop(guard);
|
||||
assert!(control.observation().unwrap().is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -334,6 +334,29 @@ pub(crate) fn resolve_reload_config(
|
||||
old: &ProxyConfig,
|
||||
desired: &ProxyConfig,
|
||||
) -> Result<ResolvedReloadConfig, String> {
|
||||
let mut resolved = project_reload_config(old, desired);
|
||||
resolved
|
||||
.effective
|
||||
.validate_effective_web()
|
||||
.map_err(|error| format!("effective WEB configuration is invalid: {error}"))?;
|
||||
resolved
|
||||
.effective
|
||||
.rebuild_runtime_user_auth()
|
||||
.map_err(|error| format!("effective user runtime preparation failed: {error}"))?;
|
||||
resolved
|
||||
.effective
|
||||
.rebuild_runtime_web()
|
||||
.map_err(|error| format!("effective WEB runtime preparation failed: {error}"))?;
|
||||
resolved.runtime_changed = !configs_equal(old, &resolved.effective);
|
||||
Ok(resolved)
|
||||
}
|
||||
|
||||
/// Projects retained process policy without DNS, static acquisition or validation.
|
||||
/// State inspection uses this projection; preflight still uses the full resolver.
|
||||
pub(crate) fn project_reload_config(
|
||||
old: &ProxyConfig,
|
||||
desired: &ProxyConfig,
|
||||
) -> ResolvedReloadConfig {
|
||||
let mut effective = desired.clone();
|
||||
let mut fields = Vec::new();
|
||||
let listener_identity_matches = listeners_have_same_bind_identity(&old.server, &desired.server);
|
||||
@@ -462,21 +485,15 @@ pub(crate) fn resolve_reload_config(
|
||||
fields.push("web.debug".to_string());
|
||||
effective.web.debug = old.web.debug.clone();
|
||||
}
|
||||
effective
|
||||
.validate_effective_web()
|
||||
.map_err(|error| format!("effective WEB configuration is invalid: {error}"))?;
|
||||
effective
|
||||
.rebuild_runtime_user_auth()
|
||||
.map_err(|error| format!("effective user runtime preparation failed: {error}"))?;
|
||||
effective
|
||||
.rebuild_runtime_web()
|
||||
.map_err(|error| format!("effective WEB runtime preparation failed: {error}"))?;
|
||||
if !fields.is_empty() {
|
||||
effective.provenance = crate::config::observation::ConfigProvenance::Mixed;
|
||||
}
|
||||
let runtime_changed = !configs_equal(old, &effective);
|
||||
Ok(ResolvedReloadConfig {
|
||||
ResolvedReloadConfig {
|
||||
effective,
|
||||
deferred_process_fields: fields,
|
||||
runtime_changed,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn listeners_have_same_bind_identity(old: &ServerConfig, desired: &ServerConfig) -> bool {
|
||||
|
||||
@@ -172,6 +172,9 @@ pub(super) async fn prepare_runtime(
|
||||
} else {
|
||||
let _ = use_middle_proxy;
|
||||
use_middle_proxy = false;
|
||||
if config.general.use_middle_proxy {
|
||||
config.provenance = crate::config::observation::ConfigProvenance::Mixed;
|
||||
}
|
||||
config.general.use_middle_proxy = false;
|
||||
startup_tracker.set_transport_mode("direct").await;
|
||||
startup_tracker.set_degraded(true).await;
|
||||
|
||||
@@ -297,6 +297,7 @@ impl Drop for UserIpPermit {
|
||||
|
||||
impl UserConnectionReservation {
|
||||
/// Creates an active reservation after both admission counters were acquired.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn new(
|
||||
stats: Arc<Stats>,
|
||||
ip_tracker: Arc<UserIpTracker>,
|
||||
@@ -375,6 +376,7 @@ impl Drop for UserConnectionReservation {
|
||||
}
|
||||
|
||||
/// Applies user quota, connection, and source-IP admission atomically.
|
||||
#[cfg(test)]
|
||||
pub(crate) async fn acquire_user_connection_reservation(
|
||||
user: &str,
|
||||
config: &ProxyConfig,
|
||||
|
||||
+3
-3
@@ -71,9 +71,9 @@ mod authenticated;
|
||||
use handshake_support::*;
|
||||
#[cfg(test)]
|
||||
pub use stream_entry::handle_client_stream;
|
||||
pub use stream_entry::{
|
||||
handle_client_stream_with_shared, handle_client_stream_with_shared_and_pool_runtime,
|
||||
};
|
||||
#[cfg(test)]
|
||||
pub use stream_entry::handle_client_stream_with_shared;
|
||||
pub use stream_entry::handle_client_stream_with_shared_and_pool_runtime;
|
||||
|
||||
pub struct ClientHandler;
|
||||
|
||||
|
||||
@@ -41,7 +41,8 @@ where
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[allow(dead_code)]
|
||||
/// Runs a client stream with shared process state in tests.
|
||||
#[cfg(test)]
|
||||
pub async fn handle_client_stream_with_shared<S>(
|
||||
stream: S,
|
||||
peer: SocketAddr,
|
||||
|
||||
@@ -269,6 +269,7 @@ impl DirectBufferBudget {
|
||||
}
|
||||
|
||||
/// Returns the conservative ceiling used when memory discovery is unavailable.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn fallback_direct_buffer_hard_limit() -> usize {
|
||||
AUTO_HARD_FALLBACK_BYTES
|
||||
}
|
||||
|
||||
@@ -43,9 +43,9 @@ mod relay;
|
||||
// Telegram DC resolution and upstream handshake.
|
||||
mod routing;
|
||||
|
||||
pub(crate) use relay::{
|
||||
handle_via_direct, handle_via_direct_with_shared, handle_via_direct_with_shared_and_conntrack,
|
||||
};
|
||||
#[cfg(test)]
|
||||
pub(crate) use relay::handle_via_direct;
|
||||
pub(crate) use relay::handle_via_direct_with_shared_and_conntrack;
|
||||
use routing::*;
|
||||
const UNKNOWN_DC_LOG_DISTINCT_LIMIT: usize = 1024;
|
||||
static LOGGED_UNKNOWN_DCS: OnceLock<Mutex<HashSet<i16>>> = OnceLock::new();
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user