rustberg 0.0.5

A production-grade, cross-platform, single-binary Apache Iceberg REST Catalog
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
//! Azure credential provider for Azure Blob Storage / ADLS Gen2 access.
//!
//! This provider vends Azure storage credentials for accessing table data in Azure storage.
//!
//! # Authentication Methods
//!
//! The provider supports multiple authentication methods:
//! - **SAS Token** - Pre-generated Shared Access Signature token
//! - **Account Key** - Storage account access key
//! - **Connection String** - Full Azure connection string
//!
//! # Example
//!
//! ```no_run
//! use rustberg::credentials::{AzureCredentialProvider, AzureConfig};
//!
//! // Using SAS token
//! let config = AzureConfig::new()
//!     .with_account_name("mystorageaccount")
//!     .with_sas_token("sv=2022-11-02&ss=b&srt=sco&sp=rwdlacitfx...")
//!     .with_allowed_prefix("abfss://container@mystorageaccount.dfs.core.windows.net/");
//!
//! let provider = AzureCredentialProvider::new(config)?;
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! # ADLS Gen2 URIs
//!
//! The provider supports multiple URI schemes for Azure storage:
//! - `abfss://container@account.dfs.core.windows.net/path` - ADLS Gen2 (secure)
//! - `abfs://container@account.dfs.core.windows.net/path` - ADLS Gen2
//! - `wasbs://container@account.blob.core.windows.net/path` - Blob Storage (secure)
//! - `wasb://container@account.blob.core.windows.net/path` - Blob Storage
//!
//! # Credential Config Keys
//!
//! The credentials returned use the following Iceberg config keys:
//! - `adls.sas-token.<account>` - SAS token for the storage account
//! - `adls.account-key.<account>` - Storage account key
//! - `adls.connection-string.<account>` - Full connection string

use async_trait::async_trait;
use std::collections::HashMap;

use super::provider::{
    StorageCredential, StorageCredentialProvider, StorageCredentialRequest,
    StorageCredentialVendingError,
};

/// Azure credential provider configuration.
#[derive(Debug, Clone, Default)]
pub struct AzureConfig {
    /// Azure storage account name.
    pub account_name: Option<String>,

    /// SAS token for the storage account (without leading `?`).
    pub sas_token: Option<String>,

    /// Storage account access key.
    pub account_key: Option<String>,

    /// Full connection string (alternative to individual settings).
    pub connection_string: Option<String>,

    /// Azure storage prefixes that this provider can grant access to.
    /// If empty, the provider will attempt to grant access to any Azure location.
    pub allowed_prefixes: Vec<String>,
}

impl AzureConfig {
    /// Creates a new Azure config with default settings.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the Azure storage account name.
    pub fn with_account_name(mut self, name: impl Into<String>) -> Self {
        self.account_name = Some(name.into());
        self
    }

    /// Sets the SAS token (without leading `?`).
    pub fn with_sas_token(mut self, token: impl Into<String>) -> Self {
        let token = token.into();
        // Strip leading `?` if present
        self.sas_token = Some(token.strip_prefix('?').unwrap_or(&token).to_string());
        self
    }

    /// Sets the storage account access key.
    pub fn with_account_key(mut self, key: impl Into<String>) -> Self {
        self.account_key = Some(key.into());
        self
    }

    /// Sets the full connection string.
    pub fn with_connection_string(mut self, conn_string: impl Into<String>) -> Self {
        self.connection_string = Some(conn_string.into());
        self
    }

    /// Adds an allowed Azure storage prefix.
    pub fn with_allowed_prefix(mut self, prefix: impl Into<String>) -> Self {
        self.allowed_prefixes.push(prefix.into());
        self
    }

    /// Sets the allowed Azure storage prefixes.
    pub fn with_allowed_prefixes(mut self, prefixes: Vec<String>) -> Self {
        self.allowed_prefixes = prefixes;
        self
    }

    /// Validates the configuration.
    fn validate(&self) -> Result<(), StorageCredentialVendingError> {
        // Must have account name (unless using connection string)
        if self.connection_string.is_none() && self.account_name.is_none() {
            return Err(StorageCredentialVendingError::ConfigurationError(
                "Azure credential provider requires either account_name or connection_string"
                    .to_string(),
            ));
        }

        // Must have at least one credential type
        if self.sas_token.is_none()
            && self.account_key.is_none()
            && self.connection_string.is_none()
        {
            return Err(StorageCredentialVendingError::ConfigurationError(
                "Azure credential provider requires sas_token, account_key, or connection_string"
                    .to_string(),
            ));
        }

        Ok(())
    }
}

/// Azure credential provider.
///
/// Vends Azure storage credentials for accessing table data in Azure Blob Storage
/// or ADLS Gen2.
#[derive(Debug)]
pub struct AzureCredentialProvider {
    config: AzureConfig,
}

impl AzureCredentialProvider {
    /// Creates a new Azure credential provider.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rustberg::credentials::{AzureCredentialProvider, AzureConfig};
    ///
    /// let config = AzureConfig::new()
    ///     .with_account_name("mystorageaccount")
    ///     .with_sas_token("sv=2022-11-02&ss=b&srt=sco...");
    /// let provider = AzureCredentialProvider::new(config)?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn new(config: AzureConfig) -> Result<Self, StorageCredentialVendingError> {
        config.validate()?;
        Ok(Self { config })
    }

    /// Checks if the given location starts with any allowed prefix.
    fn is_location_allowed(&self, location: &str) -> bool {
        if self.config.allowed_prefixes.is_empty() {
            // No restrictions - allow any Azure location
            return true;
        }

        self.config
            .allowed_prefixes
            .iter()
            .any(|prefix| location.starts_with(prefix))
    }

    /// Extracts the storage account name from an Azure URI.
    ///
    /// Supported formats:
    /// - `abfss://container@account.dfs.core.windows.net/path`
    /// - `wasbs://container@account.blob.core.windows.net/path`
    fn extract_account_from_uri(uri: &str) -> Option<String> {
        // Format: scheme://container@account.*.core.windows.net/path
        let without_scheme = uri
            .strip_prefix("abfss://")
            .or_else(|| uri.strip_prefix("abfs://"))
            .or_else(|| uri.strip_prefix("wasbs://"))
            .or_else(|| uri.strip_prefix("wasb://"))?;

        // Find @account part
        let at_pos = without_scheme.find('@')?;
        let after_at = &without_scheme[at_pos + 1..];

        // Account name is before the first `.`
        let dot_pos = after_at.find('.')?;
        Some(after_at[..dot_pos].to_string())
    }

    /// Extracts the table prefix from a table location.
    fn get_table_prefix(location: &str) -> String {
        if location.ends_with('/') {
            location.to_string()
        } else {
            format!("{}/", location)
        }
    }

    /// Builds credential config map based on the configuration.
    fn build_credential_config(&self, account: &str) -> HashMap<String, String> {
        let mut config = HashMap::new();

        // Priority: SAS token > Account key > Connection string
        if let Some(ref sas) = self.config.sas_token {
            let key = format!("adls.sas-token.{}", account);
            config.insert(key, sas.clone());
        } else if let Some(ref key) = self.config.account_key {
            let config_key = format!("adls.account-key.{}", account);
            config.insert(config_key, key.clone());
        } else if let Some(ref conn_str) = self.config.connection_string {
            let key = format!("adls.connection-string.{}", account);
            config.insert(key, conn_str.clone());
        }

        config
    }
}

#[async_trait]
impl StorageCredentialProvider for AzureCredentialProvider {
    async fn vend_credentials(
        &self,
        request: &StorageCredentialRequest,
    ) -> Result<Vec<StorageCredential>, StorageCredentialVendingError> {
        // Check if this location is allowed
        if !self.is_location_allowed(&request.table_location) {
            return Ok(vec![]);
        }

        // Try to extract account from URI, fall back to configured account
        let account = Self::extract_account_from_uri(&request.table_location)
            .or_else(|| self.config.account_name.clone())
            .ok_or_else(|| {
                StorageCredentialVendingError::AzureError(
                    "Cannot determine storage account from location or config".to_string(),
                )
            })?;

        // Build the storage credential
        let prefix = Self::get_table_prefix(&request.table_location);
        let config = self.build_credential_config(&account);

        Ok(vec![StorageCredential::new(prefix, config)])
    }

    fn supports_location(&self, location: &str) -> bool {
        location.starts_with("abfss://")
            || location.starts_with("abfs://")
            || location.starts_with("wasbs://")
            || location.starts_with("wasb://")
    }
}

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

    #[test]
    fn test_config_builder() {
        let config = AzureConfig::new()
            .with_account_name("myaccount")
            .with_sas_token("sv=2022-11-02&ss=b")
            .with_allowed_prefix("abfss://container@myaccount.dfs.core.windows.net/");

        assert_eq!(config.account_name, Some("myaccount".to_string()));
        assert_eq!(config.sas_token, Some("sv=2022-11-02&ss=b".to_string()));
        assert_eq!(config.allowed_prefixes.len(), 1);
    }

    #[test]
    fn test_sas_token_strips_leading_question_mark() {
        let config = AzureConfig::new()
            .with_account_name("myaccount")
            .with_sas_token("?sv=2022-11-02&ss=b");

        assert_eq!(config.sas_token, Some("sv=2022-11-02&ss=b".to_string()));
    }

    #[test]
    fn test_config_validation_missing_account() {
        let config = AzureConfig::new().with_sas_token("token");
        let result = config.validate();
        assert!(result.is_err());
    }

    #[test]
    fn test_config_validation_missing_credentials() {
        let config = AzureConfig::new().with_account_name("myaccount");
        let result = config.validate();
        assert!(result.is_err());
    }

    #[test]
    fn test_config_validation_valid() {
        let config = AzureConfig::new()
            .with_account_name("myaccount")
            .with_sas_token("token");
        let result = config.validate();
        assert!(result.is_ok());
    }

    #[test]
    fn test_extract_account_from_uri_abfss() {
        let uri = "abfss://container@myaccount.dfs.core.windows.net/path/to/table";
        assert_eq!(
            AzureCredentialProvider::extract_account_from_uri(uri),
            Some("myaccount".to_string())
        );
    }

    #[test]
    fn test_extract_account_from_uri_wasbs() {
        let uri = "wasbs://container@myaccount.blob.core.windows.net/path";
        assert_eq!(
            AzureCredentialProvider::extract_account_from_uri(uri),
            Some("myaccount".to_string())
        );
    }

    #[test]
    fn test_extract_account_from_uri_invalid() {
        let uri = "gs://bucket/path";
        assert_eq!(AzureCredentialProvider::extract_account_from_uri(uri), None);
    }

    #[test]
    fn test_table_prefix() {
        assert_eq!(
            AzureCredentialProvider::get_table_prefix(
                "abfss://container@account.dfs.core.windows.net/warehouse/ns/table"
            ),
            "abfss://container@account.dfs.core.windows.net/warehouse/ns/table/"
        );

        assert_eq!(
            AzureCredentialProvider::get_table_prefix(
                "abfss://container@account.dfs.core.windows.net/warehouse/ns/table/"
            ),
            "abfss://container@account.dfs.core.windows.net/warehouse/ns/table/"
        );
    }

    #[test]
    fn test_location_allowed() {
        let config = AzureConfig::new()
            .with_account_name("myaccount")
            .with_sas_token("token")
            .with_allowed_prefix("abfss://allowed@myaccount.dfs.core.windows.net/");

        let provider = AzureCredentialProvider::new(config).unwrap();

        assert!(provider
            .is_location_allowed("abfss://allowed@myaccount.dfs.core.windows.net/data/table"));
        assert!(!provider
            .is_location_allowed("abfss://other@myaccount.dfs.core.windows.net/data/table"));
    }

    #[test]
    fn test_location_allowed_no_restrictions() {
        let config = AzureConfig::new()
            .with_account_name("myaccount")
            .with_sas_token("token");

        let provider = AzureCredentialProvider::new(config).unwrap();

        assert!(provider.is_location_allowed("abfss://any@account.dfs.core.windows.net/any/path"));
    }

    #[test]
    fn test_supports_location() {
        let config = AzureConfig::new()
            .with_account_name("myaccount")
            .with_sas_token("token");

        let provider = AzureCredentialProvider::new(config).unwrap();

        assert!(provider.supports_location("abfss://container@account.dfs.core.windows.net/"));
        assert!(provider.supports_location("abfs://container@account.dfs.core.windows.net/"));
        assert!(provider.supports_location("wasbs://container@account.blob.core.windows.net/"));
        assert!(provider.supports_location("wasb://container@account.blob.core.windows.net/"));
        assert!(!provider.supports_location("gs://bucket/path"));
        assert!(!provider.supports_location("s3://bucket/path"));
    }

    #[test]
    fn test_build_credential_config_sas() {
        let config = AzureConfig::new()
            .with_account_name("myaccount")
            .with_sas_token("sv=2022&ss=b");

        let provider = AzureCredentialProvider::new(config).unwrap();
        let cred_config = provider.build_credential_config("myaccount");

        assert_eq!(
            cred_config.get("adls.sas-token.myaccount").unwrap(),
            "sv=2022&ss=b"
        );
    }

    #[test]
    fn test_build_credential_config_account_key() {
        let config = AzureConfig::new()
            .with_account_name("myaccount")
            .with_account_key("secret-key");

        let provider = AzureCredentialProvider::new(config).unwrap();
        let cred_config = provider.build_credential_config("myaccount");

        assert_eq!(
            cred_config.get("adls.account-key.myaccount").unwrap(),
            "secret-key"
        );
    }

    #[tokio::test]
    async fn test_vend_credentials() {
        let config = AzureConfig::new()
            .with_account_name("myaccount")
            .with_sas_token("sv=2022&ss=b");

        let provider = AzureCredentialProvider::new(config).unwrap();

        let request = StorageCredentialRequest {
            tenant_id: "tenant1".to_string(),
            namespace: vec!["ns".to_string()],
            table_name: "table".to_string(),
            table_location: "abfss://container@myaccount.dfs.core.windows.net/warehouse/ns/table"
                .to_string(),
            write_access: false,
        };

        let credentials = provider.vend_credentials(&request).await.unwrap();

        assert_eq!(credentials.len(), 1);
        let cred = &credentials[0];
        assert_eq!(
            cred.prefix,
            "abfss://container@myaccount.dfs.core.windows.net/warehouse/ns/table/"
        );
        assert_eq!(
            cred.config.get("adls.sas-token.myaccount").unwrap(),
            "sv=2022&ss=b"
        );
    }

    #[tokio::test]
    async fn test_vend_credentials_location_not_allowed() {
        let config = AzureConfig::new()
            .with_account_name("myaccount")
            .with_sas_token("token")
            .with_allowed_prefix("abfss://allowed@myaccount.dfs.core.windows.net/");

        let provider = AzureCredentialProvider::new(config).unwrap();

        let request = StorageCredentialRequest {
            tenant_id: "tenant1".to_string(),
            namespace: vec!["ns".to_string()],
            table_name: "table".to_string(),
            table_location: "abfss://other@myaccount.dfs.core.windows.net/warehouse/ns/table"
                .to_string(),
            write_access: false,
        };

        let credentials = provider.vend_credentials(&request).await.unwrap();
        assert!(credentials.is_empty());
    }
}