mirror of
https://github.com/telemt/telemt.git
synced 2026-11-22 15:26:37 +03:00
API: add dry-run validation with change preview and runtime guards
This commit is contained in:
+47
-155
@@ -6,14 +6,13 @@ 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,
|
||||
load_config_snapshot, render_server_listeners, render_top_level_section,
|
||||
resolve_single_source_owner, 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 +24,12 @@ use serde::Serialize;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
mod diagnostics;
|
||||
mod preflight;
|
||||
mod preparation;
|
||||
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 +45,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 +61,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 +70,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 +78,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 +93,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 +125,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 +150,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 +179,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(
|
||||
@@ -470,3 +359,6 @@ mod host_list_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod quota_period_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod preflight_tests;
|
||||
|
||||
Reference in New Issue
Block a user