mockforge-ftp 0.3.236

FTP protocol support for MockForge
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
use crate::spec_registry::FtpSpecRegistry;
use crate::storage::MockForgeStorage;
use crate::vfs::VirtualFileSystem;
use anyhow::Result;
use libunftp::ServerBuilder;
use mockforge_core::config::FtpConfig;
use std::sync::Arc;
use tracing::info;

/// FTP Server implementation for MockForge
#[derive(Debug)]
pub struct FtpServer {
    config: FtpConfig,
    vfs: Arc<VirtualFileSystem>,
    spec_registry: Arc<FtpSpecRegistry>,
}

impl FtpServer {
    pub fn new(config: FtpConfig) -> Self {
        let vfs = Arc::new(VirtualFileSystem::new(config.virtual_root.clone()));
        let spec_registry = Arc::new(FtpSpecRegistry::new().with_vfs(vfs.clone()));

        Self {
            config,
            vfs,
            spec_registry,
        }
    }

    /// Create a server pre-loaded with FTP fixtures.
    ///
    /// `FtpSpecRegistry` fixtures are attached at construction time via its
    /// builder, so this is the public path for programmatic fixtures
    /// (`FtpServer::new` starts empty; the registry is immutable afterwards).
    pub fn new_with_fixtures(
        config: FtpConfig,
        fixtures: Vec<crate::fixtures::FtpFixture>,
    ) -> Result<Self> {
        let vfs = Arc::new(VirtualFileSystem::new(config.virtual_root.clone()));
        let spec_registry =
            Arc::new(FtpSpecRegistry::new().with_vfs(vfs.clone()).with_fixtures(fixtures)?);

        Ok(Self {
            config,
            vfs,
            spec_registry,
        })
    }

    pub async fn start(&self) -> Result<()> {
        let addr = format!("{}:{}", self.config.host, self.config.port);
        info!("Starting FTP server on {}", addr);

        // Create the storage backend
        let storage = MockForgeStorage::new(self.vfs.clone(), self.spec_registry.clone());

        // Create the FTP server with our custom storage
        let server = ServerBuilder::new(Box::new(move || storage.clone()))
            .greeting("MockForge FTP Server")
            .passive_ports(self.config.passive_ports.0..=self.config.passive_ports.1)
            .idle_session_timeout(self.config.timeout_secs);

        info!("FTP server listening on {}", addr);
        let server = server.build()?;
        server.listen(&addr).await?;

        Ok(())
    }

    pub async fn handle_upload(&self, path: &std::path::Path, data: Vec<u8>) -> Result<()> {
        // Handle file upload through fixtures
        let path_str = path.to_string_lossy();

        // Find matching upload rule
        if let Some(rule) = self.spec_registry.find_upload_rule(&path_str) {
            // Validate the upload
            rule.validate_file(&data, &path_str).map_err(|e| anyhow::anyhow!(e))?;

            if rule.auto_accept {
                // Store the file based on rule
                match &rule.storage {
                    crate::fixtures::UploadStorage::Memory => {
                        // Store in VFS
                        let size = data.len() as u64;
                        let file = crate::vfs::VirtualFile::new(
                            path.to_path_buf(),
                            crate::vfs::FileContent::Static(data),
                            crate::vfs::FileMetadata {
                                size,
                                ..Default::default()
                            },
                        );
                        self.vfs.add_file_async(path.to_path_buf(), file).await?;
                    }
                    crate::fixtures::UploadStorage::File { path: storage_path } => {
                        // Write to file system
                        tokio::fs::write(storage_path, &data).await?;
                    }
                    crate::fixtures::UploadStorage::Discard => {
                        // Do nothing
                    }
                }
            }
        }

        Ok(())
    }

    pub fn spec_registry(&self) -> Arc<FtpSpecRegistry> {
        self.spec_registry.clone()
    }

    pub fn vfs(&self) -> Arc<VirtualFileSystem> {
        self.vfs.clone()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fixtures::{FileValidation, UploadRule, UploadStorage};

    #[test]
    fn test_ftp_server_new() {
        let config = FtpConfig {
            host: "127.0.0.1".to_string(),
            port: 2121,
            virtual_root: std::path::PathBuf::from("/"),
            ..Default::default()
        };

        let server = FtpServer::new(config.clone());
        assert_eq!(server.config.host, "127.0.0.1");
        assert_eq!(server.config.port, 2121);
    }

    #[test]
    fn test_ftp_server_debug() {
        let config = FtpConfig {
            host: "localhost".to_string(),
            port: 21,
            virtual_root: std::path::PathBuf::from("/tmp"),
            ..Default::default()
        };

        let server = FtpServer::new(config);
        let debug = format!("{:?}", server);
        assert!(debug.contains("FtpServer"));
    }

    #[test]
    fn test_ftp_server_spec_registry() {
        let config = FtpConfig {
            host: "127.0.0.1".to_string(),
            port: 2121,
            virtual_root: std::path::PathBuf::from("/"),
            ..Default::default()
        };

        let server = FtpServer::new(config);
        let registry = server.spec_registry();
        assert!(registry.fixtures.is_empty());
    }

    #[test]
    fn test_ftp_server_vfs() {
        let config = FtpConfig {
            host: "127.0.0.1".to_string(),
            port: 2121,
            virtual_root: std::path::PathBuf::from("/test"),
            ..Default::default()
        };

        let server = FtpServer::new(config);
        let vfs = server.vfs();
        let files = vfs.list_files(&std::path::PathBuf::from("/"));
        assert!(files.is_empty());
    }

    #[tokio::test]
    async fn test_handle_upload_memory_storage() {
        let config = FtpConfig {
            host: "127.0.0.1".to_string(),
            port: 2121,
            virtual_root: std::path::PathBuf::from("/"),
            ..Default::default()
        };

        let server = FtpServer::new(config);

        // Create a fixture with an upload rule
        let rule = UploadRule {
            path_pattern: r"^/uploads/.*".to_string(),
            auto_accept: true,
            validation: None,
            storage: UploadStorage::Memory,
        };

        let fixture = crate::fixtures::FtpFixture {
            identifier: "test".to_string(),
            name: "Test".to_string(),
            description: None,
            virtual_files: vec![],
            upload_rules: vec![rule],
        };

        // Update the spec registry
        let new_registry = FtpSpecRegistry::new()
            .with_vfs(server.vfs.clone())
            .with_fixtures(vec![fixture])
            .unwrap();

        let server = FtpServer {
            config: server.config,
            vfs: server.vfs.clone(),
            spec_registry: Arc::new(new_registry),
        };

        let path = std::path::Path::new("/uploads/test.txt");
        let data = b"test file content".to_vec();

        let result = server.handle_upload(path, data.clone()).await;
        assert!(result.is_ok());

        // Verify file was stored in VFS
        let file = server.vfs.get_file_async(path).await;
        assert!(file.is_some());
    }

    #[tokio::test]
    async fn test_handle_upload_discard_storage() {
        let config = FtpConfig {
            host: "127.0.0.1".to_string(),
            port: 2121,
            virtual_root: std::path::PathBuf::from("/"),
            ..Default::default()
        };

        let server = FtpServer::new(config);

        let rule = UploadRule {
            path_pattern: r"^/uploads/.*".to_string(),
            auto_accept: true,
            validation: None,
            storage: UploadStorage::Discard,
        };

        let fixture = crate::fixtures::FtpFixture {
            identifier: "test".to_string(),
            name: "Test".to_string(),
            description: None,
            virtual_files: vec![],
            upload_rules: vec![rule],
        };

        let new_registry = FtpSpecRegistry::new()
            .with_vfs(server.vfs.clone())
            .with_fixtures(vec![fixture])
            .unwrap();

        let server = FtpServer {
            config: server.config,
            vfs: server.vfs.clone(),
            spec_registry: Arc::new(new_registry),
        };

        let path = std::path::Path::new("/uploads/test.txt");
        let data = b"test file content".to_vec();

        let result = server.handle_upload(path, data).await;
        assert!(result.is_ok());

        // With discard storage, file should not be in VFS
        let file = server.vfs.get_file_async(path).await;
        assert!(file.is_none());
    }

    #[tokio::test]
    async fn test_handle_upload_validation_failure() {
        let config = FtpConfig {
            host: "127.0.0.1".to_string(),
            port: 2121,
            virtual_root: std::path::PathBuf::from("/"),
            ..Default::default()
        };

        let server = FtpServer::new(config);

        let rule = UploadRule {
            path_pattern: r"^/uploads/.*".to_string(),
            auto_accept: true,
            validation: Some(FileValidation {
                max_size_bytes: Some(10),
                allowed_extensions: None,
                mime_types: None,
            }),
            storage: UploadStorage::Memory,
        };

        let fixture = crate::fixtures::FtpFixture {
            identifier: "test".to_string(),
            name: "Test".to_string(),
            description: None,
            virtual_files: vec![],
            upload_rules: vec![rule],
        };

        let new_registry = FtpSpecRegistry::new()
            .with_vfs(server.vfs.clone())
            .with_fixtures(vec![fixture])
            .unwrap();

        let server = FtpServer {
            config: server.config,
            vfs: server.vfs.clone(),
            spec_registry: Arc::new(new_registry),
        };

        let path = std::path::Path::new("/uploads/test.txt");
        let data = b"this is a very large file that exceeds the limit".to_vec();

        let result = server.handle_upload(path, data).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_handle_upload_no_matching_rule() {
        let config = FtpConfig {
            host: "127.0.0.1".to_string(),
            port: 2121,
            virtual_root: std::path::PathBuf::from("/"),
            ..Default::default()
        };

        let server = FtpServer::new(config);

        let path = std::path::Path::new("/no-rule/test.txt");
        let data = b"test content".to_vec();

        let result = server.handle_upload(path, data).await;
        // Should succeed but do nothing since no rule matches
        assert!(result.is_ok());
    }

    #[test]
    fn test_new_with_fixtures_loads_virtual_files() {
        let config = FtpConfig {
            host: "127.0.0.1".to_string(),
            port: 2121,
            virtual_root: std::path::PathBuf::from("/"),
            ..Default::default()
        };

        let fixture = crate::fixtures::FtpFixture {
            identifier: "programmatic".to_string(),
            name: "Programmatic Fixture".to_string(),
            description: Some("Created in code".to_string()),
            virtual_files: vec![crate::fixtures::VirtualFileConfig {
                path: std::path::PathBuf::from("/pub/hello.txt"),
                content: crate::fixtures::FileContentConfig::Static {
                    content: "hello world".to_string(),
                },
                permissions: "644".to_string(),
                owner: "mockforge".to_string(),
                group: "mockforge".to_string(),
            }],
            upload_rules: vec![],
        };

        let server = FtpServer::new_with_fixtures(config, vec![fixture]).unwrap();

        // The fixture's identifier is registered and its virtual file was
        // loaded into the server's VFS.
        assert_eq!(server.spec_registry().fixtures.len(), 1);
        assert_eq!(server.spec_registry().fixtures[0].identifier, "programmatic");

        let file = server.vfs().get_file(std::path::Path::new("/pub/hello.txt"));
        assert!(file.is_some(), "virtual file from fixture should be in VFS");
    }

    #[tokio::test]
    async fn test_readme_yaml_fixture_loads_into_server_inside_async_runtime() {
        let readme = include_str!("../README.md");
        let yaml = readme.split("```yaml\n").nth(1).unwrap().split("```").next().unwrap();
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("ftp-fixture.yaml");
        std::fs::write(&path, yaml).unwrap();
        let fixture = crate::FtpFixture::from_yaml_file(&path).unwrap();
        let server = FtpServer::new_with_fixtures(FtpConfig::default(), vec![fixture]).unwrap();
        assert_eq!(server.spec_registry().fixtures.len(), 1);
        let file = server
            .vfs()
            .get_file_async(std::path::Path::new("/welcome.txt"))
            .await
            .expect("documented fixture should populate the actual server VFS");
        assert!(
            matches!(file.content, crate::FileContent::Static(bytes) if bytes == b"Welcome to MockForge FTP!")
        );
        assert!(server.vfs().get_file_async(std::path::Path::new("/data.bin")).await.is_some());
    }

    #[test]
    fn test_fixture_file_reports_missing_and_invalid_yaml() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("fixture.yaml");
        let error = crate::FtpFixture::from_yaml_file(&path).unwrap_err();
        assert!(error.to_string().contains("Failed to open FTP fixture"));
        std::fs::write(&path, "virtual_files: [").unwrap();
        let error = crate::FtpFixture::from_yaml_file(&path).unwrap_err();
        assert!(error.to_string().contains("Failed to parse FTP fixture"));
    }
}