nora-registry 0.2.35

Cloud-Native Artifact Registry - Fast, lightweight, multi-protocol
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
// Copyright (c) 2026 Volkov Pavel | DevITWay
// SPDX-License-Identifier: MIT

use async_trait::async_trait;
use axum::body::Bytes;
use chrono::Utc;
use hmac::{Hmac, Mac};
use sha2::{Digest, Sha256};

use super::{FileMeta, Result, StorageBackend, StorageError};

type HmacSha256 = Hmac<Sha256>;

/// S3-compatible storage backend (MinIO, AWS S3)
pub struct S3Storage {
    s3_url: String,
    bucket: String,
    region: String,
    access_key: Option<String>,
    secret_key: Option<String>,
    client: reqwest::Client,
}

impl S3Storage {
    /// Create new S3 storage with optional credentials
    pub fn new(
        s3_url: &str,
        bucket: &str,
        region: &str,
        access_key: Option<&str>,
        secret_key: Option<&str>,
    ) -> Self {
        Self {
            s3_url: s3_url.trim_end_matches('/').to_string(),
            bucket: bucket.to_string(),
            region: region.to_string(),
            access_key: access_key.map(String::from),
            secret_key: secret_key.map(String::from),
            client: reqwest::Client::new(),
        }
    }

    /// Sign a request using AWS Signature v4
    fn sign_request(
        &self,
        method: &str,
        path: &str,
        payload_hash: &str,
        timestamp: &str,
        date: &str,
    ) -> Option<String> {
        let (access_key, secret_key) = match (&self.access_key, &self.secret_key) {
            (Some(ak), Some(sk)) => (ak.as_str(), sk.as_str()),
            _ => return None,
        };

        // Parse host from URL
        let host = self
            .s3_url
            .trim_start_matches("http://")
            .trim_start_matches("https://");

        // Canonical request
        // URI must be URL-encoded (except /)
        let encoded_path = uri_encode(path);
        let canonical_uri = format!("/{}/{}", self.bucket, encoded_path);
        let canonical_query = "";
        let canonical_headers = format!(
            "host:{}\nx-amz-content-sha256:{}\nx-amz-date:{}\n",
            host, payload_hash, timestamp
        );
        let signed_headers = "host;x-amz-content-sha256;x-amz-date";

        // AWS Signature v4 canonical request format:
        // HTTPMethod\nCanonicalURI\nCanonicalQueryString\nCanonicalHeaders\n\nSignedHeaders\nHashedPayload
        // Note: CanonicalHeaders already ends with \n, plus blank line before SignedHeaders
        let canonical_request = format!(
            "{}\n{}\n{}\n{}\n{}\n{}",
            method, canonical_uri, canonical_query, canonical_headers, signed_headers, payload_hash
        );

        let canonical_request_hash = hex::encode(Sha256::digest(canonical_request.as_bytes()));

        // String to sign
        let credential_scope = format!("{}/{}/s3/aws4_request", date, self.region);
        let string_to_sign = format!(
            "AWS4-HMAC-SHA256\n{}\n{}\n{}",
            timestamp, credential_scope, canonical_request_hash
        );

        // Calculate signature
        let k_date = hmac_sha256(format!("AWS4{}", secret_key).as_bytes(), date.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");
        let signature = hex::encode(hmac_sha256(&k_signing, string_to_sign.as_bytes()));

        // Authorization header
        Some(format!(
            "AWS4-HMAC-SHA256 Credential={}/{}, SignedHeaders={}, Signature={}",
            access_key, credential_scope, signed_headers, signature
        ))
    }

    /// Make a signed request
    async fn signed_request(
        &self,
        method: reqwest::Method,
        key: &str,
        body: Option<&[u8]>,
    ) -> std::result::Result<reqwest::Response, StorageError> {
        let url = format!("{}/{}/{}", self.s3_url, self.bucket, key);
        let now = Utc::now();
        let timestamp = now.format("%Y%m%dT%H%M%SZ").to_string();
        let date = now.format("%Y%m%d").to_string();

        let payload_hash = match body {
            Some(data) => hex::encode(Sha256::digest(data)),
            None => hex::encode(Sha256::digest(b"")),
        };

        let mut request = self
            .client
            .request(method.clone(), &url)
            .header("x-amz-date", &timestamp)
            .header("x-amz-content-sha256", &payload_hash);

        if let Some(auth) =
            self.sign_request(method.as_str(), key, &payload_hash, &timestamp, &date)
        {
            request = request.header("Authorization", auth);
        }

        if let Some(data) = body {
            request = request.body(data.to_vec());
        }

        request
            .send()
            .await
            .map_err(|e| StorageError::Network(e.to_string()))
    }

    fn parse_s3_keys(xml: &str, prefix: &str) -> Vec<String> {
        xml.split("<Key>")
            .filter_map(|part| part.split("</Key>").next())
            .filter(|key| key.starts_with(prefix))
            .map(String::from)
            .collect()
    }
}

/// URL-encode a string for S3 canonical URI (encode all except A-Za-z0-9-_.~/)
fn uri_encode(s: &str) -> String {
    let mut result = String::with_capacity(s.len() * 3);
    for c in s.chars() {
        match c {
            'A'..='Z' | 'a'..='z' | '0'..='9' | '-' | '_' | '.' | '~' | '/' => result.push(c),
            _ => {
                for b in c.to_string().as_bytes() {
                    result.push_str(&format!("%{:02X}", b));
                }
            }
        }
    }
    result
}

fn hmac_sha256(key: &[u8], data: &[u8]) -> Vec<u8> {
    let mut mac = HmacSha256::new_from_slice(key).expect("HMAC can take key of any size");
    mac.update(data);
    mac.finalize().into_bytes().to_vec()
}

#[async_trait]
impl StorageBackend for S3Storage {
    async fn put(&self, key: &str, data: &[u8]) -> Result<()> {
        let response = self
            .signed_request(reqwest::Method::PUT, key, Some(data))
            .await?;

        if response.status().is_success() {
            Ok(())
        } else {
            Err(StorageError::Network(format!(
                "PUT failed: {}",
                response.status()
            )))
        }
    }

    async fn get(&self, key: &str) -> Result<Bytes> {
        let response = self.signed_request(reqwest::Method::GET, key, None).await?;

        if response.status().is_success() {
            response
                .bytes()
                .await
                .map_err(|e| StorageError::Network(e.to_string()))
        } else if response.status().as_u16() == 404 {
            Err(StorageError::NotFound)
        } else {
            Err(StorageError::Network(format!(
                "GET failed: {}",
                response.status()
            )))
        }
    }

    async fn delete(&self, key: &str) -> Result<()> {
        let response = self
            .signed_request(reqwest::Method::DELETE, key, None)
            .await?;

        if response.status().is_success() || response.status().as_u16() == 204 {
            Ok(())
        } else if response.status().as_u16() == 404 {
            Err(StorageError::NotFound)
        } else {
            Err(StorageError::Network(format!(
                "DELETE failed: {}",
                response.status()
            )))
        }
    }

    async fn list(&self, prefix: &str) -> Vec<String> {
        // For listing, we need to make a request to the bucket
        let url = format!("{}/{}", self.s3_url, self.bucket);
        let now = Utc::now();
        let timestamp = now.format("%Y%m%dT%H%M%SZ").to_string();
        let date = now.format("%Y%m%d").to_string();
        let payload_hash = hex::encode(Sha256::digest(b""));

        let host = self
            .s3_url
            .trim_start_matches("http://")
            .trim_start_matches("https://");

        let mut request = self
            .client
            .get(&url)
            .header("x-amz-date", &timestamp)
            .header("x-amz-content-sha256", &payload_hash);

        // Sign for bucket listing (different path)
        if let (Some(access_key), Some(secret_key)) = (&self.access_key, &self.secret_key) {
            let canonical_uri = format!("/{}", self.bucket);
            let canonical_headers = format!(
                "host:{}\nx-amz-content-sha256:{}\nx-amz-date:{}\n",
                host, payload_hash, timestamp
            );
            let signed_headers = "host;x-amz-content-sha256;x-amz-date";

            let canonical_request = format!(
                "GET\n{}\n\n{}\n{}\n{}",
                canonical_uri, canonical_headers, signed_headers, payload_hash
            );

            let canonical_request_hash = hex::encode(Sha256::digest(canonical_request.as_bytes()));
            let credential_scope = format!("{}/{}/s3/aws4_request", date, self.region);
            let string_to_sign = format!(
                "AWS4-HMAC-SHA256\n{}\n{}\n{}",
                timestamp, credential_scope, canonical_request_hash
            );

            let k_date = hmac_sha256(format!("AWS4{}", secret_key).as_bytes(), date.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");
            let signature = hex::encode(hmac_sha256(&k_signing, string_to_sign.as_bytes()));

            let auth = format!(
                "AWS4-HMAC-SHA256 Credential={}/{}, SignedHeaders={}, Signature={}",
                access_key, credential_scope, signed_headers, signature
            );
            request = request.header("Authorization", auth);
        }

        match request.send().await {
            Ok(response) if response.status().is_success() => {
                if let Ok(xml) = response.text().await {
                    Self::parse_s3_keys(&xml, prefix)
                } else {
                    Vec::new()
                }
            }
            _ => Vec::new(),
        }
    }

    async fn stat(&self, key: &str) -> Option<FileMeta> {
        let response = self
            .signed_request(reqwest::Method::HEAD, key, None)
            .await
            .ok()?;

        if !response.status().is_success() {
            return None;
        }

        let size = response
            .headers()
            .get("content-length")
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.parse().ok())
            .unwrap_or(0);

        let modified = response
            .headers()
            .get("last-modified")
            .and_then(|v| v.to_str().ok())
            .and_then(|v| httpdate::parse_http_date(v).ok())
            .map(|t| {
                t.duration_since(std::time::UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_secs()
            })
            .unwrap_or(0);

        Some(FileMeta { size, modified })
    }

    async fn health_check(&self) -> bool {
        // Try HEAD on the bucket
        let url = format!("{}/{}", self.s3_url, self.bucket);
        let now = Utc::now();
        let timestamp = now.format("%Y%m%dT%H%M%SZ").to_string();
        let date = now.format("%Y%m%d").to_string();
        let payload_hash = hex::encode(Sha256::digest(b""));

        let host = self
            .s3_url
            .trim_start_matches("http://")
            .trim_start_matches("https://");

        let mut request = self
            .client
            .head(&url)
            .header("x-amz-date", &timestamp)
            .header("x-amz-content-sha256", &payload_hash);

        if let (Some(access_key), Some(secret_key)) = (&self.access_key, &self.secret_key) {
            let canonical_uri = format!("/{}", self.bucket);
            let canonical_headers = format!(
                "host:{}\nx-amz-content-sha256:{}\nx-amz-date:{}\n",
                host, payload_hash, timestamp
            );
            let signed_headers = "host;x-amz-content-sha256;x-amz-date";

            let canonical_request = format!(
                "HEAD\n{}\n\n{}\n{}\n{}",
                canonical_uri, canonical_headers, signed_headers, payload_hash
            );

            let canonical_request_hash = hex::encode(Sha256::digest(canonical_request.as_bytes()));
            let credential_scope = format!("{}/{}/s3/aws4_request", date, self.region);
            let string_to_sign = format!(
                "AWS4-HMAC-SHA256\n{}\n{}\n{}",
                timestamp, credential_scope, canonical_request_hash
            );

            let k_date = hmac_sha256(format!("AWS4{}", secret_key).as_bytes(), date.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");
            let signature = hex::encode(hmac_sha256(&k_signing, string_to_sign.as_bytes()));

            let auth = format!(
                "AWS4-HMAC-SHA256 Credential={}/{}, SignedHeaders={}, Signature={}",
                access_key, credential_scope, signed_headers, signature
            );
            request = request.header("Authorization", auth);
        }

        match request.send().await {
            Ok(response) => response.status().is_success() || response.status().as_u16() == 404,
            Err(_) => false,
        }
    }

    fn backend_name(&self) -> &'static str {
        "s3"
    }
}

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

    #[test]
    fn test_backend_name() {
        let storage = S3Storage::new(
            "http://localhost:9000",
            "test-bucket",
            "us-east-1",
            Some("access"),
            Some("secret"),
        );
        assert_eq!(storage.backend_name(), "s3");
    }

    #[test]
    fn test_s3_storage_creation_anonymous() {
        let storage = S3Storage::new(
            "http://localhost:9000",
            "test-bucket",
            "us-east-1",
            None,
            None,
        );
        assert_eq!(storage.backend_name(), "s3");
    }

    #[test]
    fn test_parse_s3_keys() {
        let xml = r#"<Key>docker/a</Key><Key>docker/b</Key><Key>maven/c</Key>"#;
        let keys = S3Storage::parse_s3_keys(xml, "docker/");
        assert_eq!(keys, vec!["docker/a", "docker/b"]);
    }

    #[test]
    fn test_hmac_sha256() {
        let result = hmac_sha256(b"key", b"data");
        assert!(!result.is_empty());
    }
}