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
55 changes: 49 additions & 6 deletions src/dto/request/filters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,19 @@ pub fn parse_email_format(s: &str) -> EmailFormat {
/// other column of the `Filters` table is optional and falls back to the
/// schema default when omitted (flags `0`, `execute_interval` `60`,
/// `email_format` `Individual`).
/// `zmfilter.pl` puts these in the headers of the mail it sends, and the
/// server name in its SMTP connection. A line break in one would start a new
/// header (a `Bcc:`, say) or a new SMTP command, so none may hold a control
/// character.
fn mail_header(value: &Option<String>, _: &()) -> garde::Result {
match value.as_deref() {
Some(v) if v.chars().any(char::is_control) => Err(garde::Error::new(
"must not contain line breaks or control characters",
)),
_ => Ok(()),
}
}

#[derive(Debug, Default, Clone, Serialize, Deserialize, ToSchema, Validate)]
pub struct CreateFilterRequest {
#[garde(length(chars, max = 64))]
Expand Down Expand Up @@ -48,13 +61,13 @@ pub struct CreateFilterRequest {
pub auto_upload: Option<u8>,
#[garde(skip)]
pub auto_email: Option<u8>,
#[garde(skip)]
#[garde(custom(mail_header))]
pub email_to: Option<String>,
#[garde(skip)]
#[garde(custom(mail_header))]
pub email_subject: Option<String>,
#[garde(skip)]
pub email_body: Option<String>,
#[garde(skip)]
#[garde(custom(mail_header))]
pub email_server: Option<String>,
#[garde(skip)]
pub auto_message: Option<u8>,
Expand Down Expand Up @@ -111,13 +124,13 @@ pub struct UpdateFilterRequest {
pub auto_upload: Option<u8>,
#[garde(skip)]
pub auto_email: Option<u8>,
#[garde(skip)]
#[garde(custom(mail_header))]
pub email_to: Option<String>,
#[garde(skip)]
#[garde(custom(mail_header))]
pub email_subject: Option<String>,
#[garde(skip)]
pub email_body: Option<String>,
#[garde(skip)]
#[garde(custom(mail_header))]
pub email_server: Option<String>,
#[garde(skip)]
pub auto_message: Option<u8>,
Expand All @@ -144,3 +157,33 @@ pub struct UpdateFilterRequest {
#[garde(skip)]
pub lock_rows: Option<u8>,
}

#[cfg(test)]
mod mail_tests {
use super::*;

#[test]
fn a_mail_field_cannot_carry_a_second_header() {
let ok = CreateFilterRequest {
name: "nightly".into(),
email_to: Some("ops@example.com, me@example.com".into()),
email_subject: Some("ZoneMinder: %EI% on %MN%".into()),
email_server: Some("smtp.example.com:587".into()),
..Default::default()
};
assert!(ok.validate().is_ok());

let injected = CreateFilterRequest {
name: "nightly".into(),
email_to: Some("ops@example.com\r\nBcc: thief@example.net".into()),
..Default::default()
};
assert!(injected.validate().is_err());

let update = UpdateFilterRequest {
email_subject: Some("alarm\nX-Injected: 1".into()),
..Default::default()
};
assert!(update.validate().is_err());
}
}
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
46 changes: 44 additions & 2 deletions src/dto/request/notifications.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,33 @@ impl PushState {
}
}

/// A monitor list is ids and commas. ZoneMinder's push sender reads the
/// column back and splits it, so anything else stored here is handed to code
/// that expects numbers.
fn monitor_id_list(value: &str) -> garde::Result {
let ok = value.len() <= 1024
&& value
.split(',')
.map(str::trim)
.all(|id| id.is_empty() || id.parse::<u32>().is_ok());
if ok {
Ok(())
} else {
Err(garde::Error::new("must be comma-separated monitor ids"))
}
}

fn monitor_ids(value: &Option<String>, _: &()) -> garde::Result {
value.as_deref().map_or(Ok(()), monitor_id_list)
}

fn monitor_ids_update(value: &Option<Option<String>>, _: &()) -> garde::Result {
match value {
Some(Some(list)) => monitor_id_list(list),
_ => Ok(()),
}
}

/// Register a push token. A token already registered is updated in place,
/// as ZoneMinder's `notifications.json` does.
#[derive(Debug, Serialize, Deserialize, ToSchema, Validate)]
Expand All @@ -61,7 +88,7 @@ pub struct CreateNotificationRequest {
#[garde(skip)]
pub platform: PushPlatform,
/// Comma-separated monitor ids to notify for; empty or absent for all.
#[garde(skip)]
#[garde(custom(monitor_ids))]
pub monitor_list: Option<String>,
/// Minimum seconds between pushes.
#[garde(skip)]
Expand Down Expand Up @@ -92,7 +119,7 @@ pub struct UpdateNotificationRequest {
/// `null` clears it; omit to leave it unchanged.
#[serde(default, deserialize_with = "crate::dto::serde_helpers::double_option")]
#[schema(value_type = Option<String>)]
#[garde(skip)]
#[garde(custom(monitor_ids_update))]
pub monitor_list: Option<Option<String>>,
#[garde(skip)]
pub interval: Option<u32>,
Expand All @@ -116,3 +143,18 @@ pub struct UpdateNotificationRequest {
#[garde(skip)]
pub user_id: Option<u32>,
}

#[cfg(test)]
mod monitor_list_tests {
use super::*;

#[test]
fn a_monitor_list_is_ids_and_commas() {
for ok in ["", "1", "1,2,30", " 4, 5 "] {
assert!(monitor_id_list(ok).is_ok(), "{ok:?}");
}
for bad in ["1 OR 1=1", "1;DROP TABLE Monitors", "a,b", "1,-2", "1\n2"] {
assert!(monitor_id_list(bad).is_err(), "{bad:?}");
}
}
}
Loading
Loading