dahua-camera-http 0.3.1

Digest-authenticating HTTP client for Dahua camera CGI endpoints
Documentation
//! HTTP client for the cameras' own CGI interfaces.
//!
//! This replaces a hand-rolled TCP request writer that spoke Basic auth and
//! parsed responses by scanning for a blank line. That arrangement had two
//! problems worth recording, since both were silent:
//!
//! - Dahua firmware answers Basic auth with `401` and a Digest challenge, so
//!   authenticated CGI calls could never have succeeded against real hardware.
//! - Reading to EOF only terminates because the request asked the camera to
//!   close the connection, which rules out the keep-alive streaming that the
//!   analytics-event endpoint needs.

use dahua_camera_core::{CameraError, Result};
use std::time::Duration;

/// Default per-request timeout for CGI calls.
///
/// Deliberately not applied to the analytics-event stream, which is a
/// long-lived connection that is idle by design between events.
const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);

/// An HTTP client that answers a camera's Digest challenge.
///
/// Cloning is cheap: `reqwest::Client` is an `Arc` around a shared connection
/// pool, so all of a camera's CGI traffic reuses one set of sockets.
#[derive(Clone)]
pub struct CameraHttpClient {
    client: reqwest::Client,
    camera_id: String,
    username: String,
    password: String,
}

/// Hand-written so a password can never reach a log line.
///
/// The derived implementation printed `password` verbatim, which meant any
/// `{:?}` on a struct holding one of these — a config dump, a `tracing` field,
/// an `anyhow` context — leaked the credential. There is a test below that
/// fails if the derive is ever restored.
impl std::fmt::Debug for CameraHttpClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CameraHttpClient")
            .field("camera_id", &self.camera_id)
            .field("username", &self.username)
            .field("password", &"<redacted>")
            .finish_non_exhaustive()
    }
}

impl CameraHttpClient {
    /// Build a client for one camera.
    pub fn new(camera_id: &str, username: &str, password: &str) -> Self {
        // Falling back to the default client keeps construction infallible;
        // the only way `build` fails here is a broken TLS backend, which a
        // plain-HTTP client does not have.
        let client = reqwest::Client::builder()
            .timeout(REQUEST_TIMEOUT)
            .build()
            .unwrap_or_default();

        Self {
            client,
            camera_id: camera_id.to_owned(),
            username: username.to_owned(),
            password: password.to_owned(),
        }
    }

    /// `GET` a URL, answering a Digest challenge if the camera issues one.
    ///
    /// Set `stream` for endpoints that stay open indefinitely, which disables
    /// the request timeout. Everything else should leave it `false`.
    pub async fn get(&self, url: &str, stream: bool) -> Result<reqwest::Response> {
        let first = self.send(url, None, stream).await?;

        if first.status() != reqwest::StatusCode::UNAUTHORIZED {
            return self.check_status(first, url);
        }

        let challenge = first
            .headers()
            .get(reqwest::header::WWW_AUTHENTICATE)
            .and_then(|v| v.to_str().ok())
            .map(str::to_owned)
            .ok_or_else(|| self.error("401 with no WWW-Authenticate challenge"))?;

        let authorization = self.answer_challenge(&challenge, url)?;
        let second = self.send(url, Some(&authorization), stream).await?;
        self.check_status(second, url)
    }

    /// `GET` a URL and return its body as text.
    pub async fn get_text(&self, url: &str) -> Result<String> {
        self.get(url, false)
            .await?
            .text()
            .await
            .map_err(|e| self.error(&format!("reading body: {e}")))
    }

    /// `GET` a URL and return its body as bytes.
    pub async fn get_bytes(&self, url: &str) -> Result<bytes::Bytes> {
        self.get(url, false)
            .await?
            .bytes()
            .await
            .map_err(|e| self.error(&format!("reading body: {e}")))
    }

    /// `POST` a SOAP envelope, answering a Digest challenge if one comes back.
    ///
    /// ONVIF carries its own WS-Security header inside the body, but some
    /// Dahua firmware *also* demands HTTP Digest on the same endpoint, so both
    /// layers have to work at once. Returns the response body as text.
    pub async fn post_xml(&self, url: &str, body: String) -> Result<String> {
        let first = self.send_xml(url, body.clone(), None).await?;

        let response = if first.status() == reqwest::StatusCode::UNAUTHORIZED {
            let challenge = first
                .headers()
                .get(reqwest::header::WWW_AUTHENTICATE)
                .and_then(|v| v.to_str().ok())
                .map(str::to_owned)
                .ok_or_else(|| self.error("401 with no WWW-Authenticate challenge"))?;

            let authorization = self.answer_challenge_for(&challenge, url, "POST")?;
            self.send_xml(url, body, Some(&authorization)).await?
        } else {
            first
        };

        // A SOAP fault arrives with a 400 or 500 and a body worth reading, so
        // the status is not checked here — the caller parses the fault.
        response.text().await.map_err(|e| self.error(&format!("reading body: {e}")))
    }

    async fn send_xml(
        &self,
        url: &str,
        body: String,
        authorization: Option<&str>,
    ) -> Result<reqwest::Response> {
        let mut request = self
            .client
            .post(url)
            .header(reqwest::header::CONTENT_TYPE, "application/soap+xml; charset=utf-8")
            .body(body);
        if let Some(value) = authorization {
            request = request.header(reqwest::header::AUTHORIZATION, value);
        }
        request.send().await.map_err(|e| self.error(&e.to_string()))
    }

    async fn send(
        &self,
        url: &str,
        authorization: Option<&str>,
        stream: bool,
    ) -> Result<reqwest::Response> {
        let mut request = self.client.get(url);
        if stream {
            request = request.timeout(Duration::MAX);
        }
        if let Some(value) = authorization {
            request = request.header(reqwest::header::AUTHORIZATION, value);
        }
        request.send().await.map_err(|e| self.error(&e.to_string()))
    }

    /// Compute the `Authorization` header for a Digest challenge on a `GET`.
    fn answer_challenge(&self, challenge: &str, url: &str) -> Result<String> {
        self.answer_challenge_for(challenge, url, "GET")
    }

    /// Compute the `Authorization` header for a Digest challenge.
    ///
    /// The method is part of what Digest signs, so a `POST` answered with a
    /// `GET`-derived response is rejected — which looks exactly like a wrong
    /// password.
    fn answer_challenge_for(&self, challenge: &str, url: &str, method: &str) -> Result<String> {
        let mut prompt = digest_auth::parse(challenge)
            .map_err(|e| self.error(&format!("unparseable auth challenge: {e}")))?;

        // Digest signs the path and query, not the absolute URL.
        let parsed = url::Url::parse(url).map_err(|e| self.error(&format!("bad url: {e}")))?;
        let path = match parsed.query() {
            Some(query) => format!("{}?{}", parsed.path(), query),
            None => parsed.path().to_owned(),
        };

        let mut context = digest_auth::AuthContext::new(&self.username, &self.password, &path);
        context.method = digest_auth::HttpMethod::from(method);
        prompt
            .respond(&context)
            .map(|answer| answer.to_header_string())
            .map_err(|e| self.error(&format!("computing digest response: {e}")))
    }

    fn check_status(&self, response: reqwest::Response, url: &str) -> Result<reqwest::Response> {
        let status = response.status();
        if status == reqwest::StatusCode::UNAUTHORIZED {
            return Err(CameraError::Unauthorized {
                camera_id: self.camera_id.clone(),
                detail: format!("{status} for {}", redact(url)),
            });
        }
        if !status.is_success() {
            return Err(self.error(&format!("{status} for {}", redact(url))));
        }
        Ok(response)
    }

    fn error(&self, detail: &str) -> CameraError {
        CameraError::Cgi { camera_id: self.camera_id.clone(), detail: detail.to_owned() }
    }
}

/// Strip any userinfo from a URL before it reaches a log line.
fn redact(url: &str) -> String {
    match url::Url::parse(url) {
        Ok(mut parsed) if !parsed.username().is_empty() || parsed.password().is_some() => {
            let _ = parsed.set_username("");
            let _ = parsed.set_password(None);
            parsed.to_string()
        }
        _ => url.to_owned(),
    }
}

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

    fn client() -> CameraHttpClient {
        CameraHttpClient::new("front", "admin", "hunter2")
    }

    #[test]
    fn digest_response_covers_path_and_query_not_the_whole_url() {
        let challenge = r#"Digest realm="DHAC", qop="auth", nonce="abc123", opaque="xyz""#;
        let header = client()
            .answer_challenge(challenge, "http://10.0.0.5/cgi-bin/ptz.cgi?action=start&code=Up")
            .expect("challenge is answerable");

        assert!(header.starts_with("Digest "), "{header}");
        assert!(header.contains(r#"username="admin""#), "{header}");
        assert!(
            header.contains(r#"uri="/cgi-bin/ptz.cgi?action=start&code=Up""#),
            "digest must sign path+query: {header}"
        );
        assert!(!header.contains("hunter2"), "password must never appear: {header}");
    }

    #[test]
    fn digest_response_handles_a_url_with_no_query() {
        let challenge = r#"Digest realm="DHAC", qop="auth", nonce="abc123""#;
        let header = client()
            .answer_challenge(challenge, "http://10.0.0.5/cgi-bin/magicBox.cgi")
            .expect("challenge is answerable");
        assert!(header.contains(r#"uri="/cgi-bin/magicBox.cgi""#), "{header}");
    }

    #[test]
    fn a_malformed_challenge_is_an_error_not_a_panic() {
        let err = client().answer_challenge("Basic realm=\"x\"", "http://10.0.0.5/a").unwrap_err();
        assert!(matches!(err, CameraError::Cgi { .. }), "{err}");
    }

    #[test]
    fn redaction_removes_embedded_credentials() {
        assert_eq!(
            redact("http://admin:hunter2@10.0.0.5/cgi-bin/snapshot.cgi"),
            "http://10.0.0.5/cgi-bin/snapshot.cgi"
        );
    }

    #[test]
    fn debug_never_prints_the_password() {
        let rendered = format!("{:?}", client());
        assert!(!rendered.contains("hunter2"), "password leaked into Debug: {rendered}");
        assert!(rendered.contains("<redacted>"), "{rendered}");
        // The id and user are safe and useful for correlating log lines.
        assert!(rendered.contains("front") && rendered.contains("admin"), "{rendered}");
    }

    #[test]
    fn redaction_leaves_ordinary_urls_alone() {
        let url = "http://10.0.0.5/cgi-bin/snapshot.cgi?channel=1";
        assert_eq!(redact(url), url);
    }
}