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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ async-trait = "0.1"
axum = { version = "0.8", features = ["ws"] }
axum-extra = { version = "0.12", features = ["typed-header"] }
axum-server = { version = "0.8", features = ["tls-rustls"] }
# For the HTTP/1 header read timeout: hyper enforces it only with a timer.
hyper-util = { version = "0.1", features = ["tokio"] }
rustls = { version = "0.23", default-features = false, features = ["ring", "std"] }
rustls-pki-types = { version = "1", features = ["std"] }
tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12", "logging"] }
Expand Down Expand Up @@ -127,6 +129,7 @@ tower-http = { version = "0.7", features = [
"compression-gzip",
"compression-br",
"set-header",
"timeout",
] }
tower_governor = "0.8"

Expand Down
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
21 changes: 20 additions & 1 deletion src/dto/pagination.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@ pub const DEFAULT_PAGE_SIZE: u64 = 25;
/// Maximum page size allowed
pub const MAX_PAGE_SIZE: u64 = 1000;

/// The highest page number honoured. A row offset is `page * page_size`, here
/// and inside the ORM's paginator; with a page near `u64::MAX` that multiply
/// overflows, which panics a debug build and wraps to an arbitrary offset in
/// a release one. No table has this many pages.
pub const MAX_PAGE: u64 = u32::MAX as u64;

/// Common pagination query parameters for list endpoints
#[derive(Debug, Clone, Default, Deserialize, Serialize, ToSchema, Validate)]
pub struct PaginationParams {
Expand All @@ -27,7 +33,7 @@ pub struct PaginationParams {
impl PaginationParams {
/// Get the page number (1-indexed), defaulting to 1
pub fn page(&self) -> u64 {
self.page.unwrap_or(1).max(1)
self.page.unwrap_or(1).clamp(1, MAX_PAGE)
}

/// Get the page size, defaulting to DEFAULT_PAGE_SIZE
Expand Down Expand Up @@ -91,6 +97,19 @@ impl<T> PaginatedResponse<T> {
mod tests {
use super::*;

/// `?page=18446744073709551615` must not overflow the offset.
#[test]
fn a_huge_page_number_does_not_overflow_the_offset() {
let params = PaginationParams {
page: Some(u64::MAX),
page_size: Some(MAX_PAGE_SIZE),
};
assert_eq!(params.page(), MAX_PAGE);
assert_eq!(params.offset(), (MAX_PAGE - 1) * MAX_PAGE_SIZE);
// What the ORM's paginator computes from the page it is given.
assert!(params.page().checked_mul(params.page_size()).is_some());
}

#[test]
fn test_pagination_params_defaults() {
let params = PaginationParams::default();
Expand Down
10 changes: 10 additions & 0 deletions src/dto/request/monitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,14 @@ pub fn is_safe_capture_path(value: &str, ctx: &()) -> garde::Result {
if v.is_empty() || v.starts_with('/') {
return Ok(());
}
// zmc fetches whatever this names, as the server. A camera on the same
// host is normal, so loopback stays allowed; a cloud metadata service is
// never a camera, and it answers with the instance's credentials.
if crate::util::net_guard::names_metadata_service(v) {
return Err(garde::Error::new(
"must not point at a cloud metadata service",
));
}
match v.split_once("://") {
Some((scheme, _)) if CAPTURE_SCHEMES.contains(&scheme.to_ascii_lowercase().as_str()) => {
Ok(())
Expand Down Expand Up @@ -1364,6 +1372,8 @@ mod validator_tests {

#[test]
fn storage_path_must_be_shell_literal() {
assert!(is_safe_capture_path("rtsp://127.0.0.1:8554/cam", &()).is_ok());
assert!(is_safe_capture_path("http://169.254.169.254/latest/meta-data/", &()).is_err());
assert!(is_safe_storage_path("", &()).is_ok());
assert!(is_safe_storage_path("/var/cache/zoneminder/events", &()).is_ok());
assert!(is_safe_storage_path("/mnt/nas-1/zm_events.2", &()).is_ok());
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
23 changes: 22 additions & 1 deletion src/handlers/event_export.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,17 @@ use crate::service::monitor_acl::MonitorScope;
/// (`frames.json`), `images`, `video` and `misc` (the event directory's other
/// files). Every id is checked first: one that doesn't exist or isn't
/// visible to the caller is a 404 and nothing is sent.
/// The most exports written at once. One reads up to 500 events' recordings
/// off the disks the cameras are recording to, and it takes only View access
/// to start one, so without a limit a viewer could start enough to stall
/// recording.
const MAX_CONCURRENT_EXPORTS: usize = 4;

static EXPORT_SLOTS: once_cell::sync::Lazy<std::sync::Arc<tokio::sync::Semaphore>> =
once_cell::sync::Lazy::new(|| {
std::sync::Arc::new(tokio::sync::Semaphore::new(MAX_CONCURRENT_EXPORTS))
});

#[utoipa::path(
post,
path = "/api/v3/events/export",
Expand All @@ -39,9 +50,19 @@ pub async fn export_events(
Json(req): Json<EventExportRequest>,
) -> AppResult<Response> {
req.validate().map_err(AppError::InvalidInputError)?;
// Taken before any work, held until the archive is written.
let slot = EXPORT_SLOTS.clone().try_acquire_owned().map_err(|_| {
AppError::ServiceUnavailableError(format!(
"{MAX_CONCURRENT_EXPORTS} exports are already running; try again when one finishes"
))
})?;
let exports = svc::prepare(&state, &scope, &req.ids).await?;
let (writer, reader) = tokio::io::duplex(64 * 1024);
tokio::spawn(svc::write(state.clone(), exports, req.parts(), writer));
let (state_for_write, parts) = (state.clone(), req.parts());
tokio::spawn(async move {
let _slot = slot;
svc::write(state_for_write, exports, parts, writer).await;
});

let name = format!(
"attachment; filename=\"zm-events-{}.zip\"",
Expand Down
Loading
Loading