fraiseql-storage 2.3.2

Object storage backends and HTTP handlers for FraiseQL
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
//! Tests for `S3Backend`.
//!
//! Note: These tests require a running S3-compatible service (S3, `MinIO`, etc.).
//! To run with `MinIO` locally:
//!
//! ```bash
//! docker run -d -p 9000:9000 -p 9001:9001 minio/minio server /data
//! export AWS_ACCESS_KEY_ID=minioadmin
//! export AWS_SECRET_ACCESS_KEY=minioadmin
//! cargo test -p fraiseql-storage --lib --features aws-s3 s3::tests
//! ```

#![allow(clippy::unwrap_used)] // Reason: test code, panics acceptable
#![allow(missing_docs)] // Reason: test functions are self-describing
#![allow(clippy::indexing_slicing)] // Reason: test fixtures index into known-shape collections; OOB indices correctly fail the test

use crate::backend::S3Backend;

/// Helper to skip tests if S3 service is not configured.
fn skip_if_no_s3() -> Option<()> {
    if std::env::var("S3_ENDPOINT").is_err() && std::env::var("AWS_ENDPOINT_URL").is_err() {
        return None;
    }
    Some(())
}

/// Helper to create an `S3Backend` for testing.
fn create_test_backend() -> S3Backend {
    let endpoint = std::env::var("S3_ENDPOINT").or_else(|_| std::env::var("AWS_ENDPOINT_URL")).ok();

    // Use a unique bucket name for tests to avoid conflicts
    let bucket = format!("test-{}", uuid::Uuid::new_v4());

    let rt = tokio::runtime::Runtime::new().expect("create tokio runtime");
    rt.block_on(async { S3Backend::new(&bucket, None, endpoint.as_deref()).await })
}

#[test]
fn test_s3_backend_struct_creation() {
    // This test just verifies that the S3Backend struct can be created
    // It doesn't require external services
    let _backend = create_test_backend();
    // If we get here, the test passed (no panic)
}

#[test]
#[ignore = "requires MinIO to be running"]
fn test_s3_put_and_get_roundtrip() {
    let Some(()) = skip_if_no_s3() else {
        return;
    };

    let backend = create_test_backend();
    let rt = tokio::runtime::Runtime::new().unwrap();

    rt.block_on(async {
        let key = "test-file.txt";
        let data = b"Hello, S3 world!";
        let content_type = "text/plain";

        // Upload test data
        let result = backend.upload(key, data, content_type).await;
        assert!(result.is_ok(), "upload should succeed");
        assert_eq!(result.unwrap(), key);

        // Download and verify
        let downloaded = backend.download(key).await;
        assert!(downloaded.is_ok(), "download should succeed");
        assert_eq!(downloaded.unwrap(), data);
    });
}

#[test]
#[ignore = "requires MinIO to be running"]
fn test_s3_get_nonexistent_returns_not_found() {
    let Some(()) = skip_if_no_s3() else {
        return;
    };

    let backend = create_test_backend();
    let rt = tokio::runtime::Runtime::new().unwrap();

    rt.block_on(async {
        let result = backend.download("nonexistent-key.txt").await;
        assert!(result.is_err(), "download of nonexistent key should fail");

        let err = result.unwrap_err();
        let err_msg = err.to_string();
        assert!(
            err_msg.contains("not found") || err_msg.contains("404"),
            "error should indicate not found: {}",
            err_msg
        );
    });
}

#[test]
#[ignore = "requires MinIO to be running"]
fn test_s3_delete_removes_object() {
    let Some(()) = skip_if_no_s3() else {
        return;
    };

    let backend = create_test_backend();
    let rt = tokio::runtime::Runtime::new().unwrap();

    rt.block_on(async {
        let key = "to-delete.txt";
        let data = b"temporary file";

        // Upload
        backend.upload(key, data, "text/plain").await.expect("upload succeeds");

        // Verify exists
        let exists = backend.exists(key).await.expect("exists check succeeds");
        assert!(exists, "file should exist after upload");

        // Delete
        let delete_result = backend.delete(key).await;
        assert!(delete_result.is_ok(), "delete should succeed");

        // Verify deleted
        let exists_after = backend.exists(key).await.expect("exists check succeeds");
        assert!(!exists_after, "file should not exist after delete");
    });
}

#[test]
#[ignore = "requires MinIO to be running"]
fn test_s3_list_with_prefix() {
    let Some(()) = skip_if_no_s3() else {
        return;
    };

    let backend = create_test_backend();
    let rt = tokio::runtime::Runtime::new().unwrap();

    rt.block_on(async {
        // Upload files with different prefixes
        backend
            .upload("avatars/user1.jpg", b"avatar 1", "image/jpeg")
            .await
            .expect("upload 1");
        backend
            .upload("avatars/user2.jpg", b"avatar 2", "image/jpeg")
            .await
            .expect("upload 2");
        backend
            .upload("documents/doc.pdf", b"pdf content", "application/pdf")
            .await
            .expect("upload 3");

        // List with "avatars/" prefix
        let result = backend.list("avatars/", None, 100).await.expect("list succeeds");

        assert_eq!(result.objects.len(), 2, "should have 2 items under avatars/");
        assert!(
            result.objects.iter().any(|o| o.key == "avatars/user1.jpg"),
            "should include avatars/user1.jpg"
        );
        assert!(
            result.objects.iter().any(|o| o.key == "avatars/user2.jpg"),
            "should include avatars/user2.jpg"
        );
    });
}

#[test]
#[ignore = "requires MinIO to be running"]
fn test_s3_list_pagination() {
    let Some(()) = skip_if_no_s3() else {
        return;
    };

    let backend = create_test_backend();
    let rt = tokio::runtime::Runtime::new().unwrap();

    rt.block_on(async {
        // Upload 5 objects
        for i in 0..5 {
            let key = format!("file{:02}.txt", i);
            backend
                .upload(&key, format!("data {}", i).as_bytes(), "text/plain")
                .await
                .expect("upload succeeds");
        }

        // First page with limit=2
        let page1 = backend.list("", None, 2).await.expect("list page 1 succeeds");
        assert_eq!(page1.objects.len(), 2, "first page should have 2 items");

        let cursor1 = page1.next_cursor.expect("first page should have cursor");

        // Second page using cursor
        let page2 = backend.list("", Some(&cursor1), 2).await.expect("list page 2 succeeds");
        assert_eq!(page2.objects.len(), 2, "second page should have 2 items");

        // Verify pages don't overlap
        assert_ne!(
            page1.objects[0].key, page2.objects[0].key,
            "pages should have different objects"
        );

        // Third page (remaining items)
        let cursor2 = page2.next_cursor.expect("second page should have cursor");
        let page3 = backend.list("", Some(&cursor2), 2).await.expect("list page 3 succeeds");
        assert_eq!(page3.objects.len(), 1, "third page should have 1 item");
        assert!(page3.next_cursor.is_none(), "last page should have no cursor");
    });
}

#[test]
#[ignore = "requires MinIO to be running"]
fn test_s3_exists_true_and_false() {
    let Some(()) = skip_if_no_s3() else {
        return;
    };

    let backend = create_test_backend();
    let rt = tokio::runtime::Runtime::new().unwrap();

    rt.block_on(async {
        let key = "existence-test.txt";

        // Before upload, should not exist
        let exists_before = backend.exists(key).await.expect("exists check succeeds");
        assert!(!exists_before, "should not exist before upload");

        // Upload
        backend.upload(key, b"test", "text/plain").await.expect("upload succeeds");

        // After upload, should exist
        let exists_after = backend.exists(key).await.expect("exists check succeeds");
        assert!(exists_after, "should exist after upload");

        // Non-existent key should return false, not error
        let not_exist = backend
            .exists("definitely-does-not-exist.txt")
            .await
            .expect("exists check on non-existent key should not error");
        assert!(!not_exist, "non-existent key should return false");
    });
}

#[test]
#[ignore = "requires MinIO to be running"]
fn test_s3_large_object_streaming() {
    let Some(()) = skip_if_no_s3() else {
        return;
    };

    let backend = create_test_backend();
    let rt = tokio::runtime::Runtime::new().unwrap();

    rt.block_on(async {
        // Create 10MB of data to test streaming
        let large_data = vec![42u8; 10 * 1024 * 1024];
        let key = "large-file.bin";

        // Upload large object
        let upload_result = backend.upload(key, &large_data, "application/octet-stream").await;
        assert!(upload_result.is_ok(), "large upload should succeed");

        // Download and verify size
        let downloaded = backend.download(key).await.expect("large download should succeed");
        assert_eq!(
            downloaded.len(),
            large_data.len(),
            "downloaded size should match uploaded size"
        );
        assert_eq!(downloaded, large_data, "downloaded content should match uploaded content");
    });
}

#[test]
fn test_s3_key_validation() {
    let backend = create_test_backend();
    let rt = tokio::runtime::Runtime::new().unwrap();

    rt.block_on(async {
        // Test empty key
        let result = backend.upload("", b"data", "text/plain").await;
        assert!(result.is_err(), "empty key should be rejected");

        // Test path traversal
        let result = backend.upload("../etc/passwd", b"data", "text/plain").await;
        assert!(result.is_err(), "path traversal should be rejected");

        // Test absolute path
        let result = backend.upload("/etc/passwd", b"data", "text/plain").await;
        assert!(result.is_err(), "absolute path should be rejected");
    });
}

// ============================================================================
// PRESIGNED URL TESTS (Phase 2, Cycle 2)
// ============================================================================

#[test]
#[ignore = "requires MinIO to be running"]
fn test_s3_presign_upload_returns_valid_url() {
    let Some(()) = skip_if_no_s3() else {
        return;
    };

    let backend = create_test_backend();
    let rt = tokio::runtime::Runtime::new().unwrap();

    rt.block_on(async {
        let key = "presign-upload-test.txt";

        // Generate presigned URL for upload (1 hour expiry)
        let presigned_result =
            backend.presigned_url(key, std::time::Duration::from_secs(3600)).await;

        assert!(presigned_result.is_ok(), "presigned URL generation should succeed");

        let url = presigned_result.unwrap();
        assert!(
            url.starts_with("http://") || url.starts_with("https://"),
            "presigned URL should be a valid HTTP URL"
        );
        assert!(
            url.contains(key) || url.contains("presign-upload-test"),
            "presigned URL should contain the key"
        );
    });
}

#[test]
#[ignore = "requires MinIO to be running"]
fn test_s3_presign_download_returns_valid_url() {
    let Some(()) = skip_if_no_s3() else {
        return;
    };

    let backend = create_test_backend();
    let rt = tokio::runtime::Runtime::new().unwrap();

    rt.block_on(async {
        let key = "presign-download-test.txt";
        let data = b"presigned download content";

        // Upload file first
        backend.upload(key, data, "text/plain").await.expect("upload succeeds");

        // Generate presigned URL for download
        let presigned_result =
            backend.presigned_url(key, std::time::Duration::from_secs(3600)).await;

        assert!(presigned_result.is_ok(), "presigned URL generation should succeed");

        let url = presigned_result.unwrap();
        assert!(
            url.starts_with("http://") || url.starts_with("https://"),
            "presigned URL should be a valid HTTP URL"
        );
    });
}

#[test]
#[ignore = "requires MinIO to be running"]
fn test_s3_presign_url_expires() {
    let Some(()) = skip_if_no_s3() else {
        return;
    };

    let backend = create_test_backend();
    let rt = tokio::runtime::Runtime::new().unwrap();

    rt.block_on(async {
        let key = "presign-expire-test.txt";

        // Generate presigned URL with 1 second expiry
        let presigned_result = backend.presigned_url(key, std::time::Duration::from_secs(1)).await;

        assert!(presigned_result.is_ok(), "presigned URL generation should succeed");

        // URL should be valid immediately
        let url = presigned_result.unwrap();
        assert!(!url.is_empty(), "presigned URL should not be empty");

        // Sleep for 2 seconds - URL should expire
        tokio::time::sleep(std::time::Duration::from_secs(2)).await;

        // Note: We can't directly test URL expiry without actually using it,
        // but the URL structure should be correct with X-Amz-Expires parameter
        assert!(
            url.contains("X-Amz-Expires") || url.contains("expires"),
            "presigned URL should contain expiry information"
        );
    });
}

#[test]
fn test_s3_presign_rejects_invalid_keys() {
    let backend = create_test_backend();
    let rt = tokio::runtime::Runtime::new().unwrap();

    rt.block_on(async {
        // Test path traversal in presigned URL
        let result = backend
            .presigned_url("../etc/passwd", std::time::Duration::from_secs(3600))
            .await;
        assert!(result.is_err(), "path traversal should be rejected");

        // Test empty key
        let result = backend.presigned_url("", std::time::Duration::from_secs(3600)).await;
        assert!(result.is_err(), "empty key should be rejected");
    });
}

#[test]
#[ignore = "requires MinIO to be running"]
fn test_s3_presign_respects_expiry() {
    let Some(()) = skip_if_no_s3() else {
        return;
    };

    let backend = create_test_backend();
    let rt = tokio::runtime::Runtime::new().unwrap();

    rt.block_on(async {
        let key = "presign-ttl-test.txt";

        // Generate URLs with different expiry times
        let short_ttl = std::time::Duration::from_secs(60);
        let long_ttl = std::time::Duration::from_secs(3600);

        let short_url = backend
            .presigned_url(key, short_ttl)
            .await
            .expect("short TTL presigned URL should succeed");

        let long_url = backend
            .presigned_url(key, long_ttl)
            .await
            .expect("long TTL presigned URL should succeed");

        // Both should be valid URLs
        assert!(!short_url.is_empty(), "short TTL URL should not be empty");
        assert!(!long_url.is_empty(), "long TTL URL should not be empty");

        // URLs should differ (different expiry times)
        assert_ne!(short_url, long_url, "URLs with different TTLs should be different");
    });
}