diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e562fd1..231491df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,15 @@ recognisable path forward. ### Added +- **Multi-server installs** (#230). Every ZoneMinder server runs a zm-api, + and a request for a monitor another server runs is relayed to the zm-api + there with the caller's own token: live HLS, WHEP, snapshots, alarms, PTZ, + monitor state, pipeline, and edits to the monitor's row. A client needs one + address. Every server must share the same JWT key files. New `[cluster]` + settings name the other servers where the default (this server's scheme and + port on `Servers.Hostname`) is wrong. `GET /api/v3/servers` gains `api_url` + and `is_this_server`. See the multi-server guide for the limits: WebSocket + signalling, system-wide control and recordings are not relayed yet. - **Live event stream**, `GET /api/v3/events/stream` (Server-Sent Events): `event_start`, `event_end` and `event_updated` (notes changed, where object detection writes) for every monitor the caller may see, and each monitor's diff --git a/Cargo.lock b/Cargo.lock index e21b9b1a..043095fe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4898,12 +4898,14 @@ dependencies = [ "tokio", "tokio-native-tls", "tokio-rustls", + "tokio-util", "tower", "tower-http 0.6.11", "tower-service", "url", "wasm-bindgen", "wasm-bindgen-futures", + "wasm-streams", "web-sys", ] @@ -7423,6 +7425,19 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "wasm-streams" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "web-sys" version = "0.3.106" diff --git a/Cargo.toml b/Cargo.toml index 2b0c416c..93d210c0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -94,7 +94,7 @@ openssl = "0.10" once_cell = "1" rand = "0.10" regex = "1" -reqwest = { version = "0.13", features = ["json"] } +reqwest = { version = "0.13", features = ["json", "stream"] } rust_decimal = "1" test-context = "0.5" thiserror = "2" diff --git a/book/src/SUMMARY.md b/book/src/SUMMARY.md index 1dd7d810..b0f065f2 100644 --- a/book/src/SUMMARY.md +++ b/book/src/SUMMARY.md @@ -15,6 +15,7 @@ - [Configuration](guide/configuration.md) - [TLS and certificates](guide/tls.md) - [Passive and takeover mode](guide/takeover.md) +- [Multi-server installs](guide/multi-server.md) - [Recording retention](guide/retention.md) - [Replacing the Perl daemons](guide/maintenance.md) diff --git a/book/src/guide/multi-server.md b/book/src/guide/multi-server.md new file mode 100644 index 00000000..ac0c186b --- /dev/null +++ b/book/src/guide/multi-server.md @@ -0,0 +1,62 @@ +# Multi-server installs + +A ZoneMinder install can spread its cameras over several servers that share one database. Each camera belongs to one server, named by `Monitors.ServerId`. + +Three things a monitor needs exist only on the server that runs it: its shared memory, the stream socket zmc serves video on, and the daemon control socket. So a zm-api can serve live video, snapshots, alarms and daemon control for its own server's monitors and no others. + +## How it works + +Run zm-api on every server. A client can talk to any one of them. + +When a request arrives for a monitor another server runs, zm-api sends the same request to the zm-api on that server and streams the answer back. The client never needs a second address. + +The relayed request carries the caller's own token. The owning server authenticates it and applies that user's permissions as it would for a direct request. No server holds a credential that can act as anyone. + +What is relayed: + +- live HLS, live start and stop, live stats, WHEP +- snapshots +- forcing and cancelling an alarm +- PTZ +- a monitor's state (start, stop, restart), its pipeline, and edits to and deletion of its row +- running a monitor action + +What stays on the server the client asked: anything that only reads or writes the database, such as listing monitors, reading a monitor's row, events and users. + +## Setup + +1. **Give every server the same JWT keys.** Copy the four key files named under `[secret]` from one server to the others. A token issued by one server must verify on all of them. This also makes signed media links valid on every server. +2. **Check each server knows who it is.** zm-api reads `ZM_SERVER_ID`, `ZM_SERVER_NAME` or `ZM_SERVER_HOST` from `zm.conf`, as ZoneMinder does. Its log says `This host is Servers.Id N` at startup. +3. **Check the servers can reach each other.** By default a server expects to find another one at its own scheme and port on that server's `Servers.Hostname`. If that is wrong for a server, name its address: + +```toml +[cluster] +peer_port = 8443 # if the others listen on a different port than this one + +[cluster.peers] +2 = "https://zm2.lan:8443" +``` + +`GET /api/v3/servers` shows the address each server was resolved to, as `api_url`, and marks the one that answered with `is_this_server`. + +If the servers use certificates from a private CA, point `cluster.tls_ca_file` at its PEM file. + +## When something is wrong + +| Answer | Meaning | +|---|---| +| 502 `server 2 (zm2) did not answer` | The owning server is down or unreachable from this one. | +| 502 `refused credentials this server accepted` | The servers have different JWT keys. Copy the key files. | +| 421 `belongs to server 2, which has no address` | The `Servers` row has no hostname and `cluster.peers` names none. | +| 421 `the servers disagree` | Two servers each think the other runs the monitor. Check `ZM_SERVER_ID` on both. | + +## Limits + +- **WebRTC media goes direct.** WHEP signalling is relayed, but the video itself travels over UDP from the server that runs the camera. The viewer must be able to reach that server. +- **WebSocket signalling is not relayed.** A WebSocket for another server's monitor answers 421 with that server's address. Use WHEP, or connect to that server. +- **System-wide control is per server.** `/api/v3/daemons` and `/api/v3/system/*` act on the server that receives them. +- **Recordings are served by the server asked.** Event video and frame images are read from that server's filesystem, so they need storage every server can reach. +- **A logout takes up to ten seconds to reach the other servers.** Each server re-reads the token floors from the database on that interval. +- **Rate limits see the relaying server.** A relayed request arrives from another server's address, with the client's own appended to `X-Forwarded-For`. The global limiter is off by default. If you turn it on, set `trust_proxy_headers = true` and list the other servers in `trusted_proxies`, so each client is counted on its own. + +Turning relaying off with `cluster.enabled = false` restores the old behaviour, where requests for another server's monitor fail locally. diff --git a/openapi.json b/openapi.json index e8dd9bd7..78369321 100644 --- a/openapi.json +++ b/openapi.json @@ -3842,8 +3842,6 @@ "tags": [ "Events" ], - "summary": "Export events as a zip", - "description": "Streams a zip, built as it goes, with a `{event_id}/` folder per event\nholding the parts asked for: `details` (`event.json`), `frames`\n(`frames.json`), `images`, `video` and `misc` (the event directory's other\nfiles). Every id is checked first: one that doesn't exist or isn't\nvisible to the caller is a 404 and nothing is sent.", "operationId": "exportEvents", "requestBody": { "content": { @@ -21993,6 +21991,32 @@ } } }, + { + "type": "object", + "description": "Another server of a multi-server install did not answer a relayed\nrequest, or answered it in a way that only a setup fault explains.", + "required": [ + "BadGatewayError" + ], + "properties": { + "BadGatewayError": { + "type": "string", + "description": "Another server of a multi-server install did not answer a relayed\nrequest, or answered it in a way that only a setup fault explains." + } + } + }, + { + "type": "object", + "description": "The request is for another server's monitor and this server can't\nrelay it. The message names the server that can answer.", + "required": [ + "MisdirectedError" + ], + "properties": { + "MisdirectedError": { + "type": "string", + "description": "The request is for another server's monitor and this server can't\nrelay it. The message names the server that can answer." + } + } + }, { "type": "object", "description": "A 503 for something that will be back shortly, with a Retry-After of\nthis many seconds.", @@ -24497,7 +24521,6 @@ }, "CreateFilterRequest": { "type": "object", - "description": "Create a saved event filter. `name` and `query_json` are required; every\nother column of the `Filters` table is optional and falls back to the\nschema default when omitted (flags `0`, `execute_interval` `60`,\n`email_format` `Individual`).", "required": [ "name" ], @@ -26969,7 +26992,8 @@ "minimum": 0 }, "username": { - "type": "string" + "type": "string", + "description": "The characters login accepts. Anything else could not sign in, and a\ncontrol character would end up in the log lines that name the user." } } } @@ -33904,6 +33928,13 @@ "zmeventnotification" ], "properties": { + "api_url": { + "type": [ + "string", + "null" + ], + "description": "Where this server's zm-api is, as the server answering works it out:\nits `cluster.peers` setting, else its own scheme and port on this\nrow's hostname. Absent when the row has no hostname. A client does not\nneed it: any server relays requests for another server's monitors." + }, "hostname": { "type": [ "string", @@ -33915,6 +33946,10 @@ "format": "int32", "minimum": 0 }, + "is_this_server": { + "type": "boolean", + "description": "Whether this is the server that answered." + }, "latitude": { "type": [ "number", @@ -38465,7 +38500,7 @@ "string", "null" ], - "description": "New password (re-hashed with bcrypt; never stored in plaintext)." + "description": "New password (re-hashed with bcrypt; never stored in plaintext).\nEmpty leaves the password as it is." }, "phone": { "type": [ diff --git a/settings/base.toml b/settings/base.toml index b24bd1fc..a96f8126 100644 --- a/settings/base.toml +++ b/settings/base.toml @@ -364,3 +364,24 @@ max_age_days = 0 max_bytes = 0 # Log what would be deleted without deleting (eyeball before enforcing). dry_run = false + +# Multi-server installs only. Each ZoneMinder server runs its own zm-api, and +# a request for a monitor another server runs is relayed to the zm-api there, +# with the caller's own token. Every server must use the same JWT key files +# ([secret]), or the owning server refuses the relayed token. +# +# Nothing here applies to a single-server install. +[cluster] +enabled = true +# The port zm-api listens on at the other servers. Default: this server's own. +# peer_port = 8443 +connect_timeout_secs = 5 +# How long another server may go without sending anything. +read_timeout_secs = 30 +# Extra root certificates to trust for the other servers (a private CA). +# tls_ca_file = "/etc/zm-api/cluster-ca.pem" + +# A server's zm-api is assumed to be at this server's scheme and peer_port on +# its Servers.Hostname. Name it here, by Servers.Id, when it is somewhere else. +# [cluster.peers] +# 2 = "https://zm2.lan:8443" diff --git a/src/cluster/forward.rs b/src/cluster/forward.rs new file mode 100644 index 00000000..87f2a998 --- /dev/null +++ b/src/cluster/forward.rs @@ -0,0 +1,397 @@ +//! Relay a request for another server's monitor to the zm-api there. +//! +//! [`forward_to_owner`] sits behind the authentication and monitor guards of +//! the routes that touch a monitor's node-local resources. For a monitor +//! this server owns it does nothing. For another server's monitor it sends +//! the same request there, with the caller's own credentials, and streams +//! the answer back, so a client only ever needs one address. + +use axum::body::Body; +use axum::extract::{OriginalUri, RawPathParams, Request, State}; +use axum::http::{header, HeaderMap, HeaderName, HeaderValue, Method}; +use axum::middleware::Next; +use axum::response::Response; +use tracing::{debug, warn}; + +use super::{Owner, Peer}; +use crate::error::{AppError, AppResult, Resource, ResourceType}; +use crate::server::state::AppState; +use crate::service::monitor_acl::{self, MonitorScope}; +use crate::util::authz::Level; +use crate::util::claim::UserClaims; + +/// Set on a relayed request to the id of the server that relayed it. A +/// server that receives it never relays again, so two servers that disagree +/// about who owns a monitor answer with an error, not a loop. +pub const FORWARDED_BY: HeaderName = HeaderName::from_static("x-zm-forwarded-by"); + +const X_FORWARDED_FOR: HeaderName = HeaderName::from_static("x-forwarded-for"); + +/// The largest request body relayed. Every relayed route takes a small JSON +/// document or an SDP offer. +const MAX_RELAYED_BODY: usize = 2 * 1024 * 1024; + +/// Headers that describe one connection, not the request, and so are not +/// passed on (RFC 9110 §7.6.1), plus the two the HTTP client sets itself. +const HOP_BY_HOP: [HeaderName; 9] = [ + header::CONNECTION, + header::PROXY_AUTHENTICATE, + header::PROXY_AUTHORIZATION, + header::TE, + header::TRAILER, + header::TRANSFER_ENCODING, + header::UPGRADE, + header::HOST, + header::CONTENT_LENGTH, +]; + +/// Whether a route stays on this server even for another server's monitor. +/// +/// - Reading a monitor's row is a database read any server can do. +/// - A signed playlist link is minted here, so the client keeps the one +/// address it already has. The link is valid on every server, and the +/// playlist requests that follow it are relayed. +fn stays_local(method: &Method, path: &str) -> bool { + let path = path.trim_end_matches('/'); + if path.ends_with("/hls/link") { + return true; + } + let is_read = matches!(*method, Method::GET | Method::HEAD | Method::OPTIONS); + let last_is_the_id = path + .rsplit_once('/') + .is_some_and(|(parent, last)| parent.ends_with("/monitors") && last.parse::().is_ok()); + is_read && last_is_the_id +} + +/// The middleware. Apply with `route_layer`, inside the guards. +pub async fn forward_to_owner( + State(state): State, + params: RawPathParams, + request: Request, + next: Next, +) -> Result { + if !state.cluster.relays() { + return Ok(next.run(request).await); + } + let Some(monitor_id) = monitor_acl::path_monitor_id(¶ms) else { + return Ok(next.run(request).await); + }; + let path_and_query = original_path_and_query(&request); + let path = path_and_query.split('?').next().unwrap_or_default(); + if stays_local(request.method(), path) { + return Ok(next.run(request).await); + } + let Owner::Peer(server_id) = state.cluster.monitor_owner(state.db(), monitor_id).await? else { + return Ok(next.run(request).await); + }; + + // The caller must be able to see the monitor before anything leaves this + // server. The owning server checks again, with the level the route needs. + let sight = sight(&request, monitor_id); + if !caller_sees(&state, sight, monitor_id).await? { + return Err(AppError::NotFoundError(Resource { + details: vec![("monitor_id".to_string(), monitor_id.to_string())], + resource_type: ResourceType::Monitor, + })); + } + + let peer = state.cluster.peer(state.db(), server_id).await?; + if let Some(by) = request.headers().get(&FORWARDED_BY) { + return Err(AppError::MisdirectedError(format!( + "monitor {monitor_id} belongs to server {server_id}, and server {} already relayed \ + this request here; the servers disagree about which one this is", + by.to_str().unwrap_or("?") + ))); + } + let Some(peer) = peer else { + return Err(AppError::MisdirectedError(format!( + "monitor {monitor_id} belongs to server {server_id}, which has no address: give its \ + Servers row a hostname, or set cluster.peers.{server_id}" + ))); + }; + if request.headers().contains_key(header::UPGRADE) { + return Err(AppError::MisdirectedError(format!( + "monitor {monitor_id} belongs to {}; a WebSocket is not relayed, so connect to {} \ + or use WHEP", + peer.label(), + peer.base_url + ))); + } + debug!("relaying monitor {monitor_id} request to {}", peer.label()); + relay(&state, &peer, &path_and_query, request).await +} + +/// The path and query the client sent. A nested router strips its prefix +/// from the request's own URI, so the original is read from the extension +/// axum keeps. +fn original_path_and_query(request: &Request) -> String { + let uri = request + .extensions() + .get::() + .map_or_else(|| request.uri(), |original| &original.0); + uri.path_and_query() + .map_or_else(|| uri.path().to_string(), |pq| pq.as_str().to_string()) +} + +/// What the guards left on the request about the caller's view of a monitor. +enum Sight { + Known(bool), + /// Only the claims: the scope still has to be resolved. + Resolve(u32, Level), +} + +/// Read synchronously, because a borrowed request can't be held across the +/// database call that resolving a scope needs. +fn sight(request: &Request, monitor_id: u32) -> Sight { + let ext = request.extensions(); + if let Some(scope) = ext.get::() { + Sight::Known(scope.allows(monitor_id, Level::View)) + } else if let Some(grant) = ext.get::() { + Sight::Known(grant.scope().allows(monitor_id, Level::View)) + } else if let Some(claims) = ext.get::() { + Sight::Resolve(claims.uid, claims.perms.monitors) + } else { + // Nothing authenticated this request here. The owning server will. + Sight::Known(true) + } +} + +/// Whether the caller may view the monitor. +async fn caller_sees(state: &AppState, sight: Sight, monitor_id: u32) -> AppResult { + match sight { + Sight::Known(sees) => Ok(sees), + Sight::Resolve(uid, level) => { + let scope = monitor_acl::resolve(state.db(), uid, level).await?; + Ok(scope.allows(monitor_id, Level::View)) + } + } +} + +/// The headers the owning server gets: the caller's own, minus the ones +/// that belong to this connection, plus who relayed it and for whom. +fn relayed_headers( + from_caller: &HeaderMap, + client: Option, + this_server: Option, +) -> HeaderMap { + let mut headers = end_to_end(from_caller); + if let Some(id) = this_server { + headers.insert(FORWARDED_BY, HeaderValue::from(id)); + } + // The owner's rate limiter can key on the real client, if it trusts this + // server as a proxy. Appended, as a proxy does, to what the client sent. + if let Some(client) = client.and_then(|ip| HeaderValue::from_str(&ip.to_string()).ok()) { + headers.append(X_FORWARDED_FOR, client); + } + headers +} + +fn end_to_end(headers: &HeaderMap) -> HeaderMap { + headers + .iter() + .filter(|(name, _)| !HOP_BY_HOP.contains(name)) + .map(|(name, value)| (name.clone(), value.clone())) + .collect() +} + +/// Send `request` to `peer` and stream its answer back. +async fn relay( + state: &AppState, + peer: &Peer, + path_and_query: &str, + request: Request, +) -> Result { + let (parts, body) = request.into_parts(); + let body = axum::body::to_bytes(body, MAX_RELAYED_BODY) + .await + .map_err(|_| AppError::BadRequestError("the request body is too large".to_string()))?; + + let client = parts + .extensions + .get::>() + .map(|info| info.0.ip()); + let headers = relayed_headers(&parts.headers, client, state.cluster.this_server()); + let url = format!("{}{}", peer.base_url, path_and_query); + let sent = state + .cluster + .client() + .request(parts.method, url) + .headers(headers) + .body(body) + .send() + .await; + let answer = match sent { + Ok(answer) => answer, + Err(e) => { + // The URL can carry a token in its query, so it stays out. + warn!("{} did not answer: {}", peer.label(), e.without_url()); + return Err(AppError::BadGatewayError(format!( + "{} did not answer", + peer.label() + ))); + } + }; + + // This server accepted the caller's credentials a moment ago. The only + // way the owner can refuse them is with different signing keys. + if answer.status() == reqwest::StatusCode::UNAUTHORIZED { + warn!( + "{} refused credentials this server accepted: every server must use the same JWT \ + key files", + peer.label() + ); + return Err(AppError::BadGatewayError(format!( + "{} refused credentials this server accepted; the servers' JWT keys differ", + peer.label() + ))); + } + + let mut response = Response::builder().status(answer.status().as_u16()); + if let Some(out) = response.headers_mut() { + for (name, value) in answer.headers() { + // Content-Length is kept: the body is passed on untouched. + if !HOP_BY_HOP.contains(name) || name == header::CONTENT_LENGTH { + out.append(name.clone(), value.clone()); + } + } + } + response + .body(Body::from_stream(answer.bytes_stream())) + .map_err(|e| AppError::InternalServerError(e.to_string())) +} + +/// After a monitor row was saved here: if another server owns it now, ask +/// that server to restart its daemons. +/// +/// Edits and deletes reach the owner through [`forward_to_owner`], so its own +/// daemon control runs in the right place. Two cases end up on a server that +/// doesn't own the saved row: a monitor created for another server, and a +/// monitor just moved to one. Failures are logged, not returned, as for any +/// daemon control after a row change: the row is saved either way. +pub async fn restart_on_owner( + state: &AppState, + caller: &HeaderMap, + monitor_id: u32, + monitor_server: Option, +) { + state.cluster.forget_monitor(monitor_id); + if !state.cluster.relays() { + return; + } + let Owner::Peer(server_id) = super::owner(state.cluster.this_server(), monitor_server) else { + return; + }; + let peer = match state.cluster.peer(state.db(), server_id).await { + Ok(Some(peer)) => peer, + Ok(None) => { + warn!( + "monitor {monitor_id}: server {server_id} runs its daemons but has no address; they start when that server next reconciles" + ); + return; + } + Err(e) => { + warn!("monitor {monitor_id}: looking up server {server_id} failed: {e}"); + return; + } + }; + let mut request = state + .cluster + .client() + .patch(format!( + "{}/api/v3/monitors/{monitor_id}/state", + peer.base_url + )) + .json(&serde_json::json!({ "state": "restart" })); + if let Some(auth) = caller.get(header::AUTHORIZATION) { + request = request.header(header::AUTHORIZATION, auth); + } + if let Some(id) = state.cluster.this_server() { + request = request.header(FORWARDED_BY, HeaderValue::from(id)); + } + match request.send().await { + Ok(answer) if answer.status().is_success() => { + debug!( + "monitor {monitor_id}: {} restarted its daemons", + peer.label() + ) + } + Ok(answer) => warn!( + "monitor {monitor_id}: {} answered {} to a daemon restart", + peer.label(), + answer.status() + ), + Err(e) => warn!( + "monitor {monitor_id}: {} did not answer a daemon restart: {}", + peer.label(), + e.without_url() + ), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reading_a_monitors_row_stays_local() { + assert!(stays_local(&Method::GET, "/api/v3/monitors/7")); + assert!(stays_local(&Method::HEAD, "/api/v3/monitors/7/")); + // Changing it does not: the owner must restart its daemons. + assert!(!stays_local(&Method::PATCH, "/api/v3/monitors/7")); + assert!(!stays_local(&Method::DELETE, "/api/v3/monitors/7")); + } + + #[test] + fn node_local_reads_are_relayed() { + for path in [ + "/api/v3/monitors/7/snapshot", + "/api/v3/monitors/7/audio-level", + "/api/v3/monitors/7/pipeline", + "/api/v3/live/7/hls/live.m3u8", + "/api/v3/live/7/stats", + ] { + assert!(!stays_local(&Method::GET, path), "{path}"); + } + } + + #[test] + fn a_signed_playlist_link_is_minted_here() { + assert!(stays_local(&Method::POST, "/api/v3/live/7/hls/link")); + // The RTSP link names the owner's RTSP server, so it is relayed. + assert!(!stays_local(&Method::POST, "/api/v3/live/7/rtsp/link")); + } + + #[test] + fn the_owner_learns_who_relayed_and_for_which_client() { + let mut from_caller = HeaderMap::new(); + from_caller.insert(X_FORWARDED_FOR, HeaderValue::from_static("203.0.113.9")); + // A caller can't pose as a relaying server: the value is replaced. + from_caller.insert(FORWARDED_BY, HeaderValue::from_static("7")); + let out = relayed_headers(&from_caller, Some("192.0.2.4".parse().unwrap()), Some(1)); + assert_eq!(out.get(FORWARDED_BY).unwrap(), "1"); + let chain: Vec<_> = out.get_all(X_FORWARDED_FOR).iter().collect(); + assert_eq!(chain, ["203.0.113.9", "192.0.2.4"]); + // With no connection address (a test client), nothing is invented. + let bare = relayed_headers(&HeaderMap::new(), None, Some(1)); + assert!(!bare.contains_key(X_FORWARDED_FOR)); + } + + #[test] + fn connection_headers_stay_behind_and_credentials_go_through() { + let mut headers = HeaderMap::new(); + headers.insert(header::AUTHORIZATION, HeaderValue::from_static("Bearer t")); + headers.insert(header::HOST, HeaderValue::from_static("zm1")); + headers.insert(header::CONNECTION, HeaderValue::from_static("keep-alive")); + headers.insert(header::CONTENT_LENGTH, HeaderValue::from_static("2")); + headers.insert( + header::CONTENT_TYPE, + HeaderValue::from_static("application/json"), + ); + let out = end_to_end(&headers); + assert_eq!(out.get(header::AUTHORIZATION).unwrap(), "Bearer t"); + assert_eq!(out.get(header::CONTENT_TYPE).unwrap(), "application/json"); + assert!(!out.contains_key(header::HOST)); + assert!(!out.contains_key(header::CONNECTION)); + assert!(!out.contains_key(header::CONTENT_LENGTH)); + } +} diff --git a/src/cluster/mod.rs b/src/cluster/mod.rs new file mode 100644 index 00000000..d34248a4 --- /dev/null +++ b/src/cluster/mod.rs @@ -0,0 +1,360 @@ +//! Multi-server installs: which server owns a monitor, and how to reach the +//! zm-api there. +//! +//! A ZoneMinder install can spread its monitors over several servers that +//! share one database. Shared memory, zmc's stream socket and the daemon +//! control socket exist only on the server that runs a monitor, so a zm-api +//! can serve live video, snapshots, alarms and daemon control for its own +//! monitors alone (#230). Every server runs a zm-api, and a request that +//! reaches the wrong one is relayed to the right one ([`forward`]). +//! +//! The servers talk over the v3 API itself, with the caller's own +//! credentials: the owning server authenticates the user and applies their +//! permissions exactly as it would for a direct request. No server holds a +//! credential that can act as anyone. That requires every server to share +//! the same JWT key files. + +pub mod forward; + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use sea_orm::DatabaseConnection; + +use crate::configure::cluster::ClusterConfig; +use crate::error::AppResult; + +/// How long a monitor's owner and the `Servers` rows are remembered. Short: +/// a monitor moved to another server is followed within seconds. +const CACHE_TTL: Duration = Duration::from_secs(5); + +/// Where a monitor's node-local resources live. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Owner { + /// This server, or no server in particular: handle it here. + Here, + /// The server with this `Servers.Id`. + Peer(u32), +} + +/// Which server answers for a monitor. +/// +/// A host with no server id is a single-server install, and everything is +/// local. Otherwise a monitor belongs to the server its `ServerId` names. A +/// monitor with no `ServerId` belongs to nobody in particular, so it is +/// handled wherever the request landed. +pub fn owner(this_server: Option, monitor_server: Option) -> Owner { + match (this_server, monitor_server) { + (None, _) | (_, None) | (_, Some(0)) => Owner::Here, + (Some(here), Some(there)) if here == there => Owner::Here, + (Some(_), Some(there)) => Owner::Peer(there), + } +} + +/// Another server's zm-api. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Peer { + pub id: u32, + pub name: String, + /// `https://host:port`, no trailing slash. + pub base_url: String, +} + +impl Peer { + /// `server 2 (zm2)`, for messages. + pub fn label(&self) -> String { + format!("server {} ({})", self.id, self.name) + } +} + +#[derive(Debug, Clone)] +struct ServerRow { + name: String, + hostname: Option, +} + +type Cached = Mutex>; + +pub struct Cluster { + this_server: Option, + enabled: bool, + /// The scheme and port zm-api is assumed to use on the other servers: + /// this server's own, unless `cluster.peer_port` says otherwise. + scheme: &'static str, + port: u16, + overrides: HashMap, + client: reqwest::Client, + servers: Cached>>, + owners: Mutex)>>, +} + +impl std::fmt::Debug for Cluster { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Cluster") + .field("this_server", &self.this_server) + .field("enabled", &self.enabled) + .finish_non_exhaustive() + } +} + +impl Cluster { + /// `tls` is whether this server's own listener speaks TLS. + pub fn new(this_server: Option, config: &ClusterConfig, own_port: u16, tls: bool) -> Self { + Self { + this_server, + enabled: config.enabled, + scheme: if tls { "https" } else { "http" }, + port: config.peer_port.unwrap_or(own_port), + overrides: config.peer_overrides(), + client: build_client(config), + servers: Mutex::new(None), + owners: Mutex::new(HashMap::new()), + } + } + + /// A single-server install: nothing is ever relayed. + pub fn single() -> Self { + Self::new(None, &ClusterConfig::default(), 0, false) + } + + pub fn this_server(&self) -> Option { + self.this_server + } + + /// Whether any request could be relayed at all. False on a single-server + /// install, where the relay layer does no work. + pub fn relays(&self) -> bool { + self.enabled && self.this_server.is_some() + } + + pub(crate) fn client(&self) -> &reqwest::Client { + &self.client + } + + /// The server that owns a monitor. `Here` for a monitor that doesn't + /// exist, so the local handler answers 404 as it always did. + pub async fn monitor_owner( + &self, + db: &DatabaseConnection, + monitor_id: u32, + ) -> AppResult { + if !self.relays() { + return Ok(Owner::Here); + } + let cached = self + .owners + .lock() + .unwrap() + .get(&monitor_id) + .filter(|(at, _)| at.elapsed() < CACHE_TTL) + .map(|(_, server)| *server); + let monitor_server = match cached { + Some(server) => server, + None => { + let server = crate::repo::monitors::find_by_id(db, monitor_id) + .await? + .and_then(|m| m.server_id); + let mut owners = self.owners.lock().unwrap(); + owners.retain(|_, (at, _)| at.elapsed() < CACHE_TTL); + owners.insert(monitor_id, (Instant::now(), server)); + server + } + }; + Ok(owner(self.this_server, monitor_server)) + } + + /// Drop what is remembered about a monitor, after its row changed here. + pub fn forget_monitor(&self, monitor_id: u32) { + self.owners.lock().unwrap().remove(&monitor_id); + } + + /// Where another server's zm-api is. `None` when there is no `Servers` + /// row for it, or the row has no hostname and settings name none. + pub async fn peer(&self, db: &DatabaseConnection, server_id: u32) -> AppResult> { + let servers = self.servers(db).await?; + let row = servers.get(&server_id); + let name = row.map_or_else(|| server_id.to_string(), |r| r.name.clone()); + let hostname = row.and_then(|r| r.hostname.as_deref()); + Ok(self.base_url(server_id, hostname).map(|base_url| Peer { + id: server_id, + name, + base_url, + })) + } + + /// The v3 address of a server: the settings override, else this server's + /// scheme and the peer port on the row's hostname. + pub fn base_url(&self, server_id: u32, hostname: Option<&str>) -> Option { + if let Some(url) = self.overrides.get(&server_id) { + return Some(url.clone()); + } + let host = hostname.map(str::trim).filter(|h| !h.is_empty())?; + Some(format!("{}://{}:{}", self.scheme, host, self.port)) + } + + async fn servers(&self, db: &DatabaseConnection) -> AppResult>> { + if let Some((at, rows)) = self.servers.lock().unwrap().as_ref() { + if at.elapsed() < CACHE_TTL { + return Ok(rows.clone()); + } + } + let rows: HashMap = crate::repo::servers::find_all(db) + .await? + .into_iter() + .map(|s| { + ( + s.id, + ServerRow { + name: s.name, + hostname: s.hostname, + }, + ) + }) + .collect(); + let rows = Arc::new(rows); + *self.servers.lock().unwrap() = Some((Instant::now(), rows.clone())); + Ok(rows) + } +} + +/// How often a server of a multi-server install re-reads the token floors. +const REVOCATION_SYNC: Duration = Duration::from_secs(10); + +/// Keep this server's token-revocation floors in step with the database. +/// +/// A logout or password change raises `Users.TokenMinExpiry` and the floor +/// in the memory of the server that handled it. Access tokens are checked +/// against memory only, so without this another server would go on accepting +/// the revoked token until it expired. Floors only rise, so re-reading is +/// safe to repeat. +pub fn sync_revocations( + db: Arc, + revocations: Arc, +) { + tokio::spawn(async move { + let mut tick = tokio::time::interval(REVOCATION_SYNC); + tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + loop { + tick.tick().await; + match crate::repo::users::token_floors(db.as_ref()).await { + Ok(floors) => { + for (uid, floor) in floors { + revocations.revoke(uid, floor); + } + } + Err(e) => tracing::debug!("re-reading token floors failed: {e}"), + } + } + }); +} + +/// The client for requests to the other servers. No overall timeout, because +/// a relayed live stream runs as long as its viewer watches. A server that +/// goes quiet is dropped by the read timeout. +fn build_client(config: &ClusterConfig) -> reqwest::Client { + let mut builder = reqwest::Client::builder() + .no_proxy() + // A relayed response is passed on as it is, redirects included. + .redirect(reqwest::redirect::Policy::none()) + .connect_timeout(Duration::from_secs(config.connect_timeout_secs.max(1))) + .read_timeout(Duration::from_secs(config.read_timeout_secs.max(1))); + if let Some(path) = &config.tls_ca_file { + match std::fs::read(path).map(|pem| reqwest::Certificate::from_pem_bundle(&pem)) { + Ok(Ok(certs)) => { + for cert in certs { + builder = builder.add_root_certificate(cert); + } + } + Ok(Err(e)) => tracing::warn!("cluster.tls_ca_file {}: {e}", path.display()), + Err(e) => tracing::warn!("cluster.tls_ca_file {}: {e}", path.display()), + } + } + builder.build().unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn cluster(this: Option, config: &ClusterConfig) -> Cluster { + Cluster::new(this, config, 8443, true) + } + + #[test] + fn a_monitor_belongs_to_the_server_its_row_names() { + assert_eq!(owner(Some(1), Some(1)), Owner::Here); + assert_eq!(owner(Some(1), Some(2)), Owner::Peer(2)); + } + + #[test] + fn a_single_server_install_owns_everything() { + assert_eq!(owner(None, None), Owner::Here); + assert_eq!(owner(None, Some(2)), Owner::Here); + } + + /// Nobody in particular owns it, so there is nowhere to relay it to. + #[test] + fn a_monitor_with_no_server_is_handled_where_the_request_landed() { + assert_eq!(owner(Some(1), None), Owner::Here); + assert_eq!(owner(Some(1), Some(0)), Owner::Here); + } + + #[test] + fn a_peer_is_at_this_servers_scheme_and_port_on_its_hostname() { + let c = cluster(Some(1), &ClusterConfig::default()); + assert_eq!( + c.base_url(2, Some("zm2.lan")).as_deref(), + Some("https://zm2.lan:8443") + ); + let plain = Cluster::new(Some(1), &ClusterConfig::default(), 8080, false); + assert_eq!( + plain.base_url(2, Some(" zm2 ")).as_deref(), + Some("http://zm2:8080") + ); + } + + #[test] + fn settings_override_the_address_and_the_port() { + let mut config = ClusterConfig { + peer_port: Some(9000), + ..Default::default() + }; + config + .peers + .insert("3".into(), "https://nvr3.example:444/".into()); + let c = cluster(Some(1), &config); + assert_eq!( + c.base_url(2, Some("zm2")).as_deref(), + Some("https://zm2:9000") + ); + assert_eq!( + c.base_url(3, Some("ignored")).as_deref(), + Some("https://nvr3.example:444") + ); + // An override works for a server whose row has no hostname. + assert_eq!( + c.base_url(3, None).as_deref(), + Some("https://nvr3.example:444") + ); + } + + #[test] + fn a_server_with_no_hostname_and_no_override_has_no_address() { + let c = cluster(Some(1), &ClusterConfig::default()); + assert_eq!(c.base_url(2, None), None); + assert_eq!(c.base_url(2, Some(" ")), None); + } + + #[test] + fn relaying_needs_a_server_id_and_the_setting() { + assert!(cluster(Some(1), &ClusterConfig::default()).relays()); + assert!(!cluster(None, &ClusterConfig::default()).relays()); + let off = ClusterConfig { + enabled: false, + ..Default::default() + }; + assert!(!cluster(Some(1), &off).relays()); + assert!(!Cluster::single().relays()); + } +} diff --git a/src/configure/cluster.rs b/src/configure/cluster.rs new file mode 100644 index 00000000..503a3e54 --- /dev/null +++ b/src/configure/cluster.rs @@ -0,0 +1,101 @@ +//! Multi-server installs: how this zm-api reaches the zm-api on each other +//! ZoneMinder server. +//! +//! Shared memory, zmc's stream socket and the daemon control socket exist +//! only on the server that runs a monitor. A request for another server's +//! monitor is relayed to the zm-api there (see `crate::cluster`). Nothing +//! here matters on a single-server install: with no server id, every monitor +//! is local. + +use std::collections::HashMap; +use std::path::PathBuf; + +use serde::Deserialize; + +#[derive(Debug, Deserialize, Clone)] +pub struct ClusterConfig { + /// Relay requests for another server's monitors to that server. Off + /// leaves them to fail locally, as they did before. + #[serde(default = "default_true")] + pub enabled: bool, + + /// The port zm-api listens on at the other servers. Defaults to this + /// server's own port. + #[serde(default)] + pub peer_port: Option, + + /// How long to wait for a connection to another server. + #[serde(default = "default_connect_timeout_secs")] + pub connect_timeout_secs: u64, + + /// How long another server may go without sending anything. + #[serde(default = "default_read_timeout_secs")] + pub read_timeout_secs: u64, + + /// A PEM file of extra root certificates to trust for the other servers, + /// for a private CA on the LAN. + #[serde(default)] + pub tls_ca_file: Option, + + /// A base URL per `Servers.Id`, for a server whose zm-api isn't at + /// `://:`. + #[serde(default)] + pub peers: HashMap, +} + +impl Default for ClusterConfig { + fn default() -> Self { + Self { + enabled: true, + peer_port: None, + connect_timeout_secs: default_connect_timeout_secs(), + read_timeout_secs: default_read_timeout_secs(), + tls_ca_file: None, + peers: HashMap::new(), + } + } +} + +impl ClusterConfig { + /// The configured base URLs by server id. An entry whose key isn't a + /// number is dropped with a warning. + pub fn peer_overrides(&self) -> HashMap { + self.peers + .iter() + .filter_map(|(id, url)| match id.parse::() { + Ok(id) => Some((id, url.trim_end_matches('/').to_string())), + Err(_) => { + tracing::warn!("cluster.peers: {id:?} is not a Servers.Id; ignored"); + None + } + }) + .collect() + } +} + +fn default_true() -> bool { + true +} + +fn default_connect_timeout_secs() -> u64 { + 5 +} + +fn default_read_timeout_secs() -> u64 { + 30 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn overrides_are_keyed_by_server_id_and_lose_a_trailing_slash() { + let mut c = ClusterConfig::default(); + c.peers.insert("2".into(), "https://zm2.lan:8443/".into()); + c.peers.insert("two".into(), "https://nope".into()); + let o = c.peer_overrides(); + assert_eq!(o.len(), 1); + assert_eq!(o[&2], "https://zm2.lan:8443"); + } +} diff --git a/src/configure/mod.rs b/src/configure/mod.rs index 8670b104..3da3bd4d 100644 --- a/src/configure/mod.rs +++ b/src/configure/mod.rs @@ -13,6 +13,7 @@ use self::{ synopsis::SynopsisConfig, web::WebConfig, zmnext::ZmNextConfig, }; +pub mod cluster; pub mod daemon; pub mod db; pub mod env; @@ -63,6 +64,9 @@ pub struct AppConfig { /// zmtelemetry). Each independently switchable; all off by default. #[serde(default)] pub maintenance: MaintenanceConfig, + /// Multi-server installs: reaching the zm-api on the other servers. + #[serde(default)] + pub cluster: cluster::ClusterConfig, } impl AppConfig { diff --git a/src/configure/server.rs b/src/configure/server.rs index 6a77930e..d7a751a9 100644 --- a/src/configure/server.rs +++ b/src/configure/server.rs @@ -221,6 +221,16 @@ impl MiddlewareConfig { } } +impl ServerConfig { + /// Whether the listener speaks TLS, from a certificate file or ACME. A + /// `[server.tls]` or `[server.acme]` section that is present but not + /// enabled, as the packaged settings have, does not count. + pub fn serves_tls(&self) -> bool { + self.tls.as_ref().is_some_and(|tls| tls.enabled) + || self.acme.as_ref().is_some_and(|acme| acme.enabled) + } +} + #[derive(Debug, Deserialize, Clone)] pub struct ServerTlsConfig { #[serde(default)] @@ -323,6 +333,31 @@ pub mod tests { assert_eq!(config.get_http_addr(), "http://127.0.0.1:1024"); } + /// The packaged settings carry a `[server.tls]` section with + /// `enabled = false`. A listener on plain HTTP must not be taken for TLS: + /// a multi-server peer would be given an `https://` address it can't answer. + #[test] + fn a_tls_section_that_is_switched_off_is_not_tls() { + let mut config = ServerConfig { + addr: "127.0.0.1".to_string(), + port: 8080, + tls: None, + acme: None, + allowed_origins: Vec::new(), + middleware: MiddlewareConfig::default(), + public_prefix: String::new(), + }; + assert!(!config.serves_tls()); + config.tls = Some(ServerTlsConfig { + enabled: false, + cert_path: Some("/etc/ssl/cert.pem".into()), + key_path: Some("/etc/ssl/key.pem".into()), + }); + assert!(!config.serves_tls()); + config.tls.as_mut().unwrap().enabled = true; + assert!(config.serves_tls()); + } + #[test] fn public_prefix_is_normalized() { assert_eq!(normalize_prefix("").unwrap(), ""); diff --git a/src/dto/response/servers.rs b/src/dto/response/servers.rs index 17031381..13e217b7 100644 --- a/src/dto/response/servers.rs +++ b/src/dto/response/servers.rs @@ -25,6 +25,15 @@ pub struct ServerResponse { /// Monitors assigned to this server (`Monitors.ServerId`). #[serde(default)] pub monitor_count: u64, + /// Where this server's zm-api is, as the server answering works it out: + /// its `cluster.peers` setting, else its own scheme and port on this + /// row's hostname. Absent when the row has no hostname. A client does not + /// need it: any server relays requests for another server's monitors. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub api_url: Option, + /// Whether this is the server that answered. + #[serde(default)] + pub is_this_server: bool, } impl From<&crate::entity::servers::Model> for ServerResponse { @@ -48,6 +57,8 @@ impl From<&crate::entity::servers::Model> for ServerResponse { latitude: m.latitude.and_then(|d| d.to_f64()), longitude: m.longitude.and_then(|d| d.to_f64()), monitor_count: 0, + api_url: None, + is_this_server: false, } } } diff --git a/src/error/mod.rs b/src/error/mod.rs index f2af5e69..670d8c3c 100644 --- a/src/error/mod.rs +++ b/src/error/mod.rs @@ -46,6 +46,14 @@ pub enum AppError { InternalServerError(String), #[error("service unavailable: {0}")] ServiceUnavailableError(String), + /// Another server of a multi-server install did not answer a relayed + /// request, or answered it in a way that only a setup fault explains. + #[error("bad gateway: {0}")] + BadGatewayError(String), + /// The request is for another server's monitor and this server can't + /// relay it. The message names the server that can answer. + #[error("misdirected request: {0}")] + MisdirectedError(String), /// A 503 for something that will be back shortly, with a Retry-After of /// this many seconds. #[error("service unavailable: {0}")] @@ -239,6 +247,18 @@ impl AppError { vec![], StatusCode::SERVICE_UNAVAILABLE, ), + BadGatewayError(_err) => ( + "BAD_GATEWAY_ERROR".to_string(), + None, + vec![], + StatusCode::BAD_GATEWAY, + ), + MisdirectedError(_err) => ( + "MISDIRECTED_REQUEST_ERROR".to_string(), + None, + vec![], + StatusCode::MISDIRECTED_REQUEST, + ), RetryLaterError(_err, secs) => ( "SERVICE_UNAVAILABLE_ERROR".to_string(), None, diff --git a/src/handlers/monitor.rs b/src/handlers/monitor.rs index e67ef5cc..cfd8f0c8 100644 --- a/src/handlers/monitor.rs +++ b/src/handlers/monitor.rs @@ -3,6 +3,7 @@ use axum::Json; use garde::Validate; use tracing::{info, warn}; +use crate::cluster::forward::restart_on_owner; use crate::dto::request::monitor::MonitorListParams; use crate::dto::request::{ AlarmControlRequest, CreateMonitorRequest, MonitorStateRequest, UpdateMonitorRequest, @@ -113,6 +114,7 @@ pub async fn create_monitor( State(state): State, claims: UserClaims, scope: MonitorScope, + headers: axum::http::HeaderMap, Json(req): Json, ) -> AppResult> { // `Monitors: Create` is checked by the route's `require_monitor_create`. @@ -139,7 +141,11 @@ pub async fn create_monitor( // Log the name only: the request body carries camera RTSP/ONVIF credentials. info!("Creating new monitor: {}.", req.name); match service::monitor::create(&state, req).await { - Ok(monitor) => Ok(Json(monitor)), + Ok(monitor) => { + // Multi-server: the server that runs it starts its daemons. + restart_on_owner(&state, &headers, monitor.id, monitor.server_id).await; + Ok(Json(monitor)) + } Err(e) => { warn!("Failed to create monitor: {e:?}."); Err(e) @@ -171,13 +177,18 @@ pub async fn update_monitor( Path(id): Path, claims: UserClaims, scope: MonitorScope, + headers: axum::http::HeaderMap, Json(req): Json, ) -> AppResult> { req.validate().map_err(AppError::InvalidInputError)?; // Log the id only: the request body carries camera RTSP/ONVIF credentials. info!("Editing monitor with ID: {id}."); match service::monitor::update(&state, id, req, &scope, &claims.perms).await { - Ok(monitor) => Ok(Json(monitor)), + Ok(monitor) => { + // Multi-server: a monitor moved to another server starts there. + restart_on_owner(&state, &headers, monitor.id, monitor.server_id).await; + Ok(Json(monitor)) + } Err(e) => { warn!("Failed to edit monitor: {e:?}."); Err(e) diff --git a/src/lib.rs b/src/lib.rs index cacc4db6..dd36ad48 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -21,6 +21,7 @@ pub fn install_crypto_provider() { } pub mod client; +pub mod cluster; pub mod configure; pub mod constant; pub mod daemon; diff --git a/src/repo/users.rs b/src/repo/users.rs index 890287e8..ec771bab 100644 --- a/src/repo/users.rs +++ b/src/repo/users.rs @@ -7,6 +7,24 @@ pub async fn find_all(db: &DatabaseConnection) -> AppResult> { Ok(Users::find().all(db).await?) } +/// Every user's token-revocation floor (`TokenMinExpiry`), for the users who +/// have one. +pub async fn token_floors(db: &DatabaseConnection) -> AppResult> { + use crate::entity::users::Column; + let rows: Vec<(u32, u64)> = Users::find() + .select_only() + .column(Column::Id) + .column(Column::TokenMinExpiry) + .filter(Column::TokenMinExpiry.gt(0)) + .into_tuple() + .all(db) + .await?; + Ok(rows + .into_iter() + .map(|(id, floor)| (id, floor as i64)) + .collect()) +} + pub async fn find_paginated( db: &DatabaseConnection, params: &PaginationParams, diff --git a/src/routes/mod.rs b/src/routes/mod.rs index 67912180..995ccb41 100644 --- a/src/routes/mod.rs +++ b/src/routes/mod.rs @@ -508,7 +508,16 @@ pub fn create_router_app(state: AppState) -> Router { crate::service::monitor_acl::monitor_row_gate, )) }; - let monitors_routes = monitor_gate(monitors::add_monitor_routes(Router::new())); + // Multi-server (#230): a request for a monitor another server runs is + // relayed there. Added before each guard so it runs after it: this server + // authenticates the caller and checks the monitor first. + let to_owner = |router: Router| { + router.route_layer(axum::middleware::from_fn_with_state( + state.clone(), + crate::cluster::forward::forward_to_owner, + )) + }; + let monitors_routes = monitor_gate(to_owner(monitors::add_monitor_routes(Router::new()))); let monitor_preset_routes = protect( monitor_presets::add_monitor_preset_routes(Router::new()), Feature::Monitors, @@ -575,10 +584,12 @@ pub fn create_router_app(state: AppState) -> Router { // feature-level RBAC check runs first and the guard's DB query is only // reached after the caller has at least `Control:View`. let ptz_routes = protect( - ptz::add_ptz_routes(Router::new()).route_layer(axum::middleware::from_fn_with_state( - state.clone(), - crate::service::monitor_acl::monitor_path_guard, - )), + to_owner(ptz::add_ptz_routes(Router::new())).route_layer( + axum::middleware::from_fn_with_state( + state.clone(), + crate::service::monitor_acl::monitor_path_guard, + ), + ), Feature::Control, ); let trigger_x10_routes = protect( @@ -621,10 +632,12 @@ pub fn create_router_app(state: AppState) -> Router { // feature-level RBAC check runs first and the guard's DB query is only // reached after the caller has at least `Stream:View`. let live_routes = protect( - live::add_live_routes(Router::new()).route_layer(axum::middleware::from_fn_with_state( - state.clone(), - crate::service::monitor_acl::monitor_stream_guard, - )), + to_owner(live::add_live_routes(Router::new())).route_layer( + axum::middleware::from_fn_with_state( + state.clone(), + crate::service::monitor_acl::monitor_stream_guard, + ), + ), Feature::Stream, ); @@ -676,7 +689,7 @@ pub fn create_router_app(state: AppState) -> Router { let monitor_action_routes = monitor_gate(monitor_actions::add_monitor_action_routes(Router::new())); let monitor_action_run_route = authz::protect_at( - monitor_actions::add_monitor_action_run_route(Router::new()), + to_owner(monitor_actions::add_monitor_action_run_route(Router::new())), Feature::Control, authz::Level::View, state.clone(), diff --git a/src/server/state.rs b/src/server/state.rs index f3a249ba..248b9598 100644 --- a/src/server/state.rs +++ b/src/server/state.rs @@ -61,6 +61,9 @@ pub struct AppState { /// up in `Servers`): which monitors this host's zmdc.pl runs. `None` /// when ZoneMinder has none, and then every monitor is local. pub server_id: Option, + /// Multi-server installs: which server owns a monitor, and the client + /// for relaying its requests there. + pub cluster: Arc, } /// How long a request to another service (the search models, telemetry) may @@ -325,6 +328,16 @@ impl AppState { Err(e) => tracing::warn!("failed to hydrate token revocations from Users: {e}"), } + let cluster = Arc::new(crate::cluster::Cluster::new( + this_server.zoneminder_id, + &config.cluster, + config.server.port, + config.server.serves_tls(), + )); + // Another server may have handled a logout: follow the floors it wrote. + if cluster.relays() { + crate::cluster::sync_revocations(db.clone(), revocations.clone()); + } Ok(Self { config: Arc::new(config), db, @@ -340,6 +353,7 @@ impl AppState { revocations, schema_behind, server_id: this_server.zoneminder_id, + cluster, media_job_wake: Arc::new(tokio::sync::Notify::new()), event_hub: Default::default(), whep: Default::default(), @@ -387,6 +401,7 @@ impl AppState { revocations: std::sync::Arc::new(crate::util::revocation::TokenRevocations::default()), schema_behind: None, server_id: None, + cluster: std::sync::Arc::new(crate::cluster::Cluster::single()), media_job_wake: std::sync::Arc::new(tokio::sync::Notify::new()), event_hub: Default::default(), whep: Default::default(), diff --git a/src/service/monitor_acl.rs b/src/service/monitor_acl.rs index 733e6f3f..ecfc746e 100644 --- a/src/service/monitor_acl.rs +++ b/src/service/monitor_acl.rs @@ -465,7 +465,7 @@ pub async fn zone_row_gate( gate_monitor(&state, mid, request, next).await } -fn path_monitor_id(params: &RawPathParams) -> Option { +pub(crate) fn path_monitor_id(params: &RawPathParams) -> Option { params .iter() .find(|(key, _)| *key == "monitor_id" || *key == "id") diff --git a/src/service/monitor_daemons.rs b/src/service/monitor_daemons.rs index 7e0b7601..5a7fc773 100644 --- a/src/service/monitor_daemons.rs +++ b/src/service/monitor_daemons.rs @@ -97,9 +97,28 @@ fn log_manager( } } +/// Whether another server's daemon manager runs this monitor. zm-api's own +/// manager, unlike zmdc.pl, starts whatever it is asked to, so the takeover +/// paths below check first: starting another server's monitor here would +/// capture the camera twice (#230). +fn runs_elsewhere(state: &AppState, m: &MonitorModel) -> bool { + let elsewhere = matches!( + crate::cluster::owner(state.server_id, m.server_id), + crate::cluster::Owner::Peer(_) + ); + if elsewhere { + info!( + "monitor {}: Servers.Id {:?} runs its daemons, not this server", + m.id, m.server_id + ); + } + elsewhere +} + /// A monitor was created. pub async fn created(state: &AppState, m: &MonitorModel) { match &state.daemon_manager { + Some(_) if runs_elsewhere(state, m) => {} Some(dm) => log_manager(m.id, "start", dm.start_monitor(m.id).await), None => passive_start(state, m).await, } @@ -108,6 +127,10 @@ pub async fn created(state: &AppState, m: &MonitorModel) { /// A monitor was saved: stop its daemons as they were, start them as saved. pub async fn updated(state: &AppState, old: &MonitorModel, new: &MonitorModel) { match &state.daemon_manager { + // Moved to another server: stop it here, and that server starts it. + Some(dm) if runs_elsewhere(state, new) => { + log_manager(new.id, "stop", dm.stop_monitor(new.id).await) + } Some(dm) => log_manager(new.id, "restart", dm.restart_monitor(new.id).await), None => { if old.r#type != MonitorType::WebSite { @@ -128,6 +151,9 @@ pub async fn deleting(state: &AppState, m: &MonitorModel) { /// `PATCH /monitors/{id}/state`. pub async fn set_state(state: &AppState, m: &MonitorModel, action: Action) { + if state.daemon_manager.is_some() && runs_elsewhere(state, m) { + return; + } match (&state.daemon_manager, action) { (Some(dm), Action::Start) => log_manager(m.id, "start", dm.start_monitor(m.id).await), (Some(dm), Action::Stop) => log_manager(m.id, "stop", dm.stop_monitor(m.id).await), diff --git a/src/service/servers.rs b/src/service/servers.rs index 8c37c944..871901da 100644 --- a/src/service/servers.rs +++ b/src/service/servers.rs @@ -15,6 +15,8 @@ async fn with_counts( .map(|m| { let mut r = ServerResponse::from(m); r.monitor_count = counts.get(&m.id).copied().unwrap_or(0); + r.api_url = state.cluster.base_url(m.id, m.hostname.as_deref()); + r.is_this_server = state.server_id == Some(m.id); r }) .collect()) diff --git a/tests/it_cluster.rs b/tests/it_cluster.rs new file mode 100644 index 00000000..90b0f331 --- /dev/null +++ b/tests/it_cluster.rs @@ -0,0 +1,598 @@ +//! Multi-server installs: a request for another server's monitor is relayed +//! to the zm-api there (#230). +//! +//! The app under test is server 1. Server 2 is a stub that records what +//! reaches it and answers with a fixed status. +//! +//! Requires the test database — run with: +//! APP_PROFILE=test-db cargo test --test it_cluster -- --include-ignored + +mod common; + +use std::sync::{Arc, Mutex}; + +use axum::body::Bytes; +use axum::extract::{Request, State}; +use axum::http::{header, HeaderMap, Method, StatusCode}; +use axum::response::{IntoResponse, Response}; +use axum::Router; +use common::assertions::{assert_error, assert_status}; +use common::fixtures::{insert_monitor, RowGuard}; +use common::harness::{superuser_token, TestApp}; +use sea_orm::{ActiveModelTrait, DatabaseConnection, Set}; +use serde_json::json; +use zm_api::cluster::Cluster; +use zm_api::configure::cluster::ClusterConfig; +use zm_api::entity::monitors::{ActiveModel as MonitorActiveModel, Model as MonitorModel}; + +const HERE: u32 = 1; +const THERE: u32 = 2; + +/// One request the stub received. +#[derive(Clone)] +struct Seen { + method: Method, + path_and_query: String, + headers: HeaderMap, + body: Bytes, +} + +#[derive(Clone)] +struct Stub { + status: StatusCode, + seen: Arc>>, +} + +struct Peer { + url: String, + seen: Arc>>, +} + +impl Peer { + fn seen(&self) -> Vec { + self.seen.lock().unwrap().clone() + } +} + +async fn record(State(stub): State, request: Request) -> Response { + let (parts, body) = request.into_parts(); + let body = axum::body::to_bytes(body, usize::MAX).await.unwrap(); + stub.seen.lock().unwrap().push(Seen { + method: parts.method, + path_and_query: parts + .uri + .path_and_query() + .map(|pq| pq.as_str().to_string()) + .unwrap_or_default(), + headers: parts.headers, + body, + }); + ( + stub.status, + [ + (header::CONTENT_TYPE, "text/plain"), + (header::HeaderName::from_static("x-answered-by"), "2"), + ], + "from server 2", + ) + .into_response() +} + +/// Server 2: answers every request with `status`. +async fn peer(status: StatusCode) -> Peer { + let seen = Arc::new(Mutex::new(Vec::new())); + let router = Router::new().fallback(record).with_state(Stub { + status, + seen: seen.clone(), + }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { + axum::serve(listener, router).await.unwrap(); + }); + Peer { url, seen } +} + +/// The app as server 1, with server 2 at `peer_url` (if any). +async fn server_one(peer_url: Option<&str>) -> TestApp { + let mut config = ClusterConfig { + connect_timeout_secs: 1, + ..Default::default() + }; + if let Some(url) = peer_url { + config.peers.insert(THERE.to_string(), url.to_string()); + } + TestApp::spawn_with(move |state| { + state.server_id = Some(HERE); + state.cluster = Arc::new(Cluster::new(Some(HERE), &config, 0, false)); + }) + .await +} + +/// A monitor that `server` runs. +async fn monitor_on(db: &DatabaseConnection, label: &str, server: u32) -> MonitorModel { + let monitor = insert_monitor(db, label).await.expect("monitor"); + let mut row: MonitorActiveModel = monitor.into(); + row.server_id = Set(Some(server)); + row.update(db).await.expect("set server") +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn another_servers_monitor_is_answered_by_that_server() { + let peer = peer(StatusCode::OK).await; + let app = server_one(Some(&peer.url)).await; + let monitor = monitor_on(&app.db, "ClusterRelay", THERE).await; + let _m = RowGuard::monitor(monitor.id); + let token = superuser_token(); + + let path = format!("/api/v3/monitors/{}/snapshot?scale=50", monitor.id); + let r = app.get(&path, &token).await; + + // The owner's answer comes back as it was sent. + assert_status(&r, StatusCode::OK); + assert_eq!(r.text(), "from server 2"); + assert_eq!(r.headers["x-answered-by"], "2"); + assert_eq!(r.headers[header::CONTENT_TYPE], "text/plain"); + + // And the owner saw the same request, from the same caller. + let seen = peer.seen(); + assert_eq!(seen.len(), 1); + assert_eq!(seen[0].method, Method::GET); + assert_eq!(seen[0].path_and_query, path); + assert_eq!( + seen[0].headers[header::AUTHORIZATION], + format!("Bearer {token}") + ); + assert_eq!(seen[0].headers["x-zm-forwarded-by"], "1"); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_write_is_relayed_with_its_body() { + let peer = peer(StatusCode::ACCEPTED).await; + let app = server_one(Some(&peer.url)).await; + let monitor = monitor_on(&app.db, "ClusterWrite", THERE).await; + let _m = RowGuard::monitor(monitor.id); + + let body = json!({ "action": "on", "cause": "relay-test" }); + let r = app + .patch_json( + &format!("/api/v3/monitors/{}/alarm", monitor.id), + &superuser_token(), + &body, + ) + .await; + + assert_status(&r, StatusCode::ACCEPTED); + let seen = peer.seen(); + assert_eq!(seen.len(), 1); + assert_eq!(seen[0].method, Method::PATCH); + assert_eq!( + serde_json::from_slice::(&seen[0].body).unwrap(), + body + ); + assert_eq!(seen[0].headers[header::CONTENT_TYPE], "application/json"); +} + +/// The live routes are nested under `/api/v3/live/{monitor_id}`, which strips +/// that prefix from the URI a handler sees. The owner must get the full path. +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_nested_live_route_is_relayed_at_its_full_path() { + let peer = peer(StatusCode::OK).await; + let app = server_one(Some(&peer.url)).await; + let monitor = monitor_on(&app.db, "ClusterLive", THERE).await; + let _m = RowGuard::monitor(monitor.id); + + let path = format!("/api/v3/live/{}/hls/live.m3u8", monitor.id); + let r = app.get(&path, &superuser_token()).await; + + assert_status(&r, StatusCode::OK); + assert_eq!(peer.seen()[0].path_and_query, path); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn this_servers_own_monitor_is_not_relayed() { + let peer = peer(StatusCode::OK).await; + let app = server_one(Some(&peer.url)).await; + let monitor = monitor_on(&app.db, "ClusterLocal", HERE).await; + let _m = RowGuard::monitor(monitor.id); + + let r = app + .get( + &format!("/api/v3/monitors/{}/snapshot", monitor.id), + &superuser_token(), + ) + .await; + + assert_ne!(r.text(), "from server 2"); + assert!(peer.seen().is_empty()); +} + +/// Any server can read a monitor's row, so that never leaves this one. +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn reading_another_servers_monitor_row_stays_here() { + let peer = peer(StatusCode::OK).await; + let app = server_one(Some(&peer.url)).await; + let monitor = monitor_on(&app.db, "ClusterRow", THERE).await; + let _m = RowGuard::monitor(monitor.id); + + let r = app + .get( + &format!("/api/v3/monitors/{}", monitor.id), + &superuser_token(), + ) + .await; + + assert_status(&r, StatusCode::OK); + let row: serde_json::Value = r.json(); + assert_eq!(row["id"], monitor.id); + assert_eq!(row["server_id"], THERE); + assert!(peer.seen().is_empty()); +} + +/// A caller who can't see the monitor gets the usual 404, and nothing about +/// them or the request reaches the other server. +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_caller_who_cannot_see_the_monitor_is_not_relayed() { + use common::fixtures::{grant_monitor_permission, insert_user_with_id}; + use common::harness::token_for; + use zm_api::entity::sea_orm_active_enums::Permission; + use zm_api::util::authz::UserPermissions; + + let peer = peer(StatusCode::OK).await; + let app = server_one(Some(&peer.url)).await; + let hidden = monitor_on(&app.db, "ClusterHidden", THERE).await; + let _h = RowGuard::monitor(hidden.id); + let visible = monitor_on(&app.db, "ClusterVisible", THERE).await; + let _v = RowGuard::monitor(visible.id); + + // Denied one monitor by its own permission row. The rest follow the + // account's base level. + const UID: u32 = 990_230; + insert_user_with_id(&app.db, UID, "ClusterAcl") + .await + .expect("user"); + let _u = RowGuard::user(UID); + grant_monitor_permission(&app.db, hidden.id, UID, Permission::None) + .await + .expect("grant"); + let token = token_for(UID, UserPermissions::superuser()); + + let r = app + .get(&format!("/api/v3/monitors/{}/snapshot", hidden.id), &token) + .await; + assert_status(&r, StatusCode::NOT_FOUND); + assert!(peer.seen().is_empty()); + + // The one they can see is relayed. + let r = app + .get(&format!("/api/v3/monitors/{}/snapshot", visible.id), &token) + .await; + assert_status(&r, StatusCode::OK); + assert_eq!(peer.seen().len(), 1); +} + +/// Two servers that disagree about who owns a monitor answer with an error. +/// They do not pass the request back and forth. +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_request_that_was_already_relayed_is_not_relayed_again() { + let peer = peer(StatusCode::OK).await; + let app = server_one(Some(&peer.url)).await; + let monitor = monitor_on(&app.db, "ClusterLoop", THERE).await; + let _m = RowGuard::monitor(monitor.id); + + let r = app + .request( + Method::GET, + &format!("/api/v3/monitors/{}/snapshot", monitor.id), + ) + .bearer(&superuser_token()) + .header("x-zm-forwarded-by", "2") + .send() + .await; + + assert_error( + &r, + StatusCode::MISDIRECTED_REQUEST, + "MISDIRECTED_REQUEST_ERROR", + ); + assert!(peer.seen().is_empty()); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn an_owner_with_no_address_is_named_in_the_error() { + let app = server_one(None).await; + let monitor = monitor_on(&app.db, "ClusterNoAddr", THERE).await; + let _m = RowGuard::monitor(monitor.id); + + let r = app + .get( + &format!("/api/v3/monitors/{}/snapshot", monitor.id), + &superuser_token(), + ) + .await; + + assert_error( + &r, + StatusCode::MISDIRECTED_REQUEST, + "MISDIRECTED_REQUEST_ERROR", + ); + assert!(r.text().contains("server 2"), "{}", r.text()); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn an_owner_that_does_not_answer_is_a_bad_gateway() { + // A port nothing listens on. + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let dead = format!("http://{}", listener.local_addr().unwrap()); + drop(listener); + + let app = server_one(Some(&dead)).await; + let monitor = monitor_on(&app.db, "ClusterDown", THERE).await; + let _m = RowGuard::monitor(monitor.id); + let token = superuser_token(); + + let r = app + .get( + &format!("/api/v3/monitors/{}/snapshot?token={token}", monitor.id), + &token, + ) + .await; + + assert_error(&r, StatusCode::BAD_GATEWAY, "BAD_GATEWAY_ERROR"); + // The message names the server and leaks neither its address nor the token. + let text = r.text(); + assert!(text.contains("server 2"), "{text}"); + assert!(!text.contains("127.0.0.1"), "{text}"); + assert!(!text.contains(&token), "{text}"); +} + +/// This server accepted the token, so an owner that refuses it has different +/// signing keys. That is a setup fault, reported as one, and not a 401 that +/// would send the client to log in again for nothing. +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn an_owner_that_refuses_the_token_is_reported_as_a_key_mismatch() { + let peer = peer(StatusCode::UNAUTHORIZED).await; + let app = server_one(Some(&peer.url)).await; + let monitor = monitor_on(&app.db, "ClusterKeys", THERE).await; + let _m = RowGuard::monitor(monitor.id); + + let r = app + .get( + &format!("/api/v3/monitors/{}/snapshot", monitor.id), + &superuser_token(), + ) + .await; + + assert_error(&r, StatusCode::BAD_GATEWAY, "BAD_GATEWAY_ERROR"); + assert!(r.text().contains("JWT keys"), "{}", r.text()); +} + +/// An owner's own errors pass through: a 404 there is a 404 here. +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn the_owners_error_status_passes_through() { + let peer = peer(StatusCode::CONFLICT).await; + let app = server_one(Some(&peer.url)).await; + let monitor = monitor_on(&app.db, "ClusterStatus", THERE).await; + let _m = RowGuard::monitor(monitor.id); + + let r = app + .get( + &format!("/api/v3/monitors/{}/snapshot", monitor.id), + &superuser_token(), + ) + .await; + + assert_status(&r, StatusCode::CONFLICT); + assert_eq!(r.text(), "from server 2"); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_websocket_for_another_servers_monitor_is_refused_with_its_address() { + let peer = peer(StatusCode::OK).await; + let app = server_one(Some(&peer.url)).await; + let monitor = monitor_on(&app.db, "ClusterWs", THERE).await; + let _m = RowGuard::monitor(monitor.id); + let token = superuser_token(); + + let r = app + .request( + Method::GET, + &format!("/api/v3/live/{}/webrtc/ws?token={token}", monitor.id), + ) + .bearer(&token) + .header("connection", "upgrade") + .header("upgrade", "websocket") + .send() + .await; + + assert_error( + &r, + StatusCode::MISDIRECTED_REQUEST, + "MISDIRECTED_REQUEST_ERROR", + ); + assert!(r.text().contains(&peer.url), "{}", r.text()); + assert!(peer.seen().is_empty()); +} + +/// Moving a monitor to another server is saved here, by the server that ran +/// it, which then asks the new owner to start its daemons. +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_monitor_moved_to_another_server_is_started_there() { + let peer = peer(StatusCode::OK).await; + let app = server_one(Some(&peer.url)).await; + let monitor = monitor_on(&app.db, "ClusterMove", HERE).await; + let _m = RowGuard::monitor(monitor.id); + let token = superuser_token(); + + let r = app + .patch_json( + &format!("/api/v3/monitors/{}", monitor.id), + &token, + &json!({ "server_id": THERE }), + ) + .await; + + assert_status(&r, StatusCode::OK); + let saved: serde_json::Value = r.json(); + assert_eq!(saved["server_id"], THERE); + + let seen = peer.seen(); + assert_eq!(seen.len(), 1, "one call, to restart it on its new server"); + assert_eq!(seen[0].method, Method::PATCH); + assert_eq!( + seen[0].path_and_query, + format!("/api/v3/monitors/{}/state", monitor.id) + ); + assert_eq!( + serde_json::from_slice::(&seen[0].body).unwrap(), + json!({ "state": "restart" }) + ); + assert_eq!( + seen[0].headers[header::AUTHORIZATION], + format!("Bearer {token}") + ); + assert_eq!(seen[0].headers["x-zm-forwarded-by"], "1"); +} + +/// A single-server install has no server id, and nothing is ever relayed. +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_single_server_install_relays_nothing() { + let peer = peer(StatusCode::OK).await; + let mut config = ClusterConfig::default(); + config.peers.insert(THERE.to_string(), peer.url.clone()); + let app = TestApp::spawn_with(move |state| { + state.server_id = None; + state.cluster = Arc::new(Cluster::new(None, &config, 0, false)); + }) + .await; + let monitor = monitor_on(&app.db, "ClusterSingle", THERE).await; + let _m = RowGuard::monitor(monitor.id); + + let r = app + .get( + &format!("/api/v3/monitors/{}/snapshot", monitor.id), + &superuser_token(), + ) + .await; + + assert_ne!(r.text(), "from server 2"); + assert!(peer.seen().is_empty()); +} + +/// What each server re-reads to learn of a logout another server handled. +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn token_floors_lists_only_users_who_have_one() { + use common::fixtures::insert_user_with_id; + use sea_orm::EntityTrait; + use zm_api::entity::users; + + let app = TestApp::spawn().await; + const REVOKED: u32 = 990_231; + const CLEAN: u32 = 990_232; + for (uid, label) in [(REVOKED, "ClusterFloor"), (CLEAN, "ClusterNoFloor")] { + insert_user_with_id(&app.db, uid, label) + .await + .expect("user"); + } + let _r = RowGuard::user(REVOKED); + let _c = RowGuard::user(CLEAN); + let mut row: users::ActiveModel = users::Entity::find_by_id(REVOKED) + .one(&app.db) + .await + .unwrap() + .unwrap() + .into(); + row.token_min_expiry = Set(1_800_000_000); + row.update(&app.db).await.expect("set floor"); + + let floors = zm_api::repo::users::token_floors(&app.db).await.unwrap(); + + assert!(floors.contains(&(REVOKED, 1_800_000_000))); + assert!(!floors.iter().any(|(uid, _)| *uid == CLEAN)); +} + +/// Server 2 as a real zm-api: the same router, on a real socket, counting +/// what it handles. +async fn real_server_two() -> (String, Arc) { + use std::sync::atomic::{AtomicUsize, Ordering}; + + let app = TestApp::spawn_with(|state| { + state.server_id = Some(THERE); + state.cluster = Arc::new(Cluster::new( + Some(THERE), + &ClusterConfig::default(), + 0, + false, + )); + }) + .await; + let handled = Arc::new(AtomicUsize::new(0)); + let count = handled.clone(); + let router = app.router().layer(axum::middleware::from_fn( + move |request, next: axum::middleware::Next| { + let count = count.clone(); + async move { + count.fetch_add(1, Ordering::SeqCst); + next.run(request).await + } + }, + )); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { + axum::serve(listener, router).await.unwrap(); + }); + (url, handled) +} + +/// Both ends real: server 1 relays an edit, and server 2's own router +/// accepts the same token, applies the caller's permissions and saves it. +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn two_real_servers_share_one_token() { + use std::sync::atomic::Ordering; + + let (two, handled) = real_server_two().await; + let one = server_one(Some(&two)).await; + let monitor = monitor_on(&one.db, "ClusterReal", THERE).await; + let _m = RowGuard::monitor(monitor.id); + let path = format!("/api/v3/monitors/{}", monitor.id); + + let r = one + .patch_json( + &path, + &superuser_token(), + &json!({ "notes": "edited via server 1" }), + ) + .await; + + assert_status(&r, StatusCode::OK); + let saved: serde_json::Value = r.json(); + assert_eq!(saved["notes"], "edited via server 1"); + assert_eq!(handled.load(Ordering::SeqCst), 1, "server 2 handled it"); + + // A caller with view-only access is still refused an edit. + let viewer = common::harness::token_with(zm_api::util::authz::UserPermissions { + monitors: zm_api::util::authz::Level::View, + ..zm_api::util::authz::UserPermissions::superuser() + }); + let r = one + .patch_json(&path, &viewer, &json!({ "notes": "nope" })) + .await; + assert_status(&r, StatusCode::FORBIDDEN); +}