-
Notifications
You must be signed in to change notification settings - Fork 180
RUST-1442 On-demand Azure KMS credentials #872
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
Merged
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
507be86
wip
abr-egn e7735a3
trait for Azure IMDS access
abr-egn 8839f60
move http client construction into handshaker
abr-egn 283a836
decouple http client from aws-auth
abr-egn ea4b5a2
factor out azure kms module
abr-egn 2b0c542
token source impl
abr-egn 631285d
allow setting test host
abr-egn 9ebcb11
passing case 1
abr-egn 768cd63
better test coverage
abr-egn 54b62dd
passing unit tests
abr-egn e7e679c
evergreen
abr-egn 434150c
fmt
abr-egn 6ebfe55
more fmt
abr-egn 342a09e
clippy
abr-egn 9360388
update feature doc
abr-egn 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 hidden or 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 hidden or 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 hidden or 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,9 @@ | ||
#!/bin/bash | ||
|
||
. ${DRIVERS_TOOLS}/.evergreen/find-python3.sh | ||
PYTHON=$(find_python3) | ||
|
||
function prepend() { while read line; do echo "${1}${line}"; done; } | ||
|
||
cd ${DRIVERS_TOOLS}/.evergreen/csfle | ||
${PYTHON} bottle.py fake_azure:imds -b localhost:${AZURE_IMDS_MOCK_PORT} 2>&1 | prepend "[MOCK AZURE IMDS] " |
This file contains hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 |
---|---|---|
|
@@ -35,6 +35,8 @@ pub(crate) struct CryptExecutor { | |
mongocryptd: Option<Mongocryptd>, | ||
mongocryptd_client: Option<Client>, | ||
metadata_client: Option<WeakClient>, | ||
#[cfg(feature = "azure-kms")] | ||
azure: azure::ExecutorState, | ||
} | ||
|
||
impl CryptExecutor { | ||
|
@@ -56,6 +58,8 @@ impl CryptExecutor { | |
mongocryptd: None, | ||
mongocryptd_client: None, | ||
metadata_client: None, | ||
#[cfg(feature = "azure-kms")] | ||
azure: azure::ExecutorState::new()?, | ||
}) | ||
} | ||
|
||
|
@@ -211,11 +215,10 @@ impl CryptExecutor { | |
let ctx = result_mut(&mut ctx)?; | ||
#[allow(unused_mut)] | ||
let mut out = rawdoc! {}; | ||
if self | ||
.kms_providers | ||
.credentials() | ||
let credentials = self.kms_providers.credentials(); | ||
if credentials | ||
.get(&KmsProvider::Aws) | ||
.map_or(false, |d| d.is_empty()) | ||
.map_or(false, Document::is_empty) | ||
{ | ||
#[cfg(feature = "aws-auth")] | ||
{ | ||
|
@@ -240,6 +243,21 @@ impl CryptExecutor { | |
)); | ||
} | ||
} | ||
if credentials | ||
.get(&KmsProvider::Azure) | ||
.map_or(false, Document::is_empty) | ||
{ | ||
#[cfg(feature = "azure-kms")] | ||
{ | ||
out.append("azure", self.azure.get_token().await?); | ||
} | ||
#[cfg(not(feature = "azure-kms"))] | ||
{ | ||
return Err(Error::invalid_argument( | ||
"On-demand Azure KMS credentials require the `azure-kms` feature.", | ||
)); | ||
} | ||
} | ||
ctx.provide_kms_providers(&out)?; | ||
} | ||
State::Ready => { | ||
|
@@ -346,3 +364,134 @@ fn raw_to_doc(raw: &RawDocument) -> Result<Document> { | |
raw.try_into() | ||
.map_err(|e| Error::internal(format!("could not parse raw document: {}", e))) | ||
} | ||
|
||
#[cfg(feature = "azure-kms")] | ||
pub(crate) mod azure { | ||
use bson::{rawdoc, RawDocumentBuf}; | ||
use serde::Deserialize; | ||
use std::time::{Duration, Instant}; | ||
use tokio::sync::Mutex; | ||
|
||
use crate::{ | ||
error::{Error, Result}, | ||
runtime::HttpClient, | ||
}; | ||
|
||
#[derive(Debug)] | ||
pub(crate) struct ExecutorState { | ||
cached_access_token: Mutex<Option<CachedAccessToken>>, | ||
http: HttpClient, | ||
#[cfg(test)] | ||
pub(crate) test_host: Option<(&'static str, u16)>, | ||
#[cfg(test)] | ||
pub(crate) test_param: Option<&'static str>, | ||
} | ||
|
||
impl ExecutorState { | ||
pub(crate) fn new() -> Result<Self> { | ||
const AZURE_IMDS_TIMEOUT: Duration = Duration::from_secs(10); | ||
Ok(Self { | ||
cached_access_token: Mutex::new(None), | ||
http: HttpClient::with_timeout(AZURE_IMDS_TIMEOUT)?, | ||
#[cfg(test)] | ||
test_host: None, | ||
#[cfg(test)] | ||
test_param: None, | ||
}) | ||
} | ||
|
||
pub(crate) async fn get_token(&self) -> Result<RawDocumentBuf> { | ||
let mut cached_token = self.cached_access_token.lock().await; | ||
if let Some(cached) = &*cached_token { | ||
if cached.expire_time.saturating_duration_since(Instant::now()) | ||
> Duration::from_secs(60) | ||
{ | ||
return Ok(cached.token_doc.clone()); | ||
} | ||
} | ||
let token = self.fetch_new_token().await?; | ||
let out = token.token_doc.clone(); | ||
*cached_token = Some(token); | ||
Ok(out) | ||
} | ||
|
||
async fn fetch_new_token(&self) -> Result<CachedAccessToken> { | ||
let now = Instant::now(); | ||
let server_response: ServerResponse = self | ||
.http | ||
.get_and_deserialize_json(self.make_url()?, &self.make_headers()) | ||
.await | ||
.map_err(|e| Error::authentication_error("azure imds", &format!("{}", e)))?; | ||
let expires_in_secs: u64 = server_response.expires_in.parse().map_err(|e| { | ||
Error::authentication_error( | ||
"azure imds", | ||
&format!("invalid `expires_in` response field: {}", e), | ||
) | ||
})?; | ||
#[allow(clippy::redundant_clone)] | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. why is a redundant clone needed here? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The |
||
Ok(CachedAccessToken { | ||
token_doc: rawdoc! { "accessToken": server_response.access_token.clone() }, | ||
expire_time: now + Duration::from_secs(expires_in_secs), | ||
#[cfg(test)] | ||
server_response, | ||
}) | ||
} | ||
|
||
fn make_url(&self) -> Result<reqwest::Url> { | ||
let url = reqwest::Url::parse_with_params( | ||
"http://169.254.169.254/metadata/identity/oauth2/token", | ||
&[ | ||
("api-version", "2018-02-01"), | ||
("resource", "https://vault.azure.net"), | ||
], | ||
) | ||
.map_err(|e| Error::internal(format!("invalid Azure IMDS URL: {}", e)))?; | ||
#[cfg(test)] | ||
let url = { | ||
let mut url = url; | ||
if let Some((host, port)) = self.test_host { | ||
url.set_host(Some(host)) | ||
.map_err(|e| Error::internal(format!("invalid test host: {}", e)))?; | ||
url.set_port(Some(port)) | ||
.map_err(|()| Error::internal(format!("invalid test port {}", port)))?; | ||
} | ||
url | ||
}; | ||
Ok(url) | ||
} | ||
|
||
fn make_headers(&self) -> Vec<(&'static str, &'static str)> { | ||
let headers = vec![("Metadata", "true"), ("Accept", "application/json")]; | ||
#[cfg(test)] | ||
let headers = { | ||
let mut headers = headers; | ||
if let Some(p) = self.test_param { | ||
headers.push(("X-MongoDB-HTTP-TestParams", p)); | ||
} | ||
headers | ||
}; | ||
headers | ||
} | ||
|
||
#[cfg(test)] | ||
pub(crate) async fn take_cached(&self) -> Option<CachedAccessToken> { | ||
self.cached_access_token.lock().await.take() | ||
} | ||
} | ||
|
||
#[derive(Debug, Deserialize)] | ||
pub(crate) struct ServerResponse { | ||
pub(crate) access_token: String, | ||
pub(crate) expires_in: String, | ||
#[allow(unused)] | ||
pub(crate) resource: String, | ||
} | ||
|
||
#[derive(Debug)] | ||
pub(crate) struct CachedAccessToken { | ||
pub(crate) token_doc: RawDocumentBuf, | ||
pub(crate) expire_time: Instant, | ||
#[cfg(test)] | ||
pub(crate) server_response: ServerResponse, | ||
} | ||
} |
This file contains hidden or 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.
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.
Can we add a note here that this can only be used with tokio (similar to above)? It's a bummer that we need to add a new feature flag here; I'll also need to do so for the GCP KMS work. We should try to consolidate these in 3.0.0; we could unify them under the
reqwest
feature created by the optional dependency, or possibly make them simpler if we remove support for tokio.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.
Good call, done. And yeah, agreed that it's not a great situation w.r.t. features and dependencies.