You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@opendal.apache.org by xu...@apache.org on 2026/07/29 04:20:39 UTC
(opendal-reqsign) branch main updated: feat: add scoped credential granting with Azure user delegation SAS (#803)
This is an automated email from the ASF dual-hosted git repository.
Xuanwo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/opendal-reqsign.git
The following commit(s) were added to refs/heads/main by this push:
new f221055 feat: add scoped credential granting with Azure user delegation SAS (#803)
f221055 is described below
commit f221055541d17cf14372b848da0b37bf8b81c726
Author: Xuanwo <gi...@xuanwo.io>
AuthorDate: Wed Jul 29 12:20:35 2026 +0800
feat: add scoped credential granting with Azure user delegation SAS (#803)
## Overview
reqsign currently composes credential providers with request signers,
but it has no lifecycle abstraction for using a service credential to
issue another bounded, expiring credential in the same service family.
That leaves scoped credential vending to ad-hoc service APIs and makes
source credential caching, replacement isolation, post-I/O validity, and
redaction difficult to apply consistently.
This introduces `GrantCredential` and `Granter<K>` in `reqsign-core`.
`Granter<K>` loads and caches only the source credential, delegates
service-specific authorization semantics to `GrantCredential<K>`, and
returns credentials that remain directly consumable by the existing
`Signer<K>`. The contract standardizes orchestration and lifecycle
rather than imposing a cross-cloud scope model or promising strict
monotonic downscoping for every service.
Azure User Delegation SAS is the first reference implementation. It
exchanges a Bearer credential for a cached User Delegation Key,
validates the account, endpoint, resource, path prefix, permissions, and
time bounds, and emits an expiration-aware `Credential::SasToken`.
Adding expiration to that public variant is an intentional compatibility
evolution required for exact validity checks.
Closes #801.
Closes #751.
Closes #750.
Refs #749.
---
core/src/api.rs | 116 ++
core/src/granter.rs | 596 ++++++++
core/src/lib.rs | 4 +
core/src/signer.rs | 27 +-
services/azure-storage/src/credential.rs | 31 +-
services/azure-storage/src/lib.rs | 4 +
.../src/provide_credential/default.rs | 2 +-
.../azure-storage/src/provide_credential/env.rs | 2 +-
.../src/provide_credential/static_provider.rs | 34 +-
services/azure-storage/src/sign_request.rs | 159 +-
services/azure-storage/src/user_delegation.rs | 305 +++-
services/azure-storage/src/user_delegation_sas.rs | 1596 ++++++++++++++++++++
.../tests/credential_providers/default.rs | 1 +
.../tests/credential_providers/env.rs | 2 +-
.../tests/credential_providers/static_provider.rs | 2 +-
15 files changed, 2784 insertions(+), 97 deletions(-)
diff --git a/core/src/api.rs b/core/src/api.rs
index cb03aae..eb4b5d0 100644
--- a/core/src/api.rs
+++ b/core/src/api.rs
@@ -113,6 +113,122 @@ where
}
}
+/// Service-specific credential granting.
+///
+/// A granter uses an existing service credential to authorize one bounded,
+/// expiring credential transition. The source and result remain in the same
+/// service credential family, while the concrete implementation owns the
+/// service-specific resource, permission, policy, and identity semantics.
+///
+/// This trait standardizes orchestration and lifecycle, not a cross-service
+/// scope model, and does not promise that every service can express strict
+/// monotonic downscoping. Implementations must validate the concrete source
+/// credential variant before performing I/O. Returned credentials must own
+/// credential material that is independent from the source credential and
+/// must not retain or share its secret buffers. Implementations must also keep
+/// secrets out of [`Debug`] output and returned errors.
+pub trait GrantCredential: Debug + Send + Sync + Unpin + 'static {
+ /// Credential used as the source and returned as the granted result.
+ type Credential: SigningCredential;
+
+ /// Return the timestamp through which the source credential must remain usable.
+ ///
+ /// This method must not perform I/O or mutate state. It must conservatively
+ /// include any service I/O headroom unless current service-specific cache
+ /// state proves that the operation can complete without that I/O.
+ fn required_valid_until(
+ &self,
+ credential: &Self::Credential,
+ expires_in: Option<Duration>,
+ ) -> Timestamp;
+
+ /// Grant a bounded, expiring credential from an existing service credential.
+ ///
+ /// `expires_in` is a service-specific requested lifetime. `None` does not
+ /// mean that the returned credential may be non-expiring. After all I/O,
+ /// the implementation must ensure that the returned credential remains
+ /// exactly usable at the actual completion time and carries or reliably
+ /// derives its absolute expiration.
+ fn grant_credential<'a>(
+ &'a self,
+ ctx: &'a Context,
+ credential: &'a Self::Credential,
+ expires_in: Option<Duration>,
+ ) -> impl Future<Output = Result<Self::Credential>> + MaybeSend + 'a;
+}
+
+/// Dyn version of [`GrantCredential`].
+pub trait GrantCredentialDyn: Debug + Send + Sync + Unpin + 'static {
+ /// Credential used as the source and returned as the granted result.
+ type Credential: SigningCredential;
+
+ /// Dyn version of [`GrantCredential::required_valid_until`].
+ fn required_valid_until_dyn(
+ &self,
+ credential: &Self::Credential,
+ expires_in: Option<Duration>,
+ ) -> Timestamp;
+
+ /// Dyn version of [`GrantCredential::grant_credential`].
+ fn grant_credential_dyn<'a>(
+ &'a self,
+ ctx: &'a Context,
+ credential: &'a Self::Credential,
+ expires_in: Option<Duration>,
+ ) -> BoxedFuture<'a, Result<Self::Credential>>;
+}
+
+impl<T> GrantCredentialDyn for T
+where
+ T: GrantCredential + ?Sized,
+{
+ type Credential = T::Credential;
+
+ fn required_valid_until_dyn(
+ &self,
+ credential: &Self::Credential,
+ expires_in: Option<Duration>,
+ ) -> Timestamp {
+ self.required_valid_until(credential, expires_in)
+ }
+
+ fn grant_credential_dyn<'a>(
+ &'a self,
+ ctx: &'a Context,
+ credential: &'a Self::Credential,
+ expires_in: Option<Duration>,
+ ) -> BoxedFuture<'a, Result<Self::Credential>> {
+ Box::pin(self.grant_credential(ctx, credential, expires_in))
+ }
+}
+
+impl<T> GrantCredential for std::sync::Arc<T>
+where
+ T: GrantCredentialDyn + ?Sized,
+{
+ type Credential = T::Credential;
+
+ fn required_valid_until(
+ &self,
+ credential: &Self::Credential,
+ expires_in: Option<Duration>,
+ ) -> Timestamp {
+ self.deref()
+ .required_valid_until_dyn(credential, expires_in)
+ }
+
+ async fn grant_credential(
+ &self,
+ ctx: &Context,
+ credential: &Self::Credential,
+ expires_in: Option<Duration>,
+ ) -> Result<Self::Credential> {
+ self.deref()
+ .grant_credential_dyn(ctx, credential, expires_in)
+ .await
+ }
+}
+
/// Service-specific request signing.
///
/// Implementations receive a request URI that is already percent-encoded and ready
diff --git a/core/src/granter.rs b/core/src/granter.rs
new file mode 100644
index 0000000..4c47684
--- /dev/null
+++ b/core/src/granter.rs
@@ -0,0 +1,596 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use crate::time::Timestamp;
+use crate::{
+ Context, Error, GrantCredential, GrantCredentialDyn, ProvideCredential, ProvideCredentialDyn,
+ Result, SigningCredential,
+};
+use std::any::type_name;
+use std::fmt::{Debug, Formatter};
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+/// Loads a source credential and grants a bounded service credential.
+///
+/// `Granter` caches only the source credential. Every call to [`Granter::grant`]
+/// invokes the configured service granter and validates the returned credential
+/// after all granting I/O has completed. Granted outputs are never cached or
+/// written back into the source cache.
+#[derive(Clone)]
+pub struct Granter<K: SigningCredential> {
+ ctx: Context,
+ provider: Arc<dyn ProvideCredentialDyn<Credential = K>>,
+ granter: Arc<dyn GrantCredentialDyn<Credential = K>>,
+ credential: Arc<Mutex<Option<K>>>,
+}
+
+impl<K: SigningCredential> Debug for Granter<K> {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("Granter")
+ .field("credential_type", &type_name::<K>())
+ .finish_non_exhaustive()
+ }
+}
+
+impl<K: SigningCredential> Granter<K> {
+ /// Create a granter from a context, source provider, and bound granting operation.
+ pub fn new(
+ ctx: Context,
+ provider: impl ProvideCredential<Credential = K>,
+ granter: impl GrantCredential<Credential = K>,
+ ) -> Self {
+ Self {
+ ctx,
+ provider: Arc::new(provider),
+ granter: Arc::new(granter),
+ credential: Arc::new(Mutex::new(None)),
+ }
+ }
+
+ /// Replace the context and create an isolated empty source credential cache.
+ pub fn with_context(mut self, ctx: Context) -> Self {
+ self.ctx = ctx;
+ self.credential = Arc::new(Mutex::new(None));
+ self
+ }
+
+ /// Replace the source provider and create an isolated empty source credential cache.
+ pub fn with_credential_provider(
+ mut self,
+ provider: impl ProvideCredential<Credential = K>,
+ ) -> Self {
+ self.provider = Arc::new(provider);
+ self.credential = Arc::new(Mutex::new(None));
+ self
+ }
+
+ /// Replace the granting operation while retaining the shared source credential cache.
+ ///
+ /// The replacement operation must accept the same service credential family and
+ /// must still validate the same concrete source credential variant before
+ /// doing I/O. The service operation owns any service-specific intermediate
+ /// cache; `Granter` does not transfer such state from the old operation.
+ pub fn with_credential_granter(
+ mut self,
+ granter: impl GrantCredential<Credential = K>,
+ ) -> Self {
+ self.granter = Arc::new(granter);
+ self
+ }
+
+ /// Grant a bounded service credential.
+ ///
+ /// Cached source credentials must be fresh according to
+ /// [`SigningCredential::is_valid`] and usable through the service granter's
+ /// required deadline. A refreshed source credential only needs to satisfy
+ /// the exact deadline. Provider and granting errors are returned without
+ /// retry or fallback. The granted result must own material independent from
+ /// the cached source credential.
+ pub async fn grant(&self, expires_in: Option<Duration>) -> Result<K> {
+ let credential = self.credential.lock().expect("lock poisoned").clone();
+ let credential = match credential {
+ Some(credential)
+ if credential.is_valid()
+ && credential.is_valid_at(
+ self.granter
+ .required_valid_until_dyn(&credential, expires_in),
+ ) =>
+ {
+ credential
+ }
+ _ => {
+ let credential = self
+ .provider
+ .provide_credential_dyn(&self.ctx)
+ .await?
+ .ok_or_else(|| {
+ Error::credential_invalid("failed to load source credential")
+ .with_context(format!("credential_type: {}", type_name::<K>()))
+ })?;
+
+ let required_until = self
+ .granter
+ .required_valid_until_dyn(&credential, expires_in);
+ if !credential.is_valid_at(required_until) {
+ return Err(Error::credential_invalid(
+ "refreshed source credential expires before the granting deadline",
+ )
+ .with_context(format!("credential_type: {}", type_name::<K>()))
+ .with_context(format!("required_valid_until: {required_until}")));
+ }
+
+ *self.credential.lock().expect("lock poisoned") = Some(credential.clone());
+ credential
+ }
+ };
+
+ let granted = self
+ .granter
+ .grant_credential_dyn(&self.ctx, &credential, expires_in)
+ .await?;
+ let now = Timestamp::now();
+ if !granted.is_valid_at(now) {
+ return Err(
+ Error::credential_invalid("granted credential is not currently usable")
+ .with_context(format!("credential_type: {}", type_name::<K>()))
+ .with_context(format!("validated_at: {now}")),
+ );
+ }
+
+ Ok(granted)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::time::Timestamp;
+ use crate::{ErrorKind, GrantCredentialDyn, StaticEnv};
+ use std::collections::HashMap;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ #[derive(Clone)]
+ struct TestCredential {
+ generation: usize,
+ fresh: bool,
+ expires_at: Timestamp,
+ secret: Arc<String>,
+ }
+
+ impl Debug for TestCredential {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("TestCredential")
+ .field("generation", &self.generation)
+ .field("secret", &self.secret)
+ .finish()
+ }
+ }
+
+ impl SigningCredential for TestCredential {
+ fn is_valid(&self) -> bool {
+ self.fresh && self.is_valid_at(Timestamp::now() + Duration::from_secs(20))
+ }
+
+ fn is_valid_at(&self, timestamp: Timestamp) -> bool {
+ !self.secret.is_empty() && self.expires_at > timestamp
+ }
+ }
+
+ #[derive(Clone)]
+ struct CountingProvider {
+ calls: Arc<AtomicUsize>,
+ secret: Arc<String>,
+ expires_at: Timestamp,
+ fresh: bool,
+ }
+
+ impl Debug for CountingProvider {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("CountingProvider")
+ .field("secret", &self.secret)
+ .finish()
+ }
+ }
+
+ impl CountingProvider {
+ fn new(secret: &str, expires_at: Timestamp) -> (Self, Arc<AtomicUsize>) {
+ let calls = Arc::new(AtomicUsize::new(0));
+ (
+ Self {
+ calls: calls.clone(),
+ secret: Arc::new(secret.to_string()),
+ expires_at,
+ fresh: true,
+ },
+ calls,
+ )
+ }
+
+ fn with_fresh(mut self, fresh: bool) -> Self {
+ self.fresh = fresh;
+ self
+ }
+ }
+
+ impl ProvideCredential for CountingProvider {
+ type Credential = TestCredential;
+
+ async fn provide_credential(&self, ctx: &Context) -> Result<Option<Self::Credential>> {
+ let call = self.calls.fetch_add(1, Ordering::SeqCst) + 1;
+ let generation = ctx
+ .env_var("generation")
+ .and_then(|value| value.parse().ok())
+ .unwrap_or(call);
+ Ok(Some(TestCredential {
+ generation,
+ fresh: self.fresh,
+ expires_at: self.expires_at,
+ secret: self.secret.clone(),
+ }))
+ }
+ }
+
+ #[derive(Clone)]
+ struct CountingGranter {
+ calls: Arc<AtomicUsize>,
+ required_until: Timestamp,
+ output_expires_at: Timestamp,
+ secret: Arc<String>,
+ }
+
+ impl Debug for CountingGranter {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("CountingGranter")
+ .field("secret", &self.secret)
+ .finish()
+ }
+ }
+
+ impl CountingGranter {
+ fn new(
+ secret: &str,
+ required_until: Timestamp,
+ output_expires_at: Timestamp,
+ ) -> (Self, Arc<AtomicUsize>) {
+ let calls = Arc::new(AtomicUsize::new(0));
+ (
+ Self {
+ calls: calls.clone(),
+ required_until,
+ output_expires_at,
+ secret: Arc::new(secret.to_string()),
+ },
+ calls,
+ )
+ }
+ }
+
+ impl GrantCredential for CountingGranter {
+ type Credential = TestCredential;
+
+ fn required_valid_until(
+ &self,
+ _credential: &Self::Credential,
+ _expires_in: Option<Duration>,
+ ) -> Timestamp {
+ self.required_until
+ }
+
+ async fn grant_credential(
+ &self,
+ _ctx: &Context,
+ credential: &Self::Credential,
+ _expires_in: Option<Duration>,
+ ) -> Result<Self::Credential> {
+ let call = self.calls.fetch_add(1, Ordering::SeqCst) + 1;
+ Ok(TestCredential {
+ generation: credential.generation * 100 + call,
+ fresh: true,
+ expires_at: self.output_expires_at,
+ secret: Arc::new(format!("granted-{call}")),
+ })
+ }
+ }
+
+ #[derive(Clone)]
+ struct ErrorProvider {
+ calls: Arc<AtomicUsize>,
+ }
+
+ impl Debug for ErrorProvider {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("ErrorProvider").finish_non_exhaustive()
+ }
+ }
+
+ impl ProvideCredential for ErrorProvider {
+ type Credential = TestCredential;
+
+ async fn provide_credential(&self, _ctx: &Context) -> Result<Option<Self::Credential>> {
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ Err(Error::unexpected("source provider failed"))
+ }
+ }
+
+ #[derive(Clone)]
+ struct FailOnceGranter {
+ calls: Arc<AtomicUsize>,
+ required_until: Timestamp,
+ output_expires_at: Timestamp,
+ }
+
+ impl Debug for FailOnceGranter {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("FailOnceGranter").finish_non_exhaustive()
+ }
+ }
+
+ impl GrantCredential for FailOnceGranter {
+ type Credential = TestCredential;
+
+ fn required_valid_until(
+ &self,
+ _credential: &Self::Credential,
+ _expires_in: Option<Duration>,
+ ) -> Timestamp {
+ self.required_until
+ }
+
+ async fn grant_credential(
+ &self,
+ _ctx: &Context,
+ credential: &Self::Credential,
+ _expires_in: Option<Duration>,
+ ) -> Result<Self::Credential> {
+ let call = self.calls.fetch_add(1, Ordering::SeqCst) + 1;
+ if call == 1 {
+ return Err(Error::unexpected("grant operation failed"));
+ }
+ Ok(TestCredential {
+ generation: credential.generation * 100 + call,
+ fresh: true,
+ expires_at: self.output_expires_at,
+ secret: Arc::new(format!("granted-{call}")),
+ })
+ }
+ }
+
+ fn future_timestamp(seconds: u64) -> Timestamp {
+ Timestamp::now() + Duration::from_secs(seconds)
+ }
+
+ fn context_with_generation(generation: usize) -> Context {
+ Context::new().with_env(StaticEnv {
+ home_dir: None,
+ envs: HashMap::from([("generation".to_string(), generation.to_string())]),
+ })
+ }
+
+ #[test]
+ fn dyn_bridge_forwards_deadline_and_grant() {
+ let required_until = future_timestamp(60);
+ let output_expires_at = future_timestamp(120);
+ let (operation, calls) =
+ CountingGranter::new("operation-secret", required_until, output_expires_at);
+ let operation: Arc<dyn GrantCredentialDyn<Credential = TestCredential>> =
+ Arc::new(operation);
+ let credential = TestCredential {
+ generation: 4,
+ fresh: true,
+ expires_at: future_timestamp(120),
+ secret: Arc::new("source-secret".to_string()),
+ };
+
+ assert_eq!(
+ operation.required_valid_until(&credential, None),
+ required_until
+ );
+ let granted = futures::executor::block_on(operation.grant_credential(
+ &Context::new(),
+ &credential,
+ None,
+ ))
+ .expect("dyn grant must succeed");
+
+ assert_eq!(granted.generation, 401);
+ assert_eq!(calls.load(Ordering::SeqCst), 1);
+ }
+
+ #[test]
+ fn caches_only_source_and_shares_it_across_clones() {
+ let (provider, provider_calls) =
+ CountingProvider::new("provider-secret", future_timestamp(300));
+ let source_secret = provider.secret.clone();
+ let (operation, operation_calls) = CountingGranter::new(
+ "operation-secret",
+ future_timestamp(30),
+ future_timestamp(120),
+ );
+ let granter = Granter::new(context_with_generation(7), provider, operation);
+
+ let first = futures::executor::block_on(granter.grant(None)).expect("grant must succeed");
+ let second =
+ futures::executor::block_on(granter.clone().grant(None)).expect("grant must succeed");
+
+ assert_eq!(first.generation, 701);
+ assert_eq!(second.generation, 702);
+ assert_eq!(provider_calls.load(Ordering::SeqCst), 1);
+ assert_eq!(operation_calls.load(Ordering::SeqCst), 2);
+ assert!(!Arc::ptr_eq(&first.secret, &source_secret));
+ assert!(!Arc::ptr_eq(&second.secret, &source_secret));
+ }
+
+ #[test]
+ fn replacements_follow_source_cache_isolation_contract() {
+ let (provider, provider_calls) =
+ CountingProvider::new("provider-secret", future_timestamp(300));
+ let (operation, _) = CountingGranter::new(
+ "operation-secret",
+ future_timestamp(30),
+ future_timestamp(120),
+ );
+ let granter = Granter::new(context_with_generation(1), provider, operation);
+ futures::executor::block_on(granter.grant(None)).expect("initial grant must succeed");
+
+ let (replacement_operation, _) = CountingGranter::new(
+ "replacement-operation-secret",
+ future_timestamp(30),
+ future_timestamp(120),
+ );
+ let replacement = granter
+ .clone()
+ .with_credential_granter(replacement_operation);
+ let granted = futures::executor::block_on(replacement.grant(None))
+ .expect("operation replacement must reuse source");
+ assert_eq!(granted.generation / 100, 1);
+ assert_eq!(provider_calls.load(Ordering::SeqCst), 1);
+
+ let isolated_context = granter.clone().with_context(context_with_generation(2));
+ let granted = futures::executor::block_on(isolated_context.grant(None))
+ .expect("context replacement must reload source");
+ assert_eq!(granted.generation / 100, 2);
+ assert_eq!(provider_calls.load(Ordering::SeqCst), 2);
+
+ let (replacement_provider, replacement_provider_calls) =
+ CountingProvider::new("replacement-provider-secret", future_timestamp(300));
+ let isolated_provider = granter.with_credential_provider(replacement_provider);
+ futures::executor::block_on(isolated_provider.grant(None))
+ .expect("provider replacement must reload source");
+ assert_eq!(replacement_provider_calls.load(Ordering::SeqCst), 1);
+ }
+
+ #[test]
+ fn rejects_unusable_source_without_caching_it() {
+ let required_until = future_timestamp(120);
+ let (provider, provider_calls) =
+ CountingProvider::new("source-secret", future_timestamp(60));
+ let (operation, operation_calls) =
+ CountingGranter::new("operation-secret", required_until, future_timestamp(180));
+ let granter = Granter::new(Context::new(), provider, operation);
+
+ for _ in 0..2 {
+ let err = futures::executor::block_on(granter.grant(None))
+ .expect_err("short-lived source must be rejected");
+ assert_eq!(err.kind(), ErrorKind::CredentialInvalid);
+ assert!(!format!("{err:?}").contains("source-secret"));
+ }
+
+ assert_eq!(provider_calls.load(Ordering::SeqCst), 2);
+ assert_eq!(operation_calls.load(Ordering::SeqCst), 0);
+ }
+
+ #[test]
+ fn refreshed_source_needs_exact_validity_but_is_not_reused_when_stale() {
+ let (provider, provider_calls) =
+ CountingProvider::new("source-secret", future_timestamp(300));
+ let provider = provider.with_fresh(false);
+ let (operation, operation_calls) = CountingGranter::new(
+ "operation-secret",
+ future_timestamp(30),
+ future_timestamp(120),
+ );
+ let granter = Granter::new(Context::new(), provider, operation);
+
+ futures::executor::block_on(granter.grant(None))
+ .expect("exact-valid refreshed source must be accepted");
+ futures::executor::block_on(granter.grant(None))
+ .expect("stale cached source must be refreshed again");
+
+ assert_eq!(provider_calls.load(Ordering::SeqCst), 2);
+ assert_eq!(operation_calls.load(Ordering::SeqCst), 2);
+ }
+
+ #[test]
+ fn provider_and_grant_errors_do_not_create_output_cache_state() {
+ let provider_calls = Arc::new(AtomicUsize::new(0));
+ let (operation, operation_calls) = CountingGranter::new(
+ "operation-secret",
+ future_timestamp(30),
+ future_timestamp(120),
+ );
+ let provider_error = Granter::new(
+ Context::new(),
+ ErrorProvider {
+ calls: provider_calls.clone(),
+ },
+ operation,
+ );
+ for _ in 0..2 {
+ futures::executor::block_on(provider_error.grant(None))
+ .expect_err("provider error must be returned");
+ }
+ assert_eq!(provider_calls.load(Ordering::SeqCst), 2);
+ assert_eq!(operation_calls.load(Ordering::SeqCst), 0);
+
+ let (provider, provider_calls) =
+ CountingProvider::new("source-secret", future_timestamp(300));
+ let grant_calls = Arc::new(AtomicUsize::new(0));
+ let granter = Granter::new(
+ Context::new(),
+ provider,
+ FailOnceGranter {
+ calls: grant_calls.clone(),
+ required_until: future_timestamp(30),
+ output_expires_at: future_timestamp(120),
+ },
+ );
+ futures::executor::block_on(granter.grant(None))
+ .expect_err("first grant error must be returned");
+ let output = futures::executor::block_on(granter.grant(None))
+ .expect("second grant must execute again");
+
+ assert_eq!(output.generation, 102);
+ assert_eq!(provider_calls.load(Ordering::SeqCst), 1);
+ assert_eq!(grant_calls.load(Ordering::SeqCst), 2);
+ }
+
+ #[test]
+ fn rejects_output_that_is_expired_after_granting() {
+ let (provider, _) = CountingProvider::new("source-secret", future_timestamp(120));
+ let (operation, _) = CountingGranter::new(
+ "operation-secret",
+ future_timestamp(30),
+ Timestamp::now() - Duration::from_secs(1),
+ );
+ let granter = Granter::new(Context::new(), provider, operation);
+
+ let err = futures::executor::block_on(granter.grant(None))
+ .expect_err("expired output must be rejected");
+ assert_eq!(err.kind(), ErrorKind::CredentialInvalid);
+ assert!(!format!("{err:?}").contains("source-secret"));
+ assert!(!format!("{err:?}").contains("operation-secret"));
+ }
+
+ #[test]
+ fn debug_is_opaque_even_after_source_is_cached() {
+ let (provider, _) = CountingProvider::new("provider-secret", future_timestamp(300));
+ let (operation, _) = CountingGranter::new(
+ "operation-secret",
+ future_timestamp(30),
+ future_timestamp(120),
+ );
+ let granter = Granter::new(Context::new(), provider, operation);
+ futures::executor::block_on(granter.grant(None)).expect("grant must succeed");
+
+ let debug = format!("{granter:?}");
+ assert!(debug.starts_with("Granter"));
+ assert!(!debug.contains("provider-secret"));
+ assert!(!debug.contains("operation-secret"));
+ assert!(!debug.contains("granted-"));
+ }
+}
diff --git a/core/src/lib.rs b/core/src/lib.rs
index d453ea1..5432092 100644
--- a/core/src/lib.rs
+++ b/core/src/lib.rs
@@ -208,6 +208,8 @@ pub use context::OsEnv;
pub use context::StaticEnv;
mod api;
+pub use api::GrantCredential;
+pub use api::GrantCredentialDyn;
pub use api::ProvideCredential;
pub use api::ProvideCredentialChain;
pub use api::ProvideCredentialDyn;
@@ -218,3 +220,5 @@ mod request;
pub use request::{SigningMethod, SigningRequest};
mod signer;
pub use signer::Signer;
+mod granter;
+pub use granter::Granter;
diff --git a/core/src/signer.rs b/core/src/signer.rs
index 8d7c378..663c95d 100644
--- a/core/src/signer.rs
+++ b/core/src/signer.rs
@@ -24,6 +24,7 @@ use crate::SignRequest;
use crate::SignRequestDyn;
use crate::SigningCredential;
use std::any::type_name;
+use std::fmt::{Debug, Formatter};
use std::sync::{Arc, Mutex};
use std::time::Duration;
@@ -31,7 +32,7 @@ use std::time::Duration;
///
/// The service-specific [`SignRequest`] runs against a private candidate. Only the
/// candidate URI and headers are committed after successful signing.
-#[derive(Clone, Debug)]
+#[derive(Clone)]
pub struct Signer<K: SigningCredential> {
ctx: Context,
loader: Arc<dyn ProvideCredentialDyn<Credential = K>>,
@@ -39,6 +40,14 @@ pub struct Signer<K: SigningCredential> {
credential: Arc<Mutex<Option<K>>>,
}
+impl<K: SigningCredential> Debug for Signer<K> {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("Signer")
+ .field("credential_type", &type_name::<K>())
+ .finish_non_exhaustive()
+ }
+}
+
impl<K: SigningCredential> Signer<K> {
/// Create a new signer.
pub fn new(
@@ -497,4 +506,20 @@ mod tests {
Some(&HeaderValue::from_static("2"))
);
}
+
+ #[test]
+ fn debug_is_opaque() {
+ let signer = Signer::new(
+ Context::new(),
+ StaticProvider,
+ MutatingSigner { fail: false },
+ );
+ *signer.credential.lock().expect("lock poisoned") = Some(TestCredential);
+
+ let debug = format!("{signer:?}");
+ assert!(debug.starts_with("Signer"));
+ assert!(!debug.contains("StaticProvider"));
+ assert!(!debug.contains("MutatingSigner"));
+ assert!(!debug.contains("credential:"));
+ }
}
diff --git a/services/azure-storage/src/credential.rs b/services/azure-storage/src/credential.rs
index d164491..81e34b9 100644
--- a/services/azure-storage/src/credential.rs
+++ b/services/azure-storage/src/credential.rs
@@ -35,6 +35,8 @@ pub enum Credential {
SasToken {
/// SAS token.
token: String,
+ /// Optional absolute expiration time for this SAS token.
+ expires_at: Option<Timestamp>,
},
/// Bearer token for OAuth authentication
BearerToken {
@@ -56,9 +58,10 @@ impl Debug for Credential {
.field("account_name", &Redact::from(account_name))
.field("account_key", &Redact::from(account_key))
.finish(),
- Credential::SasToken { token } => f
+ Credential::SasToken { token, expires_at } => f
.debug_struct("Credential::SasToken")
.field("token", &Redact::from(token))
+ .field("expires_at", expires_at)
.finish(),
Credential::BearerToken { token, expires_in } => f
.debug_struct("Credential::BearerToken")
@@ -80,7 +83,9 @@ impl SigningCredential for Credential {
account_name,
account_key,
} => !account_name.is_empty() && !account_key.is_empty(),
- Credential::SasToken { token } => !token.is_empty(),
+ Credential::SasToken { token, expires_at } => {
+ !token.is_empty() && expires_at.is_none_or(|expires| expires > timestamp)
+ }
Credential::BearerToken { token, expires_in } => {
if token.is_empty() {
return false;
@@ -104,6 +109,15 @@ impl Credential {
pub fn with_sas_token(sas_token: &str) -> Self {
Self::SasToken {
token: sas_token.to_string(),
+ expires_at: None,
+ }
+ }
+
+ /// Create a new credential with an expiring SAS token.
+ pub fn with_sas_token_expires_at(sas_token: &str, expires_at: Timestamp) -> Self {
+ Self::SasToken {
+ token: sas_token.to_string(),
+ expires_at: Some(expires_at),
}
}
@@ -130,4 +144,17 @@ mod tests {
assert!(credential.is_valid_at(now + Duration::from_secs(5)));
assert!(!credential.is_valid_at(now + Duration::from_secs(10)));
}
+
+ #[test]
+ fn separates_sas_cache_freshness_from_exact_validity() {
+ let now = Timestamp::now();
+ let credential = Credential::with_sas_token_expires_at(
+ "sv=2020-12-06&sig=secret",
+ now + Duration::from_secs(10),
+ );
+
+ assert!(!credential.is_valid());
+ assert!(credential.is_valid_at(now + Duration::from_secs(5)));
+ assert!(!credential.is_valid_at(now + Duration::from_secs(10)));
+ }
}
diff --git a/services/azure-storage/src/lib.rs b/services/azure-storage/src/lib.rs
index 21c4581..65973c0 100644
--- a/services/azure-storage/src/lib.rs
+++ b/services/azure-storage/src/lib.rs
@@ -173,11 +173,15 @@
mod constants;
mod service_sas;
mod user_delegation;
+mod user_delegation_sas;
mod credential;
pub use credential::Credential;
pub use service_sas::{ServiceSasResource, ServiceSharedAccessSignature};
+pub use user_delegation_sas::{
+ SasProtocol, UserDelegationSasGrant, UserDelegationSasGranter, UserDelegationSasPermissions,
+};
mod sign_request;
pub use sign_request::RequestSigner;
diff --git a/services/azure-storage/src/provide_credential/default.rs b/services/azure-storage/src/provide_credential/default.rs
index cd2dc49..1ae5d8a 100644
--- a/services/azure-storage/src/provide_credential/default.rs
+++ b/services/azure-storage/src/provide_credential/default.rs
@@ -326,7 +326,7 @@ mod tests {
let cred = loader.provide_credential(&ctx).await.unwrap().unwrap();
match cred {
- crate::Credential::SasToken { token } => {
+ crate::Credential::SasToken { token, .. } => {
assert_eq!(token, "sv=2021-01-01&ss=b&srt=c&sp=rwdlaciytfx");
}
_ => panic!("Expected SasToken credential"),
diff --git a/services/azure-storage/src/provide_credential/env.rs b/services/azure-storage/src/provide_credential/env.rs
index 8be2368..835ce8d 100644
--- a/services/azure-storage/src/provide_credential/env.rs
+++ b/services/azure-storage/src/provide_credential/env.rs
@@ -126,7 +126,7 @@ mod tests {
let cred = provider.provide_credential(&ctx).await.unwrap();
match cred {
- Some(Credential::SasToken { token }) => {
+ Some(Credential::SasToken { token, .. }) => {
assert_eq!(token, "mysastoken");
}
_ => panic!("Expected SasToken credential"),
diff --git a/services/azure-storage/src/provide_credential/static_provider.rs b/services/azure-storage/src/provide_credential/static_provider.rs
index 159a5e7..392c6a0 100644
--- a/services/azure-storage/src/provide_credential/static_provider.rs
+++ b/services/azure-storage/src/provide_credential/static_provider.rs
@@ -15,6 +15,7 @@
// specific language governing permissions and limitations
// under the License.
+use reqsign_core::time::Timestamp;
use reqsign_core::{Context, ProvideCredential};
use crate::credential::Credential;
@@ -25,18 +26,28 @@ pub struct StaticCredentialProvider {
}
impl StaticCredentialProvider {
+ /// Create a provider for a static Azure Storage shared key.
pub fn new_shared_key(account_name: &str, account_key: &str) -> Self {
Self {
credential: Credential::with_shared_key(account_name, account_key),
}
}
+ /// Create a provider for a static SAS token with unknown expiration.
pub fn new_sas_token(sas_token: &str) -> Self {
Self {
credential: Credential::with_sas_token(sas_token),
}
}
+ /// Create a provider for a static SAS token with an absolute expiration.
+ pub fn new_sas_token_expires_at(sas_token: &str, expires_at: Timestamp) -> Self {
+ Self {
+ credential: Credential::with_sas_token_expires_at(sas_token, expires_at),
+ }
+ }
+
+ /// Create a provider for a static bearer token with unknown expiration.
pub fn new_bearer_token(bearer_token: &str) -> Self {
Self {
credential: Credential::with_bearer_token(bearer_token, None),
@@ -92,13 +103,34 @@ mod tests {
let cred = provider.provide_credential(&ctx).await.unwrap();
match cred {
- Some(Credential::SasToken { token }) => {
+ Some(Credential::SasToken { token, .. }) => {
assert_eq!(token, "mysastoken");
}
_ => panic!("Expected SasToken credential"),
}
}
+ #[tokio::test]
+ async fn test_static_credential_provider_expiring_sas_token() {
+ let expires_at = Timestamp::now() + std::time::Duration::from_secs(60);
+ let provider = StaticCredentialProvider::new_sas_token_expires_at("mysastoken", expires_at);
+ let credential = provider
+ .provide_credential(&Context::new())
+ .await
+ .expect("provider must succeed");
+
+ match credential {
+ Some(Credential::SasToken {
+ token,
+ expires_at: Some(actual),
+ }) => {
+ assert_eq!(token, "mysastoken");
+ assert_eq!(actual, expires_at);
+ }
+ other => panic!("expected expiring SAS token, got {other:?}"),
+ }
+ }
+
#[tokio::test]
async fn test_static_credential_provider_bearer_token() {
let provider = StaticCredentialProvider::new_bearer_token("mybearertoken");
diff --git a/services/azure-storage/src/sign_request.rs b/services/azure-storage/src/sign_request.rs
index 83f5ebc..b9c843c 100644
--- a/services/azure-storage/src/sign_request.rs
+++ b/services/azure-storage/src/sign_request.rs
@@ -17,6 +17,10 @@
use crate::Credential;
use crate::constants::*;
+use crate::user_delegation::{
+ MAX_USER_DELEGATION_KEY_LIFETIME, UserDelegationKeyCache, ceil_to_wire_second,
+ floor_to_wire_second, user_delegation_key_covers,
+};
use http::request::Parts;
use http::{HeaderValue, Uri, header};
use log::debug;
@@ -27,6 +31,7 @@ use reqsign_core::{
Context, Result, SignRequest, SigningCredential, SigningMethod, SigningRequest,
};
use std::fmt::Write;
+use std::fmt::{Debug, Formatter};
use std::sync::Mutex;
use std::time::Duration;
@@ -44,7 +49,6 @@ pub enum SasResourceKind {
/// RequestSigner that implement Azure Storage Shared Key Authorization.
///
/// - [Authorize with Shared Key](https://docs.microsoft.com/en-us/rest/api/storageservices/authorize-with-shared-key)
-#[derive(Debug)]
pub struct RequestSigner {
time: Option<Timestamp>,
service_sas_permissions: Option<String>,
@@ -54,7 +58,7 @@ pub struct RequestSigner {
service_sas_version: Option<String>,
user_delegation_presign: Option<UserDelegationPresignConfig>,
- user_delegation_key_cache: Mutex<Option<crate::user_delegation::UserDelegationKey>>,
+ user_delegation_key_cache: Mutex<UserDelegationKeyCache<UserDelegationPresignCacheKey>>,
}
#[derive(Clone, Debug)]
@@ -67,6 +71,20 @@ struct UserDelegationPresignConfig {
version: Option<String>,
}
+#[derive(Clone, PartialEq, Eq, Hash)]
+struct UserDelegationPresignCacheKey {
+ account: String,
+ endpoint: String,
+ source_authority: String,
+ version: String,
+}
+
+impl Debug for RequestSigner {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("RequestSigner").finish_non_exhaustive()
+ }
+}
+
impl RequestSigner {
/// Create a new builder for Azure Storage signer.
pub fn new() -> Self {
@@ -79,7 +97,7 @@ impl RequestSigner {
service_sas_version: None,
user_delegation_presign: None,
- user_delegation_key_cache: Mutex::new(None),
+ user_delegation_key_cache: Mutex::new(UserDelegationKeyCache::default()),
}
}
@@ -186,27 +204,10 @@ impl RequestSigner {
&self,
credential: &Credential,
signing_time: Timestamp,
- expires_in: Option<Duration>,
+ _expires_in: Option<Duration>,
) -> Timestamp {
match credential {
- Credential::BearerToken { .. } => {
- let cached_key_covers_operation = expires_in.is_some_and(|expires| {
- self.user_delegation_key_cache
- .lock()
- .expect("lock poisoned")
- .as_ref()
- .is_some_and(|key| {
- key.signed_expiry
- > signing_time + expires + BEARER_TOKEN_OPERATION_HEADROOM
- })
- });
-
- if cached_key_covers_operation {
- signing_time
- } else {
- signing_time + BEARER_TOKEN_OPERATION_HEADROOM
- }
- }
+ Credential::BearerToken { .. } => signing_time + BEARER_TOKEN_OPERATION_HEADROOM,
Credential::SharedKey { .. } | Credential::SasToken { .. } => signing_time,
}
}
@@ -258,7 +259,7 @@ impl SignRequest for RequestSigner {
// Handle different credential types
match cred {
- Credential::SasToken { token } => {
+ Credential::SasToken { token, .. } => {
// SAS token authentication
final_uri = Some(append_query_fragment(&original_uri, token)?);
}
@@ -271,8 +272,31 @@ impl SignRequest for RequestSigner {
"BearerToken can't be used in query string",
));
};
-
- let expiry = signing_time + d;
+ if d.is_zero() || d > MAX_USER_DELEGATION_KEY_LIFETIME {
+ return Err(reqsign_core::Error::request_invalid(
+ "Azure user delegation SAS lifetime must be greater than zero and at most seven days",
+ ));
+ }
+ let expiry = floor_to_wire_second(signing_time + d)?;
+ if expiry <= signing_time {
+ return Err(reqsign_core::Error::request_invalid(
+ "Azure user delegation SAS lifetime does not reach a future wire timestamp",
+ ));
+ }
+ let start = cfg.start.map(ceil_to_wire_second).transpose()?;
+ if start.is_some_and(|start| start >= expiry) {
+ return Err(reqsign_core::Error::request_invalid(
+ "Azure user delegation SAS start time must be before its expiration",
+ ));
+ }
+ let key_start = floor_to_wire_second(
+ start.map_or(signing_time, |start| start.min(signing_time)),
+ )?;
+ if expiry > key_start + MAX_USER_DELEGATION_KEY_LIFETIME {
+ return Err(reqsign_core::Error::request_invalid(
+ "Azure user delegation SAS interval exceeds the seven-day user delegation key limit",
+ ));
+ }
let resource = service_sas_resource(&sctx.path)?;
match (cfg.resource, &resource) {
@@ -292,56 +316,69 @@ impl SignRequest for RequestSigner {
}
let account = infer_account_name(sctx.authority.as_str())?;
+ let version = cfg.version.as_deref().unwrap_or("2020-12-06");
+ let cache_key = UserDelegationPresignCacheKey {
+ account: account.clone(),
+ endpoint: format!("{}://{}", sctx.scheme, sctx.authority),
+ source_authority: reqsign_core::hash::hex_sha256(token.as_bytes()),
+ version: version.to_string(),
+ };
+ let effective_start = start.unwrap_or(signing_time);
let key = {
let cached = self
.user_delegation_key_cache
.lock()
.expect("lock poisoned")
- .clone();
- if let Some(cached) = cached {
- if cached.signed_expiry > expiry + Duration::from_secs(20) {
- cached
- } else {
- let version = cfg.version.as_deref().unwrap_or("2020-12-06");
- let fetched = crate::user_delegation::get_user_delegation_key(
- context,
- crate::user_delegation::UserDelegationKeyRequest {
- scheme: sctx.scheme.as_str(),
- authority: sctx.authority.as_str(),
- bearer_token: token,
- start: signing_time,
- expiry,
- service_version: version,
- now: signing_time,
- },
+ .find_cloned(&cache_key, |key| {
+ user_delegation_key_covers(
+ key,
+ effective_start,
+ expiry,
+ signing_time,
+ version,
)
- .await?;
- *self
- .user_delegation_key_cache
- .lock()
- .expect("lock poisoned") = Some(fetched.clone());
- fetched
- }
+ });
+ if let Some(cached) = cached {
+ cached
} else {
- let version = cfg.version.as_deref().unwrap_or("2020-12-06");
+ let required_until =
+ self.get_time() + BEARER_TOKEN_OPERATION_HEADROOM;
+ if !cred.is_valid_at(required_until) {
+ return Err(reqsign_core::Error::credential_invalid(
+ "Azure bearer token expires before the user delegation key request can complete",
+ ));
+ }
let fetched = crate::user_delegation::get_user_delegation_key(
context,
crate::user_delegation::UserDelegationKeyRequest {
scheme: sctx.scheme.as_str(),
authority: sctx.authority.as_str(),
bearer_token: token,
- start: signing_time,
+ start: key_start,
expiry,
service_version: version,
now: signing_time,
},
)
.await?;
- *self
+ let after_io = self.get_time();
+ if !user_delegation_key_covers(
+ &fetched,
+ effective_start,
+ expiry,
+ after_io,
+ version,
+ ) {
+ return Err(reqsign_core::Error::credential_invalid(
+ "Azure user delegation key does not cover the requested SAS interval",
+ ));
+ }
+ let mut cache = self
.user_delegation_key_cache
.lock()
- .expect("lock poisoned") = Some(fetched.clone());
+ .expect("lock poisoned");
+ cache.insert(cache_key, fetched.clone(), after_io);
fetched
}
};
@@ -350,11 +387,11 @@ impl SignRequest for RequestSigner {
crate::user_delegation::UserDelegationSharedAccessSignature::new(
account,
key,
- resource,
+ resource.into(),
cfg.permissions.to_string(),
expiry,
);
- if let Some(start) = cfg.start {
+ if let Some(start) = start {
signer = signer.with_start(start);
}
if let Some(ip) = &cfg.ip {
@@ -1058,7 +1095,7 @@ mod tests {
#[tokio::test]
async fn test_bearer_token_presign_user_delegation_sas() {
- let now = Timestamp::from_str("2022-03-01T08:12:34Z").unwrap();
+ let now = Timestamp::from_str("2022-03-01T08:12:34.500Z").unwrap();
let http_send = MockUserDelegationHttpSend::default();
let ctx = Context::new()
@@ -1089,7 +1126,7 @@ mod tests {
assert_eq!(
parts.uri.to_string(),
format!(
- "{original_uri}sv=2020-12-06&se=2022-03-01T08%3A17%3A34Z&sp=r&sr=b&skoid=oid&sktid=tid&skt=2022-03-01T08%3A12%3A34Z&ske=2022-03-01T09%3A12%3A34Z&sks=b&skv=2020-12-06&sig=VkI3h/LWkD6qcDzshjQzCuCdMPDCFA3tMEbxM%2BED5Nc%3D"
+ "{original_uri}sv=2020-12-06&se=2022-03-01T08%3A17%3A34Z&sp=r&sr=b&skoid=oid&sktid=tid&skt=2022-03-01T08%3A12%3A34Z&ske=2022-03-01T09%3A12%3A34Z&sks=b&skv=2020-12-06&sig=ZEuqL17Enw3SO6zeRjYDnedXYngQ8GrQMUBx82BGelY%3D"
)
);
@@ -1097,12 +1134,12 @@ mod tests {
Credential::with_bearer_token("token", Some(now + Duration::from_secs(5)));
assert_eq!(
builder.required_valid_until(&near_expiry_cred, Some(Duration::from_secs(300))),
- now
+ now + BEARER_TOKEN_OPERATION_HEADROOM
);
let req = Request::builder().uri(&original_uri).body(()).unwrap();
let (mut cached_parts, _) = req.into_parts();
- builder
+ let err = builder
.sign_request(
&ctx,
&mut cached_parts,
@@ -1110,8 +1147,8 @@ mod tests {
Some(Duration::from_secs(300)),
)
.await
- .unwrap();
- assert_eq!(cached_parts.uri, parts.uri);
+ .expect_err("request-blind preflight must retain Bearer I/O headroom");
+ assert_eq!(err.kind(), reqsign_core::ErrorKind::CredentialInvalid);
assert_eq!(http_send.calls.load(Ordering::SeqCst), 1);
}
}
diff --git a/services/azure-storage/src/user_delegation.rs b/services/azure-storage/src/user_delegation.rs
index d8e7f8f..2350d2e 100644
--- a/services/azure-storage/src/user_delegation.rs
+++ b/services/azure-storage/src/user_delegation.rs
@@ -21,12 +21,18 @@ use reqsign_core::Context;
use reqsign_core::Result;
use reqsign_core::hash;
use reqsign_core::time::Timestamp;
+use reqsign_core::utils::Redact;
+use std::collections::VecDeque;
+use std::fmt::{Debug, Formatter};
+use std::time::Duration;
use crate::service_sas::ServiceSasResource;
const DEFAULT_USER_DELEGATION_SAS_VERSION: &str = "2020-12-06";
+pub(crate) const USER_DELEGATION_KEY_CACHE_CAPACITY: usize = 64;
+pub(crate) const MAX_USER_DELEGATION_KEY_LIFETIME: Duration = Duration::from_secs(7 * 24 * 60 * 60);
-#[derive(Clone, Debug)]
+#[derive(Clone)]
pub(crate) struct UserDelegationKey {
pub signed_oid: String,
pub signed_tid: String,
@@ -37,6 +43,163 @@ pub(crate) struct UserDelegationKey {
pub value: String,
}
+impl Debug for UserDelegationKey {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("UserDelegationKey")
+ .field("signed_oid", &Redact::from(&self.signed_oid))
+ .field("signed_tid", &Redact::from(&self.signed_tid))
+ .field("signed_start", &self.signed_start)
+ .field("signed_expiry", &self.signed_expiry)
+ .field("signed_service", &self.signed_service)
+ .field("signed_version", &self.signed_version)
+ .field("value", &Redact::from(&self.value))
+ .finish()
+ }
+}
+
+pub(crate) struct UserDelegationKeyCache<K> {
+ entries: VecDeque<(K, UserDelegationKey)>,
+}
+
+impl<K> Default for UserDelegationKeyCache<K> {
+ fn default() -> Self {
+ Self {
+ entries: VecDeque::new(),
+ }
+ }
+}
+
+impl<K: Eq> UserDelegationKeyCache<K> {
+ pub(crate) fn find_cloned(
+ &self,
+ cache_key: &K,
+ usable: impl Fn(&UserDelegationKey) -> bool,
+ ) -> Option<UserDelegationKey> {
+ self.entries.iter().find_map(|(candidate, key)| {
+ (candidate == cache_key && usable(key)).then(|| key.clone())
+ })
+ }
+
+ pub(crate) fn insert(&mut self, cache_key: K, key: UserDelegationKey, current_time: Timestamp) {
+ self.entries
+ .retain(|(_, cached)| cached.signed_expiry > current_time);
+ if let Some(index) = self
+ .entries
+ .iter()
+ .position(|(candidate, _)| candidate == &cache_key)
+ {
+ self.entries.remove(index);
+ }
+ if key.signed_expiry <= current_time {
+ return;
+ }
+ while self.entries.len() >= USER_DELEGATION_KEY_CACHE_CAPACITY {
+ self.entries.pop_front();
+ }
+ self.entries.push_back((cache_key, key));
+ }
+
+ #[cfg(test)]
+ pub(crate) fn len(&self) -> usize {
+ self.entries.len()
+ }
+}
+
+pub(crate) fn floor_to_wire_second(timestamp: Timestamp) -> Result<Timestamp> {
+ Timestamp::from_second(timestamp.as_second())
+}
+
+pub(crate) fn ceil_to_wire_second(timestamp: Timestamp) -> Result<Timestamp> {
+ let mut second = timestamp.as_second();
+ if timestamp.subsec_nanosecond() > 0 {
+ second = second.checked_add(1).ok_or_else(|| {
+ reqsign_core::Error::request_invalid("Azure SAS timestamp exceeds the wire time range")
+ })?;
+ }
+ Timestamp::from_second(second)
+}
+
+pub(crate) fn user_delegation_key_covers(
+ key: &UserDelegationKey,
+ effective_start: Timestamp,
+ expiry: Timestamp,
+ current_time: Timestamp,
+ service_version: &str,
+) -> bool {
+ !key.signed_oid.is_empty()
+ && !key.signed_tid.is_empty()
+ && !key.value.is_empty()
+ && key.signed_service == "b"
+ && key.signed_version == service_version
+ && key.signed_start <= effective_start
+ && key.signed_expiry >= expiry
+ && key.signed_expiry > current_time
+}
+
+#[cfg(test)]
+mod cache_tests {
+ use super::*;
+
+ fn timestamp(value: &str) -> Timestamp {
+ value.parse().expect("timestamp must parse")
+ }
+
+ fn key(expiry: Timestamp, value: &str) -> UserDelegationKey {
+ UserDelegationKey {
+ signed_oid: "oid".to_string(),
+ signed_tid: "tid".to_string(),
+ signed_start: timestamp("2030-01-01T00:00:00Z"),
+ signed_expiry: expiry,
+ signed_service: "b".to_string(),
+ signed_version: DEFAULT_USER_DELEGATION_SAS_VERSION.to_string(),
+ value: value.to_string(),
+ }
+ }
+
+ #[test]
+ fn wire_time_rounding_preserves_bounds() {
+ let fractional = timestamp("2030-01-01T00:00:00.500Z");
+
+ assert_eq!(
+ floor_to_wire_second(fractional).expect("floor must succeed"),
+ timestamp("2030-01-01T00:00:00Z")
+ );
+ assert_eq!(
+ ceil_to_wire_second(fractional).expect("ceil must succeed"),
+ timestamp("2030-01-01T00:00:01Z")
+ );
+ }
+
+ #[test]
+ fn cache_is_bounded_and_drops_expired_entries() {
+ let now = timestamp("2030-01-01T00:00:00Z");
+ let expiry = now + Duration::from_secs(60);
+ let mut cache = UserDelegationKeyCache::default();
+
+ for index in 0..=USER_DELEGATION_KEY_CACHE_CAPACITY {
+ cache.insert(format!("key-{index}"), key(expiry, "a2V5"), now);
+ }
+
+ assert_eq!(cache.len(), USER_DELEGATION_KEY_CACHE_CAPACITY);
+ assert!(cache.find_cloned(&"key-0".to_string(), |_| true).is_none());
+ assert!(
+ cache
+ .find_cloned(&format!("key-{USER_DELEGATION_KEY_CACHE_CAPACITY}"), |_| {
+ true
+ },)
+ .is_some()
+ );
+
+ cache.insert("expired".to_string(), key(now, "expired"), now);
+ assert_eq!(cache.len(), USER_DELEGATION_KEY_CACHE_CAPACITY);
+ assert!(
+ cache
+ .find_cloned(&"expired".to_string(), |_| true)
+ .is_none()
+ );
+ }
+}
+
pub(crate) struct UserDelegationKeyRequest<'a> {
pub scheme: &'a str,
pub authority: &'a str,
@@ -64,19 +227,26 @@ pub(crate) async fn get_user_delegation_key(
//
// Reference: https://learn.microsoft.com/en-us/rest/api/storageservices/get-user-delegation-key
let body = format!(
- "<KeyInfo><Start>{}</Start><Expiry>{}</Expiry></KeyInfo>",
+ "<?xml version=\"1.0\" encoding=\"utf-8\"?><KeyInfo><Start>{}</Start><Expiry>{}</Expiry></KeyInfo>",
request.start.format_rfc3339_zulu(),
request.expiry.format_rfc3339_zulu(),
);
+ let mut authorization: http::HeaderValue = format!("Bearer {}", request.bearer_token)
+ .parse()
+ .map_err(|e| {
+ reqsign_core::Error::credential_invalid(
+ "failed to build user delegation key authorization header",
+ )
+ .with_source(e)
+ })?;
+ authorization.set_sensitive(true);
+
let req = http::Request::post(uri)
.header("x-ms-version", request.service_version)
.header("x-ms-date", request.now.format_http_date())
.header(header::CONTENT_TYPE, "application/xml")
- .header(
- header::AUTHORIZATION,
- format!("Bearer {}", request.bearer_token),
- )
+ .header(header::AUTHORIZATION, authorization)
.body(Bytes::from(body))
.map_err(|e| {
reqsign_core::Error::unexpected("failed to build user delegation key request")
@@ -134,11 +304,65 @@ fn extract_tag(xml: &str, tag: &str) -> Result<String> {
Ok(xml[start..end].trim().to_string())
}
+#[derive(Clone)]
+pub(crate) enum UserDelegationSasResource {
+ Container {
+ container: String,
+ },
+ Blob {
+ container: String,
+ blob: String,
+ },
+ Directory {
+ container: String,
+ path: String,
+ depth: usize,
+ },
+}
+
+impl UserDelegationSasResource {
+ fn canonicalized_resource(&self, account: &str) -> String {
+ match self {
+ Self::Container { container } => format!("/blob/{account}/{container}"),
+ Self::Blob { container, blob } => {
+ format!("/blob/{account}/{container}/{blob}")
+ }
+ Self::Directory {
+ container, path, ..
+ } => format!("/blob/{account}/{container}/{path}"),
+ }
+ }
+
+ fn signed_resource(&self) -> &'static str {
+ match self {
+ Self::Container { .. } => "c",
+ Self::Blob { .. } => "b",
+ Self::Directory { .. } => "d",
+ }
+ }
+
+ fn directory_depth(&self) -> Option<usize> {
+ match self {
+ Self::Directory { depth, .. } => Some(*depth),
+ _ => None,
+ }
+ }
+}
+
+impl From<ServiceSasResource> for UserDelegationSasResource {
+ fn from(value: ServiceSasResource) -> Self {
+ match value {
+ ServiceSasResource::Container { container } => Self::Container { container },
+ ServiceSasResource::Blob { container, blob } => Self::Blob { container, blob },
+ }
+ }
+}
+
pub(crate) struct UserDelegationSharedAccessSignature {
account: String,
key: UserDelegationKey,
- resource: ServiceSasResource,
+ resource: UserDelegationSasResource,
permissions: String,
expiry: Timestamp,
start: Option<Timestamp>,
@@ -151,7 +375,7 @@ impl UserDelegationSharedAccessSignature {
pub(crate) fn new(
account: String,
key: UserDelegationKey,
- resource: ServiceSasResource,
+ resource: UserDelegationSasResource,
permissions: String,
expiry: Timestamp,
) -> Self {
@@ -191,32 +415,54 @@ impl UserDelegationSharedAccessSignature {
fn signature(&self) -> Result<String> {
let canonicalized_resource = self.resource.canonicalized_resource(&self.account);
- let string_to_sign = format!(
- "{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}",
- self.permissions,
- self.start
- .as_ref()
- .map_or("".to_string(), |v| v.format_rfc3339_zulu()),
+ if self.version.as_str() >= "2025-07-05" {
+ return Err(reqsign_core::Error::request_invalid(
+ "user delegation SAS versions 2025-07-05 and later are not supported",
+ ));
+ }
+
+ let start = self
+ .start
+ .as_ref()
+ .map_or_else(String::new, |v| v.format_rfc3339_zulu());
+ let mut fields = vec![
+ self.permissions.clone(),
+ start,
self.expiry.format_rfc3339_zulu(),
canonicalized_resource,
- self.key.signed_oid,
- self.key.signed_tid,
+ self.key.signed_oid.clone(),
+ self.key.signed_tid.clone(),
self.key.signed_start.format_rfc3339_zulu(),
self.key.signed_expiry.format_rfc3339_zulu(),
- self.key.signed_service,
- self.key.signed_version,
+ self.key.signed_service.clone(),
+ self.key.signed_version.clone(),
+ ];
+
+ if self.version.as_str() >= "2020-02-10" {
+ fields.extend([String::new(), String::new(), String::new()]);
+ }
+
+ fields.extend([
self.ip.clone().unwrap_or_default(),
self.protocol.clone().unwrap_or_default(),
- self.version,
- self.resource.signed_resource(),
- "", // snapshot time
- "", // encryption scope
- "", // rscc
- "", // rscd
- "", // rsce
- "", // rscl
- "", // rsct
- );
+ self.version.clone(),
+ self.resource.signed_resource().to_string(),
+ String::new(), // snapshot time
+ ]);
+
+ if self.version.as_str() >= "2020-12-06" {
+ fields.push(String::new()); // encryption scope
+ }
+
+ fields.extend([
+ String::new(), // rscc
+ String::new(), // rscd
+ String::new(), // rsce
+ String::new(), // rscl
+ String::new(), // rsct
+ ]);
+
+ let string_to_sign = fields.join("\n");
let decoded_key = hash::base64_decode(&self.key.value)?;
Ok(hash::base64_hmac_sha256(
@@ -248,6 +494,9 @@ impl UserDelegationSharedAccessSignature {
("skv".to_string(), self.key.signed_version.to_string()),
];
+ if let Some(depth) = self.resource.directory_depth() {
+ elements.push(("sdd".to_string(), depth.to_string()));
+ }
if let Some(start) = &self.start {
elements.push(("st".to_string(), start.format_rfc3339_zulu()))
}
diff --git a/services/azure-storage/src/user_delegation_sas.rs b/services/azure-storage/src/user_delegation_sas.rs
new file mode 100644
index 0000000..a81db32
--- /dev/null
+++ b/services/azure-storage/src/user_delegation_sas.rs
@@ -0,0 +1,1596 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use crate::Credential;
+use crate::constants::AZURE_QUERY_ENCODE_SET;
+use crate::user_delegation::{
+ MAX_USER_DELEGATION_KEY_LIFETIME, UserDelegationKey, UserDelegationKeyCache,
+ UserDelegationKeyRequest, UserDelegationSasResource, UserDelegationSharedAccessSignature,
+ ceil_to_wire_second, floor_to_wire_second, get_user_delegation_key, user_delegation_key_covers,
+};
+use percent_encoding::percent_encode;
+use reqsign_core::hash::hex_sha256;
+use reqsign_core::time::Timestamp;
+use reqsign_core::{Context, Error, GrantCredential, Result, SigningCredential};
+use std::fmt::{Debug, Formatter};
+use std::net::Ipv4Addr;
+use std::ops::{BitOr, BitOrAssign};
+use std::str::FromStr;
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+const USER_DELEGATION_SERVICE_VERSION: &str = "2020-12-06";
+const MAX_USER_DELEGATION_LIFETIME: Duration = MAX_USER_DELEGATION_KEY_LIFETIME;
+const BEARER_TOKEN_OPERATION_HEADROOM: Duration = Duration::from_secs(20);
+
+/// Permissions that can be granted by an Azure Storage user delegation SAS.
+///
+/// Combining values with `|` produces the canonical Azure permission order.
+#[derive(Clone, Copy, Default, PartialEq, Eq)]
+pub struct UserDelegationSasPermissions(u16);
+
+impl UserDelegationSasPermissions {
+ /// Read resource data and metadata.
+ pub const READ: Self = Self(1 << 0);
+ /// Add blocks to an append blob.
+ pub const ADD: Self = Self(1 << 1);
+ /// Create blobs or directories.
+ pub const CREATE: Self = Self(1 << 2);
+ /// Write resource data and metadata.
+ pub const WRITE: Self = Self(1 << 3);
+ /// Delete resources.
+ pub const DELETE: Self = Self(1 << 4);
+ /// Delete a blob version.
+ pub const DELETE_VERSION: Self = Self(1 << 5);
+ /// Permanently delete a blob snapshot or version.
+ pub const PERMANENT_DELETE: Self = Self(1 << 6);
+ /// List blobs or directory entries.
+ pub const LIST: Self = Self(1 << 7);
+ /// Read or write blob index tags.
+ pub const TAGS: Self = Self(1 << 8);
+ /// Find blobs by tags within a container.
+ pub const FILTER_BY_TAGS: Self = Self(1 << 9);
+ /// Move a blob or directory.
+ pub const MOVE: Self = Self(1 << 10);
+ /// Read system properties or POSIX ACLs.
+ pub const EXECUTE: Self = Self(1 << 11);
+ /// Set the owner or owning group for hierarchical namespace resources.
+ pub const OWNERSHIP: Self = Self(1 << 12);
+ /// Set POSIX permissions or ACLs for hierarchical namespace resources.
+ pub const PERMISSIONS: Self = Self(1 << 13);
+ /// Set an immutability policy or legal hold.
+ pub const SET_IMMUTABILITY_POLICY: Self = Self(1 << 14);
+
+ /// Return whether no permission is selected.
+ pub const fn is_empty(self) -> bool {
+ self.0 == 0
+ }
+
+ /// Return whether all permissions in `other` are selected.
+ pub const fn contains(self, other: Self) -> bool {
+ self.0 & other.0 == other.0
+ }
+
+ const fn is_subset_of(self, allowed: Self) -> bool {
+ self.0 & !allowed.0 == 0
+ }
+
+ fn as_canonical_string(self) -> String {
+ [
+ (Self::READ, 'r'),
+ (Self::ADD, 'a'),
+ (Self::CREATE, 'c'),
+ (Self::WRITE, 'w'),
+ (Self::DELETE, 'd'),
+ (Self::DELETE_VERSION, 'x'),
+ (Self::PERMANENT_DELETE, 'y'),
+ (Self::LIST, 'l'),
+ (Self::TAGS, 't'),
+ (Self::FILTER_BY_TAGS, 'f'),
+ (Self::MOVE, 'm'),
+ (Self::EXECUTE, 'e'),
+ (Self::OWNERSHIP, 'o'),
+ (Self::PERMISSIONS, 'p'),
+ (Self::SET_IMMUTABILITY_POLICY, 'i'),
+ ]
+ .into_iter()
+ .filter_map(|(permission, symbol)| self.contains(permission).then_some(symbol))
+ .collect()
+ }
+}
+
+impl Debug for UserDelegationSasPermissions {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ f.write_str("UserDelegationSasPermissions(REDACTED)")
+ }
+}
+
+impl BitOr for UserDelegationSasPermissions {
+ type Output = Self;
+
+ fn bitor(self, rhs: Self) -> Self::Output {
+ Self(self.0 | rhs.0)
+ }
+}
+
+impl BitOrAssign for UserDelegationSasPermissions {
+ fn bitor_assign(&mut self, rhs: Self) {
+ self.0 |= rhs.0;
+ }
+}
+
+/// Protocol restriction embedded in a user delegation SAS.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub enum SasProtocol {
+ /// Require HTTPS for every request that uses the SAS.
+ #[default]
+ Https,
+ /// Permit either HTTPS or HTTP.
+ HttpsAndHttp,
+}
+
+impl SasProtocol {
+ fn as_str(self) -> &'static str {
+ match self {
+ Self::Https => "https",
+ Self::HttpsAndHttp => "https,http",
+ }
+ }
+}
+
+#[derive(Clone)]
+enum UserDelegationSasGrantResource {
+ Container {
+ container: String,
+ },
+ Blob {
+ container: String,
+ blob: String,
+ },
+ PathPrefix {
+ container: String,
+ path_prefix: String,
+ },
+}
+
+/// A typed Azure Storage resource and permission grant for user delegation SAS.
+///
+/// Resource names are logical, percent-decoded Azure names. Path prefixes map
+/// to Azure's directory/prefix SAS resource (`sr=d`) and therefore require a
+/// hierarchical-namespace or otherwise prefix-capable storage account.
+#[derive(Clone)]
+pub struct UserDelegationSasGrant {
+ resource: UserDelegationSasGrantResource,
+ permissions: UserDelegationSasPermissions,
+}
+
+impl Debug for UserDelegationSasGrant {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("UserDelegationSasGrant")
+ .finish_non_exhaustive()
+ }
+}
+
+impl UserDelegationSasGrant {
+ /// Grant access to a container.
+ pub fn for_container(
+ container: impl Into<String>,
+ permissions: UserDelegationSasPermissions,
+ ) -> Self {
+ Self {
+ resource: UserDelegationSasGrantResource::Container {
+ container: container.into(),
+ },
+ permissions,
+ }
+ }
+
+ /// Grant access to one exact blob.
+ ///
+ /// The percent-decoded blob name must contain at most 1,024 Unicode
+ /// scalar values.
+ pub fn for_blob(
+ container: impl Into<String>,
+ blob: impl Into<String>,
+ permissions: UserDelegationSasPermissions,
+ ) -> Self {
+ Self {
+ resource: UserDelegationSasGrantResource::Blob {
+ container: container.into(),
+ blob: blob.into(),
+ },
+ permissions,
+ }
+ }
+
+ /// Grant access to one non-empty directory or path prefix.
+ ///
+ /// The prefix must be a relative, slash-separated path without a leading
+ /// slash, trailing slash, empty segment, `.` segment, or `..` segment.
+ /// It may contain at most 61 segments after accounting for the storage
+ /// account and container segments in Azure's hierarchical-namespace limit.
+ pub fn for_path_prefix(
+ container: impl Into<String>,
+ path_prefix: impl Into<String>,
+ permissions: UserDelegationSasPermissions,
+ ) -> Self {
+ Self {
+ resource: UserDelegationSasGrantResource::PathPrefix {
+ container: container.into(),
+ path_prefix: path_prefix.into(),
+ },
+ permissions,
+ }
+ }
+
+ fn validate(&self) -> Result<ValidatedGrant> {
+ if self.permissions.is_empty() {
+ return Err(Error::request_invalid(
+ "user delegation SAS permissions must not be empty",
+ ));
+ }
+
+ let resource = match &self.resource {
+ UserDelegationSasGrantResource::Container { container } => {
+ validate_container(container)?;
+ let allowed = UserDelegationSasPermissions::READ
+ | UserDelegationSasPermissions::ADD
+ | UserDelegationSasPermissions::CREATE
+ | UserDelegationSasPermissions::WRITE
+ | UserDelegationSasPermissions::DELETE
+ | UserDelegationSasPermissions::DELETE_VERSION
+ | UserDelegationSasPermissions::LIST
+ | UserDelegationSasPermissions::TAGS
+ | UserDelegationSasPermissions::FILTER_BY_TAGS
+ | UserDelegationSasPermissions::MOVE
+ | UserDelegationSasPermissions::EXECUTE
+ | UserDelegationSasPermissions::SET_IMMUTABILITY_POLICY
+ | UserDelegationSasPermissions::OWNERSHIP
+ | UserDelegationSasPermissions::PERMISSIONS;
+ validate_permissions(self.permissions, allowed)?;
+ UserDelegationSasResource::Container {
+ container: container.clone(),
+ }
+ }
+ UserDelegationSasGrantResource::Blob { container, blob } => {
+ validate_container(container)?;
+ validate_blob(blob)?;
+ let allowed = UserDelegationSasPermissions::READ
+ | UserDelegationSasPermissions::ADD
+ | UserDelegationSasPermissions::CREATE
+ | UserDelegationSasPermissions::WRITE
+ | UserDelegationSasPermissions::DELETE
+ | UserDelegationSasPermissions::DELETE_VERSION
+ | UserDelegationSasPermissions::PERMANENT_DELETE
+ | UserDelegationSasPermissions::LIST
+ | UserDelegationSasPermissions::TAGS
+ | UserDelegationSasPermissions::MOVE
+ | UserDelegationSasPermissions::EXECUTE
+ | UserDelegationSasPermissions::SET_IMMUTABILITY_POLICY
+ | UserDelegationSasPermissions::OWNERSHIP
+ | UserDelegationSasPermissions::PERMISSIONS;
+ validate_permissions(self.permissions, allowed)?;
+ UserDelegationSasResource::Blob {
+ container: container.clone(),
+ blob: blob.clone(),
+ }
+ }
+ UserDelegationSasGrantResource::PathPrefix {
+ container,
+ path_prefix,
+ } => {
+ validate_container(container)?;
+ let depth = validate_path_prefix(path_prefix)?;
+ let allowed = UserDelegationSasPermissions::READ
+ | UserDelegationSasPermissions::ADD
+ | UserDelegationSasPermissions::CREATE
+ | UserDelegationSasPermissions::WRITE
+ | UserDelegationSasPermissions::DELETE
+ | UserDelegationSasPermissions::LIST
+ | UserDelegationSasPermissions::MOVE
+ | UserDelegationSasPermissions::EXECUTE
+ | UserDelegationSasPermissions::OWNERSHIP
+ | UserDelegationSasPermissions::PERMISSIONS;
+ validate_permissions(self.permissions, allowed)?;
+ UserDelegationSasResource::Directory {
+ container: container.clone(),
+ path: path_prefix.clone(),
+ depth,
+ }
+ }
+ };
+
+ Ok(ValidatedGrant {
+ resource,
+ permissions: self.permissions.as_canonical_string(),
+ })
+ }
+}
+
+struct ValidatedGrant {
+ resource: UserDelegationSasResource,
+ permissions: String,
+}
+
+fn validate_permissions(
+ permissions: UserDelegationSasPermissions,
+ allowed: UserDelegationSasPermissions,
+) -> Result<()> {
+ if !permissions.is_subset_of(allowed) {
+ return Err(Error::request_invalid(
+ "user delegation SAS permissions are not supported for the selected resource",
+ ));
+ }
+ Ok(())
+}
+
+fn validate_account(account: &str) -> Result<()> {
+ if !(3..=24).contains(&account.len())
+ || !account
+ .bytes()
+ .all(|value| value.is_ascii_lowercase() || value.is_ascii_digit())
+ {
+ return Err(Error::config_invalid(
+ "Azure storage account name must be 3-24 lowercase ASCII letters or digits",
+ ));
+ }
+ Ok(())
+}
+
+fn validate_container(container: &str) -> Result<()> {
+ if matches!(container, "$root" | "$web" | "$logs") {
+ return Ok(());
+ }
+ if !(3..=63).contains(&container.len())
+ || !container
+ .bytes()
+ .all(|value| value.is_ascii_lowercase() || value.is_ascii_digit() || value == b'-')
+ || !container
+ .as_bytes()
+ .first()
+ .is_some_and(u8::is_ascii_alphanumeric)
+ || !container
+ .as_bytes()
+ .last()
+ .is_some_and(u8::is_ascii_alphanumeric)
+ || container.contains("--")
+ {
+ return Err(Error::request_invalid(
+ "invalid Azure Blob Storage container name",
+ ));
+ }
+ Ok(())
+}
+
+fn validate_blob(blob: &str) -> Result<()> {
+ if blob.is_empty()
+ || blob.chars().count() > 1024
+ || blob.starts_with('/')
+ || blob
+ .chars()
+ .any(|value| value.is_control() || value == '\\')
+ {
+ return Err(Error::request_invalid(
+ "blob name must be a non-empty relative percent-decoded path",
+ ));
+ }
+ Ok(())
+}
+
+fn validate_path_prefix(path_prefix: &str) -> Result<usize> {
+ validate_blob(path_prefix)?;
+ if path_prefix.ends_with('/') {
+ return Err(Error::request_invalid(
+ "path prefix must not end with a slash",
+ ));
+ }
+ let segments = path_prefix.split('/').collect::<Vec<_>>();
+ if segments
+ .iter()
+ .any(|segment| segment.is_empty() || *segment == "." || *segment == "..")
+ {
+ return Err(Error::request_invalid(
+ "path prefix contains an empty or ambiguous segment",
+ ));
+ }
+ if segments.len() > 61 {
+ return Err(Error::request_invalid(
+ "path prefix exceeds the Azure hierarchical namespace segment limit",
+ ));
+ }
+ Ok(segments.len())
+}
+
+#[derive(Clone, PartialEq, Eq, Hash)]
+struct UserDelegationKeyCacheKey {
+ account: String,
+ endpoint: String,
+ source_authority: String,
+ service_version: &'static str,
+}
+
+#[derive(Clone)]
+struct ParsedEndpoint {
+ scheme: String,
+ authority: String,
+ identity: String,
+}
+
+struct OperationTimes {
+ now: Timestamp,
+ start: Option<Timestamp>,
+ expiry: Timestamp,
+ key_start: Timestamp,
+ key_expiry: Timestamp,
+}
+
+/// Grants expiration-aware Azure Storage user delegation SAS credentials.
+///
+/// The source credential must be [`Credential::BearerToken`]. Clones and
+/// values produced with [`UserDelegationSasGranter::with_grant`] share a
+/// source-aware user delegation key cache. The cache is partitioned by account,
+/// endpoint, source bearer authority, and service version, and is bounded to a
+/// fixed number of live entries. No singleflight behavior is promised.
+///
+/// Azure SAS wire timestamps have whole-second precision. Explicit start times
+/// are rounded forward, expirations are rounded backward, and the returned
+/// credential expiration exactly matches the signed `se` value.
+#[derive(Clone)]
+pub struct UserDelegationSasGranter {
+ account: String,
+ endpoint: String,
+ grant: UserDelegationSasGrant,
+ start: Option<Timestamp>,
+ ip: Option<String>,
+ protocol: SasProtocol,
+ key_cache: Arc<Mutex<UserDelegationKeyCache<UserDelegationKeyCacheKey>>>,
+ #[cfg(test)]
+ time: Option<Timestamp>,
+ #[cfg(test)]
+ time_after_request: Option<Timestamp>,
+}
+
+impl Debug for UserDelegationSasGranter {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("UserDelegationSasGranter")
+ .finish_non_exhaustive()
+ }
+}
+
+impl UserDelegationSasGranter {
+ /// Create a granter for an Azure storage account and typed grant.
+ ///
+ /// The default service endpoint is
+ /// `https://{account}.blob.core.windows.net`.
+ pub fn new(account: impl Into<String>, grant: UserDelegationSasGrant) -> Self {
+ let account = account.into();
+ Self {
+ endpoint: format!("https://{account}.blob.core.windows.net"),
+ account,
+ grant,
+ start: None,
+ ip: None,
+ protocol: SasProtocol::Https,
+ key_cache: Arc::new(Mutex::new(UserDelegationKeyCache::default())),
+ #[cfg(test)]
+ time: None,
+ #[cfg(test)]
+ time_after_request: None,
+ }
+ }
+
+ /// Replace the bound grant while retaining the shared user delegation key cache.
+ pub fn with_grant(mut self, grant: UserDelegationSasGrant) -> Self {
+ self.grant = grant;
+ self
+ }
+
+ /// Replace the HTTPS Blob service endpoint with an explicitly trusted authority.
+ ///
+ /// The source Bearer token is sent to this endpoint. The caller must trust
+ /// the endpoint to receive that credential. It must have no path or query,
+ /// and its first DNS label must equal the configured storage account name.
+ pub fn with_trusted_endpoint(mut self, endpoint: impl Into<String>) -> Self {
+ self.endpoint = endpoint.into();
+ self
+ }
+
+ /// Set an optional SAS start time.
+ pub fn with_start(mut self, start: Timestamp) -> Self {
+ self.start = Some(start);
+ self
+ }
+
+ /// Restrict the SAS to one IPv4 address or inclusive IPv4 range.
+ pub fn with_ip(mut self, ip: impl Into<String>) -> Self {
+ self.ip = Some(ip.into());
+ self
+ }
+
+ /// Set the protocol restriction embedded in the SAS.
+ pub fn with_protocol(mut self, protocol: SasProtocol) -> Self {
+ self.protocol = protocol;
+ self
+ }
+
+ #[cfg(test)]
+ fn with_time(mut self, time: Timestamp) -> Self {
+ self.time = Some(time);
+ self
+ }
+
+ #[cfg(test)]
+ fn with_time_after_request(mut self, time: Timestamp) -> Self {
+ self.time_after_request = Some(time);
+ self
+ }
+
+ fn now(&self) -> Timestamp {
+ #[cfg(test)]
+ if let Some(time) = self.time {
+ return time;
+ }
+ Timestamp::now()
+ }
+
+ fn now_after_request(&self) -> Timestamp {
+ #[cfg(test)]
+ if let Some(time) = self.time_after_request {
+ return time;
+ }
+ #[cfg(test)]
+ if let Some(time) = self.time {
+ return time;
+ }
+ Timestamp::now()
+ }
+
+ fn parse_endpoint(&self) -> Result<ParsedEndpoint> {
+ validate_account(&self.account)?;
+ let uri: http::Uri = self.endpoint.parse().map_err(|e| {
+ Error::config_invalid("invalid Azure Blob service endpoint").with_source(e)
+ })?;
+ if uri.scheme_str() != Some("https") {
+ return Err(Error::config_invalid(
+ "Azure user delegation key endpoint must use HTTPS",
+ ));
+ }
+ if uri.path() != "/" || uri.query().is_some() {
+ return Err(Error::config_invalid(
+ "Azure Blob service endpoint must not include a path or query",
+ ));
+ }
+ let authority = uri
+ .authority()
+ .ok_or_else(|| Error::config_invalid("Azure Blob service endpoint has no authority"))?;
+ let host = uri
+ .host()
+ .ok_or_else(|| Error::config_invalid("Azure Blob service endpoint has no host"))?;
+ if host.split('.').next() != Some(self.account.as_str()) {
+ return Err(Error::config_invalid(
+ "Azure Blob service endpoint does not match the storage account",
+ ));
+ }
+
+ Ok(ParsedEndpoint {
+ scheme: "https".to_string(),
+ authority: authority.as_str().to_string(),
+ identity: format!("https://{}", authority.as_str()),
+ })
+ }
+
+ fn operation_times(&self, expires_in: Option<Duration>) -> Result<OperationTimes> {
+ let expires_in = expires_in.ok_or_else(|| {
+ Error::request_invalid("Azure user delegation SAS requires an explicit lifetime")
+ })?;
+ if expires_in.is_zero() || expires_in > MAX_USER_DELEGATION_LIFETIME {
+ return Err(Error::request_invalid(
+ "Azure user delegation SAS lifetime must be greater than zero and at most seven days",
+ ));
+ }
+
+ let now = self.now();
+ let expiry = floor_to_wire_second(now + expires_in)?;
+ if expiry <= now {
+ return Err(Error::request_invalid(
+ "Azure user delegation SAS lifetime does not reach a future wire timestamp",
+ ));
+ }
+ let start = self.start.map(ceil_to_wire_second).transpose()?;
+ if start.is_some_and(|start| start >= expiry) {
+ return Err(Error::request_invalid(
+ "Azure user delegation SAS start time must be before its expiration",
+ ));
+ }
+
+ let key_start = floor_to_wire_second(start.map_or(now, |start| start.min(now)))?;
+ let key_expiry = key_start + MAX_USER_DELEGATION_LIFETIME;
+ if expiry > key_expiry {
+ return Err(Error::request_invalid(
+ "Azure user delegation SAS interval exceeds the seven-day user delegation key limit",
+ ));
+ }
+
+ Ok(OperationTimes {
+ now,
+ start,
+ expiry,
+ key_start,
+ key_expiry,
+ })
+ }
+
+ fn validate_ip(&self) -> Result<()> {
+ let Some(ip) = &self.ip else {
+ return Ok(());
+ };
+ if let Some((start, end)) = ip.split_once('-') {
+ let start = Ipv4Addr::from_str(start)
+ .map_err(|_| Error::request_invalid("invalid SAS IPv4 range"))?;
+ let end = Ipv4Addr::from_str(end)
+ .map_err(|_| Error::request_invalid("invalid SAS IPv4 range"))?;
+ if u32::from(start) > u32::from(end) {
+ return Err(Error::request_invalid(
+ "SAS IPv4 range start must not exceed its end",
+ ));
+ }
+ } else {
+ Ipv4Addr::from_str(ip)
+ .map_err(|_| Error::request_invalid("invalid SAS IPv4 address"))?;
+ }
+ Ok(())
+ }
+
+ fn cache_key(
+ &self,
+ endpoint: &ParsedEndpoint,
+ bearer_token: &str,
+ ) -> UserDelegationKeyCacheKey {
+ UserDelegationKeyCacheKey {
+ account: self.account.clone(),
+ endpoint: endpoint.identity.clone(),
+ source_authority: hex_sha256(bearer_token.as_bytes()),
+ service_version: USER_DELEGATION_SERVICE_VERSION,
+ }
+ }
+
+ fn key_covers(
+ key: &UserDelegationKey,
+ times: &OperationTimes,
+ current_time: Timestamp,
+ ) -> bool {
+ let effective_start = times.start.unwrap_or(times.now);
+ user_delegation_key_covers(
+ key,
+ effective_start,
+ times.expiry,
+ current_time,
+ USER_DELEGATION_SERVICE_VERSION,
+ )
+ }
+
+ fn cached_key(
+ &self,
+ cache_key: &UserDelegationKeyCacheKey,
+ times: &OperationTimes,
+ ) -> Option<UserDelegationKey> {
+ self.key_cache
+ .lock()
+ .expect("lock poisoned")
+ .find_cloned(cache_key, |key| Self::key_covers(key, times, times.now))
+ }
+}
+
+impl GrantCredential for UserDelegationSasGranter {
+ type Credential = Credential;
+
+ fn required_valid_until(
+ &self,
+ credential: &Self::Credential,
+ expires_in: Option<Duration>,
+ ) -> Timestamp {
+ let now = self.now();
+ let Credential::BearerToken { token, .. } = credential else {
+ return now + BEARER_TOKEN_OPERATION_HEADROOM;
+ };
+ let Ok(endpoint) = self.parse_endpoint() else {
+ return now + BEARER_TOKEN_OPERATION_HEADROOM;
+ };
+ let Ok(times) = self.operation_times(expires_in) else {
+ return now + BEARER_TOKEN_OPERATION_HEADROOM;
+ };
+ let cache_key = self.cache_key(&endpoint, token);
+ if self.cached_key(&cache_key, ×).is_some() {
+ now
+ } else {
+ now + BEARER_TOKEN_OPERATION_HEADROOM
+ }
+ }
+
+ async fn grant_credential(
+ &self,
+ ctx: &Context,
+ credential: &Self::Credential,
+ expires_in: Option<Duration>,
+ ) -> Result<Self::Credential> {
+ let Credential::BearerToken { token, .. } = credential else {
+ return Err(Error::credential_invalid(
+ "Azure user delegation SAS requires a bearer token source credential",
+ ));
+ };
+
+ let endpoint = self.parse_endpoint()?;
+ let grant = self.grant.validate()?;
+ self.validate_ip()?;
+ let times = self.operation_times(expires_in)?;
+ let required_until = self.required_valid_until(credential, expires_in);
+ if !credential.is_valid_at(required_until) {
+ return Err(Error::credential_invalid(
+ "Azure bearer token expires before the user delegation key request can complete",
+ ));
+ }
+
+ let cache_key = self.cache_key(&endpoint, token);
+ let cached = self.cached_key(&cache_key, ×);
+ let (key, fetched) = if let Some(key) = cached {
+ (key, false)
+ } else {
+ let required_until = self.now() + BEARER_TOKEN_OPERATION_HEADROOM;
+ if !credential.is_valid_at(required_until) {
+ return Err(Error::credential_invalid(
+ "Azure bearer token expires before the user delegation key request can complete",
+ ));
+ }
+ let key = get_user_delegation_key(
+ ctx,
+ UserDelegationKeyRequest {
+ scheme: &endpoint.scheme,
+ authority: &endpoint.authority,
+ bearer_token: token,
+ start: times.key_start,
+ expiry: times.key_expiry,
+ service_version: USER_DELEGATION_SERVICE_VERSION,
+ now: times.now,
+ },
+ )
+ .await?;
+ (key, true)
+ };
+
+ let after_io = if fetched {
+ self.now_after_request()
+ } else {
+ self.now()
+ };
+ if times.expiry <= after_io {
+ return Err(Error::request_invalid(
+ "Azure user delegation SAS expired before granting completed",
+ ));
+ }
+ if !Self::key_covers(&key, ×, after_io) {
+ return Err(Error::credential_invalid(
+ "Azure user delegation key does not cover the requested SAS interval",
+ ));
+ }
+
+ let mut signer = UserDelegationSharedAccessSignature::new(
+ self.account.clone(),
+ key.clone(),
+ grant.resource,
+ grant.permissions,
+ times.expiry,
+ )
+ .with_protocol(self.protocol.as_str());
+ if let Some(start) = times.start {
+ signer = signer.with_start(start);
+ }
+ if let Some(ip) = &self.ip {
+ signer = signer.with_ip(ip);
+ }
+
+ let pairs = signer.token().map_err(|e| {
+ Error::unexpected("failed to generate Azure user delegation SAS").with_source(e)
+ })?;
+ let token = encode_query_pairs(&pairs);
+ let output = Credential::with_sas_token_expires_at(&token, times.expiry);
+ if !output.is_valid_at(after_io) {
+ return Err(Error::credential_invalid(
+ "granted Azure user delegation SAS is not currently usable",
+ ));
+ }
+
+ if fetched {
+ let mut cache = self.key_cache.lock().expect("lock poisoned");
+ cache.insert(cache_key, key, after_io);
+ }
+
+ Ok(output)
+ }
+}
+
+fn encode_query_pairs(pairs: &[(String, String)]) -> String {
+ pairs
+ .iter()
+ .map(|(key, value)| {
+ format!(
+ "{}={}",
+ percent_encode(key.as_bytes(), &AZURE_QUERY_ENCODE_SET),
+ percent_encode(value.as_bytes(), &AZURE_QUERY_ENCODE_SET)
+ )
+ })
+ .collect::<Vec<_>>()
+ .join("&")
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::{RequestSigner, StaticCredentialProvider};
+ use bytes::Bytes;
+ use percent_encoding::percent_decode_str;
+ use reqsign_core::{ErrorKind, Granter, HttpSend, ProvideCredential, Signer};
+ use std::collections::VecDeque;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ #[derive(Clone, Debug)]
+ struct CapturedRequest {
+ method: http::Method,
+ uri: String,
+ version: Option<String>,
+ date: Option<String>,
+ content_type: Option<String>,
+ authorization: Option<String>,
+ authorization_sensitive: bool,
+ body: String,
+ }
+
+ #[derive(Clone)]
+ struct MockUserDelegationHttpSend {
+ calls: Arc<AtomicUsize>,
+ requests: Arc<Mutex<Vec<CapturedRequest>>>,
+ responses: Arc<Mutex<VecDeque<String>>>,
+ }
+
+ impl Debug for MockUserDelegationHttpSend {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("MockUserDelegationHttpSend")
+ .field("calls", &self.calls.load(Ordering::SeqCst))
+ .finish_non_exhaustive()
+ }
+ }
+
+ impl MockUserDelegationHttpSend {
+ fn new(responses: impl IntoIterator<Item = String>) -> Self {
+ Self {
+ calls: Arc::new(AtomicUsize::new(0)),
+ requests: Arc::new(Mutex::new(Vec::new())),
+ responses: Arc::new(Mutex::new(responses.into_iter().collect())),
+ }
+ }
+ }
+
+ impl HttpSend for MockUserDelegationHttpSend {
+ async fn http_send(&self, req: http::Request<Bytes>) -> Result<http::Response<Bytes>> {
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ let authorization = req.headers().get(http::header::AUTHORIZATION);
+ self.requests
+ .lock()
+ .expect("lock poisoned")
+ .push(CapturedRequest {
+ method: req.method().clone(),
+ uri: req.uri().to_string(),
+ version: req
+ .headers()
+ .get("x-ms-version")
+ .and_then(|value| value.to_str().ok())
+ .map(ToString::to_string),
+ date: req
+ .headers()
+ .get("x-ms-date")
+ .and_then(|value| value.to_str().ok())
+ .map(ToString::to_string),
+ content_type: req
+ .headers()
+ .get(http::header::CONTENT_TYPE)
+ .and_then(|value| value.to_str().ok())
+ .map(ToString::to_string),
+ authorization: authorization
+ .and_then(|value| value.to_str().ok())
+ .map(ToString::to_string),
+ authorization_sensitive: authorization
+ .is_some_and(http::HeaderValue::is_sensitive),
+ body: String::from_utf8_lossy(req.body()).into_owned(),
+ });
+
+ let body = self
+ .responses
+ .lock()
+ .expect("lock poisoned")
+ .pop_front()
+ .ok_or_else(|| Error::unexpected("missing mock user delegation key response"))?;
+ Ok(http::Response::builder()
+ .status(200)
+ .body(Bytes::from(body))
+ .expect("mock response must build"))
+ }
+ }
+
+ #[derive(Clone)]
+ struct FixedCredentialProvider(Credential);
+
+ impl Debug for FixedCredentialProvider {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("FixedCredentialProvider")
+ .finish_non_exhaustive()
+ }
+ }
+
+ impl ProvideCredential for FixedCredentialProvider {
+ type Credential = Credential;
+
+ async fn provide_credential(&self, _ctx: &Context) -> Result<Option<Self::Credential>> {
+ Ok(Some(self.0.clone()))
+ }
+ }
+
+ fn timestamp(value: &str) -> Timestamp {
+ value.parse().expect("timestamp must parse")
+ }
+
+ fn delegation_key_response(
+ signed_start: Timestamp,
+ signed_expiry: Timestamp,
+ oid: &str,
+ tid: &str,
+ value: &str,
+ ) -> String {
+ format!(
+ "<?xml version=\"1.0\" encoding=\"utf-8\"?>\
+ <UserDelegationKey>\
+ <SignedOid>{oid}</SignedOid>\
+ <SignedTid>{tid}</SignedTid>\
+ <SignedStart>{}</SignedStart>\
+ <SignedExpiry>{}</SignedExpiry>\
+ <SignedService>b</SignedService>\
+ <SignedVersion>{USER_DELEGATION_SERVICE_VERSION}</SignedVersion>\
+ <Value>{value}</Value>\
+ </UserDelegationKey>",
+ signed_start.format_rfc3339_zulu(),
+ signed_expiry.format_rfc3339_zulu(),
+ )
+ }
+
+ fn bearer(token: &str) -> Credential {
+ Credential::with_bearer_token(token, None)
+ }
+
+ fn output_parts(credential: &Credential) -> (&str, Timestamp) {
+ match credential {
+ Credential::SasToken {
+ token,
+ expires_at: Some(expires_at),
+ } => (token, *expires_at),
+ other => panic!("expected expiring SAS token, got {other:?}"),
+ }
+ }
+
+ fn query_value(token: &str, key: &str) -> Option<String> {
+ token.split('&').find_map(|element| {
+ let (candidate, value) = element.split_once('=')?;
+ (candidate == key).then(|| {
+ percent_decode_str(value)
+ .decode_utf8()
+ .expect("query value must be UTF-8")
+ .into_owned()
+ })
+ })
+ }
+
+ fn blob_grant(path: &str, permissions: UserDelegationSasPermissions) -> UserDelegationSasGrant {
+ UserDelegationSasGrant::for_blob("container", path, permissions)
+ }
+
+ #[test]
+ fn serializes_permissions_in_azure_canonical_order() {
+ let common = UserDelegationSasPermissions::READ
+ | UserDelegationSasPermissions::ADD
+ | UserDelegationSasPermissions::CREATE
+ | UserDelegationSasPermissions::WRITE
+ | UserDelegationSasPermissions::DELETE
+ | UserDelegationSasPermissions::DELETE_VERSION
+ | UserDelegationSasPermissions::TAGS
+ | UserDelegationSasPermissions::MOVE
+ | UserDelegationSasPermissions::EXECUTE
+ | UserDelegationSasPermissions::OWNERSHIP
+ | UserDelegationSasPermissions::PERMISSIONS
+ | UserDelegationSasPermissions::SET_IMMUTABILITY_POLICY;
+ let container = UserDelegationSasGrant::for_container(
+ "container",
+ common
+ | UserDelegationSasPermissions::LIST
+ | UserDelegationSasPermissions::FILTER_BY_TAGS,
+ )
+ .validate()
+ .expect("container permissions must be valid");
+ assert_eq!(container.permissions, "racwdxltfmeopi");
+
+ let blob = blob_grant(
+ "blob",
+ common
+ | UserDelegationSasPermissions::PERMANENT_DELETE
+ | UserDelegationSasPermissions::LIST,
+ )
+ .validate()
+ .expect("blob permissions must be valid");
+ assert_eq!(blob.permissions, "racwdxyltmeopi");
+
+ assert!(
+ blob_grant("blob", UserDelegationSasPermissions::FILTER_BY_TAGS)
+ .validate()
+ .is_err()
+ );
+ }
+
+ #[tokio::test]
+ async fn grants_real_user_delegation_protocol_shape() {
+ let now = timestamp("2022-03-01T08:12:34Z");
+ let key_expiry = now + MAX_USER_DELEGATION_LIFETIME;
+ let http = MockUserDelegationHttpSend::new([delegation_key_response(
+ now, key_expiry, "oid", "tid", "a2V5",
+ )]);
+ let ctx = Context::new().with_http_send(http.clone());
+ let operation = UserDelegationSasGranter::new(
+ "account",
+ blob_grant(
+ "path/to/blob name.txt",
+ UserDelegationSasPermissions::WRITE | UserDelegationSasPermissions::READ,
+ ),
+ )
+ .with_time(now);
+
+ let output = operation
+ .grant_credential(
+ &ctx,
+ &bearer("source-bearer-secret"),
+ Some(Duration::from_secs(300)),
+ )
+ .await
+ .expect("grant must succeed");
+
+ let requests = http.requests.lock().expect("lock poisoned");
+ assert_eq!(requests.len(), 1);
+ let request = &requests[0];
+ assert_eq!(request.method, http::Method::POST);
+ assert_eq!(
+ request.uri,
+ "https://account.blob.core.windows.net/?restype=service&comp=userdelegationkey"
+ );
+ assert_eq!(request.version.as_deref(), Some("2020-12-06"));
+ assert_eq!(
+ request.date.as_deref(),
+ Some("Tue, 01 Mar 2022 08:12:34 GMT")
+ );
+ assert_eq!(request.content_type.as_deref(), Some("application/xml"));
+ assert_eq!(
+ request.authorization.as_deref(),
+ Some("Bearer source-bearer-secret")
+ );
+ assert!(request.authorization_sensitive);
+ assert_eq!(
+ request.body,
+ "<?xml version=\"1.0\" encoding=\"utf-8\"?><KeyInfo><Start>2022-03-01T08:12:34Z</Start><Expiry>2022-03-08T08:12:34Z</Expiry></KeyInfo>"
+ );
+
+ let (token, expires_at) = output_parts(&output);
+ assert_eq!(expires_at, timestamp("2022-03-01T08:17:34Z"));
+ assert_eq!(query_value(token, "sv").as_deref(), Some("2020-12-06"));
+ assert_eq!(
+ query_value(token, "se").as_deref(),
+ Some("2022-03-01T08:17:34Z")
+ );
+ assert_eq!(query_value(token, "sp").as_deref(), Some("rw"));
+ assert_eq!(query_value(token, "sr").as_deref(), Some("b"));
+ assert_eq!(query_value(token, "spr").as_deref(), Some("https"));
+ assert_eq!(
+ query_value(token, "sig").as_deref(),
+ Some("aoHQpVbSMBC3EY94Aw7g2XFUZxtqh48MWBZLxq32Q6g=")
+ );
+ assert!(!token.contains("source-bearer-secret"));
+ }
+
+ #[tokio::test]
+ async fn normalizes_fractional_bounds_to_exact_wire_times() {
+ let now = timestamp("2030-01-01T00:00:00.500Z");
+ let key_start = timestamp("2030-01-01T00:00:00Z");
+ let key_expiry = timestamp("2030-01-08T00:00:00Z");
+ let http = MockUserDelegationHttpSend::new([delegation_key_response(
+ key_start, key_expiry, "oid", "tid", "a2V5",
+ )]);
+ let ctx = Context::new().with_http_send(http.clone());
+ let operation = UserDelegationSasGranter::new(
+ "account",
+ blob_grant("blob", UserDelegationSasPermissions::READ),
+ )
+ .with_time(now);
+ let source = bearer("source");
+
+ let output = operation
+ .grant_credential(&ctx, &source, Some(MAX_USER_DELEGATION_LIFETIME))
+ .await
+ .expect("the exact seven-day bound must remain representable");
+ let (token, expires_at) = output_parts(&output);
+ assert_eq!(expires_at, key_expiry);
+ assert_eq!(
+ query_value(token, "se").as_deref(),
+ Some("2030-01-08T00:00:00Z")
+ );
+
+ let output = operation
+ .clone()
+ .with_start(timestamp("2030-01-01T00:00:00.750Z"))
+ .grant_credential(&ctx, &source, Some(Duration::from_millis(2_500)))
+ .await
+ .expect("fractional bounds must use the cached key");
+ let (token, expires_at) = output_parts(&output);
+ assert_eq!(expires_at, timestamp("2030-01-01T00:00:03Z"));
+ assert_eq!(
+ query_value(token, "st").as_deref(),
+ Some("2030-01-01T00:00:01Z")
+ );
+ assert_eq!(
+ query_value(token, "se").as_deref(),
+ Some("2030-01-01T00:00:03Z")
+ );
+
+ let err = operation
+ .grant_credential(&ctx, &source, Some(Duration::from_millis(400)))
+ .await
+ .expect_err("a lifetime without a future wire second must fail");
+ assert_eq!(err.kind(), ErrorKind::RequestInvalid);
+ assert_eq!(http.calls.load(Ordering::SeqCst), 1);
+ assert_eq!(
+ http.requests.lock().expect("lock poisoned")[0].body,
+ "<?xml version=\"1.0\" encoding=\"utf-8\"?><KeyInfo><Start>2030-01-01T00:00:00Z</Start><Expiry>2030-01-08T00:00:00Z</Expiry></KeyInfo>"
+ );
+ }
+
+ #[tokio::test]
+ async fn core_granter_output_is_consumed_by_existing_signer() {
+ let now = Timestamp::now();
+ let http = MockUserDelegationHttpSend::new([delegation_key_response(
+ now,
+ now + MAX_USER_DELEGATION_LIFETIME,
+ "oid",
+ "tid",
+ "a2V5",
+ )]);
+ let ctx = Context::new().with_http_send(http);
+ let operation = UserDelegationSasGranter::new(
+ "account",
+ blob_grant("path/to/blob.txt", UserDelegationSasPermissions::READ),
+ )
+ .with_time(now);
+ let granter = Granter::new(
+ ctx,
+ StaticCredentialProvider::new_bearer_token("source-token"),
+ operation,
+ );
+ let output = granter
+ .grant(Some(Duration::from_secs(300)))
+ .await
+ .expect("core granter must return a usable SAS credential");
+ let (token, _) = output_parts(&output);
+ let token = token.to_string();
+
+ let signer = Signer::new(
+ Context::new(),
+ FixedCredentialProvider(output),
+ RequestSigner::new(),
+ );
+ let mut parts = http::Request::get(
+ "https://account.blob.core.windows.net/container/path/to/blob.txt?existing=%2F",
+ )
+ .body(())
+ .expect("request must build")
+ .into_parts()
+ .0;
+ signer
+ .sign(&mut parts, None)
+ .await
+ .expect("existing signer must consume granted credential");
+
+ assert_eq!(
+ parts.uri.to_string(),
+ format!(
+ "https://account.blob.core.windows.net/container/path/to/blob.txt?existing=%2F&{token}"
+ )
+ );
+ assert!(!parts.headers.contains_key(http::header::AUTHORIZATION));
+ }
+
+ #[tokio::test]
+ async fn rejects_non_bearer_source_variants_before_io() {
+ let now = timestamp("2030-01-01T00:00:00Z");
+ let http = MockUserDelegationHttpSend::new([]);
+ let ctx = Context::new().with_http_send(http.clone());
+ let operation = UserDelegationSasGranter::new(
+ "account",
+ blob_grant("blob", UserDelegationSasPermissions::READ),
+ )
+ .with_time(now);
+
+ for source in [
+ Credential::with_shared_key("account", "a2V5"),
+ Credential::with_sas_token("sv=2020-12-06&sig=secret"),
+ ] {
+ let err = operation
+ .grant_credential(&ctx, &source, Some(Duration::from_secs(60)))
+ .await
+ .expect_err("non-bearer source must be rejected");
+ assert_eq!(err.kind(), ErrorKind::CredentialInvalid);
+ }
+ assert_eq!(http.calls.load(Ordering::SeqCst), 0);
+ }
+
+ #[tokio::test]
+ async fn validates_lifetime_and_post_io_expiration() {
+ let now = timestamp("2030-01-01T00:00:00Z");
+ let key_expiry = now + MAX_USER_DELEGATION_LIFETIME;
+ let http = MockUserDelegationHttpSend::new([delegation_key_response(
+ now, key_expiry, "oid", "tid", "a2V5",
+ )]);
+ let ctx = Context::new().with_http_send(http.clone());
+ let base = UserDelegationSasGranter::new(
+ "account",
+ blob_grant("blob", UserDelegationSasPermissions::READ),
+ )
+ .with_time(now);
+ let source = bearer("source-secret");
+
+ for lifetime in [
+ None,
+ Some(Duration::ZERO),
+ Some(MAX_USER_DELEGATION_LIFETIME + Duration::from_secs(1)),
+ ] {
+ let err = base
+ .grant_credential(&ctx, &source, lifetime)
+ .await
+ .expect_err("invalid lifetime must fail");
+ assert_eq!(err.kind(), ErrorKind::RequestInvalid);
+ }
+ assert_eq!(http.calls.load(Ordering::SeqCst), 0);
+
+ let err = base
+ .clone()
+ .with_start(now + Duration::from_secs(61))
+ .grant_credential(&ctx, &source, Some(Duration::from_secs(60)))
+ .await
+ .expect_err("start at or after expiry must fail");
+ assert_eq!(err.kind(), ErrorKind::RequestInvalid);
+ assert_eq!(http.calls.load(Ordering::SeqCst), 0);
+
+ let err = base
+ .clone()
+ .with_start(now - Duration::from_secs(60))
+ .grant_credential(&ctx, &source, Some(MAX_USER_DELEGATION_LIFETIME))
+ .await
+ .expect_err("SAS interval outside key lifetime must fail");
+ assert_eq!(err.kind(), ErrorKind::RequestInvalid);
+ assert_eq!(http.calls.load(Ordering::SeqCst), 0);
+
+ let slow = base.with_time_after_request(now + Duration::from_secs(300));
+ let err = slow
+ .grant_credential(&ctx, &source, Some(Duration::from_secs(300)))
+ .await
+ .expect_err("SAS expired during I/O must fail");
+ assert_eq!(err.kind(), ErrorKind::RequestInvalid);
+ assert!(!format!("{err:?}").contains("source-secret"));
+ assert_eq!(http.calls.load(Ordering::SeqCst), 1);
+ }
+
+ #[tokio::test]
+ async fn shares_and_partitions_user_delegation_key_cache() {
+ let now = timestamp("2030-01-01T00:00:00Z");
+ let key_expiry = now + MAX_USER_DELEGATION_LIFETIME;
+ let response = || delegation_key_response(now, key_expiry, "oid", "tid", "a2V5");
+ let http = MockUserDelegationHttpSend::new([response(), response(), response()]);
+ let ctx = Context::new().with_http_send(http.clone());
+ let first = UserDelegationSasGranter::new(
+ "account",
+ blob_grant("first", UserDelegationSasPermissions::READ),
+ )
+ .with_time(now);
+ let second = first
+ .clone()
+ .with_grant(blob_grant("second", UserDelegationSasPermissions::WRITE));
+
+ let first_output = first
+ .grant_credential(&ctx, &bearer("source-a"), Some(Duration::from_secs(300)))
+ .await
+ .expect("first grant must fetch a key");
+ let second_output = second
+ .grant_credential(&ctx, &bearer("source-a"), Some(Duration::from_secs(300)))
+ .await
+ .expect("bound clone must share the key");
+ assert_ne!(
+ output_parts(&first_output).0,
+ output_parts(&second_output).0
+ );
+ assert_eq!(http.calls.load(Ordering::SeqCst), 1);
+
+ second
+ .grant_credential(&ctx, &bearer("source-b"), Some(Duration::from_secs(300)))
+ .await
+ .expect("different source authority must fetch a key");
+ assert_eq!(http.calls.load(Ordering::SeqCst), 2);
+
+ second
+ .with_trusted_endpoint("https://account.blob.core.windows.net:444")
+ .grant_credential(&ctx, &bearer("source-a"), Some(Duration::from_secs(300)))
+ .await
+ .expect("different endpoint must fetch a key");
+ assert_eq!(http.calls.load(Ordering::SeqCst), 3);
+ }
+
+ #[tokio::test]
+ async fn expires_user_delegation_key_cache_by_requested_interval() {
+ let now = timestamp("2030-01-01T00:00:00Z");
+ let first_key_expiry = now + Duration::from_secs(600);
+ let later = now + Duration::from_secs(400);
+ let http = MockUserDelegationHttpSend::new([
+ delegation_key_response(now, first_key_expiry, "oid", "tid", "a2V5"),
+ delegation_key_response(
+ later,
+ later + MAX_USER_DELEGATION_LIFETIME,
+ "oid",
+ "tid",
+ "a2V5",
+ ),
+ ]);
+ let ctx = Context::new().with_http_send(http.clone());
+ let operation = UserDelegationSasGranter::new(
+ "account",
+ blob_grant("blob", UserDelegationSasPermissions::READ),
+ )
+ .with_time(now);
+
+ operation
+ .grant_credential(&ctx, &bearer("source"), Some(Duration::from_secs(300)))
+ .await
+ .expect("first key must cover short grant");
+ operation
+ .clone()
+ .with_time(later)
+ .grant_credential(&ctx, &bearer("source"), Some(Duration::from_secs(300)))
+ .await
+ .expect("insufficient cached key must be replaced");
+
+ assert_eq!(http.calls.load(Ordering::SeqCst), 2);
+ }
+
+ #[tokio::test]
+ async fn encodes_container_blob_and_path_prefix_bounds() {
+ let now = timestamp("2030-01-01T00:00:00Z");
+ let key_expiry = now + MAX_USER_DELEGATION_LIFETIME;
+ let response = || delegation_key_response(now, key_expiry, "oid", "tid", "a2V5");
+ let http = MockUserDelegationHttpSend::new([response(), response(), response()]);
+ let ctx = Context::new().with_http_send(http.clone());
+ let source = bearer("source");
+
+ let container = UserDelegationSasGranter::new(
+ "account",
+ UserDelegationSasGrant::for_container(
+ "container",
+ UserDelegationSasPermissions::LIST
+ | UserDelegationSasPermissions::READ
+ | UserDelegationSasPermissions::FILTER_BY_TAGS,
+ ),
+ )
+ .with_time(now);
+ let output = container
+ .grant_credential(&ctx, &source, Some(Duration::from_secs(300)))
+ .await
+ .expect("container grant must succeed");
+ let token = output_parts(&output).0;
+ assert_eq!(query_value(token, "sr").as_deref(), Some("c"));
+ assert_eq!(query_value(token, "sp").as_deref(), Some("rlf"));
+ assert_eq!(query_value(token, "sdd"), None);
+
+ let prefix = UserDelegationSasGranter::new(
+ "account",
+ UserDelegationSasGrant::for_path_prefix(
+ "container",
+ "dir name/part%2Fvalue",
+ UserDelegationSasPermissions::LIST | UserDelegationSasPermissions::READ,
+ ),
+ )
+ .with_time(now);
+ let output = prefix
+ .grant_credential(&ctx, &source, Some(Duration::from_secs(300)))
+ .await
+ .expect("path prefix grant must succeed");
+ let token = output_parts(&output).0;
+ assert_eq!(query_value(token, "sr").as_deref(), Some("d"));
+ assert_eq!(query_value(token, "sdd").as_deref(), Some("2"));
+ assert_eq!(query_value(token, "sp").as_deref(), Some("rl"));
+ assert_eq!(
+ query_value(token, "sig").as_deref(),
+ Some("sD5AzbOySNQNewoyR+FPzp8mY4Q+PzxTbbZo7SCAR78=")
+ );
+
+ let blob = UserDelegationSasGranter::new(
+ "account",
+ blob_grant(
+ "blob",
+ UserDelegationSasPermissions::DELETE
+ | UserDelegationSasPermissions::READ
+ | UserDelegationSasPermissions::WRITE,
+ ),
+ )
+ .with_protocol(SasProtocol::HttpsAndHttp)
+ .with_time(now);
+ let output = blob
+ .grant_credential(&ctx, &source, Some(Duration::from_secs(300)))
+ .await
+ .expect("blob grant must succeed");
+ let token = output_parts(&output).0;
+ assert_eq!(query_value(token, "sr").as_deref(), Some("b"));
+ assert_eq!(query_value(token, "sp").as_deref(), Some("rwd"));
+ assert_eq!(query_value(token, "spr").as_deref(), Some("https,http"));
+ }
+
+ #[tokio::test]
+ async fn rejects_scope_widening_and_invalid_permissions_before_io() {
+ let now = timestamp("2030-01-01T00:00:00Z");
+ let http = MockUserDelegationHttpSend::new([]);
+ let ctx = Context::new().with_http_send(http.clone());
+ let source = bearer("source");
+
+ for prefix in ["", "/", "///", "/prefix", "prefix/", "a//b", ".", ".."] {
+ let operation = UserDelegationSasGranter::new(
+ "account",
+ UserDelegationSasGrant::for_path_prefix(
+ "container",
+ prefix,
+ UserDelegationSasPermissions::READ,
+ ),
+ )
+ .with_time(now);
+ let err = operation
+ .grant_credential(&ctx, &source, Some(Duration::from_secs(60)))
+ .await
+ .expect_err("ambiguous prefix must fail closed");
+ assert_eq!(err.kind(), ErrorKind::RequestInvalid);
+ }
+
+ for grant in [
+ UserDelegationSasGrant::for_blob(
+ "container",
+ "x".repeat(1025),
+ UserDelegationSasPermissions::READ,
+ ),
+ UserDelegationSasGrant::for_path_prefix(
+ "container",
+ (0..62)
+ .map(|index| format!("segment-{index}"))
+ .collect::<Vec<_>>()
+ .join("/"),
+ UserDelegationSasPermissions::READ,
+ ),
+ ] {
+ let err = UserDelegationSasGranter::new("account", grant)
+ .with_time(now)
+ .grant_credential(&ctx, &source, Some(Duration::from_secs(60)))
+ .await
+ .expect_err("out-of-range Azure resource name must fail");
+ assert_eq!(err.kind(), ErrorKind::RequestInvalid);
+ }
+
+ let empty_permissions = UserDelegationSasGranter::new(
+ "account",
+ blob_grant("blob", UserDelegationSasPermissions::default()),
+ )
+ .with_time(now);
+ assert_eq!(
+ empty_permissions
+ .grant_credential(&ctx, &source, Some(Duration::from_secs(60)))
+ .await
+ .expect_err("empty permissions must fail")
+ .kind(),
+ ErrorKind::RequestInvalid
+ );
+
+ let blob_filter = UserDelegationSasGranter::new(
+ "account",
+ blob_grant("blob", UserDelegationSasPermissions::FILTER_BY_TAGS),
+ )
+ .with_time(now);
+ assert_eq!(
+ blob_filter
+ .grant_credential(&ctx, &source, Some(Duration::from_secs(60)))
+ .await
+ .expect_err("blob filter-by-tags permission must fail")
+ .kind(),
+ ErrorKind::RequestInvalid
+ );
+ assert_eq!(http.calls.load(Ordering::SeqCst), 0);
+ }
+
+ #[tokio::test]
+ async fn validates_account_endpoint_and_ip_before_io() {
+ let now = timestamp("2030-01-01T00:00:00Z");
+ let http = MockUserDelegationHttpSend::new([]);
+ let ctx = Context::new().with_http_send(http.clone());
+ let source = bearer("source");
+ let grant = blob_grant("blob", UserDelegationSasPermissions::READ);
+
+ for operation in [
+ UserDelegationSasGranter::new("UPPER", grant.clone()),
+ UserDelegationSasGranter::new("account", grant.clone())
+ .with_trusted_endpoint("http://account.blob.core.windows.net"),
+ UserDelegationSasGranter::new("account", grant.clone())
+ .with_trusted_endpoint("https://other.blob.core.windows.net"),
+ UserDelegationSasGranter::new("account", grant.clone())
+ .with_trusted_endpoint("https://account.blob.core.windows.net/path"),
+ UserDelegationSasGranter::new("account", grant.clone())
+ .with_trusted_endpoint("https://account.blob.core.windows.net?x=1"),
+ UserDelegationSasGranter::new("account", grant.clone()).with_ip("2001:db8::1"),
+ UserDelegationSasGranter::new("account", grant).with_ip("192.0.2.2-192.0.2.1"),
+ ] {
+ let err = operation
+ .with_time(now)
+ .grant_credential(&ctx, &source, Some(Duration::from_secs(60)))
+ .await
+ .expect_err("invalid authority configuration must fail");
+ assert!(matches!(
+ err.kind(),
+ ErrorKind::ConfigInvalid | ErrorKind::RequestInvalid
+ ));
+ }
+ assert_eq!(http.calls.load(Ordering::SeqCst), 0);
+ }
+
+ #[test]
+ fn debug_redacts_grant_policy_credentials_and_key_material() {
+ let grant = UserDelegationSasGrant::for_path_prefix(
+ "sensitive-container",
+ "sensitive/path",
+ UserDelegationSasPermissions::READ | UserDelegationSasPermissions::WRITE,
+ );
+ let operation = UserDelegationSasGranter::new("secretaccount", grant.clone());
+ let credential =
+ Credential::with_sas_token_expires_at("sv=secret&sig=secret", Timestamp::now());
+ let key = UserDelegationKey {
+ signed_oid: "sensitive-object-id".to_string(),
+ signed_tid: "sensitive-tenant-id".to_string(),
+ signed_start: Timestamp::now(),
+ signed_expiry: Timestamp::now() + Duration::from_secs(60),
+ signed_service: "b".to_string(),
+ signed_version: USER_DELEGATION_SERVICE_VERSION.to_string(),
+ value: "sensitive-signing-key".to_string(),
+ };
+
+ for (debug, secret) in [
+ (format!("{grant:?}"), "sensitive-container"),
+ (format!("{operation:?}"), "secretaccount"),
+ (format!("{credential:?}"), "sv=secret&sig=secret"),
+ (format!("{key:?}"), "sensitive-signing-key"),
+ ] {
+ assert!(!debug.contains(secret));
+ }
+ }
+}
diff --git a/services/azure-storage/tests/credential_providers/default.rs b/services/azure-storage/tests/credential_providers/default.rs
index 95a7be4..853f9cb 100644
--- a/services/azure-storage/tests/credential_providers/default.rs
+++ b/services/azure-storage/tests/credential_providers/default.rs
@@ -153,6 +153,7 @@ async fn test_chain_stops_at_first_success() {
name: "provider3".to_string(),
return_credential: Some(Credential::SasToken {
token: "sv=2021-01-01&ss=b".to_string(),
+ expires_at: None,
}),
call_count: count3.clone(),
});
diff --git a/services/azure-storage/tests/credential_providers/env.rs b/services/azure-storage/tests/credential_providers/env.rs
index 8799436..54ce394 100644
--- a/services/azure-storage/tests/credential_providers/env.rs
+++ b/services/azure-storage/tests/credential_providers/env.rs
@@ -94,7 +94,7 @@ async fn test_env_provider_sas_token() {
let cred = cred.unwrap();
match cred {
- Credential::SasToken { token } => {
+ Credential::SasToken { token, .. } => {
assert_eq!(token, sas_token);
}
_ => panic!("Expected SasToken credential"),
diff --git a/services/azure-storage/tests/credential_providers/static_provider.rs b/services/azure-storage/tests/credential_providers/static_provider.rs
index 130f1eb..b3156e1 100644
--- a/services/azure-storage/tests/credential_providers/static_provider.rs
+++ b/services/azure-storage/tests/credential_providers/static_provider.rs
@@ -102,7 +102,7 @@ async fn test_static_provider_sas_token() {
let cred = cred.unwrap();
match cred {
- Credential::SasToken { token } => {
+ Credential::SasToken { token, .. } => {
assert_eq!(token, sas_token);
}
_ => panic!("Expected SasToken credential"),