Skip to content

Implement cloud configuration support for Azure SDK for Rust #2898

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
189 changes: 189 additions & 0 deletions docs/CLOUD_CONFIGURATION.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
# Cloud Configuration in Azure SDK for Rust

The Azure SDK for Rust now supports cloud configuration, enabling services to work across different Azure cloud environments including Azure Public Cloud, Azure China Cloud, Azure Germany Cloud, and Azure US Government Cloud.

## Overview

Cloud configuration provides:
- **Automatic endpoint selection** based on the target cloud environment
- **Correct authentication scopes** for each cloud and service
- **Easy switching** between sovereign clouds
- **Consistent API** across all cloud environments

## Quick Start

### Creating Credentials for Specific Clouds

```rust
use azure_core::credentials::Secret;
use azure_identity::ClientSecretCredential;

// Public Cloud (default)
let public_credential = ClientSecretCredential::new_for_public_cloud(
"tenant-id",
"client-id".to_string(),
Secret::new("client-secret".to_string()),
)?;

// China Cloud
let china_credential = ClientSecretCredential::new_for_china_cloud(
"tenant-id",
"client-id".to_string(),
Secret::new("client-secret".to_string()),
)?;

// US Government Cloud
let us_gov_credential = ClientSecretCredential::new_for_us_government_cloud(
"tenant-id",
"client-id".to_string(),
Secret::new("client-secret".to_string()),
)?;
```

### Configuring Service Clients

```rust
use azure_core::cloud::configurations;
use azure_core::http::ClientOptions;

// Configure for China Cloud with Tables service
let options = ClientOptions::default()
.with_cloud_config(configurations::azure_china_cloud())
.with_audience("https://storage.azure.com");

// Automatically derive the correct OAuth scope
let scope = options.get_auth_scope(Some("tables"));
// Returns: "https://storage.azure.com/.default"
```

## Available Cloud Configurations

| Cloud | Configuration |
|-------|---------------|
| Azure Public Cloud | `configurations::azure_public_cloud()` |
| Azure China Cloud | `configurations::azure_china_cloud()` |
| Azure Germany Cloud | `configurations::azure_germany_cloud()` |
| Azure US Government Cloud | `configurations::azure_us_government_cloud()` |

## Service Audiences

Each cloud configuration includes service-specific audience URIs:

### Public Cloud
- **Storage/Tables**: `https://storage.azure.com`
- **Key Vault**: `https://vault.azure.net`
- **Resource Manager**: `https://management.azure.com`

### China Cloud
- **Storage/Tables**: `https://storage.azure.com`
- **Key Vault**: `https://vault.azure.cn`
- **Resource Manager**: `https://management.chinacloudapi.cn`

### US Government Cloud
- **Storage/Tables**: `https://storage.azure.com`
- **Key Vault**: `https://vault.usgovcloudapi.net`
- **Resource Manager**: `https://management.usgovcloudapi.net`

## Complete Example: Tables Service

```rust
use azure_core::cloud::configurations;
use azure_core::credentials::Secret;
use azure_core::http::{ClientOptions, policies::BearerTokenCredentialPolicy};
use azure_identity::ClientSecretCredential;

// Create credential for China Cloud
let credential = ClientSecretCredential::new_for_china_cloud(
"tenant-id",
"client-id".to_string(),
Secret::new("client-secret".to_string()),
)?;

// Configure client options for Tables service in China Cloud
let options = ClientOptions::default()
.with_cloud_config(configurations::azure_china_cloud())
.with_audience("https://storage.azure.com");

// Get the OAuth scope for authentication
let scope = options.get_auth_scope(Some("tables")).unwrap();
// scope = "https://storage.azure.com/.default"

// Create authentication policy with the derived scope
let auth_policy = BearerTokenCredentialPolicy::new(credential, [scope]);

// Build service endpoint (China Cloud Tables endpoint)
let endpoint = format!("https://{}.table.core.chinacloudapi.cn", account_name);
```

## Migration Guide

### From Deprecated Constants

The old `authority_hosts` and `resource_manager_endpoint` modules are deprecated. Migrate to cloud configurations:

```rust
// OLD (deprecated)
use azure_core::authority_hosts;
let authority = authority_hosts::AZURE_CHINA_CLOUD;

// NEW
use azure_core::cloud::configurations;
let cloud_config = configurations::azure_china_cloud();
let authority = &cloud_config.authority_host;
```

### Updating Service Clients

If you have existing service clients, update them to use cloud configuration:

```rust
// Before
let client = ServiceClient::new(endpoint, credential);

// After - with cloud configuration
let options = ClientOptions::default()
.with_cloud_config(configurations::azure_china_cloud())
.with_audience("https://service-audience.com");

let client = ServiceClient::new_with_options(endpoint, credential, options);
```

## Custom Cloud Configuration

For custom or private cloud environments:

```rust
use azure_core::cloud::CloudConfiguration;
use azure_core::http::Url;

let custom_cloud = CloudConfiguration::new(
Url::parse("https://login.custom-cloud.com")?,
Url::parse("https://management.custom-cloud.com")?,
"https://management.custom-cloud.com".to_string(),
)
.with_service_audience("storage", "https://storage.custom-cloud.com")
.with_service_audience("keyvault", "https://vault.custom-cloud.com");

let options = ClientOptions::default()
.with_cloud_config(&custom_cloud)
.with_audience("https://storage.custom-cloud.com");
```

## Best Practices

1. **Use convenience methods** for well-known clouds: `new_for_china_cloud()`, etc.
2. **Let the SDK derive scopes** using `get_auth_scope()` instead of hardcoding
3. **Configure cloud at the client level** using `ClientOptions`
4. **Test with different clouds** to ensure your service works across environments

## Examples

See the examples in the repository:
- [`identity/examples/cloud_configuration.rs`](../sdk/identity/azure_identity/examples/cloud_configuration.rs) - Identity credential usage
- [`core/examples/tables_cloud_configuration.rs`](../sdk/core/azure_core/examples/tables_cloud_configuration.rs) - Service client integration

## Reference

- [Azure Cloud Configuration API](../sdk/core/azure_core/src/cloud.rs)
- [Identity Options API](../sdk/identity/azure_identity/src/options.rs)
- [Client Options API](../sdk/core/azure_core/src/http/options/mod.rs)
160 changes: 160 additions & 0 deletions sdk/core/azure_core/examples/tables_cloud_configuration.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

//! Example showing how a Tables service client would use cloud configuration.
//! This demonstrates the pattern that Tables and other services would follow.

use azure_core::cloud::configurations;
use azure_core::credentials::Secret;
use azure_core::http::{ClientOptions, policies::BearerTokenCredentialPolicy};
use azure_identity::ClientSecretCredential;
use std::env;
use std::sync::Arc;

/// Example Tables client that demonstrates cloud configuration usage.
#[derive(Debug)]
pub struct ExampleTablesClient {
#[allow(dead_code)]
endpoint: String,
#[allow(dead_code)]
pipeline: Vec<Arc<dyn azure_core::http::policies::Policy>>,
}

impl ExampleTablesClient {
/// Create a new Tables client for Azure Public Cloud.
pub fn new_for_public_cloud(
account_name: &str,
credential: Arc<dyn azure_core::credentials::TokenCredential>,
) -> Self {
let options = ClientOptions::default()
.with_cloud_config(configurations::azure_public_cloud())
.with_audience("https://storage.azure.com");

Self::new_with_options(account_name, credential, options)
}

/// Create a new Tables client for Azure China Cloud.
pub fn new_for_china_cloud(
account_name: &str,
credential: Arc<dyn azure_core::credentials::TokenCredential>,
) -> Self {
let options = ClientOptions::default()
.with_cloud_config(configurations::azure_china_cloud())
.with_audience("https://storage.azure.com");

Self::new_with_options(account_name, credential, options)
}

/// Create a new Tables client for Azure US Government Cloud.
pub fn new_for_us_government_cloud(
account_name: &str,
credential: Arc<dyn azure_core::credentials::TokenCredential>,
) -> Self {
let options = ClientOptions::default()
.with_cloud_config(configurations::azure_us_government_cloud())
.with_audience("https://storage.azure.com");

Self::new_with_options(account_name, credential, options)
}
Comment on lines +25 to +58
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do NOT add methods for each cloud. The cloud configuration is only used if passed in via the options bag


/// Create a new Tables client with custom options.
pub fn new_with_options(
account_name: &str,
credential: Arc<dyn azure_core::credentials::TokenCredential>,
options: ClientOptions,
) -> Self {
Comment on lines +61 to +65
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be new(......).

The options param is optional and should be:
options: Option

// Get the appropriate scope for the service
let scope = options.get_auth_scope(Some("tables"))
.unwrap_or_else(|| "https://storage.azure.com/.default".to_string());

// Create authentication policy with the derived scope
let auth_policy = BearerTokenCredentialPolicy::new(credential, [scope]);

// Build the endpoint URL based on cloud configuration
let cloud_config = options.cloud_config.unwrap_or_else(|| configurations::azure_public_cloud());
let storage_suffix = get_storage_suffix_for_cloud(cloud_config);
let endpoint = format!("https://{}.table.{}", account_name, storage_suffix);

println!("Tables client created:");
println!(" Endpoint: {}", endpoint);
println!(" Cloud: {}", cloud_config.authority_host);

Self {
endpoint,
pipeline: vec![Arc::new(auth_policy)],
}
}
}

/// Helper function to get the storage suffix for different clouds.
fn get_storage_suffix_for_cloud(cloud_config: &azure_core::cloud::CloudConfiguration) -> &'static str {
// In a real implementation, this would be part of the cloud configuration
match cloud_config.authority_host.as_str() {
"https://login.microsoftonline.com/" => "core.windows.net",
"https://login.chinacloudapi.cn/" => "core.chinacloudapi.cn",
"https://login.microsoftonline.de/" => "core.cloudapi.de",
"https://login.microsoftonline.us/" => "core.usgovcloudapi.net",
_ => "core.windows.net", // Default to public cloud
}
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("=== Example Tables Service with Cloud Configuration ===\n");

// Get credentials from environment variables
let tenant_id = env::var("AZURE_TENANT_ID").unwrap_or_else(|_| "tenant-id".to_string());
let client_id = env::var("AZURE_CLIENT_ID").unwrap_or_else(|_| "client-id".to_string());
let client_secret = env::var("AZURE_CLIENT_SECRET").unwrap_or_else(|_| "client-secret".to_string());
let account_name = "exampleaccount";

// Example 1: Tables client for Public Cloud
println!("1. Creating Tables client for Public Cloud:");
let public_credential = ClientSecretCredential::new_for_public_cloud(
&tenant_id,
client_id.clone(),
Secret::new(client_secret.clone()),
)?;
let _public_tables = ExampleTablesClient::new_for_public_cloud(account_name, public_credential);

// Example 2: Tables client for China Cloud
println!("\n2. Creating Tables client for China Cloud:");
let china_credential = ClientSecretCredential::new_for_china_cloud(
&tenant_id,
client_id.clone(),
Secret::new(client_secret.clone()),
)?;
let _china_tables = ExampleTablesClient::new_for_china_cloud(account_name, china_credential);

// Example 3: Tables client for US Government Cloud
println!("\n3. Creating Tables client for US Government Cloud:");
let us_gov_credential = ClientSecretCredential::new_for_us_government_cloud(
&tenant_id,
client_id.clone(),
Secret::new(client_secret.clone()),
)?;
let _us_gov_tables = ExampleTablesClient::new_for_us_government_cloud(account_name, us_gov_credential);

// Example 4: Custom configuration
println!("\n4. Creating Tables client with custom configuration:");
let custom_credential = ClientSecretCredential::new_for_public_cloud(
&tenant_id,
client_id,
Secret::new(client_secret),
)?;

let custom_options = ClientOptions::default()
.with_cloud_config(configurations::azure_germany_cloud())
.with_audience("https://storage.azure.com");

let _custom_tables = ExampleTablesClient::new_with_options(account_name, custom_credential, custom_options);

println!("\n✅ All Tables clients created successfully!");
println!("\nKey benefits of cloud configuration:");
println!("• Automatic endpoint selection based on cloud");
println!("• Correct authentication scopes for each cloud");
println!("• Easy switching between sovereign clouds");
println!("• Consistent API across all cloud environments");

Ok(())
}
Loading
Loading