Skip to content
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ resolver = "3"
edition = "2024"
license = "Apache-2.0"
repository = "https://github.com/apache/reqsign"
rust-version = "1.86.0"
rust-version = "1.87.0"

[workspace.dependencies]
# Workspace dependencies
Expand Down Expand Up @@ -66,7 +66,7 @@ pretty_assertions = "1.3"
prost = "0.14"
quick-xml = { version = "0.42.0", features = ["serialize"] }
reqwest = { version = "0.13.1", default-features = false }
rsa = { version = "0.9.2", features = ["pkcs5", "sha2"] }
rsa = { version = "0.10.0", features = ["pkcs1v15", "pkcs5"] }
rust-ini = { version = "0.21" }
serde = { version = "1", features = ["derive"] }
serde_json = { version = "1" }
Expand Down
117 changes: 63 additions & 54 deletions core/src/jwt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,20 @@
// under the License.

//! JWT encoding helpers.
//!
//! ## Migrating from `encode_rs256`
//!
//! `encode_rs256` accepted a backend RSA key type and is no longer public.
//! Serialize the private key as PKCS#8 PEM and call [`encode_rs256_pem`]
//! instead. The byte-oriented PEM entry point keeps the same behavior.

use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use rsa::RsaPrivateKey;
use rsa::PrivateKey;
use rsa::pkcs1v15::SigningKey;
use rsa::pkcs8::DecodePrivateKey;
use rsa::rand_core::OsRng;
use rsa::sha2::Sha256;
use rsa::signature::{RandomizedSigner, SignatureEncoding};
use rsa::signature::{SignatureEncoding, Signer};
use serde::Serialize;

use crate::{Error, Result};
Expand All @@ -33,7 +38,7 @@ use crate::{Error, Result};
///
/// RS256 is RSA PKCS#1 v1.5 with SHA-256. The caller owns the JWT header and
/// claims shape so service-specific fields such as `x5t` stay service-local.
pub fn encode_rs256<H, C>(header: &H, claims: &C, private_key: &RsaPrivateKey) -> Result<String>
fn encode_rs256<H, C>(header: &H, claims: &C, private_key: &PrivateKey) -> Result<String>
where
H: Serialize,
C: Serialize,
Expand All @@ -42,9 +47,10 @@ where
let encoded_claims = encode_json(claims)?;
let signing_input = format!("{encoded_header}.{encoded_claims}");

let mut rng = OsRng;
let signing_key = SigningKey::<Sha256>::new(private_key.clone());
let signature = signing_key.sign_with_rng(&mut rng, signing_input.as_bytes());
let signature = signing_key
.try_sign(signing_input.as_bytes())
.map_err(|e| Error::unexpected("failed to sign JWT").with_source(e))?;
let encoded_signature = URL_SAFE_NO_PAD.encode(signature.to_bytes());

Ok(format!("{signing_input}.{encoded_signature}"))
Expand All @@ -59,7 +65,7 @@ where
let private_key_pem = std::str::from_utf8(private_key_pem).map_err(|e| {
Error::credential_invalid("RSA private key PEM is not valid UTF-8").with_source(e)
})?;
let private_key = RsaPrivateKey::from_pkcs8_pem(private_key_pem).map_err(|e| {
let private_key = PrivateKey::from_pkcs8_pem(private_key_pem).map_err(|e| {
Error::credential_invalid("failed to parse PKCS#8 RSA private key PEM").with_source(e)
})?;

Expand All @@ -80,10 +86,11 @@ mod tests {
use super::*;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use rsa::pkcs1v15::{Signature, VerifyingKey};
use rsa::rand_core::OsRng;
use rsa::signature::Verifier;
use serde_json::json;

const PRIVATE_KEY_PEM: &str = include_str!("../tests/fixtures/rsa-2048-pkcs8.pem");

#[derive(Serialize)]
struct Header<'a> {
alg: &'a str,
Expand All @@ -101,52 +108,54 @@ mod tests {

#[test]
fn encode_rs256_keeps_jws_shape_and_verifiable_signature() -> Result<()> {
let mut rng = OsRng;
let private_key = RsaPrivateKey::new(&mut rng, 2048)
.map_err(|e| Error::unexpected("failed to generate test RSA key").with_source(e))?;

let jwt = encode_rs256(
&Header {
alg: "RS256",
typ: "JWT",
x5t: "thumbprint",
},
&Claims {
iss: "client",
sub: "client",
aud: "https://example.com/token",
exp: 1,
},
&private_key,
)?;

let parts = jwt.split('.').collect::<Vec<_>>();
assert_eq!(parts.len(), 3);

let header: serde_json::Value = serde_json::from_slice(
&URL_SAFE_NO_PAD
.decode(parts[0])
.map_err(|e| Error::unexpected("failed to decode JWT header").with_source(e))?,
)
.map_err(|e| Error::unexpected("failed to parse JWT header").with_source(e))?;
assert_eq!(
header,
json!({
"alg": "RS256",
"typ": "JWT",
"x5t": "thumbprint"
})
);

let signature = URL_SAFE_NO_PAD
.decode(parts[2])
.map_err(|e| Error::unexpected("failed to decode JWT signature").with_source(e))?;
let signature = Signature::try_from(signature.as_slice())
.map_err(|e| Error::unexpected("failed to parse JWT signature").with_source(e))?;
let verifying_key = VerifyingKey::<Sha256>::new(private_key.to_public_key());
verifying_key
.verify(format!("{}.{}", parts[0], parts[1]).as_bytes(), &signature)
.map_err(|e| Error::unexpected("failed to verify JWT signature").with_source(e))?;
let private_key = PrivateKey::from_pkcs8_pem(PRIVATE_KEY_PEM)
.map_err(|e| Error::unexpected("failed to parse test RSA key").with_source(e))?;

let header = Header {
alg: "RS256",
typ: "JWT",
x5t: "thumbprint",
};
let claims = Claims {
iss: "client",
sub: "client",
aud: "https://example.com/token",
exp: 1,
};

let jwts = [
encode_rs256(&header, &claims, &private_key)?,
encode_rs256_pem(&header, &claims, PRIVATE_KEY_PEM.as_bytes())?,
];

for jwt in jwts {
let parts = jwt.split('.').collect::<Vec<_>>();
assert_eq!(parts.len(), 3);

let header: serde_json::Value =
serde_json::from_slice(&URL_SAFE_NO_PAD.decode(parts[0]).map_err(|e| {
Error::unexpected("failed to decode JWT header").with_source(e)
})?)
.map_err(|e| Error::unexpected("failed to parse JWT header").with_source(e))?;
assert_eq!(
header,
json!({
"alg": "RS256",
"typ": "JWT",
"x5t": "thumbprint"
})
);

let signature = URL_SAFE_NO_PAD
.decode(parts[2])
.map_err(|e| Error::unexpected("failed to decode JWT signature").with_source(e))?;
let signature = Signature::try_from(signature.as_slice())
.map_err(|e| Error::unexpected("failed to parse JWT signature").with_source(e))?;
let verifying_key = VerifyingKey::<Sha256>::new(private_key.to_public_key());
verifying_key
.verify(format!("{}.{}", parts[0], parts[1]).as_bytes(), &signature)
.map_err(|e| Error::unexpected("failed to verify JWT signature").with_source(e))?;
}

Ok(())
}
Expand Down
28 changes: 28 additions & 0 deletions core/tests/fixtures/rsa-2048-pkcs8.pem
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
-----BEGIN PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCI8XCPUpe0PkVK
8b85K66gUSm73/QeTzs62JBNglLKiULu8T2Ba/KYidEx53rWq3c1P8wtHMCQYfgE
ZlbdzmDdvKBGkX5OHkPQEU9/4/k1TSqX3af9FXiujLK8uqkOhkRCfItxz6/VbAEt
bWfpnatyKNxFYN+qGHOD8eZme5z0ebJ6k3zC/M3eqQVgyTP+GWETc1mDFeuwq2lh
5CGt/ZzV6ua6Sx5CaKzp+LBVzU/DuURGizNmKBT4S6t3CH1DevQqep8bttXDqHsR
yOcim0fv9YYAiHrETI49Yg0QsHrV4BjOqHuCOSPufJHI2yGEM/7yjCWNLZ4v9uYP
w2BQdmu3AgMBAAECggEAHrv1M61pL8I0AgRsktOrbv6YO7qhCrZkiCn3hPXFSABz
XbYVxDiqazKvGSCnEIvOBszpMYy86Qqbw70GLOS3F7zQSdY4fybKuGVSLtVG5oAJ
majdHW9WtPIN4U6RR5m5syRJlYLzpxYE06G0yxkgU9A403dQ61dugYPmXkTK7pEX
fMa+izSbZtYcGmKTs3tTIVPOToPxUQFB8s/abFex1voKY6OW9et8QiBz5uD/RL2p
1eNdixRHUOQZ/EqdWVHt5GivD5fh3s8PboANJARWwRfBCArtitJmtWg1bqMfRWr3
hbe2qiKuObR9sf4iasdlaiOoUwmhCdNCQLm1AyltGQKBgQC/oZrbHMwSwJS5HM6W
eJpaBpILFT84y7GEoRd5YluO4ZY51zg5d/SSLjhR6/UUdXrw1suzPPP9BMeeC54S
6VzoE8k6gfa9z+8RCojVpjYZ1Bc8oSzdU7NQ/p1xEsEr4YICcpfuIXhOuhFggjWt
sz00uBfEU7NSLKBok/4pPMzk3wKBgQC28THe3y4Z1gFhPRDrDy1e2MDnoU8v6i3N
85TqA1BIebTkWDfF4Sr5gWgSv6Kaxq2IgM9gBhVgL/SugzTZctqFbgMTH5hVK6OD
vjX9CLJOIpPnk/BUZ47HQrzd8RkFVv85FEYnF4rPeMpEvCQcBMyP8olK2xd86+6J
vJ8p9K68KQKBgQCjTCwxAbYpWLCjmhe1g+pMQwMarK1mUbXhRoFBb/6DoFqqyWrh
FgZ0tyxJKyB6oa31I6UMBSoJd5Q/arj2dqQ0JAA7elpv34xiYi6+mVfK5MA0a0hX
Bqdsorw5ifjQ0uc9/LbZNu5VcBu0uODTN0U18pZWN9k8ckjzNQHF1Ejp0wKBgQCg
2RS2FpicErOH4X88jU2g9Qc3IXdUc5vuVtp5now6DPhlRMNU8pMsaQEuatv3JfRx
7n9muDKXLdL+lVIkVn2Xj5CYgdEYIZRVQyqI3dqYJILSvBo0vBCnViBlK5SKQ2GH
uDGuMV7U6Ck/ogRFtlp9vgvEizntlitXY0a2RvJTcQKBgQCEGqWgUu+nM9NhyGwk
o7nZluSKpvEVtrCA9CKZVecXiY43nUYXGj1WuG5K9TBs3MnkDWzE/SCY+Xygz79y
JCxdaRmbRxGE5Lq+Ci7m4xY8W8fVGthxTiMBiilWDYDcaxEB+x2Floie8Ydsbm5w
r21BN6gLdVmtcnjM2zhSNdby0A==
-----END PRIVATE KEY-----
1 change: 0 additions & 1 deletion services/azure-storage/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ sha1 = { workspace = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
pem = { workspace = true }
reqsign-core = { workspace = true, features = ["jwt"] }
rsa = { workspace = true }

[dev-dependencies]
asyncband = { workspace = true, features = ["semaphore"] }
Expand Down
80 changes: 64 additions & 16 deletions services/azure-storage/src/provide_credential/client_certificate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,6 @@ use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use reqsign_core::time::Timestamp;
use reqsign_core::{Context, ProvideCredential};
use rsa::RsaPrivateKey;
use rsa::pkcs8::DecodePrivateKey;
use serde::Serialize;
use sha1::{Digest, Sha1};

Expand Down Expand Up @@ -99,7 +97,7 @@ impl ClientCertificateCredentialProvider {
&self,
ctx: &Context,
path: &str,
) -> Result<(Vec<u8>, RsaPrivateKey), reqsign_core::Error> {
) -> Result<(Vec<u8>, Vec<u8>), reqsign_core::Error> {
let cert_data = ctx.file_read(path).await.map_err(|e| {
reqsign_core::Error::credential_invalid(format!("Failed to read certificate file: {e}"))
})?;
Expand Down Expand Up @@ -140,14 +138,7 @@ impl ClientCertificateCredentialProvider {
reqsign_core::Error::credential_invalid("PEM does not contain a private key")
})?;

// Parse private key
let private_key = RsaPrivateKey::from_pkcs8_pem(&private_key_pem).map_err(|e| {
reqsign_core::Error::credential_invalid(format!(
"Failed to parse private key from PEM: {e}"
))
})?;

Ok((cert_der, private_key))
Ok((cert_der, private_key_pem.into_bytes()))
}

/// Calculate certificate thumbprint (x5t)
Expand All @@ -163,7 +154,7 @@ impl ClientCertificateCredentialProvider {
tenant_id: &str,
client_id: &str,
cert_der: &[u8],
private_key: &RsaPrivateKey,
private_key_pem: &[u8],
) -> Result<String, reqsign_core::Error> {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
Expand All @@ -172,11 +163,30 @@ impl ClientCertificateCredentialProvider {
})?
.as_secs();

self.create_client_assertion_at(
tenant_id,
client_id,
cert_der,
private_key_pem,
now,
generate_jti(now),
)
}

fn create_client_assertion_at(
&self,
tenant_id: &str,
client_id: &str,
cert_der: &[u8],
private_key_pem: &[u8],
now: u64,
jti: String,
) -> Result<String, reqsign_core::Error> {
let claims = ClientAssertionClaims {
aud: format!("https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"),
exp: now + 600, // 10 minutes
iss: client_id.to_string(),
jti: generate_jti(now),
jti,
nbf: now,
sub: client_id.to_string(),
};
Expand All @@ -187,7 +197,7 @@ impl ClientCertificateCredentialProvider {
x5t: self.calculate_thumbprint(cert_der),
};

reqsign_core::jwt::encode_rs256(&header, &claims, private_key)
reqsign_core::jwt::encode_rs256_pem(&header, &claims, private_key_pem)
}

/// Exchange client assertion for access token
Expand Down Expand Up @@ -289,11 +299,11 @@ impl ProvideCredential for ClientCertificateCredentialProvider {
};

// Load certificate and private key
let (cert_der, private_key) = self.load_certificate(ctx, &certificate_path).await?;
let (cert_der, private_key_pem) = self.load_certificate(ctx, &certificate_path).await?;

// Create client assertion
let client_assertion =
self.create_client_assertion(&tenant_id, &client_id, &cert_der, &private_key)?;
self.create_client_assertion(&tenant_id, &client_id, &cert_der, &private_key_pem)?;

// Exchange for access token
let token_response = self
Expand All @@ -313,6 +323,44 @@ impl ProvideCredential for ClientCertificateCredentialProvider {
#[cfg(test)]
mod tests {
use super::*;
use reqsign_core::FileRead;

const CLIENT_CERTIFICATE_PEM: &str =
include_str!("../../tests/fixtures/client-certificate.pem");
// Fixed RS256 output for the synthetic fixture and fixed timestamp/JTI below.
// This protects the certificate x5t, claims shape and PKCS#1 v1.5 signature.
const EXPECTED_CLIENT_ASSERTION: &str = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsIng1dCI6IjlsNlFzcGRYRVZ5WXI5VXI1Z1F5RkhoRnBKTSJ9.eyJhdWQiOiJodHRwczovL2xvZ2luLm1pY3Jvc29mdG9ubGluZS5jb20vdGVuYW50L29hdXRoMi92Mi4wL3Rva2VuIiwiZXhwIjoxNzAwMDAwNjAwLCJpc3MiOiJjbGllbnQiLCJqdGkiOiJmaXhlZC1qdGkiLCJuYmYiOjE3MDAwMDAwMDAsInN1YiI6ImNsaWVudCJ9.VovaDD9_dOI8PyYGC3HwefKgk9LhnZkVCkv8OegzWcuvhcm2oFUP2IipkS691hmjrtNTTORu8e8ow0M3iD1_73-ilJKvbwjNGf64EDY33b0aUG1xEVDqgeqdVa9rqltGeiuSAIBjRg01N_cRiezf6LMMWNtpbymKFxZWg0icqn08FYkhb1fvKCNaQW_fxSzfwNJv0wdM6OT9no12nuoIL8S0iCf-a7Piv14U75ECIADUvC3ssySlDxIs53tBtCOOc1sv6A59QEaR4z6MczFmVFFg8Kh1D8H51K5S9wWCCKbzZn1c_1Q-iRfnr5ZFlHIRDTYsAEI24E4aK-cLUQlF7Q";

#[derive(Debug)]
struct FixtureFileRead;

impl FileRead for FixtureFileRead {
async fn file_read(&self, path: &str) -> reqsign_core::Result<Vec<u8>> {
assert_eq!(path, "client-certificate.pem");
Ok(CLIENT_CERTIFICATE_PEM.as_bytes().to_vec())
}
}

#[tokio::test]
async fn client_assertion_matches_the_certificate_fixture() -> anyhow::Result<()> {
let provider = ClientCertificateCredentialProvider::new();
let ctx = Context::new().with_file_read(FixtureFileRead);
let (cert_der, private_key_pem) = provider
.load_certificate(&ctx, "client-certificate.pem")
.await?;
assert!(private_key_pem.starts_with(b"-----BEGIN PRIVATE KEY-----"));

let jwt = provider.create_client_assertion_at(
"tenant",
"client",
&cert_der,
&private_key_pem,
1_700_000_000,
"fixed-jti".to_string(),
)?;
assert_eq!(jwt, EXPECTED_CLIENT_ASSERTION);
Ok(())
}

#[test]
fn test_calculate_thumbprint() {
Expand Down
Loading
Loading