Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 52 additions & 3 deletions services/azure-storage/src/credential.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ pub enum Credential {
},
/// SAS (Shared Access Signature) token authentication
SasToken {
/// SAS token.
/// SAS query string without the leading `?`.
token: String,
/// Optional absolute expiration time for this SAS token.
expires_at: Option<Timestamp>,
Expand Down Expand Up @@ -104,17 +104,23 @@ impl Credential {
}

/// Create a new credential with SAS token authentication.
///
/// `sas_token` is the raw SAS query string. A single leading `?`, as
/// commonly present when copying a SAS URL, is accepted and removed.
pub fn with_sas_token(sas_token: &str) -> Self {
Self::SasToken {
token: sas_token.to_string(),
token: normalize_sas_token(sas_token).to_string(),
expires_at: None,
}
}

/// Create a new credential with an expiring SAS token.
///
/// Like [`Credential::with_sas_token`], the token may start with a single
/// `?`.
pub fn with_sas_token_expires_at(sas_token: &str, expires_at: Timestamp) -> Self {
Self::SasToken {
token: sas_token.to_string(),
token: normalize_sas_token(sas_token).to_string(),
expires_at: Some(expires_at),
}
}
Expand All @@ -128,6 +134,10 @@ impl Credential {
}
}

fn normalize_sas_token(sas_token: &str) -> &str {
sas_token.strip_prefix('?').unwrap_or(sas_token)
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -156,6 +166,45 @@ mod tests {
assert!(!credential.is_valid_at(now + Duration::from_secs(10)));
}

#[test]
fn sas_token_constructors_accept_one_leading_question_mark() {
let token = concat!(
"sv=test",
"&ss=b&srt=c&sp=r",
"&se=2030-01-01T00%3A00%3A00Z",
"&st=2020-01-01T00%3A00%3A00Z",
"&spr=https",
"&sig=test%2Bsignature",
);
let prefixed = format!("?{token}");
let expires_at = Timestamp::now() + Duration::from_secs(60);
let cases = [
(Credential::with_sas_token(token), None),
(Credential::with_sas_token(&prefixed), None),
(
Credential::with_sas_token_expires_at(token, expires_at),
Some(expires_at),
),
(
Credential::with_sas_token_expires_at(&prefixed, expires_at),
Some(expires_at),
),
];

for (credential, expected_expires_at) in cases {
match credential {
Credential::SasToken {
token: actual,
expires_at,
} => {
assert_eq!(actual, token);
assert_eq!(expires_at, expected_expires_at);
}
other => panic!("expected SAS token, got {other:?}"),
}
}
}

#[test]
fn debug_fully_redacts_credential_material() {
let debug = [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,19 @@ impl StaticCredentialProvider {
}

/// Create a provider for a static SAS token with unknown expiration.
///
/// A single leading `?`, as commonly present when copying a SAS URL, is
/// accepted and removed.
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.
///
/// Like [`StaticCredentialProvider::new_sas_token`], the token may start
/// with a single `?`.
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),
Expand Down
4 changes: 1 addition & 3 deletions services/azure-storage/tests/credential_providers/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,7 @@ async fn test_env_provider_sas_token() -> anyhow::Result<()> {

assert_env_provider(HashMap::from([(
"AZURE_STORAGE_SAS_TOKEN".to_string(),
required_env("REQSIGN_AZURE_STORAGE_SAS_TOKEN")
.trim_start_matches('?')
.to_string(),
required_env("REQSIGN_AZURE_STORAGE_SAS_TOKEN"),
)]))
.await
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ async fn test_static_provider_sas_token() -> anyhow::Result<()> {
}

let token = required_env("REQSIGN_AZURE_STORAGE_SAS_TOKEN");
let provider = StaticCredentialProvider::new_sas_token(token.trim_start_matches('?'));
let provider = StaticCredentialProvider::new_sas_token(&token);
assert_provider_reads_probe(provider, live_context()).await
}

Expand Down
85 changes: 75 additions & 10 deletions services/azure-storage/tests/signing/sas_token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

use bytes::Bytes;
use reqsign_azure_storage::{RequestSigner, StaticCredentialProvider};
use reqsign_core::time::Timestamp;
use reqsign_core::{OsEnv, Signer};
use reqsign_file_read_tokio::TokioFileRead;
use reqsign_http_send_reqwest::ReqwestHttpSend;
Expand All @@ -31,8 +32,61 @@ fn required_env(name: &str) -> String {

fn load_sas_token() -> String {
required_env("REQSIGN_AZURE_STORAGE_SAS_TOKEN")
.trim_start_matches('?')
.to_string()
}

#[tokio::test]
async fn test_sas_token_accepts_optional_leading_question_mark() -> anyhow::Result<()> {
// Synthetic SAS text with percent-encoded values; no real account or signature.
const SAS: &str = concat!(
"sv=test",
"&ss=b&srt=c&sp=r",
"&se=2030-01-01T00%3A00%3A00Z",
"&st=2020-01-01T00%3A00%3A00Z",
"&spr=https",
"&sig=test%2Bsignature",
);
const BASE_URL: &str = "https://account.blob.core.windows.net/container/blob.txt";
const QUERY: &str = "comp=list&maxresults=10";

let urls = [
(BASE_URL.to_string(), '?'),
(format!("{BASE_URL}?{QUERY}"), '&'),
];
for (url, separator) in urls {
for token in [SAS.to_string(), format!("?{SAS}")] {
let signer = Signer::new(
crate::common::test_context(),
StaticCredentialProvider::new_sas_token(&token),
RequestSigner::new(),
);
let mut parts = http::Request::get(&url).body(()).unwrap().into_parts().0;

signer.sign(&mut parts, None).await?;

assert_eq!(parts.uri.to_string(), format!("{url}{separator}{SAS}"));
assert!(!parts.headers.contains_key("authorization"));
}
}

// The expiring SAS constructor shares the same normalization.
let signer = Signer::new(
crate::common::test_context(),
StaticCredentialProvider::new_sas_token_expires_at(
&format!("?{SAS}"),
Timestamp::now() + std::time::Duration::from_secs(3600),
),
RequestSigner::new(),
);
let mut parts = http::Request::get(format!("{BASE_URL}?{QUERY}"))
.body(())
.unwrap()
.into_parts()
.0;

signer.sign(&mut parts, None).await?;

assert_eq!(parts.uri.to_string(), format!("{BASE_URL}?{QUERY}&{SAS}"));
Ok(())
}

#[tokio::test]
Expand All @@ -43,7 +97,16 @@ async fn test_sas_token_signing() -> anyhow::Result<()> {
}

let url = required_env("REQSIGN_AZURE_STORAGE_PROBE_URL");
let sas_token = load_sas_token();
let configured_sas_token = load_sas_token();
// Ensure this single live request exercises the optional leading delimiter
// even when the fixture secret is stored without it. Other live cases keep
// the configured environment value unchanged.
let sas_token = if configured_sas_token.starts_with('?') {
configured_sas_token
} else {
format!("?{configured_sas_token}")
};
let expected_fragment = sas_token.strip_prefix('?').unwrap_or(&sas_token);

let ctx = crate::common::test_context()
.with_file_read(TokioFileRead)
Expand All @@ -64,14 +127,16 @@ async fn test_sas_token_signing() -> anyhow::Result<()> {
// With SAS token, no Authorization header should be added
assert!(!parts.headers.contains_key("authorization"));

// Decide separator from the original URL. Checking the signed URI always
// sees '?', which incorrectly forces the '&' branch.
// Decide the separator from the original URL; the signed URI always has
// a '?', so inspecting it would force the '&' branch. Compare the fragment
// after removing the credential's single optional leading delimiter.
let uri = parts.uri.to_string();
if url.contains('?') {
assert!(uri.contains(&format!("&{sas_token}")) || sas_token.is_empty());
} else {
assert!(uri.contains(&format!("?{sas_token}")) || sas_token.is_empty());
}
let separator = if url.contains('?') { '&' } else { '?' };
let expected_query = format!("{separator}{expected_fragment}");
assert!(
uri.contains(&expected_query),
"signed URI must append the normalized SAS query fragment"
);

let response = ctx
.http_send(http::Request::from_parts(parts, body))
Expand Down
Loading