shove 0.11.4

Async tasks via pubsub on steroids. Comes with built-in support for complex queue configurations, audit logs, autoscaling consumer groups and more.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
use std::future::Future;
use std::path::PathBuf;
use std::time::Duration;

use tracing::debug;
use url::Url;

use crate::error::{Result, ShoveError};
use crate::metrics;

#[derive(Clone)]
pub struct ManagementConfig {
    pub base_url: String,
    pub username: String,
    pub password: String,
    /// Raw (unencoded) vhost name. Default: `"/"` (the default RabbitMQ virtual host).
    ///
    /// Pass the vhost exactly as it appears in RabbitMQ — e.g. `"my-vhost"` or
    /// `"/"`. Percent-encoding is applied automatically when the management URL
    /// is constructed.
    pub vhost: String,
    /// Skip TLS certificate verification (insecure; only for testing/dev environments).
    pub tls_skip_verify: bool,
    /// Path to a PEM-encoded CA certificate to add as a trusted root.
    pub tls_ca_cert: Option<PathBuf>,
}

impl std::fmt::Debug for ManagementConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ManagementConfig")
            .field("base_url", &self.base_url)
            .field("username", &self.username)
            .field("password", &"<redacted>")
            .field("vhost", &self.vhost)
            .finish()
    }
}

impl ManagementConfig {
    pub fn new(
        base_url: impl Into<String>,
        username: impl Into<String>,
        password: impl Into<String>,
    ) -> Self {
        Self {
            base_url: base_url.into(),
            username: username.into(),
            password: password.into(),
            vhost: "/".into(),
            tls_skip_verify: false,
            tls_ca_cert: None,
        }
    }

    pub fn with_vhost(mut self, vhost: impl Into<String>) -> Self {
        self.vhost = vhost.into();
        self
    }

    pub fn with_tls_skip_verify(mut self) -> Self {
        self.tls_skip_verify = true;
        self
    }

    pub fn with_tls_ca_cert(mut self, path: impl Into<PathBuf>) -> Self {
        self.tls_ca_cert = Some(path.into());
        self
    }
}

/// Subset of queue statistics returned by the RabbitMQ Management API.
#[derive(Debug, Clone, Default, serde::Deserialize)]
pub struct QueueStats {
    #[serde(default)]
    pub messages_ready: u64,
    #[serde(default)]
    pub messages_unacknowledged: u64,
    #[serde(default)]
    pub consumers: u64,
}

/// Abstraction over the RabbitMQ Management HTTP API for fetching queue stats.
///
/// Using a trait here allows injecting a mock implementation in tests.
pub trait QueueStatsProvider: Send + Sync {
    fn get_queue_stats(&self, queue: &str) -> impl Future<Output = Result<QueueStats>> + Send;
}

/// HTTP client that talks to the RabbitMQ Management Plugin REST API.
#[derive(Debug)]
pub struct ManagementClient {
    http: reqwest::Client,
    config: ManagementConfig,
    /// Parsed and validated at construction. Stored to avoid re-parsing on
    /// every request and to ensure the scheme / userinfo checks are done once.
    base_url: Url,
}

impl ManagementClient {
    pub fn new(config: ManagementConfig) -> Result<Self> {
        let base_url = Url::parse(&config.base_url).map_err(|e| {
            ShoveError::Connection(format!(
                "ManagementConfig::base_url is not a valid URL ({e}): {:?}",
                config.base_url
            ))
        })?;

        let scheme = base_url.scheme();
        if scheme != "http" && scheme != "https" {
            return Err(ShoveError::Connection(format!(
                "ManagementConfig::base_url scheme must be \"http\" or \"https\", got {scheme:?}"
            )));
        }

        if !base_url.username().is_empty() || base_url.password().is_some() {
            return Err(ShoveError::Connection(format!(
                "ManagementConfig::base_url must not embed credentials \
                 (found userinfo in {:?})",
                config.base_url
            )));
        }

        let mut builder = reqwest::ClientBuilder::new()
            .connect_timeout(Duration::from_secs(5))
            .timeout(Duration::from_secs(10))
            .danger_accept_invalid_certs(config.tls_skip_verify);

        if let Some(ca_path) = &config.tls_ca_cert {
            let pem = std::fs::read(ca_path).map_err(|e| {
                ShoveError::Connection(format!(
                    "failed to read management API CA certificate at {}: {e}",
                    ca_path.display()
                ))
            })?;
            let cert = reqwest::Certificate::from_pem(&pem).map_err(|e| {
                ShoveError::Connection(format!(
                    "failed to parse management API CA certificate: {e}"
                ))
            })?;
            builder = builder.add_root_certificate(cert);
        }

        let http = builder
            .build()
            .map_err(|e| ShoveError::Connection(format!("failed to build HTTP client: {e}")))?;

        Ok(Self {
            http,
            config,
            base_url,
        })
    }
}

/// Build the management API URL for a specific vhost + queue.
///
/// Uses [`Url::path_segments_mut`] so each component is percent-encoded as an
/// opaque path segment — `/` in a vhost or queue name becomes `%2F` and cannot
/// be confused with a path separator.
///
/// Dot-segment names (`"."` and `".."`) are rejected before URL construction.
/// `path_segments_mut` does not encode `.`/`..`, and the url crate silently
/// normalises them away during serialisation, which would silently corrupt the
/// path (RFC 3986 §5.2.4). Checking the raw inputs avoids that silent
/// corruption.  A string like `"../nodes"` is safe — the interior `/` gets
/// encoded to `%2F`, making it one opaque segment.
fn build_queue_url(base: &Url, vhost: &str, queue: &str) -> Result<Url> {
    for (label, value) in [("vhost", vhost), ("queue", queue)] {
        if value == ".." || value == "." {
            return Err(ShoveError::Topology(format!(
                "management API {label} must not be a dot-segment; \
                 got {value:?} — this would silently corrupt the request URL"
            )));
        }
    }

    let mut url = base.clone();

    // `path_segments_mut` fails only for cannot-be-a-base URLs (e.g. `data:`).
    // We validated http/https at construction, so this should never fail.
    url.path_segments_mut()
        .expect("base_url is a hierarchical URL (validated at ManagementClient::new)")
        .extend(["api", "queues", vhost, queue]);

    Ok(url)
}

impl QueueStatsProvider for ManagementClient {
    async fn get_queue_stats(&self, queue: &str) -> Result<QueueStats> {
        let url = build_queue_url(&self.base_url, &self.config.vhost, queue)?;

        let request = self
            .http
            .get(url)
            .basic_auth(&self.config.username, Some(&self.config.password))
            .build()
            .map_err(|e| {
                ShoveError::Topology(format!("failed to build management API request: {e}"))
            })?;

        let response =
            self.http.execute(request).await.map_err(|e| {
                ShoveError::Connection(format!("management API request failed: {e}"))
            })?;

        if !response.status().is_success() {
            let status = response.status();
            metrics::record_backend_error(
                metrics::BackendLabel::RabbitMq,
                metrics::BackendErrorKind::Topology,
            );
            return Err(ShoveError::Connection(format!(
                "management API returned non-success status {status} for queue {queue}"
            )));
        }

        let stats = response.json::<QueueStats>().await.map_err(|e| {
            ShoveError::Topology(format!(
                "failed to deserialize management API response for queue {queue}: {e}"
            ))
        })?;

        debug!(
            queue,
            messages_ready = stats.messages_ready,
            messages_unacknowledged = stats.messages_unacknowledged,
            consumers = stats.consumers,
            "fetched queue stats"
        );

        Ok(stats)
    }
}

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

    // ---------------------------------------------------------------------------
    // ManagementConfig
    // ---------------------------------------------------------------------------

    #[test]
    fn management_config_debug_redacts_password() {
        let config = ManagementConfig::new("http://localhost:15672", "admin", "s3cret!");
        let debug_output = format!("{config:?}");
        assert!(!debug_output.contains("s3cret!"));
        assert!(debug_output.contains("<redacted>"));
        assert!(debug_output.contains("admin"));
        assert!(debug_output.contains("localhost"));
    }

    #[test]
    fn management_config_defaults() {
        let config = ManagementConfig::new("http://localhost:15672", "guest", "guest");
        assert_eq!(config.base_url, "http://localhost:15672");
        assert_eq!(config.username, "guest");
        assert_eq!(config.password, "guest");
        // Default vhost is the raw "/" — encoding happens at URL construction time.
        assert_eq!(config.vhost, "/");
    }

    #[test]
    fn management_config_with_vhost() {
        let config = ManagementConfig::new("http://localhost:15672", "guest", "guest")
            .with_vhost("my-vhost");
        assert_eq!(config.vhost, "my-vhost");
    }

    // ---------------------------------------------------------------------------
    // QueueStats
    // ---------------------------------------------------------------------------

    #[test]
    fn queue_stats_defaults() {
        let stats = QueueStats::default();
        assert_eq!(stats.messages_ready, 0);
        assert_eq!(stats.messages_unacknowledged, 0);
        assert_eq!(stats.consumers, 0);
    }

    #[test]
    fn queue_stats_deserialize_full() {
        let json = r#"{"messages_ready": 42, "messages_unacknowledged": 7, "consumers": 3}"#;
        let stats: QueueStats = serde_json::from_str(json).unwrap();
        assert_eq!(stats.messages_ready, 42);
        assert_eq!(stats.messages_unacknowledged, 7);
        assert_eq!(stats.consumers, 3);
    }

    #[test]
    fn queue_stats_deserialize_partial() {
        let json = r#"{"messages_ready": 10}"#;
        let stats: QueueStats = serde_json::from_str(json).unwrap();
        assert_eq!(stats.messages_ready, 10);
        assert_eq!(stats.messages_unacknowledged, 0);
        assert_eq!(stats.consumers, 0);
    }

    #[test]
    fn queue_stats_deserialize_empty_object() {
        let json = r#"{}"#;
        let stats: QueueStats = serde_json::from_str(json).unwrap();
        assert_eq!(stats.messages_ready, 0);
        assert_eq!(stats.messages_unacknowledged, 0);
        assert_eq!(stats.consumers, 0);
    }

    #[test]
    fn queue_stats_deserialize_extra_fields_ignored() {
        let json = r#"{"messages_ready": 5, "node": "rabbit@host", "state": "running"}"#;
        let stats: QueueStats = serde_json::from_str(json).unwrap();
        assert_eq!(stats.messages_ready, 5);
    }

    // ---------------------------------------------------------------------------
    // URL construction — build_queue_url
    // ---------------------------------------------------------------------------

    fn base(url: &str) -> Url {
        Url::parse(url).unwrap()
    }

    #[test]
    fn url_default_vhost_encoded_as_slash() {
        // Raw "/" vhost must be percent-encoded to "%2F" in the URL path.
        let url = build_queue_url(&base("http://localhost:15672"), "/", "my-queue").unwrap();
        assert_eq!(
            url.as_str(),
            "http://localhost:15672/api/queues/%2F/my-queue"
        );
    }

    #[test]
    fn url_named_vhost_passes_through() {
        let url = build_queue_url(&base("http://localhost:15672"), "staging", "orders").unwrap();
        assert_eq!(
            url.as_str(),
            "http://localhost:15672/api/queues/staging/orders"
        );
    }

    #[test]
    fn url_vhost_with_slash_encoded() {
        // A vhost name that legitimately contains "/" must be encoded, not
        // interpreted as a path separator.
        let url = build_queue_url(&base("http://localhost:15672"), "ns/vhost", "q").unwrap();
        assert!(
            url.as_str().contains("ns%2Fvhost"),
            "slash in vhost not encoded: {url}"
        );
    }

    #[test]
    fn url_queue_with_slash_encoded() {
        // Queue names may legally contain "/" (e.g. namespaced queues); each
        // slash must be encoded so it doesn't introduce an extra path segment.
        let url = build_queue_url(&base("http://localhost:15672"), "/", "ns/queue").unwrap();
        assert!(
            url.as_str().contains("ns%2Fqueue"),
            "slash in queue not encoded: {url}"
        );
    }

    #[test]
    fn url_queue_with_hash_encoded() {
        let url = build_queue_url(&base("http://localhost:15672"), "/", "q#1").unwrap();
        assert!(url.as_str().contains("q%231"), "# not encoded: {url}");
    }

    #[test]
    fn url_queue_with_question_mark_encoded() {
        let url = build_queue_url(&base("http://localhost:15672"), "/", "q?1").unwrap();
        assert!(url.as_str().contains("q%3F1"), "? not encoded: {url}");
    }

    // --- dot-segment traversal rejection ---

    #[test]
    fn url_rejects_dotdot_vhost() {
        // ".." as a path segment causes HTTP servers to navigate to the parent
        // directory, reaching unrelated management endpoints.
        let result = build_queue_url(&base("http://localhost:15672"), "..", "queue");
        assert!(
            result.is_err(),
            "expected error for '..' vhost, got: {result:?}"
        );
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("dot-segment"),
            "error should mention dot-segment: {msg}"
        );
    }

    #[test]
    fn url_rejects_dot_vhost() {
        let result = build_queue_url(&base("http://localhost:15672"), ".", "queue");
        assert!(result.is_err(), "expected error for '.' vhost");
    }

    #[test]
    fn url_rejects_dotdot_queue() {
        let result = build_queue_url(&base("http://localhost:15672"), "/", "..");
        assert!(result.is_err(), "expected error for '..' queue");
    }

    #[test]
    fn url_slash_in_vhost_does_not_traverse() {
        // "../nodes" contains a slash which path_segments_mut encodes as %2F,
        // so the full string becomes "..%2Fnodes" — one opaque segment, not a
        // traversal. This must succeed (the vhost is odd but not dangerous).
        let result = build_queue_url(&base("http://localhost:15672"), "../nodes", "q");
        assert!(
            result.is_ok(),
            "unexpected error for '../nodes' vhost: {result:?}"
        );
        let url = result.unwrap();
        assert!(
            url.as_str().contains("..%2Fnodes"),
            "slash not encoded within segment: {url}"
        );
    }

    // --- base_url validation ---

    #[test]
    fn management_client_rejects_file_scheme() {
        let err = ManagementClient::new(ManagementConfig::new("file:///etc/passwd", "u", "p"))
            .unwrap_err();
        assert!(
            err.to_string().contains("scheme must be"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn management_client_rejects_ftp_scheme() {
        let err =
            ManagementClient::new(ManagementConfig::new("ftp://host/path", "u", "p")).unwrap_err();
        assert!(
            err.to_string().contains("scheme must be"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn management_client_rejects_embedded_userinfo() {
        let err = ManagementClient::new(ManagementConfig::new(
            "http://admin:secret@localhost:15672",
            "u",
            "p",
        ))
        .unwrap_err();
        assert!(
            err.to_string().contains("must not embed credentials"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn management_client_rejects_embedded_username_only() {
        let err = ManagementClient::new(ManagementConfig::new(
            "http://admin@localhost:15672",
            "u",
            "p",
        ))
        .unwrap_err();
        assert!(
            err.to_string().contains("must not embed credentials"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn management_client_rejects_invalid_url() {
        let err = ManagementClient::new(ManagementConfig::new("not a url", "u", "p")).unwrap_err();
        assert!(
            err.to_string().contains("not a valid URL"),
            "unexpected error: {err}"
        );
    }
}