rs3gw 0.2.1

High-Performance AI/HPC Object Storage Gateway powered by scirs2-io
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
//! Presigned POST Policy Generation
//!
//! Implements S3-compatible presigned POST for browser-based uploads.
//! This allows creating HTML forms that can upload directly to S3.

use base64::Engine;
use chrono::{DateTime, Duration, Utc};
use hmac::KeyInit;
use hmac::{Hmac, Mac};
use serde::{Deserialize, Serialize};
use sha2::Sha256;

type HmacSha256 = Hmac<Sha256>;

const BASE64: base64::engine::general_purpose::GeneralPurpose =
    base64::engine::general_purpose::STANDARD;

/// Presigned POST policy
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PostPolicy {
    /// Expiration time (ISO 8601)
    pub expiration: String,
    /// Policy conditions
    pub conditions: Vec<PostCondition>,
}

/// A condition in the POST policy
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PostCondition {
    /// Exact match condition: {"bucket": "mybucket"}
    ExactMatch(serde_json::Map<String, serde_json::Value>),
    /// Starts-with condition: ["starts-with", "$key", "user/"]
    StartsWith(String, String, String),
    /// Content-length-range condition: ["content-length-range", min, max]
    ContentLengthRange(String, u64, u64),
    /// Equality condition as array: ["eq", "$key", "value"]
    Equality(String, String, String),
}

impl PostCondition {
    /// Create an exact match condition
    pub fn exact(field: &str, value: &str) -> Self {
        let mut map = serde_json::Map::new();
        map.insert(
            field.to_string(),
            serde_json::Value::String(value.to_string()),
        );
        PostCondition::ExactMatch(map)
    }

    /// Create a starts-with condition
    pub fn starts_with(field: &str, prefix: &str) -> Self {
        PostCondition::StartsWith(
            "starts-with".to_string(),
            format!("${}", field),
            prefix.to_string(),
        )
    }

    /// Create a content-length-range condition
    pub fn content_length_range(min: u64, max: u64) -> Self {
        PostCondition::ContentLengthRange("content-length-range".to_string(), min, max)
    }
}

/// Result of generating a presigned POST
#[derive(Debug, Clone, Serialize)]
pub struct PresignedPost {
    /// URL to POST to
    pub url: String,
    /// Form fields to include
    pub fields: PresignedPostFields,
}

/// Form fields for presigned POST
#[derive(Debug, Clone, Serialize)]
pub struct PresignedPostFields {
    /// The bucket name
    pub bucket: String,
    /// Object key (may include ${filename} placeholder)
    pub key: String,
    /// Base64-encoded policy
    pub policy: String,
    /// AWS access key ID
    #[serde(rename = "X-Amz-Algorithm")]
    pub algorithm: String,
    /// Credential string
    #[serde(rename = "X-Amz-Credential")]
    pub credential: String,
    /// Date in ISO 8601 format
    #[serde(rename = "X-Amz-Date")]
    pub date: String,
    /// Signature
    #[serde(rename = "X-Amz-Signature")]
    pub signature: String,
    /// Optional ACL
    #[serde(skip_serializing_if = "Option::is_none")]
    pub acl: Option<String>,
    /// Optional content type
    #[serde(rename = "Content-Type", skip_serializing_if = "Option::is_none")]
    pub content_type: Option<String>,
    /// Optional success redirect
    #[serde(skip_serializing_if = "Option::is_none")]
    pub success_action_redirect: Option<String>,
    /// Optional success status
    #[serde(skip_serializing_if = "Option::is_none")]
    pub success_action_status: Option<String>,
}

/// Builder for presigned POST
pub struct PresignedPostBuilder {
    access_key: String,
    secret_key: String,
    region: String,
    host: String,
    bucket: String,
    key: String,
    expiration: DateTime<Utc>,
    conditions: Vec<PostCondition>,
    acl: Option<String>,
    content_type: Option<String>,
    content_length_range: Option<(u64, u64)>,
    success_redirect: Option<String>,
    success_status: Option<String>,
}

impl PresignedPostBuilder {
    /// Create a new builder
    pub fn new(
        access_key: String,
        secret_key: String,
        region: String,
        host: String,
        bucket: String,
        key: String,
    ) -> Self {
        Self {
            access_key,
            secret_key,
            region,
            host,
            bucket,
            key,
            expiration: Utc::now() + Duration::hours(1),
            conditions: Vec::new(),
            acl: None,
            content_type: None,
            content_length_range: None,
            success_redirect: None,
            success_status: None,
        }
    }

    /// Set expiration time
    pub fn expires_in(mut self, duration: Duration) -> Self {
        self.expiration = Utc::now() + duration;
        self
    }

    /// Set expiration as DateTime
    pub fn expires_at(mut self, expiration: DateTime<Utc>) -> Self {
        self.expiration = expiration;
        self
    }

    /// Add a custom condition
    pub fn condition(mut self, condition: PostCondition) -> Self {
        self.conditions.push(condition);
        self
    }

    /// Set ACL
    pub fn acl(mut self, acl: &str) -> Self {
        self.acl = Some(acl.to_string());
        self
    }

    /// Set content type
    pub fn content_type(mut self, content_type: &str) -> Self {
        self.content_type = Some(content_type.to_string());
        self
    }

    /// Set content length range
    pub fn content_length_range(mut self, min: u64, max: u64) -> Self {
        self.content_length_range = Some((min, max));
        self
    }

    /// Set success redirect URL
    pub fn success_redirect(mut self, url: &str) -> Self {
        self.success_redirect = Some(url.to_string());
        self
    }

    /// Set success status code
    pub fn success_status(mut self, status: u16) -> Self {
        self.success_status = Some(status.to_string());
        self
    }

    /// Build the presigned POST
    pub fn build(self) -> PresignedPost {
        let now = Utc::now();
        let date_stamp = now.format("%Y%m%d").to_string();
        let amz_date = now.format("%Y%m%dT%H%M%SZ").to_string();
        let credential = format!(
            "{}/{}/{}/s3/aws4_request",
            self.access_key, date_stamp, self.region
        );

        // Build conditions
        let mut conditions: Vec<serde_json::Value> = Vec::new();

        // Required bucket condition
        conditions.push(serde_json::json!({"bucket": self.bucket}));

        // Key condition - use starts-with if key contains ${filename}
        if self.key.contains("${filename}") {
            let prefix = self.key.replace("${filename}", "");
            conditions.push(serde_json::json!(["starts-with", "$key", prefix]));
        } else {
            conditions.push(serde_json::json!({"key": self.key}));
        }

        // Required AWS fields
        conditions.push(serde_json::json!({"X-Amz-Algorithm": "AWS4-HMAC-SHA256"}));
        conditions.push(serde_json::json!({"X-Amz-Credential": credential}));
        conditions.push(serde_json::json!({"X-Amz-Date": amz_date}));

        // Optional ACL
        if let Some(ref acl) = self.acl {
            conditions.push(serde_json::json!({"acl": acl}));
        }

        // Optional content type
        if let Some(ref ct) = self.content_type {
            conditions.push(serde_json::json!({"Content-Type": ct}));
        }

        // Optional content length range
        if let Some((min, max)) = self.content_length_range {
            conditions.push(serde_json::json!(["content-length-range", min, max]));
        }

        // Optional success redirect
        if let Some(ref redirect) = self.success_redirect {
            conditions.push(serde_json::json!({"success_action_redirect": redirect}));
        }

        // Optional success status
        if let Some(ref status) = self.success_status {
            conditions.push(serde_json::json!({"success_action_status": status}));
        }

        // Add custom conditions
        for condition in &self.conditions {
            match condition {
                PostCondition::ExactMatch(map) => {
                    conditions.push(serde_json::Value::Object(map.clone()));
                }
                PostCondition::StartsWith(op, field, prefix) => {
                    conditions.push(serde_json::json!([op, field, prefix]));
                }
                PostCondition::ContentLengthRange(op, min, max) => {
                    conditions.push(serde_json::json!([op, min, max]));
                }
                PostCondition::Equality(op, field, value) => {
                    conditions.push(serde_json::json!([op, field, value]));
                }
            }
        }

        // Create policy
        let policy = serde_json::json!({
            "expiration": self.expiration.format("%Y-%m-%dT%H:%M:%SZ").to_string(),
            "conditions": conditions
        });

        let policy_json = serde_json::to_string(&policy).unwrap_or_default();
        let policy_base64 = BASE64.encode(policy_json.as_bytes());

        // Calculate signature
        let signature = self.calculate_signature(&policy_base64, &date_stamp);

        // Build URL
        let url = format!("http://{}/{}", self.host, self.bucket);

        PresignedPost {
            url,
            fields: PresignedPostFields {
                bucket: self.bucket,
                key: self.key,
                policy: policy_base64,
                algorithm: "AWS4-HMAC-SHA256".to_string(),
                credential,
                date: amz_date,
                signature,
                acl: self.acl,
                content_type: self.content_type,
                success_action_redirect: self.success_redirect,
                success_action_status: self.success_status,
            },
        }
    }

    /// Calculate the signature for the policy
    fn calculate_signature(&self, policy_base64: &str, date_stamp: &str) -> String {
        // Step 1: Create signing key
        let k_secret = format!("AWS4{}", self.secret_key);
        let k_date = hmac_sha256(k_secret.as_bytes(), date_stamp.as_bytes());
        let k_region = hmac_sha256(&k_date, self.region.as_bytes());
        let k_service = hmac_sha256(&k_region, b"s3");
        let k_signing = hmac_sha256(&k_service, b"aws4_request");

        // Step 2: Sign the policy
        let signature = hmac_sha256(&k_signing, policy_base64.as_bytes());

        // Step 3: Encode as hex
        hex::encode(signature)
    }
}

/// Calculate HMAC-SHA256
fn hmac_sha256(key: &[u8], data: &[u8]) -> Vec<u8> {
    // HMAC-SHA256 accepts any key size; this should never fail
    let mut mac = match HmacSha256::new_from_slice(key) {
        Ok(m) => m,
        Err(e) => {
            tracing::error!("HMAC initialization failed: {}", e);
            // Return empty vector to cause auth failure rather than panic
            return vec![];
        }
    };
    mac.update(data);
    mac.finalize().into_bytes().to_vec()
}

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

    #[test]
    fn test_presigned_post_builder() {
        let post = PresignedPostBuilder::new(
            "AKIAIOSFODNN7EXAMPLE".to_string(),
            "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY".to_string(),
            "us-east-1".to_string(),
            "localhost:9000".to_string(),
            "mybucket".to_string(),
            "uploads/${filename}".to_string(),
        )
        .expires_in(Duration::hours(1))
        .acl("public-read")
        .content_length_range(0, 10 * 1024 * 1024)
        .build();

        assert_eq!(post.fields.bucket, "mybucket");
        assert_eq!(post.fields.algorithm, "AWS4-HMAC-SHA256");
        assert!(!post.fields.policy.is_empty());
        assert!(!post.fields.signature.is_empty());
        assert!(post.url.contains("localhost:9000"));
    }

    #[test]
    fn test_presigned_post_with_fixed_key() {
        let post = PresignedPostBuilder::new(
            "testkey".to_string(),
            "testsecret".to_string(),
            "us-east-1".to_string(),
            "localhost:9000".to_string(),
            "testbucket".to_string(),
            "fixed-key.txt".to_string(),
        )
        .build();

        assert_eq!(post.fields.key, "fixed-key.txt");
        assert!(!post.fields.signature.is_empty());
    }

    #[test]
    fn test_post_condition_exact() {
        let condition = PostCondition::exact("bucket", "mybucket");
        match condition {
            PostCondition::ExactMatch(map) => {
                assert_eq!(
                    map.get("bucket"),
                    Some(&serde_json::Value::String("mybucket".to_string()))
                );
            }
            _ => panic!("Expected ExactMatch"),
        }
    }

    #[test]
    fn test_post_condition_starts_with() {
        let condition = PostCondition::starts_with("key", "user/");
        match condition {
            PostCondition::StartsWith(op, field, prefix) => {
                assert_eq!(op, "starts-with");
                assert_eq!(field, "$key");
                assert_eq!(prefix, "user/");
            }
            _ => panic!("Expected StartsWith"),
        }
    }

    #[test]
    fn test_presigned_post_policy_json() {
        let post = PresignedPostBuilder::new(
            "testkey".to_string(),
            "testsecret".to_string(),
            "us-east-1".to_string(),
            "localhost:9000".to_string(),
            "testbucket".to_string(),
            "test.txt".to_string(),
        )
        .content_type("text/plain")
        .success_status(201)
        .build();

        // Decode policy and verify it's valid JSON
        let policy_bytes = BASE64
            .decode(&post.fields.policy)
            .expect("Failed to decode base64 policy");
        let policy: serde_json::Value =
            serde_json::from_slice(&policy_bytes).expect("Failed to parse policy JSON");

        assert!(policy.get("expiration").is_some());
        assert!(policy.get("conditions").is_some());
    }
}