-
Notifications
You must be signed in to change notification settings - Fork 268
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add AzurePipelinesCredential #2306
Open
heaths
wants to merge
2
commits into
Azure:main
Choose a base branch
from
heaths:issue2030
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+676
−102
Open
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
// Copyright (c) Microsoft Corporation. All rights reserved. | ||
// Licensed under the MIT License. | ||
|
||
//! Credentials for live and recorded tests. | ||
use azure_core::{ | ||
credentials::{AccessToken, Secret, TokenCredential}, | ||
date::OffsetDateTime, | ||
error::ErrorKind, | ||
}; | ||
use azure_identity::{AzurePipelinesCredential, DefaultAzureCredential, TokenCredentialOptions}; | ||
use std::{env, sync::Arc, time::Duration}; | ||
|
||
/// A mock [`TokenCredential`] useful for testing. | ||
#[derive(Clone, Debug, Default)] | ||
pub struct MockCredential; | ||
|
||
#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))] | ||
#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)] | ||
impl TokenCredential for MockCredential { | ||
async fn get_token(&self, scopes: &[&str]) -> azure_core::Result<AccessToken> { | ||
let token: Secret = format!("TEST TOKEN {}", scopes.join(" ")).into(); | ||
let expires_on = OffsetDateTime::now_utc().saturating_add( | ||
Duration::from_secs(60 * 5).try_into().map_err(|err| { | ||
azure_core::Error::full(ErrorKind::Other, err, "failed to compute expiration") | ||
})?, | ||
); | ||
Ok(AccessToken { token, expires_on }) | ||
} | ||
|
||
async fn clear_cache(&self) -> azure_core::Result<()> { | ||
Ok(()) | ||
} | ||
} | ||
|
||
/// Gets a `TokenCredential` appropriate for the current environment. | ||
/// | ||
/// When running in Azure Pipelines, this will return an [`AzurePipelinesCredential`]; | ||
/// otherwise, it will return a [`DefaultAzureCredential`]. | ||
pub fn from_env( | ||
options: Option<TokenCredentialOptions>, | ||
) -> azure_core::Result<Arc<dyn TokenCredential>> { | ||
// cspell:ignore accesstoken azuresubscription | ||
let tenant_id = env::var("AZURESUBSCRIPTION_TENANT_ID").ok(); | ||
let client_id = env::var("AZURESUBSCRIPTION_CLIENT_ID").ok(); | ||
let connection_id = env::var("AZURESUBSCRIPTION_SERVICE_CONNECTION_ID").ok(); | ||
let access_token = env::var("SYSTEM_ACCESSTOKEN").ok(); | ||
|
||
if let (Some(tenant_id), Some(client_id), Some(connection_id), Some(access_token)) = | ||
(tenant_id, client_id, connection_id, access_token) | ||
{ | ||
if !tenant_id.is_empty() | ||
&& !client_id.is_empty() | ||
&& !connection_id.is_empty() | ||
&& !access_token.is_empty() | ||
{ | ||
return Ok(AzurePipelinesCredential::new( | ||
tenant_id, | ||
client_id, | ||
&connection_id, | ||
access_token, | ||
options.map(Into::into), | ||
)? as Arc<dyn TokenCredential>); | ||
} | ||
} | ||
|
||
Ok( | ||
DefaultAzureCredential::with_options(options.unwrap_or_default())? | ||
as Arc<dyn TokenCredential>, | ||
) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
// Copyright (c) Microsoft Corporation. All rights reserved. | ||
// Licensed under the MIT License. | ||
|
||
use async_trait::async_trait; | ||
use azure_core::{HttpClient, Request, Response, Result}; | ||
use futures::lock::Mutex; | ||
use std::{fmt, future::Future, pin::Pin}; | ||
|
||
pub struct MockHttpClient<C>(Mutex<C>); | ||
|
||
impl<C> MockHttpClient<C> | ||
where | ||
C: FnMut(&Request) -> Pin<Box<dyn Future<Output = Result<Response>> + Send + Sync + '_>> | ||
+ Send | ||
+ Sync, | ||
{ | ||
pub fn new(client: C) -> Self { | ||
Self(Mutex::new(client)) | ||
} | ||
} | ||
|
||
impl<C> fmt::Debug for MockHttpClient<C> { | ||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
f.write_str(stringify!("MockHttpClient")) | ||
} | ||
} | ||
|
||
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))] | ||
#[cfg_attr(not(target_arch = "wasm32"), async_trait)] | ||
impl<C> HttpClient for MockHttpClient<C> | ||
where | ||
C: FnMut(&Request) -> Pin<Box<dyn Future<Output = Result<Response>> + Send + Sync + '_>> | ||
+ Send | ||
+ Sync, | ||
{ | ||
async fn execute_request(&self, req: &Request) -> Result<Response> { | ||
let mut client = self.0.lock().await; | ||
(client)(req).await | ||
} | ||
} | ||
|
||
#[tokio::test] | ||
async fn test_mock_http_client() { | ||
use azure_core::{ | ||
headers::{HeaderName, Headers}, | ||
Method, StatusCode, | ||
}; | ||
use std::sync::{Arc, Mutex}; | ||
|
||
const COUNT_HEADER: HeaderName = HeaderName::from_static("x-count"); | ||
|
||
let count = Arc::new(Mutex::new(0)); | ||
let mock_client = Arc::new(MockHttpClient::new(|req| { | ||
let count = count.clone(); | ||
Box::pin(async move { | ||
assert_eq!(req.url().host_str(), Some("localhost")); | ||
|
||
if req.headers().get_optional_str(&COUNT_HEADER).is_some() { | ||
let mut count = count.lock().unwrap(); | ||
*count += 1; | ||
} | ||
|
||
Ok(Response::from_bytes(StatusCode::Ok, Headers::new(), vec![])) | ||
}) | ||
})) as Arc<dyn HttpClient>; | ||
|
||
let req = Request::new("https://localhost".parse().unwrap(), Method::Get); | ||
mock_client.execute_request(&req).await.unwrap(); | ||
|
||
let mut req = Request::new("https://localhost".parse().unwrap(), Method::Get); | ||
req.insert_header(COUNT_HEADER, "true"); | ||
mock_client.execute_request(&req).await.unwrap(); | ||
|
||
assert_eq!(*count.lock().unwrap(), 1); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
// Copyright (c) Microsoft Corporation. All rights reserved. | ||
// Licensed under the MIT License. | ||
|
||
//! HTTP testing utilities. | ||
mod clients; | ||
|
||
pub use clients::*; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@analogrelay any other good ideas here? The DX this forces (see test below; we have to pin the future) is unwieldy but I couldn't figure out a better way without taking advantage of Rust 1.85 async captures.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I cleaned it up a little using a
BoxedFuture
, though theboxed()
"extension method" probably does more heavy lifting here. Still open to other suggestions, but this seems to be a fairly common solution I found - more than what inspired me originally.