icepick 0.4.1

Experimental Rust client for Apache Iceberg with WASM support for AWS S3 Tables and Cloudflare R2
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
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
//! Vended credential provider for REST catalogs
use crate::error::{Error, Result};
use crate::io::{VendedCredentialProvider, VendedCredentials};
use reqwest::Client;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use urlencoding::encode;

use super::types::LoadTableCredentialsResponse;

/// Credential provider that fetches vended credentials from Iceberg REST catalog
#[derive(Debug)]
pub(crate) struct RestCredentialProvider {
    pub(crate) endpoint: String,
    pub(crate) prefix: String,
    pub(crate) token: String,
    pub(crate) http_client: Client,
    pub(crate) s3_endpoint: Option<String>,
    /// Cache credentials by table location prefix
    pub(crate) credential_cache: Arc<RwLock<HashMap<String, VendedCredentials>>>,
    /// Map table location prefix -> (namespace, table_name) for UUID-based paths
    /// R2 Data Catalog uses UUID-based file paths that cannot be parsed to extract
    /// namespace/table name. This registry allows explicit registration of table
    /// identity for credential lookup.
    pub(crate) table_registry: Arc<RwLock<HashMap<String, (String, String)>>>,
}

/// Extract table location from a file path.
///
/// For R2 Data Catalog, paths follow pattern:
/// `s3://bucket/namespace.db/tablename/metadata/...`
/// `s3://bucket/namespace.db/tablename/data/...`
///
/// This function strips the Iceberg-specific directories (data, metadata) to get
/// the table location prefix.
///
/// # Arguments
/// * `path` - Full path to an Iceberg file (data or metadata)
///
/// # Returns
/// The table location prefix (e.g., `s3://bucket/namespace.db/tablename`)
///
/// # Errors
/// Returns `Error::IoError` if the path doesn't match expected Iceberg structure
fn extract_table_location(path: &str) -> Result<String> {
    // Find known Iceberg directories that mark the table boundary
    let iceberg_dirs = ["/data/", "/metadata/"];

    for dir in iceberg_dirs {
        if let Some(idx) = path.find(dir) {
            return Ok(path[..idx].to_string());
        }
    }

    // If no Iceberg directory found, try to handle paths that end with these dirs
    for dir_name in ["data", "metadata"] {
        let suffix = format!("/{}", dir_name);
        if path.ends_with(&suffix) {
            return Ok(path[..path.len() - suffix.len()].to_string());
        }
    }

    Err(Error::IoError(format!(
        "Path does not contain Iceberg directory structure (data/ or metadata/): {}",
        path
    )))
}

/// Parse table identifier (namespace, table_name) from a table location.
///
/// For R2 Data Catalog, table locations follow pattern:
/// `s3://bucket/namespace.db/tablename`
///
/// The namespace is extracted from the part before `.db`, and the table name
/// is the final path component.
///
/// # Arguments
/// * `location` - Table location (e.g., `s3://bucket/namespace.db/tablename`)
///
/// # Returns
/// Tuple of (namespace, table_name)
///
/// # Errors
/// Returns `Error::IoError` if the location doesn't match expected pattern
fn parse_table_identifier_from_location(location: &str) -> Result<(String, String)> {
    // Strip the s3:// or similar prefix and bucket
    let path = if let Some(rest) = location.strip_prefix("s3://") {
        // Skip the bucket name (first path segment)
        if let Some(idx) = rest.find('/') {
            &rest[idx + 1..]
        } else {
            return Err(Error::IoError(format!(
                "Table location missing path after bucket: {}",
                location
            )));
        }
    } else {
        return Err(Error::IoError(format!(
            "Table location must start with s3://: {}",
            location
        )));
    };

    // Split the remaining path by '/'
    let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();

    if segments.is_empty() {
        return Err(Error::IoError(format!(
            "Table location has no path segments: {}",
            location
        )));
    }

    // The last segment is the table name
    let table_name = segments.last().unwrap().to_string();

    // Look for namespace.db pattern in the path
    // The namespace is typically in a segment ending with .db
    for segment in &segments[..segments.len().saturating_sub(1)] {
        if let Some(ns) = segment.strip_suffix(".db") {
            return Ok((ns.to_string(), table_name));
        }
    }

    // Fallback: if no .db suffix found, use the segment before the table name as namespace
    // This handles paths like s3://bucket/warehouse/namespace/table
    if segments.len() >= 2 {
        let namespace = segments[segments.len() - 2].to_string();
        return Ok((namespace, table_name));
    }

    Err(Error::IoError(format!(
        "Could not extract namespace from table location: {}",
        location
    )))
}

impl RestCredentialProvider {
    /// Register a table's identity for credential lookup.
    ///
    /// This allows the credential provider to fetch credentials using the table's
    /// actual namespace and name, rather than trying to parse them from file paths.
    /// This is essential for R2 Data Catalog which uses UUID-based paths like:
    /// `s3://bucket/019b9635-52b8-72b3-829b-de5900e5b195.019b9635-53e1-7732-b9f4-7b6b9ff240e7/data/file.parquet`
    ///
    /// # Arguments
    /// * `table_location` - The table's location prefix (e.g., `s3://bucket/uuid.uuid`)
    /// * `namespace` - The namespace name
    /// * `table_name` - The table name
    pub fn register_table(
        &self,
        table_location: &str,
        namespace: &str,
        table_name: &str,
    ) -> Result<()> {
        let mut registry = self.table_registry.write().map_err(|e| {
            Error::IoError(format!(
                "Failed to acquire table registry write lock: {}",
                e
            ))
        })?;
        registry.insert(
            table_location.to_string(),
            (namespace.to_string(), table_name.to_string()),
        );
        Ok(())
    }

    /// Look up a registered table identity by location.
    ///
    /// Returns `Some((namespace, table_name))` if the table was registered,
    /// or `None` if not found.
    fn lookup_registered_table(&self, table_location: &str) -> Result<Option<(String, String)>> {
        let registry = self.table_registry.read().map_err(|e| {
            Error::IoError(format!("Failed to acquire table registry read lock: {}", e))
        })?;
        Ok(registry.get(table_location).cloned())
    }

    /// Check if non-expired credentials are cached for the given table location.
    /// Returns None if credentials are not cached or have expired.
    fn check_cache_by_location(&self, table_location: &str) -> Result<Option<VendedCredentials>> {
        let cache = self
            .credential_cache
            .read()
            .map_err(|e| Error::IoError(format!("Failed to acquire cache read lock: {}", e)))?;

        match cache.get(table_location) {
            Some(creds) if !creds.is_expired() => Ok(Some(creds.clone())),
            Some(_) => Ok(None), // Expired credentials - treat as cache miss
            None => Ok(None),
        }
    }

    /// Cache credentials for a table location.
    fn cache_credentials(&self, table_location: &str, creds: VendedCredentials) -> Result<()> {
        let mut cache = self
            .credential_cache
            .write()
            .map_err(|e| Error::IoError(format!("Failed to acquire cache write lock: {}", e)))?;

        cache.insert(table_location.to_string(), creds);
        Ok(())
    }

    /// Fetch credentials from the REST catalog's /credentials endpoint.
    async fn fetch_credentials(
        &self,
        namespace: &str,
        table_name: &str,
    ) -> Result<LoadTableCredentialsResponse> {
        let url = format!(
            "{}/v1/{}/namespaces/{}/tables/{}/credentials",
            self.endpoint.trim_end_matches('/'),
            encode(&self.prefix),
            encode(namespace),
            encode(table_name)
        );

        let response = self
            .http_client
            .get(&url)
            .header("Authorization", format!("Bearer {}", self.token))
            .header("Accept", "application/json")
            .send()
            .await
            .map_err(|e| Error::IoError(format!("Failed to fetch credentials: {}", e)))?;

        let status = response.status();
        if status.as_u16() == 404 {
            return Err(Error::NotFound {
                resource: format!("credentials for {}.{}", namespace, table_name),
            });
        }

        if !status.is_success() {
            let body = response
                .text()
                .await
                .unwrap_or_else(|_| "Unknown error".to_string());
            return Err(Error::IoError(format!(
                "Credentials request failed with status {}: {}",
                status, body
            )));
        }

        let creds_response: LoadTableCredentialsResponse = response
            .json()
            .await
            .map_err(|e| Error::IoError(format!("Failed to parse credentials response: {}", e)))?;

        Ok(creds_response)
    }
}

#[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)]
#[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))]
impl VendedCredentialProvider for RestCredentialProvider {
    async fn get_credentials(&self, path: &str) -> Result<VendedCredentials> {
        // 1. Parse table location from path
        let table_location = extract_table_location(path)?;

        // 2. Check cache first using the extracted table location
        if let Some(cached) = self.check_cache_by_location(&table_location)? {
            return Ok(cached);
        }

        // 3. Derive table identifier from location
        // Check if we have a registered table identity for this location (for UUID-based paths)
        let (namespace, table_name) =
            if let Some((ns, tn)) = self.lookup_registered_table(&table_location)? {
                (ns, tn)
            } else {
                // Fall back to path parsing for backwards compatibility
                parse_table_identifier_from_location(&table_location)?
            };

        // 4. Fetch credentials from REST endpoint
        let creds_response = self.fetch_credentials(&namespace, &table_name).await?;

        // 5. Find matching credential for this path
        // R2 may return "/" as the prefix meaning "all paths", so we need flexible matching
        let cred = creds_response
            .storage_credentials
            .iter()
            .find(|c| {
                // "/" or empty prefix means "match all"
                if c.prefix == "/" || c.prefix.is_empty() {
                    return true;
                }
                // Try exact prefix match first
                if path.starts_with(&c.prefix) {
                    return true;
                }
                // Try matching just the path portion (after s3://bucket/)
                if let Some(path_portion) = path
                    .strip_prefix("s3://")
                    .and_then(|p| p.find('/').map(|i| &p[i..]))
                {
                    if path_portion.starts_with(&c.prefix) {
                        return true;
                    }
                }
                false
            })
            .ok_or_else(|| {
                Error::IoError(format!(
                    "No matching credential prefix for path: {}. Available prefixes: {:?}",
                    path,
                    creds_response
                        .storage_credentials
                        .iter()
                        .map(|c| &c.prefix)
                        .collect::<Vec<_>>()
                ))
            })?;

        // 6. Convert to VendedCredentials
        let access_key_id = cred.config.access_key_id.clone().ok_or_else(|| {
            Error::InvalidInput("Vended credentials missing access_key_id".to_string())
        })?;

        let secret_access_key = cred.config.secret_access_key.clone().ok_or_else(|| {
            Error::InvalidInput("Vended credentials missing secret_access_key".to_string())
        })?;

        let vended = VendedCredentials {
            access_key_id,
            secret_access_key,
            session_token: cred.config.session_token.clone(),
            endpoint: cred
                .config
                .endpoint
                .clone()
                .or_else(|| self.s3_endpoint.clone()),
            region: cred.config.region.clone(),
            expires_at_ms: cred.config.expires_at_ms,
        };

        // 7. Cache by table location
        self.cache_credentials(&table_location, vended.clone())?;

        Ok(vended)
    }

    fn s3_endpoint(&self) -> Option<&str> {
        self.s3_endpoint.as_deref()
    }

    fn register_table(
        &self,
        table_location: &str,
        namespace: &str,
        table_name: &str,
    ) -> Result<()> {
        // Delegate to the struct's register_table method
        RestCredentialProvider::register_table(self, table_location, namespace, table_name)
    }
}

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

    #[test]
    fn test_extract_table_location_data_path() {
        let path = "s3://bucket/warehouse/default.db/logs/data/00001.parquet";
        let result = extract_table_location(path).unwrap();
        assert_eq!(result, "s3://bucket/warehouse/default.db/logs");
    }

    #[test]
    fn test_extract_table_location_metadata_path() {
        let path = "s3://bucket/warehouse/default.db/logs/metadata/v1.metadata.json";
        let result = extract_table_location(path).unwrap();
        assert_eq!(result, "s3://bucket/warehouse/default.db/logs");
    }

    #[test]
    fn test_extract_table_location_nested_data() {
        let path = "s3://bucket/ns.db/table/data/partition=a/file.parquet";
        let result = extract_table_location(path).unwrap();
        assert_eq!(result, "s3://bucket/ns.db/table");
    }

    #[test]
    fn test_extract_table_location_no_iceberg_dir() {
        let path = "s3://bucket/some/random/path.parquet";
        let result = extract_table_location(path);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("does not contain Iceberg directory structure"));
    }

    #[test]
    fn test_parse_table_identifier_with_db_suffix() {
        let location = "s3://bucket/warehouse/default.db/logs";
        let (namespace, table) = parse_table_identifier_from_location(location).unwrap();
        assert_eq!(namespace, "default");
        assert_eq!(table, "logs");
    }

    #[test]
    fn test_parse_table_identifier_nested_warehouse() {
        let location = "s3://bucket/some/path/myns.db/mytable";
        let (namespace, table) = parse_table_identifier_from_location(location).unwrap();
        assert_eq!(namespace, "myns");
        assert_eq!(table, "mytable");
    }

    #[test]
    fn test_parse_table_identifier_fallback_no_db_suffix() {
        // When there's no .db suffix, use segment before table name
        let location = "s3://bucket/warehouse/namespace/table";
        let (namespace, table) = parse_table_identifier_from_location(location).unwrap();
        assert_eq!(namespace, "namespace");
        assert_eq!(table, "table");
    }

    #[test]
    fn test_parse_table_identifier_missing_prefix() {
        let location = "http://bucket/path/ns.db/table";
        let result = parse_table_identifier_from_location(location);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("must start with s3://"));
    }

    #[test]
    fn test_parse_table_identifier_no_path() {
        let location = "s3://bucket";
        let result = parse_table_identifier_from_location(location);
        assert!(result.is_err());
    }

    /// Create a test RestCredentialProvider with dummy values.
    /// Only the credential_cache is functional; HTTP calls will fail.
    fn create_test_provider() -> RestCredentialProvider {
        RestCredentialProvider {
            endpoint: "http://localhost:8080".to_string(),
            prefix: "test-prefix".to_string(),
            token: "test-token".to_string(),
            http_client: Client::new(),
            s3_endpoint: None,
            credential_cache: Arc::new(RwLock::new(HashMap::new())),
            table_registry: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    fn sample_credentials(id: &str) -> VendedCredentials {
        VendedCredentials {
            access_key_id: format!("AKIATEST{}", id),
            secret_access_key: format!("secret-{}", id),
            session_token: Some(format!("token-{}", id)),
            endpoint: Some("https://s3.example.com".to_string()),
            region: Some("us-west-2".to_string()),
            expires_at_ms: None, // No expiration for test credentials
        }
    }

    #[test]
    fn test_credential_caching_cache_miss_returns_none() {
        let provider = create_test_provider();

        // Cache miss: uncached location returns None
        let result = provider
            .check_cache_by_location("s3://bucket/ns.db/table1")
            .unwrap();
        assert!(result.is_none(), "Uncached location should return None");
    }

    #[test]
    fn test_credential_caching_cache_hit_after_store() {
        let provider = create_test_provider();
        let location = "s3://bucket/ns.db/table1";
        let creds = sample_credentials("1");

        // Store credentials
        provider.cache_credentials(location, creds.clone()).unwrap();

        // Cache hit: should return the stored credentials
        let cached = provider
            .check_cache_by_location(location)
            .unwrap()
            .expect("Should find cached credentials");

        assert_eq!(cached.access_key_id, creds.access_key_id);
        assert_eq!(cached.secret_access_key, creds.secret_access_key);
        assert_eq!(cached.session_token, creds.session_token);
        assert_eq!(cached.endpoint, creds.endpoint);
        assert_eq!(cached.region, creds.region);
    }

    #[test]
    fn test_credential_caching_different_locations_get_different_entries() {
        let provider = create_test_provider();

        let location1 = "s3://bucket/ns.db/table1";
        let location2 = "s3://bucket/ns.db/table2";
        let creds1 = sample_credentials("1");
        let creds2 = sample_credentials("2");

        // Store credentials for both locations
        provider
            .cache_credentials(location1, creds1.clone())
            .unwrap();
        provider
            .cache_credentials(location2, creds2.clone())
            .unwrap();

        // Verify each location returns its own credentials
        let cached1 = provider
            .check_cache_by_location(location1)
            .unwrap()
            .expect("Should find cached credentials for table1");
        let cached2 = provider
            .check_cache_by_location(location2)
            .unwrap()
            .expect("Should find cached credentials for table2");

        assert_eq!(cached1.access_key_id, creds1.access_key_id);
        assert_eq!(cached2.access_key_id, creds2.access_key_id);
        assert_ne!(cached1.access_key_id, cached2.access_key_id);
    }

    #[test]
    fn test_credential_caching_overwrite_existing() {
        let provider = create_test_provider();
        let location = "s3://bucket/ns.db/table1";

        let creds_v1 = sample_credentials("v1");
        let creds_v2 = sample_credentials("v2");

        // Store initial credentials
        provider.cache_credentials(location, creds_v1).unwrap();

        // Overwrite with new credentials
        provider
            .cache_credentials(location, creds_v2.clone())
            .unwrap();

        // Should return the updated credentials
        let cached = provider
            .check_cache_by_location(location)
            .unwrap()
            .expect("Should find cached credentials");

        assert_eq!(cached.access_key_id, creds_v2.access_key_id);
        assert_eq!(cached.secret_access_key, creds_v2.secret_access_key);
    }

    #[test]
    fn test_credential_caching_cache_isolation() {
        // Each provider has its own cache
        let provider1 = create_test_provider();
        let provider2 = create_test_provider();

        let location = "s3://bucket/ns.db/shared_table";
        let creds = sample_credentials("shared");

        // Store in provider1's cache only
        provider1.cache_credentials(location, creds).unwrap();

        // provider1 should have the entry
        assert!(provider1
            .check_cache_by_location(location)
            .unwrap()
            .is_some());

        // provider2 should not have the entry (separate cache)
        assert!(provider2
            .check_cache_by_location(location)
            .unwrap()
            .is_none());
    }

    #[test]
    fn test_table_registry_register_and_lookup() {
        let provider = create_test_provider();
        let location =
            "s3://bucket/019b9635-52b8-72b3-829b-de5900e5b195.019b9635-53e1-7732-b9f4-7b6b9ff240e7";

        // Initially not registered
        let result = provider.lookup_registered_table(location).unwrap();
        assert!(result.is_none());

        // Register the table
        provider
            .register_table(location, "my_namespace", "my_table")
            .unwrap();

        // Now it should be found
        let (namespace, table_name) = provider
            .lookup_registered_table(location)
            .unwrap()
            .expect("Should find registered table");
        assert_eq!(namespace, "my_namespace");
        assert_eq!(table_name, "my_table");
    }

    #[test]
    fn test_table_registry_overwrite() {
        let provider = create_test_provider();
        let location = "s3://bucket/uuid-path";

        // Register initial values
        provider.register_table(location, "ns1", "table1").unwrap();

        // Overwrite with new values
        provider.register_table(location, "ns2", "table2").unwrap();

        // Should return the updated values
        let (namespace, table_name) = provider
            .lookup_registered_table(location)
            .unwrap()
            .expect("Should find registered table");
        assert_eq!(namespace, "ns2");
        assert_eq!(table_name, "table2");
    }

    #[test]
    fn test_table_registry_multiple_tables() {
        let provider = create_test_provider();
        let location1 = "s3://bucket/uuid1";
        let location2 = "s3://bucket/uuid2";

        provider.register_table(location1, "ns1", "table1").unwrap();
        provider.register_table(location2, "ns2", "table2").unwrap();

        let (ns1, tn1) = provider
            .lookup_registered_table(location1)
            .unwrap()
            .expect("Should find table1");
        let (ns2, tn2) = provider
            .lookup_registered_table(location2)
            .unwrap()
            .expect("Should find table2");

        assert_eq!(ns1, "ns1");
        assert_eq!(tn1, "table1");
        assert_eq!(ns2, "ns2");
        assert_eq!(tn2, "table2");
    }

    #[test]
    fn test_expired_credentials_not_returned_from_cache() {
        let provider = create_test_provider();
        let location = "s3://bucket/ns.db/table1";

        // Create credentials that expired 1 hour ago
        let now_ms = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_millis() as i64;
        let expired_creds = VendedCredentials {
            access_key_id: "AKIAEXPIRED".to_string(),
            secret_access_key: "expired-secret".to_string(),
            session_token: None,
            endpoint: Some("https://s3.example.com".to_string()),
            region: Some("us-west-2".to_string()),
            expires_at_ms: Some(now_ms - 3_600_000), // Expired 1 hour ago
        };

        // Store expired credentials
        provider.cache_credentials(location, expired_creds).unwrap();

        // Cache check should return None for expired credentials
        let result = provider.check_cache_by_location(location).unwrap();
        assert!(
            result.is_none(),
            "Expired credentials should not be returned from cache"
        );
    }

    #[test]
    fn test_valid_credentials_returned_from_cache() {
        let provider = create_test_provider();
        let location = "s3://bucket/ns.db/table1";

        // Create credentials that expire in 1 hour
        let now_ms = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_millis() as i64;
        let valid_creds = VendedCredentials {
            access_key_id: "AKIAVALID".to_string(),
            secret_access_key: "valid-secret".to_string(),
            session_token: None,
            endpoint: Some("https://s3.example.com".to_string()),
            region: Some("us-west-2".to_string()),
            expires_at_ms: Some(now_ms + 3_600_000), // Expires in 1 hour
        };

        // Store valid credentials
        provider
            .cache_credentials(location, valid_creds.clone())
            .unwrap();

        // Cache check should return the credentials
        let result = provider.check_cache_by_location(location).unwrap();
        assert!(
            result.is_some(),
            "Valid credentials should be returned from cache"
        );
        assert_eq!(result.unwrap().access_key_id, "AKIAVALID");
    }

    #[test]
    fn test_credentials_near_expiry_not_returned() {
        let provider = create_test_provider();
        let location = "s3://bucket/ns.db/table1";

        // Create credentials that expire in 30 seconds (within 60s buffer)
        let now_ms = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_millis() as i64;
        let near_expiry_creds = VendedCredentials {
            access_key_id: "AKIANEAREXPIRY".to_string(),
            secret_access_key: "near-expiry-secret".to_string(),
            session_token: None,
            endpoint: Some("https://s3.example.com".to_string()),
            region: Some("us-west-2".to_string()),
            expires_at_ms: Some(now_ms + 30_000), // Expires in 30 seconds
        };

        // Store credentials
        provider
            .cache_credentials(location, near_expiry_creds)
            .unwrap();

        // Cache check should return None (within 60s buffer)
        let result = provider.check_cache_by_location(location).unwrap();
        assert!(
            result.is_none(),
            "Credentials near expiry should not be returned from cache"
        );
    }
}