This is an automated email from the ASF dual-hosted git repository. Xuanwo pushed a commit to branch xuanwo/azblob-service-principal-presign in repository https://gitbox.apache.org/repos/asf/opendal.git
commit 2b6593b59f8385e946189f23710e546b86b92273 Author: Xuanwo <[email protected]> AuthorDate: Sun Nov 29 22:52:00 2026 +0100 fix(services/azblob): presign Blob reads with service principals Use Reqsign to grant a read-only user delegation SAS for the requested blob. Reuse source credentials and delegation keys within each effective HTTP transport while binding a new grant to each read. --- core/services/azblob/src/backend.rs | 323 ++++++++++++++++++++++++++++++---- core/services/azblob/src/core.rs | 60 ++++++- core/services/azblob/src/docs.md | 19 +- dev/src/generate/capabilities_docs.rs | 25 ++- website/data/capabilities.json | 4 +- 5 files changed, 377 insertions(+), 54 deletions(-) diff --git a/core/services/azblob/src/backend.rs b/core/services/azblob/src/backend.rs index db89c111a3..5984bfa47f 100644 --- a/core/services/azblob/src/backend.rs +++ b/core/services/azblob/src/backend.rs @@ -522,10 +522,10 @@ impl AzblobBuilder { .sas_token .as_deref() .is_some_and(|token| !token.trim_start_matches('?').is_empty()); - let is_path_style_endpoint = match endpoint.parse::<http::Uri>() { - Ok(uri) => uri.authority().is_none() || !uri.path().trim_matches('/').is_empty(), - Err(_) => true, - }; + let endpoint_uri = endpoint.parse::<http::Uri>().ok(); + let is_path_style_endpoint = endpoint_uri.as_ref().is_none_or(|uri| { + uri.authority().is_none() || !uri.path().trim_matches('/').is_empty() + }); if let (Some(account_name), Some(account_key)) = (account_name.as_deref(), self.config.account_key.as_deref()) @@ -540,6 +540,24 @@ impl AzblobBuilder { credential_providers.push_front(StaticCredentialProvider::new_sas_token(sas_token)); } + let user_delegation_account = account_name.filter(|account| { + has_explicit_client_secret + && !self.config.skip_signature + && self.config.sas_token.is_none() + && self.config.account_key.is_none() + && self.credential_providers.is_none() + && endpoint_uri.as_ref().is_some_and(|uri| { + uri.scheme_str() == Some("https") + && uri.path() == "/" + && uri.query().is_none() + && uri.authority().is_some_and(|authority| { + endpoint.strip_prefix("https://") == Some(authority.as_str()) + && !authority.as_str().contains('@') + && authority.host().split('.').next() == Some(account.as_str()) + }) + }) + }); + if let Some(customized_credential_chain) = self.credential_providers { credential_providers = customized_credential_chain; } @@ -554,6 +572,7 @@ impl AzblobBuilder { // require a pre-generated `sas_token` for presigning. let azblob_can_presign = !self.config.skip_signature && (has_sas_token || (has_shared_key && !is_path_style_endpoint)); + let azblob_can_presign_read = azblob_can_presign || user_delegation_account.is_some(); // Restrict transactional CRC64 to the Azure Blob endpoints that enforce it. let azblob_can_checksum = endpoint @@ -610,9 +629,9 @@ impl AzblobBuilder { list: true, list_with_recursive: true, - presign: azblob_can_presign, + presign: azblob_can_presign_read, presign_stat: azblob_can_presign, - presign_read: azblob_can_presign, + presign_read: azblob_can_presign_read, presign_write: azblob_can_presign, shared: true, @@ -634,7 +653,9 @@ impl AzblobBuilder { sign_ctx: ctx, credential_provider, request_signer, + user_delegation_account, signers: HttpTransportCache::new(), + user_delegation_granters: HttpTransportCache::new(), }), }) } @@ -814,29 +835,46 @@ impl Service for AzblobBackend { } let req = match args.operation() { - PresignOperation::Stat(v) => self.core.azblob_head_blob_request(path, v), - PresignOperation::Read(range, v) => self.core.azblob_get_blob_request(path, *range, v), - PresignOperation::Write(v) if v.checksum().is_some() => Err(Error::new( - ErrorKind::Unsupported, - "azblob does not support checksums on presigned writes", - ) - .with_operation(Operation::Presign)), - PresignOperation::Write(v) => { + PresignOperation::Stat(v) if self.core.capability.presign_stat => { + self.core.azblob_head_blob_request(path, v)? + } + PresignOperation::Read(range, v) if self.core.capability.presign_read => { + self.core.azblob_get_blob_request(path, *range, v)? + } + PresignOperation::Write(v) if self.core.capability.presign_write => { + if v.checksum().is_some() { + return Err(Error::new( + ErrorKind::Unsupported, + "azblob does not support checksums on presigned writes", + ) + .with_operation(Operation::Presign)); + } self.core - .azblob_put_blob_request(path, None, v, Buffer::new()) + .azblob_put_blob_request(path, None, v, Buffer::new())? + } + PresignOperation::Delete(_) => { + return Err(Error::new( + ErrorKind::Unsupported, + "operation is not supported", + )); + } + _ => { + return Err(Error::new( + ErrorKind::Unsupported, + "presign operation is not supported", + )); } - PresignOperation::Delete(_) => Err(Error::new( - ErrorKind::Unsupported, - "operation is not supported", - )), - _ => Err(Error::new( - ErrorKind::Unsupported, - "presign operation is not supported", - )), }; - let req = req?; - let req = self.core.sign_query(ctx, req, args.expire()).await?; + let req = if matches!(args.operation(), PresignOperation::Read(..)) + && let Some(account) = &self.core.user_delegation_account + { + self.core + .sign_read_with_user_delegation(ctx, req, account, path, args.expire()) + .await? + } else { + self.core.sign_query(ctx, req, args.expire()).await? + }; let (parts, _) = req.into_parts(); @@ -1142,18 +1180,6 @@ mod tests { .unwrap_err(); assert_eq!(err.kind(), ErrorKind::Unsupported); - // Entra ID client credentials alone must not claim presign support. - let entra_op = Operator::new( - AzblobBuilder::default() - .container("test") - .endpoint("https://myaccount.blob.core.windows.net") - .client_id("client-123") - .client_secret("secret-123") - .tenant_id("tenant-123"), - ) - .unwrap(); - assert!(!entra_op.info().capability().presign); - // Empty or "?" sas_token and skip_signature must not enable presign. for sas_token in ["", "?"] { let op = Operator::from_config(AzblobConfig { @@ -1177,6 +1203,227 @@ mod tests { assert!(!skipped_op.info().capability().presign); } + #[derive(Clone)] + struct DelegationTransport { + identity: &'static str, + key: [u8; 32], + requests: Arc<std::sync::Mutex<Vec<&'static str>>>, + } + + impl DelegationTransport { + fn new(identity: &'static str, key: [u8; 32]) -> Self { + Self { + identity, + key, + requests: Arc::default(), + } + } + } + + impl HttpTransport for DelegationTransport { + async fn fetch(&self, req: http::Request<Buffer>) -> Result<http::Response<HttpBody>> { + assert_eq!(req.method(), http::Method::POST); + let body = match req.uri().host() { + Some("login.example.com") => { + assert_eq!(req.uri().path(), "/test-tenant/oauth2/v2.0/token"); + self.requests.lock().unwrap().push("token"); + Buffer::from(format!( + r#"{{"access_token":"{}","expires_in":3600}}"#, + self.identity + )) + } + Some("account1.blob.core.windows.net") => { + self.requests.lock().unwrap().push("delegation key"); + assert_eq!(req.uri().path(), "/"); + let query = parse_query_params(req.uri()); + assert_eq!(query.get("restype").map(String::as_str), Some("service")); + assert_eq!( + query.get("comp").map(String::as_str), + Some("userdelegationkey") + ); + assert_eq!( + req.headers()[http::header::AUTHORIZATION], + format!("Bearer {}", self.identity) + ); + let now = reqsign_core::time::Timestamp::now(); + let start = (now - Duration::from_secs(60)).format_rfc3339_zulu(); + let expiry = (now + Duration::from_secs(3600)).format_rfc3339_zulu(); + let version = req.headers()["x-ms-version"].to_str().unwrap(); + let key = BASE64_STANDARD.encode(self.key); + let identity = self.identity; + Buffer::from(format!( + "<UserDelegationKey><SignedOid>{identity}</SignedOid><SignedTid>test-tid</SignedTid>\ + <SignedStart>{start}</SignedStart><SignedExpiry>{expiry}</SignedExpiry>\ + <SignedService>b</SignedService><SignedVersion>{version}</SignedVersion>\ + <Value>{key}</Value></UserDelegationKey>" + )) + } + host => panic!("unexpected request host: {host:?}"), + }; + let size = body.len() as u64; + Ok(http::Response::new(HttpBody::new( + futures::stream::iter([Ok(body)]), + Some(size), + ))) + } + } + + fn assert_delegation_read( + request: &PresignedRequest, + transport: &DelegationTransport, + wire_path: &str, + blob: &str, + ) -> std::collections::HashMap<String, String> { + assert_eq!(request.method(), http::Method::GET); + assert_eq!(request.uri().scheme_str(), Some("https")); + assert_eq!(request.uri().host(), Some("account1.blob.core.windows.net")); + assert_eq!(request.uri().path(), wire_path); + assert!(!request.header().contains_key(http::header::AUTHORIZATION)); + let params = parse_query_params(request.uri()); + assert_eq!(params["sr"], "b"); + assert_eq!(params["sp"], "r"); + assert_eq!(params["spr"], "https"); + assert_eq!(params["skoid"], transport.identity); + + // Verify Azure's signature over the expected decoded resource name. + let resource = format!("/blob/account1/test/{blob}"); + let string_to_sign = [ + "r", + "", + ¶ms["se"], + &resource, + transport.identity, + "test-tid", + ¶ms["skt"], + ¶ms["ske"], + "b", + ¶ms["skv"], + "", + "", + "", + "", + "https", + ¶ms["sv"], + "b", + "", + "", + "", + "", + "", + "", + "", + ] + .join("\n"); + assert_eq!( + params["sig"], + reqsign_core::hash::base64_hmac_sha256(&transport.key, string_to_sign.as_bytes()) + ); + params + } + + #[tokio::test] + async fn client_secret_presigns_only_blob_reads() { + let transport = DelegationTransport::new("first-principal", [42; 32]); + let op = Operator::new( + AzblobBuilder::default() + .root("/root path/") + .container("test") + .endpoint("https://account1.blob.core.windows.net/") + .tenant_id("test-tenant") + .client_id("test-client") + .client_secret("test-secret") + .authority_host("https://login.example.com"), + ) + .unwrap() + .with_context( + OperationContext::new().with_http_transport(HttpTransporter::new(transport.clone())), + ); + let cap = op.info().capability(); + assert!(cap.presign); + assert!(cap.presign_read); + assert!(!cap.presign_stat); + assert!(!cap.presign_write); + assert!(!cap.presign_delete); + + let path = "folder/blob %.txt"; + let expiry = Duration::from_secs(120); + for err in [ + op.presign_stat(path, expiry).await.unwrap_err(), + op.presign_write(path, expiry).await.unwrap_err(), + op.presign_delete(path, expiry).await.unwrap_err(), + op.presign_read_with(path, expiry) + .override_content_disposition("attachment") + .await + .unwrap_err(), + ] { + assert_eq!(err.kind(), ErrorKind::Unsupported); + } + assert!(transport.requests.lock().unwrap().is_empty()); + + let before = reqsign_core::time::Timestamp::now(); + let request = op + .presign_read_with(path, expiry) + .if_match("\"etag\"") + .await + .unwrap(); + let after = reqsign_core::time::Timestamp::now(); + assert_eq!(request.header()[http::header::IF_MATCH], "\"etag\""); + let params = assert_delegation_read( + &request, + &transport, + "/test/root%20path/folder/blob%20%25.txt", + "root path/folder/blob %.txt", + ); + let signed_expiry = params["se"] + .parse::<reqsign_core::time::Timestamp>() + .unwrap(); + assert!(signed_expiry >= before + expiry - Duration::from_secs(1)); + assert!(signed_expiry <= after + expiry); + assert_eq!( + *transport.requests.lock().unwrap(), + ["token", "delegation key"] + ); + + let second = op + .presign_read("folder/other.txt", Duration::from_secs(60)) + .await + .unwrap(); + let second_params = assert_delegation_read( + &second, + &transport, + "/test/root%20path/folder/other.txt", + "root path/folder/other.txt", + ); + assert_ne!(params["sig"], second_params["sig"]); + assert_eq!( + *transport.requests.lock().unwrap(), + ["token", "delegation key"] + ); + assert_eq!(params["ske"], second_params["ske"]); + + let other_transport = DelegationTransport::new("second-principal", [43; 32]); + let other_ctx = op + .context() + .with_http_transport(HttpTransporter::new(other_transport.clone())); + let other = op.clone().with_context(other_ctx); + let request = other.presign_read(path, expiry).await.unwrap(); + let other_params = assert_delegation_read( + &request, + &other_transport, + "/test/root%20path/folder/blob%20%25.txt", + "root path/folder/blob %.txt", + ); + assert_ne!(params["sig"], other_params["sig"]); + assert_eq!( + *other_transport.requests.lock().unwrap(), + ["token", "delegation key"] + ); + assert_eq!( + *transport.requests.lock().unwrap(), + ["token", "delegation key"] + ); + } + #[tokio::test] async fn presign_honors_requested_expiration() { let key = BASE64_STANDARD.encode([42u8; 64]); @@ -1261,7 +1508,7 @@ mod tests { .build_backend() .unwrap(); - assert!(!backend.capability().presign); + assert!(backend.capability().presign_read); let http = MockTokenHttpSend::default(); let ctx = Context::new() diff --git a/core/services/azblob/src/core.rs b/core/services/azblob/src/core.rs index 905ea64de4..cd6901503f 100644 --- a/core/services/azblob/src/core.rs +++ b/core/services/azblob/src/core.rs @@ -38,8 +38,11 @@ use http::header::IF_NONE_MATCH; use http::header::IF_UNMODIFIED_SINCE; use opendal_service_azure_common::with_azure_error_response_context; use quick_xml::de; -use reqsign_azure_storage::{Credential, RequestSigner}; -use reqsign_core::{Context, ProvideCredentialDyn, Signer}; +use reqsign_azure_storage::{ + Credential, RequestSigner, UserDelegationSasGrant, UserDelegationSasGranter, + UserDelegationSasPermissions, +}; +use reqsign_core::{Context, Granter, ProvideCredentialDyn, SignRequest, Signer}; use serde::Deserialize; use serde::Serialize; use uuid::Uuid; @@ -97,7 +100,10 @@ pub struct AzblobCore { pub sign_ctx: Context, pub credential_provider: Arc<dyn ProvideCredentialDyn<Credential = Credential>>, pub request_signer: Arc<RequestSigner>, + pub user_delegation_account: Option<String>, pub signers: HttpTransportCache<Signer<Credential>>, + pub user_delegation_granters: + HttpTransportCache<(Granter<Credential>, UserDelegationSasGranter)>, } impl Debug for AzblobCore { @@ -150,6 +156,54 @@ impl AzblobCore { Ok(Request::from_parts(parts, body)) } + pub async fn sign_read_with_user_delegation( + &self, + ctx: &OperationContext, + req: Request<Buffer>, + account: &str, + path: &str, + duration: Duration, + ) -> Result<Request<Buffer>> { + // Reqsign's typed grant signs the blob name without response query overrides. + if req.uri().query().is_some() { + return Err(Error::new( + ErrorKind::Unsupported, + "azblob user delegation presign does not support read query options", + )); + } + + let grant = UserDelegationSasGrant::for_blob( + &self.container, + build_absolute_path(&self.root, path), + UserDelegationSasPermissions::READ, + ); + let (granter, operation) = + self.user_delegation_granters + .get_or_init(ctx.http_transport(), |transport| { + let operation = UserDelegationSasGranter::new(account, grant.clone()) + .with_trusted_endpoint(&self.endpoint); + let granter = Granter::new( + self.sign_ctx.clone().with_http_send(transport), + self.credential_provider.clone(), + operation.clone(), + ); + (granter, operation) + }); + // Bind the request's blob while retaining both Reqsign caches. + let credential = granter + .with_credential_granter(operation.with_grant(grant)) + .grant(Some(duration)) + .await + .map_err(|err| new_request_sign_error(err.into()))?; + + let (mut parts, body) = req.into_parts(); + self.request_signer + .sign_request(&self.sign_ctx, &mut parts, Some(&credential), None) + .await + .map_err(|err| new_request_sign_error(err.into()))?; + Ok(Request::from_parts(parts, body)) + } + pub async fn sign<T>(&self, ctx: &OperationContext, req: Request<T>) -> Result<Request<T>> { let (mut parts, body) = req.into_parts(); @@ -1074,7 +1128,9 @@ mod tests { sign_ctx: Context::new(), credential_provider: Arc::new(StaticCredentialProvider::new_shared_key("acc", "a2V5")), request_signer: Arc::new(RequestSigner::new()), + user_delegation_account: None, signers: HttpTransportCache::new(), + user_delegation_granters: HttpTransportCache::new(), } } diff --git a/core/services/azblob/src/docs.md b/core/services/azblob/src/docs.md index b5718f0042..b18d9aba69 100644 --- a/core/services/azblob/src/docs.md +++ b/core/services/azblob/src/docs.md @@ -15,12 +15,19 @@ Depending on its configuration and the backing system, this service can expose: Inspect the effective capability set with [`opendal_core::Operator::info`] and [`opendal_core::OperatorInfo::capability`] after building an operator. -Presigning (`presign_stat`, `presign_read`, and `presign_write`) requires -`skip_signature` to be disabled and either a pre-generated `sas_token` or -SharedKey credentials (`account_name` and `account_key`) with a host-style -endpoint such as `https://<account>.blob.core.windows.net`. Path-style -endpoints such as Azurite (`http://127.0.0.1:10000/<account>`) require a -pre-generated `sas_token` for presigning. +Presigning requires `skip_signature` to be disabled. A pre-generated +`sas_token` or SharedKey credentials (`account_name` and `account_key`) +with a host-style endpoint support `presign_stat`, `presign_read`, and +`presign_write`. Path-style endpoints such as Azurite +(`http://127.0.0.1:10000/<account>`) require a supplied `sas_token`. + +With explicit `tenant_id`, `client_id`, and `client_secret`, `presign_read` can +use a read-only user delegation SAS for the requested blob. Use a host-style +HTTPS Blob endpoint whose first DNS label matches the storage account. The +service principal needs permission to obtain a user delegation key on the +account and read the blob. Set a positive expiration of at most seven days. +Response content-disposition overrides return `Unsupported` with user +delegation SAS. Supplied SAS and SharedKey credentials take precedence. ### Write checksums diff --git a/dev/src/generate/capabilities_docs.rs b/dev/src/generate/capabilities_docs.rs index 06b0735c21..4200f14b23 100644 --- a/dev/src/generate/capabilities_docs.rs +++ b/dev/src/generate/capabilities_docs.rs @@ -706,6 +706,12 @@ fn describe_bool_condition(expr: &Expr, rel_path: &str) -> Result<String> { .to_string(), ); } + if ident == "azblob_can_presign_read" { + return Ok( + "Requires `sas_token`, a host-style endpoint with Shared Key, or explicit service principal credentials on a matching HTTPS Blob endpoint for reads, with `skip_signature` disabled" + .to_string(), + ); + } if ident == "azblob_can_presign" { return Ok( "Requires `sas_token` or a host-style endpoint with `account_key` (and `account_name`), with `skip_signature` disabled" @@ -1301,13 +1307,20 @@ mod tests { ); let azblob = out.services.iter().find(|s| s.scheme == "azblob").unwrap(); - assert_eq!( - azblob.native.get("presign"), - Some(&NativeBoolDoc::Conditional( - "Requires `sas_token` or a host-style endpoint with `account_key` (and `account_name`), with `skip_signature` disabled" - .to_string() - )) + let delegation = azblob.native.get("presign_read").unwrap(); + assert_eq!(azblob.native.get("presign"), Some(delegation)); + assert!( + matches!(delegation, NativeBoolDoc::Conditional(value) if value.contains("service principal")) ); + for operation in ["presign_stat", "presign_write"] { + assert_eq!( + azblob.native.get(operation), + Some(&NativeBoolDoc::Conditional( + "Requires `sas_token` or a host-style endpoint with `account_key` (and `account_name`), with `skip_signature` disabled" + .to_string() + )) + ); + } } #[test] diff --git a/website/data/capabilities.json b/website/data/capabilities.json index 37359b927c..e8b50bd318 100644 --- a/website/data/capabilities.json +++ b/website/data/capabilities.json @@ -880,8 +880,8 @@ "delete_with_if_none_match": true, "list": true, "list_with_recursive": true, - "presign": "Requires `sas_token` or a host-style endpoint with `account_key` (and `account_name`), with `skip_signature` disabled", - "presign_read": "Requires `sas_token` or a host-style endpoint with `account_key` (and `account_name`), with `skip_signature` disabled", + "presign": "Requires `sas_token`, a host-style endpoint with Shared Key, or explicit service principal credentials on a matching HTTPS Blob endpoint for reads, with `skip_signature` disabled", + "presign_read": "Requires `sas_token`, a host-style endpoint with Shared Key, or explicit service principal credentials on a matching HTTPS Blob endpoint for reads, with `skip_signature` disabled", "presign_stat": "Requires `sas_token` or a host-style endpoint with `account_key` (and `account_name`), with `skip_signature` disabled", "presign_write": "Requires `sas_token` or a host-style endpoint with `account_key` (and `account_name`), with `skip_signature` disabled", "read": true,
