rabbitmq-backup-core 0.1.0

Core engine for RabbitMQ backup and restore operations
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
//! Storage configuration types.

use serde::{Deserialize, Serialize};
use std::path::PathBuf;

/// Storage backend configuration using tagged enum for type-safe configuration.
///
/// Supports multiple storage backends:
/// - S3 and S3-compatible (MinIO, Ceph RGW, etc.)
/// - Azure Blob Storage
/// - Google Cloud Storage
/// - Local filesystem
/// - In-memory (for testing)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "backend")]
pub enum StorageBackendConfig {
    /// AWS S3 or S3-compatible storage (MinIO, Ceph RGW, DigitalOcean Spaces, etc.)
    #[serde(rename = "s3")]
    S3 {
        /// S3 bucket name
        bucket: String,
        /// AWS region (e.g., "us-east-1")
        #[serde(default)]
        region: Option<String>,
        /// Custom endpoint URL (for S3-compatible services like MinIO)
        #[serde(default)]
        endpoint: Option<String>,
        /// Access key ID (falls back to AWS_ACCESS_KEY_ID env var)
        #[serde(default)]
        access_key: Option<String>,
        /// Secret access key (falls back to AWS_SECRET_ACCESS_KEY env var)
        #[serde(default)]
        secret_key: Option<String>,
        /// Key prefix for all operations
        #[serde(default)]
        prefix: Option<String>,
        /// Use path-style requests (required for MinIO/Ceph RGW)
        #[serde(default)]
        path_style: bool,
        /// Allow HTTP (insecure) connections
        #[serde(default)]
        allow_http: bool,
    },

    /// Azure Blob Storage
    #[serde(rename = "azure")]
    Azure {
        /// Azure storage account name
        account_name: String,
        /// Azure blob container name
        container_name: String,
        /// Storage account key (if None, uses DefaultAzureCredential chain)
        #[serde(default)]
        account_key: Option<String>,
        /// Key prefix for all operations
        #[serde(default)]
        prefix: Option<String>,
        /// Custom endpoint URL for sovereign clouds
        #[serde(default)]
        endpoint: Option<String>,
        /// Enable Workload Identity authentication (for AKS)
        #[serde(default)]
        use_workload_identity: Option<bool>,
        /// Azure AD client ID
        #[serde(default)]
        client_id: Option<String>,
        /// Azure AD tenant ID
        #[serde(default)]
        tenant_id: Option<String>,
        /// Client secret (for service principal authentication)
        #[serde(default)]
        client_secret: Option<String>,
        /// SAS token for shared access signature authentication
        #[serde(default)]
        sas_token: Option<String>,
    },

    /// Google Cloud Storage
    #[serde(rename = "gcs")]
    Gcs {
        /// GCS bucket name
        bucket: String,
        /// Path to service account JSON key file
        #[serde(default)]
        service_account_path: Option<String>,
        /// Key prefix for all operations
        #[serde(default)]
        prefix: Option<String>,
    },

    /// Local filesystem storage
    #[serde(rename = "filesystem")]
    Filesystem {
        /// Base path for storage
        path: PathBuf,
    },

    /// In-memory storage (for testing)
    #[serde(rename = "memory")]
    Memory,
}

impl StorageBackendConfig {
    /// Parse configuration from a URL string.
    ///
    /// Supported URL formats:
    /// - `s3://bucket-name?region=us-east-1`
    /// - `azure://account.blob.core.windows.net/container`
    /// - `gcs://bucket-name`
    /// - `file:///path/to/data`
    /// - `memory://`
    pub fn from_url(url: &str) -> crate::Result<Self> {
        let parsed = url::Url::parse(url)
            .map_err(|e| crate::Error::Config(format!("Invalid storage URL: {}", e)))?;

        match parsed.scheme() {
            "s3" | "s3a" => {
                let bucket = parsed.host_str().unwrap_or_default().to_string();
                let prefix = path_prefix(&parsed);
                let region = parsed
                    .query_pairs()
                    .find(|(k, _)| k == "region")
                    .map(|(_, v)| v.to_string());
                let endpoint = parsed
                    .query_pairs()
                    .find(|(k, _)| k == "endpoint")
                    .map(|(_, v)| v.to_string());
                let path_style = parsed
                    .query_pairs()
                    .find(|(k, _)| k == "path_style")
                    .map(|(_, v)| v == "true")
                    .unwrap_or(false);
                let allow_http = parsed
                    .query_pairs()
                    .find(|(k, _)| k == "allow_http")
                    .map(|(_, v)| v == "true")
                    .unwrap_or(false);

                Ok(Self::S3 {
                    bucket,
                    region,
                    endpoint,
                    access_key: std::env::var("AWS_ACCESS_KEY_ID").ok(),
                    secret_key: std::env::var("AWS_SECRET_ACCESS_KEY").ok(),
                    prefix,
                    path_style,
                    allow_http,
                })
            }
            "azure" | "az" => {
                let host = parsed.host_str().unwrap_or_default();
                let account_name = host.split('.').next().unwrap_or(host).to_string();
                let path = parsed.path().trim_start_matches('/');
                let (container_name, prefix) = split_first_path_component(path);

                let has_workload_identity = std::env::var("AZURE_FEDERATED_TOKEN_FILE").is_ok();

                Ok(Self::Azure {
                    account_name,
                    container_name,
                    account_key: std::env::var("AZURE_STORAGE_KEY")
                        .ok()
                        .or_else(|| std::env::var("AZURE_STORAGE_ACCOUNT_KEY").ok()),
                    prefix,
                    endpoint: None,
                    use_workload_identity: if has_workload_identity {
                        Some(true)
                    } else {
                        None
                    },
                    client_id: std::env::var("AZURE_CLIENT_ID").ok(),
                    tenant_id: std::env::var("AZURE_TENANT_ID").ok(),
                    client_secret: std::env::var("AZURE_CLIENT_SECRET").ok(),
                    sas_token: std::env::var("AZURE_STORAGE_SAS_TOKEN").ok(),
                })
            }
            "gcs" | "gs" => {
                let bucket = parsed.host_str().unwrap_or_default().to_string();
                let prefix = path_prefix(&parsed);

                Ok(Self::Gcs {
                    bucket,
                    service_account_path: std::env::var("GOOGLE_APPLICATION_CREDENTIALS").ok(),
                    prefix,
                })
            }
            "file" => Ok(Self::Filesystem {
                path: PathBuf::from(parsed.path()),
            }),
            "memory" => Ok(Self::Memory),
            scheme => Err(crate::Error::Config(format!(
                "Unknown storage scheme: {}",
                scheme
            ))),
        }
    }

    /// Get the prefix for this storage configuration.
    pub fn prefix(&self) -> Option<&str> {
        match self {
            Self::S3 { prefix, .. } => prefix.as_deref(),
            Self::Azure { prefix, .. } => prefix.as_deref(),
            Self::Gcs { prefix, .. } => prefix.as_deref(),
            Self::Filesystem { .. } => None,
            Self::Memory => None,
        }
    }
}

fn path_prefix(parsed: &url::Url) -> Option<String> {
    let prefix = parsed.path().trim_matches('/');
    if prefix.is_empty() {
        None
    } else {
        Some(prefix.to_string())
    }
}

fn split_first_path_component(path: &str) -> (String, Option<String>) {
    let trimmed = path.trim_matches('/');
    match trimmed.split_once('/') {
        Some((first, rest)) => (first.to_string(), Some(rest.trim_matches('/').to_string())),
        None => (trimmed.to_string(), None),
    }
}

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

    #[test]
    fn test_s3_url_parsing() {
        let config = StorageBackendConfig::from_url("s3://my-bucket?region=us-west-2").unwrap();
        match config {
            StorageBackendConfig::S3 { bucket, region, .. } => {
                assert_eq!(bucket, "my-bucket");
                assert_eq!(region, Some("us-west-2".to_string()));
            }
            _ => panic!("Expected S3 config"),
        }
    }

    #[test]
    fn test_s3_url_parsing_with_prefix_and_flags() {
        let config = StorageBackendConfig::from_url(
            "s3://my-bucket/backups/prod?region=us-west-2&path_style=true&allow_http=true",
        )
        .unwrap();
        match config {
            StorageBackendConfig::S3 {
                bucket,
                region,
                prefix,
                path_style,
                allow_http,
                ..
            } => {
                assert_eq!(bucket, "my-bucket");
                assert_eq!(region, Some("us-west-2".to_string()));
                assert_eq!(prefix, Some("backups/prod".to_string()));
                assert!(path_style);
                assert!(allow_http);
            }
            _ => panic!("Expected S3 config"),
        }
    }

    #[test]
    fn test_gcs_url_parsing_with_prefix() {
        let config = StorageBackendConfig::from_url("gcs://my-bucket/backups/prod").unwrap();
        match config {
            StorageBackendConfig::Gcs { bucket, prefix, .. } => {
                assert_eq!(bucket, "my-bucket");
                assert_eq!(prefix, Some("backups/prod".to_string()));
            }
            _ => panic!("Expected GCS config"),
        }
    }

    #[test]
    fn test_azure_url_parsing_with_container_and_prefix() {
        let config =
            StorageBackendConfig::from_url("azure://account.blob.core.windows.net/container/path")
                .unwrap();
        match config {
            StorageBackendConfig::Azure {
                account_name,
                container_name,
                prefix,
                ..
            } => {
                assert_eq!(account_name, "account");
                assert_eq!(container_name, "container");
                assert_eq!(prefix, Some("path".to_string()));
            }
            _ => panic!("Expected Azure config"),
        }
    }

    #[test]
    fn test_filesystem_url_parsing() {
        let config = StorageBackendConfig::from_url("file:///var/rabbitmq-backups").unwrap();
        match config {
            StorageBackendConfig::Filesystem { path } => {
                assert_eq!(path, PathBuf::from("/var/rabbitmq-backups"));
            }
            _ => panic!("Expected Filesystem config"),
        }
    }

    #[test]
    fn test_memory_url_parsing() {
        let config = StorageBackendConfig::from_url("memory://").unwrap();
        assert!(matches!(config, StorageBackendConfig::Memory));
    }

    #[test]
    fn test_yaml_deserialization_s3() {
        let yaml = r#"
backend: s3
bucket: rabbitmq-backups
region: us-east-1
endpoint: http://localhost:9000
path_style: true
allow_http: true
"#;
        let config: StorageBackendConfig = serde_yaml::from_str(yaml).unwrap();
        match config {
            StorageBackendConfig::S3 {
                bucket,
                region,
                endpoint,
                path_style,
                allow_http,
                ..
            } => {
                assert_eq!(bucket, "rabbitmq-backups");
                assert_eq!(region, Some("us-east-1".to_string()));
                assert_eq!(endpoint, Some("http://localhost:9000".to_string()));
                assert!(path_style);
                assert!(allow_http);
            }
            _ => panic!("Expected S3 config"),
        }
    }

    #[test]
    fn test_yaml_deserialization_filesystem() {
        let yaml = r#"
backend: filesystem
path: /tmp/backups
"#;
        let config: StorageBackendConfig = serde_yaml::from_str(yaml).unwrap();
        match config {
            StorageBackendConfig::Filesystem { path } => {
                assert_eq!(path, PathBuf::from("/tmp/backups"));
            }
            _ => panic!("Expected Filesystem config"),
        }
    }

    #[test]
    fn test_yaml_deserialization_memory() {
        let yaml = "backend: memory\n";
        let config: StorageBackendConfig = serde_yaml::from_str(yaml).unwrap();
        assert!(matches!(config, StorageBackendConfig::Memory));
    }

    #[test]
    fn test_yaml_deserialization_azure() {
        let yaml = r#"
backend: azure
account_name: myaccount
container_name: backups
"#;
        let config: StorageBackendConfig = serde_yaml::from_str(yaml).unwrap();
        match config {
            StorageBackendConfig::Azure {
                account_name,
                container_name,
                ..
            } => {
                assert_eq!(account_name, "myaccount");
                assert_eq!(container_name, "backups");
            }
            _ => panic!("Expected Azure config"),
        }
    }

    #[test]
    fn test_yaml_deserialization_gcs() {
        let yaml = r#"
backend: gcs
bucket: my-gcs-bucket
prefix: backups/
"#;
        let config: StorageBackendConfig = serde_yaml::from_str(yaml).unwrap();
        match config {
            StorageBackendConfig::Gcs { bucket, prefix, .. } => {
                assert_eq!(bucket, "my-gcs-bucket");
                assert_eq!(prefix, Some("backups/".to_string()));
            }
            _ => panic!("Expected GCS config"),
        }
    }

    #[test]
    fn test_unknown_scheme() {
        let result = StorageBackendConfig::from_url("ftp://example.com");
        assert!(result.is_err());
    }
}