-
Notifications
You must be signed in to change notification settings - Fork 290
Fixing build break in using client_certificate credentials #1018
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
5 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 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 | ||||
---|---|---|---|---|---|---|
@@ -1,8 +1,11 @@ | ||||||
use super::{authority_hosts, TokenCredential}; | ||||||
use azure_core::auth::{AccessToken, TokenResponse}; | ||||||
use azure_core::error::{ErrorKind, ResultExt}; | ||||||
use super::authority_hosts; | ||||||
use azure_core::{ | ||||||
auth::{AccessToken, TokenCredential, TokenResponse}, | ||||||
content_type, | ||||||
error::{Error, ErrorKind}, | ||||||
headers, new_http_client, Method, Request, | ||||||
}; | ||||||
use base64::{CharacterSet, Config}; | ||||||
use chrono::Utc; | ||||||
use openssl::{ | ||||||
error::ErrorStack, | ||||||
hash::{hash, DigestBytes, MessageDigest}, | ||||||
|
@@ -14,6 +17,8 @@ use openssl::{ | |||||
use serde::Deserialize; | ||||||
use std::str; | ||||||
use std::time::Duration; | ||||||
use time::OffsetDateTime; | ||||||
use url::{form_urlencoded, Url}; | ||||||
|
||||||
/// Refresh time to use in seconds | ||||||
const DEFAULT_REFRESH_TIME: i64 = 300; | ||||||
|
@@ -130,16 +135,17 @@ struct AadTokenResponse { | |||||
access_token: String, | ||||||
} | ||||||
|
||||||
fn get_encoded_cert(cert: &X509) -> Result<String, ClientCertificateCredentialError> { | ||||||
fn get_encoded_cert(cert: &X509) -> azure_core::Result<String> { | ||||||
Ok(format!( | ||||||
"\"{}\"", | ||||||
base64::encode( | ||||||
cert.to_pem() | ||||||
.map_err(ClientCertificateCredentialError::OpensslError)? | ||||||
) | ||||||
base64::encode(cert.to_pem().map_err(|_| openssl_error())?) | ||||||
)) | ||||||
} | ||||||
|
||||||
fn openssl_error() -> azure_core::error::Error { | ||||||
Error::message(ErrorKind::Credential, "Openssl decode error") | ||||||
} | ||||||
|
||||||
#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))] | ||||||
#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)] | ||||||
impl TokenCredential for ClientCertificateCredential { | ||||||
|
@@ -152,14 +158,14 @@ impl TokenCredential for ClientCertificateCredential { | |||||
); | ||||||
|
||||||
let certificate = base64::decode(&self.client_certificate) | ||||||
.map_err(ClientCertificateCredentialError::DecodeError)?; | ||||||
.map_err(|_| Error::message(ErrorKind::Credential, "Base64 decode failed"))?; | ||||||
let certificate = Pkcs12::from_der(&certificate) | ||||||
.map_err(ClientCertificateCredentialError::OpensslError)? | ||||||
.map_err(|_| openssl_error())? | ||||||
.parse(&self.client_certificate_pass) | ||||||
.map_err(ClientCertificateCredentialError::OpensslError)?; | ||||||
.map_err(|_| openssl_error())?; | ||||||
|
||||||
let thumbprint = ClientCertificateCredential::get_thumbprint(&certificate.cert) | ||||||
.map_err(ClientCertificateCredentialError::OpensslError)?; | ||||||
.map_err(|_| openssl_error())?; | ||||||
|
||||||
let uuid = uuid::Uuid::new_v4(); | ||||||
let current_time = OffsetDateTime::now_utc().unix_timestamp(); | ||||||
|
@@ -174,7 +180,7 @@ impl TokenCredential for ClientCertificateCredential { | |||||
let chain = chain | ||||||
.into_iter() | ||||||
.map(|x| get_encoded_cert(&x)) | ||||||
.collect::<Result<Vec<String>, ClientCertificateCredentialError>>()? | ||||||
.collect::<Result<Vec<String>, azure_core::error::Error>>()? | ||||||
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.
Suggested change
|
||||||
.join(","); | ||||||
format! {"{},{}", base_signature, chain} | ||||||
} | ||||||
|
@@ -197,32 +203,42 @@ impl TokenCredential for ClientCertificateCredential { | |||||
|
||||||
let jwt = format!("{}.{}", header, payload); | ||||||
let signature = ClientCertificateCredential::sign(&jwt, &certificate.pkey) | ||||||
.map_err(ClientCertificateCredentialError::OpensslError)?; | ||||||
.map_err(|_| openssl_error())?; | ||||||
let sig = ClientCertificateCredential::as_jwt_part(&signature); | ||||||
let client_assertion = format!("{}.{}", jwt, sig); | ||||||
|
||||||
let form_data = vec![ | ||||||
("client_id", self.client_id.to_owned()), | ||||||
("scope", format!("{}/.default", resource)), | ||||||
( | ||||||
"client_assertion_type", | ||||||
"urn:ietf:params:oauth:client-assertion-type:jwt-bearer".to_owned(), | ||||||
), | ||||||
("client_assertion", client_assertion), | ||||||
("grant_type", "client_credentials".to_owned()), | ||||||
]; | ||||||
let encoded = { | ||||||
let mut encoded = &mut form_urlencoded::Serializer::new(String::new()); | ||||||
encoded = encoded | ||||||
.append_pair("client_id", self.client_id.as_str()) | ||||||
.append_pair("scope", format!("{}/.default", resource).as_str()) | ||||||
.append_pair( | ||||||
"client_assertion_type", | ||||||
"urn:ietf:params:oauth:client-assertion-type:jwt-bearer", | ||||||
) | ||||||
.append_pair("client_assertion", client_assertion.as_str()) | ||||||
.append_pair("grant_type", "client_credentials"); | ||||||
encoded.finish() | ||||||
}; | ||||||
|
||||||
let url = Url::parse(url)?; | ||||||
let mut req = Request::new(url, Method::Post); | ||||||
req.insert_header( | ||||||
headers::CONTENT_TYPE, | ||||||
content_type::APPLICATION_X_WWW_FORM_URLENCODED, | ||||||
); | ||||||
req.set_body(encoded); | ||||||
|
||||||
let http_client = new_http_client(); | ||||||
let response: AadTokenResponse = client | ||||||
.post(url) | ||||||
.form(&form_data) | ||||||
.send() | ||||||
.await | ||||||
.map_err(ClientCertificateCredentialError::ReqwestError)? | ||||||
.json() | ||||||
.await | ||||||
.map_err(ClientCertificateCredentialError::ReqwestError)?; | ||||||
let rsp = http_client.execute_request(&req).await?; | ||||||
let rsp_status = rsp.status(); | ||||||
let rsp_body = rsp.into_body().collect().await?; | ||||||
|
||||||
if !rsp_status.is_success() { | ||||||
return Err(ErrorKind::http_response_from_body(rsp_status, &rsp_body).into_error()); | ||||||
} | ||||||
|
||||||
let response: AadTokenResponse = serde_json::from_slice(&rsp_body)?; | ||||||
Ok(TokenResponse::new( | ||||||
AccessToken::new(response.access_token.to_string()), | ||||||
OffsetDateTime::now_utc() + Duration::from_secs(response.expires_in), | ||||||
|
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.
I don't think we want to use the same error message for all of these errors. It makes it hard to tell what actually went wrong.