diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d820dfbb..1bd77f62 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -44,6 +44,33 @@ jobs: - name: Clippy run: cargo clippy --workspace --all-targets --all-features -- -D warnings + - name: Check production crypto dependencies + run: | + packages=( + reqsign-core + reqsign-aliyun-oss + reqsign-aws-core + reqsign-aws-v4 + reqsign-aws-v4a + reqsign-azure-storage + reqsign-google + reqsign-huaweicloud-obs + reqsign-openstack-keystone + reqsign-oracle + reqsign-tencent-cos + reqsign-volcengine-tos + ) + # Query each root separately so the facade's default-crypto graph is + # not unified into the roots. --all-features covers every optional + # path; --target all also covers target-specific dependencies. + for package in "${packages[@]}"; do + if cargo tree --package "$package" --all-features --target all --edges normal --prefix none \ + | grep -Eq '^(sha1|sha2|hmac|rsa|p256|aes-gcm) v'; then + echo "production cryptographic dependency found in $package" + exit 1 + fi + done + licenses: runs-on: ubuntu-latest timeout-minutes: 10 @@ -98,11 +125,12 @@ jobs: - name: Check run: | rustup target add wasm32-unknown-unknown - cargo check -p reqsign-core --target wasm32-unknown-unknown + cargo check --package reqsign-core --target wasm32-unknown-unknown + cargo check --package reqsign-crypto-rustcrypto --target wasm32-unknown-unknown cargo check -p reqsign-aws-core --target wasm32-unknown-unknown cargo check -p reqsign-aws-v4a --target wasm32-unknown-unknown cargo build --manifest-path reqsign/Cargo.toml --target wasm32-unknown-unknown --no-default-features --features=aws,aws-v4a,azure,aliyun,tencent - cargo build --manifest-path reqsign/Cargo.toml --target wasm32-unknown-unknown --no-default-features --features=default-context,aws,aws-v4a,azure,aliyun,tencent + cargo build --manifest-path reqsign/Cargo.toml --target wasm32-unknown-unknown --no-default-features --features=default-context,default-crypto,aws,aws-v4a,azure,aliyun,tencent unit: runs-on: ubuntu-latest @@ -117,6 +145,10 @@ jobs: env: RUST_LOG: DEBUG RUST_BACKTRACE: full + - name: Facade crypto feature tests + run: | + cargo test --package reqsign --all-features --test crypto --test default_signer + cargo test --package reqsign --no-default-features --features default-context --test crypto_without_default_crypto - name: Doc Test run: cargo +nightly test --doc --all-features --workspace env: diff --git a/.github/workflows/crypto_boring.yml b/.github/workflows/crypto_boring.yml new file mode 100644 index 00000000..b7e6348a --- /dev/null +++ b/.github/workflows/crypto_boring.yml @@ -0,0 +1,63 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +name: Crypto Boring + +on: + push: + branches: + - main + paths: + - "Cargo.toml" + - "rust-toolchain.toml" + - "core/**" + - "crypto/boring/**" + - "crypto/rustcrypto/**" + - "services/aws-core/**" + - "services/aws-v4/**" + - ".github/workflows/crypto_boring.yml" + pull_request: + branches: + - main + paths: + - "Cargo.toml" + - "rust-toolchain.toml" + - "core/**" + - "crypto/boring/**" + - "crypto/rustcrypto/**" + - "services/aws-core/**" + - "services/aws-v4/**" + - ".github/workflows/crypto_boring.yml" + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }}-${{ github.event_name }} + cancel-in-progress: true + +permissions: {} + +jobs: + test: + runs-on: ubuntu-latest + timeout-minutes: 60 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Clippy + run: cargo clippy --manifest-path crypto/boring/Cargo.toml --all-targets -- -D warnings + - name: Test + run: cargo test --manifest-path crypto/boring/Cargo.toml diff --git a/AGENTS.md b/AGENTS.md index af1ee053..117d247d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -40,6 +40,17 @@ For security-sensitive changes, follow [SECURITY.md](SECURITY.md) and [THREAT_MODEL.md](THREAT_MODEL.md) as the source of truth for Reqsign's security boundary and its relationship to OpenDAL and other host applications. +### Crypto Provider + +All signing cryptography goes through a `reqsign_core::crypto::CryptoProvider` +resolved by `Context` (explicit binding, then the process-wide registration). +`reqsign-core` and every `services/*` crate carry no production cryptographic +implementation. `reqsign-core` exposes no public JWT module or feature; Azure +and Google own their private RS256 JWS formatting. Follow +[docs/crypto-provider.md](docs/crypto-provider.md) as the source of truth for +the provider contract, resolution and installation ownership, error semantics, +and the official RustCrypto/BoringSSL implementations. + ### Default Credential Provider All future refactors and API reviews around `DefaultCredentialProvider` must @@ -76,6 +87,8 @@ this supported subset. - Service crates and core share a lockstep major version (`3.0.0`). - `reqsign-http-send-reqwest` has its own major (`4.0.0`). +- `reqsign-crypto-rustcrypto` and `reqsign-crypto-boring` each have independent + version lines, starting at `1.0.0`. - The facade `reqsign` crate follows an independent scheme (`0.20.0`). - Release is triggered by pushing a `v*.*.*` tag; `cargo publish --workspace` publishes everything. diff --git a/Cargo.toml b/Cargo.toml index 4098fb3e..f484da8e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,7 +16,8 @@ # under the License. [workspace] -members = ["core", "context/*", "services/*", "reqsign"] +members = ["core", "context/*", "crypto/rustcrypto", "services/*", "reqsign"] +exclude = ["crypto/boring"] resolver = "3" [workspace.package] @@ -34,6 +35,7 @@ reqsign-aws-v4a = { version = "3.2.0", path = "services/aws-v4a" } reqsign-azure-storage = { version = "3.3.2", path = "services/azure-storage" } reqsign-command-execute-tokio = { version = "3.0.9", path = "context/command-execute-tokio" } reqsign-core = { version = "3.3.4", path = "core" } +reqsign-crypto-rustcrypto = { version = "1.0.0", path = "crypto/rustcrypto" } reqsign-file-read-tokio = { version = "3.0.9", path = "context/file-read-tokio" } reqsign-google = { version = "3.4.0", path = "services/google" } reqsign-http-send-reqwest = { version = "4.0.9", path = "context/http-send-reqwest" } @@ -54,6 +56,7 @@ dotenvy = "0.15" env_logger = "0.11" form_urlencoded = "1" futures = "0.3" +getrandom = "0.3" hex = "0.4" hmac = "0.13" http = "1" diff --git a/README.md b/README.md index 405e70a1..f453ad52 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,8 @@ use reqsign::{aws, default_context}; #[tokio::main] async fn main() -> Result<()> { - // Create a default runtime context (HTTP client, file reader, OS env, command execution) + // Create a default runtime context (HTTP client, file reader, OS env, command execution). + // It binds RustCrypto when no process-wide provider is installed. let ctx = default_context(); // Create a default signer for S3 in us-east-1 using the supplied context let signer = aws::default_signer(ctx, "s3", "us-east-1"); @@ -55,15 +56,17 @@ For more control over the components, you can manually assemble the signer: ```rust use anyhow::Result; -use reqsign::{Context, Signer}; +use reqsign::{Context, RustCryptoProvider, Signer}; use reqsign_aws_v4::{DefaultCredentialProvider, RequestSigner}; use reqsign_file_read_tokio::TokioFileRead; use reqsign_http_send_reqwest::ReqwestHttpSend; #[tokio::main] async fn main() -> Result<()> { - // Build your own context with specific implementations + // Build your own context with specific implementations. + // A bare Context starts unbound, so bind the provider explicitly. let ctx = Context::new() + .with_crypto(RustCryptoProvider::new()) .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(reqsign::OsEnv); diff --git a/core/Cargo.toml b/core/Cargo.toml index dc3a0428..4f545b9c 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -29,7 +29,6 @@ rust-version.workspace = true [features] default = [] -jwt = ["dep:rsa", "dep:serde", "dep:serde_json"] [dependencies] anyhow = { workspace = true } @@ -37,18 +36,10 @@ asyncband = { workspace = true } base64 = { workspace = true } bytes = { workspace = true } hex = { workspace = true } -hmac = { workspace = true } http = { workspace = true } jiff = { workspace = true } log = { workspace = true } percent-encoding = { workspace = true } -sha1 = { workspace = true } -sha2 = { workspace = true } - -# Optional dependencies -rsa = { workspace = true, optional = true } -serde = { workspace = true, optional = true } -serde_json = { workspace = true, optional = true } [target.'cfg(target_os = "windows")'.dependencies] windows-sys = { version = "0.61.0", features = [ diff --git a/core/src/context.rs b/core/src/context.rs index 2e14995c..a85dbc94 100644 --- a/core/src/context.rs +++ b/core/src/context.rs @@ -15,6 +15,7 @@ // specific language governing permissions and limitations // under the License. +use crate::crypto::{self, CryptoProvider}; use crate::{BoxedFuture, Error, MaybeSend, Result}; use bytes::Bytes; use std::collections::HashMap; @@ -31,6 +32,15 @@ use std::sync::Arc; /// reqsign provides NO default implementations. Users MAY configure components they need. /// Any unconfigured component will use a no-op implementation that returns errors or empty values when called. /// +/// ## Cryptographic provider +/// +/// Crypto operations resolve through the context. Resolution prefers a provider +/// bound with [`Context::with_crypto`], then the process-wide provider installed +/// with [`crate::crypto::install_default`]. A bare `Context::new()` has no +/// explicit binding and returns [`crate::ErrorKind::ConfigInvalid`] when crypto +/// is first needed without a process-wide provider. Creating or cloning a +/// context never installs or freezes a global provider. +/// /// ## Example /// /// ``` @@ -46,6 +56,7 @@ pub struct Context { http: Arc, env: Arc, cmd: Arc, + crypto: Option>, } impl Debug for Context { @@ -55,6 +66,7 @@ impl Debug for Context { .field("http", &self.http) .field("env", &self.env) .field("cmd", &self.cmd) + .field("crypto", &self.crypto) .finish() } } @@ -87,6 +99,7 @@ impl Context { http: Arc::new(NoopHttpSend), env: Arc::new(NoopEnv), cmd: Arc::new(NoopCommandExecute), + crypto: None, } } @@ -114,6 +127,41 @@ impl Context { self } + /// Bind a cryptographic provider to this context. + /// + /// An explicitly bound provider has the highest priority for every crypto + /// operation performed through this context. It does not affect the + /// process-wide provider or other contexts. + pub fn with_crypto(mut self, provider: impl CryptoProvider) -> Self { + self.crypto = Some(Arc::new(provider)); + self + } + + /// Resolve the cryptographic provider for this context. + /// + /// Resolution order is: + /// + /// 1. the provider bound with [`Context::with_crypto`]; + /// 2. the process-wide provider installed with + /// [`crate::crypto::install_default`]. + /// + /// If neither is available this returns [`crate::ErrorKind::ConfigInvalid`] + /// at the point of use. Resolution never installs or freezes a provider. + /// An unbound context observes the current process-wide registration; a + /// context that already has an explicit binding keeps it. + pub fn crypto_provider(&self) -> Result<&dyn CryptoProvider> { + if let Some(provider) = &self.crypto { + return Ok(provider.as_ref()); + } + if let Some(provider) = crypto::get_default() { + return Ok(provider.as_ref()); + } + + Err(Error::config_invalid( + "no CryptoProvider is available; bind one with Context::with_crypto or install a process-wide default", + )) + } + /// Read the file content entirely in `Vec`. #[inline] pub async fn file_read(&self, path: &str) -> Result> { diff --git a/core/src/crypto.rs b/core/src/crypto.rs new file mode 100644 index 00000000..eeed186e --- /dev/null +++ b/core/src/crypto.rs @@ -0,0 +1,142 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Process-wide cryptographic provider. +//! +//! Reqsign does not bundle a cryptographic implementation. A [`Context`](crate::Context) +//! resolves crypto operations with this priority: an explicit +//! [`Context::with_crypto`](crate::Context::with_crypto) binding, then the +//! process-wide provider installed with [`install_default`]. +//! +//! A process can install at most one global provider. Installation is not +//! idempotent: later attempts return the provider they tried to install and +//! leave the first provider in place. Contexts never install or freeze the +//! global slot; [`get_default`] only reads the current global registration. + +use std::fmt::Debug; +use std::sync::{Arc, OnceLock}; + +use crate::{Error, Result}; + +/// Cryptographic operations required by reqsign. +/// +/// The trait deliberately exposes only the digest, HMAC, signature, encryption, +/// and random-generation operations needed by reqsign's signing and credential +/// flows. Keeping this byte-oriented surface small lets different backend +/// crates implement it without exposing their own key, digest, or signature +/// types. A context or the process-wide registration selects one provider for +/// all of these operations; callers do not compose individual algorithms from +/// different providers at runtime. +/// +/// The first four methods are mandatory. A provider implements the remaining +/// methods when it supports the corresponding operation; the default +/// implementations return [`crate::ErrorKind::ConfigInvalid`] so that a minimal +/// provider can serve services that only need hashing and MACs. +/// +/// Implementations must be safe to call concurrently and must not retain mutable +/// per-call state between invocations. +pub trait CryptoProvider: Debug + Send + Sync + 'static { + /// Compute the SHA-1 digest of `input`. + fn sha1(&self, input: &[u8]) -> Result<[u8; 20]>; + + /// Compute the SHA-256 digest of `input`. + fn sha256(&self, input: &[u8]) -> Result<[u8; 32]>; + + /// Compute HMAC-SHA-1 over `input` with `key`. + fn hmac_sha1(&self, key: &[u8], input: &[u8]) -> Result<[u8; 20]>; + + /// Compute HMAC-SHA-256 over `input` with `key`. + fn hmac_sha256(&self, key: &[u8], input: &[u8]) -> Result<[u8; 32]>; + + /// RSASSA-PKCS1-v1_5 with SHA-256 over `message`. + /// + /// `private_key_pem` is an unencrypted PKCS#8 (`PRIVATE KEY`) or PKCS#1 + /// (`RSA PRIVATE KEY`) PEM document. The returned bytes are the signature + /// in big-endian, fixed-width form as required by RS256. + fn rsa_pkcs1v15_sha256_sign(&self, private_key_pem: &[u8], message: &[u8]) -> Result> { + let _ = (private_key_pem, message); + Err(Error::config_invalid( + "configured CryptoProvider does not support RSA PKCS#1 v1.5 SHA-256 signing", + )) + } + + /// ECDSA over NIST P-256 with SHA-256 over `message`. + /// + /// `private_key_scalar` is the big-endian 32-byte private scalar in the + /// range `1 <= d < n`. The returned bytes are an ASN.1 DER signature. + fn ecdsa_p256_sha256_sign( + &self, + private_key_scalar: &[u8; 32], + message: &[u8], + ) -> Result> { + let _ = (private_key_scalar, message); + Err(Error::config_invalid( + "configured CryptoProvider does not support ECDSA P-256 SHA-256 signing", + )) + } + + /// AES-128-GCM (16-byte key) or AES-256-GCM (32-byte key) encryption. + /// + /// `nonce` is a 12-byte GCM nonce. `aad` is authenticated but not + /// encrypted. The returned bytes are `ciphertext || 16-byte tag`. + fn aes_gcm_encrypt( + &self, + key: &[u8], + nonce: &[u8; 12], + aad: &[u8], + plaintext: &[u8], + ) -> Result> { + let _ = (key, nonce, aad, plaintext); + Err(Error::config_invalid( + "configured CryptoProvider does not support AES-GCM encryption", + )) + } + + /// Fill `dest` with cryptographically secure random bytes. + fn fill_random(&self, dest: &mut [u8]) -> Result<()> { + let _ = dest; + Err(Error::config_invalid( + "configured CryptoProvider does not support random byte generation", + )) + } +} + +static DEFAULT_PROVIDER: OnceLock> = OnceLock::new(); + +/// Install the process-wide [`CryptoProvider`]. +/// +/// Installation succeeds at most once per process. Concurrent calls are safe; +/// exactly one caller succeeds and every other caller receives an error holding +/// the provider it attempted to install. A failed installation does not replace +/// the provider that was installed first. +pub fn install_default( + provider: impl CryptoProvider, +) -> std::result::Result<(), Arc> { + let provider: Arc = Arc::new(provider); + match DEFAULT_PROVIDER.set(provider) { + Ok(()) => Ok(()), + Err(provider) => Err(provider), + } +} + +/// Return the installed process-wide [`CryptoProvider`], if any. +/// +/// This only reads the current state. Reading `None` before installation does +/// not prevent a later [`install_default`] call from succeeding. +pub fn get_default() -> Option<&'static Arc> { + DEFAULT_PROVIDER.get() +} diff --git a/core/src/hash.rs b/core/src/hash.rs index 7300d8d5..4d752d37 100644 --- a/core/src/hash.rs +++ b/core/src/hash.rs @@ -16,16 +16,18 @@ // under the License. //! Hash related utils. +//! +//! Encoding helpers are pure functions. Digest and MAC helpers require a +//! [`CryptoProvider`] selected by the caller. Callers with a +//! [`Context`](crate::Context) resolve it with +//! [`Context::crypto_provider`](crate::Context::crypto_provider); helpers never +//! fall back to the process-wide registration on their own. use crate::Error; +use crate::Result; +use crate::crypto::CryptoProvider; use base64::Engine; use base64::prelude::BASE64_STANDARD; -use hmac::Hmac; -use hmac::KeyInit; -use hmac::Mac; -use sha1::Sha1; -use sha2::Digest; -use sha2::Sha256; /// Base64 encode pub fn base64_encode(content: &[u8]) -> String { @@ -39,69 +41,64 @@ pub fn base64_decode(content: &str) -> crate::Result> { .map_err(|e| Error::unexpected("base64 decode failed").with_source(e)) } -/// Hex encoded SHA1 hash. -/// -/// Use this function instead of `hex::encode(sha1(content))` can reduce -/// extra copy. -pub fn hex_sha1(content: &[u8]) -> String { - hex::encode(Sha1::digest(content)) +/// SHA1 digest. +pub fn sha1(provider: &dyn CryptoProvider, content: &[u8]) -> Result<[u8; 20]> { + provider.sha1(content) } -/// Hex encoded SHA256 hash. -/// -/// Use this function instead of `hex::encode(sha256(content))` can reduce -/// extra copy. -pub fn hex_sha256(content: &[u8]) -> String { - hex::encode(Sha256::digest(content)) +/// SHA256 digest. +pub fn sha256(provider: &dyn CryptoProvider, content: &[u8]) -> Result<[u8; 32]> { + provider.sha256(content) +} + +/// HMAC with SHA1 hash. +pub fn hmac_sha1(provider: &dyn CryptoProvider, key: &[u8], content: &[u8]) -> Result<[u8; 20]> { + provider.hmac_sha1(key, content) } /// HMAC with SHA256 hash. -pub fn hmac_sha256(key: &[u8], content: &[u8]) -> Vec { - // SAFETY: HMAC's new_from_slice always returns Ok - it handles any key length - let mut h = Hmac::::new_from_slice(key).unwrap(); - h.update(content); +pub fn hmac_sha256(provider: &dyn CryptoProvider, key: &[u8], content: &[u8]) -> Result<[u8; 32]> { + provider.hmac_sha256(key, content) +} - h.finalize().into_bytes().to_vec() +/// Hex encoded SHA1 hash. +pub fn hex_sha1(provider: &dyn CryptoProvider, content: &[u8]) -> Result { + Ok(hex::encode(sha1(provider, content)?)) } -/// Base64 encoded HMAC with SHA256 hash. -pub fn base64_hmac_sha256(key: &[u8], content: &[u8]) -> String { - // SAFETY: HMAC's new_from_slice always returns Ok - it handles any key length - let mut h = Hmac::::new_from_slice(key).unwrap(); - h.update(content); +/// Hex encoded SHA256 hash. +pub fn hex_sha256(provider: &dyn CryptoProvider, content: &[u8]) -> Result { + Ok(hex::encode(sha256(provider, content)?)) +} - base64_encode(&h.finalize().into_bytes()) +/// Base64 encoded HMAC with SHA256 hash. +pub fn base64_hmac_sha256( + provider: &dyn CryptoProvider, + key: &[u8], + content: &[u8], +) -> Result { + Ok(base64_encode(&hmac_sha256(provider, key, content)?)) } /// Hex encoded HMAC with SHA1 hash. -/// -/// Use this function instead of `hex::encode(hmac_sha1(key, content))` can -/// reduce extra copy. -pub fn hex_hmac_sha1(key: &[u8], content: &[u8]) -> String { - // SAFETY: HMAC's new_from_slice always returns Ok - it handles any key length - let mut h = Hmac::::new_from_slice(key).unwrap(); - h.update(content); - - hex::encode(h.finalize().into_bytes()) +pub fn hex_hmac_sha1(provider: &dyn CryptoProvider, key: &[u8], content: &[u8]) -> Result { + Ok(hex::encode(hmac_sha1(provider, key, content)?)) } /// Hex encoded HMAC with SHA256 hash. -/// -/// Use this function instead of `hex::encode(hmac_sha256(key, content))` can -/// reduce extra copy. -pub fn hex_hmac_sha256(key: &[u8], content: &[u8]) -> String { - // SAFETY: HMAC's new_from_slice always returns Ok - it handles any key length - let mut h = Hmac::::new_from_slice(key).unwrap(); - h.update(content); - - hex::encode(h.finalize().into_bytes()) +pub fn hex_hmac_sha256( + provider: &dyn CryptoProvider, + key: &[u8], + content: &[u8], +) -> Result { + Ok(hex::encode(hmac_sha256(provider, key, content)?)) } /// Base64 encoded HMAC with SHA1 hash. -pub fn base64_hmac_sha1(key: &[u8], content: &[u8]) -> String { - // SAFETY: HMAC's new_from_slice always returns Ok - it handles any key length - let mut h = Hmac::::new_from_slice(key).unwrap(); - h.update(content); - - base64_encode(&h.finalize().into_bytes()) +pub fn base64_hmac_sha1( + provider: &dyn CryptoProvider, + key: &[u8], + content: &[u8], +) -> Result { + Ok(base64_encode(&hmac_sha1(provider, key, content)?)) } diff --git a/core/src/jwt.rs b/core/src/jwt.rs deleted file mode 100644 index 413ff8fb..00000000 --- a/core/src/jwt.rs +++ /dev/null @@ -1,153 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -//! JWT encoding helpers. - -use base64::Engine; -use base64::engine::general_purpose::URL_SAFE_NO_PAD; -use rsa::RsaPrivateKey; -use rsa::pkcs1v15::SigningKey; -use rsa::pkcs8::DecodePrivateKey; -use rsa::rand_core::OsRng; -use rsa::sha2::Sha256; -use rsa::signature::{RandomizedSigner, SignatureEncoding}; -use serde::Serialize; - -use crate::{Error, Result}; - -/// Encode a JWS compact JWT using the RS256 algorithm. -/// -/// 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(header: &H, claims: &C, private_key: &RsaPrivateKey) -> Result -where - H: Serialize, - C: Serialize, -{ - let encoded_header = encode_json(header)?; - let encoded_claims = encode_json(claims)?; - let signing_input = format!("{encoded_header}.{encoded_claims}"); - - let mut rng = OsRng; - let signing_key = SigningKey::::new(private_key.clone()); - let signature = signing_key.sign_with_rng(&mut rng, signing_input.as_bytes()); - let encoded_signature = URL_SAFE_NO_PAD.encode(signature.to_bytes()); - - Ok(format!("{signing_input}.{encoded_signature}")) -} - -/// Encode a JWS compact JWT using an RSA private key in PKCS#8 PEM format. -pub fn encode_rs256_pem(header: &H, claims: &C, private_key_pem: &[u8]) -> Result -where - H: Serialize, - C: Serialize, -{ - 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| { - Error::credential_invalid("failed to parse PKCS#8 RSA private key PEM").with_source(e) - })?; - - encode_rs256(header, claims, &private_key) -} - -fn encode_json(value: &T) -> Result -where - T: Serialize, -{ - let json = serde_json::to_vec(value) - .map_err(|e| Error::unexpected("failed to serialize JWT JSON").with_source(e))?; - Ok(URL_SAFE_NO_PAD.encode(json)) -} - -#[cfg(test)] -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; - - #[derive(Serialize)] - struct Header<'a> { - alg: &'a str, - typ: &'a str, - x5t: &'a str, - } - - #[derive(Serialize)] - struct Claims<'a> { - iss: &'a str, - sub: &'a str, - aud: &'a str, - exp: u64, - } - - #[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::>(); - 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::::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(()) - } -} diff --git a/core/src/lib.rs b/core/src/lib.rs index 324e35ee..d7ebd842 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -173,16 +173,16 @@ //! //! The crate also provides utility modules: //! -//! - [`hash`]: Cryptographic hashing utilities +//! - [`crypto`]: Process-wide cryptographic provider +//! - [`hash`]: Cryptographic hashing and encoding utilities //! - [`time`]: Time manipulation utilities //! - [`utils`]: General utilities including data redaction // Make sure all our public APIs have docs. #![warn(missing_docs)] +pub mod crypto; pub mod hash; -#[cfg(all(not(target_arch = "wasm32"), feature = "jwt"))] -pub mod jwt; pub mod time; pub mod utils; diff --git a/core/tests/crypto_provider_context.rs b/core/tests/crypto_provider_context.rs new file mode 100644 index 00000000..ca2fd4f6 --- /dev/null +++ b/core/tests/crypto_provider_context.rs @@ -0,0 +1,88 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +mod support; + +use reqsign_core::crypto::{get_default, install_default}; +use reqsign_core::{Context, hash}; +use support::ByteProvider; + +#[test] +fn context_resolution_prefers_explicit_then_global() { + let bare = Context::new(); + assert!( + bare.crypto_provider().is_err(), + "a bare context must fail before a global provider exists" + ); + + let explicit = Context::new().with_crypto(ByteProvider(2)); + assert_eq!( + hash::sha256( + explicit.crypto_provider().expect("explicit must resolve"), + b"x" + ) + .expect("explicit hashing must succeed"), + [2; 32] + ); + + let unbound = Context::new(); + assert!( + get_default().is_none(), + "creating a context must not install" + ); + install_default(ByteProvider(9)).expect("global installation must succeed"); + + assert_eq!( + hash::sha256( + unbound.crypto_provider().expect("global must resolve"), + b"x" + ) + .expect("global hashing must succeed"), + [9; 32], + "an unbound context must observe the process-wide provider" + ); + assert_eq!( + hash::sha256( + explicit.crypto_provider().expect("explicit must resolve"), + b"x" + ) + .expect("explicit hashing must succeed"), + [2; 32], + "an explicit binding must keep priority over the global provider" + ); + + let first = Context::new().with_crypto(ByteProvider(4)); + let second = Context::new().with_crypto(ByteProvider(5)); + assert_eq!( + hash::sha256( + first.crypto_provider().expect("first context must resolve"), + b"x" + ) + .expect("first context hashing must succeed"), + [4; 32] + ); + assert_eq!( + hash::sha256( + second + .crypto_provider() + .expect("second context must resolve"), + b"x" + ) + .expect("second context hashing must succeed"), + [5; 32] + ); +} diff --git a/core/tests/crypto_provider_early_lookup.rs b/core/tests/crypto_provider_early_lookup.rs new file mode 100644 index 00000000..4f77b29e --- /dev/null +++ b/core/tests/crypto_provider_early_lookup.rs @@ -0,0 +1,31 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +mod support; + +use reqsign_core::crypto::{get_default, install_default}; +use support::TestProvider; + +#[test] +fn early_lookup_does_not_freeze_an_unset_provider() { + assert!( + get_default().is_none(), + "this binary starts without a provider" + ); + assert!(install_default(TestProvider::new("first")).is_ok()); + assert!(get_default().is_some()); +} diff --git a/core/tests/crypto_provider_second_install.rs b/core/tests/crypto_provider_second_install.rs new file mode 100644 index 00000000..2d46ffc9 --- /dev/null +++ b/core/tests/crypto_provider_second_install.rs @@ -0,0 +1,52 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +mod support; + +use reqsign_core::crypto::{get_default, install_default}; +use support::ByteProvider; + +#[test] +fn second_installation_returns_the_rejected_provider_without_replacing_first() { + install_default(ByteProvider(1)).expect("first install must succeed"); + let installed = get_default().expect("provider must be installed"); + assert_eq!( + installed + .sha256(b"probe") + .expect("installed provider hashing must succeed"), + [1; 32], + "the first provider must be installed" + ); + + let rejected = install_default(ByteProvider(2)).expect_err("second install must be rejected"); + + assert_eq!( + rejected + .sha256(b"probe") + .expect("rejected provider hashing must succeed"), + [2; 32], + "the error must return the provider that was not installed" + ); + assert_eq!( + get_default() + .expect("provider must stay installed") + .sha256(b"probe") + .expect("installed provider hashing must succeed"), + [1; 32], + "the first provider must remain installed" + ); +} diff --git a/core/tests/crypto_provider_unset.rs b/core/tests/crypto_provider_unset.rs new file mode 100644 index 00000000..f420fc93 --- /dev/null +++ b/core/tests/crypto_provider_unset.rs @@ -0,0 +1,34 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! This test binary runs without a provider on purpose. Keep it as a separate +//! test target so another test cannot install a provider into the same process. + +use reqsign_core::Context; +use reqsign_core::ErrorKind; +use reqsign_core::crypto::get_default; + +#[test] +fn bare_context_without_a_provider_returns_config_invalid() { + assert!(get_default().is_none()); + + let err = Context::new() + .crypto_provider() + .expect_err("a bare context without a provider must fail"); + assert_eq!(err.kind(), ErrorKind::ConfigInvalid); + assert!(!err.is_retryable()); +} diff --git a/core/tests/support/mod.rs b/core/tests/support/mod.rs new file mode 100644 index 00000000..bda533ba --- /dev/null +++ b/core/tests/support/mod.rs @@ -0,0 +1,74 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#![allow(dead_code)] + +use reqsign_core::Result; +use reqsign_core::crypto::CryptoProvider; + +/// Minimal provider used to test installation and hash delegation without +/// linking a second copy of `reqsign-core` through a provider crate. +#[derive(Debug)] +pub struct TestProvider { + pub name: &'static str, +} + +impl TestProvider { + pub fn new(name: &'static str) -> Self { + Self { name } + } +} + +impl CryptoProvider for TestProvider { + fn sha1(&self, _input: &[u8]) -> Result<[u8; 20]> { + Ok([1; 20]) + } + + fn sha256(&self, _input: &[u8]) -> Result<[u8; 32]> { + Ok([2; 32]) + } + + fn hmac_sha1(&self, _key: &[u8], _input: &[u8]) -> Result<[u8; 20]> { + Ok([3; 20]) + } + + fn hmac_sha256(&self, _key: &[u8], _input: &[u8]) -> Result<[u8; 32]> { + Ok([4; 32]) + } +} + +/// Provider whose digests identify the provider without using real crypto. +#[derive(Debug)] +pub struct ByteProvider(pub u8); + +impl CryptoProvider for ByteProvider { + fn sha1(&self, _input: &[u8]) -> Result<[u8; 20]> { + Ok([self.0; 20]) + } + + fn sha256(&self, _input: &[u8]) -> Result<[u8; 32]> { + Ok([self.0; 32]) + } + + fn hmac_sha1(&self, _key: &[u8], _input: &[u8]) -> Result<[u8; 20]> { + Ok([self.0; 20]) + } + + fn hmac_sha256(&self, _key: &[u8], _input: &[u8]) -> Result<[u8; 32]> { + Ok([self.0; 32]) + } +} diff --git a/crypto/boring/Cargo.toml b/crypto/boring/Cargo.toml new file mode 100644 index 00000000..cb1e5a90 --- /dev/null +++ b/crypto/boring/Cargo.toml @@ -0,0 +1,46 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +[package] +name = "reqsign-crypto-boring" +version = "1.0.0" + +categories = ["authentication", "cryptography"] +description = "BoringSSL backend for reqsign." +edition = "2024" +license = "Apache-2.0" +repository = "https://github.com/apache/reqsign" +rust-version = "1.86.0" + +[features] +default = [] +fips = ["boring/fips"] + +[dependencies] +boring = "5.5.1" +reqsign-core = { version = "3.3.4", path = "../../core" } + +[dev-dependencies] +hex = "0.4" +hmac = "0.13" +http = "1" +p256 = { version = "0.14.0", default-features = false, features = ["ecdsa"] } +reqsign-aws-core = { version = "3.4.0", path = "../../services/aws-core" } +reqsign-aws-v4 = { version = "3.5.0", path = "../../services/aws-v4" } +reqsign-crypto-rustcrypto = { version = "1.0.0", path = "../rustcrypto" } +sha2 = "0.11" +tokio = { version = "1", features = ["macros", "rt"] } diff --git a/crypto/boring/src/lib.rs b/crypto/boring/src/lib.rs new file mode 100644 index 00000000..2241829a --- /dev/null +++ b/crypto/boring/src/lib.rs @@ -0,0 +1,207 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! BoringSSL [`CryptoProvider`] for reqsign. +//! +//! The provider implements every operation with BoringSSL's safe, one-shot +//! APIs. Each call creates and drops its own BoringSSL context, so concurrent +//! calls do not share mutable state and the crate contains no `unsafe` code. +//! +//! This crate is excluded from the reqsign workspace: building it requires a +//! C/C++ toolchain and CMake, and the main workspace must stay pure Rust. The +//! `fips` feature forwards to `boring/fips`. + +use std::sync::Arc; + +use boring::aead::{AeadCtx, Algorithm}; +use boring::bn::{BigNum, BigNumContext}; +use boring::ec::{EcGroup, EcKey, EcPoint}; +use boring::ecdsa::EcdsaSig; +use boring::hash::{MessageDigest, hash}; +use boring::hmac::Hmac; +use boring::nid::Nid; +use boring::pkey::{Id, PKey, Private}; +use boring::rsa::Padding; +use boring::sign::Signer; +use reqsign_core::crypto::{self, CryptoProvider}; +use reqsign_core::{Error, Result}; + +/// BoringSSL implementation of [`CryptoProvider`]. +#[derive(Debug, Default)] +pub struct BoringCryptoProvider; + +impl BoringCryptoProvider { + /// Create a BoringSSL provider. + pub fn new() -> Self { + Self + } + + /// Install this provider as the process-wide default. + /// + /// See [`reqsign_core::crypto::install_default`] for the installation + /// contract. + pub fn install_default() -> std::result::Result<(), Arc> { + crypto::install_default(Self) + } +} + +fn unexpected( + context: &'static str, + source: impl std::error::Error + Send + Sync + 'static, +) -> Error { + Error::unexpected(context).with_source(source) +} + +fn digest(md: MessageDigest, input: &[u8]) -> Result<[u8; N]> { + let bytes = hash(md, input).map_err(|e| unexpected("BoringSSL hashing failed", e))?; + bytes + .as_ref() + .try_into() + .map_err(|_| Error::unexpected("BoringSSL produced an unexpected digest length")) +} + +fn hmac(md: MessageDigest, key: &[u8], input: &[u8]) -> Result<[u8; N]> { + let mut hmac = + Hmac::init(key, &md).map_err(|e| unexpected("failed to initialize BoringSSL HMAC", e))?; + hmac.update(input) + .map_err(|e| unexpected("BoringSSL HMAC update failed", e))?; + let bytes = hmac + .finalize() + .map_err(|e| unexpected("BoringSSL HMAC finalization failed", e))?; + bytes + .as_slice() + .try_into() + .map_err(|_| Error::unexpected("BoringSSL produced an unexpected HMAC length")) +} + +fn rsa_private_key(private_key_pem: &[u8]) -> Result> { + let private_key = PKey::private_key_from_pem(private_key_pem).map_err(|e| { + Error::credential_invalid("failed to parse RSA private key PEM").with_source(e) + })?; + if private_key.id() != Id::RSA { + return Err(Error::credential_invalid( + "private key PEM does not contain an RSA key", + )); + } + Ok(private_key) +} + +fn p256_private_key(private_key_scalar: &[u8; 32]) -> Result> { + let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1) + .map_err(|e| unexpected("failed to load the P-256 group", e))?; + let mut context = BigNumContext::new() + .map_err(|e| unexpected("failed to create a P-256 big number context", e))?; + let mut order = + BigNum::new().map_err(|e| unexpected("failed to allocate the P-256 group order", e))?; + group + .order(&mut order, &mut context) + .map_err(|e| unexpected("failed to read the P-256 group order", e))?; + let one = BigNum::from_u32(1) + .map_err(|e| unexpected("failed to allocate a P-256 scalar bound", e))?; + let scalar = BigNum::from_slice(private_key_scalar) + .map_err(|e| unexpected("failed to parse the P-256 private scalar", e))?; + + if scalar < one || scalar >= order { + return Err(Error::credential_invalid( + "ECDSA P-256 private key scalar is outside the valid range", + )); + } + + let mut public_key = EcPoint::new(&group) + .map_err(|e| unexpected("failed to allocate a P-256 public point", e))?; + public_key + .mul_generator(&group, &scalar, &mut context) + .map_err(|e| unexpected("failed to derive the P-256 public point", e))?; + EcKey::from_private_components(&group, &scalar, &public_key) + .map_err(|e| unexpected("failed to build the P-256 private key", e)) +} + +impl CryptoProvider for BoringCryptoProvider { + fn sha1(&self, input: &[u8]) -> Result<[u8; 20]> { + digest(MessageDigest::sha1(), input) + } + + fn sha256(&self, input: &[u8]) -> Result<[u8; 32]> { + digest(MessageDigest::sha256(), input) + } + + fn hmac_sha1(&self, key: &[u8], input: &[u8]) -> Result<[u8; 20]> { + hmac(MessageDigest::sha1(), key, input) + } + + fn hmac_sha256(&self, key: &[u8], input: &[u8]) -> Result<[u8; 32]> { + hmac(MessageDigest::sha256(), key, input) + } + + fn rsa_pkcs1v15_sha256_sign(&self, private_key_pem: &[u8], message: &[u8]) -> Result> { + let private_key = rsa_private_key(private_key_pem)?; + let mut signer = Signer::new(MessageDigest::sha256(), &private_key) + .map_err(|e| unexpected("failed to initialize RSA signing", e))?; + signer + .set_rsa_padding(Padding::PKCS1) + .map_err(|e| unexpected("failed to select RSA PKCS#1 v1.5 padding", e))?; + signer + .sign_oneshot_to_vec(message) + .map_err(|e| unexpected("RSA PKCS#1 v1.5 SHA-256 signing failed", e)) + } + + fn ecdsa_p256_sha256_sign( + &self, + private_key_scalar: &[u8; 32], + message: &[u8], + ) -> Result> { + let private_key = p256_private_key(private_key_scalar)?; + let digest = digest::<32>(MessageDigest::sha256(), message)?; + let signature = EcdsaSig::sign(&digest, &private_key) + .map_err(|e| unexpected("ECDSA P-256 signing failed", e))?; + signature + .to_der() + .map_err(|e| unexpected("failed to encode the ECDSA signature", e)) + } + + fn aes_gcm_encrypt( + &self, + key: &[u8], + nonce: &[u8; 12], + aad: &[u8], + plaintext: &[u8], + ) -> Result> { + let algorithm = match key.len() { + 16 => Algorithm::aes_128_gcm(), + 32 => Algorithm::aes_256_gcm(), + _ => { + return Err(Error::credential_invalid( + "AES-GCM key must be 16 or 32 bytes", + )); + } + }; + let mut context = AeadCtx::new_default_tag(&algorithm, key) + .map_err(|e| unexpected("failed to initialize AES-GCM", e))?; + let mut ciphertext = plaintext.to_vec(); + let mut tag = [0u8; 16]; + let tag = context + .seal_in_place_mut(nonce, &mut ciphertext, &mut tag, aad) + .map_err(|e| unexpected("AES-GCM encryption failed", e))?; + ciphertext.extend_from_slice(tag); + Ok(ciphertext) + } + + fn fill_random(&self, dest: &mut [u8]) -> Result<()> { + boring::rand::rand_bytes(dest) + .map_err(|e| unexpected("BoringSSL random generation failed", e)) + } +} diff --git a/crypto/boring/tests/fixtures/ec_p256_pkcs8.pem b/crypto/boring/tests/fixtures/ec_p256_pkcs8.pem new file mode 100644 index 00000000..e047b0e8 --- /dev/null +++ b/crypto/boring/tests/fixtures/ec_p256_pkcs8.pem @@ -0,0 +1,5 @@ +-----BEGIN PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgq9yLI9buS+bNa4NE +v/kj+1eGe3Vhv4xlzlr7Ji/nycChRANCAASWAk4Etk08LZa/3WSQxvFQLxtb1C2B +gJt2OhFEiG2wlwaQUn7STIoAykOejvOqUwuK0UYV5KkrrflbIWuf/lSz +-----END PRIVATE KEY----- diff --git a/crypto/boring/tests/fixtures/rsa_pkcs1.pem b/crypto/boring/tests/fixtures/rsa_pkcs1.pem new file mode 100644 index 00000000..e288b7c1 --- /dev/null +++ b/crypto/boring/tests/fixtures/rsa_pkcs1.pem @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEogIBAAKCAQEAnsTjUJMw3j44uhVLoMcTJUCXXaF2OrjThNXEthwArpnNhkrd +3TGKamz7VIUsXYL3lB6OgOCGsodWARqGfINI9B4oY0am6AfQvW4w4g2UZuoDPwhN +R3cx20JOFV8/XVvHkaQcTtG9tZeHrkb6f3KxUOPjYquU88JVWOJJTW70T540HW6a +j+kOWR4UulJKHPRvkgxQX85f4UHXnz0XWvLmKWSNbMv2EyOHwMGnTDk5fwxevkAr +14iUuWBRiku/54n1FaXc28fbJOdrml22NUWqC8AZZuJo3pFmdZ35Xzzbf636SNh3 +inbLN7ys4h1or2yZq5UsiKUkQLBKFNrD5iLwrQIDAQABAoIBAACYkJne05Ih/aiF +J/GEjcfYBDlvv7fctb6L5t8gH8iH/0N/yHFqHDDmE9NvZIk9UpyVuMc3EIpfA62h +YdvZyk5QRqqIu1unm9r6LOjMUEBKpJR5/YBFLES8bPqbjutUytz7FrgdBW9HEFVR +IuOTlKLPGC1oo3h+xD8/KjNGNViPJ/HlwZhmHOuo0C3pKKv15p3NBdeZXG44XTIW +2g8cR5cn627o+OyDk41f59nCZmcMIrkBgBXj6RYUT0A6nIsuJhvWKezomf/Hf7FR +oBSEQM5mYQWW7FqfOemrXagqEdLKqZUhX+FsPke69Ci/Zbh5HDBDuprjBkUTx/6/ +8QSD2YECgYEA3I5YRdfl5s5Pesse16hpvnzCC2Umgg0TgPHIjKqHMLj+RoS4Ttkh +Zq2DBljpj82Ffnz8TTYNV2hWbWgJQAdh1RQpLzTVYF6EC9m88MVaY/7DZ0Zz1gCO +PZf9bB8GnM8Gyj6C3HC3EypZQYnbdApLC3GaemftgncmJWWId8NsSXECgYEAuEii +TlBAOG3yJrWc/LzKnJSf+We2Z6FnJEEtn4qa2WiViKUNlQeJWEfXXrKHsIMtnov1 +uc0xYLWR32kqzRm2ZLQx/8nH6LAELwgaHLRBT8cSHE5HFnZiV826Onzari8bWeHL +MB/dKo0lGGdJyydjd/ugS4DXuqgviAjiJjJ2HP0CgYBtREgPMgq/8e4GU6MQDGt2 +56/qnU4amAfVlfNZXRJk3QF8RjxZM9EMYWHMPzhW+ebs51bHmcO6TgKjaStMAVxC +iB5vOKmNeMXKaTDlx6Akcg60l37Dwrq1YRs3+Zb5EMe4YofKVj0czZoyke2a646K +ONnjUqGkRQss88RMMRDwwQKBgEmX2BlmOv9OCPIkfPkBe/hj8i7rmBByiHoV/V5F +P+mqtmzHXVEynUrABeYvbbiz6jfytMLqitmQKR0LJqiZqBk3TPBVaJwoDsOpfKQR +6DMv0K+1IvZ5eHSQF9rbmYkODuIqJbamQvCHRVUlinay2CpGNpFwdrZ4C+NLiOSw +KjMRAoGABqdsYe0JENqpV0RRt4lgYRq22UqqRIhsPaxJhAq6Q93lUeFwktwEeMjm +/8B5xSVnXkEPzFf7gj3KEPXTj30Z5laeQaW4lwZ5tyrgZKJtQBtqttQAR6QQj7vL +LrDAnZuX5mRC5fj93/iZfFPFNf5eY+U0vBba5st0uM9mE7h9ZvU= +-----END RSA PRIVATE KEY----- diff --git a/crypto/boring/tests/fixtures/rsa_pkcs8.pem b/crypto/boring/tests/fixtures/rsa_pkcs8.pem new file mode 100644 index 00000000..97f97b4d --- /dev/null +++ b/crypto/boring/tests/fixtures/rsa_pkcs8.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCexONQkzDePji6 +FUugxxMlQJddoXY6uNOE1cS2HACumc2GSt3dMYpqbPtUhSxdgveUHo6A4Iayh1YB +GoZ8g0j0HihjRqboB9C9bjDiDZRm6gM/CE1HdzHbQk4VXz9dW8eRpBxO0b21l4eu +Rvp/crFQ4+Niq5TzwlVY4klNbvRPnjQdbpqP6Q5ZHhS6Ukoc9G+SDFBfzl/hQdef +PRda8uYpZI1sy/YTI4fAwadMOTl/DF6+QCvXiJS5YFGKS7/nifUVpdzbx9sk52ua +XbY1RaoLwBlm4mjekWZ1nflfPNt/rfpI2HeKdss3vKziHWivbJmrlSyIpSRAsEoU +2sPmIvCtAgMBAAECggEAAJiQmd7TkiH9qIUn8YSNx9gEOW+/t9y1vovm3yAfyIf/ +Q3/IcWocMOYT029kiT1SnJW4xzcQil8DraFh29nKTlBGqoi7W6eb2vos6MxQQEqk +lHn9gEUsRLxs+puO61TK3PsWuB0Fb0cQVVEi45OUos8YLWijeH7EPz8qM0Y1WI8n +8eXBmGYc66jQLekoq/Xmnc0F15lcbjhdMhbaDxxHlyfrbuj47IOTjV/n2cJmZwwi +uQGAFePpFhRPQDqciy4mG9Yp7OiZ/8d/sVGgFIRAzmZhBZbsWp856atdqCoR0sqp +lSFf4Ww+R7r0KL9luHkcMEO6muMGRRPH/r/xBIPZgQKBgQDcjlhF1+Xmzk96yx7X +qGm+fMILZSaCDROA8ciMqocwuP5GhLhO2SFmrYMGWOmPzYV+fPxNNg1XaFZtaAlA +B2HVFCkvNNVgXoQL2bzwxVpj/sNnRnPWAI49l/1sHwaczwbKPoLccLcTKllBidt0 +CksLcZp6Z+2CdyYlZYh3w2xJcQKBgQC4SKJOUEA4bfImtZz8vMqclJ/5Z7ZnoWck +QS2fiprZaJWIpQ2VB4lYR9desoewgy2ei/W5zTFgtZHfaSrNGbZktDH/ycfosAQv +CBoctEFPxxIcTkcWdmJXzbo6fNquLxtZ4cswH90qjSUYZ0nLJ2N3+6BLgNe6qC+I +COImMnYc/QKBgG1ESA8yCr/x7gZToxAMa3bnr+qdThqYB9WV81ldEmTdAXxGPFkz +0QxhYcw/OFb55uznVseZw7pOAqNpK0wBXEKIHm84qY14xcppMOXHoCRyDrSXfsPC +urVhGzf5lvkQx7hih8pWPRzNmjKR7Zrrjoo42eNSoaRFCyzzxEwxEPDBAoGASZfY +GWY6/04I8iR8+QF7+GPyLuuYEHKIehX9XkU/6aq2bMddUTKdSsAF5i9tuLPqN/K0 +wuqK2ZApHQsmqJmoGTdM8FVonCgOw6l8pBHoMy/Qr7Ui9nl4dJAX2tuZiQ4O4iol +tqZC8IdFVSWKdrLYKkY2kXB2tngL40uI5LAqMxECgYAGp2xh7QkQ2qlXRFG3iWBh +GrbZSqpEiGw9rEmECrpD3eVR4XCS3AR4yOb/wHnFJWdeQQ/MV/uCPcoQ9dOPfRnm +Vp5BpbiXBnm3KuBkom1AG2q21ABHpBCPu8susMCdm5fmZELl+P3f+Jl8U8U1/l5j +5TS8Ftrmy3S4z2YTuH1m9Q== +-----END PRIVATE KEY----- diff --git a/crypto/boring/tests/parity.rs b/crypto/boring/tests/parity.rs new file mode 100644 index 00000000..86b105af --- /dev/null +++ b/crypto/boring/tests/parity.rs @@ -0,0 +1,283 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use hmac::{Hmac, KeyInit, Mac}; +use p256::ecdsa::signature::Verifier; +use p256::ecdsa::{Signature, SigningKey, VerifyingKey}; +use reqsign_aws_core::Credential; +use reqsign_aws_v4::RequestSigner; +use reqsign_core::crypto::CryptoProvider; +use reqsign_core::{Context, ErrorKind, SignRequest}; +use reqsign_crypto_boring::BoringCryptoProvider; +use reqsign_crypto_rustcrypto::RustCryptoProvider; +use sha2::{Digest, Sha256}; + +const RSA_PKCS8: &[u8] = include_bytes!("fixtures/rsa_pkcs8.pem"); +const RSA_PKCS1: &[u8] = include_bytes!("fixtures/rsa_pkcs1.pem"); +const EC_PKCS8: &[u8] = include_bytes!("fixtures/ec_p256_pkcs8.pem"); + +fn boring() -> BoringCryptoProvider { + BoringCryptoProvider::new() +} + +fn rustcrypto() -> RustCryptoProvider { + RustCryptoProvider::new() +} + +#[test] +fn hashes_and_hmacs_match_rustcrypto() { + let boring = boring(); + let rustcrypto = rustcrypto(); + + for input in [&b""[..], b"abc", &[0u8; 65][..], &vec![b'x'; 100_000][..]] { + assert_eq!( + boring.sha1(input).expect("BoringSSL SHA-1 must succeed"), + rustcrypto + .sha1(input) + .expect("RustCrypto SHA-1 must succeed") + ); + assert_eq!( + boring + .sha256(input) + .expect("BoringSSL SHA-256 must succeed"), + rustcrypto + .sha256(input) + .expect("RustCrypto SHA-256 must succeed") + ); + } + + for key in [ + &b""[..], + &b"k"[..], + &[0u8; 64][..], + &[0u8; 65][..], + &[0xaa; 131][..], + ] { + for input in [&b""[..], b"boundary message", &vec![b'x'; 100_000][..]] { + assert_eq!( + boring + .hmac_sha1(key, input) + .expect("BoringSSL HMAC-SHA1 must succeed"), + rustcrypto + .hmac_sha1(key, input) + .expect("RustCrypto HMAC-SHA1 must succeed") + ); + assert_eq!( + boring + .hmac_sha256(key, input) + .expect("BoringSSL HMAC-SHA256 must succeed"), + rustcrypto + .hmac_sha256(key, input) + .expect("RustCrypto HMAC-SHA256 must succeed") + ); + } + } +} + +#[test] +fn rsa_signatures_match_rustcrypto_for_both_pem_formats() { + let boring = boring(); + let rustcrypto = rustcrypto(); + + for message in [&b""[..], b"message", &vec![b'x'; 100_000][..]] { + for pem in [RSA_PKCS8, RSA_PKCS1] { + assert_eq!( + boring + .rsa_pkcs1v15_sha256_sign(pem, message) + .expect("BoringSSL RSA signing must succeed"), + rustcrypto + .rsa_pkcs1v15_sha256_sign(pem, message) + .expect("RustCrypto RSA signing must succeed"), + "RSA PKCS#1 v1.5 signatures must be byte-identical" + ); + } + } +} + +#[test] +fn aes_gcm_output_matches_rustcrypto() { + let boring = boring(); + let rustcrypto = rustcrypto(); + + for key_len in [16, 32] { + let key = vec![0x42; key_len]; + let nonce = [0x24; 12]; + for (aad, plaintext) in [ + (&b""[..], &b""[..]), + (b"aad", b"message"), + (b"", &[0u8; 128][..]), + (b"header", &vec![b'p'; 10_000][..]), + ] { + assert_eq!( + boring + .aes_gcm_encrypt(&key, &nonce, aad, plaintext) + .expect("BoringSSL AES-GCM must succeed"), + rustcrypto + .aes_gcm_encrypt(&key, &nonce, aad, plaintext) + .expect("RustCrypto AES-GCM must succeed") + ); + } + } +} + +#[test] +fn ecdsa_signature_verifies_across_backends() { + let scalar = [7u8; 32]; + let signing_key = SigningKey::from_slice(&scalar).expect("test scalar must be valid"); + let verifying_key = VerifyingKey::from(&signing_key); + + for message in [&b""[..], b"message", &vec![b'x'; 100_000][..]] { + let boring_signature = boring() + .ecdsa_p256_sha256_sign(&scalar, message) + .expect("BoringSSL ECDSA signing must succeed"); + let boring_signature = + Signature::from_der(&boring_signature).expect("BoringSSL signature must be DER"); + verifying_key + .verify(message, &boring_signature) + .expect("BoringSSL signature must verify with p256"); + + let rustcrypto_signature = rustcrypto() + .ecdsa_p256_sha256_sign(&scalar, message) + .expect("RustCrypto ECDSA signing must succeed"); + let rustcrypto_signature = + Signature::from_der(&rustcrypto_signature).expect("RustCrypto signature must be DER"); + verifying_key + .verify(message, &rustcrypto_signature) + .expect("RustCrypto signature must verify with p256"); + } +} + +#[test] +fn invalid_key_material_maps_to_credential_invalid() { + let provider = boring(); + + assert_eq!( + provider + .rsa_pkcs1v15_sha256_sign(b"not a private key", b"message") + .expect_err("malformed key must fail") + .kind(), + ErrorKind::CredentialInvalid + ); + assert_eq!( + provider + .rsa_pkcs1v15_sha256_sign(EC_PKCS8, b"message") + .expect_err("non-RSA key must fail") + .kind(), + ErrorKind::CredentialInvalid + ); + + let order = hex::decode("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551") + .expect("P-256 order must decode"); + let mut order_bytes = [0u8; 32]; + order_bytes.copy_from_slice(&order); + for scalar in [[0u8; 32], order_bytes, [0xffu8; 32]] { + assert_eq!( + provider + .ecdsa_p256_sha256_sign(&scalar, b"message") + .expect_err("invalid scalar must fail") + .kind(), + ErrorKind::CredentialInvalid + ); + } + + for key in [&b""[..], &[0u8; 15][..], &[0u8; 31][..], &[0u8; 33][..]] { + assert_eq!( + provider + .aes_gcm_encrypt(key, &[0u8; 12], b"", b"message") + .expect_err("invalid AES key length must fail") + .kind(), + ErrorKind::CredentialInvalid + ); + } +} + +#[test] +fn fill_random_produces_distinct_nonzero_bytes() { + let provider = boring(); + let mut first = [0u8; 32]; + let mut second = [0u8; 32]; + provider + .fill_random(&mut first) + .expect("random must succeed"); + provider + .fill_random(&mut second) + .expect("random must succeed"); + assert_ne!(first, [0u8; 32]); + assert_ne!(first, second); + provider + .fill_random(&mut []) + .expect("filling an empty buffer must succeed"); +} + +#[tokio::test] +async fn aws_sigv4_end_to_end_matches_an_independent_hmac_implementation() { + let context = Context::new().with_crypto(BoringCryptoProvider::new()); + let credential = Credential { + access_key_id: "AKIDEXAMPLE".to_string(), + secret_access_key: "test-secret-key".to_string(), + session_token: None, + expires_in: None, + }; + let mut parts = http::Request::get("https://example.amazonaws.com/object") + .body(()) + .expect("request must build") + .into_parts() + .0; + + RequestSigner::new("s3", "test-region") + .sign_request(&context, &mut parts, Some(&credential), None) + .await + .expect("AWS SigV4 signing must succeed"); + + let date = parts.headers["x-amz-date"] + .to_str() + .expect("x-amz-date must be text"); + let canonical_request = format!( + "GET\n/object\n\nhost:example.amazonaws.com\n\ + x-amz-content-sha256:UNSIGNED-PAYLOAD\n\ + x-amz-date:{date}\n\n\ + host;x-amz-content-sha256;x-amz-date\n\ + UNSIGNED-PAYLOAD" + ); + let scope = format!("{}/{}/{}/aws4_request", &date[..8], "test-region", "s3"); + let string_to_sign = format!( + "AWS4-HMAC-SHA256\n{date}\n{scope}\n{}", + hex::encode(Sha256::digest(canonical_request.as_bytes())) + ); + let date_key = hmac_sha256( + format!("AWS4{}", credential.secret_access_key).as_bytes(), + &date.as_bytes()[..8], + ); + let region_key = hmac_sha256(&date_key, b"test-region"); + let service_key = hmac_sha256(®ion_key, b"s3"); + let signing_key = hmac_sha256(&service_key, b"aws4_request"); + let signature = hex::encode(hmac_sha256(&signing_key, string_to_sign.as_bytes())); + + let authorization = parts.headers[http::header::AUTHORIZATION] + .to_str() + .expect("authorization must be text"); + assert!( + authorization.ends_with(&format!("Signature={signature}")), + "unexpected SigV4 authorization: {authorization}" + ); +} + +fn hmac_sha256(key: &[u8], input: &[u8]) -> [u8; 32] { + let mut mac = Hmac::::new_from_slice(key).expect("HMAC accepts any key length"); + mac.update(input); + mac.finalize().into_bytes().into() +} diff --git a/crypto/rustcrypto/Cargo.toml b/crypto/rustcrypto/Cargo.toml new file mode 100644 index 00000000..c473abe1 --- /dev/null +++ b/crypto/rustcrypto/Cargo.toml @@ -0,0 +1,43 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +[package] +name = "reqsign-crypto-rustcrypto" +version = "1.0.0" + +categories = ["authentication", "cryptography"] +description = "RustCrypto backend for reqsign." + +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[dependencies] +hmac = { workspace = true } +p256 = { workspace = true } +reqsign-core = { workspace = true } +sha1 = { workspace = true } +sha2 = { workspace = true } + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +aes-gcm = { workspace = true, default-features = false, features = ["aes", "alloc"] } +getrandom = { workspace = true } +rsa = { workspace = true } + +[dev-dependencies] +hex = { workspace = true } diff --git a/crypto/rustcrypto/src/lib.rs b/crypto/rustcrypto/src/lib.rs new file mode 100644 index 00000000..035df380 --- /dev/null +++ b/crypto/rustcrypto/src/lib.rs @@ -0,0 +1,163 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Pure Rust [`CryptoProvider`] for reqsign based on the RustCrypto crates. +//! +//! The provider supports SHA-1, SHA-256, HMAC-SHA-1, HMAC-SHA-256 and +//! ECDSA P-256 on every target. RSA PKCS#1 v1.5, AES-GCM and secure random +//! generation are available on native targets. On `wasm32` those operations +//! inherit the trait's unsupported-operation error. + +use std::sync::Arc; + +use hmac::{Hmac, KeyInit, Mac}; +use p256::ecdsa::signature::Signer; +use p256::ecdsa::{DerSignature, SigningKey}; +use reqsign_core::crypto::{self, CryptoProvider}; +use reqsign_core::{Error, Result}; +use sha1::Sha1; +use sha2::{Digest, Sha256}; + +/// RustCrypto implementation of [`CryptoProvider`]. +#[derive(Debug, Default)] +pub struct RustCryptoProvider; + +impl RustCryptoProvider { + /// Create a RustCrypto provider. + pub fn new() -> Self { + Self + } + + /// Install this provider as the process-wide default. + /// + /// See [`reqsign_core::crypto::install_default`] for the installation + /// contract. + pub fn install_default() -> std::result::Result<(), Arc> { + crypto::install_default(Self) + } +} + +impl CryptoProvider for RustCryptoProvider { + fn sha1(&self, input: &[u8]) -> Result<[u8; 20]> { + Ok(Sha1::digest(input).into()) + } + + fn sha256(&self, input: &[u8]) -> Result<[u8; 32]> { + Ok(Sha256::digest(input).into()) + } + + fn hmac_sha1(&self, key: &[u8], input: &[u8]) -> Result<[u8; 20]> { + let mut mac = Hmac::::new_from_slice(key) + .map_err(|e| Error::unexpected("failed to initialize HMAC-SHA1").with_source(e))?; + mac.update(input); + Ok(mac.finalize().into_bytes().into()) + } + + fn hmac_sha256(&self, key: &[u8], input: &[u8]) -> Result<[u8; 32]> { + let mut mac = Hmac::::new_from_slice(key) + .map_err(|e| Error::unexpected("failed to initialize HMAC-SHA256").with_source(e))?; + mac.update(input); + Ok(mac.finalize().into_bytes().into()) + } + + #[cfg(not(target_arch = "wasm32"))] + fn rsa_pkcs1v15_sha256_sign(&self, private_key_pem: &[u8], message: &[u8]) -> Result> { + use rsa::pkcs1::DecodeRsaPrivateKey; + use rsa::pkcs1v15::SigningKey as RsaSigningKey; + use rsa::pkcs8::DecodePrivateKey; + use rsa::rand_core::OsRng; + use rsa::sha2::Sha256 as RsaSha256; + use rsa::signature::{RandomizedSigner, SignatureEncoding}; + + let 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 = rsa::RsaPrivateKey::from_pkcs8_pem(pem) + .or_else(|_| rsa::RsaPrivateKey::from_pkcs1_pem(pem)) + .map_err(|e| { + Error::credential_invalid("failed to parse RSA private key PEM").with_source(e) + })?; + + let signing_key = RsaSigningKey::::new(private_key); + let signature = signing_key + .try_sign_with_rng(&mut OsRng, message) + .map_err(|e| { + Error::unexpected("RSA PKCS#1 v1.5 SHA-256 signing failed").with_source(e) + })?; + Ok(signature.to_bytes().to_vec()) + } + + fn ecdsa_p256_sha256_sign( + &self, + private_key_scalar: &[u8; 32], + message: &[u8], + ) -> Result> { + let signing_key = SigningKey::from_slice(private_key_scalar).map_err(|e| { + Error::credential_invalid("invalid ECDSA P-256 private key scalar").with_source(e) + })?; + let signature: DerSignature = signing_key.sign(message); + Ok(signature.as_bytes().to_vec()) + } + + #[cfg(not(target_arch = "wasm32"))] + fn aes_gcm_encrypt( + &self, + key: &[u8], + nonce: &[u8; 12], + aad: &[u8], + plaintext: &[u8], + ) -> Result> { + use aes_gcm::aead::{Aead, KeyInit, Payload, array::Array}; + use aes_gcm::{Aes128Gcm, Aes256Gcm}; + + let ciphertext = match key.len() { + 16 => Aes128Gcm::new_from_slice(key) + .map_err(|e| Error::credential_invalid("invalid AES-128-GCM key").with_source(e))? + .encrypt( + &Array(*nonce), + Payload { + msg: plaintext, + aad, + }, + ) + .map_err(|e| Error::unexpected("AES-GCM encryption failed").with_source(e))?, + 32 => Aes256Gcm::new_from_slice(key) + .map_err(|e| Error::credential_invalid("invalid AES-256-GCM key").with_source(e))? + .encrypt( + &Array(*nonce), + Payload { + msg: plaintext, + aad, + }, + ) + .map_err(|e| Error::unexpected("AES-GCM encryption failed").with_source(e))?, + _ => { + return Err(Error::credential_invalid( + "AES-GCM key must be 16 or 32 bytes", + )); + } + }; + + Ok(ciphertext) + } + + #[cfg(not(target_arch = "wasm32"))] + fn fill_random(&self, dest: &mut [u8]) -> Result<()> { + getrandom::fill(dest) + .map_err(|e| Error::unexpected(format!("secure random generation failed: {e}"))) + } +} diff --git a/crypto/rustcrypto/tests/core_hash.rs b/crypto/rustcrypto/tests/core_hash.rs new file mode 100644 index 00000000..508e3598 --- /dev/null +++ b/crypto/rustcrypto/tests/core_hash.rs @@ -0,0 +1,103 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use reqsign_core::crypto::CryptoProvider; +use reqsign_core::hash; +use reqsign_core::hash::{ + base64_hmac_sha1, base64_hmac_sha256, hex_hmac_sha1, hex_hmac_sha256, hex_sha1, hex_sha256, + hmac_sha1, hmac_sha256, sha1, sha256, +}; +use reqsign_crypto_rustcrypto::RustCryptoProvider; + +const INPUT: &[u8] = b"GET /bucket/object?partNumber=1&uploadId=example"; +const KEY: &[u8] = b"reqsign-test-secret-key-material"; + +#[test] +fn hash_helpers_delegate_to_the_provider_with_expected_widths() { + let provider = RustCryptoProvider::new(); + let expected_sha1 = provider.sha1(INPUT).expect("SHA-1 must succeed"); + let expected_sha256 = provider.sha256(INPUT).expect("SHA-256 must succeed"); + + assert_eq!( + sha1(&provider, INPUT).expect("SHA-1 must succeed"), + expected_sha1 + ); + assert_eq!( + sha256(&provider, INPUT).expect("SHA-256 must succeed"), + expected_sha256 + ); + assert_eq!(expected_sha1.len(), 20); + assert_eq!(expected_sha256.len(), 32); + + assert_eq!( + hex_sha1(&provider, INPUT).expect("hex SHA-1 must succeed"), + hex::encode(expected_sha1) + ); + assert_eq!( + hex_sha256(&provider, INPUT).expect("hex SHA-256 must succeed"), + hex::encode(expected_sha256) + ); +} + +#[test] +fn hmac_helpers_preserve_key_and_input_with_expected_widths() { + let provider = RustCryptoProvider::new(); + let expected_sha1 = provider + .hmac_sha1(KEY, INPUT) + .expect("HMAC-SHA1 must succeed"); + let expected_sha256 = provider + .hmac_sha256(KEY, INPUT) + .expect("HMAC-SHA256 must succeed"); + + assert_eq!( + hmac_sha1(&provider, KEY, INPUT).expect("HMAC-SHA1 must succeed"), + expected_sha1 + ); + assert_eq!( + hmac_sha256(&provider, KEY, INPUT).expect("HMAC-SHA256 must succeed"), + expected_sha256 + ); + assert_eq!(expected_sha1.len(), 20); + assert_eq!(expected_sha256.len(), 32); + + assert_eq!( + hex_hmac_sha1(&provider, KEY, INPUT).expect("hex HMAC-SHA1 must succeed"), + hex::encode(expected_sha1) + ); + assert_eq!( + hex_hmac_sha256(&provider, KEY, INPUT).expect("hex HMAC-SHA256 must succeed"), + hex::encode(expected_sha256) + ); + assert_eq!( + base64_hmac_sha1(&provider, KEY, INPUT).expect("base64 HMAC-SHA1 must succeed"), + hash::base64_encode(&expected_sha1) + ); + assert_eq!( + base64_hmac_sha256(&provider, KEY, INPUT).expect("base64 HMAC-SHA256 must succeed"), + hash::base64_encode(&expected_sha256) + ); +} + +#[test] +fn base64_helpers_remain_pure_encoding_utilities() { + let encoded = hash::base64_encode(b"\x00binary\xff"); + assert_eq!( + hash::base64_decode(&encoded).expect("base64 decode must succeed"), + b"\x00binary\xff" + ); + assert_eq!(encoded, "AGJpbmFyef8="); +} diff --git a/crypto/rustcrypto/tests/fixtures/ec_p256_pkcs8.pem b/crypto/rustcrypto/tests/fixtures/ec_p256_pkcs8.pem new file mode 100644 index 00000000..e047b0e8 --- /dev/null +++ b/crypto/rustcrypto/tests/fixtures/ec_p256_pkcs8.pem @@ -0,0 +1,5 @@ +-----BEGIN PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgq9yLI9buS+bNa4NE +v/kj+1eGe3Vhv4xlzlr7Ji/nycChRANCAASWAk4Etk08LZa/3WSQxvFQLxtb1C2B +gJt2OhFEiG2wlwaQUn7STIoAykOejvOqUwuK0UYV5KkrrflbIWuf/lSz +-----END PRIVATE KEY----- diff --git a/crypto/rustcrypto/tests/fixtures/rsa_pkcs1.pem b/crypto/rustcrypto/tests/fixtures/rsa_pkcs1.pem new file mode 100644 index 00000000..e288b7c1 --- /dev/null +++ b/crypto/rustcrypto/tests/fixtures/rsa_pkcs1.pem @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEogIBAAKCAQEAnsTjUJMw3j44uhVLoMcTJUCXXaF2OrjThNXEthwArpnNhkrd +3TGKamz7VIUsXYL3lB6OgOCGsodWARqGfINI9B4oY0am6AfQvW4w4g2UZuoDPwhN +R3cx20JOFV8/XVvHkaQcTtG9tZeHrkb6f3KxUOPjYquU88JVWOJJTW70T540HW6a +j+kOWR4UulJKHPRvkgxQX85f4UHXnz0XWvLmKWSNbMv2EyOHwMGnTDk5fwxevkAr +14iUuWBRiku/54n1FaXc28fbJOdrml22NUWqC8AZZuJo3pFmdZ35Xzzbf636SNh3 +inbLN7ys4h1or2yZq5UsiKUkQLBKFNrD5iLwrQIDAQABAoIBAACYkJne05Ih/aiF +J/GEjcfYBDlvv7fctb6L5t8gH8iH/0N/yHFqHDDmE9NvZIk9UpyVuMc3EIpfA62h +YdvZyk5QRqqIu1unm9r6LOjMUEBKpJR5/YBFLES8bPqbjutUytz7FrgdBW9HEFVR +IuOTlKLPGC1oo3h+xD8/KjNGNViPJ/HlwZhmHOuo0C3pKKv15p3NBdeZXG44XTIW +2g8cR5cn627o+OyDk41f59nCZmcMIrkBgBXj6RYUT0A6nIsuJhvWKezomf/Hf7FR +oBSEQM5mYQWW7FqfOemrXagqEdLKqZUhX+FsPke69Ci/Zbh5HDBDuprjBkUTx/6/ +8QSD2YECgYEA3I5YRdfl5s5Pesse16hpvnzCC2Umgg0TgPHIjKqHMLj+RoS4Ttkh +Zq2DBljpj82Ffnz8TTYNV2hWbWgJQAdh1RQpLzTVYF6EC9m88MVaY/7DZ0Zz1gCO +PZf9bB8GnM8Gyj6C3HC3EypZQYnbdApLC3GaemftgncmJWWId8NsSXECgYEAuEii +TlBAOG3yJrWc/LzKnJSf+We2Z6FnJEEtn4qa2WiViKUNlQeJWEfXXrKHsIMtnov1 +uc0xYLWR32kqzRm2ZLQx/8nH6LAELwgaHLRBT8cSHE5HFnZiV826Onzari8bWeHL +MB/dKo0lGGdJyydjd/ugS4DXuqgviAjiJjJ2HP0CgYBtREgPMgq/8e4GU6MQDGt2 +56/qnU4amAfVlfNZXRJk3QF8RjxZM9EMYWHMPzhW+ebs51bHmcO6TgKjaStMAVxC +iB5vOKmNeMXKaTDlx6Akcg60l37Dwrq1YRs3+Zb5EMe4YofKVj0czZoyke2a646K +ONnjUqGkRQss88RMMRDwwQKBgEmX2BlmOv9OCPIkfPkBe/hj8i7rmBByiHoV/V5F +P+mqtmzHXVEynUrABeYvbbiz6jfytMLqitmQKR0LJqiZqBk3TPBVaJwoDsOpfKQR +6DMv0K+1IvZ5eHSQF9rbmYkODuIqJbamQvCHRVUlinay2CpGNpFwdrZ4C+NLiOSw +KjMRAoGABqdsYe0JENqpV0RRt4lgYRq22UqqRIhsPaxJhAq6Q93lUeFwktwEeMjm +/8B5xSVnXkEPzFf7gj3KEPXTj30Z5laeQaW4lwZ5tyrgZKJtQBtqttQAR6QQj7vL +LrDAnZuX5mRC5fj93/iZfFPFNf5eY+U0vBba5st0uM9mE7h9ZvU= +-----END RSA PRIVATE KEY----- diff --git a/crypto/rustcrypto/tests/fixtures/rsa_pkcs8.pem b/crypto/rustcrypto/tests/fixtures/rsa_pkcs8.pem new file mode 100644 index 00000000..97f97b4d --- /dev/null +++ b/crypto/rustcrypto/tests/fixtures/rsa_pkcs8.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCexONQkzDePji6 +FUugxxMlQJddoXY6uNOE1cS2HACumc2GSt3dMYpqbPtUhSxdgveUHo6A4Iayh1YB +GoZ8g0j0HihjRqboB9C9bjDiDZRm6gM/CE1HdzHbQk4VXz9dW8eRpBxO0b21l4eu +Rvp/crFQ4+Niq5TzwlVY4klNbvRPnjQdbpqP6Q5ZHhS6Ukoc9G+SDFBfzl/hQdef +PRda8uYpZI1sy/YTI4fAwadMOTl/DF6+QCvXiJS5YFGKS7/nifUVpdzbx9sk52ua +XbY1RaoLwBlm4mjekWZ1nflfPNt/rfpI2HeKdss3vKziHWivbJmrlSyIpSRAsEoU +2sPmIvCtAgMBAAECggEAAJiQmd7TkiH9qIUn8YSNx9gEOW+/t9y1vovm3yAfyIf/ +Q3/IcWocMOYT029kiT1SnJW4xzcQil8DraFh29nKTlBGqoi7W6eb2vos6MxQQEqk +lHn9gEUsRLxs+puO61TK3PsWuB0Fb0cQVVEi45OUos8YLWijeH7EPz8qM0Y1WI8n +8eXBmGYc66jQLekoq/Xmnc0F15lcbjhdMhbaDxxHlyfrbuj47IOTjV/n2cJmZwwi +uQGAFePpFhRPQDqciy4mG9Yp7OiZ/8d/sVGgFIRAzmZhBZbsWp856atdqCoR0sqp +lSFf4Ww+R7r0KL9luHkcMEO6muMGRRPH/r/xBIPZgQKBgQDcjlhF1+Xmzk96yx7X +qGm+fMILZSaCDROA8ciMqocwuP5GhLhO2SFmrYMGWOmPzYV+fPxNNg1XaFZtaAlA +B2HVFCkvNNVgXoQL2bzwxVpj/sNnRnPWAI49l/1sHwaczwbKPoLccLcTKllBidt0 +CksLcZp6Z+2CdyYlZYh3w2xJcQKBgQC4SKJOUEA4bfImtZz8vMqclJ/5Z7ZnoWck +QS2fiprZaJWIpQ2VB4lYR9desoewgy2ei/W5zTFgtZHfaSrNGbZktDH/ycfosAQv +CBoctEFPxxIcTkcWdmJXzbo6fNquLxtZ4cswH90qjSUYZ0nLJ2N3+6BLgNe6qC+I +COImMnYc/QKBgG1ESA8yCr/x7gZToxAMa3bnr+qdThqYB9WV81ldEmTdAXxGPFkz +0QxhYcw/OFb55uznVseZw7pOAqNpK0wBXEKIHm84qY14xcppMOXHoCRyDrSXfsPC +urVhGzf5lvkQx7hih8pWPRzNmjKR7Zrrjoo42eNSoaRFCyzzxEwxEPDBAoGASZfY +GWY6/04I8iR8+QF7+GPyLuuYEHKIehX9XkU/6aq2bMddUTKdSsAF5i9tuLPqN/K0 +wuqK2ZApHQsmqJmoGTdM8FVonCgOw6l8pBHoMy/Qr7Ui9nl4dJAX2tuZiQ4O4iol +tqZC8IdFVSWKdrLYKkY2kXB2tngL40uI5LAqMxECgYAGp2xh7QkQ2qlXRFG3iWBh +GrbZSqpEiGw9rEmECrpD3eVR4XCS3AR4yOb/wHnFJWdeQQ/MV/uCPcoQ9dOPfRnm +Vp5BpbiXBnm3KuBkom1AG2q21ABHpBCPu8susMCdm5fmZELl+P3f+Jl8U8U1/l5j +5TS8Ftrmy3S4z2YTuH1m9Q== +-----END PRIVATE KEY----- diff --git a/crypto/rustcrypto/tests/provider.rs b/crypto/rustcrypto/tests/provider.rs new file mode 100644 index 00000000..a63cf578 --- /dev/null +++ b/crypto/rustcrypto/tests/provider.rs @@ -0,0 +1,324 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use hmac::{Hmac, KeyInit, Mac}; +use p256::ecdsa::signature::Verifier; +use p256::ecdsa::{Signature, SigningKey, VerifyingKey}; +use reqsign_core::crypto::{CryptoProvider, get_default}; +use reqsign_core::{ErrorKind, Result}; +use reqsign_crypto_rustcrypto::RustCryptoProvider; +use rsa::RsaPrivateKey; +use rsa::pkcs1v15::{Signature as RsaSignature, VerifyingKey as RsaVerifyingKey}; +use rsa::pkcs8::DecodePrivateKey; +use rsa::sha2::Sha256 as RsaSha256; +use rsa::signature::Verifier as _; +use sha1::Sha1; +use sha2::{Digest, Sha256}; + +const RSA_PKCS8: &[u8] = include_bytes!("fixtures/rsa_pkcs8.pem"); +const RSA_PKCS1: &[u8] = include_bytes!("fixtures/rsa_pkcs1.pem"); +const EC_PKCS8: &[u8] = include_bytes!("fixtures/ec_p256_pkcs8.pem"); + +fn provider() -> RustCryptoProvider { + RustCryptoProvider::new() +} + +fn install_provider() { + let _ = RustCryptoProvider::install_default(); +} + +fn hex(bytes: &[u8]) -> String { + hex::encode(bytes) +} + +#[test] +fn installs_one_process_wide_provider() { + install_provider(); + assert!(get_default().is_some()); + assert!( + RustCryptoProvider::install_default().is_err(), + "a second installation must be rejected" + ); +} + +#[test] +fn hashes_delegate_to_the_expected_algorithms() { + let provider = provider(); + let large_input = vec![b'a'; 1_000_000]; + + for input in [&b""[..], b"abc", large_input.as_slice()] { + let expected_sha1: [u8; 20] = Sha1::digest(input).into(); + assert_eq!( + provider.sha1(input).expect("SHA-1 must succeed"), + expected_sha1 + ); + + let expected_sha256: [u8; 32] = Sha256::digest(input).into(); + assert_eq!( + provider.sha256(input).expect("SHA-256 must succeed"), + expected_sha256 + ); + } +} + +#[test] +fn hmac_handles_block_boundaries_without_changing_key_or_input() { + let provider = provider(); + let input = b"POST /object?uploadId=example HTTP/1.1"; + + for key in [ + &b""[..], + &b"k"[..], + &[0u8; 64][..], + &[0u8; 65][..], + &[0xaa; 80][..], + &[0xaa; 131][..], + ] { + assert_eq!( + provider + .hmac_sha1(key, input) + .expect("HMAC-SHA1 must succeed"), + reference_hmac_sha1(key, input) + ); + assert_eq!( + provider + .hmac_sha256(key, input) + .expect("HMAC-SHA256 must succeed"), + reference_hmac_sha256(key, input) + ); + } +} + +fn reference_hmac_sha1(key: &[u8], input: &[u8]) -> [u8; 20] { + let mut mac = Hmac::::new_from_slice(key).expect("HMAC accepts any key length"); + mac.update(input); + mac.finalize().into_bytes().into() +} + +fn reference_hmac_sha256(key: &[u8], input: &[u8]) -> [u8; 32] { + let mut mac = Hmac::::new_from_slice(key).expect("HMAC accepts any key length"); + mac.update(input); + mac.finalize().into_bytes().into() +} + +#[test] +fn rsa_signs_both_pkcs8_and_pkcs1_pem() { + let provider = provider(); + let public_key = RsaPrivateKey::from_pkcs8_pem(std::str::from_utf8(RSA_PKCS8).unwrap()) + .expect("test key must parse") + .to_public_key(); + let verifying_key = RsaVerifyingKey::::new(public_key); + + let large_message = vec![b'x'; 100_000]; + for message in [&b""[..], b"message", large_message.as_slice()] { + for pem in [RSA_PKCS8, RSA_PKCS1] { + let signature = provider + .rsa_pkcs1v15_sha256_sign(pem, message) + .expect("RSA signing must succeed"); + assert_eq!(signature.len(), 256); + let signature = + RsaSignature::try_from(signature.as_slice()).expect("signature must parse"); + verifying_key + .verify(message, &signature) + .expect("signature must verify"); + } + } +} + +#[test] +fn rsa_rejects_malformed_and_non_rsa_keys() { + let provider = provider(); + assert_eq!( + provider + .rsa_pkcs1v15_sha256_sign(b"not a private key", b"message") + .expect_err("malformed key must fail") + .kind(), + ErrorKind::CredentialInvalid + ); + assert_eq!( + provider + .rsa_pkcs1v15_sha256_sign(EC_PKCS8, b"message") + .expect_err("non-RSA key must fail") + .kind(), + ErrorKind::CredentialInvalid + ); +} + +#[test] +fn ecdsa_signature_verifies_with_p256() { + let provider = provider(); + let scalar = [7u8; 32]; + let signing_key = SigningKey::from_slice(&scalar).expect("test scalar must be valid"); + let verifying_key = VerifyingKey::from(&signing_key); + + let large_message = vec![b'x'; 100_000]; + for message in [&b""[..], b"message", large_message.as_slice()] { + let signature = provider + .ecdsa_p256_sha256_sign(&scalar, message) + .expect("ECDSA signing must succeed"); + let signature = Signature::from_der(&signature).expect("signature must be DER"); + verifying_key + .verify(message, &signature) + .expect("signature must verify"); + } +} + +#[test] +fn ecdsa_rejects_invalid_scalars() { + let provider = provider(); + let order = hex::decode("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551") + .expect("order must decode"); + let mut order_bytes = [0u8; 32]; + order_bytes.copy_from_slice(&order); + + for scalar in [[0u8; 32], order_bytes, [0xffu8; 32]] { + assert_eq!( + provider + .ecdsa_p256_sha256_sign(&scalar, b"message") + .expect_err("invalid scalar must fail") + .kind(), + ErrorKind::CredentialInvalid + ); + } +} + +#[test] +fn aes_gcm_matches_nist_vectors() { + let provider = provider(); + + assert_eq!( + hex(&provider + .aes_gcm_encrypt(&[0u8; 16], &[0u8; 12], b"", b"") + .expect("AES-128-GCM must succeed")), + "58e2fccefa7e3061367f1d57a4e7455a" + ); + assert_eq!( + hex(&provider + .aes_gcm_encrypt(&[0u8; 16], &[0u8; 12], b"", &[0u8; 16]) + .expect("AES-128-GCM must succeed")), + "0388dace60b6a392f328c2b971b2fe78ab6e47d42cec13bdf53a67b21257bddf" + ); + assert_eq!( + hex(&provider + .aes_gcm_encrypt(&[0u8; 32], &[0u8; 12], b"", b"") + .expect("AES-256-GCM must succeed")), + "530f8afbc74536b9a963b4f1c4cb738b" + ); + + let key = hex::decode("feffe9928665731c6d6a8f9467308308").expect("key must decode"); + let nonce: [u8; 12] = hex::decode("cafebabefacedbaddecaf888") + .expect("nonce must decode") + .try_into() + .expect("nonce must be 12 bytes"); + let plaintext = hex::decode( + "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39", + ) + .expect("plaintext must decode"); + let aad = hex::decode("feedfacedeadbeeffeedfacedeadbeefabaddad2").expect("aad must decode"); + assert_eq!( + hex(&provider + .aes_gcm_encrypt(&key, &nonce, &aad, &plaintext) + .expect("AES-128-GCM with AAD must succeed")), + "42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e21d514b25466931c7d8f6a5aac84aa051ba30b396a0aac973d58e0915bc94fbc3221a5db94fae95ae7121a47" + ); +} + +#[test] +fn aes_gcm_rejects_invalid_key_lengths() { + let provider = provider(); + for key in [&b""[..], &[0u8; 15][..], &[0u8; 31][..], &[0u8; 33][..]] { + assert_eq!( + provider + .aes_gcm_encrypt(key, &[0u8; 12], b"", b"message") + .expect_err("invalid key length must fail") + .kind(), + ErrorKind::CredentialInvalid + ); + } +} + +#[test] +fn fill_random_produces_distinct_nonzero_bytes() { + let provider = provider(); + let mut first = [0u8; 32]; + let mut second = [0u8; 32]; + provider + .fill_random(&mut first) + .expect("random must succeed"); + provider + .fill_random(&mut second) + .expect("random must succeed"); + assert_ne!(first, [0u8; 32]); + assert_ne!(first, second); + provider + .fill_random(&mut []) + .expect("filling an empty buffer must succeed"); +} + +#[derive(Debug)] +struct MinimalProvider; + +impl CryptoProvider for MinimalProvider { + fn sha1(&self, _: &[u8]) -> Result<[u8; 20]> { + Ok([0; 20]) + } + + fn sha256(&self, _: &[u8]) -> Result<[u8; 32]> { + Ok([0; 32]) + } + + fn hmac_sha1(&self, _: &[u8], _: &[u8]) -> Result<[u8; 20]> { + Ok([0; 20]) + } + + fn hmac_sha256(&self, _: &[u8], _: &[u8]) -> Result<[u8; 32]> { + Ok([0; 32]) + } +} + +#[test] +fn minimal_provider_reports_unsupported_operations_as_config_invalid() { + let provider = MinimalProvider; + assert_eq!( + provider + .rsa_pkcs1v15_sha256_sign(b"pem", b"message") + .expect_err("RSA must be unsupported") + .kind(), + ErrorKind::ConfigInvalid + ); + assert_eq!( + provider + .ecdsa_p256_sha256_sign(&[1; 32], b"message") + .expect_err("ECDSA must be unsupported") + .kind(), + ErrorKind::ConfigInvalid + ); + assert_eq!( + provider + .aes_gcm_encrypt(&[0; 16], &[0; 12], b"", b"message") + .expect_err("AES-GCM must be unsupported") + .kind(), + ErrorKind::ConfigInvalid + ); + assert_eq!( + provider + .fill_random(&mut [0; 8]) + .expect_err("random must be unsupported") + .kind(), + ErrorKind::ConfigInvalid + ); +} diff --git a/docs/crypto-provider.md b/docs/crypto-provider.md new file mode 100644 index 00000000..c052e993 --- /dev/null +++ b/docs/crypto-provider.md @@ -0,0 +1,386 @@ +# CryptoProvider API Design + +This document defines the repository's authoritative public contract for +request-signing cryptography in reqsign 4.x. Implementations that do not match +this document are legacy debt; new work and reviews must follow it. + +## Summary + +Reqsign no longer links a cryptographic implementation into `reqsign-core` or +any `services/*` crate. Hashing, MACs, asymmetric signing, AES-GCM encryption, +and secure random generation are provided by a +`reqsign_core::crypto::CryptoProvider` resolved through the `Context` supplied +to each signer, granter, or credential provider. + +The change is deliberately breaking: a context without a resolvable provider, +or a provider that does not implement a requested operation, returns +`ErrorKind::ConfigInvalid` instead of falling back to a bundled implementation. + +Two provider crates ship with this design: + +- `reqsign-crypto-rustcrypto`, a pure-Rust workspace member with + `wasm32-unknown-unknown` support for its supported subset. +- `reqsign-crypto-boring`, an independent, native-only crate built on + BoringSSL and excluded from the main workspace. + +Both provider crates start at `1.0.0` and version independently from the core +and service lockstep line and from each other. + +## Provider Contract + +```rust +pub trait CryptoProvider: Debug + Send + Sync + 'static { + fn sha1(&self, input: &[u8]) -> Result<[u8; 20]>; + fn sha256(&self, input: &[u8]) -> Result<[u8; 32]>; + fn hmac_sha1(&self, key: &[u8], input: &[u8]) -> Result<[u8; 20]>; + fn hmac_sha256(&self, key: &[u8], input: &[u8]) -> Result<[u8; 32]>; + + fn rsa_pkcs1v15_sha256_sign( + &self, + private_key_pem: &[u8], + message: &[u8], + ) -> Result>; + + fn ecdsa_p256_sha256_sign( + &self, + private_key_scalar: &[u8; 32], + message: &[u8], + ) -> Result>; + + fn aes_gcm_encrypt( + &self, + key: &[u8], + nonce: &[u8; 12], + aad: &[u8], + plaintext: &[u8], + ) -> Result>; + + fn fill_random(&self, dest: &mut [u8]) -> Result<()>; +} +``` + +The four hash/MAC methods are mandatory. The remaining four have default +implementations that return `ConfigInvalid`, so a minimal provider remains +useful for services that only need hashing. + +### Operation Semantics + +- `sha1` and `sha256` return the digest as a fixed-width byte array. +- `hmac_sha1` and `hmac_sha256` return the MAC as a fixed-width byte array. + HMAC accepts keys of any length, including empty and longer-than-block keys. +- `rsa_pkcs1v15_sha256_sign` implements RSASSA-PKCS1-v1_5 with SHA-256. The key + is an unencrypted PKCS#8 (`PRIVATE KEY`) or PKCS#1 (`RSA PRIVATE KEY`) PEM + document. The result is the big-endian signature with the modulus width. +- `ecdsa_p256_sha256_sign` implements ECDSA over NIST P-256 with SHA-256. The + scalar is the big-endian 32-byte private key in `1 <= d < n`. The result is an + ASN.1 DER signature. +- `aes_gcm_encrypt` implements AES-128-GCM for a 16-byte key and AES-256-GCM for + a 32-byte key. The nonce is exactly 12 bytes. AAD is authenticated and not + encrypted. The result is `ciphertext || 16-byte authentication tag`. +- `fill_random` fills the complete destination with bytes from a + cryptographically secure random source. + +Implementations must allow concurrent calls and must not share mutable +per-call state between invocations. A provider may keep immutable configuration, +but it must not be required to serialize signing operations for correctness. + +## Context Resolution + +`Context` owns crypto resolution for all work performed through it: + +```rust +impl Context { + pub fn with_crypto(self, provider: impl CryptoProvider) -> Self; + pub fn crypto_provider(&self) -> Result<&dyn CryptoProvider>; +} +``` + +`crypto_provider()` resolves in this order at the point of use: + +1. the provider bound with `Context::with_crypto`; +2. the process-wide provider installed with + `reqsign_core::crypto::install_default`; +3. otherwise `ErrorKind::ConfigInvalid`. + +The order is fixed. Resolution does not fall through because a provider returns +an error or reports an operation as unsupported. + +A context never installs or freezes the process-wide registration. Creating, +using, or cloning a context does not change `get_default()`. A context with an +explicit binding keeps that provider for its lifetime, including after a global +provider is installed later. An unbound context observes the current global +registration at the point of use. Cloning a context preserves its binding. + +`Context::new()` starts without an explicit binding. Resolution may still find +a process-wide provider; otherwise portable core code must bind a provider on +the context or install a global one. The facade's `default_context()` binds +RustCrypto when the global slot is empty at construction, as described below. + +## Global Registration + +```rust +pub fn install_default( + provider: impl CryptoProvider, +) -> std::result::Result<(), Arc>; + +pub fn get_default() -> Option<&'static Arc>; +``` + +Global installation is optional and backed by +`OnceLock>`. It succeeds at most once per process. + +- The first successful call installs the provider. +- A later call leaves the first provider installed and returns the rejected + provider inside `Err`. +- Concurrent calls are safe: exactly one caller wins and every other caller + receives `Err`. +- Installation is not idempotent: a repeated call is rejected rather than + succeeding as a no-op. +- `get_default()` only reads the current value. Calling it before installation + returns `None` and does not freeze the unset state; a later + `install_default()` still succeeds. + +Applications own the process-wide choice. A top-level application that wants a +global provider installs it before constructing facade contexts; contexts +created afterward use the global provider, while contexts that already bind +RustCrypto keep that binding. Integrating middleware, such as OpenDAL, must not +install a global provider on behalf of its users: doing so would take away the +application's choice and can race with the application's own initialization. + +## Failure Semantics + +| Condition | Error kind | Retryable | +| --- | --- | --- | +| No provider resolvable through the context | `ConfigInvalid` | no | +| Installed provider does not support the operation | `ConfigInvalid` | no | +| Unencrypted-key material is malformed, not RSA, out of range, or has an invalid AES key length | `CredentialInvalid` | no | +| Backend, FFI, allocator, or random-source failure | `Unexpected` | no | + +`ConfigInvalid` is a configuration/ownership error, not a transient failure. A +caller that retries it without binding, installing, or changing a provider +cannot succeed. `CredentialInvalid` identifies key material supplied by the +caller or loaded from a credential source. + +Reqsign must not panic when no provider resolves, an operation is unsupported, +or key material is malformed. Backends must use their fallible APIs rather than +unwrap backend errors. + +## Core Helpers + +`reqsign_core::hash` keeps its pure encoding helpers unchanged: + +```rust +pub fn base64_encode(content: &[u8]) -> String; +pub fn base64_decode(content: &str) -> Result>; +``` + +The digest, MAC, and encoded digest/MAC helpers require an explicitly supplied +provider and return `Result`: + +```rust +pub fn sha1(provider: &dyn CryptoProvider, content: &[u8]) -> Result<[u8; 20]>; +pub fn sha256(provider: &dyn CryptoProvider, content: &[u8]) -> Result<[u8; 32]>; +pub fn hmac_sha1(provider: &dyn CryptoProvider, key: &[u8], content: &[u8]) -> Result<[u8; 20]>; +pub fn hmac_sha256(provider: &dyn CryptoProvider, key: &[u8], content: &[u8]) -> Result<[u8; 32]>; +pub fn hex_sha1(provider: &dyn CryptoProvider, content: &[u8]) -> Result; +pub fn hex_sha256(provider: &dyn CryptoProvider, content: &[u8]) -> Result; +pub fn hex_hmac_sha1(provider: &dyn CryptoProvider, key: &[u8], content: &[u8]) -> Result; +pub fn hex_hmac_sha256(provider: &dyn CryptoProvider, key: &[u8], content: &[u8]) -> Result; +pub fn base64_hmac_sha1(provider: &dyn CryptoProvider, key: &[u8], content: &[u8]) -> Result; +pub fn base64_hmac_sha256(provider: &dyn CryptoProvider, key: &[u8], content: &[u8]) -> Result; +``` + +Callers with a `Context` pass `ctx.crypto_provider()?`. These helpers never +perform a context or global lookup themselves, so they cannot silently bypass +the caller's selected provider. + +`reqsign-core` has no JWT module or `jwt` feature and does not depend on +`serde` or `serde_json` for JWT formatting. Azure client-certificate +authentication and Google service-account exchanges format their compact RS256 +JWS in their own crates using `serde_json`, URL-safe unpadded base64, and +`CryptoProvider::rsa_pkcs1v15_sha256_sign`. The header and claims remain +service-local and are not part of the core API. + +Standalone public crypto entry points follow the same rule. For example, +Azure Storage's `ServiceSharedAccessSignature::token` takes +`&dyn CryptoProvider`; callers resolve it from their context. + +## Official Providers + +### `reqsign-crypto-rustcrypto` + +Location: `crypto/rustcrypto`. Workspace member. It has its own independent +version line, starting at `1.0.0`. + +`RustCryptoProvider::new()`, `Default`, and +`RustCryptoProvider::install_default()` are the public entry points. + +| Operation | Native | `wasm32-unknown-unknown` | +| --- | --- | --- | +| SHA-1, SHA-256, HMAC-SHA-1/256 | yes | yes | +| ECDSA P-256 with SHA-256 | yes | yes | +| RSA PKCS#1 v1.5 with SHA-256 | yes | unsupported (`ConfigInvalid`) | +| AES-128/256-GCM | yes | unsupported (`ConfigInvalid`) | +| Secure random bytes | yes | unsupported (`ConfigInvalid`) | + +The native RSA path accepts PKCS#8 and PKCS#1 PEM and uses OS randomness for +blinding. The WASM subset matches the services reqsign supports on +`wasm32-unknown-unknown` and avoids requiring a JavaScript random source. + +### `reqsign-crypto-boring` + +Location: `crypto/boring`. Excluded from the root workspace so the main +workspace, `--all-features`, Windows/macOS builds, WASM builds, and release +planning never require CMake or a C/C++ toolchain. + +`BoringCryptoProvider::new()`, `Default`, and +`BoringCryptoProvider::install_default()` are the public entry points. The +provider implements all eight operations through safe, stateless BoringSSL +calls and contains no `unsafe` code. The optional `fips` feature forwards to +`boring/fips`. + +The crate has an independent version cadence (`1.0.0` initially), is verified by +`.github/workflows/crypto_boring.yml`, and is not published by +`cargo publish --workspace`. + +## Facade and Features + +The `reqsign` facade adds: + +```toml +default = ["default-context", "default-crypto"] +default-crypto = ["dep:reqsign-crypto-rustcrypto"] +``` + +`default-crypto` re-exports `RustCryptoProvider`. When it is enabled, +`default_context()` checks the process-wide registration at construction. If +the slot is empty it binds `RustCryptoProvider` with `with_crypto`; if a global +provider is already installed it leaves the context unbound so the global +provider is used. It never writes the process-wide slot. + +Without `default-crypto`, `default_context()` resolves a provider only from an +explicit binding or a process-wide installation. `Context::new()` starts +unbound. + +The facade's per-service `default_signer(...)` helpers take the caller-supplied +`Context` as their first argument. Passing `default_context()` inherits the +conditional RustCrypto binding described above; passing a custom context keeps +that context's explicit or global provider selection. The signer owns the +context, and replacing it with `Signer::with_context` also isolates the +credential cache. + +Applications that select a different backend disable `default-crypto` and take +the backend crate directly. Applications that use only hashing can provide +their own minimal `CryptoProvider`. + +## Migration + +### Applications and bare core users + +Facade users can construct a context with `default_context()` and pass it to a +per-service `default_signer(...)` without installing anything. To select one +provider for the whole application, install it once before constructing facade +contexts; contexts that were already bound to RustCrypto keep their binding: + +```rust +use reqsign::RustCryptoProvider; + +fn main() -> Result<(), Box> { + RustCryptoProvider::install_default() + .map_err(|_| "a CryptoProvider is already installed")?; + + // Build contexts, signers, granters, and clients here. + Ok(()) +} +``` + +A failure from `install_default` means another component already installed a +global provider. To keep a provider local, bind it with +`Context::new().with_crypto(provider)` instead. Applications that intentionally +compose several libraries should settle the global choice before any of them +loads credentials. + +Bare `reqsign-core` users must provide a provider through the context or install +a global one before signing. Hash helpers take the provider directly; service JWT formatting +also uses the selected provider, with no implicit lookup. + +The generic credential chain continues past provider errors and returns +`Ok(None)` when every source is exhausted; services that select an identity +before loading, such as AWS SSO, propagate that identity's errors instead. A +context without a provider found through the generic chain can therefore surface +as credential absence, and `Signer::sign` reports `CredentialInvalid` ("failed +to load signing credential") with the request unchanged. This preserves the +existing chain and `Ok(None)` contract; providing a provider before credential +loading is what makes the missing-provider `ConfigInvalid` visible. + +### Core and Service Crates + +`reqsign-core` and every `services/*` crate have no production dependency on +`sha1`, `sha2`, `hmac`, `rsa`, `p256`, or `aes-gcm`. Those crates remain +permitted as `dev-dependencies` for verification. Encoding (`base64`, `hex`) and +secret zeroization (`zeroize`) remain ordinary dependencies where needed. + +All former hash and MAC call sites propagate `?` and resolve the provider from +the `Context` supplied to the signing, granting, or credential-loading entry +point. Public signing, granting, and credential entry points already return +`Result`, so this changes error propagation but not their success contracts. +On-wire formats are unchanged: AWS SigV4/SigV4a, Azure Storage SAS/shared +key/client certificate, Google signed URLs and CAB tokens, Oracle, Aliyun OSS, +Huawei Cloud OBS, Tencent COS, and Volcengine TOS keep their existing +canonicalization and encodings. + +Notable service-specific details: + +- AWS SigV4a derives the P-256 scalar in pure Rust, keeps the scalar in + `Zeroizing<[u8; 32]>`, and performs the fixed-width range check against + `n - 2` before incrementing. The signature is still DER-encoded hex. +- Azure client certificate authentication keeps the certificate/key PEM + splitting and RS256 client-assertion formatting in `azure-storage`; the + thumbprint uses the provider's SHA-1. +- Azure `ServiceSharedAccessSignature::token` takes the resolved provider. +- Google service-account signing encodes the provider's RSA signature as hex; + its private JWT helper is shared by the signer and service-account token + provider. Client-side credential access boundary encryption uses AES-GCM + through the provider and gets its nonce from `fill_random`. Malformed + service-account key material returns `CredentialInvalid` while signing the + exchange JWT. + +### Removed APIs + +- The public `reqsign_core::jwt` module and `jwt` feature are removed. Azure + and Google own their private RS256 JWS formatting and sign through the + resolved provider. +- Hash and MAC helpers take `&dyn CryptoProvider` and return `Result`. +- `reqsign-core` no longer provides crypto implementations, so a context with no + provider binding and no global provider fails with `ConfigInvalid` at the + point of use. + +## Verification + +The repository verifies this contract with: + +- Separate `reqsign-core` integration test binaries for the bare missing + context, early global lookup, rejected second installation, concurrent + installation, and context resolution priority. The priority test covers + explicit priority over global and independent providers on distinct + contexts. +- Facade tests with and without `default-crypto`, including installation before + and after context construction, OnceLock non-occupation, a default signer + using its bound provider, and a signer whose explicitly selected provider is + used. +- RustCrypto provider tests for published hash/HMAC vectors, block-size key + boundaries, both RSA PEM formats, AES-128/256-GCM with and without AAD, + ECDSA verification, invalid scalars, invalid AES key lengths, random output, + and unsupported-operation defaults. +- BoringSSL parity tests against `reqsign-crypto-rustcrypto` for byte-identical + hashes, HMACs, RSA signatures, and AES-GCM output; cross-backend ECDSA + verification; error-kind checks; and an AWS SigV4 end-to-end signing test with + an explicit BoringSSL context. +- A per-root `cargo tree --all-features --target all --edges normal` check + confirms that no core or service production graph contains a cryptographic + implementation crate, without workspace feature unification hiding optional + paths. +- `cargo check -p reqsign-crypto-rustcrypto --target wasm32-unknown-unknown`, + the workspace test suite, doc tests, formatting, clippy with `-D warnings`, + license headers, the standalone BoringSSL workflow, and the website provider + catalog validator. diff --git a/reqsign/Cargo.toml b/reqsign/Cargo.toml index 9d71b1f0..69bac08f 100644 --- a/reqsign/Cargo.toml +++ b/reqsign/Cargo.toml @@ -36,6 +36,7 @@ rustdoc-args = ["--cfg", "docsrs"] [dependencies] # Core functionality (always included) reqsign-core = { workspace = true } +reqsign-crypto-rustcrypto = { workspace = true, optional = true } # Service implementations (optional) reqsign-aliyun-oss = { workspace = true, optional = true } @@ -55,7 +56,8 @@ reqsign-file-read-tokio = { workspace = true, optional = true } reqsign-http-send-reqwest = { workspace = true, optional = true } [features] -default = ["default-context"] +default = ["default-context", "default-crypto"] +default-crypto = ["dep:reqsign-crypto-rustcrypto"] default-context = [ "dep:reqsign-command-execute-tokio", "dep:reqsign-file-read-tokio", @@ -103,35 +105,36 @@ tokio = { version = "1", features = ["full"] } [[example]] name = "aws" -required-features = ["aws", "default-context"] +required-features = ["aws", "default-context", "default-crypto"] [[example]] name = "azure" -required-features = ["azure", "default-context"] +required-features = ["azure", "default-context", "default-crypto"] [[example]] name = "google" -required-features = ["google", "default-context"] +required-features = ["google", "default-context", "default-crypto"] [[example]] name = "static_credentials" -required-features = ["aws", "default-context"] +required-features = ["aws", "default-context", "default-crypto"] [[example]] name = "presign" -required-features = ["aws", "default-context"] +required-features = ["aws", "default-context", "default-crypto"] [[example]] name = "custom_context" -required-features = ["aws", "default-context"] +required-features = ["aws", "default-context", "default-crypto"] [[example]] name = "s3_express_grant" -required-features = ["aws", "default-context"] +required-features = ["aws", "default-context", "default-crypto"] [[example]] name = "s3_express_sign" -required-features = ["aws", "default-context"] +required-features = ["aws", "default-context", "default-crypto"] [[example]] name = "custom_http" +required-features = ["default-crypto"] diff --git a/reqsign/README.md b/reqsign/README.md index d706bef0..de4a4f47 100644 --- a/reqsign/README.md +++ b/reqsign/README.md @@ -42,7 +42,13 @@ Add `reqsign` to your `Cargo.toml`: reqsign = "0.20" ``` -By default, this includes the `default-context` feature which provides a ready-to-use context implementation using `reqwest` and `tokio`. +By default, this includes `default-context` (a ready-to-use context using +`reqwest` and `tokio`) and `default-crypto` (the RustCrypto provider). +`default-crypto` makes `default_context()` bind RustCrypto when the process-wide +slot is empty, so default signers work without startup boilerplate. It never +writes the global slot. To choose a global provider, install it before +constructing facade contexts; contexts already bound to RustCrypto keep that +binding, and an explicit `Context::with_crypto` binding always wins. To use specific services only: @@ -63,7 +69,8 @@ use reqsign::{aws, default_context}; #[tokio::main] async fn main() -> Result<()> { - // Create a default runtime context (HTTP client, file reader, OS env, command execution) + // Create a default runtime context (HTTP client, file reader, OS env, command execution). + // It binds RustCrypto when no process-wide provider is installed. let ctx = default_context(); // Create a default signer for AWS S3 in us-east-1 using the supplied context let signer = aws::default_signer(ctx, "s3", "us-east-1"); @@ -90,16 +97,19 @@ For more control, you can manually assemble the signer components: ```rust,ignore use anyhow::Result; -use reqsign::{Context, Signer, default_context}; +use reqsign::{Context, RustCryptoProvider, Signer, default_context}; use reqsign::aws::{DefaultCredentialProvider, RequestSigner}; #[tokio::main] async fn main() -> Result<()> { // Create a context with default implementations + // (including a RustCrypto binding when default-crypto is enabled). let ctx = default_context(); - // Or build your own context with specific implementations + // Or build your own context with specific implementations. + // A bare Context starts unbound, so bind the provider explicitly. let ctx = Context::new() + .with_crypto(RustCryptoProvider::new()) .with_file_read(reqsign_file_read_tokio::TokioFileRead) .with_http_send(reqsign_http_send_reqwest::ReqwestHttpSend::default()) .with_env(reqsign::OsEnv); @@ -182,8 +192,9 @@ let signer = oracle::default_signer(ctx); ## Feature Flags -- `default`: Enables `default-context` +- `default`: Enables `default-context` and `default-crypto` - `default-context`: Provides a default context implementation using `reqwest` and `tokio` +- `default-crypto`: Re-exports `RustCryptoProvider`; `default_context()` binds it when no process-wide provider is installed - `aliyun`: Enable Aliyun OSS support - `aws`: Enable AWS services support - `azure`: Enable Azure Storage support diff --git a/reqsign/examples/custom_context.rs b/reqsign/examples/custom_context.rs index 25667c99..2bd73257 100644 --- a/reqsign/examples/custom_context.rs +++ b/reqsign/examples/custom_context.rs @@ -23,6 +23,7 @@ use reqsign_http_send_reqwest::ReqwestHttpSend; fn main() { let ctx = Context::new() + .with_crypto(reqsign::RustCryptoProvider::new()) .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv) diff --git a/reqsign/examples/custom_http.rs b/reqsign/examples/custom_http.rs index ee1324f5..7856833a 100644 --- a/reqsign/examples/custom_http.rs +++ b/reqsign/examples/custom_http.rs @@ -30,5 +30,7 @@ impl HttpSend for MyHttpSend { fn main() { // This example only assembles the context; implement http_send before use. - let _ctx = Context::new().with_http_send(MyHttpSend); + let _ctx = Context::new() + .with_crypto(reqsign::RustCryptoProvider::new()) + .with_http_send(MyHttpSend); } diff --git a/reqsign/src/context.rs b/reqsign/src/context.rs index e367fcda..eb5153a2 100644 --- a/reqsign/src/context.rs +++ b/reqsign/src/context.rs @@ -17,6 +17,9 @@ use reqsign_core::{Context, OsEnv}; +#[cfg(feature = "default-crypto")] +use reqsign_crypto_rustcrypto::RustCryptoProvider; + #[cfg(not(target_arch = "wasm32"))] use reqsign_command_execute_tokio::TokioCommandExecute; #[cfg(not(target_arch = "wasm32"))] @@ -30,6 +33,15 @@ use reqsign_http_send_reqwest::ReqwestHttpSend; /// - `TokioFileRead` for file reading (non-WASM only) /// - `ReqwestHttpSend` for HTTP requests /// - `OsEnv` for environment variable access +/// - `RustCryptoProvider` bound to the context when `default-crypto` is enabled +/// and no process-wide provider is installed at construction time +/// +/// This makes `reqsign` examples and default signers usable without installation +/// boilerplate. It does not touch the process-wide registration. An application +/// that wants to choose a process-wide provider installs it before constructing +/// facade contexts; a context that already binds RustCrypto keeps that binding. +/// An explicit `Context::with_crypto` binding always wins. Integrating middleware +/// must leave provider installation to the application. /// /// # Example /// @@ -66,18 +78,23 @@ use reqsign_http_send_reqwest::ReqwestHttpSend; /// ``` pub fn default_context() -> Context { #[cfg(not(target_arch = "wasm32"))] - { - Context::new() - .with_command_execute(TokioCommandExecute) - .with_file_read(TokioFileRead) - .with_http_send(ReqwestHttpSend::default()) - .with_env(OsEnv) - } + let ctx = Context::new() + .with_command_execute(TokioCommandExecute) + .with_file_read(TokioFileRead) + .with_http_send(ReqwestHttpSend::default()) + .with_env(OsEnv); #[cfg(target_arch = "wasm32")] - { - Context::new() - .with_http_send(ReqwestHttpSend::default()) - .with_env(OsEnv) - } + let ctx = Context::new() + .with_http_send(ReqwestHttpSend::default()) + .with_env(OsEnv); + + #[cfg(feature = "default-crypto")] + let ctx = if reqsign_core::crypto::get_default().is_none() { + ctx.with_crypto(RustCryptoProvider::new()) + } else { + ctx + }; + + ctx } diff --git a/reqsign/src/lib.rs b/reqsign/src/lib.rs index 9e5a04d1..c560b843 100644 --- a/reqsign/src/lib.rs +++ b/reqsign/src/lib.rs @@ -21,6 +21,11 @@ // Re-export core types pub use reqsign_core::*; +// The default cryptographic backend. Applications may install it process-wide; +// `default_context` binds it conditionally when no global provider is installed. +#[cfg(feature = "default-crypto")] +pub use reqsign_crypto_rustcrypto::RustCryptoProvider; + // Context utilities #[cfg(feature = "default-context")] mod context; @@ -57,21 +62,45 @@ pub mod volcengine; #[cfg(all(test, feature = "aws-v4"))] mod tests { - use crate::{Context, StaticEnv, aws}; + use crate::crypto::CryptoProvider; + use crate::{Context, Result, StaticEnv, aws}; use std::collections::HashMap; + #[derive(Debug)] + struct TestCryptoProvider; + + impl CryptoProvider for TestCryptoProvider { + fn sha1(&self, _: &[u8]) -> Result<[u8; 20]> { + Ok([1; 20]) + } + + fn sha256(&self, _: &[u8]) -> Result<[u8; 32]> { + Ok([2; 32]) + } + + fn hmac_sha1(&self, _: &[u8], _: &[u8]) -> Result<[u8; 20]> { + Ok([3; 20]) + } + + fn hmac_sha256(&self, _: &[u8], _: &[u8]) -> Result<[u8; 32]> { + Ok([4; 32]) + } + } + #[tokio::test] async fn default_signer_works_without_default_context_feature() { - let ctx = Context::new().with_env(StaticEnv { - home_dir: None, - envs: HashMap::from([ - ("AWS_ACCESS_KEY_ID".to_string(), "AKIDEXAMPLE".to_string()), - ( - "AWS_SECRET_ACCESS_KEY".to_string(), - "example-secret-key".to_string(), - ), - ]), - }); + let ctx = Context::new() + .with_crypto(TestCryptoProvider) + .with_env(StaticEnv { + home_dir: None, + envs: HashMap::from([ + ("AWS_ACCESS_KEY_ID".to_string(), "AKIDEXAMPLE".to_string()), + ( + "AWS_SECRET_ACCESS_KEY".to_string(), + "example-secret-key".to_string(), + ), + ]), + }); let signer = aws::default_signer(ctx, "s3", "us-east-1"); let mut req = http::Request::get("https://s3.amazonaws.com/my-bucket/my-object") diff --git a/reqsign/tests/crypto.rs b/reqsign/tests/crypto.rs new file mode 100644 index 00000000..3a62d8bb --- /dev/null +++ b/reqsign/tests/crypto.rs @@ -0,0 +1,111 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! The facade binds RustCrypto only when the global slot is empty. + +#[cfg(feature = "default-context")] +#[test] +fn default_context_binds_rustcrypto_without_installing_global() { + use reqsign::crypto::{CryptoProvider, get_default, install_default}; + use reqsign::hash; + use reqsign::{Context, Result}; + + #[derive(Debug)] + struct TestProvider(u8); + + impl CryptoProvider for TestProvider { + fn sha1(&self, _: &[u8]) -> Result<[u8; 20]> { + Ok([self.0; 20]) + } + + fn sha256(&self, _: &[u8]) -> Result<[u8; 32]> { + Ok([self.0; 32]) + } + + fn hmac_sha1(&self, _: &[u8], _: &[u8]) -> Result<[u8; 20]> { + Ok([self.0; 20]) + } + + fn hmac_sha256(&self, _: &[u8], _: &[u8]) -> Result<[u8; 32]> { + Ok([self.0; 32]) + } + } + + fn assert_sha256_abc(ctx: &Context) { + assert_eq!( + reqsign::hash::base64_encode( + &hash::sha256( + ctx.crypto_provider().expect("provider must resolve"), + b"abc" + ) + .expect("hashing must succeed") + ), + "ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0=" + ); + } + + assert!(get_default().is_none()); + let ctx = reqsign::default_context(); + assert!(get_default().is_none(), "default_context must not install"); + assert_sha256_abc(&ctx); + + install_default(TestProvider(9)).expect("global installation must succeed"); + assert_sha256_abc(&ctx); + + let after_global = reqsign::default_context(); + assert_eq!( + hash::sha256( + after_global.crypto_provider().expect("global must resolve"), + b"x" + ) + .expect("global hashing must succeed"), + [9; 32], + "a default_context created after installation must use the global provider" + ); + + let explicit = Context::new().with_crypto(TestProvider(2)); + assert_eq!( + hash::sha256( + explicit.crypto_provider().expect("explicit must resolve"), + b"x" + ) + .expect("explicit hashing must succeed"), + [2; 32], + "an explicit binding must keep priority over the global provider" + ); + + let first = Context::new().with_crypto(TestProvider(4)); + let second = Context::new().with_crypto(TestProvider(5)); + assert_eq!( + hash::sha256( + first.crypto_provider().expect("first context must resolve"), + b"x" + ) + .expect("first context hashing must succeed"), + [4; 32] + ); + assert_eq!( + hash::sha256( + second + .crypto_provider() + .expect("second context must resolve"), + b"x" + ) + .expect("second context hashing must succeed"), + [5; 32] + ); +} diff --git a/reqsign/tests/crypto_without_default_crypto.rs b/reqsign/tests/crypto_without_default_crypto.rs new file mode 100644 index 00000000..1321e7ae --- /dev/null +++ b/reqsign/tests/crypto_without_default_crypto.rs @@ -0,0 +1,65 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! This binary is built with `--no-default-features --features default-context`. + +#![cfg(all(feature = "default-context", not(feature = "default-crypto")))] + +use reqsign::ErrorKind; +use reqsign::crypto::{CryptoProvider, install_default}; + +#[derive(Debug)] +struct TestProvider; + +impl CryptoProvider for TestProvider { + fn sha1(&self, _: &[u8]) -> reqsign::Result<[u8; 20]> { + Ok([9; 20]) + } + + fn sha256(&self, _: &[u8]) -> reqsign::Result<[u8; 32]> { + Ok([9; 32]) + } + + fn hmac_sha1(&self, _: &[u8], _: &[u8]) -> reqsign::Result<[u8; 20]> { + Ok([9; 20]) + } + + fn hmac_sha256(&self, _: &[u8], _: &[u8]) -> reqsign::Result<[u8; 32]> { + Ok([9; 32]) + } +} + +#[test] +fn default_context_without_default_crypto_uses_explicit_or_global_only() { + assert!(reqsign::crypto::get_default().is_none()); + let before_global = reqsign::default_context(); + let err = before_global + .crypto_provider() + .expect_err("default-context alone must not resolve a provider"); + assert_eq!(err.kind(), ErrorKind::ConfigInvalid); + + install_default(TestProvider).expect("global installation must succeed"); + let after_global = reqsign::default_context(); + assert_eq!( + reqsign::hash::sha256( + after_global.crypto_provider().expect("global must resolve"), + b"x" + ) + .expect("global hashing must succeed"), + [9; 32] + ); +} diff --git a/reqsign/tests/default_signer.rs b/reqsign/tests/default_signer.rs new file mode 100644 index 00000000..b78a1ef8 --- /dev/null +++ b/reqsign/tests/default_signer.rs @@ -0,0 +1,86 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#![cfg(feature = "aws")] + +use reqsign::aws::{StaticCredentialProvider, default_signer}; +use reqsign::crypto::CryptoProvider; +#[cfg(feature = "default-context")] +use reqsign::default_context; +use reqsign::{Context, ErrorKind, Result}; + +#[derive(Debug)] +struct UnsupportedProvider; + +impl CryptoProvider for UnsupportedProvider { + fn sha1(&self, _: &[u8]) -> Result<[u8; 20]> { + Err(reqsign::Error::config_invalid("unsupported test provider")) + } + + fn sha256(&self, _: &[u8]) -> Result<[u8; 32]> { + Err(reqsign::Error::config_invalid("unsupported test provider")) + } + + fn hmac_sha1(&self, _: &[u8], _: &[u8]) -> Result<[u8; 20]> { + Err(reqsign::Error::config_invalid("unsupported test provider")) + } + + fn hmac_sha256(&self, _: &[u8], _: &[u8]) -> Result<[u8; 32]> { + Err(reqsign::Error::config_invalid("unsupported test provider")) + } +} + +#[cfg(feature = "default-context")] +#[tokio::test] +async fn default_signer_signs_with_the_context_provider() { + let signer = default_signer(default_context(), "s3", "test-region") + .with_credential_provider(StaticCredentialProvider::new("access-key", "secret-key")); + let mut parts = http::Request::get("https://example.amazonaws.com/object") + .body(()) + .expect("request must build") + .into_parts() + .0; + + signer + .sign(&mut parts, None) + .await + .expect("default signer must use the context crypto provider"); + assert!( + parts.headers[http::header::AUTHORIZATION] + .to_str() + .expect("authorization must be text") + .starts_with("AWS4-HMAC-SHA256 ") + ); +} + +#[tokio::test] +async fn default_signer_uses_an_explicitly_selected_context_provider() { + let context = Context::new().with_crypto(UnsupportedProvider); + let signer = default_signer(context, "s3", "test-region") + .with_credential_provider(StaticCredentialProvider::new("access-key", "secret-key")); + let mut parts = http::Request::get("https://example.amazonaws.com/object") + .body(()) + .expect("request must build") + .into_parts() + .0; + + let err = signer + .sign(&mut parts, None) + .await + .expect_err("the explicitly selected provider must be used"); + assert_eq!(err.kind(), ErrorKind::ConfigInvalid); +} diff --git a/services/aliyun-oss/Cargo.toml b/services/aliyun-oss/Cargo.toml index 6dc8ce7b..80a1d5c2 100644 --- a/services/aliyun-oss/Cargo.toml +++ b/services/aliyun-oss/Cargo.toml @@ -38,6 +38,7 @@ serde = { workspace = true } serde_json = { workspace = true } [dev-dependencies] +reqsign-crypto-rustcrypto = { workspace = true } bytes = { workspace = true } dotenvy = { workspace = true } env_logger = { workspace = true } diff --git a/services/aliyun-oss/README.md b/services/aliyun-oss/README.md index e5398225..f4f16d19 100644 --- a/services/aliyun-oss/README.md +++ b/services/aliyun-oss/README.md @@ -6,9 +6,16 @@ Aliyun OSS signing implementation for reqsign. This crate provides signing support for Alibaba Cloud Object Storage Service (OSS), enabling secure authentication for all OSS operations. +> Signing needs a `CryptoProvider` resolved through the `Context`: bind one with +> `Context::with_crypto`, install a process-wide default, or use a facade +> `default_context()` (which binds RustCrypto when the global slot is empty). A +> bare `Context::new()` starts unbound. See +> [CryptoProvider](https://github.com/apache/reqsign/blob/main/docs/crypto-provider.md). + ## Quick Start ```rust +use reqsign_crypto_rustcrypto::RustCryptoProvider; use reqsign_aliyun_oss::{ AssumeRoleCredentialProvider, AssumeRoleWithOidcCredentialProvider, ConfigFileCredentialProvider, CredentialsFileCredentialProvider, @@ -22,7 +29,7 @@ use reqsign_http_send_reqwest::ReqwestHttpSend; #[tokio::main] async fn main() -> Result<()> { - let ctx = Context::new() + let ctx = Context::new().with_crypto(RustCryptoProvider::new()) .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()); diff --git a/services/aliyun-oss/examples/oss_operations.rs b/services/aliyun-oss/examples/oss_operations.rs index 68a4861c..3cc2dda7 100644 --- a/services/aliyun-oss/examples/oss_operations.rs +++ b/services/aliyun-oss/examples/oss_operations.rs @@ -23,6 +23,7 @@ use reqsign_aliyun_oss::{ }; use reqsign_core::Result; use reqsign_core::{Context, OsEnv, Signer}; +use reqsign_crypto_rustcrypto::RustCryptoProvider; use reqsign_file_read_tokio::TokioFileRead; use reqsign_http_send_reqwest::ReqwestHttpSend; use reqwest::Client; @@ -37,6 +38,7 @@ async fn main() -> Result<()> { // Create context let ctx = Context::new() + .with_crypto(RustCryptoProvider::new()) .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::new(client.clone())) .with_env(OsEnv); diff --git a/services/aliyun-oss/src/assume_role.rs b/services/aliyun-oss/src/assume_role.rs index c0e69bd1..a1f7503d 100644 --- a/services/aliyun-oss/src/assume_role.rs +++ b/services/aliyun-oss/src/assume_role.rs @@ -31,6 +31,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; use std::time::Duration; use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode}; +use reqsign_core::crypto::CryptoProvider; use reqsign_core::hash::base64_hmac_sha1; use reqsign_core::time::Timestamp; use reqsign_core::{Context, Error, GrantCredential, Result, SigningCredential}; @@ -156,6 +157,7 @@ pub(crate) fn signature_nonce(signing_time: Timestamp) -> String { /// parameter except `Signature`; the caller owns action-specific parameters. /// The request is signed with HMAC-SHA1 using `access_key_secret`. pub(crate) fn signed_rpc_request( + provider: &dyn CryptoProvider, endpoint: &str, params: &BTreeMap, access_key_secret: &str, @@ -166,9 +168,10 @@ pub(crate) fn signed_rpc_request( percent_encode_query_value(&canonicalized_query_string) ); let signature = base64_hmac_sha1( + provider, format!("{access_key_secret}&").as_bytes(), string_to_sign.as_bytes(), - ); + )?; let url = format!( "{}/?{}&Signature={}", @@ -422,7 +425,12 @@ impl GrantCredential for AssumeRoleGranter { params.insert("DurationSeconds".to_string(), duration_seconds.to_string()); } - let req = signed_rpc_request(&self.endpoint(), ¶ms, &credential.access_key_secret)?; + let req = signed_rpc_request( + ctx.crypto_provider()?, + &self.endpoint(), + ¶ms, + &credential.access_key_secret, + )?; let resp = ctx.http_send(req.map(Into::into)).await?; if resp.status() != http::StatusCode::OK { let content = String::from_utf8_lossy(resp.body()); @@ -574,7 +582,7 @@ mod tests { #[tokio::test] async fn test_grant_signs_request_and_returns_credential() -> Result<()> { let http_send = CaptureHttpSend::new(vec![SUCCESS_BODY.to_vec()]); - let ctx = Context::new().with_http_send(http_send.clone()); + let ctx = crate::test_context().with_http_send(http_send.clone()); let signing_time: Timestamp = "2024-03-05T06:07:08Z".parse().unwrap(); let grant = AssumeRoleGrant::new("acs:ram::123456789012:role/test-role") @@ -657,7 +665,11 @@ mod tests { expected.insert("Version".to_string(), "2015-04-01".to_string()); let canonical = canonicalized_query_string(&expected); let string_to_sign = format!("GET&%2F&{}", percent_encode_query_value(&canonical)); - let expected_signature = base64_hmac_sha1("base-sk&".as_bytes(), string_to_sign.as_bytes()); + let expected_signature = base64_hmac_sha1( + &reqsign_crypto_rustcrypto::RustCryptoProvider::new(), + "base-sk&".as_bytes(), + string_to_sign.as_bytes(), + )?; assert_eq!( Some(expected_signature.as_str()), params.get("Signature").map(String::as_str) @@ -668,7 +680,7 @@ mod tests { #[tokio::test] async fn test_grant_omits_optional_params_when_unset() -> Result<()> { let http_send = CaptureHttpSend::new(vec![SUCCESS_BODY.to_vec()]); - let ctx = Context::new().with_http_send(http_send.clone()); + let ctx = crate::test_context().with_http_send(http_send.clone()); let granter = AssumeRoleGranter::new(AssumeRoleGrant::new("acs:ram::123456789012:role/test-role")) @@ -694,7 +706,7 @@ mod tests { #[tokio::test] async fn test_grant_rejects_invalid_source_before_io() { let http_send = CaptureHttpSend::new(vec![SUCCESS_BODY.to_vec()]); - let ctx = Context::new().with_http_send(http_send.clone()); + let ctx = crate::test_context().with_http_send(http_send.clone()); let granter = AssumeRoleGranter::new(AssumeRoleGrant::new("acs:ram::123456789012:role/test-role")); @@ -721,7 +733,7 @@ mod tests { #[tokio::test] async fn test_grant_rejects_out_of_range_duration_before_io() { let http_send = CaptureHttpSend::new(vec![SUCCESS_BODY.to_vec()]); - let ctx = Context::new().with_http_send(http_send.clone()); + let ctx = crate::test_context().with_http_send(http_send.clone()); let granter = AssumeRoleGranter::new(AssumeRoleGrant::new("acs:ram::123456789012:role/test-role")); @@ -737,7 +749,7 @@ mod tests { async fn test_grant_rejects_expired_granted_credential() { let expired = br#"{"Credentials":{"SecurityToken":"sts-token","Expiration":"2000-01-01T00:00:00Z","AccessKeySecret":"sts-secret","AccessKeyId":"sts-ak"}}"#; let http_send = CaptureHttpSend::new(vec![expired.to_vec()]); - let ctx = Context::new().with_http_send(http_send.clone()); + let ctx = crate::test_context().with_http_send(http_send.clone()); let granter = AssumeRoleGranter::new(AssumeRoleGrant::new("acs:ram::123456789012:role/test-role")); diff --git a/services/aliyun-oss/src/lib.rs b/services/aliyun-oss/src/lib.rs index 83b7de00..cc8b0fb1 100644 --- a/services/aliyun-oss/src/lib.rs +++ b/services/aliyun-oss/src/lib.rs @@ -258,3 +258,8 @@ pub use sign_request::{RequestSigner, SigningVersion}; mod provide_credential; pub use provide_credential::*; + +#[cfg(test)] +pub(crate) fn test_context() -> reqsign_core::Context { + reqsign_core::Context::new().with_crypto(reqsign_crypto_rustcrypto::RustCryptoProvider::new()) +} diff --git a/services/aliyun-oss/src/provide_credential/assume_role.rs b/services/aliyun-oss/src/provide_credential/assume_role.rs index 0c736bd6..c717f37d 100644 --- a/services/aliyun-oss/src/provide_credential/assume_role.rs +++ b/services/aliyun-oss/src/provide_credential/assume_role.rs @@ -241,6 +241,7 @@ impl ProvideCredential for AssumeRoleCredentialProvider { } let req = signed_rpc_request( + ctx.crypto_provider()?, &self.get_sts_endpoint(&envs), ¶ms, &base_credential.access_key_secret, @@ -345,7 +346,7 @@ mod tests { #[tokio::test] async fn test_assume_role_loader_without_config() { - let ctx = Context::new().with_env(StaticEnv { + let ctx = crate::test_context().with_env(StaticEnv { home_dir: None, envs: HashMap::new(), }); @@ -368,7 +369,7 @@ mod tests { br#"{"Credentials":{"SecurityToken":"sts-token","Expiration":"2124-05-25T11:45:17Z","AccessKeySecret":"sts-secret","AccessKeyId":"sts-ak"}}"# .to_vec(), ]); - let ctx = Context::new() + let ctx = crate::test_context() .with_http_send(http_send.clone()) .with_env(StaticEnv { home_dir: None, @@ -453,9 +454,10 @@ mod tests { let canonicalized = canonicalized_query_string(&expected_params); let string_to_sign = format!("GET&%2F&{}", percent_encode_query_value(&canonicalized)); let expected_signature = base64_hmac_sha1( + &reqsign_crypto_rustcrypto::RustCryptoProvider::new(), format!("{}&", base_credential.access_key_secret).as_bytes(), string_to_sign.as_bytes(), - ); + )?; assert_eq!( Some(expected_signature.as_str()), params.get("Signature").map(String::as_str) @@ -472,7 +474,7 @@ mod tests { br#"{"Credentials":{"SecurityToken":"sts-token-2","Expiration":"2124-03-05T06:09:00Z","AccessKeySecret":"sts-secret-2","AccessKeyId":"sts-ak-2"}}"# .to_vec(), ]); - let ctx = Context::new() + let ctx = crate::test_context() .with_http_send(http_send.clone()) .with_env(StaticEnv { home_dir: None, @@ -539,7 +541,7 @@ mod tests { br#"{"Credentials":{"SecurityToken":"sts-token","Expiration":"2124-05-25T11:45:17Z","AccessKeySecret":"sts-secret","AccessKeyId":"sts-ak"}}"# .to_vec(), ]); - let ctx = Context::new() + let ctx = crate::test_context() .with_http_send(http_send.clone()) .with_env(StaticEnv { home_dir: None, diff --git a/services/aliyun-oss/src/provide_credential/assume_role_with_oidc.rs b/services/aliyun-oss/src/provide_credential/assume_role_with_oidc.rs index deba69cb..51499107 100644 --- a/services/aliyun-oss/src/provide_credential/assume_role_with_oidc.rs +++ b/services/aliyun-oss/src/provide_credential/assume_role_with_oidc.rs @@ -255,7 +255,7 @@ mod tests { use super::*; use bytes::Bytes; use reqsign_core::StaticEnv; - use reqsign_core::{Context, Env, FileRead, HttpSend}; + use reqsign_core::{Env, FileRead, HttpSend}; use reqsign_file_read_tokio::TokioFileRead; use reqsign_http_send_reqwest::ReqwestHttpSend; use std::collections::HashMap; @@ -321,7 +321,7 @@ mod tests { #[tokio::test] async fn test_assume_role_with_oidc_loader_without_config() { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()); let ctx = ctx.with_env(StaticEnv { @@ -408,7 +408,7 @@ mod tests { let http_body = r#"{"Credentials":{"SecurityToken":"security_token","Expiration":"2124-05-25T11:45:17Z","AccessKeySecret":"secret_access_key","AccessKeyId":"access_key_id"}}"#; let http_send = CaptureHttpSend::new(http_body); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(file_read) .with_http_send(http_send.clone()) .with_env(StaticEnv { @@ -474,7 +474,7 @@ mod tests { let http_body = r#"{"Credentials":{"SecurityToken":"security_token","Expiration":"2124-05-25T11:45:17Z","AccessKeySecret":"secret_access_key","AccessKeyId":"access_key_id"}}"#; let http_send = CaptureHttpSend::new(http_body); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(file_read) .with_http_send(http_send.clone()) .with_env(PanicEnv); @@ -543,7 +543,7 @@ mod tests { let http_body = r#"{"Credentials":{"SecurityToken":"security_token","Expiration":"2124-05-25T11:45:17Z","AccessKeySecret":"secret_access_key","AccessKeyId":"access_key_id"}}"#; let http_send = CaptureHttpSend::new(http_body); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(file_read) .with_http_send(http_send.clone()) .with_env(StaticEnv { @@ -602,7 +602,7 @@ mod tests { let http_body = r#"{"Credentials":{"SecurityToken":"security_token","Expiration":"2124-05-25T11:45:17Z","AccessKeySecret":"secret_access_key","AccessKeyId":"access_key_id"}}"#; let http_send = CaptureHttpSend::new(http_body); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(file_read) .with_http_send(http_send.clone()) .with_env(StaticEnv { diff --git a/services/aliyun-oss/src/provide_credential/config_file.rs b/services/aliyun-oss/src/provide_credential/config_file.rs index bbd53359..57c1df55 100644 --- a/services/aliyun-oss/src/provide_credential/config_file.rs +++ b/services/aliyun-oss/src/provide_credential/config_file.rs @@ -214,7 +214,7 @@ mod tests { #[tokio::test] async fn test_config_file_provider_uses_current_profile() -> anyhow::Result<()> { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TestFileRead::new(HashMap::from([( "/mock/config.json".to_string(), br#"{ @@ -259,7 +259,7 @@ mod tests { #[tokio::test] async fn test_config_file_provider_env_profile_overrides_current() -> anyhow::Result<()> { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TestFileRead::new(HashMap::from([( "/mock/config.json".to_string(), br#"{ @@ -305,7 +305,7 @@ mod tests { #[tokio::test] async fn test_config_file_provider_ignores_unsupported_mode() -> anyhow::Result<()> { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TestFileRead::new(HashMap::from([( "/mock/config.json".to_string(), br#"{ diff --git a/services/aliyun-oss/src/provide_credential/credentials_file.rs b/services/aliyun-oss/src/provide_credential/credentials_file.rs index c15e972b..2a6b50e9 100644 --- a/services/aliyun-oss/src/provide_credential/credentials_file.rs +++ b/services/aliyun-oss/src/provide_credential/credentials_file.rs @@ -227,7 +227,7 @@ mod tests { #[tokio::test] async fn test_credentials_file_provider_reads_default_profile() -> anyhow::Result<()> { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TestFileRead::new(HashMap::from([( "/mock/credentials.ini".to_string(), br#"[default] @@ -261,7 +261,7 @@ access_key_secret=shared_secret_key #[tokio::test] async fn test_credentials_file_provider_env_profile_overrides_builder_profile() -> anyhow::Result<()> { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TestFileRead::new(HashMap::from([( "/mock/credentials.ini".to_string(), br#"[default] @@ -305,7 +305,7 @@ sts_token=prod_token #[tokio::test] async fn test_credentials_file_provider_ignores_unsupported_mode() -> anyhow::Result<()> { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TestFileRead::new(HashMap::from([( "/mock/credentials.ini".to_string(), br#"[default] diff --git a/services/aliyun-oss/src/provide_credential/credentials_uri.rs b/services/aliyun-oss/src/provide_credential/credentials_uri.rs index a402afab..dd5c74dc 100644 --- a/services/aliyun-oss/src/provide_credential/credentials_uri.rs +++ b/services/aliyun-oss/src/provide_credential/credentials_uri.rs @@ -156,7 +156,7 @@ mod tests { use super::*; use bytes::Bytes; use reqsign_core::time::Timestamp; - use reqsign_core::{Context, HttpSend, StaticEnv}; + use reqsign_core::{HttpSend, StaticEnv}; use reqsign_file_read_tokio::TokioFileRead; use std::collections::{HashMap, VecDeque}; use std::sync::{Arc, Mutex}; @@ -232,7 +232,7 @@ mod tests { #[tokio::test] async fn test_credentials_uri_provider_without_config() -> anyhow::Result<()> { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(SequenceHttpSend::new(Vec::new())) .with_env(StaticEnv { @@ -253,7 +253,7 @@ mod tests { status: http::StatusCode::OK, body: credentials_response("2124-05-25T11:45:17Z".to_string(), "uri_access_key"), }]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(http_send.clone()) .with_env(StaticEnv { @@ -289,7 +289,7 @@ mod tests { status: http::StatusCode::OK, body: credentials_response("2124-05-25T11:45:17Z".to_string(), "override_access_key"), }]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(http_send.clone()) .with_env(StaticEnv { @@ -336,7 +336,7 @@ mod tests { ), }, ]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(http_send.clone()) .with_env(StaticEnv { @@ -378,7 +378,7 @@ mod tests { "cached_access_key", ), }]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(http_send.clone()) .with_env(StaticEnv { diff --git a/services/aliyun-oss/src/provide_credential/default.rs b/services/aliyun-oss/src/provide_credential/default.rs index 1e5a2078..8698bd19 100644 --- a/services/aliyun-oss/src/provide_credential/default.rs +++ b/services/aliyun-oss/src/provide_credential/default.rs @@ -372,7 +372,7 @@ mod tests { async fn test_default_loader_without_env() { let _ = env_logger::builder().is_test(true).try_init(); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -394,7 +394,7 @@ mod tests { async fn test_default_loader_with_env() { let _ = env_logger::builder().is_test(true).try_init(); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -423,7 +423,7 @@ mod tests { async fn test_default_loader_with_security_token() { let _ = env_logger::builder().is_test(true).try_init(); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -464,7 +464,7 @@ access_key_secret = profile_secret_key .to_vec(), )])); let http_send = CountingHttpSend::new([]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(file_read.clone()) .with_http_send(http_send.clone()) .with_env(StaticEnv { @@ -543,7 +543,7 @@ access_key_secret = profile_secret_key [br#"{"Credentials":{"SecurityToken":"security_token","Expiration":"2124-05-25T11:45:17Z","AccessKeySecret":"oidc_secret_key","AccessKeyId":"oidc_access_key"}}"# .to_vec()], ); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(file_read.clone()) .with_http_send(http_send.clone()) .with_env(StaticEnv { @@ -609,7 +609,7 @@ access_key_secret=shared_secret_key .to_vec(), ), ])); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(file_read) .with_http_send(ReqwestHttpSend::default()) .with_env(StaticEnv { @@ -659,7 +659,7 @@ access_key_secret=shared_secret_key }"# .to_vec(), )])); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(file_read) .with_http_send(ReqwestHttpSend::default()) .with_env(StaticEnv { @@ -704,7 +704,7 @@ access_key_secret=shared_secret_key }"# .to_vec(), )])); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(file_read) .with_http_send(ReqwestHttpSend::default()) .with_env(StaticEnv { @@ -766,7 +766,7 @@ access_key_secret=shared_secret_key ("/mock/token".to_string(), b"token".to_vec()), ])); let http_send = CountingHttpSend::new([br#"{"Credentials":{"SecurityToken":"security_token","Expiration":"2124-05-25T11:45:17Z","AccessKeySecret":"oidc_secret_key","AccessKeyId":"oidc_access_key"}}"#.to_vec()]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(file_read) .with_http_send(http_send.clone()) .with_env(StaticEnv { @@ -814,7 +814,7 @@ access_key_secret=shared_secret_key b"token".to_vec(), )])); let http_send = CountingHttpSend::new([br#"{"Code":"Success","AccessKeyId":"uri_access_key","AccessKeySecret":"uri_secret_key","SecurityToken":"uri_token","Expiration":"2124-05-25T11:45:17Z"}"#.to_vec()]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(file_read) .with_http_send(http_send.clone()) .with_env(StaticEnv { @@ -876,7 +876,7 @@ access_key_secret=shared_secret_key b"metadata-token".to_vec(), br#"{"Code":"Success","AccessKeyId":"ecs_access_key","AccessKeySecret":"ecs_secret_key","SecurityToken":"ecs_token","Expiration":"2124-05-25T11:45:17Z"}"#.to_vec(), ]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(file_read) .with_http_send(http_send.clone()) .with_env(StaticEnv { @@ -930,7 +930,7 @@ access_key_secret=shared_secret_key #[tokio::test] async fn test_builder_no_credentials_uri_removes_credentials_uri_provider() { let http_send = CountingHttpSend::new([br#"{"Code":"Success","AccessKeyId":"uri_access_key","AccessKeySecret":"uri_secret_key","SecurityToken":"uri_token","Expiration":"2124-05-25T11:45:17Z"}"#.to_vec()]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(http_send.clone()) .with_env(StaticEnv { @@ -984,7 +984,7 @@ access_key_secret=shared_secret_key b"metadata-token".to_vec(), br#"{"Code":"Success","AccessKeyId":"ecs_access_key","AccessKeySecret":"ecs_secret_key","SecurityToken":"ecs_token","Expiration":"2124-05-25T11:45:17Z"}"#.to_vec(), ]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(http_send.clone()) .with_env(StaticEnv { @@ -1042,7 +1042,7 @@ access_key_secret=shared_secret_key [br#"{"Credentials":{"SecurityToken":"security_token","Expiration":"2124-05-25T11:45:17Z","AccessKeySecret":"secret_access_key","AccessKeyId":"access_key_id"}}"# .to_vec()], ); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(file_read.clone()) .with_http_send(http_send.clone()) .with_env(StaticEnv { @@ -1098,7 +1098,7 @@ access_key_secret=shared_secret_key br#"{"Credentials":{"SecurityToken":"sts_token","Expiration":"2124-05-25T11:45:17Z","AccessKeySecret":"assumed_secret_key","AccessKeyId":"assumed_access_key"}}"# .to_vec(), ]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(http_send.clone()) .with_env(StaticEnv { @@ -1139,7 +1139,7 @@ access_key_secret=shared_secret_key br#"{"Credentials":{"SecurityToken":"sts_token","Expiration":"2124-05-25T11:45:17Z","AccessKeySecret":"assumed_secret_key","AccessKeyId":"assumed_access_key"}}"# .to_vec(), ]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(http_send.clone()) .with_env(StaticEnv { @@ -1182,7 +1182,7 @@ access_key_secret=shared_secret_key br#"{"Credentials":{"SecurityToken":"sts_token","Expiration":"2124-05-25T11:45:17Z","AccessKeySecret":"assumed_secret_key","AccessKeyId":"assumed_access_key"}}"# .to_vec(), ]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(http_send.clone()) .with_env(StaticEnv { diff --git a/services/aliyun-oss/src/provide_credential/ecs_ram_role.rs b/services/aliyun-oss/src/provide_credential/ecs_ram_role.rs index 53da0af8..24424765 100644 --- a/services/aliyun-oss/src/provide_credential/ecs_ram_role.rs +++ b/services/aliyun-oss/src/provide_credential/ecs_ram_role.rs @@ -330,7 +330,7 @@ mod tests { use super::*; use bytes::Bytes; use reqsign_core::time::Timestamp; - use reqsign_core::{Context, HttpSend, StaticEnv}; + use reqsign_core::{HttpSend, StaticEnv}; use reqsign_file_read_tokio::TokioFileRead; use std::collections::{HashMap, VecDeque}; use std::sync::{Arc, Mutex}; @@ -421,7 +421,7 @@ mod tests { #[tokio::test] async fn test_ecs_ram_role_provider_disabled_by_env() -> anyhow::Result<()> { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(SequenceHttpSend::new(Vec::new())) .with_env(StaticEnv { @@ -452,7 +452,7 @@ mod tests { body: ecs_credential_response("2124-05-25T11:45:17Z".to_string(), "ecs_access_key"), }, ]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(http_send.clone()) .with_env(StaticEnv { @@ -504,7 +504,7 @@ mod tests { body: ecs_credential_response("2124-05-25T11:45:17Z".to_string(), "ecs_access_key"), }, ]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(http_send.clone()) .with_env(StaticEnv { @@ -533,7 +533,7 @@ mod tests { status: http::StatusCode::INTERNAL_SERVER_ERROR, body: "token failed".to_string(), }]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(http_send) .with_env(StaticEnv { @@ -582,7 +582,7 @@ mod tests { ), }, ]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(http_send.clone()) .with_env(StaticEnv { diff --git a/services/aliyun-oss/src/provide_credential/env.rs b/services/aliyun-oss/src/provide_credential/env.rs index 0a51cded..573d6da1 100644 --- a/services/aliyun-oss/src/provide_credential/env.rs +++ b/services/aliyun-oss/src/provide_credential/env.rs @@ -90,7 +90,7 @@ mod tests { ), ]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv) @@ -127,7 +127,7 @@ mod tests { ), ]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv) @@ -161,7 +161,7 @@ mod tests { ), ]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv) @@ -207,7 +207,7 @@ mod tests { ), ]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv) @@ -232,7 +232,7 @@ mod tests { #[tokio::test] async fn test_env_credential_provider_missing_credentials() -> anyhow::Result<()> { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -252,7 +252,7 @@ mod tests { "test_access_key".to_string(), )]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv) diff --git a/services/aliyun-oss/src/provide_credential/oss_profile.rs b/services/aliyun-oss/src/provide_credential/oss_profile.rs index 25710264..d343b015 100644 --- a/services/aliyun-oss/src/provide_credential/oss_profile.rs +++ b/services/aliyun-oss/src/provide_credential/oss_profile.rs @@ -180,7 +180,7 @@ mod tests { #[tokio::test] async fn test_profile_provider_reads_default_profile() -> anyhow::Result<()> { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TestFileRead::new(HashMap::from([( "/mock/credentials".to_string(), br#"[default] @@ -214,7 +214,7 @@ session_token = profile_token #[tokio::test] async fn test_profile_provider_selects_named_profile() -> anyhow::Result<()> { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TestFileRead::new(HashMap::from([( "/mock/credentials".to_string(), br#"[default] @@ -253,7 +253,7 @@ security_token = prod_token #[tokio::test] async fn test_profile_provider_returns_none_for_missing_profile() -> anyhow::Result<()> { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TestFileRead::new(HashMap::from([( "/mock/credentials".to_string(), br#"[default] diff --git a/services/aliyun-oss/src/provide_credential/static.rs b/services/aliyun-oss/src/provide_credential/static.rs index 710a33dc..ad828be8 100644 --- a/services/aliyun-oss/src/provide_credential/static.rs +++ b/services/aliyun-oss/src/provide_credential/static.rs @@ -67,7 +67,7 @@ mod tests { #[tokio::test] async fn test_static_credential_provider() -> anyhow::Result<()> { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); diff --git a/services/aliyun-oss/src/sign_request.rs b/services/aliyun-oss/src/sign_request.rs index 6fb384ba..5e7b176f 100644 --- a/services/aliyun-oss/src/sign_request.rs +++ b/services/aliyun-oss/src/sign_request.rs @@ -20,6 +20,7 @@ use http::header::{AUTHORIZATION, CONTENT_TYPE, DATE, HOST}; use http::{HeaderValue, Uri}; use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, percent_decode_str, utf8_percent_encode}; use reqsign_core::Result; +use reqsign_core::crypto::CryptoProvider; use reqsign_core::hash::{ base64_hmac_sha1, base64_hmac_sha256, hex_hmac_sha256, hex_sha256, hmac_sha256, }; @@ -161,7 +162,7 @@ impl SignRequest for RequestSigner { async fn sign_request( &self, - _ctx: &Context, + ctx: &Context, req: &mut http::request::Parts, credential: Option<&Self::Credential>, expires_in: Option, @@ -169,6 +170,7 @@ impl SignRequest for RequestSigner { let Some(cred) = credential else { return Ok(()); }; + let provider = ctx.crypto_provider()?; let signing_time = self.get_time(); let required_until = self.required_valid_until_at(signing_time, expires_in); @@ -183,16 +185,16 @@ impl SignRequest for RequestSigner { match self.signing_version { SigningVersion::V1 => { if let Some(expires) = expires_in { - self.sign_query(&mut candidate, cred, signing_time, expires)?; + self.sign_query(provider, &mut candidate, cred, signing_time, expires)?; } else { - self.sign_header(&mut candidate, cred, signing_time)?; + self.sign_header(provider, &mut candidate, cred, signing_time)?; } } SigningVersion::V2 => { - self.sign_v2(&mut candidate, cred, signing_time, expires_in)?; + self.sign_v2(provider, &mut candidate, cred, signing_time, expires_in)?; } SigningVersion::V4 => { - self.sign_v4(&mut candidate, cred, signing_time, expires_in)?; + self.sign_v4(provider, &mut candidate, cred, signing_time, expires_in)?; } } @@ -205,19 +207,21 @@ impl SignRequest for RequestSigner { impl RequestSigner { fn sign_v2( &self, + provider: &dyn CryptoProvider, req: &mut http::request::Parts, cred: &Credential, signing_time: Timestamp, expires_in: Option, ) -> Result<()> { match expires_in { - Some(expires) => self.sign_v2_query(req, cred, signing_time, expires), - None => self.sign_v2_header(req, cred, signing_time), + Some(expires) => self.sign_v2_query(provider, req, cred, signing_time, expires), + None => self.sign_v2_header(provider, req, cred, signing_time), } } fn sign_v2_header( &self, + provider: &dyn CryptoProvider, req: &mut http::request::Parts, cred: &Credential, signing_time: Timestamp, @@ -238,8 +242,11 @@ impl RequestSigner { &date, &additional_headers, )?; - let signature = - base64_hmac_sha256(cred.access_key_secret.as_bytes(), string_to_sign.as_bytes()); + let signature = base64_hmac_sha256( + provider, + cred.access_key_secret.as_bytes(), + string_to_sign.as_bytes(), + )?; let authorization = if additional_headers.is_empty() { format!( @@ -262,6 +269,7 @@ impl RequestSigner { fn sign_v2_query( &self, + provider: &dyn CryptoProvider, req: &mut http::request::Parts, cred: &Credential, signing_time: Timestamp, @@ -294,8 +302,11 @@ impl RequestSigner { &expiration_time, &additional_headers, )?; - let signature = - base64_hmac_sha256(cred.access_key_secret.as_bytes(), string_to_sign.as_bytes()); + let signature = base64_hmac_sha256( + provider, + cred.access_key_secret.as_bytes(), + string_to_sign.as_bytes(), + )?; query_pairs.push((X_OSS_SIGNATURE.to_string(), signature)); self.apply_query_pairs(req, &query_pairs, existing_query_count) @@ -303,13 +314,17 @@ impl RequestSigner { fn sign_header( &self, + provider: &dyn CryptoProvider, req: &mut http::request::Parts, cred: &Credential, signing_time: Timestamp, ) -> Result<()> { let string_to_sign = self.build_string_to_sign(req, cred, signing_time, None)?; - let signature = - base64_hmac_sha1(cred.access_key_secret.as_bytes(), string_to_sign.as_bytes()); + let signature = base64_hmac_sha1( + provider, + cred.access_key_secret.as_bytes(), + string_to_sign.as_bytes(), + )?; // Add date header req.headers @@ -331,6 +346,7 @@ impl RequestSigner { fn sign_query( &self, + provider: &dyn CryptoProvider, req: &mut http::request::Parts, cred: &Credential, signing_time: Timestamp, @@ -338,8 +354,11 @@ impl RequestSigner { ) -> Result<()> { let expiration_time = signing_time + expires; let string_to_sign = self.build_string_to_sign(req, cred, signing_time, Some(expires))?; - let signature = - base64_hmac_sha1(cred.access_key_secret.as_bytes(), string_to_sign.as_bytes()); + let signature = base64_hmac_sha1( + provider, + cred.access_key_secret.as_bytes(), + string_to_sign.as_bytes(), + )?; let mut authentication = vec![ format!( @@ -464,6 +483,7 @@ impl RequestSigner { fn sign_v4( &self, + provider: &dyn CryptoProvider, req: &mut http::request::Parts, cred: &Credential, signing_time: Timestamp, @@ -496,8 +516,9 @@ impl RequestSigner { )?; let scope = self.v4_scope(signing_time, region); let string_to_sign = - self.build_v4_string_to_sign(signing_time, &scope, &canonical_request)?; - let signature = self.build_v4_signature(cred, signing_time, region, &string_to_sign); + self.build_v4_string_to_sign(provider, signing_time, &scope, &canonical_request)?; + let signature = + self.build_v4_signature(provider, cred, signing_time, region, &string_to_sign)?; let final_uri = if expires_in.is_some() { let unsigned_uri = append_query_pairs(&original_uri, &authentication_query)?; @@ -699,6 +720,7 @@ impl RequestSigner { fn build_v4_string_to_sign( &self, + provider: &dyn CryptoProvider, signing_time: Timestamp, scope: &str, canonical_request: &str, @@ -707,25 +729,31 @@ impl RequestSigner { writeln!(&mut s, "{OSS_V4_ALGORITHM}")?; writeln!(&mut s, "{}", signing_time.format_iso8601())?; writeln!(&mut s, "{scope}")?; - write!(&mut s, "{}", hex_sha256(canonical_request.as_bytes()))?; + write!( + &mut s, + "{}", + hex_sha256(provider, canonical_request.as_bytes())? + )?; Ok(s) } fn build_v4_signature( &self, + provider: &dyn CryptoProvider, cred: &Credential, signing_time: Timestamp, region: &str, string_to_sign: &str, - ) -> String { + ) -> Result { let date_key = hmac_sha256( + provider, format!("aliyun_v4{}", cred.access_key_secret).as_bytes(), signing_time.format_date().as_bytes(), - ); - let region_key = hmac_sha256(&date_key, region.as_bytes()); - let service_key = hmac_sha256(®ion_key, OSS_V4_SERVICE.as_bytes()); - let signing_key = hmac_sha256(&service_key, OSS_V4_REQUEST.as_bytes()); - hex_hmac_sha256(&signing_key, string_to_sign.as_bytes()) + )?; + let region_key = hmac_sha256(provider, &date_key, region.as_bytes())?; + let service_key = hmac_sha256(provider, ®ion_key, OSS_V4_SERVICE.as_bytes())?; + let signing_key = hmac_sha256(provider, &service_key, OSS_V4_REQUEST.as_bytes())?; + hex_hmac_sha256(provider, &signing_key, string_to_sign.as_bytes()) } fn v4_scope(&self, signing_time: Timestamp, region: &str) -> String { @@ -1196,7 +1224,7 @@ mod tests { use super::*; use crate::Credential; use http::Request; - use reqsign_core::{Context, SigningRequest}; + use reqsign_core::SigningRequest; const RAW_QUERY: &str = "slash=%2F&hash=%23&=%26&equals=%3D&space=%20&encoded-plus=%2B&literal-plus=+&double=%252F&dup=first&dup=second&=empty-key&empty=&flag&flag=&"; @@ -1332,7 +1360,12 @@ mod tests { .0; RequestSigner::new("bucket") .with_time(time) - .sign_header(&mut without_region, &credential, time) + .sign_header( + &reqsign_crypto_rustcrypto::RustCryptoProvider::new(), + &mut without_region, + &credential, + time, + ) .expect("signing without region must succeed"); let mut with_region = @@ -1344,7 +1377,12 @@ mod tests { RequestSigner::new("bucket") .with_region("oss-cn-beijing") .with_time(time) - .sign_header(&mut with_region, &credential, time) + .sign_header( + &reqsign_crypto_rustcrypto::RustCryptoProvider::new(), + &mut with_region, + &credential, + time, + ) .expect("signing with region must succeed"); assert_eq!( @@ -1405,7 +1443,12 @@ mod tests { .into_parts() .0; signer - .sign_v2_header(&mut signed_req, &credential, time) + .sign_v2_header( + &reqsign_crypto_rustcrypto::RustCryptoProvider::new(), + &mut signed_req, + &credential, + time, + ) .expect("v2 header signing must succeed"); assert_eq!( @@ -1473,7 +1516,12 @@ mod tests { .into_parts() .0; signer - .sign_v2_header(&mut signed_req, &credential, time) + .sign_v2_header( + &reqsign_crypto_rustcrypto::RustCryptoProvider::new(), + &mut signed_req, + &credential, + time, + ) .expect("v2 header signing must succeed"); assert_eq!( @@ -1533,6 +1581,7 @@ mod tests { .0; signer .sign_v2_query( + &reqsign_crypto_rustcrypto::RustCryptoProvider::new(), &mut signed_req, &credential, time, @@ -1590,7 +1639,13 @@ mod tests { .into_parts() .0; signer - .sign_v2_query(&mut signed_req, &credential, time, Duration::from_secs(640)) + .sign_v2_query( + &reqsign_crypto_rustcrypto::RustCryptoProvider::new(), + &mut signed_req, + &credential, + time, + Duration::from_secs(640), + ) .expect("v2 presign must succeed"); assert_eq!( @@ -1659,6 +1714,7 @@ mod tests { .0; signer .sign_v2_query( + &reqsign_crypto_rustcrypto::RustCryptoProvider::new(), &mut signed_req, &credential, time, @@ -1689,7 +1745,7 @@ mod tests { let err = RequestSigner::new("examplebucket") .with_signing_version(SigningVersion::V4) .with_time(Timestamp::from_second(1_744_353_684).expect("timestamp must build")) - .sign_request(&Context::new(), &mut req, Some(&credential), None) + .sign_request(&crate::test_context(), &mut req, Some(&credential), None) .await .expect_err("v4 without region must fail"); assert!(err.to_string().contains("OSS V4 signing requires region")); @@ -1744,6 +1800,7 @@ mod tests { ); let string_to_sign = signer .build_v4_string_to_sign( + &reqsign_crypto_rustcrypto::RustCryptoProvider::new(), time, &signer.v4_scope(time, "cn-hangzhou"), &canonical_request, @@ -1766,7 +1823,13 @@ mod tests { .0; signer - .sign_v4(&mut req, &credential, time, None) + .sign_v4( + &reqsign_crypto_rustcrypto::RustCryptoProvider::new(), + &mut req, + &credential, + time, + None, + ) .expect("v4 header signing must succeed"); assert_eq!( @@ -1842,6 +1905,7 @@ mod tests { .with_signing_version(SigningVersion::V4) .with_time(time) .sign_v4( + &reqsign_crypto_rustcrypto::RustCryptoProvider::new(), &mut req, &credential, time, @@ -1876,7 +1940,13 @@ mod tests { .with_region("cn-hangzhou") .with_signing_version(SigningVersion::V4) .with_time(time) - .sign_v4(&mut req, &credential, time, Some(Duration::from_secs(60))) + .sign_v4( + &reqsign_crypto_rustcrypto::RustCryptoProvider::new(), + &mut req, + &credential, + time, + Some(Duration::from_secs(60)), + ) .expect("v4 presign must succeed"); let query = req.uri.query().expect("query must exist"); @@ -1907,7 +1977,12 @@ mod tests { .into_parts() .0; signer - .sign_request(&Context::new(), &mut header_req, Some(&credential), None) + .sign_request( + &crate::test_context(), + &mut header_req, + Some(&credential), + None, + ) .await?; assert_eq!(header_req.uri.to_string(), original_uri); assert_eq!(header_req.headers["x-custom"], " value "); @@ -1915,7 +1990,7 @@ mod tests { let mut query_req = http::Request::get(&original_uri).body(())?.into_parts().0; signer .sign_request( - &Context::new(), + &crate::test_context(), &mut query_req, Some(&credential), Some(Duration::from_secs(60)), diff --git a/services/aliyun-oss/tests/common/mod.rs b/services/aliyun-oss/tests/common/mod.rs new file mode 100644 index 00000000..864b1164 --- /dev/null +++ b/services/aliyun-oss/tests/common/mod.rs @@ -0,0 +1,22 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use reqsign_core::Context; + +pub fn test_context() -> Context { + Context::new().with_crypto(reqsign_crypto_rustcrypto::RustCryptoProvider::new()) +} diff --git a/services/aliyun-oss/tests/credential_chain.rs b/services/aliyun-oss/tests/credential_chain.rs index e9f34891..6d66d37d 100644 --- a/services/aliyun-oss/tests/credential_chain.rs +++ b/services/aliyun-oss/tests/credential_chain.rs @@ -16,6 +16,8 @@ // under the License. //! Integration tests for ProvideCredentialChain with Aliyun OSS +mod common; + use reqsign_aliyun_oss::{Credential, EnvCredentialProvider}; use reqsign_core::ProvideCredentialChain; use reqsign_core::{Context, OsEnv, ProvideCredential, Result}; @@ -52,7 +54,7 @@ impl ProvideCredential for CountingProvider { #[tokio::test] async fn test_chain_stops_at_first_success() { - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -96,7 +98,7 @@ async fn test_chain_with_real_providers() { use reqsign_core::StaticEnv; use std::collections::HashMap; - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -127,7 +129,7 @@ async fn test_chain_with_real_providers() { #[tokio::test] async fn test_empty_chain_returns_none() { - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -139,7 +141,7 @@ async fn test_empty_chain_returns_none() { #[tokio::test] async fn test_chain_all_providers_return_none() { - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); diff --git a/services/aliyun-oss/tests/main.rs b/services/aliyun-oss/tests/main.rs index a7ffbe32..cc89839f 100644 --- a/services/aliyun-oss/tests/main.rs +++ b/services/aliyun-oss/tests/main.rs @@ -15,6 +15,8 @@ // specific language governing permissions and limitations // under the License. +mod common; + use std::env; use std::str::FromStr; use std::time::Duration; @@ -41,7 +43,7 @@ async fn init_signer() -> Option<(Context, Signer, ) -> Result { - let request = self.build_request()?; + let request = self.build_request(ctx.crypto_provider()?)?; let (mut parts, body) = request.into_parts(); sts_signer.sign(&mut parts, None).await.map_err(|err| { Error::new(err.kind(), "failed to sign AWS STS AssumeRole request") @@ -210,7 +211,7 @@ impl AssumeRoleOperation { /// Build the unsigned request shared by fixed and explicit-source flows. #[doc(hidden)] - pub fn build_request(&self) -> Result> { + pub fn build_request(&self, provider: &dyn CryptoProvider) -> Result> { let get_uri = format!("https://{}/?{}", self.endpoint, self.parameters); let (method, uri, body) = if get_uri.len() <= MAX_GET_URI_LENGTH { (http::Method::GET, get_uri, Bytes::new()) @@ -221,7 +222,7 @@ impl AssumeRoleOperation { Bytes::from(self.parameters.clone()), ) }; - let payload_hash = hex_sha256(&body); + let payload_hash = hex_sha256(provider, &body)?; http::Request::builder() .method(method) @@ -735,7 +736,10 @@ mod tests { let operation = AssumeRoleOperation::new("sts.us-east-1.amazonaws.com", &grant, Some(3_600)) .expect("large grant must be valid"); - let request = operation.build_request().expect("large request must build"); + let crypto = reqsign_crypto_rustcrypto::RustCryptoProvider::new(); + let request = operation + .build_request(&crypto) + .expect("large request must build"); assert_eq!(request.method(), http::Method::POST); assert_eq!(request.uri(), "https://sts.us-east-1.amazonaws.com/"); @@ -746,7 +750,7 @@ mod tests { .headers() .get(X_AMZ_CONTENT_SHA_256) .expect("payload hash must be present"), - &hex_sha256(request.body()) + &hex_sha256(&crypto, request.body()).expect("SHA-256 must succeed") ); } diff --git a/services/aws-core/src/lib.rs b/services/aws-core/src/lib.rs index 44ea8b82..886a8b19 100644 --- a/services/aws-core/src/lib.rs +++ b/services/aws-core/src/lib.rs @@ -44,6 +44,11 @@ pub mod signing; pub const EMPTY_STRING_SHA256: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; +#[cfg(test)] +pub(crate) fn test_context() -> reqsign_core::Context { + reqsign_core::Context::new().with_crypto(reqsign_crypto_rustcrypto::RustCryptoProvider::new()) +} + #[cfg(test)] mod tests { use reqsign_core::hash::hex_sha256; @@ -52,7 +57,11 @@ mod tests { #[test] fn empty_string_sha256_matches_computed_digest() { - assert_eq!(EMPTY_STRING_SHA256, hex_sha256(b"")); + let provider = reqsign_crypto_rustcrypto::RustCryptoProvider::new(); + assert_eq!( + EMPTY_STRING_SHA256, + hex_sha256(&provider, b"").expect("SHA-256 must succeed") + ); assert_eq!( EMPTY_STRING_SHA256, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" diff --git a/services/aws-core/src/provide_credential/assume_role_with_web_identity.rs b/services/aws-core/src/provide_credential/assume_role_with_web_identity.rs index a6c63b88..4bc01342 100644 --- a/services/aws-core/src/provide_credential/assume_role_with_web_identity.rs +++ b/services/aws-core/src/provide_credential/assume_role_with_web_identity.rs @@ -550,7 +550,7 @@ mod tests { "#; let http_send = CaptureHttpSend::new(http_body); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(file_read) .with_http_send(http_send.clone()) .with_env(StaticEnv { @@ -620,7 +620,7 @@ mod tests { "#; let http_send = CaptureHttpSend::new(http_body); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(file_read) .with_http_send(http_send.clone()) .with_env(StaticEnv { @@ -677,7 +677,7 @@ mod tests { "#; let http_send = CaptureHttpSend::new(response); - let ctx = Context::new().with_http_send(http_send.clone()); + let ctx = crate::test_context().with_http_send(http_send.clone()); let first = AssumeRoleWithWebIdentityCredentialProvider::new() .with_role_arn("arn:aws:iam::123456789012:role/test-role") @@ -718,7 +718,7 @@ mod tests { #[tokio::test] async fn expired_subject_token_is_rejected_before_http() { let http_send = CaptureHttpSend::new("unused"); - let ctx = Context::new().with_http_send(http_send.clone()); + let ctx = crate::test_context().with_http_send(http_send.clone()); let provider = AssumeRoleWithWebIdentityCredentialProvider::new() .with_role_arn("arn:aws:iam::123456789012:role/test-role") .with_subject_token_and_expiration( @@ -741,7 +741,7 @@ mod tests { "InvalidIdentityToken{secret}" ); let http_send = CaptureHttpSend::with_status(http::StatusCode::BAD_REQUEST, response); - let ctx = Context::new().with_http_send(http_send); + let ctx = crate::test_context().with_http_send(http_send); let provider = AssumeRoleWithWebIdentityCredentialProvider::new() .with_role_arn("arn:aws:iam::123456789012:role/test-role") .with_subject_token(secret); diff --git a/services/aws-core/src/provide_credential/cognito.rs b/services/aws-core/src/provide_credential/cognito.rs index 0805f6b9..5ffb8b16 100644 --- a/services/aws-core/src/provide_credential/cognito.rs +++ b/services/aws-core/src/provide_credential/cognito.rs @@ -310,7 +310,7 @@ mod tests { #[tokio::test] async fn test_cognito_provider_no_config() { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()); let provider = CognitoIdentityCredentialProvider::new(); diff --git a/services/aws-core/src/provide_credential/default.rs b/services/aws-core/src/provide_credential/default.rs index 413ef12f..ac0a07db 100644 --- a/services/aws-core/src/provide_credential/default.rs +++ b/services/aws-core/src/provide_credential/default.rs @@ -369,7 +369,7 @@ mod tests { async fn test_credential_env_loader_without_env() { let _ = env_logger::builder().is_test(true).try_init(); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -397,7 +397,7 @@ mod tests { async fn test_credential_env_loader_with_env() { let _ = env_logger::builder().is_test(true).try_init(); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -424,7 +424,7 @@ mod tests { async fn test_default_credential_provider_no_env_removes_slot() { let _ = env_logger::builder().is_test(true).try_init(); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -463,7 +463,7 @@ mod tests { async fn test_credential_profile_loader_from_config() { let _ = env_logger::builder().is_test(true).try_init(); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -491,7 +491,7 @@ mod tests { async fn test_credential_profile_loader_from_shared() { let _ = env_logger::builder().is_test(true).try_init(); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -516,7 +516,7 @@ mod tests { async fn test_default_credential_provider_prepend() { let _ = env_logger::builder().is_test(true).try_init(); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -554,7 +554,7 @@ mod tests { async fn test_default_credential_provider_no_profile_removes_slot() { let _ = env_logger::builder().is_test(true).try_init(); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -595,7 +595,7 @@ mod tests { async fn test_default_credential_provider_custom_profile_slot() { let _ = env_logger::builder().is_test(true).try_init(); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -633,7 +633,7 @@ mod tests { writeln!(file, "aws_access_key_id = SELECTED")?; writeln!(file, "aws_secret_access_key = selected-secret")?; - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_env(StaticEnv { home_dir: None, @@ -670,7 +670,7 @@ mod tests { writeln!(file, "sso_role_name = Developer")?; writeln!(file, "sso_start_url = https://example.awsapps.com/start")?; - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_env(StaticEnv { home_dir: Some(tmp_dir.path().to_path_buf()), @@ -712,7 +712,7 @@ mod tests { writeln!(file, "[profile selected]")?; writeln!(file, "credential_process = python3 {helper} --profile test")?; - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_command_execute(TokioCommandExecute) .with_env(StaticEnv { @@ -763,7 +763,7 @@ mod tests { async fn test_default_credential_provider_custom_process_slot() { let _ = env_logger::builder().is_test(true).try_init(); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_command_execute(TokioCommandExecute) @@ -799,7 +799,7 @@ mod tests { async fn test_default_credential_provider_no_process_removes_slot() { let _ = env_logger::builder().is_test(true).try_init(); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_command_execute(TokioCommandExecute) @@ -834,7 +834,7 @@ mod tests { async fn test_credential_profile_loader_from_both() { let _ = env_logger::builder().is_test(true).try_init(); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); diff --git a/services/aws-core/src/provide_credential/ecs.rs b/services/aws-core/src/provide_credential/ecs.rs index 5cb41ea8..569ee675 100644 --- a/services/aws-core/src/provide_credential/ecs.rs +++ b/services/aws-core/src/provide_credential/ecs.rs @@ -311,7 +311,7 @@ mod tests { #[tokio::test] async fn test_ecs_provider_no_env() { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()); let ctx = ctx.with_env(StaticEnv { @@ -326,7 +326,7 @@ mod tests { #[tokio::test] async fn test_get_endpoint_relative_uri() { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()); let ctx = ctx.with_env(StaticEnv { @@ -344,7 +344,7 @@ mod tests { #[tokio::test] async fn test_fargate_metadata_uri_does_not_override_credentials_endpoint() { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()); let ctx = ctx.with_env(StaticEnv { @@ -368,7 +368,7 @@ mod tests { #[tokio::test] async fn test_get_endpoint_full_uri() { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()); let ctx = ctx.with_env(StaticEnv { @@ -386,7 +386,7 @@ mod tests { #[tokio::test] async fn test_custom_endpoint() { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()); let provider = ECSCredentialProvider::new().with_endpoint("http://custom-endpoint/creds"); @@ -397,7 +397,7 @@ mod tests { #[tokio::test] async fn test_configured_relative_uri() { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(StaticEnv { @@ -413,7 +413,7 @@ mod tests { #[tokio::test] async fn test_configured_relative_uri_with_custom_base() { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(StaticEnv { @@ -431,7 +431,7 @@ mod tests { #[tokio::test] async fn test_configured_values_override_env() { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(StaticEnv { @@ -458,7 +458,7 @@ mod tests { #[tokio::test] async fn test_priority_order() { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(StaticEnv { @@ -486,7 +486,7 @@ mod tests { #[tokio::test] async fn test_configured_auth_token() { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(StaticEnv { @@ -513,7 +513,7 @@ mod tests { writeln!(temp_file, "file-token").unwrap(); let temp_path = temp_file.path().to_str().unwrap(); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(StaticEnv { @@ -546,7 +546,7 @@ mod tests { writeln!(temp_file, "file-token").unwrap(); let temp_path = temp_file.path().to_str().unwrap(); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(StaticEnv { diff --git a/services/aws-core/src/provide_credential/env.rs b/services/aws-core/src/provide_credential/env.rs index db284fab..396acf71 100644 --- a/services/aws-core/src/provide_credential/env.rs +++ b/services/aws-core/src/provide_credential/env.rs @@ -73,7 +73,7 @@ mod tests { ), ]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv) @@ -107,7 +107,7 @@ mod tests { ), ]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv) @@ -129,7 +129,7 @@ mod tests { #[tokio::test] async fn test_env_credential_provider_missing_credentials() -> anyhow::Result<()> { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv) @@ -147,7 +147,7 @@ mod tests { // Only access key ID let envs = HashMap::from([(AWS_ACCESS_KEY_ID.to_string(), "test_access_key".to_string())]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv) diff --git a/services/aws-core/src/provide_credential/process.rs b/services/aws-core/src/provide_credential/process.rs index 6ea2f86e..cd2c24fe 100644 --- a/services/aws-core/src/provide_credential/process.rs +++ b/services/aws-core/src/provide_credential/process.rs @@ -245,7 +245,7 @@ mod tests { #[tokio::test] async fn test_process_provider_no_config() { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_command_execute(TokioCommandExecute) @@ -298,7 +298,7 @@ mod tests { executor: RecordingCommandExecute, ) -> (ProcessCredentialProvider, Context) { let provider = ProcessCredentialProvider::new(); - let ctx = Context::new().with_command_execute(executor); + let ctx = crate::test_context().with_command_execute(executor); match profile { None => (provider.with_command(command), ctx), Some(profile) => { diff --git a/services/aws-core/src/provide_credential/profile.rs b/services/aws-core/src/provide_credential/profile.rs index 18ddd625..d5eac47d 100644 --- a/services/aws-core/src/provide_credential/profile.rs +++ b/services/aws-core/src/provide_credential/profile.rs @@ -161,7 +161,7 @@ mod tests { writeln!(tmp_file, "aws_secret_access_key = PROFILE1SECRETACCESSKEY")?; writeln!(tmp_file, "aws_session_token = PROFILE1SESSIONTOKEN")?; - let context = Context::new() + let context = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(StaticEnv { @@ -208,7 +208,7 @@ mod tests { writeln!(tmp_file, "aws_access_key_id = PROFILE1ACCESSKEYID")?; writeln!(tmp_file, "aws_secret_access_key = PROFILE1SECRETACCESSKEY")?; - let context = Context::new() + let context = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(StaticEnv { @@ -255,7 +255,7 @@ mod tests { writeln!(tmp_file, "aws_access_key_id = PROFILE1ACCESSKEYID")?; writeln!(tmp_file, "aws_secret_access_key = PROFILE1SECRETACCESSKEY")?; - let context = Context::new() + let context = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(StaticEnv { @@ -289,7 +289,7 @@ mod tests { writeln!(tmp_file, "aws_access_key_id = PROFILE1ACCESSKEYID")?; writeln!(tmp_file, "aws_secret_access_key = PROFILE1SECRETACCESSKEY")?; - let context = Context::new() + let context = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(StaticEnv { @@ -311,7 +311,7 @@ mod tests { #[tokio::test] async fn test_profile_missing_credentials() -> anyhow::Result<()> { - let context = Context::new() + let context = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()); diff --git a/services/aws-core/src/provide_credential/role_chain.rs b/services/aws-core/src/provide_credential/role_chain.rs index d76b04fe..0c853dca 100644 --- a/services/aws-core/src/provide_credential/role_chain.rs +++ b/services/aws-core/src/provide_credential/role_chain.rs @@ -181,11 +181,13 @@ impl ProvideCredential for AssumeRoleChainCredentialProvider { } } + let crypto = ctx.crypto_provider()?; let mut credential = self.source_credential(ctx, &shared, ¤t).await?; for operation in operations.into_iter().rev() { - let request = operation.build_request()?; + let request = operation.build_request(crypto)?; let (mut parts, body) = request.into_parts(); sign_request_parts( + crypto, &mut parts, &credential, None, diff --git a/services/aws-core/src/provide_credential/role_chain/tests.rs b/services/aws-core/src/provide_credential/role_chain/tests.rs index 8f7773ae..839b1bc6 100644 --- a/services/aws-core/src/provide_credential/role_chain/tests.rs +++ b/services/aws-core/src/provide_credential/role_chain/tests.rs @@ -19,9 +19,9 @@ use super::*; use crate::{DefaultCredentialProvider, DefaultCredentialProviderBuilder}; use bytes::Bytes; use http::{Request, Response, StatusCode, header}; +use reqsign_core::hash::hex_sha1; use reqsign_core::{ErrorKind, FileRead, HttpSend, StaticEnv}; use serde_json::json; -use sha1::{Digest, Sha1}; use std::collections::{HashMap, VecDeque}; use std::sync::{Arc, Mutex}; @@ -57,9 +57,10 @@ impl Files { } fn sso_token(&self, home: &str, session: &str) { - let digest = Sha1::digest(session.as_bytes()); + let provider = reqsign_crypto_rustcrypto::RustCryptoProvider::new(); + let digest = hex_sha1(&provider, session.as_bytes()).expect("SSO cache key must hash"); self.put( - &format!("{home}/.aws/sso/cache/{}.json", hex::encode(digest)), + &format!("{home}/.aws/sso/cache/{digest}.json"), json!({ "accessToken": SSO_ACCESS_TOKEN, "expiresAt": "2099-01-01T00:00:00Z", @@ -207,7 +208,7 @@ fn fixture(config: &str, envs: HashMap) -> (Context, Arc) files.put("/config", config.to_owned()); files.sso_token("/home", "example-session"); let http = Arc::new(Http::default()); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(files) .with_http_send(http.clone()) .with_env(StaticEnv { @@ -492,7 +493,7 @@ async fn sso_source_failure_is_not_swallowed() { files.put("/config", single_hop_sso_config()); let http = Arc::new(Http::default()); // No cached token exists, so the SSO source must fail before STS. - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(files) .with_http_send(http.clone()) .with_env(StaticEnv { diff --git a/services/aws-core/src/provide_credential/sso/session.rs b/services/aws-core/src/provide_credential/sso/session.rs index 965e51fd..47f6f859 100644 --- a/services/aws-core/src/provide_credential/sso/session.rs +++ b/services/aws-core/src/provide_credential/sso/session.rs @@ -20,6 +20,7 @@ use asyncband::mutex::Mutex; use http::{Method, Request, StatusCode}; +use reqsign_core::hash::hex_sha1; use reqsign_core::time::Timestamp; use reqsign_core::{Context, Error, Result}; use serde::Deserialize; @@ -42,11 +43,12 @@ impl SessionKey { .session_name .as_deref() .unwrap_or(&config.sso_start_url); + let provider = ctx.crypto_provider()?; let path = home .join(".aws") .join("sso") .join("cache") - .join(format!("{}.json", hex_sha1(name.as_bytes()))); + .join(format!("{}.json", hex_sha1(provider, name.as_bytes())?)); Ok(SessionKey { path: path.to_string_lossy().into_owned(), config_path: config.config_path.clone(), @@ -295,11 +297,3 @@ pub(super) fn login_required(reason: &str) -> Error { "{reason}. Please run 'aws sso login' for the selected profile" )) } - -// Simple SHA1 implementation for cache key generation -pub(super) fn hex_sha1(data: &[u8]) -> String { - use sha1::{Digest, Sha1}; - let mut hasher = Sha1::new(); - hasher.update(data); - hex::encode(hasher.finalize()) -} diff --git a/services/aws-core/src/provide_credential/sso/tests.rs b/services/aws-core/src/provide_credential/sso/tests.rs index 3a05e66a..6dbba4e2 100644 --- a/services/aws-core/src/provide_credential/sso/tests.rs +++ b/services/aws-core/src/provide_credential/sso/tests.rs @@ -15,10 +15,10 @@ // specific language governing permissions and limitations // under the License. -use super::session::hex_sha1; use super::*; use bytes::Bytes; use http::Response; +use reqsign_core::hash::hex_sha1; use reqsign_core::{FileRead, HttpSend, StaticEnv}; use serde_json::{Value, json}; use std::collections::VecDeque; @@ -53,8 +53,12 @@ impl Files { } fn token(&self, home: &str, name: &str, value: Value) { + let provider = reqsign_crypto_rustcrypto::RustCryptoProvider::new(); self.put( - &format!("{home}/.aws/sso/cache/{}.json", hex_sha1(name.as_bytes())), + &format!( + "{home}/.aws/sso/cache/{}.json", + hex_sha1(&provider, name.as_bytes()).expect("SSO cache key hashing must succeed") + ), value.to_string(), ); } @@ -134,7 +138,7 @@ fn timestamp() -> Timestamp { } fn context(files: &Arc, http: &Arc, home: &str, config_path: &str) -> Context { - Context::new() + crate::test_context() .with_file_read(files.clone()) .with_http_send(http.clone()) .with_env(StaticEnv { diff --git a/services/aws-core/src/provide_credential/static.rs b/services/aws-core/src/provide_credential/static.rs index 26a8749c..07c9e59c 100644 --- a/services/aws-core/src/provide_credential/static.rs +++ b/services/aws-core/src/provide_credential/static.rs @@ -67,7 +67,7 @@ mod tests { #[tokio::test] async fn test_static_credential_provider() -> anyhow::Result<()> { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); diff --git a/services/aws-core/src/signing.rs b/services/aws-core/src/signing.rs index 3ea79e43..0c403df0 100644 --- a/services/aws-core/src/signing.rs +++ b/services/aws-core/src/signing.rs @@ -21,6 +21,7 @@ use std::time::Duration; use http::{HeaderValue, Uri, header}; use log::debug; use percent_encoding::{AsciiSet, percent_decode_str, utf8_percent_encode}; +use reqsign_core::crypto::CryptoProvider; use reqsign_core::time::Timestamp; use reqsign_core::{Result, SigningRequest}; @@ -303,6 +304,7 @@ pub struct SigV4SigningOptions<'a> { /// operation headroom. #[doc(hidden)] pub fn sign_request_parts( + provider: &dyn CryptoProvider, req: &mut http::request::Parts, credential: &Credential, expires_in: Option, @@ -345,7 +347,7 @@ pub fn sign_request_parts( &canonical_query, options.percent_encoding_mode, )?; - let encoded_req = reqsign_core::hash::hex_sha256(creq.as_bytes()); + let encoded_req = reqsign_core::hash::hex_sha256(provider, creq.as_bytes())?; // Scope: "20220313///aws4_request" let scope = format!( @@ -380,12 +382,14 @@ pub fn sign_request_parts( debug!("calculated string to sign: {string_to_sign}"); let signing_key = generate_signing_key( + provider, &credential.secret_access_key, now, options.region, options.service, - ); - let signature = reqsign_core::hash::hex_hmac_sha256(&signing_key, string_to_sign.as_bytes()); + )?; + let signature = + reqsign_core::hash::hex_hmac_sha256(provider, &signing_key, string_to_sign.as_bytes())?; let final_uri = if expires_in.is_some() { let unsigned_uri = append_query_pairs(&original_uri, &authentication_query)?; @@ -487,13 +491,29 @@ pub fn sigv4_authentication_query( query } -fn generate_signing_key(secret: &str, time: Timestamp, region: &str, service: &str) -> Vec { +fn generate_signing_key( + provider: &dyn CryptoProvider, + secret: &str, + time: Timestamp, + region: &str, + service: &str, +) -> Result> { let secret = format!("AWS4{secret}"); - let sign_date = - reqsign_core::hash::hmac_sha256(secret.as_bytes(), time.format_date().as_bytes()); - let sign_region = reqsign_core::hash::hmac_sha256(sign_date.as_slice(), region.as_bytes()); - let sign_service = reqsign_core::hash::hmac_sha256(sign_region.as_slice(), service.as_bytes()); - reqsign_core::hash::hmac_sha256(sign_service.as_slice(), "aws4_request".as_bytes()) + let sign_date = reqsign_core::hash::hmac_sha256( + provider, + secret.as_bytes(), + time.format_date().as_bytes(), + )?; + let sign_region = + reqsign_core::hash::hmac_sha256(provider, sign_date.as_slice(), region.as_bytes())?; + let sign_service = + reqsign_core::hash::hmac_sha256(provider, sign_region.as_slice(), service.as_bytes())?; + Ok(reqsign_core::hash::hmac_sha256( + provider, + sign_service.as_slice(), + "aws4_request".as_bytes(), + )? + .to_vec()) } #[cfg(test)] diff --git a/services/aws-core/tests/common/mod.rs b/services/aws-core/tests/common/mod.rs new file mode 100644 index 00000000..864b1164 --- /dev/null +++ b/services/aws-core/tests/common/mod.rs @@ -0,0 +1,22 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use reqsign_core::Context; + +pub fn test_context() -> Context { + Context::new().with_crypto(reqsign_crypto_rustcrypto::RustCryptoProvider::new()) +} diff --git a/services/aws-core/tests/shared_config.rs b/services/aws-core/tests/shared_config.rs index 74e87b7c..ba1b6598 100644 --- a/services/aws-core/tests/shared_config.rs +++ b/services/aws-core/tests/shared_config.rs @@ -15,6 +15,8 @@ // specific language governing permissions and limitations // under the License. +mod common; + use bytes::Bytes; use reqsign_aws_core::{IMDSv2RegionProvider, SharedConfig}; use reqsign_core::{Context, Error, ErrorKind, FileRead, HttpSend, Result, StaticEnv}; @@ -52,7 +54,7 @@ impl reqsign_core::CommandExecute for NoIo { } fn context(files: &[(&str, &str)], env: &[(&str, &str)]) -> Context { - Context::new() + crate::common::test_context() .with_file_read(Files( files .iter() diff --git a/services/aws-v4/Cargo.toml b/services/aws-v4/Cargo.toml index fcd79a51..627a18ad 100644 --- a/services/aws-v4/Cargo.toml +++ b/services/aws-v4/Cargo.toml @@ -40,6 +40,7 @@ reqsign-core = { workspace = true } serde = { workspace = true } [dev-dependencies] +reqsign-crypto-rustcrypto = { workspace = true } anyhow = { workspace = true } aws-credential-types = "1.1.8" aws-sigv4 = "1.2.0" diff --git a/services/aws-v4/README.md b/services/aws-v4/README.md index 8e280289..9787c1ce 100644 --- a/services/aws-v4/README.md +++ b/services/aws-v4/README.md @@ -2,9 +2,16 @@ AWS SigV4 signing implementation for `reqsign`. +> Signing needs a `CryptoProvider` resolved through the `Context`: bind one with +> `Context::with_crypto`, install a process-wide default, or use a facade +> `default_context()` (which binds RustCrypto when the global slot is empty). A +> bare `Context::new()` starts unbound. See +> [CryptoProvider](https://github.com/apache/reqsign/blob/main/docs/crypto-provider.md). + ## Quick Start ```rust,no_run +use reqsign_crypto_rustcrypto::RustCryptoProvider; use reqsign_aws_v4::{DefaultCredentialProvider, EMPTY_STRING_SHA256, RequestSigner}; use reqsign_core::{Context, OsEnv, Signer}; use reqsign_file_read_tokio::TokioFileRead; @@ -12,7 +19,7 @@ use reqsign_http_send_reqwest::ReqwestHttpSend; #[tokio::main] async fn main() -> anyhow::Result<()> { - let ctx = Context::new() + let ctx = Context::new().with_crypto(RustCryptoProvider::new()) .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -87,7 +94,7 @@ let body: &[u8] = b"Hello, World!"; let payload_hash = if body.is_empty() { EMPTY_STRING_SHA256.to_string() } else { - hex_sha256(body) + hex_sha256(body).expect("SHA-256 must succeed") }; let request = http::Request::put("https://s3.amazonaws.com/mybucket/hello.txt") @@ -185,6 +192,7 @@ an existing AWS credential and return the temporary credential issued by S3 Access Grants. The result can be passed directly to the existing AWS signer. ```rust,no_run +use reqsign_crypto_rustcrypto::RustCryptoProvider; use std::time::Duration; use reqsign_aws_v4::{ @@ -202,7 +210,7 @@ let grant = S3AccessGrantsGrant::new( S3AccessGrantsPrivilege::Minimal, ); let granter = Granter::new( - Context::new().with_http_send(ReqwestHttpSend::default()), + Context::new().with_crypto(RustCryptoProvider::new()).with_http_send(ReqwestHttpSend::default()), DefaultCredentialProvider::new(), S3AccessGrantsGranter::new( S3AccessGrantsConfig::new("111122223333", "us-east-2"), diff --git a/services/aws-v4/benches/aws.rs b/services/aws-v4/benches/aws.rs index 3d484d43..c26a2d2b 100644 --- a/services/aws-v4/benches/aws.rs +++ b/services/aws-v4/benches/aws.rs @@ -56,6 +56,7 @@ pub fn bench(c: &mut Criterion) { let s = AwsV4RequestSigner::new("s3", "test"); let ctx = Context::new() + .with_crypto(reqsign_crypto_rustcrypto::RustCryptoProvider::new()) .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()); diff --git a/services/aws-v4/examples/dynamodb_sign.rs b/services/aws-v4/examples/dynamodb_sign.rs index 29fb36f2..8f42c758 100644 --- a/services/aws-v4/examples/dynamodb_sign.rs +++ b/services/aws-v4/examples/dynamodb_sign.rs @@ -31,8 +31,11 @@ async fn main() -> Result<()> { // Create HTTP client let client = Client::new(); + let crypto = reqsign_crypto_rustcrypto::RustCryptoProvider::new(); + // Create context let ctx = Context::new() + .with_crypto(reqsign_crypto_rustcrypto::RustCryptoProvider::new()) .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::new(client.clone())) .with_env(OsEnv); @@ -69,7 +72,7 @@ async fn main() -> Result<()> { .header("x-amz-target", "DynamoDB_20120810.ListTables") .header( "x-amz-content-sha256", - &reqsign_core::hash::hex_sha256(&body_bytes), + &reqsign_core::hash::hex_sha256(&crypto, &body_bytes)?, ) .body(reqwest::Body::from(body_bytes)) .unwrap(); @@ -104,7 +107,7 @@ async fn main() -> Result<()> { .header("x-amz-target", "DynamoDB_20120810.DescribeTable") .header( "x-amz-content-sha256", - &reqsign_core::hash::hex_sha256(&body_bytes), + &reqsign_core::hash::hex_sha256(&crypto, &body_bytes)?, ) .body(reqwest::Body::from(body_bytes)) .unwrap(); @@ -140,7 +143,7 @@ async fn main() -> Result<()> { .header("x-amz-target", "DynamoDB_20120810.PutItem") .header( "x-amz-content-sha256", - &reqsign_core::hash::hex_sha256(&body_bytes), + &reqsign_core::hash::hex_sha256(&crypto, &body_bytes)?, ) .body(reqwest::Body::from(body_bytes)) .unwrap(); diff --git a/services/aws-v4/examples/s3_express_sign.rs b/services/aws-v4/examples/s3_express_sign.rs index a6fbeb4e..4283aa4a 100644 --- a/services/aws-v4/examples/s3_express_sign.rs +++ b/services/aws-v4/examples/s3_express_sign.rs @@ -32,6 +32,7 @@ async fn main() -> Result<()> { // Create context with Tokio file reader and reqwest HTTP client let ctx = Context::new() + .with_crypto(reqsign_crypto_rustcrypto::RustCryptoProvider::new()) .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::new(client.clone())) .with_env(OsEnv); diff --git a/services/aws-v4/examples/s3_sign.rs b/services/aws-v4/examples/s3_sign.rs index eb73fb0b..49de7473 100644 --- a/services/aws-v4/examples/s3_sign.rs +++ b/services/aws-v4/examples/s3_sign.rs @@ -32,6 +32,7 @@ async fn main() -> Result<()> { // Create context with Tokio file reader and reqwest HTTP client let ctx = Context::new() + .with_crypto(reqsign_crypto_rustcrypto::RustCryptoProvider::new()) .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::new(client.clone())) .with_env(OsEnv); diff --git a/services/aws-v4/src/assume_role.rs b/services/aws-v4/src/assume_role.rs index 0ef7cbcd..6ad71814 100644 --- a/services/aws-v4/src/assume_role.rs +++ b/services/aws-v4/src/assume_role.rs @@ -200,7 +200,7 @@ impl GrantCredential for AssumeRoleGranter { let required_until = self.required_valid_until(credential, expires_in); self.validate_source(credential, required_until)?; - let request = operation.build_request()?; + let request = operation.build_request(ctx.crypto_provider()?)?; let (mut parts, body) = request.into_parts(); self.request_signer() .sign_request(ctx, &mut parts, Some(credential), None) @@ -459,7 +459,7 @@ mod tests { success_response("ASIAFIRSTOUTPUT001"), success_response("ASIASECONDOUTPUT01"), ]); - let context = Context::new().with_http_send(http.clone()); + let context = crate::test_context().with_http_send(http.clone()); let (provider, provider_calls) = FixedCredentialProvider::new(source_credential(Some(SOURCE_SESSION_TOKEN))); let operation = @@ -538,14 +538,18 @@ mod tests { "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20260730/us-east-1/sts/aws4_request, SignedHeaders=content-type;host;x-amz-content-sha256;x-amz-date;x-amz-security-token, Signature=9561cc1cbe7212bd5763162afbaf215cd24c153eb27ac2718ebee4b12ff82a5f" ); let sdk_request = sign_with_aws_sdk( - AssumeRoleOperation::new( - "sts.us-east-1.amazonaws.com", - &valid_grant().with_external_id("tenant/123"), - Some(3_600), - ) - .expect("operation must build") - .build_request() - .expect("request must build"), + { + let operation = AssumeRoleOperation::new( + "sts.us-east-1.amazonaws.com", + &valid_grant().with_external_id("tenant/123"), + Some(3_600), + ) + .expect("operation must build"); + let provider = reqsign_crypto_rustcrypto::RustCryptoProvider::new(); + operation + .build_request(&provider) + .expect("request must build") + }, Some(SOURCE_SESSION_TOKEN), ); assert_eq!( @@ -570,14 +574,19 @@ mod tests { .collect(), ); let sdk_request = sign_with_aws_sdk( - AssumeRoleOperation::new("sts.us-east-1.amazonaws.com", &grant, Some(3_600)) - .expect("operation must build") - .build_request() - .expect("request must build"), + { + let operation = + AssumeRoleOperation::new("sts.us-east-1.amazonaws.com", &grant, Some(3_600)) + .expect("operation must build"); + let provider = reqsign_crypto_rustcrypto::RustCryptoProvider::new(); + operation + .build_request(&provider) + .expect("request must build") + }, Some(SOURCE_SESSION_TOKEN), ); let http = MockHttpSend::new([success_response("ASIAPOSTOUTPUT0001")]); - let context = Context::new().with_http_send(http.clone()); + let context = crate::test_context().with_http_send(http.clone()); let operation = AssumeRoleGranter::new(REGION, grant).with_time(signing_time()); operation @@ -604,7 +613,11 @@ mod tests { .expect("payload hash must be set") .to_str() .expect("payload hash must be text"), - hex_sha256(&request.body) + hex_sha256( + &reqsign_crypto_rustcrypto::RustCryptoProvider::new(), + &request.body, + ) + .expect("SHA-256 must succeed") ); assert_eq!( request @@ -634,7 +647,7 @@ mod tests { success_response("ASIALONGTERMSOURCE1"), success_response("ASIATEMPSOURCE00001"), ]); - let context = Context::new().with_http_send(http.clone()); + let context = crate::test_context().with_http_send(http.clone()); let operation = AssumeRoleGranter::new(REGION, valid_grant()).with_time(signing_time()); let mut long_lived_source = source_credential(None); long_lived_source.expires_in = None; @@ -689,7 +702,7 @@ mod tests { #[tokio::test] async fn validates_typed_grant_region_and_lifetime_before_sts_io() { let http = MockHttpSend::new(Vec::>::new()); - let context = Context::new().with_http_send(http.clone()); + let context = crate::test_context().with_http_send(http.clone()); let source = source_credential(None); let valid_policy_arn = "arn:aws:iam::123456789012:policy/customer-reader".to_string(); @@ -765,7 +778,7 @@ mod tests { #[tokio::test] async fn rejects_invalid_source_variants_before_sts_io() { let http = MockHttpSend::new(Vec::>::new()); - let context = Context::new().with_http_send(http.clone()); + let context = crate::test_context().with_http_send(http.clone()); let operation = AssumeRoleGranter::new(REGION, valid_grant()).with_time(signing_time()); let invalid_sources = [ Credential::default(), @@ -846,7 +859,7 @@ mod tests { malformed_access_key, malformed_session_token, ]); - let context = Context::new().with_http_send(http.clone()); + let context = crate::test_context().with_http_send(http.clone()); let operation = AssumeRoleGranter::new(REGION, valid_grant()).with_time(signing_time()); let expired_error = operation @@ -872,7 +885,7 @@ mod tests { #[tokio::test] async fn fixed_provider_preserves_global_endpoint_and_request_defaults() { let http = MockHttpSend::new([success_response("ASIAPROVIDERDEFAULT1")]); - let context = Context::new().with_http_send(http.clone()); + let context = crate::test_context().with_http_send(http.clone()); let (source, _) = FixedCredentialProvider::new(source_credential(None)); let provider = AssumeRoleCredentialProvider::new( ROLE_ARN.to_string(), @@ -900,7 +913,7 @@ mod tests { #[tokio::test] async fn fixed_provider_accepts_valid_iam_role_paths_and_preserves_retryability() { let success_http = MockHttpSend::new([success_response("ASIAVALIDROLEPATH01")]); - let success_context = Context::new().with_http_send(success_http); + let success_context = crate::test_context().with_http_send(success_http); let (source, _) = FixedCredentialProvider::new(source_credential(None)); let provider = AssumeRoleCredentialProvider::new( "arn:aws:iam::123456789012:role/team!prod/Reader".to_string(), @@ -920,13 +933,13 @@ mod tests { let provider = AssumeRoleCredentialProvider::new( ROLE_ARN.to_string(), Signer::new( - Context::new(), + crate::test_context(), source, RequestSigner::new("sts", REGION).with_time(signing_time()), ), ); let error = provider - .provide_credential(&Context::new().with_http_send(NonRetryableTransportError)) + .provide_credential(&crate::test_context().with_http_send(NonRetryableTransportError)) .await .expect_err("transport must fail"); assert_eq!(error.kind(), ErrorKind::Unexpected); @@ -952,7 +965,7 @@ mod tests { success_response("ASIAGRANTEROUTPUT01"), success_response("ASIAPROVIDEROUTPUT1"), ]); - let context = Context::new().with_http_send(http.clone()); + let context = crate::test_context().with_http_send(http.clone()); let operation = AssumeRoleGranter::new(REGION, grant.clone()).with_time(signing_time()); let granted = operation .grant_credential( @@ -1028,7 +1041,7 @@ mod tests { } } - let transport_context = Context::new().with_http_send(SecretTransportError); + let transport_context = crate::test_context().with_http_send(SecretTransportError); let transport_error = operation .grant_credential(&transport_context, &source, None) .await @@ -1056,7 +1069,7 @@ mod tests { )) .expect("response must build"); let http = MockHttpSend::new([known_sts_error_response, unknown_sts_error_response]); - let context = Context::new().with_http_send(http); + let context = crate::test_context().with_http_send(http); let denied = operation .grant_credential(&context, &source, None) @@ -1081,7 +1094,7 @@ mod tests { let provider = AssumeRoleCredentialProvider::new( ROLE_ARN.to_string(), Signer::new( - Context::new(), + crate::test_context(), provider_source, RequestSigner::new("sts", REGION), ), diff --git a/services/aws-v4/src/lib.rs b/services/aws-v4/src/lib.rs index 0946987c..0e29c43c 100644 --- a/services/aws-v4/src/lib.rs +++ b/services/aws-v4/src/lib.rs @@ -191,3 +191,8 @@ pub use reqsign_aws_core::{IMDSv2RegionProvider, Profile, SharedConfig}; pub use reqsign_aws_core::{ProcessCredentialProvider, SSOCredentialProvider}; pub const EMPTY_STRING_SHA256: &str = reqsign_aws_core::EMPTY_STRING_SHA256; + +#[cfg(test)] +pub(crate) fn test_context() -> reqsign_core::Context { + reqsign_core::Context::new().with_crypto(reqsign_crypto_rustcrypto::RustCryptoProvider::new()) +} diff --git a/services/aws-v4/src/provide_credential/s3_express_session.rs b/services/aws-v4/src/provide_credential/s3_express_session.rs index 96d7ad0b..08d74313 100644 --- a/services/aws-v4/src/provide_credential/s3_express_session.rs +++ b/services/aws-v4/src/provide_credential/s3_express_session.rs @@ -1273,7 +1273,7 @@ mod tests { responses: impl IntoIterator>, ) -> (S3ExpressSessionGranter, Context, MockHttpSend) { let http = MockHttpSend::new(responses); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let operation = S3ExpressSessionGranter::new(config, grant).with_time(now); (operation, ctx, http) } @@ -1292,7 +1292,7 @@ mod tests { responses: impl IntoIterator>, ) -> (S3ExpressSessionGranter, Context, MockHttpSend) { let http = MockHttpSend::new(responses); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let operation = S3ExpressSessionGranter::new_with_custom_endpoint( "compatible-bucket", "custom-region-1", @@ -2043,7 +2043,7 @@ mod tests { async fn rejects_invalid_custom_endpoint_configuration_before_provider_io() { let (source_provider, source_calls) = FixedCredentialProvider::new(source_credential()); let http = MockHttpSend::new([]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let invalid = [ ( "", @@ -2230,7 +2230,7 @@ mod tests { .expect("custom endpoint configuration must be valid") .with_time(timestamp("2030-01-01T00:00:00Z")); let source = source_credential(); - let ctx = Context::new().with_http_send(FailingHttpSend); + let ctx = crate::test_context().with_http_send(FailingHttpSend); let err = operation .grant_credential(&ctx, &source, None) @@ -2282,7 +2282,7 @@ mod tests { "2099-01-01T00:05:00Z", ); let http = MockHttpSend::new([response]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let (source_provider, source_calls) = FixedCredentialProvider::new(source_credential()); let provider = S3ExpressSessionProvider::new("example--usw2-az1--x-s3", source_provider); @@ -2320,7 +2320,7 @@ mod tests { &second_expiration, ), ]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let (source_provider, source_calls) = FixedCredentialProvider::new(source_credential()); let provider = S3ExpressSessionProvider::new("example--usw2-az1--x-s3", source_provider) .with_grant(S3ExpressSessionGrant::maximum_allowed()); @@ -2383,7 +2383,7 @@ mod tests { "2099-01-01T00:05:00Z", ); let http = MockHttpSend::new([response]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let (source_provider, source_calls) = FixedCredentialProvider::new(source_credential()); let provider = S3ExpressSessionProvider::new("example--apse6-az1--x-s3", source_provider) .with_region("ap-southeast-6"); @@ -2411,7 +2411,7 @@ mod tests { "2099-01-01T00:05:00Z", ); let http = MockHttpSend::new([response]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let (source_provider, source_calls) = FixedCredentialProvider::new(source_credential()); let provider = S3ExpressSessionProvider::new("example--cnn1-pkx1-az1--x-s3", source_provider); @@ -2440,7 +2440,7 @@ mod tests { #[tokio::test] async fn provider_validates_configuration_before_loading_source() { let http = MockHttpSend::new([]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let (source_provider, source_calls) = FixedCredentialProvider::new(source_credential()); let provider = S3ExpressSessionProvider::new("invalid-bucket", source_provider); @@ -2456,7 +2456,7 @@ mod tests { #[tokio::test] async fn provider_rejects_unsupported_partition_before_loading_source() { let http = MockHttpSend::new([]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let (source_provider, source_calls) = FixedCredentialProvider::new(source_credential()); let provider = S3ExpressSessionProvider::new("example--usgw1-az1--x-s3", source_provider) .with_region("us-gov-west-1"); @@ -2473,7 +2473,7 @@ mod tests { #[tokio::test] async fn provider_rejects_zone_region_mismatch_before_loading_source() { let http = MockHttpSend::new([]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let (source_provider, source_calls) = FixedCredentialProvider::new(source_credential()); let provider = S3ExpressSessionProvider::new("example--use1-az1--x-s3", source_provider) .with_region("us-west-2"); @@ -2499,7 +2499,7 @@ mod tests { ) }; let http = MockHttpSend::new([response(), response()]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let operation = S3ExpressSessionGranter::new(config(), S3ExpressSessionGrant::maximum_allowed()) .with_time(now); @@ -2528,7 +2528,7 @@ mod tests { let (output_provider, _) = FixedCredentialProvider::new(output); let signer = Signer::new( - Context::new(), + crate::test_context(), output_provider, crate::RequestSigner::new("s3express", "us-west-2"), ); diff --git a/services/aws-v4/src/s3_access_grants.rs b/services/aws-v4/src/s3_access_grants.rs index a517f314..236318bf 100644 --- a/services/aws-v4/src/s3_access_grants.rs +++ b/services/aws-v4/src/s3_access_grants.rs @@ -1173,7 +1173,7 @@ mod tests { "granted-session-token", RESPONSE_EXPIRATION, )]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let grant = S3AccessGrantsGrant::new( S3AccessGrantsTarget::for_object("example-bucket", "customer/%tenant/file name.txt"), S3AccessGrantsPermission::ReadWrite, @@ -1362,7 +1362,7 @@ mod tests { "granted-token", RESPONSE_EXPIRATION, )]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); operation(grant) .grant_credential(&ctx, &source_credential(), duration) .await @@ -1405,7 +1405,7 @@ mod tests { "granted-token", RESPONSE_EXPIRATION, )]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let granter = S3AccessGrantsGranter::new( config().with_trusted_endpoint(endpoint), minimal_read_grant(S3AccessGrantsTarget::for_bucket("example-bucket")), @@ -1439,7 +1439,7 @@ mod tests { "granted-token", RESPONSE_EXPIRATION, )]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let source = Credential { access_key_id: SOURCE_ACCESS_KEY.to_string(), secret_access_key: SOURCE_SECRET_KEY.to_string(), @@ -1504,7 +1504,7 @@ mod tests { #[tokio::test] async fn rejects_invalid_instance_configuration_before_io() { let http = MockHttpSend::new([]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let grant = minimal_read_grant(S3AccessGrantsTarget::for_bucket("example-bucket")); let configs = [ S3AccessGrantsConfig::new("111", REGION), @@ -1699,7 +1699,7 @@ mod tests { "granted-token", RESPONSE_EXPIRATION, )]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); operation(minimal_read_grant(S3AccessGrantsTarget::for_prefix( "example-bucket", "customer/", @@ -1815,7 +1815,7 @@ mod tests { "granted-token", authoritative, )]); - let ctx = Context::new().with_http_send(http); + let ctx = crate::test_context().with_http_send(http); let output = operation(minimal_read_grant(S3AccessGrantsTarget::for_bucket( "example-bucket", ))) @@ -1830,7 +1830,7 @@ mod tests { "granted-token", "2099-01-01T00:00:10Z", )]); - let ctx = Context::new().with_http_send(http); + let ctx = crate::test_context().with_http_send(http); let error = operation(minimal_read_grant(S3AccessGrantsTarget::for_bucket( "example-bucket", ))) @@ -1844,7 +1844,7 @@ mod tests { #[tokio::test] async fn rejects_invalid_source_and_grant_before_io() { let http = MockHttpSend::new([]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let valid_grant = minimal_read_grant(S3AccessGrantsTarget::for_bucket("example-bucket")); let mut sources = Vec::new(); @@ -1891,7 +1891,7 @@ mod tests { (ErrorKind::ConfigInvalid, false), (ErrorKind::Unexpected, true), ] { - let ctx = Context::new().with_http_send(FailingHttpSend { kind, retryable }); + let ctx = crate::test_context().with_http_send(FailingHttpSend { kind, retryable }); let error = operation(minimal_read_grant(S3AccessGrantsTarget::for_bucket( "example-bucket", ))) @@ -1918,7 +1918,7 @@ mod tests { )) .expect("response must build"); let http = MockHttpSend::new([response]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let error = operation(minimal_read_grant(S3AccessGrantsTarget::for_bucket( "example-bucket", ))) @@ -1948,7 +1948,7 @@ mod tests { "#; let http = MockHttpSend::new([response(StatusCode::OK, &body[..])]); - let ctx = Context::new().with_http_send(http); + let ctx = crate::test_context().with_http_send(http); let error = operation(minimal_read_grant(S3AccessGrantsTarget::for_bucket( "example-bucket", ))) @@ -2030,7 +2030,7 @@ mod tests { "granted-session-token", RESPONSE_EXPIRATION, )]); - let ctx = Context::new().with_http_send(http); + let ctx = crate::test_context().with_http_send(http); let (source_provider, _) = FixedCredentialProvider::new(source_credential()); let granted = Granter::new( ctx, @@ -2046,7 +2046,7 @@ mod tests { let (granted_provider, _) = FixedCredentialProvider::new(granted.clone()); let signer = Signer::new( - Context::new(), + crate::test_context(), granted_provider, RequestSigner::new("s3", REGION).with_time(timestamp("2099-01-01T00:01:00Z")), ); @@ -2090,7 +2090,7 @@ mod tests { RESPONSE_EXPIRATION, ), ]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let (source_provider, source_calls) = FixedCredentialProvider::new(source_credential()); let granter = Granter::new( ctx, diff --git a/services/aws-v4/src/sign_request.rs b/services/aws-v4/src/sign_request.rs index 73564dc0..7ef45a9f 100644 --- a/services/aws-v4/src/sign_request.rs +++ b/services/aws-v4/src/sign_request.rs @@ -50,11 +50,12 @@ const CREDENTIAL_OPERATION_HEADROOM: Duration = Duration::from_secs(10); /// use reqsign_aws_v4::EMPTY_STRING_SHA256; /// use reqsign_core::hash::hex_sha256; /// +/// let provider = reqsign_crypto_rustcrypto::RustCryptoProvider::new(); /// let body: &[u8] = b"Hello, World!"; /// let payload_hash = if body.is_empty() { /// EMPTY_STRING_SHA256.to_string() /// } else { -/// hex_sha256(body) +/// hex_sha256(&provider, body).expect("SHA-256 must succeed") /// }; /// /// let request = http::Request::put("https://s3.amazonaws.com/mybucket/hello.txt") @@ -194,7 +195,7 @@ impl SignRequest for RequestSigner { async fn sign_request( &self, - _: &Context, + ctx: &Context, req: &mut Parts, credential: Option<&Self::Credential>, expires_in: Option, @@ -202,8 +203,10 @@ impl SignRequest for RequestSigner { let Some(credential) = credential else { return Ok(()); }; + let crypto = ctx.crypto_provider()?; sign_request_parts( + crypto, req, credential, expires_in, @@ -397,7 +400,12 @@ mod tests { let (mut session_parts, body) = Request::get(S3_EXPRESS_URI).body("")?.into_parts(); RequestSigner::new("s3express", S3_EXPRESS_REGION) .with_time(now) - .sign_request(&Context::new(), &mut session_parts, Some(&credential), None) + .sign_request( + &crate::test_context(), + &mut session_parts, + Some(&credential), + None, + ) .await?; let actual_session = Request::from_parts(session_parts, body); compare_request( @@ -426,7 +434,12 @@ mod tests { RequestSigner::new("s3express", S3_EXPRESS_REGION) .with_standard_session_token() .with_time(now) - .sign_request(&Context::new(), &mut iam_parts, Some(&credential), None) + .sign_request( + &crate::test_context(), + &mut iam_parts, + Some(&credential), + None, + ) .await?; let actual_iam = Request::from_parts(iam_parts, body); compare_request("S3 Express IAM header mode", &expected_iam, &actual_iam); @@ -482,7 +495,7 @@ mod tests { RequestSigner::new("s3express", S3_EXPRESS_REGION) .with_time(now) .sign_request( - &Context::new(), + &crate::test_context(), &mut session_parts, Some(&credential), expires_in, @@ -502,7 +515,7 @@ mod tests { .with_standard_session_token() .with_time(now) .sign_request( - &Context::new(), + &crate::test_context(), &mut iam_parts, Some(&credential), expires_in, @@ -574,7 +587,7 @@ mod tests { RequestSigner::new("s3express", S3_EXPRESS_REGION) .with_time(now) .sign_request( - &Context::new(), + &crate::test_context(), &mut session_parts, Some(&credential), expires_in, @@ -598,7 +611,7 @@ mod tests { .with_standard_session_token() .with_time(now) .sign_request( - &Context::new(), + &crate::test_context(), &mut iam_parts, Some(&credential), expires_in, @@ -649,7 +662,12 @@ mod tests { let (mut parts, _body) = Request::get(uri).body("")?.into_parts(); RequestSigner::new("s3", S3_EXPRESS_REGION) .with_time(now) - .sign_request(&Context::new(), &mut parts, Some(&credential), expires_in) + .sign_request( + &crate::test_context(), + &mut parts, + Some(&credential), + expires_in, + ) .await?; if presigned { @@ -692,7 +710,7 @@ mod tests { let mut parts = Request::get(uri).body(())?.into_parts().0; let original = parts.clone(); let error = signer - .sign_request(&Context::new(), &mut parts, Some(&credential), None) + .sign_request(&crate::test_context(), &mut parts, Some(&credential), None) .await .expect_err("invalid session token must be rejected"); @@ -731,7 +749,7 @@ mod tests { calls: calls.clone(), }; let signer = Signer::new( - Context::new(), + crate::test_context(), provider, RequestSigner::new("s3", "test").with_time(now), ); @@ -776,7 +794,7 @@ mod tests { calls: calls.clone(), }; let signer = Signer::new( - Context::new(), + crate::test_context(), provider, RequestSigner::new("s3", "test").with_time(now), ); @@ -934,7 +952,8 @@ mod tests { HeaderValue::from_str(&content.len().to_string()).expect("must be valid"), ); - let body = hex_sha256(content.as_bytes()); + let provider = reqsign_crypto_rustcrypto::RustCryptoProvider::new(); + let body = hex_sha256(&provider, content.as_bytes()).expect("SHA-256 must succeed"); req.headers_mut().insert( "x-amz-content-sha256", HeaderValue::from_str(&body).expect("must be valid"), @@ -1079,7 +1098,7 @@ mod tests { let (mut parts, body) = encoding_request(uri)?.into_parts(); signer .sign_request( - &Context::new(), + &crate::test_context(), &mut parts, Some(&credential), presigned.then_some(Duration::from_secs(60)), @@ -1283,7 +1302,7 @@ mod tests { let original = parts.clone(); let error = signer .sign_request( - &Context::new(), + &crate::test_context(), &mut parts, Some(&credential), presigned.then_some(Duration::from_secs(60)), @@ -1340,7 +1359,12 @@ mod tests { .into_parts() .0; signer - .sign_request(&Context::new(), &mut header_parts, Some(&credential), None) + .sign_request( + &crate::test_context(), + &mut header_parts, + Some(&credential), + None, + ) .await?; assert_eq!(header_parts.uri.to_string(), original_uri); assert_eq!(header_parts.headers["x-custom"], " value "); @@ -1348,7 +1372,7 @@ mod tests { let mut query_parts = Request::get(&original_uri).body(())?.into_parts().0; signer .sign_request( - &Context::new(), + &crate::test_context(), &mut query_parts, Some(&credential), Some(Duration::from_secs(60)), @@ -1448,7 +1472,7 @@ mod tests { let req = req_fn(); let (mut parts, body) = req.into_parts(); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()); let loader = StaticCredentialProvider::new("access_key_id", "secret_access_key"); @@ -1526,7 +1550,7 @@ mod tests { let req = req_fn(); let (mut parts, body) = req.into_parts(); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()); let loader = StaticCredentialProvider::new("access_key_id", "secret_access_key"); @@ -1606,7 +1630,7 @@ mod tests { let req = req_fn(); let (mut parts, body) = req.into_parts(); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()); let loader = StaticCredentialProvider::new("access_key_id", "secret_access_key") @@ -1687,7 +1711,7 @@ mod tests { let req = req_fn(); let (mut parts, body) = req.into_parts(); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()); let loader = StaticCredentialProvider::new("access_key_id", "secret_access_key") diff --git a/services/aws-v4/tests/common/mod.rs b/services/aws-v4/tests/common/mod.rs new file mode 100644 index 00000000..864b1164 --- /dev/null +++ b/services/aws-v4/tests/common/mod.rs @@ -0,0 +1,22 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use reqsign_core::Context; + +pub fn test_context() -> Context { + Context::new().with_crypto(reqsign_crypto_rustcrypto::RustCryptoProvider::new()) +} diff --git a/services/aws-v4/tests/credential_providers/default.rs b/services/aws-v4/tests/credential_providers/default.rs index 83e23cd4..c50929eb 100644 --- a/services/aws-v4/tests/credential_providers/default.rs +++ b/services/aws-v4/tests/credential_providers/default.rs @@ -42,7 +42,7 @@ async fn test_default_provider_role_chain_is_consumed_by_signer() { use bytes::Bytes; use http::{Request, Response, StatusCode, header}; use reqsign_aws_v4::RequestSigner; - use reqsign_core::{Context, FileRead, HttpSend, Signer, StaticEnv}; + use reqsign_core::{FileRead, HttpSend, Signer, StaticEnv}; use std::collections::HashMap; use std::sync::Mutex; @@ -102,7 +102,7 @@ async fn test_default_provider_role_chain_is_consumed_by_signer() { let http = Http { request: Mutex::new(None), }; - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(files) .with_http_send(http) .with_env(StaticEnv { diff --git a/services/aws-v4/tests/credential_providers/mod.rs b/services/aws-v4/tests/credential_providers/mod.rs index a1358ea8..0988f35d 100644 --- a/services/aws-v4/tests/credential_providers/mod.rs +++ b/services/aws-v4/tests/credential_providers/mod.rs @@ -45,7 +45,7 @@ pub fn create_test_context() -> Context { let _ = env_logger::builder().is_test(true).try_init(); let _ = dotenvy::dotenv(); - let mut ctx = Context::new() + let mut ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -65,7 +65,7 @@ pub fn create_test_context_with_env(envs: HashMap) -> Context { // Get home directory from HOME environment variable if set let home_dir = std::env::var("HOME").ok().map(std::path::PathBuf::from); - let mut ctx = Context::new() + let mut ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); diff --git a/services/aws-v4/tests/main.rs b/services/aws-v4/tests/main.rs index 6d99c322..82413a47 100644 --- a/services/aws-v4/tests/main.rs +++ b/services/aws-v4/tests/main.rs @@ -15,5 +15,7 @@ // specific language governing permissions and limitations // under the License. +mod common; + mod credential_providers; mod signing; diff --git a/services/aws-v4/tests/signing/mod.rs b/services/aws-v4/tests/signing/mod.rs index 6980f66f..db423e01 100644 --- a/services/aws-v4/tests/signing/mod.rs +++ b/services/aws-v4/tests/signing/mod.rs @@ -59,7 +59,7 @@ pub fn init_signing_test() -> Option<(Context, RequestSigner, String)> { let service = env::var("REQSIGN_AWS_V4_SERVICE").unwrap_or_else(|_| "s3".to_string()); let url = env::var("REQSIGN_AWS_V4_URL").expect("REQSIGN_AWS_V4_URL must be set"); - let context = Context::new() + let context = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()); let signer = RequestSigner::new(&service, ®ion); diff --git a/services/aws-v4a/Cargo.toml b/services/aws-v4a/Cargo.toml index fa138e1d..81462414 100644 --- a/services/aws-v4a/Cargo.toml +++ b/services/aws-v4a/Cargo.toml @@ -30,7 +30,6 @@ rust-version.workspace = true hex = { workspace = true } http = { workspace = true } log = { workspace = true } -p256 = { workspace = true } reqsign-aws-core = { workspace = true } reqsign-core = { workspace = true } zeroize = { workspace = true } @@ -40,5 +39,7 @@ anyhow = { workspace = true } aws-credential-types = "1.1.8" aws-sigv4 = { version = "1.2.0", features = ["sigv4a"] } form_urlencoded = { workspace = true } +p256 = { workspace = true } pretty_assertions = { workspace = true } +reqsign-crypto-rustcrypto = { workspace = true } tokio = { workspace = true, features = ["full"] } diff --git a/services/aws-v4a/README.md b/services/aws-v4a/README.md index 9751c1b2..d5036d99 100644 --- a/services/aws-v4a/README.md +++ b/services/aws-v4a/README.md @@ -7,6 +7,12 @@ SigV4a uses ECDSA P-256 signatures and a signing region set, allowing one signed request to be accepted in multiple AWS regions. See the [AWS SigV4a signing documentation](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-create-signed-request.html). +> Signing needs a `CryptoProvider` resolved through the `Context`: bind one with +> `Context::with_crypto`, install a process-wide default, or use a facade +> `default_context()` (which binds RustCrypto when the global slot is empty). A +> bare `Context::new()` starts unbound. See +> [CryptoProvider](https://github.com/apache/reqsign/blob/main/docs/crypto-provider.md). + ```rust use reqsign_aws_v4a::{RequestSigner, SigningRegionSet}; diff --git a/services/aws-v4a/src/lib.rs b/services/aws-v4a/src/lib.rs index dba101ce..e23e52f7 100644 --- a/services/aws-v4a/src/lib.rs +++ b/services/aws-v4a/src/lib.rs @@ -34,3 +34,8 @@ pub use reqsign_aws_core::{IMDSv2RegionProvider, Profile, SharedConfig}; #[cfg(not(target_arch = "wasm32"))] pub use reqsign_aws_core::{ProcessCredentialProvider, SSOCredentialProvider}; pub use sign_request::RequestSigner; + +#[cfg(test)] +pub(crate) fn test_context() -> reqsign_core::Context { + reqsign_core::Context::new().with_crypto(reqsign_crypto_rustcrypto::RustCryptoProvider::new()) +} diff --git a/services/aws-v4a/src/sign_request.rs b/services/aws-v4a/src/sign_request.rs index 5170a708..da4f0219 100644 --- a/services/aws-v4a/src/sign_request.rs +++ b/services/aws-v4a/src/sign_request.rs @@ -21,13 +21,12 @@ use std::time::Duration; use http::request::Parts; use http::{HeaderValue, header}; use log::debug; -use p256::ecdsa::signature::Signer as _; -use p256::ecdsa::{DerSignature, SigningKey}; use reqsign_aws_core::Credential; use reqsign_aws_core::signing::{ append_query_fragment, append_query_pairs, canonical_request_string_with_encoding, canonicalize_headers_with_standard_session_token, canonicalize_query, }; +use reqsign_core::crypto; use reqsign_core::hash::{hex_sha256, hmac_sha256}; use reqsign_core::time::Timestamp; use reqsign_core::{Context, Error, Result, SignRequest, SigningCredential, SigningRequest}; @@ -37,6 +36,12 @@ use crate::{PercentEncodingMode, SigningRegionSet}; const ALGORITHM: &str = "AWS4-ECDSA-P256-SHA256"; const X_AMZ_REGION_SET: &str = "x-amz-region-set"; +// P-256 group order minus two: the largest KDF output k0 for which k0 + 1 +// remains a valid private scalar (k0 + 1 <= n - 1). +const P256_ORDER_MINUS_2: [u8; 32] = [ + 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17, 0x9e, 0x84, 0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x4f, +]; const CREDENTIAL_OPERATION_HEADROOM: Duration = Duration::from_secs(10); /// Request signer implementing @@ -118,7 +123,7 @@ impl SignRequest for RequestSigner { async fn sign_request( &self, - _: &Context, + ctx: &Context, req: &mut Parts, credential: Option<&Self::Credential>, expires_in: Option, @@ -126,6 +131,7 @@ impl SignRequest for RequestSigner { let Some(credential) = credential else { return Ok(()); }; + let crypto = ctx.crypto_provider()?; let now = self.get_time(); let required_until = self.required_valid_until_at(now, expires_in); @@ -166,7 +172,7 @@ impl SignRequest for RequestSigner { &canonical_query, self.percent_encoding_mode, )?; - let encoded_request = hex_sha256(canonical_request.as_bytes()); + let encoded_request = hex_sha256(crypto, canonical_request.as_bytes())?; let scope = format!("{}/{}/aws4_request", now.format_date(), self.service); debug!("calculated scope: {scope}"); @@ -174,9 +180,12 @@ impl SignRequest for RequestSigner { let string_to_sign = string_to_sign(now, &scope, &encoded_request)?; debug!("calculated string to sign: {string_to_sign}"); - let signing_key = - generate_signing_key(&credential.access_key_id, &credential.secret_access_key)?; - let signature = calculate_signature(&signing_key, string_to_sign.as_bytes()); + let signing_key = generate_signing_key( + crypto, + &credential.access_key_id, + &credential.secret_access_key, + )?; + let signature = calculate_signature(crypto, &signing_key, string_to_sign.as_bytes())?; let final_uri = if expires_in.is_some() { let unsigned_uri = append_query_pairs(&original_uri, &authentication_query)?; @@ -265,12 +274,20 @@ fn string_to_sign(now: Timestamp, scope: &str, encoded_request: &str) -> Result< Ok(output) } -fn calculate_signature(signing_key: &SigningKey, string_to_sign: &[u8]) -> String { - let signature: DerSignature = signing_key.sign(string_to_sign); - hex::encode(signature.as_bytes()) +fn calculate_signature( + provider: &dyn crypto::CryptoProvider, + signing_key: &[u8; 32], + string_to_sign: &[u8], +) -> Result { + let signature = provider.ecdsa_p256_sha256_sign(signing_key, string_to_sign)?; + Ok(hex::encode(signature)) } -fn generate_signing_key(access_key_id: &str, secret_access_key: &str) -> Result { +fn generate_signing_key( + provider: &dyn crypto::CryptoProvider, + access_key_id: &str, + secret_access_key: &str, +) -> Result> { let mut input_key = Zeroizing::new(Vec::with_capacity(secret_access_key.len() + 5)); input_key.extend_from_slice(b"AWS4A"); input_key.extend_from_slice(secret_access_key.as_bytes()); @@ -284,16 +301,19 @@ fn generate_signing_key(access_key_id: &str, secret_access_key: &str) -> Result< input.push(counter); input.extend_from_slice(&256_u32.to_be_bytes()); - let digest = Zeroizing::new(hmac_sha256(input_key.as_slice(), input.as_slice())); + let digest = Zeroizing::new(hmac_sha256( + provider, + input_key.as_slice(), + input.as_slice(), + )?); + if digest.as_slice() > P256_ORDER_MINUS_2.as_slice() { + continue; + } + let mut scalar = Zeroizing::new([0_u8; 32]); scalar.copy_from_slice(digest.as_slice()); increment_big_endian(scalar.as_mut()); - - // P-256 accepts k0 + 1 exactly when the KDF output k0 is in the - // specification's [0, n - 2] range. - if let Ok(signing_key) = SigningKey::from_slice(scalar.as_ref()) { - return Ok(signing_key); - } + return Ok(scalar); } Err(Error::unexpected( @@ -324,6 +344,7 @@ mod tests { use aws_sigv4::sign::v4a; use http::Request; use p256::ecdsa::DerSignature; + use p256::ecdsa::SigningKey as P256SigningKey; use p256::ecdsa::signature::Verifier; use pretty_assertions::assert_eq; use reqsign_core::ErrorKind; @@ -406,7 +427,10 @@ mod tests { #[test] fn signing_key_matches_aws_public_key_vector() -> AnyResult<()> { - let signing_key = generate_signing_key(ACCESS_KEY_ID, SECRET_ACCESS_KEY)?; + let provider = reqsign_crypto_rustcrypto::RustCryptoProvider::new(); + let scalar = generate_signing_key(&provider, ACCESS_KEY_ID, SECRET_ACCESS_KEY)?; + let signing_key = P256SigningKey::from_slice(scalar.as_slice()) + .expect("derived scalar must be a valid P-256 key"); let public_key = signing_key.verifying_key().to_sec1_point(false); assert_eq!( @@ -418,7 +442,7 @@ mod tests { "865ed22a7eadc9c5cb9d2cbaca1b3699139fedc5043dc6661864218330c8e518" ); - let signature = calculate_signature(&signing_key, HEADER_STRING_TO_SIGN.as_bytes()); + let signature = calculate_signature(&provider, &scalar, HEADER_STRING_TO_SIGN.as_bytes())?; let signature_bytes = hex::decode(signature)?; let signature = DerSignature::try_from(signature_bytes.as_slice()) .expect("generated signature must use DER encoding"); @@ -436,7 +460,12 @@ mod tests { .into_parts() .0; signer() - .sign_request(&Context::new(), &mut parts, Some(&credential()), None) + .sign_request( + &crate::test_context(), + &mut parts, + Some(&credential()), + None, + ) .await?; assert_eq!(parts.headers[X_AMZ_REGION_SET], "us-east-1"); @@ -461,7 +490,7 @@ mod tests { .0; signer() .sign_request( - &Context::new(), + &crate::test_context(), &mut parts, Some(&credential()), Some(Duration::from_secs(3600)), @@ -503,7 +532,11 @@ mod tests { }; format!( "AWS4-ECDSA-P256-SHA256\n20150830T123600Z\n20150830/service/aws4_request\n{}", - hex_sha256(canonical_request.as_bytes()), + hex_sha256( + &reqsign_crypto_rustcrypto::RustCryptoProvider::new(), + canonical_request.as_bytes(), + ) + .expect("SHA-256 must succeed"), ) } @@ -525,9 +558,13 @@ mod tests { let signature_bytes = hex::decode(signature)?; let signature = DerSignature::try_from(signature_bytes.as_slice()) .expect("signature must use DER encoding"); - let key = generate_signing_key(ACCESS_KEY_ID, SECRET_ACCESS_KEY)?; + let provider = reqsign_crypto_rustcrypto::RustCryptoProvider::new(); + let scalar = generate_signing_key(&provider, ACCESS_KEY_ID, SECRET_ACCESS_KEY)?; + let signing_key = P256SigningKey::from_slice(scalar.as_slice()) + .expect("derived scalar must be a valid P-256 key"); assert!( - key.verifying_key() + signing_key + .verifying_key() .verify(string_to_sign.as_bytes(), &signature) .is_ok(), "signature must verify the expected canonical request for {}", @@ -621,7 +658,12 @@ mod tests { let (mut parts, body) = Request::get(&uri).body(())?.into_parts(); let request_signer = signer().with_percent_encoding_mode(mode); request_signer - .sign_request(&Context::new(), &mut parts, Some(&credential()), expires_in) + .sign_request( + &crate::test_context(), + &mut parts, + Some(&credential()), + expires_in, + ) .await?; let actual = Request::from_parts(parts, body); assert_eq!(comparable_headers(&actual), comparable_headers(&expected)); @@ -669,7 +711,12 @@ mod tests { let (mut parts, body) = Request::get(&uri).body(())?.into_parts(); let request_signer = signer().with_percent_encoding_mode(mode); request_signer - .sign_request(&Context::new(), &mut parts, Some(&credential()), expires_in) + .sign_request( + &crate::test_context(), + &mut parts, + Some(&credential()), + expires_in, + ) .await?; let actual = Request::from_parts(parts, body); assert_eq!(actual.uri().path(), path); @@ -700,21 +747,36 @@ mod tests { for expires_in in [None, Some(Duration::from_secs(3600))] { let (mut parts, body) = Request::get(&uri).body(())?.into_parts(); signer_for(service) - .sign_request(&Context::new(), &mut parts, Some(&credential()), expires_in) + .sign_request( + &crate::test_context(), + &mut parts, + Some(&credential()), + expires_in, + ) .await?; let default = Request::from_parts(parts, body); let (mut parts, body) = Request::get(&uri).body(())?.into_parts(); signer_for(service) .with_percent_encoding_mode(PercentEncodingMode::Single) - .sign_request(&Context::new(), &mut parts, Some(&credential()), expires_in) + .sign_request( + &crate::test_context(), + &mut parts, + Some(&credential()), + expires_in, + ) .await?; let single = Request::from_parts(parts, body); let (mut parts, body) = Request::get(&uri).body(())?.into_parts(); signer_for(service) .with_percent_encoding_mode(PercentEncodingMode::Double) - .sign_request(&Context::new(), &mut parts, Some(&credential()), expires_in) + .sign_request( + &crate::test_context(), + &mut parts, + Some(&credential()), + expires_in, + ) .await?; let double = Request::from_parts(parts, body); @@ -767,7 +829,12 @@ mod tests { let mut parts = Request::get(&original_uri).body(())?.into_parts().0; signer() .with_percent_encoding_mode(mode) - .sign_request(&Context::new(), &mut parts, Some(&credential()), expires_in) + .sign_request( + &crate::test_context(), + &mut parts, + Some(&credential()), + expires_in, + ) .await?; assert_eq!(parts.uri.path(), "/object%2Fname"); if expires_in.is_some() { @@ -804,7 +871,7 @@ mod tests { }; let error = signer() - .sign_request(&Context::new(), &mut parts, Some(&expired), None) + .sign_request(&crate::test_context(), &mut parts, Some(&expired), None) .await .expect_err("expired credential must fail"); diff --git a/services/azure-storage/Cargo.toml b/services/azure-storage/Cargo.toml index 34ebb360..171fc0bc 100644 --- a/services/azure-storage/Cargo.toml +++ b/services/azure-storage/Cargo.toml @@ -38,18 +38,17 @@ percent-encoding = { workspace = true } reqsign-core = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } -sha1 = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] pem = { workspace = true } -reqsign-core = { workspace = true, features = ["jwt"] } -rsa = { workspace = true } [dev-dependencies] +reqsign-crypto-rustcrypto = { workspace = true } asyncband = { workspace = true, features = ["semaphore"] } env_logger = { workspace = true } reqsign-command-execute-tokio = { workspace = true } reqsign-file-read-tokio = { workspace = true } reqsign-http-send-reqwest = { workspace = true } reqwest = { workspace = true, features = ["default-tls"] } +rsa = { workspace = true } tokio = { workspace = true, features = ["full"] } diff --git a/services/azure-storage/README.md b/services/azure-storage/README.md index 1d7ed6f2..346c5b95 100644 --- a/services/azure-storage/README.md +++ b/services/azure-storage/README.md @@ -5,9 +5,16 @@ Azure Storage signing support for reqsign. This crate signs requests for Blob, File, Queue, and Table Storage. It supports shared key, SAS token, and Azure AD bearer token credentials. +> Signing needs a `CryptoProvider` resolved through the `Context`: bind one with +> `Context::with_crypto`, install a process-wide default, or use a facade +> `default_context()` (which binds RustCrypto when the global slot is empty). A +> bare `Context::new()` starts unbound. See +> [CryptoProvider](https://github.com/apache/reqsign/blob/main/docs/crypto-provider.md). + ## Quick Start ```rust +use reqsign_crypto_rustcrypto::RustCryptoProvider; use anyhow::Result; use reqsign_azure_storage::{DefaultCredentialProvider, RequestSigner}; use reqsign_core::{Context, Signer}; @@ -16,7 +23,7 @@ use reqsign_http_send_reqwest::ReqwestHttpSend; #[tokio::main] async fn main() -> Result<()> { - let ctx = Context::new() + let ctx = Context::new().with_crypto(RustCryptoProvider::new()) .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()); @@ -111,6 +118,7 @@ Use a Shared Key source to mint an independently usable, expiration-aware SAS for one typed container or blob grant: ```rust +use reqsign_crypto_rustcrypto::RustCryptoProvider; use std::time::Duration; use reqsign_azure_storage::{ @@ -126,7 +134,7 @@ let grant = ServiceSasGrant::for_blob( ServiceSasBlobPermissions::READ, ); let credential = Granter::new( - Context::new(), + Context::new().with_crypto(RustCryptoProvider::new()), StaticCredentialProvider::new_shared_key( "mystorageaccount", "", diff --git a/services/azure-storage/examples/blob_storage.rs b/services/azure-storage/examples/blob_storage.rs index 51cd1975..5bce3406 100644 --- a/services/azure-storage/examples/blob_storage.rs +++ b/services/azure-storage/examples/blob_storage.rs @@ -18,6 +18,7 @@ use anyhow::Result; use reqsign_azure_storage::{DefaultCredentialProvider, EnvCredentialProvider, RequestSigner}; use reqsign_core::{Context, OsEnv, Signer}; +use reqsign_crypto_rustcrypto::RustCryptoProvider; use reqsign_file_read_tokio::TokioFileRead; use reqsign_http_send_reqwest::ReqwestHttpSend; use reqwest::Client; @@ -32,6 +33,7 @@ async fn main() -> Result<()> { // Create context let ctx = Context::new() + .with_crypto(RustCryptoProvider::new()) .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::new(client.clone())) .with_env(OsEnv); diff --git a/services/azure-storage/src/lib.rs b/services/azure-storage/src/lib.rs index 5a4e3b76..ecc96be3 100644 --- a/services/azure-storage/src/lib.rs +++ b/services/azure-storage/src/lib.rs @@ -192,3 +192,8 @@ pub use sign_request::RequestSigner; mod provide_credential; pub use provide_credential::*; + +#[cfg(test)] +pub(crate) fn test_context() -> reqsign_core::Context { + reqsign_core::Context::new().with_crypto(reqsign_crypto_rustcrypto::RustCryptoProvider::new()) +} diff --git a/services/azure-storage/src/provide_credential/azure_pipelines.rs b/services/azure-storage/src/provide_credential/azure_pipelines.rs index 21545c70..ee707216 100644 --- a/services/azure-storage/src/provide_credential/azure_pipelines.rs +++ b/services/azure-storage/src/provide_credential/azure_pipelines.rs @@ -253,7 +253,7 @@ mod tests { async fn test_provide_credential_no_environment() { // When not in Azure Pipelines environment, should return None let provider = AzurePipelinesCredentialProvider::new(); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(reqsign_file_read_tokio::TokioFileRead) .with_http_send(reqsign_http_send_reqwest::ReqwestHttpSend::default()); diff --git a/services/azure-storage/src/provide_credential/client_certificate.rs b/services/azure-storage/src/provide_credential/client_certificate.rs index 5cd98cc9..9f0932ff 100644 --- a/services/azure-storage/src/provide_credential/client_certificate.rs +++ b/services/azure-storage/src/provide_credential/client_certificate.rs @@ -24,12 +24,10 @@ use crate::provide_credential::entra::{ }; use base64::Engine; use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use reqsign_core::crypto::CryptoProvider; use reqsign_core::time::Timestamp; -use reqsign_core::{Context, ProvideCredential}; -use rsa::RsaPrivateKey; -use rsa::pkcs8::DecodePrivateKey; +use reqsign_core::{Context, ProvideCredential, hash}; use serde::Serialize; -use sha1::{Digest, Sha1}; /// Generate a unique JWT ID using timestamp and a pseudo-random component fn generate_jti(now: u64) -> String { @@ -99,7 +97,7 @@ impl ClientCertificateCredentialProvider { &self, ctx: &Context, path: &str, - ) -> Result<(Vec, RsaPrivateKey), reqsign_core::Error> { + ) -> Result<(Vec, Vec), 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}")) })?; @@ -140,30 +138,54 @@ 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_pem.into_bytes())) + } - Ok((cert_der, private_key)) + /// Format a JWS compact JWT using RS256 and the selected provider. + fn encode_rs256_jws( + provider: &dyn CryptoProvider, + header: &H, + claims: &C, + private_key_pem: &[u8], + ) -> Result + where + H: Serialize, + C: Serialize, + { + let encoded_header = URL_SAFE_NO_PAD.encode(serde_json::to_vec(header).map_err(|e| { + reqsign_core::Error::unexpected("failed to serialize JWT JSON").with_source(e) + })?); + let encoded_claims = URL_SAFE_NO_PAD.encode(serde_json::to_vec(claims).map_err(|e| { + reqsign_core::Error::unexpected("failed to serialize JWT JSON").with_source(e) + })?); + let signing_input = format!("{encoded_header}.{encoded_claims}"); + let signature = + provider.rsa_pkcs1v15_sha256_sign(private_key_pem, signing_input.as_bytes())?; + + Ok(format!( + "{signing_input}.{}", + URL_SAFE_NO_PAD.encode(signature) + )) } /// Calculate certificate thumbprint (x5t) /// Azure AD expects SHA1 thumbprint for x5t field - fn calculate_thumbprint(&self, cert_der: &[u8]) -> String { - let hash = Sha1::digest(cert_der); - URL_SAFE_NO_PAD.encode(hash) + fn calculate_thumbprint( + &self, + provider: &dyn CryptoProvider, + cert_der: &[u8], + ) -> Result { + Ok(URL_SAFE_NO_PAD.encode(hash::sha1(provider, cert_der)?)) } /// Create JWT client assertion fn create_client_assertion( &self, + provider: &dyn CryptoProvider, tenant_id: &str, client_id: &str, cert_der: &[u8], - private_key: &RsaPrivateKey, + private_key_pem: &[u8], ) -> Result { let now = SystemTime::now() .duration_since(UNIX_EPOCH) @@ -184,10 +206,10 @@ impl ClientCertificateCredentialProvider { let header = ClientAssertionHeader { alg: "RS256", typ: "JWT", - x5t: self.calculate_thumbprint(cert_der), + x5t: self.calculate_thumbprint(provider, cert_der)?, }; - reqsign_core::jwt::encode_rs256(&header, &claims, private_key) + Self::encode_rs256_jws(provider, &header, &claims, private_key_pem) } /// Exchange client assertion for access token @@ -288,12 +310,19 @@ impl ProvideCredential for ClientCertificateCredentialProvider { _ => return Ok(None), }; + let provider = ctx.crypto_provider()?; + // 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)?; + let client_assertion = self.create_client_assertion( + provider, + &tenant_id, + &client_id, + &cert_der, + &private_key_pem, + )?; // Exchange for access token let token_response = self @@ -319,7 +348,10 @@ mod tests { // Test certificate DER (simplified example) let cert_der = b"test certificate"; let provider = ClientCertificateCredentialProvider::new(); - let thumbprint = provider.calculate_thumbprint(cert_der); + let crypto = reqsign_crypto_rustcrypto::RustCryptoProvider::new(); + let thumbprint = provider + .calculate_thumbprint(&crypto, cert_der) + .expect("thumbprint calculation must succeed"); // Should produce a valid base64url encoded hash assert!(!thumbprint.is_empty()); @@ -328,6 +360,115 @@ mod tests { assert!(!thumbprint.contains('=')); } + #[test] + fn client_assertion_is_three_unpadded_verifiable_segments_for_both_pem_formats() { + use rsa::RsaPrivateKey; + use rsa::pkcs1::EncodeRsaPrivateKey; + use rsa::pkcs1v15::{Signature, VerifyingKey}; + use rsa::pkcs8::{EncodePrivateKey, LineEnding}; + use rsa::rand_core::OsRng; + use rsa::sha2::Sha256; + use rsa::signature::Verifier; + + let key = RsaPrivateKey::new(&mut OsRng, 1024).expect("test RSA key generation must work"); + let provider = reqsign_crypto_rustcrypto::RustCryptoProvider::new(); + let certificate_provider = ClientCertificateCredentialProvider::new(); + let cert_der = b"test certificate"; + let thumbprint = certificate_provider + .calculate_thumbprint(&provider, cert_der) + .expect("thumbprint calculation must succeed"); + let header = ClientAssertionHeader { + alg: "RS256", + typ: "JWT", + x5t: thumbprint.clone(), + }; + let claims = ClientAssertionClaims { + aud: "https://example.com/token".to_string(), + exp: 1, + iss: "client".to_string(), + jti: "jti".to_string(), + nbf: 0, + sub: "client".to_string(), + }; + + for pem in [ + key.to_pkcs8_pem(LineEnding::LF) + .expect("test key must encode as PKCS#8"), + key.to_pkcs1_pem(LineEnding::LF) + .expect("test key must encode as PKCS#1"), + ] { + let jwt = ClientCertificateCredentialProvider::encode_rs256_jws( + &provider, + &header, + &claims, + pem.as_bytes(), + ) + .expect("JWT encoding must succeed"); + let parts = jwt.split('.').collect::>(); + assert_eq!(parts.len(), 3); + assert!(parts.iter().all(|part| !part.contains('='))); + assert_eq!( + serde_json::from_slice::( + &URL_SAFE_NO_PAD + .decode(parts[0]) + .expect("header must decode") + ) + .expect("header must be JSON"), + serde_json::json!({"alg": "RS256", "typ": "JWT", "x5t": thumbprint}) + ); + assert_eq!( + serde_json::from_slice::( + &URL_SAFE_NO_PAD + .decode(parts[1]) + .expect("claims must decode") + ) + .expect("claims must be JSON"), + serde_json::json!({ + "aud": "https://example.com/token", + "exp": 1, + "iss": "client", + "jti": "jti", + "nbf": 0, + "sub": "client" + }) + ); + + let signature = URL_SAFE_NO_PAD + .decode(parts[2]) + .expect("signature must decode"); + let signature = + Signature::try_from(signature.as_slice()).expect("signature must parse"); + let verifying_key = VerifyingKey::::new(key.to_public_key()); + verifying_key + .verify(format!("{}.{}", parts[0], parts[1]).as_bytes(), &signature) + .expect("signature must verify"); + } + } + + #[test] + fn malformed_client_certificate_private_key_is_credential_invalid() { + let crypto = reqsign_crypto_rustcrypto::RustCryptoProvider::new(); + let err = ClientCertificateCredentialProvider::encode_rs256_jws( + &crypto, + &ClientAssertionHeader { + alg: "RS256", + typ: "JWT", + x5t: "thumbprint".to_string(), + }, + &ClientAssertionClaims { + aud: "aud".to_string(), + exp: 1, + iss: "iss".to_string(), + jti: "jti".to_string(), + nbf: 0, + sub: "sub".to_string(), + }, + b"not a private key", + ) + .expect_err("malformed key must fail"); + assert_eq!(err.kind(), reqsign_core::ErrorKind::CredentialInvalid); + } + #[test] fn test_provider_configuration() { let provider = ClientCertificateCredentialProvider::new() diff --git a/services/azure-storage/src/provide_credential/default.rs b/services/azure-storage/src/provide_credential/default.rs index 0337e84c..cd0170f2 100644 --- a/services/azure-storage/src/provide_credential/default.rs +++ b/services/azure-storage/src/provide_credential/default.rs @@ -286,7 +286,7 @@ mod tests { ]), }; - let ctx = reqsign_core::Context::new().with_env(env); + let ctx = crate::test_context().with_env(env); let loader = DefaultCredentialProvider::new(); @@ -313,7 +313,7 @@ mod tests { )]), }; - let ctx = reqsign_core::Context::new().with_env(env); + let ctx = crate::test_context().with_env(env); let loader = DefaultCredentialProvider::new(); diff --git a/services/azure-storage/src/provide_credential/env.rs b/services/azure-storage/src/provide_credential/env.rs index 835ce8de..bc6aec4b 100644 --- a/services/azure-storage/src/provide_credential/env.rs +++ b/services/azure-storage/src/provide_credential/env.rs @@ -72,7 +72,7 @@ impl ProvideCredential for EnvCredentialProvider { #[cfg(test)] mod tests { use super::*; - use reqsign_core::{Context, StaticEnv}; + use reqsign_core::StaticEnv; use reqsign_file_read_tokio::TokioFileRead; use reqsign_http_send_reqwest::ReqwestHttpSend; use std::collections::HashMap; @@ -84,7 +84,7 @@ mod tests { ("AZBLOB_ACCOUNT_KEY".to_string(), "mykey".to_string()), ]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(StaticEnv { @@ -114,7 +114,7 @@ mod tests { "mysastoken".to_string(), )]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(StaticEnv { @@ -135,7 +135,7 @@ mod tests { #[tokio::test] async fn test_env_credential_provider_none() { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()); diff --git a/services/azure-storage/src/provide_credential/static_provider.rs b/services/azure-storage/src/provide_credential/static_provider.rs index 392c6a08..054c3f03 100644 --- a/services/azure-storage/src/provide_credential/static_provider.rs +++ b/services/azure-storage/src/provide_credential/static_provider.rs @@ -68,14 +68,14 @@ impl ProvideCredential for StaticCredentialProvider { #[cfg(test)] mod tests { use super::*; - use reqsign_core::{Context, OsEnv}; + use reqsign_core::OsEnv; use reqsign_file_read_tokio::TokioFileRead; use reqsign_http_send_reqwest::ReqwestHttpSend; #[tokio::test] async fn test_static_credential_provider_shared_key() { let provider = StaticCredentialProvider::new_shared_key("myaccount", "mykey"); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -96,7 +96,7 @@ mod tests { #[tokio::test] async fn test_static_credential_provider_sas_token() { let provider = StaticCredentialProvider::new_sas_token("mysastoken"); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -115,7 +115,7 @@ mod tests { let expires_at = Timestamp::now() + std::time::Duration::from_secs(60); let provider = StaticCredentialProvider::new_sas_token_expires_at("mysastoken", expires_at); let credential = provider - .provide_credential(&Context::new()) + .provide_credential(&crate::test_context()) .await .expect("provider must succeed"); @@ -134,7 +134,7 @@ mod tests { #[tokio::test] async fn test_static_credential_provider_bearer_token() { let provider = StaticCredentialProvider::new_bearer_token("mybearertoken"); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); diff --git a/services/azure-storage/src/provide_credential/workload_identity.rs b/services/azure-storage/src/provide_credential/workload_identity.rs index 3b60ae6d..27d59739 100644 --- a/services/azure-storage/src/provide_credential/workload_identity.rs +++ b/services/azure-storage/src/provide_credential/workload_identity.rs @@ -313,7 +313,7 @@ mod tests { ); let err = provider - .provide_credential(&Context::new()) + .provide_credential(&crate::test_context()) .await .expect_err("expired token must fail"); assert_eq!(err.kind(), ErrorKind::CredentialInvalid); diff --git a/services/azure-storage/src/service_sas.rs b/services/azure-storage/src/service_sas.rs index 7ca97d07..8c2ac04e 100644 --- a/services/azure-storage/src/service_sas.rs +++ b/services/azure-storage/src/service_sas.rs @@ -19,6 +19,7 @@ use crate::Credential; use crate::constants::AZURE_QUERY_ENCODE_SET; use crate::user_delegation_sas::SasProtocol; use percent_encoding::percent_encode; +use reqsign_core::crypto::CryptoProvider; use reqsign_core::hash; use reqsign_core::time::Timestamp; use reqsign_core::{Context, Error, GrantCredential, Result, SigningCredential}; @@ -701,11 +702,19 @@ impl ServiceSharedAccessSignature { .join("\n") } - fn signature_with_decoded_key(&self, decoded_key: &[u8]) -> String { - hash::base64_hmac_sha256(decoded_key, self.string_to_sign().as_bytes()) + fn signature_with_decoded_key( + &self, + provider: &dyn CryptoProvider, + decoded_key: &[u8], + ) -> reqsign_core::Result { + hash::base64_hmac_sha256(provider, decoded_key, self.string_to_sign().as_bytes()) } - fn token_with_decoded_key(&self, decoded_key: &[u8]) -> Vec<(String, String)> { + fn token_with_decoded_key( + &self, + provider: &dyn CryptoProvider, + decoded_key: &[u8], + ) -> reqsign_core::Result> { let mut elements: Vec<(String, String)> = vec![ ("sv".to_string(), self.version.to_string()), ("se".to_string(), self.expiry.format_rfc3339_zulu()), @@ -728,16 +737,19 @@ impl ServiceSharedAccessSignature { elements.push(( "sig".to_string(), - self.signature_with_decoded_key(decoded_key), + self.signature_with_decoded_key(provider, decoded_key)?, )); - elements + Ok(elements) } /// Generate SAS query parameters. - pub fn token(&self) -> Result> { + /// + /// `provider` must be the provider selected for this operation. Callers with + /// a [`Context`] resolve it with `context.crypto_provider()?`. + pub fn token(&self, provider: &dyn CryptoProvider) -> Result> { let decoded_key = hash::base64_decode(&self.key)?; - Ok(self.token_with_decoded_key(&decoded_key)) + self.token_with_decoded_key(provider, &decoded_key) } } @@ -887,10 +899,11 @@ impl GrantCredential for ServiceSasGranter { async fn grant_credential( &self, - _ctx: &Context, + ctx: &Context, credential: &Self::Credential, expires_in: Option, ) -> Result { + let provider = ctx.crypto_provider()?; let Credential::SharedKey { account_name, account_key, @@ -945,7 +958,9 @@ impl GrantCredential for ServiceSasGranter { signer = signer.with_ip(ip); } - let pairs = signer.token_with_decoded_key(&decoded_key); + let pairs = signer + .token_with_decoded_key(provider, &decoded_key) + .expect("service SAS token must build"); let token = encode_query_pairs(&pairs); let after_generation = self.now_after_generation(); if times.expiry <= after_generation { @@ -1030,7 +1045,9 @@ mod tests { expiry, ); - let token_content = sign.token().expect("token generation failed"); + let token_content = sign + .token(&reqsign_crypto_rustcrypto::RustCryptoProvider::new()) + .expect("token generation failed"); let token = token_content .iter() .map(|(k, v)| format!("{k}={v}")) @@ -1197,7 +1214,7 @@ mod tests { let output = operation .grant_credential( - &Context::new(), + &crate::test_context(), &shared_key("account", VALID_ACCOUNT_KEY), Some(Duration::from_secs(60)), ) @@ -1212,7 +1229,7 @@ mod tests { ); let signer = Signer::new( - Context::new(), + crate::test_context(), StaticCredentialProvider::new_sas_token_expires_at(token, expires_at), RequestSigner::new(), ); @@ -1256,7 +1273,11 @@ mod tests { let source = shared_key("account", VALID_ACCOUNT_KEY); let output = operation - .grant_credential(&Context::new(), &source, Some(Duration::from_millis(1_500))) + .grant_credential( + &crate::test_context(), + &source, + Some(Duration::from_millis(1_500)), + ) .await .expect("Service SAS grant must succeed"); let (token, expires_at) = output_parts(&output); @@ -1291,7 +1312,11 @@ mod tests { "rw\n2030-01-01T00:00:01Z\n2030-01-01T00:00:03Z\n/blob/account/container/path/to/blob name.txt\n\n198.51.100.10-198.51.100.20\nhttps,http\n2022-11-02\nb\n\n\n\n\n\n\n" ); assert_eq!( - encode_query_pairs(&direct.token().expect("compatibility signer must succeed")), + encode_query_pairs( + &direct + .token(&reqsign_crypto_rustcrypto::RustCryptoProvider::new()) + .expect("compatibility signer must succeed"), + ), token ); } @@ -1310,7 +1335,7 @@ mod tests { let output = operation .grant_credential( - &Context::new(), + &crate::test_context(), &shared_key("account", VALID_ACCOUNT_KEY), Some(Duration::from_secs(60)), ) @@ -1344,7 +1369,11 @@ mod tests { ]; for source in invalid_sources { let err = operation - .grant_credential(&Context::new(), &source, Some(Duration::from_secs(60))) + .grant_credential( + &crate::test_context(), + &source, + Some(Duration::from_secs(60)), + ) .await .expect_err("invalid source must fail"); assert_eq!(err.kind(), ErrorKind::CredentialInvalid); @@ -1379,7 +1408,7 @@ mod tests { Some(Duration::from_secs(u64::MAX)), ] { let err = operation - .grant_credential(&Context::new(), &source, lifetime) + .grant_credential(&crate::test_context(), &source, lifetime) .await .expect_err("invalid lifetime must fail"); assert_eq!(err.kind(), ErrorKind::RequestInvalid); @@ -1392,7 +1421,11 @@ mod tests { .with_time(now); assert_eq!( start_after_expiry - .grant_credential(&Context::new(), &source, Some(Duration::from_secs(60)),) + .grant_credential( + &crate::test_context(), + &source, + Some(Duration::from_secs(60)), + ) .await .expect_err("start at or after expiry must fail") .kind(), @@ -1406,7 +1439,11 @@ mod tests { .with_time(now); assert_eq!( future_start - .grant_credential(&Context::new(), &source, Some(Duration::from_secs(60)),) + .grant_credential( + &crate::test_context(), + &source, + Some(Duration::from_secs(60)), + ) .await .expect_err("future start must fail the immediate usability contract") .kind(), @@ -1417,7 +1454,11 @@ mod tests { operation.with_time_after_generation(timestamp("2030-01-01T00:05:00Z")); assert_eq!( expired_after_generation - .grant_credential(&Context::new(), &source, Some(Duration::from_secs(300)),) + .grant_credential( + &crate::test_context(), + &source, + Some(Duration::from_secs(300)), + ) .await .expect_err("expired post-generation output must fail") .kind(), @@ -1440,7 +1481,7 @@ mod tests { ) .with_time(now); let output = Granter::new( - Context::new(), + crate::test_context(), StaticCredentialProvider::new_shared_key("account", &key), operation, ) @@ -1451,7 +1492,7 @@ mod tests { let token = token.to_string(); let signer = Signer::new( - Context::new(), + crate::test_context(), StaticCredentialProvider::new_sas_token_expires_at(&token, expires_at), RequestSigner::new(), ); @@ -1485,7 +1526,7 @@ mod tests { .with_service_sas_permissions("r") .with_service_sas_protocol("https") .sign_request( - &Context::new(), + &crate::test_context(), &mut presigned, Some(&source), Some(Duration::from_secs(300)), @@ -1532,7 +1573,11 @@ mod tests { } let err = operation - .grant_credential(&Context::new(), &source, Some(Duration::from_secs(60))) + .grant_credential( + &crate::test_context(), + &source, + Some(Duration::from_secs(60)), + ) .await .expect_err("invalid key must fail without disclosure"); let debug = format!("{err:?}"); diff --git a/services/azure-storage/src/sign_request.rs b/services/azure-storage/src/sign_request.rs index 48387cdf..8b040f75 100644 --- a/services/azure-storage/src/sign_request.rs +++ b/services/azure-storage/src/sign_request.rs @@ -315,12 +315,16 @@ impl SignRequest for RequestSigner { } } + let provider = context.crypto_provider()?; let account = infer_account_name(sctx.authority.as_str())?; let version = cfg.version.as_deref().unwrap_or("2020-12-06"); let cache_key = UserDelegationPresignCacheKey { account: account.clone(), endpoint: format!("{}://{}", sctx.scheme, sctx.authority), - source_authority: reqsign_core::hash::hex_sha256(token.as_bytes()), + source_authority: reqsign_core::hash::hex_sha256( + provider, + token.as_bytes(), + )?, version: version.to_string(), }; @@ -404,8 +408,9 @@ impl SignRequest for RequestSigner { signer = signer.with_version(version); } - let signer_token = signer.token().map_err(|e| { - reqsign_core::Error::unexpected( + let signer_token = signer.token(provider).map_err(|e| { + reqsign_core::Error::new( + e.kind(), "failed to generate user delegation SAS token", ) .with_source(e) @@ -448,6 +453,7 @@ impl SignRequest for RequestSigner { }; let resource = service_sas_resource(&sctx.path)?; + let provider = context.crypto_provider()?; let mut signer = crate::service_sas::ServiceSharedAccessSignature::new( account_name.clone(), @@ -469,20 +475,27 @@ impl SignRequest for RequestSigner { signer = signer.with_version(version); } - let signer_token = signer.token().map_err(|e| { - reqsign_core::Error::unexpected("failed to generate service SAS token") - .with_source(e) + let signer_token = signer.token(provider).map_err(|e| { + reqsign_core::Error::new( + e.kind(), + "failed to generate service SAS token", + ) + .with_source(e) })?; final_uri = Some(append_query_pairs(&original_uri, &signer_token)?); } SigningMethod::Header => { + let provider = context.crypto_provider()?; let string_to_sign = string_to_sign(&mut sctx, account_name, signing_time)?; let decode_content = base64_decode(account_key).map_err(|e| { reqsign_core::Error::unexpected("failed to decode account key") .with_source(e) })?; - let signature = - base64_hmac_sha256(&decode_content, string_to_sign.as_bytes()); + let signature = base64_hmac_sha256( + provider, + &decode_content, + string_to_sign.as_bytes(), + )?; sctx.headers.insert(header::AUTHORIZATION, { let mut value: HeaderValue = @@ -801,7 +814,7 @@ mod tests { use super::*; use bytes::Bytes; use http::Request; - use reqsign_core::{Context, HttpSend, OsEnv}; + use reqsign_core::{HttpSend, OsEnv}; use reqsign_file_read_tokio::TokioFileRead; use reqsign_http_send_reqwest::ReqwestHttpSend; use std::str::FromStr; @@ -864,7 +877,7 @@ mod tests { async fn test_sas_token() { let _ = env_logger::builder().is_test(true).try_init(); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -897,7 +910,7 @@ mod tests { #[tokio::test] async fn test_bearer_token() { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -942,7 +955,7 @@ mod tests { #[tokio::test] async fn test_shared_key_presign_service_sas() { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -1088,7 +1101,7 @@ mod tests { let now = Timestamp::from_str("2022-03-01T08:12:34.500Z").unwrap(); let http_send = MockUserDelegationHttpSend::default(); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(http_send.clone()) .with_env(OsEnv); diff --git a/services/azure-storage/src/user_delegation.rs b/services/azure-storage/src/user_delegation.rs index 2350d2e6..4c41fad6 100644 --- a/services/azure-storage/src/user_delegation.rs +++ b/services/azure-storage/src/user_delegation.rs @@ -19,6 +19,7 @@ use bytes::Bytes; use http::header; use reqsign_core::Context; use reqsign_core::Result; +use reqsign_core::crypto::CryptoProvider; use reqsign_core::hash; use reqsign_core::time::Timestamp; use reqsign_core::utils::Redact; @@ -412,7 +413,7 @@ impl UserDelegationSharedAccessSignature { self } - fn signature(&self) -> Result { + fn signature(&self, provider: &dyn CryptoProvider) -> Result { let canonicalized_resource = self.resource.canonicalized_resource(&self.account); if self.version.as_str() >= "2025-07-05" { @@ -465,13 +466,10 @@ impl UserDelegationSharedAccessSignature { let string_to_sign = fields.join("\n"); let decoded_key = hash::base64_decode(&self.key.value)?; - Ok(hash::base64_hmac_sha256( - &decoded_key, - string_to_sign.as_bytes(), - )) + hash::base64_hmac_sha256(provider, &decoded_key, string_to_sign.as_bytes()) } - pub(crate) fn token(&self) -> Result> { + pub(crate) fn token(&self, provider: &dyn CryptoProvider) -> Result> { let mut elements: Vec<(String, String)> = vec![ ("sv".to_string(), self.version.to_string()), ("se".to_string(), self.expiry.format_rfc3339_zulu()), @@ -507,7 +505,7 @@ impl UserDelegationSharedAccessSignature { elements.push(("spr".to_string(), protocol.to_string())) } - let sig = self.signature()?; + let sig = self.signature(provider)?; elements.push(("sig".to_string(), sig)); Ok(elements) diff --git a/services/azure-storage/src/user_delegation_sas.rs b/services/azure-storage/src/user_delegation_sas.rs index 7a496567..33618e7c 100644 --- a/services/azure-storage/src/user_delegation_sas.rs +++ b/services/azure-storage/src/user_delegation_sas.rs @@ -24,6 +24,7 @@ use crate::user_delegation::{ }; use asyncband::singleflight::Group; use percent_encoding::percent_encode; +use reqsign_core::crypto::CryptoProvider; use reqsign_core::hash::hex_sha256; use reqsign_core::time::Timestamp; use reqsign_core::{Context, Error, GrantCredential, Result, SigningCredential}; @@ -670,15 +671,16 @@ impl UserDelegationSasGranter { fn cache_key( &self, + provider: &dyn CryptoProvider, endpoint: &ParsedEndpoint, bearer_token: &str, - ) -> UserDelegationKeyCacheKey { - UserDelegationKeyCacheKey { + ) -> Result { + Ok(UserDelegationKeyCacheKey { account: self.account.clone(), endpoint: endpoint.identity.clone(), - source_authority: hex_sha256(bearer_token.as_bytes()), + source_authority: hex_sha256(provider, bearer_token.as_bytes())?, service_version: USER_DELEGATION_SERVICE_VERSION, - } + }) } fn key_covers( @@ -720,18 +722,11 @@ impl GrantCredential for UserDelegationSasGranter { let Credential::BearerToken { token, .. } = credential else { return now + BEARER_TOKEN_OPERATION_HEADROOM; }; - let Ok(endpoint) = self.parse_endpoint() else { - return now + BEARER_TOKEN_OPERATION_HEADROOM; - }; - let Ok(times) = self.operation_times(expires_in) else { - return now + BEARER_TOKEN_OPERATION_HEADROOM; - }; - let cache_key = self.cache_key(&endpoint, token); - if self.cached_key(&cache_key, ×).is_some() { - now - } else { - now + BEARER_TOKEN_OPERATION_HEADROOM - } + // This trait method has no Context, so the source-authority key cannot + // be computed here. Require I/O headroom conservatively; grant_credential + // resolves the provider and reuses the key cache when possible. + let _ = (token, expires_in); + now + BEARER_TOKEN_OPERATION_HEADROOM } async fn grant_credential( @@ -746,6 +741,7 @@ impl GrantCredential for UserDelegationSasGranter { )); }; + let provider = ctx.crypto_provider()?; let endpoint = self.parse_endpoint()?; let grant = self.grant.validate()?; self.validate_ip()?; @@ -757,7 +753,7 @@ impl GrantCredential for UserDelegationSasGranter { )); } - let cache_key = self.cache_key(&endpoint, token); + let cache_key = self.cache_key(provider, &endpoint, token)?; let cached = self.cached_key(&cache_key, ×); let (key, fetched) = if let Some(key) = cached { (key, false) @@ -828,8 +824,8 @@ impl GrantCredential for UserDelegationSasGranter { signer = signer.with_ip(ip); } - let pairs = signer.token().map_err(|e| { - Error::unexpected("failed to generate Azure user delegation SAS").with_source(e) + let pairs = signer.token(provider).map_err(|e| { + Error::new(e.kind(), "failed to generate Azure user delegation SAS").with_source(e) })?; let token = encode_query_pairs(&pairs); let output = Credential::with_sas_token_expires_at(&token, times.expiry); @@ -1091,7 +1087,7 @@ mod tests { let http = MockUserDelegationHttpSend::new([delegation_key_response( now, key_expiry, "oid", "tid", "a2V5", )]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let operation = UserDelegationSasGranter::new( "account", blob_grant( @@ -1159,7 +1155,7 @@ mod tests { let http = MockUserDelegationHttpSend::new([delegation_key_response( key_start, key_expiry, "oid", "tid", "a2V5", )]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let operation = UserDelegationSasGranter::new( "account", blob_grant("blob", UserDelegationSasPermissions::READ), @@ -1217,7 +1213,7 @@ mod tests { "tid", "a2V5", )]); - let ctx = Context::new().with_http_send(http); + let ctx = crate::test_context().with_http_send(http); let operation = UserDelegationSasGranter::new( "account", blob_grant("path/to/blob.txt", UserDelegationSasPermissions::READ), @@ -1236,7 +1232,7 @@ mod tests { let token = token.to_string(); let signer = Signer::new( - Context::new(), + crate::test_context(), FixedCredentialProvider(output), RequestSigner::new(), ); @@ -1265,7 +1261,7 @@ mod tests { async fn rejects_non_bearer_source_variants_before_io() { let now = timestamp("2030-01-01T00:00:00Z"); let http = MockUserDelegationHttpSend::new([]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let operation = UserDelegationSasGranter::new( "account", blob_grant("blob", UserDelegationSasPermissions::READ), @@ -1292,7 +1288,7 @@ mod tests { let http = MockUserDelegationHttpSend::new([delegation_key_response( now, key_expiry, "oid", "tid", "a2V5", )]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let base = UserDelegationSasGranter::new( "account", blob_grant("blob", UserDelegationSasPermissions::READ), @@ -1347,7 +1343,7 @@ mod tests { let key_expiry = now + MAX_USER_DELEGATION_LIFETIME; let response = || delegation_key_response(now, key_expiry, "oid", "tid", "a2V5"); let http = MockUserDelegationHttpSend::new([response(), response(), response()]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let first = UserDelegationSasGranter::new( "account", blob_grant("first", UserDelegationSasPermissions::READ), @@ -1397,7 +1393,7 @@ mod tests { "a2V5", )]) .with_response_gate(gate.clone()); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let source = bearer("source"); let first = UserDelegationSasGranter::new( "account", @@ -1467,7 +1463,7 @@ mod tests { }; let http = MockUserDelegationHttpSend::new([response(), response()]) .with_response_gate(gate.clone()); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let source = bearer("source"); let first = UserDelegationSasGranter::new( "account", @@ -1534,7 +1530,7 @@ mod tests { Error::rate_limited("retry later").with_context("delegation key request") )); } - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let source = bearer("source"); let operation = UserDelegationSasGranter::new( "account", @@ -1588,7 +1584,7 @@ mod tests { "a2V5", )]) .with_response_gate(gate.clone()); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let source = bearer("source"); let first = UserDelegationSasGranter::new( "account", @@ -1643,7 +1639,7 @@ mod tests { "a2V5", ), ]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let operation = UserDelegationSasGranter::new( "account", blob_grant("blob", UserDelegationSasPermissions::READ), @@ -1670,7 +1666,7 @@ mod tests { let key_expiry = now + MAX_USER_DELEGATION_LIFETIME; let response = || delegation_key_response(now, key_expiry, "oid", "tid", "a2V5"); let http = MockUserDelegationHttpSend::new([response(), response(), response()]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let source = bearer("source"); let container = UserDelegationSasGranter::new( @@ -1739,7 +1735,7 @@ mod tests { async fn rejects_scope_widening_and_invalid_permissions_before_io() { let now = timestamp("2030-01-01T00:00:00Z"); let http = MockUserDelegationHttpSend::new([]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let source = bearer("source"); for prefix in ["", "/", "///", "/prefix", "prefix/", "a//b", ".", ".."] { @@ -1816,7 +1812,7 @@ mod tests { async fn validates_account_endpoint_and_ip_before_io() { let now = timestamp("2030-01-01T00:00:00Z"); let http = MockUserDelegationHttpSend::new([]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let source = bearer("source"); let grant = blob_grant("blob", UserDelegationSasPermissions::READ); diff --git a/services/azure-storage/tests/common/mod.rs b/services/azure-storage/tests/common/mod.rs new file mode 100644 index 00000000..864b1164 --- /dev/null +++ b/services/azure-storage/tests/common/mod.rs @@ -0,0 +1,22 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use reqsign_core::Context; + +pub fn test_context() -> Context { + Context::new().with_crypto(reqsign_crypto_rustcrypto::RustCryptoProvider::new()) +} diff --git a/services/azure-storage/tests/credential_providers/default.rs b/services/azure-storage/tests/credential_providers/default.rs index e3fd2756..f1e0eb98 100644 --- a/services/azure-storage/tests/credential_providers/default.rs +++ b/services/azure-storage/tests/credential_providers/default.rs @@ -18,7 +18,7 @@ use std::collections::HashMap; use reqsign_azure_storage::{DefaultCredentialProvider, EnvCredentialProvider}; -use reqsign_core::{Context, ProvideCredential, StaticEnv}; +use reqsign_core::{ProvideCredential, StaticEnv}; use super::{assert_provider_reads_probe, live_context}; @@ -38,7 +38,7 @@ async fn test_default_provider() -> anyhow::Result<()> { #[tokio::test] async fn builder_can_remove_and_restore_environment_slot() { - let ctx = Context::new().with_env(StaticEnv { + let ctx = crate::common::test_context().with_env(StaticEnv { home_dir: None, envs: HashMap::from([ ( diff --git a/services/azure-storage/tests/credential_providers/mod.rs b/services/azure-storage/tests/credential_providers/mod.rs index 7eb61167..f3450d75 100644 --- a/services/azure-storage/tests/credential_providers/mod.rs +++ b/services/azure-storage/tests/credential_providers/mod.rs @@ -40,7 +40,7 @@ pub mod workload_identity; const EXPECTED_PROBE_BODY: &[u8] = b"reqsign-live-azure-ok\n"; pub fn live_context() -> Context { - Context::new() + crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_command_execute(TokioCommandExecute) diff --git a/services/azure-storage/tests/main.rs b/services/azure-storage/tests/main.rs index 6d99c322..82413a47 100644 --- a/services/azure-storage/tests/main.rs +++ b/services/azure-storage/tests/main.rs @@ -15,5 +15,7 @@ // specific language governing permissions and limitations // under the License. +mod common; + mod credential_providers; mod signing; diff --git a/services/azure-storage/tests/signing/sas_token.rs b/services/azure-storage/tests/signing/sas_token.rs index e020838a..341310b0 100644 --- a/services/azure-storage/tests/signing/sas_token.rs +++ b/services/azure-storage/tests/signing/sas_token.rs @@ -17,7 +17,7 @@ use bytes::Bytes; use reqsign_azure_storage::{RequestSigner, StaticCredentialProvider}; -use reqsign_core::{Context, OsEnv, Signer}; +use reqsign_core::{OsEnv, Signer}; use reqsign_file_read_tokio::TokioFileRead; use reqsign_http_send_reqwest::ReqwestHttpSend; @@ -45,7 +45,7 @@ async fn test_sas_token_signing() -> anyhow::Result<()> { let url = required_env("REQSIGN_AZURE_STORAGE_PROBE_URL"); let sas_token = load_sas_token(); - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -98,7 +98,7 @@ async fn test_sas_token_with_existing_query() { let base_url = required_env("REQSIGN_AZURE_STORAGE_PROBE_URL"); let sas_token = load_sas_token(); - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -138,7 +138,7 @@ async fn test_sas_token_preserves_headers() { let url = required_env("REQSIGN_AZURE_STORAGE_PROBE_URL"); let sas_token = load_sas_token(); - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); diff --git a/services/azure-storage/tests/signing/shared_key.rs b/services/azure-storage/tests/signing/shared_key.rs index fdc17e16..b00d840b 100644 --- a/services/azure-storage/tests/signing/shared_key.rs +++ b/services/azure-storage/tests/signing/shared_key.rs @@ -17,7 +17,7 @@ use bytes::Bytes; use reqsign_azure_storage::{RequestSigner, StaticCredentialProvider}; -use reqsign_core::{Context, OsEnv, Signer}; +use reqsign_core::{OsEnv, Signer}; use reqsign_file_read_tokio::TokioFileRead; use reqsign_http_send_reqwest::ReqwestHttpSend; @@ -52,7 +52,7 @@ async fn test_shared_key_signing_get() -> anyhow::Result<()> { return Ok(()); }; - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -104,7 +104,7 @@ async fn test_shared_key_signing_put_with_body() { return; }; - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -148,7 +148,7 @@ async fn test_shared_key_signing_with_query_params() { return; }; - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -180,7 +180,7 @@ async fn test_shared_key_signing_special_headers() { return; }; - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); diff --git a/services/google/Cargo.toml b/services/google/Cargo.toml index 4d6fcce4..690ec7c1 100644 --- a/services/google/Cargo.toml +++ b/services/google/Cargo.toml @@ -31,39 +31,36 @@ all-features = true [features] credential-access-boundary-client-side = [ - "dep:aes-gcm", - "dep:base64", "dep:prost", "dep:zeroize", ] default = [] [dependencies] -aes-gcm = { workspace = true, features = ["zeroize"], optional = true } asyncband = { workspace = true } -base64 = { workspace = true, optional = true } +base64 = { workspace = true } bytes = { workspace = true } form_urlencoded = { workspace = true } +hex = { workspace = true } http = { workspace = true } log = { workspace = true } percent-encoding = { workspace = true } prost = { workspace = true, optional = true } reqsign-aws-v4 = { workspace = true } reqsign-core = { workspace = true } -rsa = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } tokio = { workspace = true, features = ["time"] } zeroize = { workspace = true, optional = true } -[target.'cfg(not(target_arch = "wasm32"))'.dependencies] -reqsign-core = { workspace = true, features = ["jwt"] } - [dev-dependencies] +aes-gcm = { workspace = true, features = ["zeroize"] } asyncband = { workspace = true, features = ["semaphore"] } dotenvy = { workspace = true } env_logger = { workspace = true } +reqsign-crypto-rustcrypto = { workspace = true } reqsign-file-read-tokio = { workspace = true } reqsign-http-send-reqwest = { workspace = true } reqwest = { workspace = true, features = ["default-tls"] } +rsa = { workspace = true } tokio = { workspace = true, features = ["full"] } diff --git a/services/google/README.md b/services/google/README.md index ded86423..a99a54d2 100644 --- a/services/google/README.md +++ b/services/google/README.md @@ -7,15 +7,22 @@ account credentials. Its default Application Default Credentials chain checks `GOOGLE_APPLICATION_CREDENTIALS`, the well-known gcloud credentials file, and the Compute Engine metadata service. +> Signing needs a `CryptoProvider` resolved through the `Context`: bind one with +> `Context::with_crypto`, install a process-wide default, or use a facade +> `default_context()` (which binds RustCrypto when the global slot is empty). A +> bare `Context::new()` starts unbound. See +> [CryptoProvider](https://github.com/apache/reqsign/blob/main/docs/crypto-provider.md). + ## Quick Start ```rust,no_run +use reqsign_crypto_rustcrypto::RustCryptoProvider; use reqsign_core::{Context, OsEnv, Signer}; use reqsign_file_read_tokio::TokioFileRead; use reqsign_google::{DefaultCredentialProvider, RequestSigner}; use reqsign_http_send_reqwest::ReqwestHttpSend; -let context = Context::new() +let context = Context::new().with_crypto(RustCryptoProvider::new()) .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); diff --git a/services/google/examples/chain_logging.rs b/services/google/examples/chain_logging.rs index 196ab3f5..bd63c59b 100644 --- a/services/google/examples/chain_logging.rs +++ b/services/google/examples/chain_logging.rs @@ -18,6 +18,7 @@ //! Example of using ProvideCredentialChain with logging to see credential resolution use log::{debug, info}; use reqsign_core::{Context, OsEnv, ProvideCredential, ProvideCredentialChain, Result}; +use reqsign_crypto_rustcrypto::RustCryptoProvider; use reqsign_file_read_tokio::TokioFileRead; use reqsign_google::{Credential, DefaultCredentialProvider}; use reqsign_http_send_reqwest::ReqwestHttpSend; @@ -75,6 +76,7 @@ async fn main() -> Result<()> { // Create context let ctx = Context::new() + .with_crypto(RustCryptoProvider::new()) .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); diff --git a/services/google/examples/custom_chain.rs b/services/google/examples/custom_chain.rs index 6ad91535..07b35ea6 100644 --- a/services/google/examples/custom_chain.rs +++ b/services/google/examples/custom_chain.rs @@ -17,6 +17,7 @@ //! Example of building a custom credential chain with specific providers use reqsign_core::{Context, ProvideCredential, ProvideCredentialChain, Result}; +use reqsign_crypto_rustcrypto::RustCryptoProvider; use reqsign_file_read_tokio::TokioFileRead; use reqsign_google::{Credential, ServiceAccount, Token}; use reqsign_http_send_reqwest::ReqwestHttpSend; @@ -88,6 +89,7 @@ impl ProvideCredential for EnvCredentialProvider { async fn main() -> Result<()> { // Create context let ctx = Context::new() + .with_crypto(RustCryptoProvider::new()) .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()); diff --git a/services/google/src/credential_access_boundary/client_side.rs b/services/google/src/credential_access_boundary/client_side.rs index 55225a95..2b3ff4ee 100644 --- a/services/google/src/credential_access_boundary/client_side.rs +++ b/services/google/src/credential_access_boundary/client_side.rs @@ -20,14 +20,13 @@ use std::fmt::{self, Debug}; use std::sync::{Arc, Mutex as SyncMutex, Weak}; use std::time::Duration; -use aes_gcm::aead::{Aead, Generate, KeyInit, array::Array}; -use aes_gcm::{Aes128Gcm, Aes256Gcm}; use asyncband::mutex::Mutex; use base64::Engine; use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; use form_urlencoded::Serializer; use http::header::{ACCEPT, CONTENT_TYPE}; use prost::Message; +use reqsign_core::crypto; use reqsign_core::hash::hex_sha256; use reqsign_core::time::Timestamp; use reqsign_core::{Context, Error, GrantCredential, Result, SigningCredential}; @@ -277,8 +276,9 @@ impl Drop for RefreshLockLease { /// "customer-a/", /// CredentialAccessBoundaryPermissions::OBJECT_VIEWER, /// ); -/// // Supply a Context configured with an HttpSend implementation. -/// let context = Context::new(); +/// // Supply a Context with an HttpSend implementation and a crypto provider. +/// let context = Context::new() +/// .with_crypto(reqsign_crypto_rustcrypto::RustCryptoProvider::new()); /// let credential = Granter::new( /// context, /// source, @@ -566,7 +566,11 @@ impl ClientSideCredentialAccessBoundaryGranter { }) } - fn cache_key(&self, source: &Token) -> Result { + fn cache_key( + &self, + provider: &dyn crypto::CryptoProvider, + source: &Token, + ) -> Result { let source_expires_at = source.expires_at.ok_or_else(|| { Error::credential_invalid( "client-side credential access boundary source token expiration is required", @@ -574,7 +578,7 @@ impl ClientSideCredentialAccessBoundaryGranter { })?; Ok(IntermediaryCacheKey { endpoint: STS_ENDPOINT, - source_authority: hex_sha256(source.access_token.as_bytes()), + source_authority: hex_sha256(provider, source.access_token.as_bytes())?, source_expires_at, }) } @@ -582,10 +586,11 @@ impl ClientSideCredentialAccessBoundaryGranter { async fn intermediary_credentials( &self, ctx: &Context, + provider: &dyn crypto::CryptoProvider, source: &Token, minimum_lifetime: Duration, ) -> Result> { - let cache_key = self.cache_key(source)?; + let cache_key = self.cache_key(provider, source)?; let now = self.now(); if let Some(credentials) = self.intermediary_state @@ -643,7 +648,10 @@ impl ClientSideCredentialAccessBoundaryGranter { Ok(credentials) } - fn next_nonce(&self) -> Result<[u8; AES_GCM_NONCE_BYTES]> { + fn next_nonce( + &self, + provider: &dyn crypto::CryptoProvider, + ) -> Result<[u8; AES_GCM_NONCE_BYTES]> { #[cfg(test)] if let Some(nonces) = &self.nonces { return nonces @@ -653,8 +661,9 @@ impl ClientSideCredentialAccessBoundaryGranter { .ok_or_else(|| Error::unexpected("test CAB nonce queue is empty")); } - <[u8; AES_GCM_NONCE_BYTES]>::try_generate() - .map_err(|_| Error::unexpected("failed to generate client-side CAB encryption nonce")) + let mut nonce = [0u8; AES_GCM_NONCE_BYTES]; + provider.fill_random(&mut nonce)?; + Ok(nonce) } #[cfg(test)] @@ -694,13 +703,16 @@ impl GrantCredential for ClientSideCredentialAccessBoundaryGranter { self.now(), minimum_lifetime.saturating_add(TOKEN_EXCHANGE_HEADROOM), )?; + let provider = ctx.crypto_provider()?; let source = self.source_token(credential, required_until)?; let intermediary = self - .intermediary_credentials(ctx, source, minimum_lifetime) + .intermediary_credentials(ctx, provider, source, minimum_lifetime) .await?; - let nonce = self.next_nonce()?; - let encrypted = intermediary.aead_key.encrypt(&restrictions, &nonce)?; + let nonce = self.next_nonce(provider)?; + let encrypted = intermediary + .aead_key + .encrypt(provider, &restrictions, &nonce)?; let access_token = format!( "{}.{}", intermediary.access_token.as_str(), @@ -828,21 +840,13 @@ impl TinkAesGcmKey { }) } - fn encrypt(&self, restrictions: &[u8], nonce: &[u8; AES_GCM_NONCE_BYTES]) -> Result> { - let ciphertext = match self.key_value.len() { - 16 => Aes128Gcm::new_from_slice(&self.key_value) - .map_err(|_| Error::unexpected("failed to initialize client-side CAB encryption"))? - .encrypt(&Array(*nonce), restrictions), - 32 => Aes256Gcm::new_from_slice(&self.key_value) - .map_err(|_| Error::unexpected("failed to initialize client-side CAB encryption"))? - .encrypt(&Array(*nonce), restrictions), - _ => { - return Err(Error::unexpected( - "client-side CAB session key uses an unsupported AEAD key", - )); - } - } - .map_err(|_| Error::unexpected("failed to encrypt client-side CAB restrictions"))?; + fn encrypt( + &self, + provider: &dyn crypto::CryptoProvider, + restrictions: &[u8], + nonce: &[u8; AES_GCM_NONCE_BYTES], + ) -> Result> { + let ciphertext = provider.aes_gcm_encrypt(&self.key_value, nonce, b"", restrictions)?; let mut encrypted = Vec::with_capacity(self.output_prefix.len() + nonce.len() + ciphertext.len()); @@ -1068,6 +1072,8 @@ struct AesGcmKeyProto { #[cfg(test)] mod tests { + use aes_gcm::aead::{Aead, KeyInit, array::Array}; + use aes_gcm::{Aes128Gcm, Aes256Gcm}; use std::collections::{BTreeMap, HashSet, VecDeque}; use std::fmt::Formatter; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -1387,7 +1393,11 @@ mod tests { let nonce = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; let encrypted = key - .encrypt(b"restriction", &nonce) + .encrypt( + &reqsign_crypto_rustcrypto::RustCryptoProvider::new(), + b"restriction", + &nonce, + ) .expect("vector must encrypt"); assert_eq!( URL_SAFE_NO_PAD.encode(encrypted), @@ -1422,7 +1432,11 @@ mod tests { let source = source_token("source+token/with=reserved", Some(source_expiry)); operation - .grant_credential(&Context::new().with_http_send(http.clone()), &source, None) + .grant_credential( + &crate::test_context().with_http_send(http.clone()), + &source, + None, + ) .await .expect("client-side grant must succeed"); @@ -1476,7 +1490,7 @@ mod tests { let http = MockHttpSend::new([success_response("intermediary", Some(3600))]); let output = operation .grant_credential( - &Context::new().with_http_send(http), + &crate::test_context().with_http_send(http), &source_token("source", Some(now + Duration::from_secs(2 * 60 * 60))), None, ) @@ -1591,7 +1605,7 @@ mod tests { .with_nonces([[9; AES_GCM_NONCE_BYTES]]); let output = operation .grant_credential( - &Context::new().with_http_send(MockHttpSend::new([success_response( + &crate::test_context().with_http_send(MockHttpSend::new([success_response( "intermediary", Some(3600), )])), @@ -1637,7 +1651,7 @@ mod tests { .with_time(now); let err = operation .grant_credential( - &Context::new().with_http_send(http.clone()), + &crate::test_context().with_http_send(http.clone()), &source_token("source", Some(now + Duration::from_secs(2 * 60 * 60))), None, ) @@ -1652,7 +1666,7 @@ mod tests { async fn rejects_incompatible_sources_and_lifetimes_before_io() { let now = timestamp("2030-01-01T00:00:00Z"); let http = MockHttpSend::new([]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let operation = ClientSideCredentialAccessBoundaryGranter::new(viewer_bucket_grant()).with_time(now); let valid_token = Token { @@ -1731,7 +1745,7 @@ mod tests { .with_nonces([[4; AES_GCM_NONCE_BYTES]]); let output = operation .grant_credential( - &Context::new().with_http_send(MockHttpSend::new([success_response( + &crate::test_context().with_http_send(MockHttpSend::new([success_response( "intermediary", Some(MAX_ACCESS_TOKEN_LIFETIME.as_secs()), )])), @@ -1767,7 +1781,7 @@ mod tests { let explicit = operation .grant_credential( - &Context::new().with_http_send(MockHttpSend::new([success_response( + &crate::test_context().with_http_send(MockHttpSend::new([success_response( "explicit", Some(3600), )])), @@ -1787,7 +1801,7 @@ mod tests { .with_time_after_request(response_time); let err = missing_expiration_operation .grant_credential( - &Context::new() + &crate::test_context() .with_http_send(MockHttpSend::new([success_response("inherited", None)])), &source, None, @@ -1803,7 +1817,7 @@ mod tests { .with_nonces([[3; AES_GCM_NONCE_BYTES]]); let clamped = clamped_operation .grant_credential( - &Context::new().with_http_send(MockHttpSend::new([success_response( + &crate::test_context().with_http_send(MockHttpSend::new([success_response( "clamped", Some(3 * 60 * 60), )])), @@ -1839,7 +1853,7 @@ mod tests { let http = MockHttpSend::new([response]); let err = ClientSideCredentialAccessBoundaryGranter::new(viewer_bucket_grant()) .with_time(now) - .grant_credential(&Context::new().with_http_send(http), &source, None) + .grant_credential(&crate::test_context().with_http_send(http), &source, None) .await .expect_err("malformed response must fail"); assert_eq!(err.kind(), ErrorKind::Unexpected); @@ -1911,18 +1925,17 @@ mod tests { ]; for key in keys { - let err = - ClientSideCredentialAccessBoundaryGranter::new(viewer_bucket_grant()) - .with_time(now) - .grant_credential( - &Context::new().with_http_send(MockHttpSend::new([ - success_response_with_key("intermediary", &key, Some(3600)), - ])), - &source, - None, - ) - .await - .expect_err("invalid keyset must fail"); + let err = ClientSideCredentialAccessBoundaryGranter::new(viewer_bucket_grant()) + .with_time(now) + .grant_credential( + &crate::test_context().with_http_send(MockHttpSend::new([ + success_response_with_key("intermediary", &key, Some(3600)), + ])), + &source, + None, + ) + .await + .expect_err("invalid keyset must fail"); assert_eq!(err.kind(), ErrorKind::Unexpected); assert!(!format!("{err:?}").contains(&key)); } @@ -1938,7 +1951,7 @@ mod tests { .with_time_after_request(now + Duration::from_secs(31 * 60)); let err = post_io .grant_credential( - &Context::new().with_http_send(MockHttpSend::new([success_response( + &crate::test_context().with_http_send(MockHttpSend::new([success_response( "intermediary", Some(3600), )])), @@ -1955,7 +1968,7 @@ mod tests { .with_nonces([[4; AES_GCM_NONCE_BYTES]]); let err = post_generation .grant_credential( - &Context::new().with_http_send(MockHttpSend::new([success_response( + &crate::test_context().with_http_send(MockHttpSend::new([success_response( "intermediary", Some(60 * 60), )])), @@ -1975,7 +1988,7 @@ mod tests { .with_time(now) .with_nonces([[1; AES_GCM_NONCE_BYTES], [2; AES_GCM_NONCE_BYTES]]); let source = source_token("source", Some(now + Duration::from_secs(2 * 60 * 60))); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let first = operation .grant_credential(&ctx, &source, None) @@ -2015,7 +2028,7 @@ mod tests { [3; AES_GCM_NONCE_BYTES], ]); let source = source_token("source", Some(now + Duration::from_secs(3 * 60 * 60))); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let first = operation .grant_credential(&ctx, &source, None) @@ -2054,7 +2067,7 @@ mod tests { .with_time(now) .with_nonces([[1; AES_GCM_NONCE_BYTES]]); let source = source_token("source", Some(now + Duration::from_secs(3 * 60 * 60))); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); operation .grant_credential(&ctx, &source, None) .await @@ -2085,7 +2098,7 @@ mod tests { (0..INTERMEDIARY_CACHE_CAPACITY + 2) .map(|index| [index as u8; AES_GCM_NONCE_BYTES]), ); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let source_expiry = now + Duration::from_secs(2 * 60 * 60); for index in 0..=INTERMEDIARY_CACHE_CAPACITY { @@ -2141,7 +2154,7 @@ mod tests { [2; AES_GCM_NONCE_BYTES], [3; AES_GCM_NONCE_BYTES], ]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let expiry = now + Duration::from_secs(2 * 60 * 60); let source_a = source_token("source-a", Some(expiry)); let source_b = source_token("source-b", Some(expiry)); @@ -2176,7 +2189,7 @@ mod tests { let operation = ClientSideCredentialAccessBoundaryGranter::new(viewer_bucket_grant()) .with_time(now) .with_nonces([[1; AES_GCM_NONCE_BYTES], [2; AES_GCM_NONCE_BYTES]]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let expiry = now + Duration::from_secs(2 * 60 * 60); let first = tokio::spawn({ @@ -2228,7 +2241,7 @@ mod tests { let operation = ClientSideCredentialAccessBoundaryGranter::new(viewer_bucket_grant()) .with_time(now) .with_nonces((0..8).map(|index| [index; AES_GCM_NONCE_BYTES])); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let source = source_token("source", Some(now + Duration::from_secs(2 * 60 * 60))); let mut tasks = Vec::new(); for _ in 0..8 { @@ -2274,7 +2287,7 @@ mod tests { let operation = ClientSideCredentialAccessBoundaryGranter::new(viewer_bucket_grant()) .with_time(now) .with_nonces([[3; AES_GCM_NONCE_BYTES]]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let source = source_token("source", Some(now + Duration::from_secs(2 * 60 * 60))); let leader = tokio::spawn({ @@ -2321,7 +2334,7 @@ mod tests { let operation = ClientSideCredentialAccessBoundaryGranter::new(viewer_bucket_grant()) .with_time(now) .with_nonces([[5; AES_GCM_NONCE_BYTES]]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let source = source_token("source", Some(now + Duration::from_secs(2 * 60 * 60))); let cancelled = { @@ -2369,7 +2382,7 @@ mod tests { "tenant/", CredentialAccessBoundaryPermissions::OBJECT_VIEWER, )); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let source = source_token("source", Some(now + Duration::from_secs(2 * 60 * 60))); let bucket_output = bucket @@ -2400,7 +2413,7 @@ mod tests { let (provider, provider_calls) = FixedCredentialProvider::new(source); let http = MockHttpSend::new([success_response("intermediary", Some(3600))]); let granter = Granter::new( - Context::new().with_http_send(http.clone()), + crate::test_context().with_http_send(http.clone()), provider, ClientSideCredentialAccessBoundaryGranter::new(viewer_bucket_grant()) .with_nonces([[1; AES_GCM_NONCE_BYTES], [2; AES_GCM_NONCE_BYTES]]), @@ -2426,7 +2439,7 @@ mod tests { .with_nonces([[8; AES_GCM_NONCE_BYTES]]); let output = operation .grant_credential( - &Context::new().with_http_send(MockHttpSend::new([success_response( + &crate::test_context().with_http_send(MockHttpSend::new([success_response( "intermediary", Some(3600), )])), @@ -2437,7 +2450,11 @@ mod tests { .expect("client-side grant must succeed"); let expected = format!("Bearer {}", output_token(&output).access_token); let (provider, _) = FixedCredentialProvider::new(output); - let signer = Signer::new(Context::new(), provider, RequestSigner::new("storage")); + let signer = Signer::new( + crate::test_context(), + provider, + RequestSigner::new("storage"), + ); let mut parts = http::Request::get("https://storage.googleapis.com/example-bucket/customer/object") .body(()) @@ -2464,7 +2481,7 @@ mod tests { ClientSideCredentialAccessBoundaryGranter::new(viewer_bucket_grant()).with_time(now); let err = operation .grant_credential( - &Context::new().with_http_send(MockHttpSend::new([response( + &crate::test_context().with_http_send(MockHttpSend::new([response( http::StatusCode::BAD_REQUEST, r#"{"error":"invalid_grant","error_description":"source-secret raw-response-secret"}"#, )])), @@ -2480,7 +2497,7 @@ mod tests { let err = operation .grant_credential( - &Context::new().with_http_send(SecretTransportError), + &crate::test_context().with_http_send(SecretTransportError), &source, None, ) @@ -2509,7 +2526,11 @@ mod tests { ); let http = MockHttpSend::new([success_response("intermediary-secret", Some(3600))]); let output = operation - .grant_credential(&Context::new().with_http_send(http.clone()), &source, None) + .grant_credential( + &crate::test_context().with_http_send(http.clone()), + &source, + None, + ) .await .expect("client-side grant must succeed"); let request = http diff --git a/services/google/src/credential_access_boundary/server_side.rs b/services/google/src/credential_access_boundary/server_side.rs index f04af31a..7430118f 100644 --- a/services/google/src/credential_access_boundary/server_side.rs +++ b/services/google/src/credential_access_boundary/server_side.rs @@ -530,7 +530,7 @@ mod tests { .with_time_after_request(response_time); let output = operation .grant_credential( - &Context::new().with_http_send(http.clone()), + &crate::test_context().with_http_send(http.clone()), &source_token("source-token", Some(timestamp("2030-01-01T02:00:00Z"))), None, ) @@ -584,7 +584,7 @@ mod tests { operation .grant_credential( - &Context::new().with_http_send(http.clone()), + &crate::test_context().with_http_send(http.clone()), &source_token(source, Some(timestamp("2030-01-01T02:00:00Z"))), None, ) @@ -608,7 +608,7 @@ mod tests { async fn rejects_invalid_policy_lifetime_and_source_before_io() { let now = timestamp("2030-01-01T00:00:00Z"); let http = MockHttpSend::new([]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let valid_source = source_token("source", Some(timestamp("2030-01-01T02:00:00Z"))); let invalid_grant = CredentialAccessBoundaryGrant::for_object_prefix( @@ -674,7 +674,7 @@ mod tests { let operation = ServerSideCredentialAccessBoundaryGranter::new(viewer_bucket_grant()) .with_time(request_time) .with_time_after_request(response_time); - let ctx = Context::new().with_http_send(http); + let ctx = crate::test_context().with_http_send(http); let source = source_token("source", Some(source_expiry)); let anchored = operation @@ -719,7 +719,7 @@ mod tests { .with_time(timestamp("2030-01-01T00:00:00Z")) .with_time_after_request(response_time) .grant_credential( - &Context::new().with_http_send(MockHttpSend::new([success_response( + &crate::test_context().with_http_send(MockHttpSend::new([success_response( "downscoped-token", Some(MAX_ACCESS_TOKEN_LIFETIME.as_secs()), )])), @@ -762,7 +762,7 @@ mod tests { let http = MockHttpSend::new(responses); let operation = ServerSideCredentialAccessBoundaryGranter::new(viewer_bucket_grant()).with_time(now); - let ctx = Context::new().with_http_send(http); + let ctx = crate::test_context().with_http_send(http); let source = source_token("source-secret", Some(timestamp("2030-01-01T13:00:00Z"))); let expected = [ @@ -793,7 +793,7 @@ mod tests { let err = ServerSideCredentialAccessBoundaryGranter::new(viewer_bucket_grant()) .with_time(now) .grant_credential( - &Context::new().with_http_send(SecretTransportError), + &crate::test_context().with_http_send(SecretTransportError), &source_token("source-secret", Some(timestamp("2030-01-01T01:00:00Z"))), None, ) @@ -821,7 +821,7 @@ mod tests { ), ]); let granter = Granter::new( - Context::new().with_http_send(http.clone()), + crate::test_context().with_http_send(http.clone()), provider, ServerSideCredentialAccessBoundaryGranter::new(viewer_bucket_grant()).with_time(now), ); @@ -860,7 +860,7 @@ mod tests { let operation = ServerSideCredentialAccessBoundaryGranter::new(viewer_bucket_grant()).with_time(now); let granter = Granter::new( - Context::new().with_http_send(first_http.clone()), + crate::test_context().with_http_send(first_http.clone()), provider, operation.clone(), ); @@ -892,7 +892,7 @@ mod tests { .await .expect("replacement provider must succeed"); let context_isolated = granter - .with_context(Context::new().with_http_send(second_http.clone())) + .with_context(crate::test_context().with_http_send(second_http.clone())) .grant(None) .await .expect("replacement context must reload the source"); @@ -928,7 +928,7 @@ mod tests { let output = ServerSideCredentialAccessBoundaryGranter::new(viewer_bucket_grant()) .with_time(now) .grant_credential( - &Context::new().with_http_send(MockHttpSend::new([success_response( + &crate::test_context().with_http_send(MockHttpSend::new([success_response( "downscoped-token", Some(3600), )])), @@ -938,7 +938,11 @@ mod tests { .await .expect("grant must succeed"); let (provider, _) = FixedCredentialProvider::new(output); - let signer = Signer::new(Context::new(), provider, RequestSigner::new("storage")); + let signer = Signer::new( + crate::test_context(), + provider, + RequestSigner::new("storage"), + ); let mut parts = http::Request::get("https://storage.googleapis.com/example-bucket/customer/object") .body(()) diff --git a/services/google/src/jwt.rs b/services/google/src/jwt.rs new file mode 100644 index 00000000..8d42b83b --- /dev/null +++ b/services/google/src/jwt.rs @@ -0,0 +1,176 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Private RS256 JWS formatting for Google service-account exchanges. + +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use reqsign_core::crypto::CryptoProvider; +use reqsign_core::{Error, Result}; +use serde::Serialize; + +/// Encode a compact RS256 JWS using the selected provider. +pub(crate) fn encode_rs256( + provider: &dyn CryptoProvider, + header: &H, + claims: &C, + private_key_pem: &[u8], +) -> Result +where + H: Serialize, + C: Serialize, +{ + let encoded_header = encode_json(header)?; + let encoded_claims = encode_json(claims)?; + let signing_input = format!("{encoded_header}.{encoded_claims}"); + + let signature = provider.rsa_pkcs1v15_sha256_sign(private_key_pem, signing_input.as_bytes())?; + + Ok(format!( + "{signing_input}.{}", + URL_SAFE_NO_PAD.encode(signature) + )) +} + +fn encode_json(value: &T) -> Result +where + T: Serialize, +{ + let json = serde_json::to_vec(value) + .map_err(|e| Error::unexpected("failed to serialize JWT JSON").with_source(e))?; + Ok(URL_SAFE_NO_PAD.encode(json)) +} + +#[cfg(test)] +mod tests { + use super::*; + use base64::engine::general_purpose::URL_SAFE_NO_PAD; + use reqsign_core::ErrorKind; + use reqsign_crypto_rustcrypto::RustCryptoProvider; + use rsa::RsaPrivateKey; + use rsa::pkcs1::EncodeRsaPrivateKey; + use rsa::pkcs1v15::{Signature, VerifyingKey}; + use rsa::pkcs8::{EncodePrivateKey, LineEnding}; + use rsa::rand_core::OsRng; + use rsa::sha2::Sha256; + use rsa::signature::Verifier; + use serde::Serialize; + + #[derive(Serialize)] + struct Header<'a> { + alg: &'a str, + typ: &'a str, + } + + #[derive(Serialize)] + struct Claims<'a> { + iss: &'a str, + scope: &'a str, + aud: &'a str, + exp: u64, + iat: u64, + } + + fn private_key() -> RsaPrivateKey { + RsaPrivateKey::new(&mut OsRng, 1024).expect("test RSA key generation must work") + } + + fn decode_json(segment: &str) -> serde_json::Value { + serde_json::from_slice( + &URL_SAFE_NO_PAD + .decode(segment) + .expect("JWS segment must decode"), + ) + .expect("JWS segment must be JSON") + } + + #[test] + fn formats_three_unpadded_verifiable_segments_for_both_pem_formats() { + let key = private_key(); + let provider = RustCryptoProvider::new(); + let header = Header { + alg: "RS256", + typ: "JWT", + }; + let claims = Claims { + iss: "signer@example.com", + scope: "https://www.googleapis.com/auth/devstorage.read_write", + aud: "https://oauth2.googleapis.com/token", + exp: 1, + iat: 0, + }; + + for pem in [ + key.to_pkcs8_pem(LineEnding::LF) + .expect("test key must encode as PKCS#8"), + key.to_pkcs1_pem(LineEnding::LF) + .expect("test key must encode as PKCS#1"), + ] { + let jwt = encode_rs256(&provider, &header, &claims, pem.as_bytes()) + .expect("JWT encoding must succeed"); + let parts = jwt.split('.').collect::>(); + assert_eq!(parts.len(), 3); + assert!(parts.iter().all(|part| !part.contains('='))); + assert_eq!( + decode_json(parts[0]), + serde_json::json!({"alg": "RS256", "typ": "JWT"}) + ); + assert_eq!( + decode_json(parts[1]), + serde_json::json!({ + "iss": "signer@example.com", + "scope": "https://www.googleapis.com/auth/devstorage.read_write", + "aud": "https://oauth2.googleapis.com/token", + "exp": 1, + "iat": 0 + }) + ); + + let signature = URL_SAFE_NO_PAD + .decode(parts[2]) + .expect("signature must decode"); + let signature = + Signature::try_from(signature.as_slice()).expect("signature must parse"); + let verifying_key = VerifyingKey::::new(key.to_public_key()); + verifying_key + .verify(format!("{}.{}", parts[0], parts[1]).as_bytes(), &signature) + .expect("signature must verify"); + } + } + + #[test] + fn malformed_private_key_is_credential_invalid() { + let provider = RustCryptoProvider::new(); + let err = encode_rs256( + &provider, + &Header { + alg: "RS256", + typ: "JWT", + }, + &Claims { + iss: "signer@example.com", + scope: "scope", + aud: "audience", + exp: 1, + iat: 0, + }, + b"not a private key", + ) + .expect_err("malformed key must fail"); + assert_eq!(err.kind(), ErrorKind::CredentialInvalid); + } +} diff --git a/services/google/src/lib.rs b/services/google/src/lib.rs index 9231bb9a..93bbe672 100644 --- a/services/google/src/lib.rs +++ b/services/google/src/lib.rs @@ -31,6 +31,7 @@ mod credential; pub use credential::{Credential, OAuth2Credentials, ServiceAccount, Token}; mod credential_access_boundary; +mod jwt; #[cfg(feature = "credential-access-boundary-client-side")] pub use credential_access_boundary::ClientSideCredentialAccessBoundaryGranter; pub use credential_access_boundary::{ @@ -54,3 +55,8 @@ pub use provide_credential::{ FileCredentialProvider, ServiceAccountTokenCredentialProvider, StaticCredentialProvider, TokenCredentialProvider, VmMetadataCredentialProvider, WellKnownCredentialProvider, }; + +#[cfg(test)] +pub(crate) fn test_context() -> reqsign_core::Context { + reqsign_core::Context::new().with_crypto(reqsign_crypto_rustcrypto::RustCryptoProvider::new()) +} diff --git a/services/google/src/provide_credential/default.rs b/services/google/src/provide_credential/default.rs index 937e567b..1eae14c3 100644 --- a/services/google/src/provide_credential/default.rs +++ b/services/google/src/provide_credential/default.rs @@ -237,7 +237,7 @@ impl DefaultCredentialProviderBuilder { mod tests { use super::*; use bytes::Bytes; - use reqsign_core::{Context, FileRead, HttpSend, StaticEnv}; + use reqsign_core::{FileRead, HttpSend, StaticEnv}; use std::collections::HashMap; use std::env; use std::sync::{Arc, Mutex}; @@ -298,7 +298,7 @@ mod tests { ), )]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(reqsign_file_read_tokio::TokioFileRead) .with_http_send(reqsign_http_send_reqwest::ReqwestHttpSend::default()) .with_env(StaticEnv { @@ -371,7 +371,7 @@ mod tests { ), ])); let http = ExternalAccountHttpSend::default(); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(file_read.clone()) .with_http_send(http.clone()) .with_env(StaticEnv { @@ -415,7 +415,7 @@ mod tests { let provider = DefaultCredentialProvider::builder().build(); // Even without valid credentials, this should not panic - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(reqsign_file_read_tokio::TokioFileRead) .with_http_send(reqsign_http_send_reqwest::ReqwestHttpSend::default()); let _ = provider.provide_credential(&ctx).await; @@ -432,7 +432,7 @@ mod tests { )) .to_vec(), )])); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(file_read.clone()) .with_env(StaticEnv { home_dir: None, @@ -466,7 +466,7 @@ mod tests { )) .to_vec(), )])); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(file_read.clone()) .with_env(StaticEnv { home_dir: None, @@ -488,7 +488,7 @@ mod tests { #[tokio::test] async fn test_default_provider_no_vm_metadata_removes_provider() -> Result<()> { let http = MockHttpSend::default(); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let provider = DefaultCredentialProvider::builder() .no_env() @@ -505,7 +505,7 @@ mod tests { #[tokio::test] async fn test_default_provider_custom_vm_metadata_service_account() -> Result<()> { let http = MockHttpSend::default(); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let provider = DefaultCredentialProvider::builder() .no_env() diff --git a/services/google/src/provide_credential/external_account.rs b/services/google/src/provide_credential/external_account.rs index bc558c59..6f32726a 100644 --- a/services/google/src/provide_credential/external_account.rs +++ b/services/google/src/provide_credential/external_account.rs @@ -1615,7 +1615,7 @@ mod tests { #[test] fn test_resolve_template() { - let ctx = Context::new().with_env(MockEnv::default().with_var("FOO", "bar")); + let ctx = crate::test_context().with_env(MockEnv::default().with_var("FOO", "bar")); assert_eq!(resolve_template(&ctx, "a${FOO}c").unwrap(), "abarc"); } @@ -1642,7 +1642,9 @@ mod tests { access_token: "access-token".to_string(), }; let fs = MockFileRead::default().with_file("/var/run/token", b" test-oidc \n"); - let ctx = Context::new().with_http_send(http).with_file_read(fs); + let ctx = crate::test_context() + .with_http_send(http) + .with_file_read(fs); let provider = ExternalAccountCredentialProvider::new(external_account).with_scope("scope-a"); @@ -1670,7 +1672,7 @@ mod tests { expected_subject_token_type: "urn:ietf:params:oauth:token-type:jwt".to_string(), access_token: "access-token".to_string(), }; - let ctx = Context::new().with_http_send(http); + let ctx = crate::test_context().with_http_send(http); let provider = ExternalAccountCredentialProvider::from_subject_token(config, "caller.subject.token") .with_scope("scope-a"); @@ -1696,7 +1698,7 @@ mod tests { "expired.subject.token", Timestamp::now() - Duration::from_secs(1), ); - let ctx = Context::new().with_http_send(PanicHttpSend); + let ctx = crate::test_context().with_http_send(PanicHttpSend); let err = provider .provide_credential(&ctx) @@ -1714,7 +1716,7 @@ mod tests { "https://sts.googleapis.com/v1/token", ); let provider = ExternalAccountCredentialProvider::from_subject_token(config, secret); - let ctx = Context::new().with_http_send(EchoErrorHttpSend { + let ctx = crate::test_context().with_http_send(EchoErrorHttpSend { response_body: format!(r#"{{"error_description":"{secret}"}}"#), }); @@ -1747,7 +1749,9 @@ mod tests { let sts_scope = Arc::clone(&http.sts_scope); let impersonation_scopes = Arc::clone(&http.impersonation_scopes); let fs = MockFileRead::default().with_file("/var/run/token", b"test-oidc"); - let ctx = Context::new().with_http_send(http).with_file_read(fs); + let ctx = crate::test_context() + .with_http_send(http) + .with_file_read(fs); let provider = ExternalAccountCredentialProvider::new(external_account).with_scope(business_scope); @@ -1800,7 +1804,7 @@ mod tests { .with_var("PATH", "oidc") .with_var("TOKEN", "secret"); - let ctx = Context::new().with_http_send(http).with_env(env); + let ctx = crate::test_context().with_http_send(http).with_env(env); let provider = ExternalAccountCredentialProvider::new(external_account); let cred = provider @@ -1863,7 +1867,7 @@ mod tests { .with_var(AWS_ACCESS_KEY_ID, "test-access-key") .with_var(AWS_SECRET_ACCESS_KEY, "test-secret-key") .with_var(AWS_SESSION_TOKEN, "test-session-token"); - let ctx = Context::new().with_env(env); + let ctx = crate::test_context().with_env(env); let provider = ExternalAccountCredentialProvider::new(aws_account(aws_source())); let token = provider.load_oidc_token(&ctx).await?; @@ -1911,7 +1915,7 @@ mod tests { region_response: "us-west-2b".to_string(), role_name: "test-role".to_string(), }; - let ctx = Context::new().with_http_send(http); + let ctx = crate::test_context().with_http_send(http); let provider = ExternalAccountCredentialProvider::new(aws_account(aws_source())); let token = provider.load_oidc_token(&ctx).await?; @@ -1946,7 +1950,7 @@ mod tests { let provider = ExternalAccountCredentialProvider::new(aws_account(source)); let err = provider - .load_oidc_token(&Context::new()) + .load_oidc_token(&crate::test_context()) .await .expect_err("unsupported AWS environment_id must fail"); assert!(err.to_string().contains("aws2")); @@ -1960,7 +1964,7 @@ mod tests { let provider = ExternalAccountCredentialProvider::new(aws_account(source)); let err = provider - .load_oidc_token(&Context::new()) + .load_oidc_token(&crate::test_context()) .await .expect_err("invalid metadata host must fail"); assert!(err.to_string().contains("169.254.169.254")); @@ -2013,7 +2017,7 @@ mod tests { "/tmp/exec-cache.json", serde_json::to_vec(&cache).expect("json"), ); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(fs) .with_env(MockEnv::default().with_var(GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES, "1")) .with_command_execute(MockCommandExecute::success(br#"{"unexpected":true}"#)); @@ -2047,7 +2051,9 @@ mod tests { let env = MockEnv::default() .with_var(GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES, "1") .with_var("SUFFIX", "value"); - let ctx = Context::new().with_env(env).with_command_execute(command); + let ctx = crate::test_context() + .with_env(env) + .with_command_execute(command); let provider = ExternalAccountCredentialProvider::new(external_account); let token = provider.load_oidc_token(&ctx).await?; @@ -2085,7 +2091,8 @@ mod tests { async fn test_executable_source_requires_opt_in() { let external_account = executable_account(executable_source("/bin/example", None), TOKEN_TYPE_ID_TOKEN); - let ctx = Context::new().with_command_execute(MockCommandExecute::success(Vec::new())); + let ctx = + crate::test_context().with_command_execute(MockCommandExecute::success(Vec::new())); let provider = ExternalAccountCredentialProvider::new(external_account); let err = provider @@ -2113,7 +2120,7 @@ mod tests { .expect("json"), b"permission denied".as_slice(), ); - let ctx = Context::new() + let ctx = crate::test_context() .with_env(MockEnv::default().with_var(GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES, "1")) .with_command_execute(command); @@ -2149,7 +2156,7 @@ mod tests { }, }; let external_account = executable_account(source, TOKEN_TYPE_ID_TOKEN); - let ctx = Context::new() + let ctx = crate::test_context() .with_env(MockEnv::default().with_var(GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES, "1")) .with_command_execute(SlowCommandExecute); @@ -2166,7 +2173,7 @@ mod tests { let external_account = executable_account(executable_source("/bin/example", None), TOKEN_TYPE_ID_TOKEN); let command = MockCommandExecute::failure("permission denied"); - let ctx = Context::new() + let ctx = crate::test_context() .with_env(MockEnv::default().with_var(GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES, "1")) .with_command_execute(command); @@ -2191,7 +2198,7 @@ mod tests { })) .expect("json"), ); - let ctx = Context::new() + let ctx = crate::test_context() .with_env(MockEnv::default().with_var(GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES, "1")) .with_command_execute(command); @@ -2218,7 +2225,7 @@ mod tests { })) .expect("json"), ); - let ctx = Context::new() + let ctx = crate::test_context() .with_env(MockEnv::default().with_var(GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES, "1")) .with_command_execute(command); @@ -2255,7 +2262,7 @@ mod tests { })) .expect("json"), ); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(fs) .with_env(MockEnv::default().with_var(GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES, "1")) .with_command_execute(command); @@ -2283,7 +2290,7 @@ mod tests { })) .expect("json"), ); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(fs) .with_env(MockEnv::default().with_var(GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES, "1")) .with_command_execute(command); diff --git a/services/google/src/provide_credential/impersonated_service_account.rs b/services/google/src/provide_credential/impersonated_service_account.rs index 1a055567..6c9368c9 100644 --- a/services/google/src/provide_credential/impersonated_service_account.rs +++ b/services/google/src/provide_credential/impersonated_service_account.rs @@ -236,7 +236,7 @@ mod tests { ); let credential = provider - .provide_credential(&Context::new().with_http_send(MockHttpSend)) + .provide_credential(&crate::test_context().with_http_send(MockHttpSend)) .await? .expect("credential must exist"); diff --git a/services/google/src/provide_credential/service_account_token.rs b/services/google/src/provide_credential/service_account_token.rs index 6e1d86ad..1efe659d 100644 --- a/services/google/src/provide_credential/service_account_token.rs +++ b/services/google/src/provide_credential/service_account_token.rs @@ -29,6 +29,7 @@ use serde::{Deserialize, Serialize}; use crate::constants::{DEFAULT_SCOPE, GOOGLE_SCOPE, TOKEN_OPERATION_HEADROOM}; use crate::credential::{Credential, ServiceAccount, Token}; +use crate::jwt::encode_rs256; use super::oauth::{OAUTH_TOKEN_ENDPOINT, checked_expiration, oauth_error, validate_token_uri}; const JWT_BEARER_GRANT_TYPE: &str = "urn:ietf:params:oauth:grant-type:jwt-bearer"; @@ -270,7 +271,13 @@ async fn exchange_service_account_token( let scope = resolve_scope(ctx, scope); debug!("exchanging service account for token with scope: {scope}"); - let request = build_token_request(service_account, &scope, token_uri, Timestamp::now())?; + let request = build_token_request( + ctx.crypto_provider()?, + service_account, + &scope, + token_uri, + Timestamp::now(), + )?; let request_started_at = Timestamp::now(); let response = ctx.http_send(request).await.map_err(|err| { Error::new(err.kind(), "service account OAuth token request failed") @@ -292,12 +299,14 @@ async fn exchange_service_account_token( } fn build_token_request( + provider: &dyn reqsign_core::crypto::CryptoProvider, service_account: &ServiceAccount, scope: &str, token_uri: &str, now: Timestamp, ) -> Result> { - let jwt = reqsign_core::jwt::encode_rs256_pem( + let jwt = encode_rs256( + provider, &JwtHeader::rs256(), &Claims::new(&service_account.client_email, scope, token_uri, now)?, service_account.private_key.as_bytes(), @@ -508,7 +517,7 @@ mod tests { let provider = ServiceAccountTokenCredentialProvider::new(service_account.clone()) .with_scope("scope-a scope-b"); let output = provider - .provide_credential(&Context::new().with_http_send(http.clone())) + .provide_credential(&crate::test_context().with_http_send(http.clone())) .await? .expect("credential must be returned"); @@ -553,7 +562,7 @@ mod tests { #[test] fn scope_precedence_is_explicit_then_environment_then_default() { - let ctx = Context::new().with_env(StaticEnv { + let ctx = crate::test_context().with_env(StaticEnv { home_dir: None, envs: HashMap::from([(GOOGLE_SCOPE.to_string(), "environment-scope".to_string())]), }); @@ -562,13 +571,13 @@ mod tests { "explicit-scope" ); assert_eq!(resolve_scope(&ctx, None), "environment-scope"); - assert_eq!(resolve_scope(&Context::new(), None), DEFAULT_SCOPE); + assert_eq!(resolve_scope(&crate::test_context(), None), DEFAULT_SCOPE); } #[tokio::test] async fn rejects_invalid_source_before_oauth_io_and_preserves_none() -> Result<()> { let http = MockHttpSend::default(); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let missing = ServiceAccountTokenCredentialProvider::from_provider(FixedProvider { credential: None, @@ -606,7 +615,7 @@ mod tests { let content = service_account_json(&service_account).into_bytes(); let file_http = MockHttpSend::new([oauth_success("file-token", 3600)]); - let file_context = Context::new() + let file_context = crate::test_context() .with_file_read(FixedFileRead::new(content.clone())) .with_http_send(file_http); let file_output = ServiceAccountTokenCredentialProvider::from_provider( @@ -624,7 +633,7 @@ mod tests { ); let default_http = MockHttpSend::new([oauth_success("default-token", 3600)]); - let default_context = Context::new() + let default_context = crate::test_context() .with_file_read(FixedFileRead::new(content)) .with_http_send(default_http) .with_env(StaticEnv { @@ -653,7 +662,7 @@ mod tests { async fn rejects_token_that_is_too_short_after_oauth_io() { let http = MockHttpSend::new([oauth_success("short-token", 5)]); let err = ServiceAccountTokenCredentialProvider::new(service_account()) - .provide_credential(&Context::new().with_http_send(http.clone())) + .provide_credential(&crate::test_context().with_http_send(http.clone())) .await .expect_err("short OAuth token must be rejected"); @@ -716,7 +725,7 @@ mod tests { }"#; let http = MockHttpSend::new([response(http::StatusCode::BAD_REQUEST, body.as_slice())]); let err = provider - .provide_credential(&Context::new().with_http_send(http)) + .provide_credential(&crate::test_context().with_http_send(http)) .await .expect_err("OAuth error must be returned"); assert_eq!(err.kind(), ErrorKind::CredentialInvalid); @@ -743,7 +752,7 @@ mod tests { CredentialAccessBoundaryPermissions::OBJECT_VIEWER, ); let output = Granter::new( - Context::new().with_http_send(http.clone()), + crate::test_context().with_http_send(http.clone()), source, ServerSideCredentialAccessBoundaryGranter::new(grant), ) diff --git a/services/google/src/provide_credential/static_provider.rs b/services/google/src/provide_credential/static_provider.rs index fc241b1f..e4c6093b 100644 --- a/services/google/src/provide_credential/static_provider.rs +++ b/services/google/src/provide_credential/static_provider.rs @@ -78,8 +78,6 @@ impl ProvideCredential for StaticCredentialProvider { #[cfg(test)] mod tests { use super::*; - use reqsign_core::Context; - #[tokio::test] async fn test_static_service_account() { let content = r#"{ @@ -89,7 +87,7 @@ mod tests { }"#; let provider = StaticCredentialProvider::new(content); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(reqsign_file_read_tokio::TokioFileRead) .with_http_send(reqsign_http_send_reqwest::ReqwestHttpSend::default()); @@ -117,7 +115,7 @@ mod tests { let provider = StaticCredentialProvider::from_base64(encoded).expect("should decode base64"); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(reqsign_file_read_tokio::TokioFileRead) .with_http_send(reqsign_http_send_reqwest::ReqwestHttpSend::default()); diff --git a/services/google/src/provide_credential/vm_metadata.rs b/services/google/src/provide_credential/vm_metadata.rs index 53f8ac53..b484e912 100644 --- a/services/google/src/provide_credential/vm_metadata.rs +++ b/services/google/src/provide_credential/vm_metadata.rs @@ -158,7 +158,7 @@ mod tests { #[tokio::test] async fn test_vm_metadata_uses_default_service_account() -> Result<()> { let http = MockHttpSend::default(); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let provider = VmMetadataCredentialProvider::new().with_endpoint("127.0.0.1:8080"); let cred = provider @@ -183,7 +183,7 @@ mod tests { #[tokio::test] async fn test_vm_metadata_uses_configured_service_account() -> Result<()> { let http = MockHttpSend::default(); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let provider = VmMetadataCredentialProvider::new() .with_endpoint("127.0.0.1:8080") diff --git a/services/google/src/service_account_impersonation.rs b/services/google/src/service_account_impersonation.rs index 7036651d..a15e39a2 100644 --- a/services/google/src/service_account_impersonation.rs +++ b/services/google/src/service_account_impersonation.rs @@ -673,7 +673,7 @@ mod tests { let credential = granter .grant_credential( - &Context::new().with_http_send(http.clone()), + &crate::test_context().with_http_send(http.clone()), &source("2026-09-02T02:00:00Z"), Some(Duration::from_millis(3_600_500)), ) @@ -745,7 +745,7 @@ mod tests { async fn rejects_invalid_input_before_iam_io() { let now = timestamp("2026-09-02T00:00:00Z"); let http = MockHttpSend::new([]); - let context = Context::new().with_http_send(http.clone()); + let context = crate::test_context().with_http_send(http.clone()); let invalid_cases = [ ( @@ -835,7 +835,7 @@ mod tests { iam_success_response("impersonated-token", "2026-09-02T01:00:00Z"), iam_success_response("impersonated-token", "2026-09-02T00:00:25Z"), ]); - let context = Context::new().with_http_send(http); + let context = crate::test_context().with_http_send(http); let source_expired = ServiceAccountImpersonationGranter::new(grant()) .with_time(now) @@ -877,7 +877,7 @@ mod tests { let error = ServiceAccountImpersonationGranter::new(grant) .with_time(timestamp("2026-09-02T00:00:00Z")) .grant_credential( - &Context::new().with_http_send(http), + &crate::test_context().with_http_send(http), &source("2026-09-02T02:00:00Z"), None, ) @@ -901,7 +901,7 @@ mod tests { iam_success_response("first-token", "2100-01-01T00:00:00Z"), iam_success_response("second-token", "2100-01-01T00:00:00Z"), ]); - let context = Context::new().with_http_send(http.clone()); + let context = crate::test_context().with_http_send(http.clone()); let granter = Granter::new( context, provider, @@ -933,7 +933,7 @@ mod tests { grant(), ); let credential = wrapper - .provide_credential(&Context::new().with_http_send(wrapper_http.clone())) + .provide_credential(&crate::test_context().with_http_send(wrapper_http.clone())) .await? .expect("provider must return an impersonated credential"); assert_eq!( @@ -958,7 +958,7 @@ mod tests { ); assert!( empty_provider - .provide_credential(&Context::new()) + .provide_credential(&crate::test_context()) .await? .is_none() ); @@ -978,7 +978,7 @@ mod tests { let error = ServiceAccountImpersonationGranter::new(grant()) .with_time(timestamp("2026-09-02T00:00:00Z")) .grant_credential( - &Context::new().with_http_send(http), + &crate::test_context().with_http_send(http), &source("2026-09-02T02:00:00Z"), None, ) diff --git a/services/google/src/sign_request.rs b/services/google/src/sign_request.rs index 164883a5..5b124e3d 100644 --- a/services/google/src/sign_request.rs +++ b/services/google/src/sign_request.rs @@ -20,10 +20,6 @@ use form_urlencoded::Serializer; use http::{Uri, header}; use log::debug; use percent_encoding::{percent_decode_str, utf8_percent_encode}; -use rsa::pkcs1v15::SigningKey; -use rsa::pkcs8::DecodePrivateKey; -use rsa::rand_core::OsRng; -use rsa::signature::RandomizedSigner; use serde::{Deserialize, Serialize}; use std::collections::VecDeque; use std::fmt::{self, Debug, Formatter}; @@ -31,7 +27,8 @@ use std::sync::{Arc, Mutex as SyncMutex, Weak}; use std::time::Duration; use reqsign_core::{ - Context, Result, SignRequest, SigningCredential, SigningRequest, hash::hex_sha256, time::*, + Context, Result, SignRequest, SigningCredential, SigningRequest, crypto, hash::hex_sha256, + time::*, }; use crate::constants::{ @@ -39,6 +36,7 @@ use crate::constants::{ TOKEN_OPERATION_HEADROOM, }; use crate::credential::{Credential, ServiceAccount, Token}; +use crate::jwt::encode_rs256; use crate::provide_credential::oauth::oauth_error; /// Claims is used to build JWT for Google Cloud. @@ -305,7 +303,7 @@ impl RequestSigner { let scope = self.resolve_scope(ctx); let key = TokenCacheKey { client_email: sa.client_email.clone(), - private_key_hash: hex_sha256(sa.private_key.as_bytes()), + private_key_hash: hex_sha256(ctx.crypto_provider()?, sa.private_key.as_bytes())?, scope: scope.clone(), }; @@ -358,8 +356,10 @@ impl RequestSigner { scope: &str, ) -> Result { debug!("exchanging service account for token with scope: {scope}"); + let provider = ctx.crypto_provider()?; - let jwt = reqsign_core::jwt::encode_rs256_pem( + let jwt = encode_rs256( + provider, &JwtHeader::rs256(), &Claims::new(&sa.client_email, scope), sa.private_key.as_bytes(), @@ -427,6 +427,7 @@ impl RequestSigner { fn build_string_to_sign( &self, + provider: &dyn crypto::CryptoProvider, req: &mut SigningRequest, client_email: &str, now: Timestamp, @@ -445,7 +446,7 @@ impl RequestSigner { let canonical_query = canonicalize_query(req, &authentication_query); let creq = canonical_request_string(req, &canonical_query)?; - let encoded_req = hex_sha256(creq.as_bytes()); + let encoded_req = hex_sha256(provider, creq.as_bytes())?; let scope = format!( "{}/{}/{}/goog4_request", @@ -471,19 +472,20 @@ impl RequestSigner { Ok((string_to_sign, authentication_query)) } - fn sign_with_service_account(private_key_pem: &str, string_to_sign: &str) -> Result { - let mut rng = OsRng; - let private_key = rsa::RsaPrivateKey::from_pkcs8_pem(private_key_pem).map_err(|e| { - reqsign_core::Error::unexpected("failed to parse private key").with_source(e) - })?; - let signing_key = SigningKey::::new(private_key); - let signature = signing_key.sign_with_rng(&mut rng, string_to_sign.as_bytes()); + fn sign_with_service_account( + provider: &dyn crypto::CryptoProvider, + private_key_pem: &str, + string_to_sign: &str, + ) -> Result { + let signature = provider + .rsa_pkcs1v15_sha256_sign(private_key_pem.as_bytes(), string_to_sign.as_bytes())?; - Ok(signature.to_string()) + Ok(hex::encode(signature)) } fn build_signed_query_with_service_account( &self, + provider: &dyn crypto::CryptoProvider, parts: &mut http::request::Parts, service_account: &ServiceAccount, expires_in: Duration, @@ -492,10 +494,18 @@ impl RequestSigner { let mut req = SigningRequest::build(parts)?; let now = Timestamp::now(); - let (string_to_sign, authentication_query) = - self.build_string_to_sign(&mut req, &service_account.client_email, now, expires_in)?; - let signature = - Self::sign_with_service_account(&service_account.private_key, &string_to_sign)?; + let (string_to_sign, authentication_query) = self.build_string_to_sign( + provider, + &mut req, + &service_account.client_email, + now, + expires_in, + )?; + let signature = Self::sign_with_service_account( + provider, + &service_account.private_key, + &string_to_sign, + )?; let unsigned_uri = append_query_pairs(&original_uri, &authentication_query)?; let final_uri = @@ -581,8 +591,13 @@ impl RequestSigner { let mut req = SigningRequest::build(parts)?; let now = Timestamp::now(); - let (string_to_sign, authentication_query) = - self.build_string_to_sign(&mut req, signer_email, now, expires_in)?; + let (string_to_sign, authentication_query) = self.build_string_to_sign( + ctx.crypto_provider()?, + &mut req, + signer_email, + now, + expires_in, + )?; let signature = self .sign_via_iamcredentials(ctx, token, signer_email, string_to_sign.as_bytes()) .await?; @@ -639,8 +654,12 @@ impl SignRequest for RequestSigner { .as_ref() .filter(|service_account| service_account.is_valid()) { - let (signing_req, uri) = - self.build_signed_query_with_service_account(req, sa, expires)?; + let (signing_req, uri) = self.build_signed_query_with_service_account( + ctx.crypto_provider()?, + req, + sa, + expires, + )?; (signing_req, Some(uri)) } else if let (Some(token), Some(signer_email)) = ( cred.token.as_ref(), @@ -891,6 +910,7 @@ mod tests { use http::header; use reqsign_core::{ErrorKind, HttpSend, ProvideCredential, Signer}; use rsa::pkcs8::{EncodePrivateKey, LineEnding}; + use rsa::rand_core::OsRng; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; @@ -1025,7 +1045,7 @@ mod tests { #[tokio::test] async fn test_signed_url_via_iamcredentials_sign_blob() -> Result<()> { let mock_http = MockHttpSend::default(); - let ctx = Context::new().with_http_send(mock_http.clone()); + let ctx = crate::test_context().with_http_send(mock_http.clone()); let signer = RequestSigner::new("storage").with_signer_email("test-signer@example.com"); @@ -1071,7 +1091,9 @@ mod tests { let (mut parts_for_rebuild, _body) = req.into_parts(); let mut signing_req = SigningRequest::build(&mut parts_for_rebuild)?; + let provider = reqsign_crypto_rustcrypto::RustCryptoProvider::new(); let (string_to_sign, authentication_query) = signer.build_string_to_sign( + &provider, &mut signing_req, "test-signer@example.com", now, @@ -1102,7 +1124,7 @@ mod tests { #[tokio::test] async fn query_signing_uses_credential_signer_email() -> Result<()> { let signer_email = "inferred-signer@example.com"; - let ctx = Context::new() + let ctx = crate::test_context() .with_http_send(MockHttpSend::default().with_expected_signer_email(signer_email)); let credential = Credential::with_token(Token { access_token: "test-access-token".to_string(), @@ -1137,7 +1159,7 @@ mod tests { #[tokio::test] async fn explicit_signer_email_overrides_credential_identity() -> Result<()> { let explicit_email = "explicit-signer@example.com"; - let ctx = Context::new() + let ctx = crate::test_context() .with_http_send(MockHttpSend::default().with_expected_signer_email(explicit_email)); let credential = Credential::with_token(Token { access_token: "test-access-token".to_string(), @@ -1174,7 +1196,7 @@ mod tests { async fn signer_refreshes_near_expiry_token_without_binding_it_to_signed_url_lifetime() -> Result<()> { let mock_http = MockHttpSend::default(); - let ctx = Context::new().with_http_send(mock_http); + let ctx = crate::test_context().with_http_send(mock_http); let credential = Credential::with_token(Token { access_token: "test-access-token".to_string(), expires_at: Some(Timestamp::now() + Duration::from_secs(60)), @@ -1230,7 +1252,7 @@ mod tests { .0; signer - .sign_request(&Context::new(), &mut parts, Some(&credential), None) + .sign_request(&crate::test_context(), &mut parts, Some(&credential), None) .await?; assert_eq!(parts.uri.to_string(), original_uri); @@ -1257,7 +1279,7 @@ mod tests { .0; signer - .sign_request(&Context::new(), &mut parts, Some(&credential), None) + .sign_request(&crate::test_context(), &mut parts, Some(&credential), None) .await?; assert_eq!( @@ -1285,7 +1307,7 @@ mod tests { RequestSigner::new("storage") .sign_request( - &Context::new().with_http_send(OAuthTokenHttpSend), + &crate::test_context().with_http_send(OAuthTokenHttpSend), &mut parts, Some(&credential), None, @@ -1309,7 +1331,11 @@ mod tests { credential, calls: calls.clone(), }; - let signer = Signer::new(Context::new(), provider, RequestSigner::new("storage")); + let signer = Signer::new( + crate::test_context(), + provider, + RequestSigner::new("storage"), + ); for _ in 0..2 { let mut parts = http::Request::get("https://storage.googleapis.com/bucket/object") @@ -1342,7 +1368,7 @@ mod tests { let original = parts.clone(); let err = signer - .sign_request(&Context::new(), &mut parts, Some(&credential), None) + .sign_request(&crate::test_context(), &mut parts, Some(&credential), None) .await .expect_err("token must cover the operation headroom"); @@ -1409,7 +1435,7 @@ mod tests { let http = QueuedOAuthHttpSend::new([QueuedOAuthHttpSend::json_response( r#"{"access_token":"cached-sa-token","expires_in":3600}"#, )]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let credential = Credential::with_service_account(test_service_account( "signer@example.iam.gserviceaccount.com", )); @@ -1449,7 +1475,7 @@ mod tests { r#"{"access_token":"fresh-token","expires_in":3600}"#, ), ]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let credential = Credential::with_service_account(test_service_account( "signer@example.iam.gserviceaccount.com", )); @@ -1515,7 +1541,7 @@ mod tests { release: Arc::new(asyncband::semaphore::Semaphore::new(0)), calls: Arc::new(AtomicUsize::new(0)), }; - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let credential = Credential::with_service_account(test_service_account( "signer@example.iam.gserviceaccount.com", )); @@ -1567,7 +1593,7 @@ mod tests { r#"{"access_token":"token-sa2-s1","expires_in":3600}"#, ), ]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let sa1 = Credential::with_service_account(test_service_account( "sa1@example.iam.gserviceaccount.com", )); @@ -1617,7 +1643,7 @@ mod tests { QueuedOAuthHttpSend::json_response(r#"{"access_token":"ephemeral-1"}"#), QueuedOAuthHttpSend::json_response(r#"{"access_token":"ephemeral-2"}"#), ]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let credential = Credential::with_service_account(test_service_account( "signer@example.iam.gserviceaccount.com", )); @@ -1644,7 +1670,7 @@ mod tests { let http = QueuedOAuthHttpSend::new([QueuedOAuthHttpSend::json_response( r#"{"access_token":"short-lived","expires_in":30}"#, )]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let credential = Credential::with_service_account(test_service_account( "signer@example.iam.gserviceaccount.com", )); @@ -1669,7 +1695,7 @@ mod tests { let http = QueuedOAuthHttpSend::new([QueuedOAuthHttpSend::json_response( r#"{"access_token":"too-short","expires_in":5}"#, )]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let credential = Credential::with_service_account(test_service_account( "signer@example.iam.gserviceaccount.com", )); @@ -1716,7 +1742,7 @@ mod tests { release: Arc::new(asyncband::semaphore::Semaphore::new(0)), calls: Arc::new(AtomicUsize::new(0)), }; - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let signer = RequestSigner::new("storage"); let sa_a = Credential::with_service_account(test_service_account( "sa-a@example.iam.gserviceaccount.com", @@ -1783,7 +1809,7 @@ mod tests { r#"{"access_token":"recovered-token","expires_in":3600}"#, ), ]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let credential = Credential::with_service_account(test_service_account( "signer@example.iam.gserviceaccount.com", )); @@ -1841,7 +1867,7 @@ mod tests { release: Arc::new(asyncband::semaphore::Semaphore::new(0)), calls: Arc::new(AtomicUsize::new(0)), }; - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let credential = Credential::with_service_account(test_service_account( "signer@example.iam.gserviceaccount.com", )); @@ -1906,7 +1932,7 @@ mod tests { r#"{"access_token":"env-scope-token","expires_in":3600}"#, ), ]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let email = "same-email@example.iam.gserviceaccount.com"; let key_1 = Credential::with_service_account(test_service_account(email)); let key_2 = Credential::with_service_account(test_service_account(email)); @@ -1927,7 +1953,7 @@ mod tests { assert_eq!(parts.headers[header::AUTHORIZATION], "Bearer key-2-token"); let env_ctx = - Context::new() + crate::test_context() .with_http_send(http.clone()) .with_env(reqsign_core::StaticEnv { home_dir: None, @@ -1952,7 +1978,7 @@ mod tests { let http = QueuedOAuthHttpSend::new([QueuedOAuthHttpSend::json_response( r#"{"access_token":"exchanged-from-expired","expires_in":3600}"#, )]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let credential = Credential { service_account: Some(test_service_account( "signer@example.iam.gserviceaccount.com", @@ -1988,7 +2014,7 @@ mod tests { async fn query_signing_with_service_account_stays_offline_and_bypasses_token_cache() -> Result<()> { let http = QueuedOAuthHttpSend::new([]); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::test_context().with_http_send(http.clone()); let credential = Credential::with_service_account(test_service_account( "signer@example.iam.gserviceaccount.com", )); diff --git a/services/google/tests/common/mod.rs b/services/google/tests/common/mod.rs new file mode 100644 index 00000000..e0593842 --- /dev/null +++ b/services/google/tests/common/mod.rs @@ -0,0 +1,23 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use reqsign_core::Context; + +#[allow(dead_code)] +pub fn test_context() -> Context { + Context::new().with_crypto(reqsign_crypto_rustcrypto::RustCryptoProvider::new()) +} diff --git a/services/google/tests/credential_access_boundary.rs b/services/google/tests/credential_access_boundary.rs index 25d17d2e..6b23fee7 100644 --- a/services/google/tests/credential_access_boundary.rs +++ b/services/google/tests/credential_access_boundary.rs @@ -17,11 +17,13 @@ #![cfg(feature = "credential-access-boundary-client-side")] +mod common; + use std::env; use log::warn; use reqsign_core::time::Timestamp; -use reqsign_core::{Context, Granter, Result, Signer}; +use reqsign_core::{Granter, Result, Signer}; use reqsign_google::{ ClientSideCredentialAccessBoundaryGranter, CredentialAccessBoundaryGrant, CredentialAccessBoundaryPermissions, RequestSigner, TokenCredentialProvider, @@ -48,7 +50,7 @@ async fn test_client_side_credential_access_boundary_live_interoperability() -> let object_prefix = env::var("REQSIGN_GOOGLE_CAB_OBJECT_PREFIX") .expect("REQSIGN_GOOGLE_CAB_OBJECT_PREFIX must be set"); - let context = Context::new().with_http_send(ReqwestHttpSend::default()); + let context = crate::common::test_context().with_http_send(ReqwestHttpSend::default()); let grant = CredentialAccessBoundaryGrant::for_object_prefix( &bucket, &object_prefix, @@ -68,7 +70,7 @@ async fn test_client_side_credential_access_boundary_live_interoperability() -> .expires_at .expect("client-side CAB output must have an expiration"); let signer = Signer::new( - Context::new(), + crate::common::test_context(), TokenCredentialProvider::new(token.access_token).with_expires_at(expires_at), RequestSigner::new("storage"), ); diff --git a/services/google/tests/credential_providers/mod.rs b/services/google/tests/credential_providers/mod.rs index ca448c27..07c2660f 100644 --- a/services/google/tests/credential_providers/mod.rs +++ b/services/google/tests/credential_providers/mod.rs @@ -39,7 +39,7 @@ pub fn create_test_context() -> Context { let _ = env_logger::builder().is_test(true).try_init(); let _ = dotenvy::dotenv(); - Context::new() + crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv) @@ -55,7 +55,7 @@ pub fn create_test_context_with_env(mut envs: HashMap) -> Contex .or_insert_with(|| home.to_string_lossy().into_owned()); } - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); diff --git a/services/google/tests/explicit_credential_access_boundary.rs b/services/google/tests/explicit_credential_access_boundary.rs index 122217c5..1ffa91de 100644 --- a/services/google/tests/explicit_credential_access_boundary.rs +++ b/services/google/tests/explicit_credential_access_boundary.rs @@ -15,13 +15,15 @@ // specific language governing permissions and limitations // under the License. +mod common; + use std::collections::BTreeMap; use std::fmt::{self, Debug}; use std::sync::{Arc, Mutex}; use std::time::Duration; use bytes::Bytes; -use reqsign_core::{Context, ErrorKind, Granter, HttpSend, Result, time::Timestamp}; +use reqsign_core::{ErrorKind, Granter, HttpSend, Result, time::Timestamp}; use reqsign_google::{ CredentialAccessBoundaryGrant, CredentialAccessBoundaryPermissions, CredentialAccessBoundaryRule, ServerSideCredentialAccessBoundaryGranter, @@ -90,7 +92,7 @@ async fn exchanges_caller_policy_without_changing_roles_or_prefixes() -> Result< ); } let output = Granter::new( - Context::new().with_http_send(http.clone()), + crate::common::test_context().with_http_send(http.clone()), source(expires_at), ServerSideCredentialAccessBoundaryGranter::new(grant.clone()), ) @@ -191,7 +193,7 @@ async fn rejects_invalid_explicit_rules_before_sts_io() { let http = MockSts::default(); for grant in invalid { let err = Granter::new( - Context::new().with_http_send(http.clone()), + crate::common::test_context().with_http_send(http.clone()), source(Timestamp::now() + Duration::from_secs(600)), ServerSideCredentialAccessBoundaryGranter::new(grant), ) @@ -217,7 +219,7 @@ async fn combines_custom_roles_and_typed_rules_without_normalization() -> Result ) .with_rule(CredentialAccessBoundaryRule::new("example-bucket", roles)); Granter::new( - Context::new().with_http_send(http.clone()), + crate::common::test_context().with_http_send(http.clone()), source(Timestamp::now() + Duration::from_secs(600)), ServerSideCredentialAccessBoundaryGranter::new(grant), ) @@ -249,7 +251,7 @@ async fn client_side_rejects_explicit_conditions_before_io() { .with_condition(CONDITION), ); let err = Granter::new( - Context::new().with_http_send(http.clone()), + crate::common::test_context().with_http_send(http.clone()), source(Timestamp::now() + Duration::from_secs(3600)), ClientSideCredentialAccessBoundaryGranter::new(grant), ) diff --git a/services/google/tests/fixtures.rs b/services/google/tests/fixtures.rs index 73fe8b09..b6d8cb20 100644 --- a/services/google/tests/fixtures.rs +++ b/services/google/tests/fixtures.rs @@ -15,6 +15,8 @@ // specific language governing permissions and limitations // under the License. +mod common; + use std::fs; use std::path::Path; diff --git a/services/google/tests/main.rs b/services/google/tests/main.rs index 6d99c322..82413a47 100644 --- a/services/google/tests/main.rs +++ b/services/google/tests/main.rs @@ -15,5 +15,7 @@ // specific language governing permissions and limitations // under the License. +mod common; + mod credential_providers; mod signing; diff --git a/services/google/tests/oauth_token_endpoint.rs b/services/google/tests/oauth_token_endpoint.rs index e7b6db05..05bf39f6 100644 --- a/services/google/tests/oauth_token_endpoint.rs +++ b/services/google/tests/oauth_token_endpoint.rs @@ -15,12 +15,14 @@ // specific language governing permissions and limitations // under the License. +mod common; + use std::sync::{Arc, Mutex, OnceLock}; use bytes::Bytes; use http::{Request, Response, StatusCode}; use reqsign_core::hash::base64_decode; -use reqsign_core::{Context, Error, ErrorKind, Granter, HttpSend, ProvideCredential, Result}; +use reqsign_core::{Error, ErrorKind, Granter, HttpSend, ProvideCredential, Result}; use reqsign_google::{ AuthorizedUserCredentialProvider, CredentialAccessBoundaryGrant, CredentialAccessBoundaryPermissions, OAuth2Credentials, @@ -114,7 +116,7 @@ async fn service_account_uses_selected_uri_for_request_and_audience_on_each_exch { for uri in [None, Some(CUSTOM_URI), Some("http://127.0.0.1:8765/token")] { let http = MockHttp::default(); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::common::test_context().with_http_send(http.clone()); let mut provider = ServiceAccountTokenCredentialProvider::new(service_account()) .with_scope("scope-a scope-b"); if let Some(uri) = uri { @@ -152,7 +154,7 @@ async fn service_account_uses_selected_uri_for_request_and_audience_on_each_exch async fn authorized_user_uses_selected_uri_and_preserves_refresh_fields() -> Result<()> { for uri in [None, Some(CUSTOM_URI), Some("http://[::1]:8765/token")] { let http = MockHttp::default(); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::common::test_context().with_http_send(http.clone()); let mut provider = AuthorizedUserCredentialProvider::new(oauth_credentials()); if let Some(uri) = uri { provider = provider.with_token_uri(uri)?; @@ -220,7 +222,7 @@ async fn adapter_selects_explicit_configuration_then_file_uri_then_default() -> user = user.with_token_uri(uri)?; } let http = MockHttp::default(); - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::common::test_context().with_http_send(http.clone()); service.provide_credential(&ctx).await?; user.provide_credential(&ctx).await?; @@ -301,7 +303,7 @@ async fn failures_are_redacted_and_do_not_fall_back() -> Result<()> { br#"{"access_token":"access-secret","expires_in":18446744073709551615}"#, )), ..Default::default() }, ] { - let ctx = Context::new().with_http_send(http.clone()); + let ctx = crate::common::test_context().with_http_send(http.clone()); let errors = [service.provide_credential(&ctx).await.unwrap_err(), user.provide_credential(&ctx).await.unwrap_err()]; for error in errors { let rendered = format!("{error} {error:?}"); @@ -330,7 +332,7 @@ async fn custom_oauth_sources_compose_with_existing_granter() -> Result<()> { CredentialAccessBoundaryPermissions::OBJECT_VIEWER, ); let output = Granter::new( - Context::new().with_http_send(http.clone()), + crate::common::test_context().with_http_send(http.clone()), source, ServerSideCredentialAccessBoundaryGranter::new(grant), ) diff --git a/services/google/tests/service_account_token.rs b/services/google/tests/service_account_token.rs index d6d02b6a..2ca8db56 100644 --- a/services/google/tests/service_account_token.rs +++ b/services/google/tests/service_account_token.rs @@ -15,10 +15,12 @@ // specific language governing permissions and limitations // under the License. +mod common; + use std::env; use log::warn; -use reqsign_core::{Context, Granter, Result, Signer}; +use reqsign_core::{Granter, Result, Signer}; use reqsign_google::{ CredentialAccessBoundaryGrant, CredentialAccessBoundaryPermissions, RequestSigner, ServerSideCredentialAccessBoundaryGranter, ServiceAccountTokenCredentialProvider, @@ -52,7 +54,7 @@ async fn test_service_account_token_provider_with_server_side_cab_live_interoper CredentialAccessBoundaryPermissions::OBJECT_VIEWER, ); let downscoped = Granter::new( - Context::new().with_http_send(ReqwestHttpSend::default()), + crate::common::test_context().with_http_send(ReqwestHttpSend::default()), source, ServerSideCredentialAccessBoundaryGranter::new(grant), ) @@ -65,7 +67,7 @@ async fn test_service_account_token_provider_with_server_side_cab_live_interoper .expires_at .expect("server-side CAB output must have an expiration"); let signer = Signer::new( - Context::new(), + crate::common::test_context(), TokenCredentialProvider::new(token.access_token).with_expires_at(expires_at), RequestSigner::new("storage"), ); diff --git a/services/google/tests/signing/signed_url.rs b/services/google/tests/signing/signed_url.rs index 1a531ca4..f4a61747 100644 --- a/services/google/tests/signing/signed_url.rs +++ b/services/google/tests/signing/signed_url.rs @@ -41,7 +41,7 @@ async fn init_signer_for_signed_url() -> Option<(Context, Signer)> { .expect("credential must be valid base64"); let builder = RequestSigner::new("storage"); - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); diff --git a/services/google/tests/signing/standard.rs b/services/google/tests/signing/standard.rs index e9ced1e7..3c43ba50 100644 --- a/services/google/tests/signing/standard.rs +++ b/services/google/tests/signing/standard.rs @@ -42,7 +42,7 @@ async fn init_signer() -> Option<(Context, Signer)> { .with_scope(&scope); let builder = RequestSigner::new("storage").with_scope(&scope); - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); diff --git a/services/huaweicloud-obs/Cargo.toml b/services/huaweicloud-obs/Cargo.toml index 15c5cbdc..e93bd3bc 100644 --- a/services/huaweicloud-obs/Cargo.toml +++ b/services/huaweicloud-obs/Cargo.toml @@ -36,6 +36,7 @@ serde = { workspace = true } serde_json = { workspace = true } [dev-dependencies] +reqsign-crypto-rustcrypto = { workspace = true } bytes = { workspace = true } env_logger = { workspace = true } reqsign-file-read-tokio = { workspace = true } diff --git a/services/huaweicloud-obs/README.md b/services/huaweicloud-obs/README.md index 1855cd12..40f92a24 100644 --- a/services/huaweicloud-obs/README.md +++ b/services/huaweicloud-obs/README.md @@ -21,13 +21,20 @@ credentials through `Granter`. The result carries the exact IAM credentials are rejected by header signing or presigning when they do not cover the requested operation deadline. +> Signing needs a `CryptoProvider` resolved through the `Context`: bind one with +> `Context::with_crypto`, install a process-wide default, or use a facade +> `default_context()` (which binds RustCrypto when the global slot is empty). A +> bare `Context::new()` starts unbound. See +> [CryptoProvider](https://github.com/apache/reqsign/blob/main/docs/crypto-provider.md). + ## Quick Start ```rust,no_run +use reqsign_crypto_rustcrypto::RustCryptoProvider; use reqsign_core::{Context, OsEnv, Signer}; use reqsign_huaweicloud_obs::{DefaultCredentialProvider, RequestSigner}; -let context = Context::new().with_env(OsEnv); +let context = Context::new().with_crypto(RustCryptoProvider::new()).with_env(OsEnv); let signer = Signer::new( context, DefaultCredentialProvider::new(), diff --git a/services/huaweicloud-obs/examples/chain_logging.rs b/services/huaweicloud-obs/examples/chain_logging.rs index fb288e2c..f7b9c9f0 100644 --- a/services/huaweicloud-obs/examples/chain_logging.rs +++ b/services/huaweicloud-obs/examples/chain_logging.rs @@ -18,6 +18,7 @@ //! Example of using ProvideCredentialChain with logging to see credential resolution use log::{debug, info}; use reqsign_core::{Context, OsEnv, ProvideCredential, ProvideCredentialChain, Result}; +use reqsign_crypto_rustcrypto::RustCryptoProvider; use reqsign_file_read_tokio::TokioFileRead; use reqsign_http_send_reqwest::ReqwestHttpSend; use reqsign_huaweicloud_obs::{ @@ -78,6 +79,7 @@ async fn main() -> Result<()> { // Create context let ctx = Context::new() + .with_crypto(RustCryptoProvider::new()) .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); diff --git a/services/huaweicloud-obs/examples/custom_chain.rs b/services/huaweicloud-obs/examples/custom_chain.rs index fdc6fa65..958a7ad1 100644 --- a/services/huaweicloud-obs/examples/custom_chain.rs +++ b/services/huaweicloud-obs/examples/custom_chain.rs @@ -17,6 +17,7 @@ //! Example of building a custom credential chain with specific providers use reqsign_core::{Context, OsEnv, ProvideCredential, ProvideCredentialChain, Result}; +use reqsign_crypto_rustcrypto::RustCryptoProvider; use reqsign_file_read_tokio::TokioFileRead; use reqsign_http_send_reqwest::ReqwestHttpSend; use reqsign_huaweicloud_obs::Credential; @@ -80,6 +81,7 @@ impl ProvideCredential for EnvCredentialProvider { async fn main() -> Result<()> { // Create context let ctx = Context::new() + .with_crypto(RustCryptoProvider::new()) .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); diff --git a/services/huaweicloud-obs/src/agency.rs b/services/huaweicloud-obs/src/agency.rs index b1cc4854..6d145872 100644 --- a/services/huaweicloud-obs/src/agency.rs +++ b/services/huaweicloud-obs/src/agency.rs @@ -34,6 +34,7 @@ use std::fmt::{Debug, Formatter}; use std::time::Duration; use http::header::{AUTHORIZATION, CONTENT_TYPE}; +use reqsign_core::crypto::CryptoProvider; use reqsign_core::hash::{hex_hmac_sha256, hex_sha256}; use reqsign_core::time::Timestamp; use reqsign_core::{Context, Error, GrantCredential, Result, SigningCredential}; @@ -312,6 +313,7 @@ impl AgencyGranter { fn build_request( &self, + provider: &dyn CryptoProvider, credential: &Credential, duration_seconds: Option, signing_time: Timestamp, @@ -345,6 +347,7 @@ impl AgencyGranter { signed_headers.insert(X_SECURITY_TOKEN.to_string(), token.trim().to_string()); } let authorization = authorization_header( + provider, http::Method::POST.as_str(), IAM_SECURITY_TOKENS_PATH, "", @@ -459,7 +462,12 @@ impl GrantCredential for AgencyGranter { let required_until = self.required_valid_until(credential, expires_in); self.validate_source(credential, required_until)?; - let request = self.build_request(credential, duration_seconds, self.now())?; + let request = self.build_request( + ctx.crypto_provider()?, + credential, + duration_seconds, + self.now(), + )?; let response = ctx .http_send(request.map(Into::into)) .await @@ -476,7 +484,9 @@ struct ValidatedEndpoint { authority: String, } +#[allow(clippy::too_many_arguments)] fn authorization_header( + provider: &dyn CryptoProvider, method: &str, path: &str, query: &str, @@ -507,16 +517,20 @@ fn authorization_header( let canonical_request = format!( "{method}\n{canonical_uri}\n{query}\n{canonical_headers}\n{signed_headers}\n{}", - hex_sha256(body) + hex_sha256(provider, body)? ); let signing_date = normalized_headers.get(X_SDK_DATE).ok_or_else(|| { Error::request_invalid("Huawei Cloud IAM request is missing the X-Sdk-Date header") })?; let string_to_sign = format!( "{SDK_HMAC_SHA256}\n{signing_date}\n{}", - hex_sha256(canonical_request.as_bytes()) + hex_sha256(provider, canonical_request.as_bytes())? ); - let signature = hex_hmac_sha256(secret_access_key.as_bytes(), string_to_sign.as_bytes()); + let signature = hex_hmac_sha256( + provider, + secret_access_key.as_bytes(), + string_to_sign.as_bytes(), + )?; Ok(format!( "{SDK_HMAC_SHA256} Access={access_key_id}, SignedHeaders={signed_headers}, Signature={signature}" @@ -746,7 +760,7 @@ mod tests { #[tokio::test] async fn grants_exact_request_and_returns_issued_expiry() { let http = MockHttpSend::new([success_response()]); - let context = Context::new().with_http_send(http.clone()); + let context = crate::test_context().with_http_send(http.clone()); let (provider, provider_calls) = FixedCredentialProvider::new(source_credential(Some(SOURCE_SECURITY_TOKEN), None)); let granter = Granter::new( @@ -831,7 +845,7 @@ mod tests { let (issued_provider, _) = FixedCredentialProvider::new(credential.clone()); let signer = Signer::new( - Context::new(), + crate::test_context(), issued_provider, crate::RequestSigner::new("bucket").with_time(signing_time()), ); @@ -866,7 +880,7 @@ mod tests { #[tokio::test] async fn supports_permanent_source_and_domain_name() { let http = MockHttpSend::new([success_response()]); - let context = Context::new().with_http_send(http.clone()); + let context = crate::test_context().with_http_send(http.clone()); let (provider, _) = FixedCredentialProvider::new(source_credential(None, None)); let granter = Granter::new( context, @@ -898,7 +912,7 @@ mod tests { #[tokio::test] async fn rejects_invalid_duration_before_io() { let http = MockHttpSend::new([]); - let context = Context::new().with_http_send(http.clone()); + let context = crate::test_context().with_http_send(http.clone()); let (provider, _) = FixedCredentialProvider::new(source_credential(None, None)); let granter = Granter::new( context, @@ -924,7 +938,7 @@ mod tests { #[tokio::test] async fn rejects_expired_source_before_io() { let http = MockHttpSend::new([]); - let context = Context::new().with_http_send(http.clone()); + let context = crate::test_context().with_http_send(http.clone()); let (provider, _) = FixedCredentialProvider::new(source_credential( None, Some(signing_time() - Duration::from_secs(1)), @@ -951,7 +965,7 @@ mod tests { br#"{"error_msg":"source-secret-key granted-secret-key source-security-token"}"#, )) .expect("response must build")]); - let context = Context::new().with_http_send(http.clone()); + let context = crate::test_context().with_http_send(http.clone()); let (provider, _) = FixedCredentialProvider::new(source_credential(Some(SOURCE_SECURITY_TOKEN), None)); let granter = Granter::new( @@ -977,7 +991,7 @@ mod tests { #[tokio::test] async fn rejects_response_expired_after_io() { let http = MockHttpSend::new([success_response_with_expiry("2026-11-19T08:00:00Z")]); - let context = Context::new().with_http_send(http.clone()); + let context = crate::test_context().with_http_send(http.clone()); let (provider, _) = FixedCredentialProvider::new(source_credential(Some(SOURCE_SECURITY_TOKEN), None)); let granter = Granter::new( @@ -1004,6 +1018,7 @@ mod tests { let headers = BTreeMap::from([("x-sdk-date".to_string(), "20060102T150405Z".to_string())]); let authorization = authorization_header( + &reqsign_crypto_rustcrypto::RustCryptoProvider::new(), "GET", "/path", "limit=1", diff --git a/services/huaweicloud-obs/src/credential.rs b/services/huaweicloud-obs/src/credential.rs index ef60cedb..5db33783 100644 --- a/services/huaweicloud-obs/src/credential.rs +++ b/services/huaweicloud-obs/src/credential.rs @@ -91,7 +91,7 @@ mod tests { use std::str::FromStr; use http::Uri; - use reqsign_core::{Context, Result, SignRequest}; + use reqsign_core::{Result, SignRequest}; use super::*; use crate::RequestSigner; @@ -163,7 +163,7 @@ mod tests { .into_parts() .0; signer - .sign_request(&Context::new(), &mut parts, Some(&active), None) + .sign_request(&crate::test_context(), &mut parts, Some(&active), None) .await?; let mut query_parts = http::Request::get(Uri::from_str(request)?) @@ -172,7 +172,7 @@ mod tests { .0; signer .sign_request( - &Context::new(), + &crate::test_context(), &mut query_parts, Some(&active), Some(Duration::from_secs(10)), @@ -191,7 +191,12 @@ mod tests { .into_parts() .0; signer - .sign_request(&Context::new(), &mut expired_parts, Some(&expired), None) + .sign_request( + &crate::test_context(), + &mut expired_parts, + Some(&expired), + None, + ) .await .expect_err("expired credentials must not sign headers"); diff --git a/services/huaweicloud-obs/src/lib.rs b/services/huaweicloud-obs/src/lib.rs index 955fdda5..2cfc51ff 100644 --- a/services/huaweicloud-obs/src/lib.rs +++ b/services/huaweicloud-obs/src/lib.rs @@ -30,3 +30,8 @@ mod provide_credential; pub use provide_credential::*; mod constants; + +#[cfg(test)] +pub(crate) fn test_context() -> reqsign_core::Context { + reqsign_core::Context::new().with_crypto(reqsign_crypto_rustcrypto::RustCryptoProvider::new()) +} diff --git a/services/huaweicloud-obs/src/provide_credential/default.rs b/services/huaweicloud-obs/src/provide_credential/default.rs index 2fc74a40..70135fa7 100644 --- a/services/huaweicloud-obs/src/provide_credential/default.rs +++ b/services/huaweicloud-obs/src/provide_credential/default.rs @@ -149,7 +149,7 @@ mod tests { #[tokio::test] async fn test_default_loader_without_env() { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()); let ctx = ctx.with_env(StaticEnv { @@ -165,7 +165,7 @@ mod tests { #[tokio::test] async fn test_builder_no_env_removes_provider() { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()); let ctx = ctx.with_env(StaticEnv { @@ -190,7 +190,7 @@ mod tests { #[tokio::test] async fn test_builder_env_readds_provider_after_no_env() { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()); let ctx = ctx.with_env(StaticEnv { @@ -219,7 +219,7 @@ mod tests { #[tokio::test] async fn test_default_loader_with_env() { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()); let ctx = ctx.with_env(StaticEnv { @@ -245,7 +245,7 @@ mod tests { #[tokio::test] async fn test_default_loader_with_security_token() { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()); let ctx = ctx.with_env(StaticEnv { diff --git a/services/huaweicloud-obs/src/provide_credential/env.rs b/services/huaweicloud-obs/src/provide_credential/env.rs index 93d4cd6b..c318b1a6 100644 --- a/services/huaweicloud-obs/src/provide_credential/env.rs +++ b/services/huaweicloud-obs/src/provide_credential/env.rs @@ -74,7 +74,7 @@ mod tests { ), ]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(StaticEnv { @@ -110,7 +110,7 @@ mod tests { ), ]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(StaticEnv { @@ -131,7 +131,7 @@ mod tests { #[tokio::test] async fn test_env_credential_provider_missing_credentials() -> anyhow::Result<()> { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()); @@ -150,7 +150,7 @@ mod tests { "test_access_key".to_string(), )]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(StaticEnv { diff --git a/services/huaweicloud-obs/src/provide_credential/static.rs b/services/huaweicloud-obs/src/provide_credential/static.rs index 13febb9b..805720ba 100644 --- a/services/huaweicloud-obs/src/provide_credential/static.rs +++ b/services/huaweicloud-obs/src/provide_credential/static.rs @@ -67,7 +67,7 @@ mod tests { #[tokio::test] async fn test_static_credential_provider() -> anyhow::Result<()> { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()); diff --git a/services/huaweicloud-obs/src/sign_request.rs b/services/huaweicloud-obs/src/sign_request.rs index cb1efb65..c038c4cb 100644 --- a/services/huaweicloud-obs/src/sign_request.rs +++ b/services/huaweicloud-obs/src/sign_request.rs @@ -97,7 +97,7 @@ impl SignRequest for RequestSigner { async fn sign_request( &self, - _ctx: &reqsign_core::Context, + ctx: &reqsign_core::Context, parts: &mut http::request::Parts, credential: Option<&Self::Credential>, expires_in: Option, @@ -105,6 +105,7 @@ impl SignRequest for RequestSigner { let Some(cred) = credential else { return Ok(()); }; + let provider = ctx.crypto_provider()?; let now = self.get_time(); let required_until = self.required_valid_until_at(now, expires_in); @@ -124,8 +125,11 @@ impl SignRequest for RequestSigner { let mut ctx = SigningRequest::build(parts)?; let string_to_sign = string_to_sign(&mut ctx, cred, now, method, &self.bucket)?; - let signature = - base64_hmac_sha1(cred.secret_access_key.as_bytes(), string_to_sign.as_bytes()); + let signature = base64_hmac_sha1( + provider, + cred.secret_access_key.as_bytes(), + string_to_sign.as_bytes(), + )?; let final_uri = match method { SigningMethod::Header => { @@ -360,7 +364,7 @@ mod tests { use http::Uri; use http::header::HeaderName; use reqsign_core::Result; - use reqsign_core::{Context, OsEnv, Signer}; + use reqsign_core::{OsEnv, Signer}; use reqsign_file_read_tokio::TokioFileRead; use reqsign_http_send_reqwest::ReqwestHttpSend; @@ -442,7 +446,7 @@ mod tests { start_log_capture(); signer - .sign_request(&Context::new(), &mut parts, Some(&credential), None) + .sign_request(&crate::test_context(), &mut parts, Some(&credential), None) .await?; assert!(!captured_logs().contains(TOKEN)); @@ -459,7 +463,7 @@ mod tests { let builder = RequestSigner::new("bucket") .with_time(Timestamp::parse_rfc2822("Mon, 15 Aug 2022 16:50:12 GMT")?); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -498,7 +502,7 @@ mod tests { let builder = RequestSigner::new("bucket") .with_time(Timestamp::parse_rfc2822("Mon, 15 Aug 2022 16:50:12 GMT")?); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -539,7 +543,7 @@ mod tests { let builder = RequestSigner::new("bucket") .with_time(Timestamp::parse_rfc2822("Mon, 15 Aug 2022 16:50:12 GMT")?); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -594,14 +598,19 @@ mod tests { let mut header_parts = http::Request::get(&original_uri).body(())?.into_parts().0; signer - .sign_request(&Context::new(), &mut header_parts, Some(&credential), None) + .sign_request( + &crate::test_context(), + &mut header_parts, + Some(&credential), + None, + ) .await?; assert_eq!(header_parts.uri.to_string(), original_uri); let mut query_parts = http::Request::get(&original_uri).body(())?.into_parts().0; signer .sign_request( - &Context::new(), + &crate::test_context(), &mut query_parts, Some(&credential), Some(Duration::from_secs(60)), diff --git a/services/huaweicloud-obs/tests/common/mod.rs b/services/huaweicloud-obs/tests/common/mod.rs new file mode 100644 index 00000000..864b1164 --- /dev/null +++ b/services/huaweicloud-obs/tests/common/mod.rs @@ -0,0 +1,22 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use reqsign_core::Context; + +pub fn test_context() -> Context { + Context::new().with_crypto(reqsign_crypto_rustcrypto::RustCryptoProvider::new()) +} diff --git a/services/huaweicloud-obs/tests/credential_chain.rs b/services/huaweicloud-obs/tests/credential_chain.rs index 5c8ccbad..b498f6fc 100644 --- a/services/huaweicloud-obs/tests/credential_chain.rs +++ b/services/huaweicloud-obs/tests/credential_chain.rs @@ -16,6 +16,8 @@ // under the License. //! Integration tests for ProvideCredentialChain with Huawei Cloud OBS +mod common; + use reqsign_core::ProvideCredentialChain; use reqsign_core::{Context, OsEnv, ProvideCredential, Result}; use reqsign_file_read_tokio::TokioFileRead; @@ -51,7 +53,7 @@ impl ProvideCredential for CountingProvider { #[tokio::test] async fn test_chain_stops_at_first_success() { - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -95,7 +97,7 @@ async fn test_chain_with_real_providers() { use reqsign_core::StaticEnv; use std::collections::HashMap; - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -126,7 +128,7 @@ async fn test_chain_with_real_providers() { #[tokio::test] async fn test_empty_chain_returns_none() { - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -138,7 +140,7 @@ async fn test_empty_chain_returns_none() { #[tokio::test] async fn test_chain_all_providers_return_none() { - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -168,7 +170,7 @@ async fn test_chain_all_providers_return_none() { #[tokio::test] async fn test_chain_with_security_token() { - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); diff --git a/services/oracle/Cargo.toml b/services/oracle/Cargo.toml index fe5e6684..23d50c05 100644 --- a/services/oracle/Cargo.toml +++ b/services/oracle/Cargo.toml @@ -32,11 +32,12 @@ base64 = { workspace = true } http = { workspace = true } log = { workspace = true } reqsign-core = { workspace = true } -rsa = { workspace = true } rust-ini = { workspace = true } [dev-dependencies] env_logger = "0.11" +reqsign-crypto-rustcrypto = { workspace = true } +rsa = { workspace = true } reqsign-file-read-tokio = { workspace = true } reqsign-http-send-reqwest = { workspace = true } tokio = { version = "1", features = ["test-util", "macros", "rt-multi-thread"] } diff --git a/services/oracle/README.md b/services/oracle/README.md index 0615f159..7329369a 100644 --- a/services/oracle/README.md +++ b/services/oracle/README.md @@ -6,14 +6,21 @@ The default credential provider checks OCI environment variables and then the OCI configuration file at `~/.oci/config`. The config path and profile can be selected with `OCI_CONFIG_FILE` and `OCI_PROFILE`. +> Signing needs a `CryptoProvider` resolved through the `Context`: bind one with +> `Context::with_crypto`, install a process-wide default, or use a facade +> `default_context()` (which binds RustCrypto when the global slot is empty). A +> bare `Context::new()` starts unbound. See +> [CryptoProvider](https://github.com/apache/reqsign/blob/main/docs/crypto-provider.md). + ## Quick Start ```rust,no_run +use reqsign_crypto_rustcrypto::RustCryptoProvider; use reqsign_core::{Context, OsEnv, Signer}; use reqsign_file_read_tokio::TokioFileRead; use reqsign_oracle::{DefaultCredentialProvider, RequestSigner}; -let context = Context::new() +let context = Context::new().with_crypto(RustCryptoProvider::new()) .with_file_read(TokioFileRead) .with_env(OsEnv); diff --git a/services/oracle/examples/oracle_chain_logging.rs b/services/oracle/examples/oracle_chain_logging.rs index e3617789..6fcd7571 100644 --- a/services/oracle/examples/oracle_chain_logging.rs +++ b/services/oracle/examples/oracle_chain_logging.rs @@ -18,6 +18,7 @@ //! Example of using ProvideCredentialChain with logging to see credential resolution use log::{debug, info}; use reqsign_core::{Context, OsEnv, ProvideCredential, ProvideCredentialChain, Result}; +use reqsign_crypto_rustcrypto::RustCryptoProvider; use reqsign_file_read_tokio::TokioFileRead; use reqsign_http_send_reqwest::ReqwestHttpSend; use reqsign_oracle::{ @@ -74,6 +75,7 @@ async fn main() -> Result<()> { // Create context let ctx = Context::new() + .with_crypto(RustCryptoProvider::new()) .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); diff --git a/services/oracle/src/lib.rs b/services/oracle/src/lib.rs index 4632912d..4f5f7e60 100644 --- a/services/oracle/src/lib.rs +++ b/services/oracle/src/lib.rs @@ -37,3 +37,8 @@ pub use provide_credential::{ ConfigFileCredentialProvider, DefaultCredentialProvider, DefaultCredentialProviderBuilder, EnvCredentialProvider, StaticCredentialProvider, }; + +#[cfg(test)] +pub(crate) fn test_context() -> reqsign_core::Context { + reqsign_core::Context::new().with_crypto(reqsign_crypto_rustcrypto::RustCryptoProvider::new()) +} diff --git a/services/oracle/src/provide_credential/config_file.rs b/services/oracle/src/provide_credential/config_file.rs index 23116951..7c9b8d39 100644 --- a/services/oracle/src/provide_credential/config_file.rs +++ b/services/oracle/src/provide_credential/config_file.rs @@ -150,7 +150,7 @@ mod tests { #[tokio::test] async fn test_config_file_credential_provider_file_not_found() -> anyhow::Result<()> { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv) diff --git a/services/oracle/src/provide_credential/default.rs b/services/oracle/src/provide_credential/default.rs index 994b9a16..fde84ccc 100644 --- a/services/oracle/src/provide_credential/default.rs +++ b/services/oracle/src/provide_credential/default.rs @@ -162,7 +162,7 @@ mod tests { use crate::constants::{ ORACLE_CONFIG_FILE, ORACLE_FINGERPRINT, ORACLE_KEY_FILE, ORACLE_TENANCY, ORACLE_USER, }; - use reqsign_core::{Context, StaticEnv}; + use reqsign_core::StaticEnv; use reqsign_file_read_tokio::TokioFileRead; use reqsign_http_send_reqwest::ReqwestHttpSend; use std::collections::HashMap; @@ -171,7 +171,7 @@ mod tests { #[tokio::test] async fn test_default_matches_new() { - let ctx = Context::new().with_env(StaticEnv { + let ctx = crate::test_context().with_env(StaticEnv { home_dir: None, envs: HashMap::from([ (ORACLE_USER.to_string(), "test_user".to_string()), @@ -205,7 +205,7 @@ mod tests { #[tokio::test] async fn test_builder_no_env_removes_env_provider() { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(StaticEnv { @@ -248,7 +248,7 @@ mod tests { ) .expect("write config file must succeed"); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(StaticEnv { diff --git a/services/oracle/src/provide_credential/env.rs b/services/oracle/src/provide_credential/env.rs index 50e32688..92ef7cdc 100644 --- a/services/oracle/src/provide_credential/env.rs +++ b/services/oracle/src/provide_credential/env.rs @@ -91,7 +91,7 @@ mod tests { ), ]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv) @@ -114,7 +114,7 @@ mod tests { #[tokio::test] async fn test_env_credential_provider_missing_credentials() -> anyhow::Result<()> { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -134,7 +134,7 @@ mod tests { (ORACLE_TENANCY.to_string(), "test_tenancy".to_string()), ]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv) @@ -162,7 +162,7 @@ mod tests { ), ]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv) diff --git a/services/oracle/src/provide_credential/static_.rs b/services/oracle/src/provide_credential/static_.rs index 4f99d397..87b3288f 100644 --- a/services/oracle/src/provide_credential/static_.rs +++ b/services/oracle/src/provide_credential/static_.rs @@ -55,7 +55,7 @@ mod tests { #[tokio::test] async fn test_static_credential_provider() -> anyhow::Result<()> { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); diff --git a/services/oracle/src/sign_request.rs b/services/oracle/src/sign_request.rs index d0aeb7ef..071edc54 100644 --- a/services/oracle/src/sign_request.rs +++ b/services/oracle/src/sign_request.rs @@ -23,10 +23,6 @@ use http::{HeaderMap, HeaderName, Method}; use log::debug; use reqsign_core::time::Timestamp; use reqsign_core::{Context, Error, Result, SignRequest, SigningCredential, SigningRequest}; -use rsa::pkcs1v15::SigningKey; -use rsa::sha2::Sha256; -use rsa::signature::{SignatureEncoding, Signer}; -use rsa::{RsaPrivateKey, pkcs1::DecodeRsaPrivateKey, pkcs8::DecodePrivateKey}; use std::fmt::Write; use std::time::Duration; @@ -103,21 +99,13 @@ impl SignRequest for RequestSigner { debug!("string to sign: {}", string_to_sign); - // Read private key from file + // Read private key from file. Both unencrypted PKCS#8 and PKCS#1 PEM + // keys are accepted by the configured CryptoProvider. let private_key_content = ctx.file_read_as_string(&cred.key_file).await?; - // Older OpenSSL versions produce PKCS#1 PEM keys with `openssl genrsa`. - let private_key = RsaPrivateKey::from_pkcs8_pem(&private_key_content) - .or_else(|_| RsaPrivateKey::from_pkcs1_pem(&private_key_content)) - .map_err(|e| { - reqsign_core::Error::credential_invalid(format!("Failed to read private key: {e}")) - })?; - - // Sign the string - let signing_key = SigningKey::::new(private_key); - let signature = signing_key - .try_sign(string_to_sign.as_bytes()) - .map_err(|e| reqsign_core::Error::unexpected(format!("Failed to sign: {e}")))?; - let encoded_signature = general_purpose::STANDARD.encode(signature.to_bytes()); + let provider = ctx.crypto_provider()?; + let signature = provider + .rsa_pkcs1v15_sha256_sign(private_key_content.as_bytes(), string_to_sign.as_bytes())?; + let encoded_signature = general_purpose::STANDARD.encode(signature); // Set headers signing_req @@ -208,6 +196,7 @@ fn single_header_value<'a>(headers: &'a HeaderMap, name: &HeaderName) -> Result< mod tests { use super::*; use reqsign_core::FileRead; + use rsa::RsaPrivateKey; use rsa::pkcs8::{EncodePrivateKey, LineEnding}; use rsa::rand_core::OsRng; @@ -254,7 +243,7 @@ mod tests { .expect("private key must encode") .as_bytes() .to_vec(); - let ctx = Context::new().with_file_read(StaticFileRead(private_key)); + let ctx = crate::test_context().with_file_read(StaticFileRead(private_key)); let mut parts = http::Request::get(&original_uri).body(())?.into_parts().0; RequestSigner::new() @@ -269,7 +258,7 @@ mod tests { #[tokio::test] async fn invalid_private_key_leaves_request_unchanged() -> Result<()> { let original_uri = format!("https://example.com/object?{RAW_QUERY}"); - let ctx = Context::new().with_file_read(StaticFileRead(b"invalid".to_vec())); + let ctx = crate::test_context().with_file_read(StaticFileRead(b"invalid".to_vec())); let mut parts = http::Request::get(&original_uri) .header("x-original", "value") .body(())? diff --git a/services/oracle/tests/common/mod.rs b/services/oracle/tests/common/mod.rs new file mode 100644 index 00000000..864b1164 --- /dev/null +++ b/services/oracle/tests/common/mod.rs @@ -0,0 +1,22 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use reqsign_core::Context; + +pub fn test_context() -> Context { + Context::new().with_crypto(reqsign_crypto_rustcrypto::RustCryptoProvider::new()) +} diff --git a/services/oracle/tests/config_profiles.rs b/services/oracle/tests/config_profiles.rs index 1b7d33e1..0bf43a04 100644 --- a/services/oracle/tests/config_profiles.rs +++ b/services/oracle/tests/config_profiles.rs @@ -15,6 +15,8 @@ // specific language governing permissions and limitations // under the License. +mod common; + use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -104,7 +106,7 @@ fn context(config: &str, profile: Option<&str>) -> (Context, Files) { if let Some(profile) = profile { envs.insert("OCI_PROFILE".into(), profile.into()); } - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(files.clone()) .with_env(StaticEnv { home_dir: Some("/synthetic/home".into()), @@ -330,7 +332,7 @@ async fn malformed_config_remains_a_configuration_error() { async fn home_directory_is_only_required_for_tilde_paths() -> Result<()> { let files = Files::default(); files.insert(CONFIG_PATH, defaults().into_bytes()); - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(files.clone()) .with_env(StaticEnv { home_dir: None, diff --git a/services/oracle/tests/credential_chain.rs b/services/oracle/tests/credential_chain.rs index cf1236e6..fa2217fb 100644 --- a/services/oracle/tests/credential_chain.rs +++ b/services/oracle/tests/credential_chain.rs @@ -16,6 +16,8 @@ // under the License. //! Integration tests for ProvideCredentialChain with Oracle Cloud Infrastructure +mod common; + use reqsign_core::ProvideCredentialChain; use reqsign_core::{Context, OsEnv, ProvideCredential, Result}; use reqsign_file_read_tokio::TokioFileRead; @@ -53,7 +55,7 @@ impl ProvideCredential for CountingProvider { #[tokio::test] async fn test_chain_stops_at_first_success() { - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -97,7 +99,7 @@ async fn test_chain_with_real_providers() { use reqsign_core::StaticEnv; use std::collections::HashMap; - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -129,7 +131,7 @@ async fn test_chain_with_real_providers() { #[tokio::test] async fn test_empty_chain_returns_none() { - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -141,7 +143,7 @@ async fn test_empty_chain_returns_none() { #[tokio::test] async fn test_chain_all_providers_return_none() { - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); diff --git a/services/oracle/tests/private_key_formats.rs b/services/oracle/tests/private_key_formats.rs index 3cae0cb1..0c6c2b6f 100644 --- a/services/oracle/tests/private_key_formats.rs +++ b/services/oracle/tests/private_key_formats.rs @@ -15,6 +15,8 @@ // specific language governing permissions and limitations // under the License. +mod common; + use std::sync::LazyLock; use base64::{Engine as _, engine::general_purpose::STANDARD}; @@ -57,7 +59,7 @@ impl FileRead for KeyFile { } fn context(pem: &str) -> Context { - Context::new().with_file_read(KeyFile(pem.as_bytes().to_vec())) + crate::common::test_context().with_file_read(KeyFile(pem.as_bytes().to_vec())) } fn credential() -> Credential { @@ -357,7 +359,12 @@ async fn absent_or_incomplete_credentials_do_not_read_private_key() -> anyhow::R let original = parts.clone(); // No file adapter is installed: credential checks must precede key loading. let result = RequestSigner::default() - .sign_request(&Context::new(), &mut parts, credential.as_ref(), None) + .sign_request( + &crate::common::test_context(), + &mut parts, + credential.as_ref(), + None, + ) .await; if credential.is_some() { assert_eq!( diff --git a/services/tencent-cos/Cargo.toml b/services/tencent-cos/Cargo.toml index 33fec1a1..2a668a6e 100644 --- a/services/tencent-cos/Cargo.toml +++ b/services/tencent-cos/Cargo.toml @@ -36,6 +36,7 @@ serde = { workspace = true } serde_json = { workspace = true } [dev-dependencies] +reqsign-crypto-rustcrypto = { workspace = true } bytes = { workspace = true } dotenvy = { workspace = true } env_logger = { workspace = true } diff --git a/services/tencent-cos/README.md b/services/tencent-cos/README.md index a5b21984..e896c6ba 100644 --- a/services/tencent-cos/README.md +++ b/services/tencent-cos/README.md @@ -6,13 +6,20 @@ The default credential provider checks Tencent Cloud environment variables and then web identity configuration. It supports both header authentication and presigned query authentication. +> Signing needs a `CryptoProvider` resolved through the `Context`: bind one with +> `Context::with_crypto`, install a process-wide default, or use a facade +> `default_context()` (which binds RustCrypto when the global slot is empty). A +> bare `Context::new()` starts unbound. See +> [CryptoProvider](https://github.com/apache/reqsign/blob/main/docs/crypto-provider.md). + ## Quick Start ```rust,no_run +use reqsign_crypto_rustcrypto::RustCryptoProvider; use reqsign_core::{Context, OsEnv, Signer}; use reqsign_tencent_cos::{DefaultCredentialProvider, RequestSigner}; -let context = Context::new().with_env(OsEnv); +let context = Context::new().with_crypto(RustCryptoProvider::new()).with_env(OsEnv); let signer = Signer::new( context, DefaultCredentialProvider::new(), diff --git a/services/tencent-cos/examples/tencent_chain_logging.rs b/services/tencent-cos/examples/tencent_chain_logging.rs index 86d01ef2..5a7d058a 100644 --- a/services/tencent-cos/examples/tencent_chain_logging.rs +++ b/services/tencent-cos/examples/tencent_chain_logging.rs @@ -18,6 +18,7 @@ //! Example of using ProvideCredentialChain with logging to see credential resolution use log::{debug, info}; use reqsign_core::{Context, OsEnv, ProvideCredential, ProvideCredentialChain, Result}; +use reqsign_crypto_rustcrypto::RustCryptoProvider; use reqsign_file_read_tokio::TokioFileRead; use reqsign_http_send_reqwest::ReqwestHttpSend; use reqsign_tencent_cos::{ @@ -78,6 +79,7 @@ async fn main() -> Result<()> { // Create context let ctx = Context::new() + .with_crypto(RustCryptoProvider::new()) .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); diff --git a/services/tencent-cos/src/get_federation_token.rs b/services/tencent-cos/src/get_federation_token.rs index 72a8a636..b8a7880b 100644 --- a/services/tencent-cos/src/get_federation_token.rs +++ b/services/tencent-cos/src/get_federation_token.rs @@ -33,6 +33,7 @@ use std::time::Duration; use http::header::{AUTHORIZATION, CONTENT_TYPE}; use percent_encoding::utf8_percent_encode; +use reqsign_core::crypto::CryptoProvider; use reqsign_core::hash::{hex_hmac_sha256, hex_sha256, hmac_sha256}; use reqsign_core::time::Timestamp; use reqsign_core::{Context, Error, GrantCredential, Result, SigningCredential}; @@ -307,6 +308,7 @@ impl GetFederationTokenGranter { fn build_request( &self, + provider: &dyn CryptoProvider, credential: &Credential, duration_seconds: Option, signing_time: Timestamp, @@ -331,20 +333,21 @@ impl GetFederationTokenGranter { let signed_headers = "content-type;host"; let canonical_request = format!( "POST\n/\n\n{canonical_headers}\n{signed_headers}\n{}", - hex_sha256(&body) + hex_sha256(provider, &body)? ); let credential_scope = format!("{date}/{STS_SERVICE}/tc3_request"); let string_to_sign = format!( "TC3-HMAC-SHA256\n{timestamp}\n{credential_scope}\n{}", - hex_sha256(canonical_request.as_bytes()) + hex_sha256(provider, canonical_request.as_bytes())? ); let secret_date = hmac_sha256( + provider, format!("TC3{}", credential.secret_key).as_bytes(), date.as_bytes(), - ); - let secret_service = hmac_sha256(&secret_date, STS_SERVICE.as_bytes()); - let secret_signing = hmac_sha256(&secret_service, b"tc3_request"); - let signature = hex_hmac_sha256(&secret_signing, string_to_sign.as_bytes()); + )?; + let secret_service = hmac_sha256(provider, &secret_date, STS_SERVICE.as_bytes())?; + let secret_signing = hmac_sha256(provider, &secret_service, b"tc3_request")?; + let signature = hex_hmac_sha256(provider, &secret_signing, string_to_sign.as_bytes())?; let authorization = format!( "TC3-HMAC-SHA256 Credential={}/{credential_scope}, SignedHeaders={signed_headers}, Signature={signature}", credential.secret_id @@ -479,7 +482,12 @@ impl GrantCredential for GetFederationTokenGranter { let required_until = self.required_valid_until(credential, expires_in); self.validate_source(credential, required_until)?; - let request = self.build_request(credential, duration_seconds, self.now())?; + let request = self.build_request( + ctx.crypto_provider()?, + credential, + duration_seconds, + self.now(), + )?; let response = ctx .http_send(request.map(Into::into)) .await @@ -826,7 +834,7 @@ mod tests { async fn grants_with_exact_tc3_signature_and_epoch_expiration() -> Result<()> { let signing_time = timestamp("2024-03-05T06:07:08Z"); let http_send = MockHttpSend::new([response(http::StatusCode::OK, SUCCESS_BODY)]); - let ctx = Context::new().with_http_send(http_send.clone()); + let ctx = crate::test_context().with_http_send(http_send.clone()); let credential = Granter::new(ctx, source_provider(), granter(signing_time)) .grant(Some(Duration::from_secs(3600))) @@ -881,7 +889,7 @@ mod tests { async fn omitted_duration_uses_the_service_default_and_accepts_iso_expiration() -> Result<()> { let body = br#"{"Response":{"Credentials":{"TmpSecretId":"sts-secret-id","TmpSecretKey":"sts-secret-key","Token":"sts-security-token"},"Expiration":"2124-05-25T11:45:17Z"}}"#; let http_send = MockHttpSend::new([response(http::StatusCode::OK, body.as_slice())]); - let ctx = Context::new().with_http_send(http_send.clone()); + let ctx = crate::test_context().with_http_send(http_send.clone()); let credential = Granter::new( ctx, @@ -915,7 +923,7 @@ mod tests { ]; for duration in durations { let http_send = MockHttpSend::new(Vec::>::new()); - let ctx = Context::new().with_http_send(http_send.clone()); + let ctx = crate::test_context().with_http_send(http_send.clone()); let err = Granter::new(ctx, source_provider(), granter(signing_time)) .grant(duration) .await @@ -931,7 +939,7 @@ mod tests { ); for grant in invalid_grants { let http_send = MockHttpSend::new(Vec::>::new()); - let ctx = Context::new().with_http_send(http_send.clone()); + let ctx = crate::test_context().with_http_send(http_send.clone()); let err = Granter::new( ctx, source_provider(), @@ -960,7 +968,7 @@ mod tests { ]; for source in invalid_sources { let http_send = MockHttpSend::new(Vec::>::new()); - let ctx = Context::new().with_http_send(http_send.clone()); + let ctx = crate::test_context().with_http_send(http_send.clone()); let err = Granter::new( ctx, FixedCredentialProvider { credential: source }, @@ -978,7 +986,7 @@ mod tests { async fn rejects_expired_granted_credential_after_io() { let body = br#"{"Response":{"Credentials":{"TmpSecretId":"sts-secret-id","TmpSecretKey":"sts-secret-key","Token":"sts-security-token"},"ExpiredTime":1893553445}}"#; let http_send = MockHttpSend::new([response(http::StatusCode::OK, body.as_slice())]); - let ctx = Context::new().with_http_send(http_send.clone()); + let ctx = crate::test_context().with_http_send(http_send.clone()); let err = Granter::new( ctx, @@ -1010,7 +1018,7 @@ mod tests { let error_body = br#"{"Response":{"Error":{"Code":"AuthFailure.SignatureFailure","Message":"source-secret-key and policy detail"},"RequestId":"request-id"}}"#; let http_send = MockHttpSend::new([response(http::StatusCode::OK, error_body.as_slice())]); - let ctx = Context::new().with_http_send(http_send.clone()); + let ctx = crate::test_context().with_http_send(http_send.clone()); let err = Granter::new( ctx, source_provider(), @@ -1030,7 +1038,7 @@ mod tests { http::StatusCode::INTERNAL_SERVER_ERROR, Bytes::from(error_body), )]); - let ctx = Context::new().with_http_send(http_send.clone()); + let ctx = crate::test_context().with_http_send(http_send.clone()); let err = Granter::new( ctx, source_provider(), @@ -1048,13 +1056,13 @@ mod tests { async fn granted_credential_is_consumable_by_the_cos_signer() -> Result<()> { let now = Timestamp::now(); let http_send = MockHttpSend::new([success_response(now.as_second() + 7200)]); - let ctx = Context::new().with_http_send(http_send); + let ctx = crate::test_context().with_http_send(http_send); let granted = Granter::new(ctx, source_provider(), granter(now)) .grant(Some(Duration::from_secs(7200))) .await?; let signer = Signer::new( - Context::new(), + crate::test_context(), FixedCredentialProvider { credential: granted, }, @@ -1079,13 +1087,13 @@ mod tests { { let now = Timestamp::now(); let http_send = MockHttpSend::new([success_response(now.as_second() + 1800)]); - let ctx = Context::new().with_http_send(http_send); + let ctx = crate::test_context().with_http_send(http_send); let granted = Granter::new(ctx, source_provider(), granter(now)) .grant(None) .await?; let signer = Signer::new( - Context::new(), + crate::test_context(), FixedCredentialProvider { credential: granted, }, diff --git a/services/tencent-cos/src/lib.rs b/services/tencent-cos/src/lib.rs index 7be93aa5..8261446e 100644 --- a/services/tencent-cos/src/lib.rs +++ b/services/tencent-cos/src/lib.rs @@ -32,3 +32,8 @@ pub use sign_request::RequestSigner; mod provide_credential; pub use provide_credential::*; + +#[cfg(test)] +pub(crate) fn test_context() -> reqsign_core::Context { + reqsign_core::Context::new().with_crypto(reqsign_crypto_rustcrypto::RustCryptoProvider::new()) +} diff --git a/services/tencent-cos/src/provide_credential/assume_role_with_web_identity.rs b/services/tencent-cos/src/provide_credential/assume_role_with_web_identity.rs index 066866e3..f582ba90 100644 --- a/services/tencent-cos/src/provide_credential/assume_role_with_web_identity.rs +++ b/services/tencent-cos/src/provide_credential/assume_role_with_web_identity.rs @@ -265,7 +265,7 @@ mod tests { }"#, ); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TestFileRead { expected_path: token_path.to_string(), content: token.as_bytes().to_vec(), diff --git a/services/tencent-cos/src/provide_credential/default.rs b/services/tencent-cos/src/provide_credential/default.rs index 7adce97c..e4a2c438 100644 --- a/services/tencent-cos/src/provide_credential/default.rs +++ b/services/tencent-cos/src/provide_credential/default.rs @@ -155,7 +155,7 @@ mod tests { #[tokio::test] async fn test_default_loader_without_env() { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -172,7 +172,7 @@ mod tests { #[tokio::test] async fn test_default_loader_with_env() { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -196,7 +196,7 @@ mod tests { #[tokio::test] async fn test_default_loader_with_security_token() { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -219,7 +219,7 @@ mod tests { #[tokio::test] async fn test_builder_no_env_removes_env_provider() { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -242,7 +242,7 @@ mod tests { #[tokio::test] async fn test_builder_no_web_identity_removes_web_identity_provider() { - let ctx = Context::new().with_env(StaticEnv { + let ctx = crate::test_context().with_env(StaticEnv { home_dir: None, envs: HashMap::from_iter([ (TENCENTCLOUD_REGION.to_string(), "ap-guangzhou".to_string()), diff --git a/services/tencent-cos/src/provide_credential/env.rs b/services/tencent-cos/src/provide_credential/env.rs index 97f3e293..43c236c5 100644 --- a/services/tencent-cos/src/provide_credential/env.rs +++ b/services/tencent-cos/src/provide_credential/env.rs @@ -91,7 +91,7 @@ mod tests { ), ]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv) @@ -122,7 +122,7 @@ mod tests { ), ]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv) @@ -144,7 +144,7 @@ mod tests { #[tokio::test] async fn test_env_credential_provider_missing_credentials() -> anyhow::Result<()> { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -164,7 +164,7 @@ mod tests { "test_secret_id".to_string(), )]); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv) diff --git a/services/tencent-cos/src/provide_credential/static.rs b/services/tencent-cos/src/provide_credential/static.rs index 91d63630..7abd9f34 100644 --- a/services/tencent-cos/src/provide_credential/static.rs +++ b/services/tencent-cos/src/provide_credential/static.rs @@ -66,7 +66,7 @@ mod tests { #[tokio::test] async fn test_static_credential_provider() -> anyhow::Result<()> { - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); diff --git a/services/tencent-cos/src/sign_request.rs b/services/tencent-cos/src/sign_request.rs index f9396f8c..69a309f1 100644 --- a/services/tencent-cos/src/sign_request.rs +++ b/services/tencent-cos/src/sign_request.rs @@ -22,6 +22,7 @@ use http::header::{AUTHORIZATION, DATE}; use http::request::Parts; use log::debug; use percent_encoding::{percent_decode_str, utf8_percent_encode}; +use reqsign_core::crypto::CryptoProvider; use reqsign_core::hash::{hex_hmac_sha1, hex_sha1}; use reqsign_core::time::Timestamp; use reqsign_core::{Context, Result, SignRequest, SigningCredential, SigningRequest}; @@ -79,7 +80,7 @@ impl SignRequest for RequestSigner { async fn sign_request( &self, - _ctx: &Context, + ctx: &Context, req: &mut Parts, credential: Option<&Self::Credential>, expires_in: Option, @@ -87,6 +88,7 @@ impl SignRequest for RequestSigner { let Some(cred) = credential else { return Ok(()); }; + let provider = ctx.crypto_provider()?; let now = self.get_time(); let required_until = self.required_valid_until_at(now, expires_in); @@ -101,7 +103,7 @@ impl SignRequest for RequestSigner { let final_uri = if let Some(expires) = expires_in { // Query signing - let signature = build_signature(&signing_req, cred, now, expires); + let signature = build_signature(provider, &signing_req, cred, now, expires)?; signing_req .headers @@ -117,7 +119,8 @@ impl SignRequest for RequestSigner { Some(append_query_fragment(&original_uri, &authentication)?) } else { // Header signing (default 3600s expiration) - let signature = build_signature(&signing_req, cred, now, Duration::from_secs(3600)); + let signature = + build_signature(provider, &signing_req, cred, now, Duration::from_secs(3600))?; signing_req .headers @@ -147,13 +150,14 @@ impl SignRequest for RequestSigner { } fn build_signature( + provider: &dyn CryptoProvider, ctx: &SigningRequest, cred: &Credential, now: Timestamp, expires: Duration, -) -> String { +) -> Result { let key_time = format!("{};{}", now.as_second(), (now + expires).as_second()); - let sign_key = hex_hmac_sha1(cred.secret_key.as_bytes(), key_time.as_bytes()); + let sign_key = hex_hmac_sha1(provider, cred.secret_key.as_bytes(), key_time.as_bytes())?; let (param_list, param_string) = canonical_query(ctx); debug!("param list: {param_list}"); @@ -201,16 +205,16 @@ fn build_signature( string_to_sign.push('\n'); string_to_sign.push_str(&key_time); string_to_sign.push('\n'); - string_to_sign.push_str(&hex_sha1(http_string.as_bytes())); + string_to_sign.push_str(&hex_sha1(provider, http_string.as_bytes())?); string_to_sign.push('\n'); debug!("string_to_sign: {string_to_sign}"); - let signature = hex_hmac_sha1(sign_key.as_bytes(), string_to_sign.as_bytes()); + let signature = hex_hmac_sha1(provider, sign_key.as_bytes(), string_to_sign.as_bytes())?; - format!( + Ok(format!( "q-sign-algorithm=sha1&q-ak={}&q-sign-time={}&q-key-time={}&q-header-list={}&q-url-param-list={}&q-signature={}", cred.secret_id, key_time, key_time, header_list, param_list, signature - ) + )) } fn canonical_query(ctx: &SigningRequest) -> (String, String) { @@ -298,14 +302,19 @@ mod tests { let mut header_parts = http::Request::get(&original_uri).body(())?.into_parts().0; signer - .sign_request(&Context::new(), &mut header_parts, Some(&credential), None) + .sign_request( + &crate::test_context(), + &mut header_parts, + Some(&credential), + None, + ) .await?; assert_eq!(header_parts.uri.to_string(), original_uri); let mut query_parts = http::Request::get(&original_uri).body(())?.into_parts().0; signer .sign_request( - &Context::new(), + &crate::test_context(), &mut query_parts, Some(&credential), Some(Duration::from_secs(60)), diff --git a/services/tencent-cos/tests/common/mod.rs b/services/tencent-cos/tests/common/mod.rs new file mode 100644 index 00000000..864b1164 --- /dev/null +++ b/services/tencent-cos/tests/common/mod.rs @@ -0,0 +1,22 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use reqsign_core::Context; + +pub fn test_context() -> Context { + Context::new().with_crypto(reqsign_crypto_rustcrypto::RustCryptoProvider::new()) +} diff --git a/services/tencent-cos/tests/credential_chain.rs b/services/tencent-cos/tests/credential_chain.rs index 210eaf90..344f301c 100644 --- a/services/tencent-cos/tests/credential_chain.rs +++ b/services/tencent-cos/tests/credential_chain.rs @@ -16,6 +16,8 @@ // under the License. //! Integration tests for ProvideCredentialChain with Tencent COS +mod common; + use reqsign_core::ProvideCredentialChain; use reqsign_core::time::Timestamp; use reqsign_core::{Context, OsEnv, ProvideCredential, Result}; @@ -54,7 +56,7 @@ impl ProvideCredential for CountingProvider { #[tokio::test] async fn test_chain_stops_at_first_success() { - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -98,7 +100,7 @@ async fn test_chain_with_real_providers() { use reqsign_core::StaticEnv; use std::collections::HashMap; - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -126,7 +128,7 @@ async fn test_chain_with_real_providers() { #[tokio::test] async fn test_empty_chain_returns_none() { - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -138,7 +140,7 @@ async fn test_empty_chain_returns_none() { #[tokio::test] async fn test_chain_all_providers_return_none() { - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -168,7 +170,7 @@ async fn test_chain_all_providers_return_none() { #[tokio::test] async fn test_chain_with_security_token() { - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); diff --git a/services/tencent-cos/tests/main.rs b/services/tencent-cos/tests/main.rs index 87b5c633..a43eb6b9 100644 --- a/services/tencent-cos/tests/main.rs +++ b/services/tencent-cos/tests/main.rs @@ -15,6 +15,8 @@ // specific language governing permissions and limitations // under the License. +mod common; + use std::env; use std::time::Duration; @@ -27,7 +29,7 @@ use log::warn; use percent_encoding::NON_ALPHANUMERIC; use percent_encoding::utf8_percent_encode; use reqsign_core::Result; -use reqsign_core::{Context, OsEnv, Signer}; +use reqsign_core::{OsEnv, Signer}; use reqsign_file_read_tokio::TokioFileRead; use reqsign_http_send_reqwest::ReqwestHttpSend; use reqsign_tencent_cos::{Credential, RequestSigner, StaticCredentialProvider}; @@ -46,7 +48,7 @@ async fn init_signer() -> Option> { let secret_key = env::var("REQSIGN_TENCENT_COS_SECRET_KEY") .expect("env REQSIGN_TENCENT_COS_SECRET_KEY must set"); let loader = StaticCredentialProvider::new(&secret_id, &secret_key); - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); diff --git a/services/tencent-cos/tests/web_identity_live.rs b/services/tencent-cos/tests/web_identity_live.rs index 43c8555e..1b491f94 100644 --- a/services/tencent-cos/tests/web_identity_live.rs +++ b/services/tencent-cos/tests/web_identity_live.rs @@ -23,13 +23,15 @@ //! temporary Tencent Cloud credentials through the real STS endpoint, then //! reads a private COS object with the credentials returned by the provider. +mod common; + use std::env; use std::time::Duration; use http::StatusCode; use log::info; use reqsign_core::Result; -use reqsign_core::{Context, OsEnv, Signer}; +use reqsign_core::{OsEnv, Signer}; use reqsign_file_read_tokio::TokioFileRead; use reqsign_http_send_reqwest::ReqwestHttpSend; use reqsign_tencent_cos::{AssumeRoleWithWebIdentityCredentialProvider, RequestSigner}; @@ -102,7 +104,7 @@ async fn test_web_identity_credential_reads_private_object() -> Result<()> { unsigned_response.status() ); - let ctx = Context::new() + let ctx = crate::common::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); diff --git a/services/volcengine-tos/Cargo.toml b/services/volcengine-tos/Cargo.toml index 5097be9e..75b23985 100644 --- a/services/volcengine-tos/Cargo.toml +++ b/services/volcengine-tos/Cargo.toml @@ -36,6 +36,7 @@ serde = { workspace = true } serde_json = { workspace = true } [dev-dependencies] +reqsign-crypto-rustcrypto = { workspace = true } anyhow = { workspace = true } bytes = { workspace = true } env_logger = { workspace = true } diff --git a/services/volcengine-tos/README.md b/services/volcengine-tos/README.md index 5dc16931..3d82f705 100644 --- a/services/volcengine-tos/README.md +++ b/services/volcengine-tos/README.md @@ -26,13 +26,20 @@ the default credential chain is unchanged. full presigned URL lifetime. Header signing continues to check the signing time. +> Signing needs a `CryptoProvider` resolved through the `Context`: bind one with +> `Context::with_crypto`, install a process-wide default, or use a facade +> `default_context()` (which binds RustCrypto when the global slot is empty). A +> bare `Context::new()` starts unbound. See +> [CryptoProvider](https://github.com/apache/reqsign/blob/main/docs/crypto-provider.md). + ## Quick Start ```rust,no_run +use reqsign_crypto_rustcrypto::RustCryptoProvider; use reqsign_core::{Context, OsEnv, Signer}; use reqsign_volcengine_tos::{DefaultCredentialProvider, RequestSigner}; -let context = Context::new().with_env(OsEnv); +let context = Context::new().with_crypto(RustCryptoProvider::new()).with_env(OsEnv); let signer = Signer::new( context, DefaultCredentialProvider::new(), diff --git a/services/volcengine-tos/src/assume_role.rs b/services/volcengine-tos/src/assume_role.rs index 1cc9cec7..6801eeaa 100644 --- a/services/volcengine-tos/src/assume_role.rs +++ b/services/volcengine-tos/src/assume_role.rs @@ -34,6 +34,7 @@ use std::fmt::{Debug, Formatter}; use std::time::Duration; use http::header::{AUTHORIZATION, HeaderValue}; +use reqsign_core::crypto::CryptoProvider; use reqsign_core::hash::{hex_hmac_sha256, hex_sha256, hmac_sha256}; use reqsign_core::time::Timestamp; use reqsign_core::{Context, Error, GrantCredential, Result, SigningCredential}; @@ -362,6 +363,7 @@ impl AssumeRoleGranter { fn build_request( &self, + provider: &dyn CryptoProvider, credential: &Credential, duration_seconds: Option, signing_time: Timestamp, @@ -410,15 +412,16 @@ impl AssumeRoleGranter { ); let string_to_sign = format!( "HMAC-SHA256\n{date}\n{credential_scope}\n{}", - hex_sha256(canonical_request.as_bytes()) + hex_sha256(provider, canonical_request.as_bytes())? ); let signing_key = derive_signing_key( + provider, &credential.secret_access_key, &short_date, &self.region, DEFAULT_STS_SERVICE, - ); - let signature = hex_hmac_sha256(&signing_key, string_to_sign.as_bytes()); + )?; + let signature = hex_hmac_sha256(provider, &signing_key, string_to_sign.as_bytes())?; let authorization = format!( "HMAC-SHA256 Credential={}/{credential_scope}, SignedHeaders={signed_headers}, Signature={signature}", credential.access_key_id @@ -532,7 +535,12 @@ impl GrantCredential for AssumeRoleGranter { let required_until = self.required_valid_until(credential, expires_in); self.validate_source(credential, required_until)?; - let request = self.build_request(credential, duration_seconds, self.now())?; + let request = self.build_request( + ctx.crypto_provider()?, + credential, + duration_seconds, + self.now(), + )?; let response = ctx .http_send(request.map(Into::into)) .await @@ -562,11 +570,17 @@ fn canonical_query_string(params: &BTreeMap) -> String { .join("&") } -fn derive_signing_key(secret: &str, date: &str, region: &str, service: &str) -> Vec { - let date_key = hmac_sha256(secret.as_bytes(), date.as_bytes()); - let region_key = hmac_sha256(&date_key, region.as_bytes()); - let service_key = hmac_sha256(®ion_key, service.as_bytes()); - hmac_sha256(&service_key, b"request") +fn derive_signing_key( + provider: &dyn CryptoProvider, + secret: &str, + date: &str, + region: &str, + service: &str, +) -> Result> { + let date_key = hmac_sha256(provider, secret.as_bytes(), date.as_bytes())?; + let region_key = hmac_sha256(provider, &date_key, region.as_bytes())?; + let service_key = hmac_sha256(provider, ®ion_key, service.as_bytes())?; + Ok(hmac_sha256(provider, &service_key, b"request")?.to_vec()) } #[derive(Deserialize)] @@ -884,7 +898,7 @@ mod tests { http::StatusCode::OK, success_body(FAR_FUTURE_EXPIRY), )]); - let ctx = Context::new().with_http_send(http_send.clone()); + let ctx = crate::test_context().with_http_send(http_send.clone()); let (provider, provider_calls) = source_provider(); let credential = Granter::new(ctx, provider, granter(signing_time)) @@ -932,7 +946,7 @@ mod tests { http::StatusCode::OK, success_body(FAR_FUTURE_EXPIRY), )]); - let ctx = Context::new().with_http_send(http_send.clone()); + let ctx = crate::test_context().with_http_send(http_send.clone()); let grant = AssumeRoleGrant::new(ROLE_TRN, SESSION_NAME).with_policy(POLICY); let granter = AssumeRoleGranter::new(REGION, grant).with_time(signing_time); @@ -987,7 +1001,7 @@ mod tests { http::StatusCode::OK, success_body(FAR_FUTURE_EXPIRY), )]); - let ctx = Context::new().with_http_send(http_send.clone()); + let ctx = crate::test_context().with_http_send(http_send.clone()); let (provider, _) = source_provider(); Granter::new(ctx, provider, granter(signing_time)) @@ -1011,7 +1025,7 @@ mod tests { Some(Duration::from_millis(900_500)), ] { let http_send = MockHttpSend::new(Vec::>::new()); - let ctx = Context::new().with_http_send(http_send.clone()); + let ctx = crate::test_context().with_http_send(http_send.clone()); let (provider, _) = source_provider(); let err = Granter::new(ctx, provider, granter(signing_time)) .grant(duration) @@ -1033,7 +1047,7 @@ mod tests { ]; for grant in invalid_grants { let http_send = MockHttpSend::new(Vec::>::new()); - let ctx = Context::new().with_http_send(http_send.clone()); + let ctx = crate::test_context().with_http_send(http_send.clone()); let (provider, _) = source_provider(); let err = Granter::new( ctx, @@ -1054,7 +1068,7 @@ mod tests { ]; for source in invalid_sources { let http_send = MockHttpSend::new(Vec::>::new()); - let ctx = Context::new().with_http_send(http_send.clone()); + let ctx = crate::test_context().with_http_send(http_send.clone()); let (provider, _) = FixedCredentialProvider::new(source); let err = Granter::new(ctx, provider, granter(signing_time)) .grant(None) @@ -1067,7 +1081,7 @@ mod tests { let expired_source = source_credential().with_expires_at(signing_time + Duration::from_secs(19)); let http_send = MockHttpSend::new(Vec::>::new()); - let ctx = Context::new().with_http_send(http_send.clone()); + let ctx = crate::test_context().with_http_send(http_send.clone()); let (provider, _) = FixedCredentialProvider::new(expired_source); let err = Granter::new(ctx, provider, granter(signing_time)) .grant(None) @@ -1077,7 +1091,7 @@ mod tests { assert_eq!(0, http_send.calls()); let http_send = MockHttpSend::new(Vec::>::new()); - let ctx = Context::new().with_http_send(http_send.clone()); + let ctx = crate::test_context().with_http_send(http_send.clone()); let (provider, _) = source_provider(); let err = Granter::new( ctx, @@ -1105,7 +1119,7 @@ mod tests { })) .expect("error body must serialize"); let http_send = MockHttpSend::new([response(http::StatusCode::UNAUTHORIZED, error_body)]); - let ctx = Context::new().with_http_send(http_send.clone()); + let ctx = crate::test_context().with_http_send(http_send.clone()); let (provider, _) = FixedCredentialProvider::new( source_credential().with_session_token(SOURCE_SESSION_TOKEN), ); @@ -1125,7 +1139,7 @@ mod tests { http::StatusCode::FORBIDDEN, br#"{"ResponseMetadata":{"Error":{"Code":"AccessDenied"}}}"#.as_slice(), )]); - let ctx = Context::new().with_http_send(http_send.clone()); + let ctx = crate::test_context().with_http_send(http_send.clone()); let (provider, _) = source_provider(); let err = Granter::new(ctx, provider, granter(signing_time)) .grant(None) @@ -1138,7 +1152,7 @@ mod tests { http::StatusCode::INTERNAL_SERVER_ERROR, br#"{"ResponseMetadata":{"Error":{"Code":"InternalError"}}}"#.as_slice(), )]); - let ctx = Context::new().with_http_send(http_send.clone()); + let ctx = crate::test_context().with_http_send(http_send.clone()); let (provider, _) = source_provider(); let err = Granter::new(ctx, provider, granter(signing_time)) .grant(None) @@ -1161,7 +1175,7 @@ mod tests { ]; for body in malformed { let http_send = MockHttpSend::new([response(http::StatusCode::OK, body)]); - let ctx = Context::new().with_http_send(http_send.clone()); + let ctx = crate::test_context().with_http_send(http_send.clone()); let (provider, _) = source_provider(); let err = Granter::new(ctx, provider, granter(signing_time)) .grant(None) @@ -1175,7 +1189,7 @@ mod tests { http::StatusCode::OK, success_body("2030-01-02T04:04:05Z"), )]); - let ctx = Context::new().with_http_send(http_send.clone()); + let ctx = crate::test_context().with_http_send(http_send.clone()); let (provider, _) = source_provider(); let err = Granter::new( ctx, @@ -1198,14 +1212,14 @@ mod tests { let signing_time = timestamp(SIGNER_SIGNING_TIME); let http_send = MockHttpSend::new([response(http::StatusCode::OK, success_body(SIGNER_EXPIRY))]); - let ctx = Context::new().with_http_send(http_send); + let ctx = crate::test_context().with_http_send(http_send); let (provider, _) = source_provider(); let granted = Granter::new(ctx, provider, granter(signing_time)) .grant(Some(Duration::from_secs(3600))) .await?; let (provider, _) = FixedCredentialProvider::new(granted.clone()); let signer = Signer::new( - Context::new(), + crate::test_context(), provider, RequestSigner::new(REGION).with_time(signing_time), ); @@ -1246,7 +1260,7 @@ mod tests { let expected = direct_request.clone(); let err = direct_signer .sign_request( - &Context::new(), + &crate::test_context(), &mut direct_request, Some(&granted), Some(Duration::from_secs(3600)), diff --git a/services/volcengine-tos/src/lib.rs b/services/volcengine-tos/src/lib.rs index 75fde31a..33592ecf 100644 --- a/services/volcengine-tos/src/lib.rs +++ b/services/volcengine-tos/src/lib.rs @@ -32,3 +32,8 @@ mod uri; pub use uri::{percent_encode_path, percent_encode_query}; pub use sign_request::RequestSigner; + +#[cfg(test)] +pub(crate) fn test_context() -> reqsign_core::Context { + reqsign_core::Context::new().with_crypto(reqsign_crypto_rustcrypto::RustCryptoProvider::new()) +} diff --git a/services/volcengine-tos/src/provide_credential/default.rs b/services/volcengine-tos/src/provide_credential/default.rs index 4c3a2a43..05523072 100644 --- a/services/volcengine-tos/src/provide_credential/default.rs +++ b/services/volcengine-tos/src/provide_credential/default.rs @@ -134,7 +134,7 @@ mod tests { #[tokio::test] async fn test_default_loader_without_env() { - let ctx = Context::new().with_env(StaticEnv { + let ctx = crate::test_context().with_env(StaticEnv { home_dir: None, envs: HashMap::new(), }); @@ -147,7 +147,7 @@ mod tests { #[tokio::test] async fn test_default_loader_with_env() { - let ctx = Context::new().with_env(StaticEnv { + let ctx = crate::test_context().with_env(StaticEnv { home_dir: None, envs: HashMap::from_iter([ (ENV_ACCESS_KEY_ID.to_string(), "access_key_id".to_string()), @@ -167,7 +167,7 @@ mod tests { #[tokio::test] async fn test_default_loader_with_security_token() { - let ctx = Context::new().with_env(StaticEnv { + let ctx = crate::test_context().with_env(StaticEnv { home_dir: None, envs: HashMap::from_iter([ (ENV_ACCESS_KEY_ID.to_string(), "access_key_id".to_string()), @@ -189,7 +189,7 @@ mod tests { #[tokio::test] async fn test_default_loader_with_no_env() { - let ctx = Context::new().with_env(StaticEnv { + let ctx = crate::test_context().with_env(StaticEnv { home_dir: None, envs: HashMap::from_iter([ (ENV_ACCESS_KEY_ID.to_string(), "access_key_id".to_string()), diff --git a/services/volcengine-tos/src/provide_credential/env.rs b/services/volcengine-tos/src/provide_credential/env.rs index fe673bf9..5cce4b79 100644 --- a/services/volcengine-tos/src/provide_credential/env.rs +++ b/services/volcengine-tos/src/provide_credential/env.rs @@ -75,7 +75,7 @@ mod tests { ), ]); - let ctx = Context::new().with_env(StaticEnv { + let ctx = crate::test_context().with_env(StaticEnv { home_dir: None, envs, }); @@ -105,7 +105,7 @@ mod tests { ), ]); - let ctx = Context::new().with_env(StaticEnv { + let ctx = crate::test_context().with_env(StaticEnv { home_dir: None, envs, }); @@ -123,7 +123,7 @@ mod tests { #[tokio::test] async fn test_env_credential_provider_missing_credentials() -> anyhow::Result<()> { - let ctx = Context::new().with_env(StaticEnv::default()); + let ctx = crate::test_context().with_env(StaticEnv::default()); let provider = EnvCredentialProvider::new(); let cred = provider.provide_credential(&ctx).await?; @@ -136,7 +136,7 @@ mod tests { async fn test_env_credential_provider_partial_credentials() -> anyhow::Result<()> { let envs = HashMap::from([(ENV_ACCESS_KEY_ID.to_string(), "test_access_key".to_string())]); - let ctx = Context::new().with_env(StaticEnv { + let ctx = crate::test_context().with_env(StaticEnv { home_dir: None, envs, }); diff --git a/services/volcengine-tos/src/provide_credential/static.rs b/services/volcengine-tos/src/provide_credential/static.rs index ab4c4d74..00af7f21 100644 --- a/services/volcengine-tos/src/provide_credential/static.rs +++ b/services/volcengine-tos/src/provide_credential/static.rs @@ -66,7 +66,7 @@ mod tests { #[tokio::test] async fn test_static_credential_provider() -> anyhow::Result<()> { - let ctx = Context::new(); + let ctx = crate::test_context(); let provider = StaticCredentialProvider::new("test_access_key", "test_secret_key"); let cred = provider.provide_credential(&ctx).await?; @@ -81,7 +81,7 @@ mod tests { #[tokio::test] async fn test_static_credential_provider_with_security_token() -> anyhow::Result<()> { - let ctx = Context::new(); + let ctx = crate::test_context(); let provider = StaticCredentialProvider::new("test_access_key", "test_secret_key") .with_security_token("test_security_token"); diff --git a/services/volcengine-tos/src/sign_request.rs b/services/volcengine-tos/src/sign_request.rs index c1350be6..7ce8858f 100644 --- a/services/volcengine-tos/src/sign_request.rs +++ b/services/volcengine-tos/src/sign_request.rs @@ -19,6 +19,7 @@ use http::header::AUTHORIZATION; use http::{HeaderName, HeaderValue, header}; use log::debug; use percent_encoding::percent_decode_str; +use reqsign_core::crypto::CryptoProvider; use reqsign_core::hash::{hex_hmac_sha256, hex_sha256, hmac_sha256}; use reqsign_core::time::Timestamp; use reqsign_core::utils::Redact; @@ -106,7 +107,7 @@ impl SignRequest for RequestSigner { async fn sign_request( &self, - _ctx: &Context, + ctx: &Context, req: &mut http::request::Parts, credential: Option<&Self::Credential>, expires_in: Option, @@ -114,6 +115,7 @@ impl SignRequest for RequestSigner { let Some(cred) = credential else { return Ok(()); }; + let provider = ctx.crypto_provider()?; let now = self.get_time(); let required_until = self.required_valid_until_at(now, expires_in); @@ -156,6 +158,7 @@ impl SignRequest for RequestSigner { EMPTY_PAYLOAD_SHA256 }; let (canonical_request_hash, _) = canonical_request_hash( + provider, &signing_req, &canonical_query, &signed_headers, @@ -179,8 +182,9 @@ impl SignRequest for RequestSigner { debug!("string to sign: {}", string_to_sign); - let signing_key = generate_signing_key(&cred.secret_access_key, &date_only, &self.region); - let signature = hex_hmac_sha256(&signing_key, string_to_sign.as_bytes()); + let signing_key = + generate_signing_key(provider, &cred.secret_access_key, &date_only, &self.region)?; + let signature = hex_hmac_sha256(provider, &signing_key, string_to_sign.as_bytes())?; let final_uri = if expires_in.is_some() { let unsigned_uri = append_query_pairs(&original_uri, &authentication_query)?; @@ -352,6 +356,7 @@ fn signed_header_names(ctx: &SigningRequest, is_presign: bool) -> Vec<&str> { } fn canonical_request_hash( + provider: &dyn CryptoProvider, ctx: &SigningRequest, canonical_query: &[(String, String)], signed_headers: &[&str], @@ -417,20 +422,25 @@ fn canonical_request_hash( canonical_request.push_str(payload_hash); - let hash = hex_sha256(canonical_request.as_bytes()); + let hash = hex_sha256(provider, canonical_request.as_bytes())?; Ok((hash, canonical_request)) } -fn generate_signing_key(secret: &str, date: &str, region: &str) -> Vec { +fn generate_signing_key( + provider: &dyn CryptoProvider, + secret: &str, + date: &str, + region: &str, +) -> Result> { // Sign date - let sign_date = hmac_sha256(secret.as_bytes(), date.as_bytes()); + let sign_date = hmac_sha256(provider, secret.as_bytes(), date.as_bytes())?; // Sign region - let sign_region = hmac_sha256(sign_date.as_slice(), region.as_bytes()); + let sign_region = hmac_sha256(provider, sign_date.as_slice(), region.as_bytes())?; // Sign service - let sign_service = hmac_sha256(sign_region.as_slice(), "tos".as_bytes()); + let sign_service = hmac_sha256(provider, sign_region.as_slice(), "tos".as_bytes())?; // Sign request - hmac_sha256(sign_service.as_slice(), "request".as_bytes()) + Ok(hmac_sha256(provider, sign_service.as_slice(), "request".as_bytes())?.to_vec()) } #[cfg(test)] @@ -442,7 +452,7 @@ mod tests { use super::*; use crate::provide_credential::StaticCredentialProvider; - use reqsign_core::{Context, OsEnv, Signer}; + use reqsign_core::{OsEnv, Signer}; use reqsign_file_read_tokio::TokioFileRead; use reqsign_http_send_reqwest::ReqwestHttpSend; @@ -456,7 +466,12 @@ mod tests { .with_time(Timestamp::parse_rfc2822("Sat, 1 Jan 2022 00:00:00 GMT")?); let (mut parts, _) = req.into_parts(); signer - .sign_request(&Context::new(), &mut parts, Some(credential), Some(expires)) + .sign_request( + &crate::test_context(), + &mut parts, + Some(credential), + Some(expires), + ) .await?; Ok(parts) } @@ -469,7 +484,7 @@ mod tests { let signer = RequestSigner::new("cn-beijing") .with_time(Timestamp::parse_rfc2822("Sat, 1 Jan 2022 00:00:00 GMT")?); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -511,7 +526,7 @@ mod tests { let signer = RequestSigner::new("cn-beijing").with_time("2026-02-03T12:24:12Z".parse()?); - let ctx = Context::new() + let ctx = crate::test_context() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) .with_env(OsEnv); @@ -643,6 +658,7 @@ mod tests { ); let canonical_query = canonicalize_query(&signing_req, &authentication_query); let (_, canonical_request) = canonical_request_hash( + &reqsign_crypto_rustcrypto::RustCryptoProvider::new(), &signing_req, &canonical_query, &signed_headers, @@ -664,7 +680,12 @@ mod tests { .unwrap() .set_sensitive(true); signer - .sign_request(&Context::new(), &mut header_parts, Some(&credential), None) + .sign_request( + &crate::test_context(), + &mut header_parts, + Some(&credential), + None, + ) .await?; assert_eq!(header_parts.uri.to_string(), original_uri); assert_eq!(header_parts.headers["x-custom"], "alpha beta"); @@ -673,7 +694,7 @@ mod tests { let mut query_parts = http::Request::get(&original_uri).body(())?.into_parts().0; signer .sign_request( - &Context::new(), + &crate::test_context(), &mut query_parts, Some(&credential), Some(Duration::from_secs(60)), @@ -716,7 +737,7 @@ mod tests { signer .sign_request( - &Context::new(), + &crate::test_context(), &mut query_parts, Some(&credential), Some(Duration::from_secs(60)), @@ -735,7 +756,12 @@ mod tests { let original_header_parts = header_parts.clone(); signer - .sign_request(&Context::new(), &mut header_parts, Some(&credential), None) + .sign_request( + &crate::test_context(), + &mut header_parts, + Some(&credential), + None, + ) .await .expect_err("an existing authorization header must be rejected"); assert_request_head_unchanged(&header_parts, &original_header_parts); diff --git a/services/volcengine-tos/tests/common/mod.rs b/services/volcengine-tos/tests/common/mod.rs new file mode 100644 index 00000000..864b1164 --- /dev/null +++ b/services/volcengine-tos/tests/common/mod.rs @@ -0,0 +1,22 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use reqsign_core::Context; + +pub fn test_context() -> Context { + Context::new().with_crypto(reqsign_crypto_rustcrypto::RustCryptoProvider::new()) +} diff --git a/services/volcengine-tos/tests/presigned.rs b/services/volcengine-tos/tests/presigned.rs index e3fb9052..efaad669 100644 --- a/services/volcengine-tos/tests/presigned.rs +++ b/services/volcengine-tos/tests/presigned.rs @@ -15,6 +15,8 @@ // specific language governing permissions and limitations // under the License. +mod common; + use anyhow::{Context as _, Result}; use http::{Method, Request, StatusCode}; use log::warn; @@ -33,7 +35,7 @@ async fn test_presigned_object_lifecycle() -> Result<()> { return Ok(()); }; - let ctx = Context::new(); + let ctx = crate::common::test_context(); let signer = RequestSigner::new(&cfg.region); let client = Client::new(); let object_key = format!( @@ -132,7 +134,10 @@ async fn signed_request( *req.method_mut() = method; *req.uri_mut() = http::Uri::from_str(url)?; if !req.body().is_empty() { - let content_sha256 = hex_sha256(req.body().as_bytes()); + let content_sha256 = hex_sha256( + &reqsign_crypto_rustcrypto::RustCryptoProvider::new(), + req.body().as_bytes(), + )?; req.headers_mut() .insert("x-tos-content-sha256", content_sha256.parse()?); } diff --git a/services/volcengine-tos/tests/signing_diagnostics.rs b/services/volcengine-tos/tests/signing_diagnostics.rs index 75339b11..fcf8a9f9 100644 --- a/services/volcengine-tos/tests/signing_diagnostics.rs +++ b/services/volcengine-tos/tests/signing_diagnostics.rs @@ -15,11 +15,13 @@ // specific language governing permissions and limitations // under the License. +mod common; + use std::sync::{Mutex, Once}; use std::time::Duration; use http::header::AUTHORIZATION; -use reqsign_core::{Context, SignRequest}; +use reqsign_core::SignRequest; use reqsign_volcengine_tos::{Credential, RequestSigner}; const ACCESS_KEY_ID: &str = "synthetic-volcengine-access-key-id"; @@ -93,7 +95,12 @@ async fn signing_diagnostics_redact_credential_material() -> anyhow::Result<()> .into_parts() .0; signer - .sign_request(&Context::new(), &mut parts, Some(&credential), None) + .sign_request( + &crate::common::test_context(), + &mut parts, + Some(&credential), + None, + ) .await?; let authorization = parts.headers[AUTHORIZATION].to_str()?.to_string(); @@ -129,7 +136,7 @@ async fn signing_diagnostics_redact_credential_material() -> anyhow::Result<()> .0; signer .sign_request( - &Context::new(), + &crate::common::test_context(), &mut parts, Some(&credential), Some(Duration::from_secs(3600)), diff --git a/website/data/providers.json b/website/data/providers.json index 05023992..8d361e9e 100644 --- a/website/data/providers.json +++ b/website/data/providers.json @@ -3,7 +3,11 @@ "internal_crates": [ { "name": "reqsign-core", - "role": "Core traits (ProvideCredential, SignRequest, GrantCredential) and the runtime-agnostic Context, Signer, and Granter types." + "role": "Core traits (ProvideCredential, SignRequest, GrantCredential), context crypto resolution, and the runtime-agnostic Context, Signer, and Granter types." + }, + { + "name": "reqsign-crypto-rustcrypto", + "role": "Pure-Rust CryptoProvider backend, re-exported by the reqsign facade's default-crypto feature and bound by the facade default context when no global provider is installed." }, { "name": "reqsign-aws-core", diff --git a/website/docs/architecture.md b/website/docs/architecture.md index 466653f7..1f45850e 100644 --- a/website/docs/architecture.md +++ b/website/docs/architecture.md @@ -103,6 +103,36 @@ capabilities by simply not providing them; and WASM targets provide browser-backed implementations. See [Custom runtimes & WASM](/docs/guides/custom-runtimes/). +## Crypto provider + +Cryptography is resolved through `Context`. Every hash, MAC, asymmetric +signature, AES-GCM operation, and random draw calls +`ctx.crypto_provider()`, which prefers an explicit +`Context::with_crypto` binding, then the process-wide provider installed with +`RustCryptoProvider::install_default()`: + +```rust +use reqsign::{Context, RustCryptoProvider, Signer}; + +// Explicit provider for this context. +let ctx = Context::new().with_crypto(RustCryptoProvider::new()); + +// Or install before constructing facade contexts to select one provider. +RustCryptoProvider::install_default() + .map_err(|_| "a CryptoProvider is already installed")?; +``` + +`reqsign-core` and the service crates contain no cryptographic implementation. +A bare `Context::new()` starts unbound and returns `ConfigInvalid` when signing +needs crypto without a global provider. The facade's `default-crypto` feature +makes `default_context()` bind RustCrypto only when the process-wide slot is +empty at construction; it never writes the slot. A context that already binds +RustCrypto keeps it, and an explicit `with_crypto` binding always wins. +Applications choose the provider, and integrating middleware such as OpenDAL +must not install a global default. See +[CryptoProvider](https://github.com/apache/reqsign/blob/main/docs/crypto-provider.md) +for the full contract and error semantics. + ## ProvideCredential One trait behind every credential source — an env reader, a config-file diff --git a/website/docs/getting-started.md b/website/docs/getting-started.md index 9bc7dbff..7d638833 100644 --- a/website/docs/getting-started.md +++ b/website/docs/getting-started.md @@ -52,10 +52,12 @@ cargo add http anyhow | `volcengine` | Volcengine TOS | | `full` | Everything above | -The default `default-context` feature wires a ready-to-use runtime (Tokio -file reading, reqwest HTTP, Tokio command execution). Keep it unless you are -[bringing your own runtime](/docs/guides/custom-runtimes/). Requires -Rust 1.86.0+. +The default features include `default-context`, which wires a ready-to-use +runtime (Tokio file reading, reqwest HTTP, Tokio command execution), and +`default-crypto`, which lets `default_context()` bind RustCrypto when no +process-wide provider is installed. Keep `default-context` unless you are +[bringing your own runtime](/docs/guides/custom-runtimes/); a custom context +must bind a `CryptoProvider` explicitly. Requires Rust 1.86.0+. ## 2. Sign your first request diff --git a/website/docs/guides/testing.md b/website/docs/guides/testing.md index df9dc40e..e3731eae 100644 --- a/website/docs/guides/testing.md +++ b/website/docs/guides/testing.md @@ -33,11 +33,12 @@ still uses the current time, so this example checks the authentication header rather than asserting a timestamp-dependent signature: ```rust -use reqsign::{Context, Signer}; +use reqsign::{Context, RustCryptoProvider, Signer}; use reqsign::aws::{RequestSigner, StaticCredentialProvider}; let signer = Signer::new( - Context::new(), // no I/O needed with static credentials + // No I/O needed with static credentials; bind crypto locally. + Context::new().with_crypto(RustCryptoProvider::new()), StaticCredentialProvider::new("AKIDEXAMPLE", "example-secret-key"), RequestSigner::new("s3", "us-east-1"), ); diff --git a/website/docs/reference/api.md b/website/docs/reference/api.md index 306b2840..082363b5 100644 --- a/website/docs/reference/api.md +++ b/website/docs/reference/api.md @@ -34,8 +34,8 @@ rustdoc owns signatures. ## Core - [`reqsign-core`](https://docs.rs/reqsign-core) — `Context`, `Signer`, - `Granter`, and the `ProvideCredential` / `SignRequest` / - `GrantCredential` / `SigningCredential` traits. + `Granter`, the `ProvideCredential` / `SignRequest` / `GrantCredential` / + `SigningCredential` traits, and the `crypto::CryptoProvider` contract. ## Service crates @@ -52,6 +52,13 @@ rustdoc owns signatures. - [`reqsign-tencent-cos`](https://docs.rs/reqsign-tencent-cos) - [`reqsign-volcengine-tos`](https://docs.rs/reqsign-volcengine-tos) +## Crypto providers + +- [`reqsign-crypto-rustcrypto`](https://docs.rs/reqsign-crypto-rustcrypto) — + pure-Rust provider, including the supported WASM subset +- [`reqsign-crypto-boring`](https://docs.rs/reqsign-crypto-boring) — native + BoringSSL provider, built outside the main workspace + ## Context components - [`reqsign-file-read-tokio`](https://docs.rs/reqsign-file-read-tokio)