diff --git a/src/configure/db.rs b/src/configure/db.rs index eb330f4..99a63b2 100644 --- a/src/configure/db.rs +++ b/src/configure/db.rs @@ -18,7 +18,7 @@ use super::zmconf::ZmConfig; /// /// When using placeholder values in TOML (like "username", "password"), /// the actual values will be loaded from ZoneMinder's zm.conf if available. -#[derive(Debug, Deserialize, Clone)] +#[derive(Deserialize, Clone)] pub struct DatabaseConfig { #[serde(default = "default_username")] pub username: String, @@ -57,6 +57,28 @@ pub struct DatabaseConfig { pub sqlx_logging: bool, } +// Manual Debug: the config is `{:?}`-printable all the way up from +// `AppConfig`, and the password must not come out with it. +impl std::fmt::Debug for DatabaseConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("DatabaseConfig") + .field("username", &self.username) + .field("password", &"[REDACTED]") + .field("port", &self.port) + .field("host", &self.host) + .field("socket", &self.socket) + .field("max_connections", &self.max_connections) + .field("min_connections", &self.min_connections) + .field("connect_timeout_secs", &self.connect_timeout_secs) + .field("acquire_timeout_secs", &self.acquire_timeout_secs) + .field("idle_timeout_secs", &self.idle_timeout_secs) + .field("max_lifetime_secs", &self.max_lifetime_secs) + .field("database_name", &self.database_name) + .field("sqlx_logging", &self.sqlx_logging) + .finish() + } +} + fn default_username() -> String { "zmuser".to_string() } @@ -307,6 +329,11 @@ mod tests { config.get_url(), "mysql://testuser:testpass@dbhost:3307/testdb?timezone=SYSTEM" ); + + // Printing the config, as a log line or a panic would, hides it. + let printed = format!("{config:?}"); + assert!(!printed.contains("testpass"), "{printed}"); + assert!(printed.contains("testuser")); } #[test] diff --git a/src/configure/sentry.rs b/src/configure/sentry.rs index d8ec957..4bded28 100644 --- a/src/configure/sentry.rs +++ b/src/configure/sentry.rs @@ -1,7 +1,7 @@ use sentry::ClientInitGuard; use serde::Deserialize; -#[derive(Debug, Deserialize, Clone)] +#[derive(Deserialize, Clone)] pub struct SentryConfig { #[serde(default)] pub enabled: bool, @@ -9,6 +9,16 @@ pub struct SentryConfig { dsn: String, } +// Manual Debug: a DSN holds the project's ingest key. +impl std::fmt::Debug for SentryConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("SentryConfig") + .field("enabled", &self.enabled) + .field("dsn", &"[REDACTED]") + .finish() + } +} + /// Initialize Sentry error reporting if enabled and DSN is configured. /// Returns None if Sentry is disabled or DSN is empty. pub fn init(config: &SentryConfig) -> Option { diff --git a/src/configure/streaming.rs b/src/configure/streaming.rs index 910cfa5..2f868ff 100644 --- a/src/configure/streaming.rs +++ b/src/configure/streaming.rs @@ -133,7 +133,7 @@ impl Default for WebRtcConfig { } } -#[derive(Debug, Clone, Deserialize)] +#[derive(Clone, Deserialize)] #[serde(default)] pub struct TurnConfig { pub enabled: bool, @@ -142,6 +142,18 @@ pub struct TurnConfig { pub password: String, } +// Manual Debug: the TURN password must not come out with the config. +impl std::fmt::Debug for TurnConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("TurnConfig") + .field("enabled", &self.enabled) + .field("server", &self.server) + .field("username", &self.username) + .field("password", &"[REDACTED]") + .finish() + } +} + impl Default for TurnConfig { fn default() -> Self { Self { @@ -242,6 +254,15 @@ impl Default for RtspConfig { mod tests { use super::*; + #[test] + fn the_turn_password_is_not_printed_with_the_config() { + let turn = TurnConfig { + password: "hunter2".to_string(), + ..TurnConfig::default() + }; + assert!(!format!("{turn:?}").contains("hunter2")); + } + #[test] fn test_streaming_config_default() { let config = StreamingConfig::default(); diff --git a/src/dto/response/storage.rs b/src/dto/response/storage.rs index 572d892..4315691 100644 --- a/src/dto/response/storage.rs +++ b/src/dto/response/storage.rs @@ -30,6 +30,17 @@ pub struct StorageFilesystem { } impl StorageResponse { + /// For a caller who may view storage but not edit it: the URL without + /// its password. An S3 area's is its secret key + /// (`s3fs://KEY:SECRET@host/bucket`). + pub fn without_secrets(mut self) -> Self { + self.url = self + .url + .as_deref() + .map(crate::dto::response::monitor::hide_url_password); + self + } + /// Fill `filesystem` from the storage path (a `statvfs`). pub fn with_filesystem(mut self) -> Self { self.filesystem = crate::daemon::stats::filesystem_usage(std::path::Path::new(&self.path)) @@ -86,3 +97,29 @@ impl From> for PaginatedStorageResponse { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_viewer_does_not_get_the_s3_secret_key() { + let shown = StorageResponse { + id: 2, + name: "cloud".into(), + path: "/mnt/s3".into(), + r#type: "s3fs".into(), + scheme: "Medium".into(), + server_id: None, + url: Some("s3fs://AKIAEXAMPLE:wJalrXUtnFEMI@s3.example.com/bucket".into()), + disk_space: None, + do_delete: 1, + enabled: 1, + filesystem: None, + } + .without_secrets(); + let url = shown.url.unwrap(); + assert!(!url.contains("wJalrXUtnFEMI"), "{url}"); + assert!(url.contains("AKIAEXAMPLE") && url.contains("s3.example.com/bucket")); + } +} diff --git a/src/error/mod.rs b/src/error/mod.rs index 5de4008..f2af5e6 100644 --- a/src/error/mod.rs +++ b/src/error/mod.rs @@ -201,6 +201,13 @@ impl AppError { None => "A database error occurred".to_string(), }; } + // A reqwest error names the URL it was sent to, which can hold a + // camera's or a provider's credentials and maps out what this server + // can reach. Same treatment as a database error. + if let HttpClientError(err) = &self { + tracing::error!("outbound HTTP request failed: {err}"); + message = "A request to another service failed".to_string(); + } let (kind, code, details, status_code) = match self { InvalidPayloadError(_err) => ( "INVALID_PAYLOAD_ERROR".to_string(), @@ -616,6 +623,20 @@ mod tests { assert!(!body.error_message.contains("column")); } + /// A failed outbound request must not hand its URL to the client. + #[tokio::test] + async fn http_client_error_message_is_generic() { + // Port 1 on loopback refuses at once. + let err = reqwest::Client::new() + .get("http://admin:hunter2@127.0.0.1:1/onvif?key=s3cret") + .send() + .await + .expect_err("nothing listens on port 1"); + let (status, body) = AppError::HttpClientError(err).response(); + assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR); + assert_eq!(body.error_message, "A request to another service failed"); + } + /// GH #55: the message parser behind the "data too long" → 400 mapping. /// /// The driver's text is the only place the column name appears, so this diff --git a/src/handlers/auth.rs b/src/handlers/auth.rs index e74767d..d46ffe8 100644 --- a/src/handlers/auth.rs +++ b/src/handlers/auth.rs @@ -44,14 +44,16 @@ fn tokens(resp: TokenResponse) -> Tokens { pub async fn login( State(state): State, Json(req): Json, -) -> AppResult> { - info!("Login attempt for user: {}.", req.username); +) -> AppResult { + // Validate before logging: the name is the client's text until then, and + // a newline in it would forge log lines. req.validate()?; + info!("Login attempt for user: {}.", req.username); let username = req.username.clone(); match service::auth::login(&state, req).await { Ok(resp) => { info!("Successfully logged in user: {username}."); - Ok(Json(resp)) + Ok(tokens(resp)) } Err(e) => { warn!("Unsuccessfully login user error: {e:?}."); diff --git a/src/handlers/events_playback.rs b/src/handlers/events_playback.rs index bfacbad..46a5a3f 100644 --- a/src/handlers/events_playback.rs +++ b/src/handlers/events_playback.rs @@ -478,10 +478,19 @@ async fn event_vod_assets( let video_path = get_event_video_path(state, id, scope).await?; let info = crate::streaming::probe::probe_event_media(id, video_path.clone()) .await - .map_err(AppError::InternalServerError)?; + .map_err(|e| unreadable_recording(id, &e))?; crate::streaming::hls::vod::get_or_build(id, video_path, info) .await - .map_err(AppError::InternalServerError) + .map_err(|e| unreadable_recording(id, &e)) +} + +/// The error for a recording that couldn't be read. `detail` names the file +/// with its full path on the server, which shows the storage layout to +/// anyone who may view events. It goes to the log; the client is told only +/// which event. +fn unreadable_recording(event_id: u64, detail: &str) -> AppError { + tracing::warn!("event {event_id}: {detail}"); + AppError::InternalServerError(format!("event {event_id}'s recording could not be read")) } /// Get the fMP4 initialization segment for an event's HLS-VOD stream. @@ -745,7 +754,7 @@ pub async fn get_event_info( let info = crate::streaming::probe::probe_event_media(path.id, video_path) .await - .map_err(AppError::InternalServerError)?; + .map_err(|e| unreadable_recording(path.id, &e))?; let playable_direct = info.playable_direct(); Ok(Json(EventVideoInfo { @@ -933,6 +942,19 @@ mod tests { // parse_range_header // ------------------------------------------------------------------ + #[test] + fn an_unreadable_recording_does_not_name_its_path() { + let detail = + "open \"/var/cache/zoneminder/events/3/2026-11-15/41/41-video.mp4\": Invalid data"; + let (_, body) = unreadable_recording(41, detail).response(); + assert!( + !body.error_message.contains("/var/cache"), + "{}", + body.error_message + ); + assert!(body.error_message.contains("41")); + } + #[test] fn parse_range_header_normal_closed_range() { assert_eq!( diff --git a/src/handlers/server.rs b/src/handlers/server.rs index 6f14aa8..3a4eff9 100644 --- a/src/handlers/server.rs +++ b/src/handlers/server.rs @@ -88,7 +88,9 @@ pub async fn change_state( State(state): State, Path(action): Path, ) -> AppResult> { - info!("Handling request to change ZoneMinder state: {}", action); + // `{:?}`: the action is the caller's text, and a line break in it would + // forge a log line. + info!("Handling request to change ZoneMinder state: {:?}", action); let message = match action.to_lowercase().as_str() { "restart" => { diff --git a/src/handlers/storage.rs b/src/handlers/storage.rs index 8aafea4..3ab3c32 100644 --- a/src/handlers/storage.rs +++ b/src/handlers/storage.rs @@ -11,6 +11,12 @@ use axum::{ use garde::Validate; use serde::Deserialize; +/// Whether the caller may edit storage, and so already knows its secrets. +fn may_edit(claims: &crate::util::claim::UserClaims) -> bool { + use crate::util::authz::{Feature, Level}; + claims.perms.level(Feature::System) >= Level::Edit +} + /// List storage definitions used by ZoneMinder for event/video storage. /// /// - Requires a valid JWT. @@ -27,9 +33,17 @@ use serde::Deserialize; )] pub async fn list_storage( State(state): State, + axum::Extension(claims): axum::Extension, Query(params): Query, ) -> AppResult> { - let result = crate::service::storage::list_paginated(&state, ¶ms).await?; + let mut result = crate::service::storage::list_paginated(&state, ¶ms).await?; + if !may_edit(&claims) { + result.items = result + .items + .into_iter() + .map(StorageResponse::without_secrets) + .collect(); + } Ok(Json(PaginatedStorageResponse::from(result))) } @@ -47,9 +61,14 @@ pub async fn list_storage( pub async fn get_storage( Path(id): Path, State(state): State, + axum::Extension(claims): axum::Extension, ) -> AppResult> { let item = crate::service::storage::get_by_id(&state, id).await?; - Ok(Json(item)) + Ok(Json(if may_edit(&claims) { + item + } else { + item.without_secrets() + })) } /// Create a new storage entry. diff --git a/src/ptz/bridge.rs b/src/ptz/bridge.rs index e54729f..5b379da 100644 --- a/src/ptz/bridge.rs +++ b/src/ptz/bridge.rs @@ -461,18 +461,7 @@ impl PerlControlProxy { "zmcontrol.pl failed" ); - // Parse common error conditions - let error_msg = if stderr.contains("Authentication") { - return Err(PtzError::AuthenticationFailed(stderr.to_string())); - } else if stderr.contains("not supported") { - return Err(PtzError::CommandNotSupported(stderr.to_string())); - } else if stderr.contains("Connection") || stderr.contains("timeout") { - return Err(PtzError::CameraOffline(stderr.to_string())); - } else { - format!("Exit code {}: {}", exit_code, stderr) - }; - - return Err(PtzError::PerlBridgeError(error_msg)); + return Err(classify_failure(exit_code, &stderr)); } if !stderr.is_empty() { @@ -489,6 +478,25 @@ impl PerlControlProxy { } } +/// The error for a failed zmcontrol.pl run, from what it wrote to stderr. +/// +/// The text itself stays in the log. It goes back to whoever sent the PTZ +/// command, who needs only Control access, and a control module's errors +/// quote the camera's address, which holds its user name and password. +fn classify_failure(exit_code: i32, stderr: &str) -> PtzError { + if stderr.contains("Authentication") { + PtzError::AuthenticationFailed("the camera refused the stored credentials".to_string()) + } else if stderr.contains("not supported") { + PtzError::CommandNotSupported("the camera's control does not support it".to_string()) + } else if stderr.contains("Connection") || stderr.contains("timeout") { + PtzError::CameraOffline("the camera did not answer".to_string()) + } else { + PtzError::PerlBridgeError(format!( + "zmcontrol.pl exited with code {exit_code}; see the server log" + )) + } +} + #[async_trait] impl PtzControl for PerlControlProxy { fn capabilities(&self) -> &PtzCapabilities { @@ -616,6 +624,35 @@ impl PtzControlFactory for PerlControlFactory { mod tests { use super::*; + /// A control module's error names the camera URL, password and all. The + /// caller, who may hold only Control access, must not be sent it. + #[test] + fn a_failed_command_does_not_return_what_zmcontrol_printed() { + let leaks = [ + "Authentication failed for http://admin:hunter2@10.0.0.9/cgi-bin/ptz", + "Connection refused: http://admin:hunter2@10.0.0.9/cgi-bin/ptz", + "move not supported by http://admin:hunter2@10.0.0.9", + "Can't locate object via http://admin:hunter2@10.0.0.9 at line 3", + ]; + for stderr in leaks { + let shown = classify_failure(1, stderr).to_string(); + assert!(!shown.contains("hunter2"), "{shown}"); + assert!(!shown.contains("10.0.0.9"), "{shown}"); + } + assert!(matches!( + classify_failure(1, leaks[0]), + PtzError::AuthenticationFailed(_) + )); + assert!(matches!( + classify_failure(1, leaks[1]), + PtzError::CameraOffline(_) + )); + assert!(matches!( + classify_failure(2, leaks[3]), + PtzError::PerlBridgeError(_) + )); + } + fn test_config() -> PtzConnectionConfig { PtzConnectionConfig { monitor_id: 1, diff --git a/src/util/middleware.rs b/src/util/middleware.rs index d4c0555..8b7c7c0 100644 --- a/src/util/middleware.rs +++ b/src/util/middleware.rs @@ -9,11 +9,18 @@ use tracing::{debug, warn}; use crate::{server::state::AppState, util::claim::UserClaims}; /// Middleware to verify JWT token for protected routes +/// +/// It does not check token revocation. Use it only inside a router that +/// [`authz::protect`](crate::util::authz::protect) or a monitor gate wraps, +/// which do; a route with a login and no feature gate takes +/// [`authenticated_middleware`]. `tests/token_revocation.rs` walks every +/// documented route with a revoked token. pub async fn auth_middleware( request: Request, next: Next, ) -> Result { - debug!("Authenticating request: {}", request.uri()); + // Path only: a query string can carry a token, which must not reach logs. + debug!("Authenticating request: {}", request.uri().path()); // Extract the authorization header let auth_header = request