Skip to main content

active_call/handler/
reload.rs

1//! Config hot-reload HTTP surface.
2//!
3//! ```text
4//! POST /reload?mode=check   validate the file, report what would change
5//! POST /reload?mode=apply   validate and install the new snapshot
6//! GET  /config              effective config (secrets redacted) + revision
7//! ```
8//!
9//! When `[reload] token = "..."` (or `PBX_RELOAD_TOKEN`) is set, every request
10//! must carry it in `X-Reload-Token`; otherwise the routes are unauthenticated
11//! and rely on the ops firewall, like rustpbx's `/reload/*` routes.
12
13use axum::{
14    Json, Router,
15    extract::{Query, State},
16    http::{HeaderMap, StatusCode},
17    response::{IntoResponse, Response},
18    routing::{get, post},
19};
20use serde::Deserialize;
21use serde_json::json;
22
23use crate::app::AppState;
24
25#[derive(Debug, Deserialize)]
26pub struct ReloadParams {
27    /// `check`/`validate`/`dry_run` = do not install; `apply` (default) = install.
28    pub mode: Option<String>,
29}
30
31pub fn reload_router() -> Router<AppState> {
32    Router::new()
33        .route("/reload", post(reload_handler))
34        .route("/config", get(config_handler))
35}
36
37fn authorized(state: &AppState, headers: &HeaderMap) -> bool {
38    let Some(expected) = state.config().reload_token().map(str::to_string) else {
39        return true;
40    };
41    headers
42        .get("x-reload-token")
43        .and_then(|v| v.to_str().ok())
44        .map(|v| v == expected)
45        .unwrap_or(false)
46}
47
48async fn reload_handler(
49    State(state): State<AppState>,
50    Query(params): Query<ReloadParams>,
51    headers: HeaderMap,
52) -> Response {
53    if !authorized(&state, &headers) {
54        return (
55            StatusCode::UNAUTHORIZED,
56            Json(json!({"status": "error", "message": "invalid or missing X-Reload-Token"})),
57        )
58            .into_response();
59    }
60
61    let check_only = matches!(
62        params.mode.as_deref().map(str::to_ascii_lowercase).as_deref(),
63        Some("check") | Some("validate") | Some("dry_run") | Some("dry-run")
64    );
65
66    let Some(path) = state.config_path().map(str::to_string) else {
67        return (
68            StatusCode::BAD_REQUEST,
69            Json(json!({
70                "status": "error",
71                "message": "no config path recorded at startup; start with --conf / with_config_metadata",
72            })),
73        )
74            .into_response();
75    };
76
77    // Parse + env overrides exactly like startup.
78    let proposed = match crate::config::Config::load(&path) {
79        Ok(config) => config,
80        Err(e) => {
81            tracing::warn!(path = %path, check_only, error = %e, "reload: config parse failed");
82            return (
83                StatusCode::UNPROCESSABLE_ENTITY,
84                Json(json!({
85                    "status": "invalid",
86                    "message": format!("{path}: {e}"),
87                })),
88            )
89                .into_response();
90        }
91    };
92
93    let report = if check_only {
94        state.preview_config(proposed)
95    } else {
96        state.apply_config(proposed)
97    };
98
99    let body = json!({
100        "status": report.status,
101        "mode": if check_only { "check" } else { "apply" },
102        "revision": report.revision,
103        "path": path,
104        "applied": report.applied,
105        "deferred": report.deferred,
106        "requires_restart": report.requires_restart,
107    });
108
109    if check_only {
110        tracing::info!(path = %path, changed = ?report.applied, "reload: check ok");
111    } else {
112        tracing::info!(
113            path = %path,
114            applied = ?report.applied,
115            deferred = ?report.deferred,
116            requires_restart = ?report.requires_restart,
117            "CONFIGRELOAD applied"
118        );
119    }
120
121    Json(body).into_response()
122}
123
124async fn config_handler(State(state): State<AppState>, headers: HeaderMap) -> Response {
125    if !authorized(&state, &headers) {
126        return (
127            StatusCode::UNAUTHORIZED,
128            Json(json!({"status": "error", "message": "invalid or missing X-Reload-Token"})),
129        )
130            .into_response();
131    }
132
133    let config = state.config();
134    let mut value = serde_json::to_value(&*config).unwrap_or_else(|_| json!({}));
135    redact_secrets(&mut value);
136
137    let switches = crate::runtime::module_switches();
138    Json(json!({
139        "path": state.config_path(),
140        "config": value,
141        "effective": {
142            "admission": {
143                "max_active_calls": config.admission_max_calls(),
144                "wait_ms": config.admission_wait_ms(),
145                "active_sessions": crate::call::active_call::ACTIVE_SESSIONS
146                    .load(std::sync::atomic::Ordering::Relaxed),
147            },
148            "modules": {
149                "denoise": switches.denoise,
150                "vad": switches.vad,
151                "eou": switches.eou,
152                "ringback_detection": switches.ringback_detection,
153                "sipflow": switches.sipflow,
154                "playbooks": switches.playbooks,
155            },
156        },
157    }))
158    .into_response()
159}
160
161/// Blank out credential-looking string fields wherever they appear.
162fn redact_secrets(value: &mut serde_json::Value) {
163    match value {
164        serde_json::Value::Object(map) => {
165            for (key, slot) in map.iter_mut() {
166                let k = key.to_ascii_lowercase();
167                if k.contains("secret") || k.contains("password") || k.contains("token") {
168                    *slot = json!("***");
169                } else {
170                    redact_secrets(slot);
171                }
172            }
173        }
174        serde_json::Value::Array(items) => items.iter_mut().for_each(redact_secrets),
175        _ => {}
176    }
177}
178
179#[cfg(test)]
180mod tests {
181    use super::redact_secrets;
182    use serde_json::json;
183
184    #[test]
185    fn redacts_secrets_recursively() {
186        let mut value = json!({
187            "callrecord": {"secret_key": "abc", "bucket": "b"},
188            "nested": [{"api_token": "t"}, {"plain": 1}],
189        });
190        redact_secrets(&mut value);
191        assert_eq!(value["callrecord"]["secret_key"], "***");
192        assert_eq!(value["callrecord"]["bucket"], "b");
193        assert_eq!(value["nested"][0]["api_token"], "***");
194        assert_eq!(value["nested"][1]["plain"], 1);
195    }
196}