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
4 changes: 3 additions & 1 deletion .github/workflows/cla.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ jobs:
(github.event.comment.body == 'recheck' ||
github.event.comment.body == 'I have read the CLA Document and I hereby sign the CLA') ||
github.event_name == 'pull_request_target'
uses: contributor-assistant/github-action@v2.6.1
# Pinned to the commit, not the tag: this job runs on pull_request_target
# with a write token, and a tag can be moved to other code.
uses: contributor-assistant/github-action@ca4a40a7d1004f18d9960b404b97e5f30a505a08 # v2.6.1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
Expand Down
8 changes: 6 additions & 2 deletions .github/workflows/docs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@ on:
- '.github/workflows/docs.yml'
workflow_dispatch:

# The build job runs third-party actions and builds whatever the branch
# holds, pull requests included, so it only reads. Publishing rights go to the
# deploy job alone.
permissions:
contents: read
pages: write
id-token: write

# Let a run finish rather than cancelling it; a half-published site is worse
# than a slightly stale one.
Expand Down Expand Up @@ -124,6 +125,9 @@ jobs:
if: github.ref == 'refs/heads/master' && github.event_name != 'pull_request'
needs: build
runs-on: ubuntu-latest
permissions:
pages: write
id-token: write
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
Expand Down
5 changes: 5 additions & 0 deletions .github/workflows/packaging.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ concurrency:
group: packaging-${{ github.ref }}
cancel-in-progress: true

# Nothing here writes to the repository; without this the token gets the
# repository's default permissions, which may include write.
permissions:
contents: read

env:
CARGO_TERM_COLOR: always

Expand Down
15 changes: 12 additions & 3 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,11 @@ on:
tags: ['v*']
workflow_dispatch:

# Read-only by default. The build jobs run third-party actions (toolchain,
# cache) and build scripts, and none of them needs to write to the repository;
# only the `release` job, which publishes, is given that below.
permissions:
contents: write
contents: read

env:
CARGO_TERM_COLOR: always
Expand Down Expand Up @@ -65,7 +68,10 @@ jobs:
# Build every bin target first: the asset list ships `migrator` as
# zm-api-db alongside the server, and cargo-deb only copies paths.
run: |
cargo build --release --bins
# --locked: build the dependency versions in Cargo.lock, the ones
# reviewed and audited, as the rpm and Arch builds do. Without it a
# stale lockfile is quietly re-resolved to whatever is newest.
cargo build --release --bins --locked
cargo deb --no-build

- name: Sanity-check package (no private keys, lists files)
Expand Down Expand Up @@ -276,6 +282,8 @@ jobs:
release:
name: Publish release
needs: [deb, rpm, arch, openapi, install-test]
permissions:
contents: write
if: always() && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
steps:
Expand Down Expand Up @@ -336,7 +344,8 @@ jobs:
echo "found=false" >> "$GITHUB_OUTPUT"
fi

- uses: softprops/action-gh-release@v2
# Pinned to the commit: this step holds a token that can write releases.
- uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2.6.2
with:
files: artifacts/**
fail_on_unmatched_files: false
Expand Down
5 changes: 5 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ on:
pull_request:
branches: [ master, main ]

# Nothing here writes to the repository; without this the token gets the
# repository's default permissions, which may include write.
permissions:
contents: read

env:
CARGO_TERM_COLOR: always
RUST_BACKTRACE: 1
Expand Down
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
6 changes: 4 additions & 2 deletions docker-compose.test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ services:
MYSQL_USER: zmuser
MYSQL_PASSWORD: zmpass
ports:
- "3307:3306"
# Loopback only: the passwords here are in the repository, and without
# an address Docker publishes the port on every interface.
- "127.0.0.1:3307:3306"
volumes:
- test-db-data:/var/lib/mysql
healthcheck:
Expand All @@ -36,7 +38,7 @@ services:
POSTGRES_USER: postgres
POSTGRES_DB: zm_test_pg
ports:
- "5433:5432"
- "127.0.0.1:5433:5432"
volumes:
- test-db-postgres-data:/var/lib/postgresql/data
healthcheck:
Expand Down
14 changes: 14 additions & 0 deletions packaging/setup-instance.sh
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ FALLBACK_HOME="/var/lib/zoneminder"
STATE_DIR="/var/lib/zm-api"
KEY_DIR="${STATE_DIR}/keys"
LOG_DIR="/var/log/zm-api"
CONFIG_DIR="${ZM_API_CONFIG_DIR:-/etc/zm-api}"

# Last assignment of KEY across zm.conf and conf.d/*.conf, the order
# ZoneMinder itself reads them in.
Expand Down Expand Up @@ -156,6 +157,19 @@ mv -f "$tmp" "$DROPIN"
install -d -o "$svc_user" -g "$svc_group" -m 0750 "$STATE_DIR" "$KEY_DIR" "$LOG_DIR"
chown -R "$svc_user:$svc_group" "$STATE_DIR" "$LOG_DIR"

# ---------------------------------------------------------------------------
# 4b. prod.toml and zm-api.env are where an operator puts the database
# password, the TURN password and API keys, and the packages install them
# 0644. Close them to everyone but root and the service account. base.toml
# is the packaged defaults and stays readable.
# ---------------------------------------------------------------------------
for f in prod.toml zm-api.env; do
if [[ -f "${CONFIG_DIR}/${f}" && ! -L "${CONFIG_DIR}/${f}" ]]; then
chown "root:${svc_group}" "${CONFIG_DIR}/${f}"
chmod 0640 "${CONFIG_DIR}/${f}"
fi
done

# ---------------------------------------------------------------------------
# 5. JWT signing keys, generated once and never overwritten.
# ---------------------------------------------------------------------------
Expand Down
10 changes: 7 additions & 3 deletions scripts/deploy-dev.sh
Original file line number Diff line number Diff line change
Expand Up @@ -106,12 +106,16 @@ else
fi
info "Built $(basename "$ARTIFACT") ($(du -h "$ARTIFACT" | cut -f1))"

# On-box install command for whichever artifact we built.
# On-box install command for whichever artifact we built. The upload goes to
# the login's home directory, not /tmp: with a fixed name in a directory every
# local user can write to, someone else on the box could put their own file
# there, or swap it between the upload and the `sudo install` below, and have
# it installed as root.
if [ "$FAST" = "yes" ]; then
REMOTE="/tmp/zm-api.new"
REMOTE="./zm-api.new"
INSTALL_CMD="sudo install -m 0755 ${REMOTE} /usr/bin/zm-api && rm -f ${REMOTE} && sudo systemctl restart ${SERVICE} && systemctl --no-pager --full status ${SERVICE} | head -n 15"
else
REMOTE="/tmp/zm-api.deb"
REMOTE="./zm-api.deb"
INSTALL_CMD="sudo apt-get install -y ${REMOTE} && rm -f ${REMOTE} && sudo systemctl enable --now ${SERVICE} && sudo systemctl restart ${SERVICE} && systemctl --no-pager --full status ${SERVICE} | head -n 20"
fi

Expand Down
3 changes: 2 additions & 1 deletion scripts/generate-jwt-keys.sh
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ generate_pair() {
return 0
fi

openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out "$private_key"
# umask first: without it the key is world-readable until the chmod below.
(umask 077 && openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out "$private_key")
openssl rsa -in "$private_key" -pubout -out "$public_key"
chmod 600 "$private_key"
chmod 644 "$public_key"
Expand Down
2 changes: 1 addition & 1 deletion scripts/package.sh
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ build_deb() {
echo "cargo-deb is required: cargo install cargo-deb" >&2
return 1
fi
(cd "$ROOT" && cargo deb)
(cd "$ROOT" && cargo deb --locked)
}

build_rpm() {
Expand Down
51 changes: 47 additions & 4 deletions 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 @@ -95,14 +117,18 @@ fn default_database_name() -> String {
}

/// Where MariaDB and MySQL put their socket: Debian/Ubuntu and Arch (and the
/// /var/run symlink to it), openSUSE, the Red Hat family, and the upstream
/// tarball default.
/// /var/run symlink to it), openSUSE, and the Red Hat family.
///
/// The upstream tarball's `/tmp/mysql.sock` is left out on purpose. Any local
/// user can create a socket there, and whenever the real ones are absent (the
/// database not started yet) zm-api would connect to it, send it the database
/// password and believe its `Users` table. An install that does keep its
/// socket in `/tmp` names it in `db.socket`.
const DEFAULT_SOCKETS: &[&str] = &[
"/run/mysqld/mysqld.sock",
"/var/run/mysqld/mysqld.sock",
"/run/mysql/mysql.sock",
"/var/lib/mysql/mysql.sock",
"/tmp/mysql.sock",
];

/// The Unix socket a connection to `host` should go through, if any.
Expand Down Expand Up @@ -307,6 +333,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 Expand Up @@ -353,6 +384,18 @@ mod tests {
assert_eq!(socket.as_deref(), Some("/run/mysqld/mysqld.sock"));
}

/// A socket in a directory every local user can write to is never
/// picked without being asked for.
#[test]
fn a_socket_in_tmp_is_used_only_when_configured() {
let only_tmp = |p: &str| p == "/tmp/mysql.sock";
assert_eq!(resolve_socket("localhost", None, only_tmp), None);
assert_eq!(
resolve_socket("localhost", Some("/tmp/mysql.sock"), only_tmp).as_deref(),
Some("/tmp/mysql.sock")
);
}

#[test]
fn localhost_resolves_to_the_first_socket_present() {
let only_redhat = |p: &str| p == "/var/lib/mysql/mysql.sock";
Expand Down
34 changes: 32 additions & 2 deletions src/configure/secret.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,37 @@ pub struct SecretConfig {
pub public_refresh_key: PathBuf,
}

/// Whether a file of this mode can be read by users other than its owner.
fn others_can_read(mode: u32) -> bool {
mode & 0o044 != 0
}

/// Read a signing key, and say so in the log if other local users can read
/// it too: whoever holds it can mint a token for any user. It is a warning
/// and not a refusal, so an install that has run this way still starts.
fn read_private(path: PathBuf) -> Result<String, std::io::Error> {
use std::os::unix::fs::PermissionsExt;
let key = fs::read_to_string(&path)?;
if fs::metadata(&path).is_ok_and(|m| others_can_read(m.permissions().mode())) {
tracing::warn!(
"the signing key {} is readable by other users; run `chmod 600` on it",
path.display()
);
}
Ok(key)
}

impl SecretConfig {
pub fn read_private_access_key(&self) -> Result<String, std::io::Error> {
fs::read_to_string(util::dir::get_project_root()?.join(&self.private_access_key))
read_private(util::dir::get_project_root()?.join(&self.private_access_key))
}

pub fn read_public_access_key(&self) -> Result<String, std::io::Error> {
fs::read_to_string(util::dir::get_project_root()?.join(&self.public_access_key))
}

pub fn read_private_refresh_key(&self) -> Result<String, std::io::Error> {
fs::read_to_string(util::dir::get_project_root()?.join(&self.private_refresh_key))
read_private(util::dir::get_project_root()?.join(&self.private_refresh_key))
}

pub fn read_public_refresh_key(&self) -> Result<String, std::io::Error> {
Expand All @@ -34,6 +54,16 @@ impl SecretConfig {
mod tests {
use crate::constant::CONFIG;

#[test]
fn a_key_only_its_owner_can_read_is_the_only_safe_one() {
use super::others_can_read;
assert!(!others_can_read(0o600));
assert!(!others_can_read(0o400));
assert!(others_can_read(0o640));
assert!(others_can_read(0o644));
assert!(others_can_read(0o604));
}

#[test]
fn test_read_private_access_key() {
let key = CONFIG.secret.read_private_access_key().unwrap();
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
Loading
Loading