lcpfs 2026.1.102

LCP File System - A ZFS-inspired copy-on-write filesystem for Rust
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
// Copyright 2025 LunaOS Contributors
// SPDX-License-Identifier: Apache-2.0

//! AWS Signature Version 4 authentication.
//!
//! Implements the AWS SigV4 signing algorithm for authenticating S3 requests.
//! Reference: <https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html>

use alloc::collections::BTreeMap;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;

// Cryptographic imports - using audited RustCrypto crates
use base16ct::lower::encode_string as hex_encode_crate;
use hmac::{Hmac, Mac};
use sha2::{Digest, Sha256};
use subtle::ConstantTimeEq;

use super::http::url_encode;
use super::types::{S3Error, S3Request};

// ═══════════════════════════════════════════════════════════════════════════════
// AUTH RESULT
// ═══════════════════════════════════════════════════════════════════════════════

/// Authentication result.
#[derive(Debug, Clone)]
pub struct AuthResult {
    /// Access key from request.
    pub access_key: String,
    /// Region from credential scope.
    pub region: String,
    /// Service from credential scope.
    pub service: String,
    /// Date from credential scope.
    pub date: String,
    /// Is the signature valid?
    pub is_valid: bool,
}

// ═══════════════════════════════════════════════════════════════════════════════
// SIGV4 VERIFICATION
// ═══════════════════════════════════════════════════════════════════════════════

/// Verify AWS SigV4 signature.
pub fn verify_signature(
    request: &S3Request,
    access_key: &str,
    secret_key: &str,
) -> Result<AuthResult, S3Error> {
    // Get Authorization header
    let auth_header = request
        .header("authorization")
        .ok_or(S3Error::AccessDenied)?;

    // Parse the authorization header
    let parsed = parse_authorization_header(auth_header)?;

    // Verify access key matches
    if parsed.access_key != access_key {
        return Err(S3Error::InvalidAccessKeyId);
    }

    // Get required headers
    let x_amz_date = request
        .header("x-amz-date")
        .ok_or(S3Error::InvalidArgument("Missing x-amz-date header".into()))?;

    // Get payload hash
    let content_sha256 = request
        .header("x-amz-content-sha256")
        .map(|s| s.as_str())
        .unwrap_or("UNSIGNED-PAYLOAD");

    // Build canonical request
    let canonical_request = build_canonical_request(
        request.method.as_str(),
        &request_path(request),
        &request.query,
        &request.headers,
        &parsed.signed_headers,
        content_sha256,
    );

    // Build string to sign
    let string_to_sign =
        build_string_to_sign(x_amz_date, &parsed.credential_scope, &canonical_request);

    // Calculate expected signature
    let expected_signature = calculate_signature(
        secret_key,
        &parsed.date,
        &parsed.region,
        &parsed.service,
        &string_to_sign,
    );

    // Constant-time comparison
    let is_valid = constant_time_compare(&expected_signature, &parsed.signature);

    Ok(AuthResult {
        access_key: parsed.access_key,
        region: parsed.region,
        service: parsed.service,
        date: parsed.date,
        is_valid,
    })
}

/// Get the request path for signing.
fn request_path(request: &S3Request) -> String {
    let mut path = String::from("/");
    if let Some(ref bucket) = request.bucket {
        path.push_str(bucket);
        if let Some(ref key) = request.key {
            path.push('/');
            path.push_str(key);
        }
    }
    path
}

// ═══════════════════════════════════════════════════════════════════════════════
// AUTHORIZATION HEADER PARSING
// ═══════════════════════════════════════════════════════════════════════════════

/// Parsed authorization header.
struct ParsedAuthHeader {
    access_key: String,
    credential_scope: String,
    date: String,
    region: String,
    service: String,
    signed_headers: Vec<String>,
    signature: String,
}

/// Parse the Authorization header.
fn parse_authorization_header(header: &str) -> Result<ParsedAuthHeader, S3Error> {
    // Format: AWS4-HMAC-SHA256 Credential=..., SignedHeaders=..., Signature=...
    let header = header
        .strip_prefix("AWS4-HMAC-SHA256 ")
        .ok_or(S3Error::SignatureDoesNotMatch)?;

    let mut credential = None;
    let mut signed_headers = None;
    let mut signature = None;

    for part in header.split(", ") {
        if let Some(val) = part.strip_prefix("Credential=") {
            credential = Some(val.to_string());
        } else if let Some(val) = part.strip_prefix("SignedHeaders=") {
            signed_headers = Some(val.to_string());
        } else if let Some(val) = part.strip_prefix("Signature=") {
            signature = Some(val.to_string());
        }
    }

    let credential = credential.ok_or(S3Error::SignatureDoesNotMatch)?;
    let signed_headers_str = signed_headers.ok_or(S3Error::SignatureDoesNotMatch)?;
    let signature = signature.ok_or(S3Error::SignatureDoesNotMatch)?;

    // Parse credential: ACCESS_KEY/DATE/REGION/SERVICE/aws4_request
    let cred_parts: Vec<&str> = credential.split('/').collect();
    if cred_parts.len() != 5 {
        return Err(S3Error::SignatureDoesNotMatch);
    }

    let access_key = cred_parts[0].to_string();
    let date = cred_parts[1].to_string();
    let region = cred_parts[2].to_string();
    let service = cred_parts[3].to_string();
    let credential_scope = cred_parts[1..].join("/");

    let signed_headers: Vec<String> = signed_headers_str
        .split(';')
        .map(|s| s.to_string())
        .collect();

    Ok(ParsedAuthHeader {
        access_key,
        credential_scope,
        date,
        region,
        service,
        signed_headers,
        signature,
    })
}

// ═══════════════════════════════════════════════════════════════════════════════
// CANONICAL REQUEST
// ═══════════════════════════════════════════════════════════════════════════════

/// Build the canonical request string.
fn build_canonical_request(
    method: &str,
    path: &str,
    query: &BTreeMap<String, String>,
    headers: &BTreeMap<String, String>,
    signed_headers: &[String],
    payload_hash: &str,
) -> String {
    let mut result = String::new();

    // HTTP method
    result.push_str(method);
    result.push('\n');

    // Canonical URI (path)
    result.push_str(&canonical_uri(path));
    result.push('\n');

    // Canonical query string
    result.push_str(&canonical_query_string(query));
    result.push('\n');

    // Canonical headers
    result.push_str(&canonical_headers(headers, signed_headers));
    result.push('\n');

    // Signed headers
    result.push_str(&signed_headers.join(";"));
    result.push('\n');

    // Hashed payload
    result.push_str(payload_hash);

    result
}

/// Build canonical URI.
fn canonical_uri(path: &str) -> String {
    // URI-encode each path segment
    let segments: Vec<&str> = path.split('/').collect();
    let encoded: Vec<String> = segments.iter().map(|s| uri_encode(s, false)).collect();
    encoded.join("/")
}

/// Build canonical query string.
fn canonical_query_string(query: &BTreeMap<String, String>) -> String {
    if query.is_empty() {
        return String::new();
    }

    // Sort by key, then encode
    let mut pairs: Vec<String> = query
        .iter()
        .map(|(k, v)| alloc::format!("{}={}", uri_encode(k, true), uri_encode(v, true)))
        .collect();
    pairs.sort();
    pairs.join("&")
}

/// Build canonical headers.
fn canonical_headers(headers: &BTreeMap<String, String>, signed_headers: &[String]) -> String {
    let mut result = String::new();

    // Headers must be in same order as signed_headers
    for header_name in signed_headers {
        let lower_name = header_name.to_lowercase();

        // Find the header (case-insensitive)
        let value = headers
            .iter()
            .find(|(k, _)| k.to_lowercase() == lower_name)
            .map(|(_, v)| v.clone())
            .unwrap_or_default();

        // Trim and collapse whitespace
        let trimmed = value.split_whitespace().collect::<Vec<_>>().join(" ");

        result.push_str(&lower_name);
        result.push(':');
        result.push_str(&trimmed);
        result.push('\n');
    }

    result
}

/// URI encode for signing.
fn uri_encode(s: &str, encode_slash: bool) -> 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);
            }
            '/' if !encode_slash => {
                result.push(c);
            }
            _ => {
                for byte in c.to_string().as_bytes() {
                    result.push_str(&alloc::format!("%{:02X}", byte));
                }
            }
        }
    }
    result
}

// ═══════════════════════════════════════════════════════════════════════════════
// STRING TO SIGN
// ═══════════════════════════════════════════════════════════════════════════════

/// Build the string to sign.
fn build_string_to_sign(
    date_time: &str,
    credential_scope: &str,
    canonical_request: &str,
) -> String {
    let mut result = String::new();

    // Algorithm
    result.push_str("AWS4-HMAC-SHA256\n");

    // Request date/time
    result.push_str(date_time);
    result.push('\n');

    // Credential scope
    result.push_str(credential_scope);
    result.push('\n');

    // Hash of canonical request
    let hash = sha256_hex(canonical_request.as_bytes());
    result.push_str(&hash);

    result
}

// ═══════════════════════════════════════════════════════════════════════════════
// SIGNATURE CALCULATION
// ═══════════════════════════════════════════════════════════════════════════════

/// Calculate the signature.
fn calculate_signature(
    secret_key: &str,
    date: &str,
    region: &str,
    service: &str,
    string_to_sign: &str,
) -> String {
    // Derive signing key
    let k_secret = alloc::format!("AWS4{}", secret_key);
    let k_date = hmac_sha256(k_secret.as_bytes(), date.as_bytes());
    let k_region = hmac_sha256(&k_date, region.as_bytes());
    let k_service = hmac_sha256(&k_region, service.as_bytes());
    let k_signing = hmac_sha256(&k_service, b"aws4_request");

    // Calculate signature
    let signature = hmac_sha256(&k_signing, string_to_sign.as_bytes());

    // Convert to hex
    hex_encode(&signature)
}

// ═══════════════════════════════════════════════════════════════════════════════
// CRYPTO HELPERS - Using RustCrypto audited implementations
// ═══════════════════════════════════════════════════════════════════════════════

/// Type alias for HMAC-SHA256.
type HmacSha256 = Hmac<Sha256>;

/// SHA-256 hash, returning hex string.
fn sha256_hex(data: &[u8]) -> String {
    hex_encode(&sha256(data))
}

/// SHA-256 hash using RustCrypto sha2 crate.
///
/// Uses the audited sha2 crate implementation for security-critical operations.
fn sha256(data: &[u8]) -> [u8; 32] {
    let mut hasher = Sha256::new();
    hasher.update(data);
    let result = hasher.finalize();
    let mut output = [0u8; 32];
    output.copy_from_slice(&result);
    output
}

/// HMAC-SHA256 using RustCrypto hmac crate.
///
/// Uses the audited hmac crate with constant-time verification.
fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32] {
    let mut mac = HmacSha256::new_from_slice(key).expect("HMAC can take key of any size");
    mac.update(data);
    let result = mac.finalize();
    let mut output = [0u8; 32];
    output.copy_from_slice(&result.into_bytes());
    output
}

/// Encode bytes as hex string.
fn hex_encode(bytes: &[u8]) -> String {
    hex_encode_crate(bytes)
}

/// Constant-time string comparison to prevent timing attacks.
fn constant_time_compare(a: &str, b: &str) -> bool {
    if a.len() != b.len() {
        return false;
    }
    a.as_bytes().ct_eq(b.as_bytes()).into()
}

// ═══════════════════════════════════════════════════════════════════════════════
// TESTS
// ═══════════════════════════════════════════════════════════════════════════════

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

    #[test]
    fn test_sha256() {
        // Test vector: empty string
        let hash = sha256(b"");
        let expected = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
        assert_eq!(hex_encode(&hash), expected);

        // Test vector: "abc"
        let hash = sha256(b"abc");
        let expected = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
        assert_eq!(hex_encode(&hash), expected);
    }

    #[test]
    fn test_hmac_sha256() {
        // Test vector from RFC 4231
        let key = b"key";
        let data = b"The quick brown fox jumps over the lazy dog";
        let hmac = hmac_sha256(key, data);
        let expected = "f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8";
        assert_eq!(hex_encode(&hmac), expected);
    }

    #[test]
    fn test_hex_encode() {
        assert_eq!(hex_encode(&[0x12, 0x34, 0xab, 0xcd]), "1234abcd");
        assert_eq!(hex_encode(&[0x00, 0xff]), "00ff");
    }

    #[test]
    fn test_constant_time_compare() {
        assert!(constant_time_compare("abc", "abc"));
        assert!(!constant_time_compare("abc", "abd"));
        assert!(!constant_time_compare("abc", "ab"));
    }

    #[test]
    fn test_uri_encode() {
        assert_eq!(uri_encode("hello world", true), "hello%20world");
        assert_eq!(uri_encode("a/b/c", false), "a/b/c");
        assert_eq!(uri_encode("a/b/c", true), "a%2Fb%2Fc");
    }

    #[test]
    fn test_canonical_query_string() {
        let mut query = BTreeMap::new();
        query.insert("b".into(), "2".into());
        query.insert("a".into(), "1".into());

        let result = canonical_query_string(&query);
        assert_eq!(result, "a=1&b=2");
    }

    #[test]
    fn test_parse_authorization_header() {
        let header = "AWS4-HMAC-SHA256 Credential=AKID/20240101/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=abc123";
        let parsed = parse_authorization_header(header).unwrap();

        assert_eq!(parsed.access_key, "AKID");
        assert_eq!(parsed.date, "20240101");
        assert_eq!(parsed.region, "us-east-1");
        assert_eq!(parsed.service, "s3");
        assert_eq!(parsed.signature, "abc123");
        assert_eq!(parsed.signed_headers, vec!["host", "x-amz-date"]);
    }

    #[test]
    fn test_canonical_headers() {
        let mut headers = BTreeMap::new();
        headers.insert("Host".into(), "example.com".into());
        headers.insert("X-Amz-Date".into(), "20240101T000000Z".into());

        let signed = vec!["host".into(), "x-amz-date".into()];
        let result = canonical_headers(&headers, &signed);

        assert_eq!(result, "host:example.com\nx-amz-date:20240101T000000Z\n");
    }

    #[test]
    fn test_calculate_signature() {
        // This is a simplified test - actual AWS test vectors would be more comprehensive
        let signature = calculate_signature(
            "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
            "20240101",
            "us-east-1",
            "s3",
            "test-string-to-sign",
        );

        // Just verify it produces a 64-char hex string
        assert_eq!(signature.len(), 64);
        assert!(signature.chars().all(|c| c.is_ascii_hexdigit()));
    }
}