Skip to content

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 5 commits into from
Aug 18, 2022
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
15 changes: 14 additions & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ jobs:
run: cargo check --all --features azurite_workaround

- name: sdk tests
run: cargo test --all
run: cargo test --all

- name: update readme of sdks
run: |
Expand All @@ -92,6 +92,19 @@ jobs:
- name: check `into_future` feature
run: cargo check --all --features into_future

nightly-build:
name: Build Nightly
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
with:
toolchain: nightly
profile: minimal
override: true
- name: Build Nightly
run: cargo +nightly build --all-features

test-services:
name: Services Tests
runs-on: ubuntu-20.04
Expand Down
8 changes: 4 additions & 4 deletions sdk/identity/examples/client_certificate_credentials.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,13 @@ async fn get_certficate(
certificate_name: &str,
) -> Result<Vec<u8>, Box<dyn Error>> {
let creds = DefaultAzureCredential::default();
let mut client = KeyvaultClient::new(
let client = KeyvaultClient::new(
format!("https://{}.vault.azure.net", vault_name).as_str(),
std::sync::Arc::new(creds),
)?
.secret_client(certificate_name);
let secret = client.get().into_future().await?;
let cert = base64::decode(secret.value())?;
.secret_client();
let secret = client.get(certificate_name).into_future().await?;
let cert = base64::decode(secret.value)?;
Ok(cert)
}

Expand Down
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},
Expand All @@ -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;
Expand Down Expand Up @@ -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")
}
Comment on lines +145 to +147
Copy link
Contributor

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.


#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
impl TokenCredential for ClientCertificateCredential {
Expand All @@ -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();
Expand All @@ -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>>()?
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
.collect::<Result<Vec<String>, azure_core::error::Error>>()?
.collect::<azure_core::Result<Vec<String>>>()?

.join(",");
format! {"{},{}", base_signature, chain}
}
Expand All @@ -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),
Expand Down