Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 28 additions & 1 deletion src/configure/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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()
}
Expand Down Expand Up @@ -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]
Expand Down
12 changes: 11 additions & 1 deletion src/configure/sentry.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,24 @@
use sentry::ClientInitGuard;
use serde::Deserialize;

#[derive(Debug, Deserialize, Clone)]
#[derive(Deserialize, Clone)]
pub struct SentryConfig {
#[serde(default)]
pub enabled: bool,
#[serde(default)]
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<ClientInitGuard> {
Expand Down
23 changes: 22 additions & 1 deletion src/configure/streaming.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ impl Default for WebRtcConfig {
}
}

#[derive(Debug, Clone, Deserialize)]
#[derive(Clone, Deserialize)]
#[serde(default)]
pub struct TurnConfig {
pub enabled: bool,
Expand All @@ -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 {
Expand Down Expand Up @@ -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();
Expand Down
37 changes: 37 additions & 0 deletions src/dto/response/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down Expand Up @@ -86,3 +97,29 @@ impl From<PaginatedResponse<StorageResponse>> 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"));
}
}
21 changes: 21 additions & 0 deletions src/error/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down Expand Up @@ -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
Expand Down
8 changes: 5 additions & 3 deletions src/handlers/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,16 @@ fn tokens(resp: TokenResponse) -> Tokens {
pub async fn login(
State(state): State<AppState>,
Json(req): Json<LoginRequest>,
) -> AppResult<Json<TokenResponse>> {
info!("Login attempt for user: {}.", req.username);
) -> AppResult<Tokens> {
// 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:?}.");
Expand Down
28 changes: 25 additions & 3 deletions src/handlers/events_playback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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!(
Expand Down
4 changes: 3 additions & 1 deletion src/handlers/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,9 @@ pub async fn change_state(
State(state): State<AppState>,
Path(action): Path<String>,
) -> AppResult<Json<MessageResponse>> {
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" => {
Expand Down
23 changes: 21 additions & 2 deletions src/handlers/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -27,9 +33,17 @@ use serde::Deserialize;
)]
pub async fn list_storage(
State(state): State<AppState>,
axum::Extension(claims): axum::Extension<crate::util::claim::UserClaims>,
Query(params): Query<PaginationParams>,
) -> AppResult<Json<PaginatedStorageResponse>> {
let result = crate::service::storage::list_paginated(&state, &params).await?;
let mut result = crate::service::storage::list_paginated(&state, &params).await?;
if !may_edit(&claims) {
result.items = result
.items
.into_iter()
.map(StorageResponse::without_secrets)
.collect();
}
Ok(Json(PaginatedStorageResponse::from(result)))
}

Expand All @@ -47,9 +61,14 @@ pub async fn list_storage(
pub async fn get_storage(
Path(id): Path<u16>,
State(state): State<AppState>,
axum::Extension(claims): axum::Extension<crate::util::claim::UserClaims>,
) -> AppResult<Json<StorageResponse>> {
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.
Expand Down
Loading
Loading