From 9e53def7d652309c2738fd746aba673fba5c172d Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Thu, 19 Nov 2026 18:09:58 +0100 Subject: [PATCH 01/11] feat(core): require an installed CryptoProvider Move all signing cryptography out of reqsign-core and the service crates behind a process-wide CryptoProvider. Core installs one provider at most once, never falls back to a bundled implementation, and returns ConfigInvalid when no provider is installed. Hash, HMAC, and JWT helpers now propagate failures; the rsa-typed JWT entry point is removed. Migrate every signing call site, including AWS SSO/SigV4a, Azure client certificate and SAS, Google service account and client-side CAB, Oracle, Aliyun, Huawei, Tencent, and Volcengine. On-wire formats and existing caller contracts are preserved. Add reqsign-crypto-rustcrypto as a workspace member with native support for all operations and the existing WASM subset, and add the excluded, native-only reqsign-crypto-boring crate with a dedicated Linux CI job. The reqsign facade re-exports RustCryptoProvider behind default-crypto but never installs it implicitly. Document the contract, ownership and migration in docs/crypto-provider.md. --- .github/workflows/ci.yml | 26 +- .github/workflows/crypto_boring.yml | 63 ++++ AGENTS.md | 9 + Cargo.toml | 5 +- README.md | 11 +- core/Cargo.toml | 10 +- core/src/crypto.rs | 141 ++++++++ core/src/hash.rs | 90 ++--- core/src/jwt.rs | 156 ++++---- core/src/lib.rs | 9 +- core/src/test_support.rs | 79 ++++ core/tests/crypto_provider_concurrency.rs | 59 +++ core/tests/crypto_provider_early_lookup.rs | 31 ++ core/tests/crypto_provider_second_install.rs | 43 +++ core/tests/crypto_provider_unset.rs | 52 +++ core/tests/support/mod.rs | 52 +++ crypto/boring/Cargo.toml | 46 +++ crypto/boring/src/lib.rs | 207 +++++++++++ .../boring/tests/fixtures/ec_p256_pkcs8.pem | 5 + crypto/boring/tests/fixtures/rsa_pkcs1.pem | 27 ++ crypto/boring/tests/fixtures/rsa_pkcs8.pem | 28 ++ crypto/boring/tests/parity.rs | 288 +++++++++++++++ crypto/rustcrypto/Cargo.toml | 43 +++ crypto/rustcrypto/src/lib.rs | 163 +++++++++ crypto/rustcrypto/tests/core_hash.rs | 106 ++++++ .../tests/fixtures/ec_p256_pkcs8.pem | 5 + .../rustcrypto/tests/fixtures/rsa_pkcs1.pem | 27 ++ .../rustcrypto/tests/fixtures/rsa_pkcs8.pem | 28 ++ crypto/rustcrypto/tests/provider.rs | 336 ++++++++++++++++++ docs/crypto-provider.md | 301 ++++++++++++++++ reqsign/Cargo.toml | 21 +- reqsign/README.md | 15 +- reqsign/examples/aws.rs | 2 + reqsign/examples/azure.rs | 2 + reqsign/examples/custom_context.rs | 2 + reqsign/examples/custom_http.rs | 2 + reqsign/examples/google.rs | 2 + reqsign/examples/presign.rs | 2 + reqsign/examples/s3_express_grant.rs | 2 + reqsign/examples/s3_express_sign.rs | 2 + reqsign/examples/static_credentials.rs | 2 + reqsign/src/context.rs | 5 + reqsign/src/lib.rs | 5 + reqsign/tests/crypto.rs | 28 ++ services/aliyun-oss/Cargo.toml | 2 + services/aliyun-oss/README.md | 4 + services/aliyun-oss/src/assume_role.rs | 5 +- services/aliyun-oss/src/lib.rs | 8 + .../src/provide_credential/assume_role.rs | 2 +- services/aliyun-oss/src/sign_request.rs | 22 +- services/aliyun-oss/tests/common/mod.rs | 24 ++ services/aliyun-oss/tests/credential_chain.rs | 2 + services/aliyun-oss/tests/main.rs | 2 + services/aws-core/Cargo.toml | 3 +- services/aws-core/src/assume_role.rs | 4 +- services/aws-core/src/lib.rs | 13 +- .../src/provide_credential/sso/session.rs | 11 +- .../src/provide_credential/sso/tests.rs | 7 +- services/aws-core/tests/common/mod.rs | 24 ++ services/aws-core/tests/shared_config.rs | 2 + services/aws-v4/Cargo.toml | 2 + services/aws-v4/README.md | 6 +- services/aws-v4/benches/aws.rs | 3 + services/aws-v4/examples/dynamodb_sign.rs | 9 +- services/aws-v4/examples/s3_express_sign.rs | 3 + services/aws-v4/examples/s3_sign.rs | 3 + services/aws-v4/src/assume_role.rs | 2 +- services/aws-v4/src/lib.rs | 8 + services/aws-v4/src/sign_request.rs | 26 +- services/aws-v4/tests/common/mod.rs | 24 ++ services/aws-v4/tests/main.rs | 2 + services/aws-v4a/Cargo.toml | 4 +- services/aws-v4a/README.md | 4 + services/aws-v4a/src/lib.rs | 8 + services/aws-v4a/src/sign_request.rs | 58 +-- services/azure-storage/Cargo.toml | 4 +- services/azure-storage/README.md | 4 + services/azure-storage/src/lib.rs | 8 + .../provide_credential/client_certificate.rs | 35 +- services/azure-storage/src/service_sas.rs | 17 +- services/azure-storage/src/sign_request.rs | 14 +- services/azure-storage/src/user_delegation.rs | 5 +- .../azure-storage/src/user_delegation_sas.rs | 16 +- services/azure-storage/tests/common/mod.rs | 24 ++ services/azure-storage/tests/main.rs | 2 + services/google/Cargo.toml | 8 +- services/google/README.md | 4 + .../credential_access_boundary/client_side.rs | 37 +- services/google/src/lib.rs | 8 + services/google/src/sign_request.rs | 25 +- services/google/tests/common/mod.rs | 24 ++ .../tests/credential_access_boundary.rs | 2 + .../explicit_credential_access_boundary.rs | 2 + services/google/tests/fixtures.rs | 2 + services/google/tests/main.rs | 2 + services/google/tests/oauth_token_endpoint.rs | 2 + .../google/tests/service_account_token.rs | 2 + services/huaweicloud-obs/Cargo.toml | 2 + services/huaweicloud-obs/README.md | 4 + services/huaweicloud-obs/src/agency.rs | 6 +- services/huaweicloud-obs/src/lib.rs | 8 + services/huaweicloud-obs/src/sign_request.rs | 2 +- services/huaweicloud-obs/tests/common/mod.rs | 24 ++ .../huaweicloud-obs/tests/credential_chain.rs | 2 + services/oracle/Cargo.toml | 4 +- services/oracle/README.md | 4 + services/oracle/src/lib.rs | 8 + services/oracle/src/sign_request.rs | 33 +- services/oracle/tests/common/mod.rs | 24 ++ services/oracle/tests/config_profiles.rs | 2 + services/oracle/tests/credential_chain.rs | 2 + services/oracle/tests/private_key_formats.rs | 2 + services/tencent-cos/Cargo.toml | 2 + services/tencent-cos/README.md | 4 + .../tencent-cos/src/get_federation_token.rs | 12 +- services/tencent-cos/src/lib.rs | 8 + services/tencent-cos/src/sign_request.rs | 16 +- services/tencent-cos/tests/common/mod.rs | 24 ++ .../tencent-cos/tests/credential_chain.rs | 2 + services/tencent-cos/tests/main.rs | 2 + .../tencent-cos/tests/web_identity_live.rs | 2 + services/volcengine-tos/Cargo.toml | 2 + services/volcengine-tos/README.md | 4 + services/volcengine-tos/src/assume_role.rs | 16 +- services/volcengine-tos/src/lib.rs | 8 + services/volcengine-tos/src/sign_request.rs | 16 +- services/volcengine-tos/tests/common/mod.rs | 24 ++ services/volcengine-tos/tests/presigned.rs | 4 +- .../tests/signing_diagnostics.rs | 2 + website/docs/architecture.md | 21 ++ website/docs/guides/testing.md | 5 +- website/docs/reference/api.md | 11 +- 132 files changed, 3053 insertions(+), 341 deletions(-) create mode 100644 .github/workflows/crypto_boring.yml create mode 100644 core/src/crypto.rs create mode 100644 core/src/test_support.rs create mode 100644 core/tests/crypto_provider_concurrency.rs create mode 100644 core/tests/crypto_provider_early_lookup.rs create mode 100644 core/tests/crypto_provider_second_install.rs create mode 100644 core/tests/crypto_provider_unset.rs create mode 100644 core/tests/support/mod.rs create mode 100644 crypto/boring/Cargo.toml create mode 100644 crypto/boring/src/lib.rs create mode 100644 crypto/boring/tests/fixtures/ec_p256_pkcs8.pem create mode 100644 crypto/boring/tests/fixtures/rsa_pkcs1.pem create mode 100644 crypto/boring/tests/fixtures/rsa_pkcs8.pem create mode 100644 crypto/boring/tests/parity.rs create mode 100644 crypto/rustcrypto/Cargo.toml create mode 100644 crypto/rustcrypto/src/lib.rs create mode 100644 crypto/rustcrypto/tests/core_hash.rs create mode 100644 crypto/rustcrypto/tests/fixtures/ec_p256_pkcs8.pem create mode 100644 crypto/rustcrypto/tests/fixtures/rsa_pkcs1.pem create mode 100644 crypto/rustcrypto/tests/fixtures/rsa_pkcs8.pem create mode 100644 crypto/rustcrypto/tests/provider.rs create mode 100644 docs/crypto-provider.md create mode 100644 reqsign/tests/crypto.rs create mode 100644 services/aliyun-oss/tests/common/mod.rs create mode 100644 services/aws-core/tests/common/mod.rs create mode 100644 services/aws-v4/tests/common/mod.rs create mode 100644 services/azure-storage/tests/common/mod.rs create mode 100644 services/google/tests/common/mod.rs create mode 100644 services/huaweicloud-obs/tests/common/mod.rs create mode 100644 services/oracle/tests/common/mod.rs create mode 100644 services/tencent-cos/tests/common/mod.rs create mode 100644 services/volcengine-tos/tests/common/mod.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d820dfbb..e9c355b2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -44,6 +44,29 @@ 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 + ) + for package in "${packages[@]}"; do + if cargo tree -p "$package" --edges normal | 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 @@ -99,10 +122,11 @@ jobs: run: | rustup target add wasm32-unknown-unknown cargo check -p reqsign-core --target wasm32-unknown-unknown + cargo check -p 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 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..574fad54 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -40,6 +40,15 @@ 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 the process-wide +`reqsign_core::crypto::CryptoProvider`. `reqsign-core` and every `services/*` +crate carry no production cryptographic implementation. Follow +[docs/crypto-provider.md](docs/crypto-provider.md) as the source of truth for +the provider contract, installation ownership, error semantics, and the +official RustCrypto/BoringSSL implementations. + ### Default Credential Provider All future refactors and API reviews around `DefaultCredentialProvider` must diff --git a/Cargo.toml b/Cargo.toml index 94ccb168..5f6d7b54 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.1.1", 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 = "3.3.4", path = "crypto/rustcrypto" } reqsign-file-read-tokio = { version = "3.0.9", path = "context/file-read-tokio" } reqsign-google = { version = "3.3.1", 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 1e60a136..59f8fac3 100644 --- a/README.md +++ b/README.md @@ -22,10 +22,14 @@ The simplest way to use `reqsign` is with the default signers provided by each s ```rust use anyhow::Result; -use reqsign::aws; +use reqsign::{RustCryptoProvider, aws}; #[tokio::main] async fn main() -> Result<()> { + // Install the process-wide crypto provider once, before any signing. + RustCryptoProvider::install_default() + .map_err(|_| anyhow::anyhow!("a CryptoProvider is already installed"))?; + // Create a default signer for S3 in us-east-1 // This will automatically: // - Load credentials from environment variables, config files, or IAM roles @@ -56,13 +60,16 @@ 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<()> { + RustCryptoProvider::install_default() + .map_err(|_| anyhow::anyhow!("a CryptoProvider is already installed"))?; + // Build your own context with specific implementations let ctx = Context::new() .with_file_read(TokioFileRead) diff --git a/core/Cargo.toml b/core/Cargo.toml index dc3a0428..479e387a 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -29,7 +29,7 @@ rust-version.workspace = true [features] default = [] -jwt = ["dep:rsa", "dep:serde", "dep:serde_json"] +jwt = ["dep:serde", "dep:serde_json"] [dependencies] anyhow = { workspace = true } @@ -37,16 +37,12 @@ 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 } @@ -60,3 +56,7 @@ windows-sys = { version = "0.61.0", features = [ [dev-dependencies] asyncband = { workspace = true, features = ["oneshot"] } futures = { workspace = true } +hmac = { workspace = true } +rsa = { workspace = true } +sha1 = { workspace = true } +sha2 = { workspace = true } diff --git a/core/src/crypto.rs b/core/src/crypto.rs new file mode 100644 index 00000000..422cee4d --- /dev/null +++ b/core/src/crypto.rs @@ -0,0 +1,141 @@ +// 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. Applications install +//! one [`CryptoProvider`] at startup with [`install_default`]. All hashing, +//! signing, encryption and random generation performed by reqsign goes through +//! the installed provider. +//! +//! A process can install at most one provider. The installation is idempotent +//! from the caller's perspective: later attempts return the provider they tried +//! to install and leave the first provider in place. + +use std::fmt::Debug; +use std::sync::{Arc, OnceLock}; + +use crate::{Error, Result}; + +/// Cryptographic operations required by reqsign. +/// +/// 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() +} + +pub(crate) fn require_default() -> Result<&'static Arc> { + get_default().ok_or_else(|| { + Error::config_invalid( + "no CryptoProvider is installed; install one during application startup", + ) + }) +} diff --git a/core/src/hash.rs b/core/src/hash.rs index 7300d8d5..3b126a41 100644 --- a/core/src/hash.rs +++ b/core/src/hash.rs @@ -16,16 +16,15 @@ // under the License. //! Hash related utils. +//! +//! Encoding helpers are pure functions. Digest and MAC helpers use the +//! process-wide [`crate::crypto::CryptoProvider`] and return an error when no +//! provider is installed or the installed provider cannot serve the operation. -use crate::Error; +use crate::crypto; +use crate::{Error, Result}; 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 +38,52 @@ 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(content: &[u8]) -> Result<[u8; 20]> { + crypto::require_default()?.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(content: &[u8]) -> Result<[u8; 32]> { + crypto::require_default()?.sha256(content) +} + +/// HMAC with SHA1 hash. +pub fn hmac_sha1(key: &[u8], content: &[u8]) -> Result<[u8; 20]> { + crypto::require_default()?.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(key: &[u8], content: &[u8]) -> Result<[u8; 32]> { + crypto::require_default()?.hmac_sha256(key, content) +} - h.finalize().into_bytes().to_vec() +/// Hex encoded SHA1 hash. +pub fn hex_sha1(content: &[u8]) -> Result { + Ok(hex::encode(sha1(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(content: &[u8]) -> Result { + Ok(hex::encode(sha256(content)?)) +} - base64_encode(&h.finalize().into_bytes()) +/// Base64 encoded HMAC with SHA256 hash. +pub fn base64_hmac_sha256(key: &[u8], content: &[u8]) -> Result { + Ok(base64_encode(&hmac_sha256(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(key: &[u8], content: &[u8]) -> Result { + Ok(hex::encode(hmac_sha1(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(key: &[u8], content: &[u8]) -> Result { + Ok(hex::encode(hmac_sha256(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(key: &[u8], content: &[u8]) -> Result { + Ok(base64_encode(&hmac_sha1(key, content)?)) } diff --git a/core/src/jwt.rs b/core/src/jwt.rs index 413ff8fb..8f8d4df9 100644 --- a/core/src/jwt.rs +++ b/core/src/jwt.rs @@ -19,21 +19,18 @@ 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::crypto; use crate::{Error, Result}; -/// Encode a JWS compact JWT using the RS256 algorithm. +/// Encode a JWS compact JWT using an RSA private key in PKCS#8 or PKCS#1 PEM +/// format. /// /// 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 +/// Signing is performed by the installed [`crypto::CryptoProvider`]. +pub fn encode_rs256_pem(header: &H, claims: &C, private_key_pem: &[u8]) -> Result where H: Serialize, C: Serialize, @@ -42,28 +39,13 @@ where 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()); + let signature = crypto::require_default()? + .rsa_pkcs1v15_sha256_sign(private_key_pem, signing_input.as_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) + Ok(format!( + "{signing_input}.{}", + URL_SAFE_NO_PAD.encode(signature) + )) } fn encode_json(value: &T) -> Result @@ -78,9 +60,15 @@ where #[cfg(test)] mod tests { use super::*; + use crate::crypto::install_default; + use crate::test_support::TestCryptoProvider; use base64::engine::general_purpose::URL_SAFE_NO_PAD; + use rsa::RsaPrivateKey; + use rsa::pkcs1::{DecodeRsaPrivateKey, EncodeRsaPrivateKey}; use rsa::pkcs1v15::{Signature, VerifyingKey}; + use rsa::pkcs8::{DecodePrivateKey, EncodePrivateKey}; use rsa::rand_core::OsRng; + use rsa::sha2::Sha256; use rsa::signature::Verifier; use serde_json::json; @@ -99,55 +87,103 @@ mod tests { 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, - )?; + fn private_key() -> RsaPrivateKey { + RsaPrivateKey::new(&mut OsRng, 1024).expect("test RSA key generation must work") + } + fn verify(header: &Header<'_>, claims: &Claims<'_>, jwt: &str, pem: &[u8]) { let parts = jwt.split('.').collect::>(); assert_eq!(parts.len(), 3); - let header: serde_json::Value = serde_json::from_slice( + let header_value: 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))?, + .expect("JWT header must decode"), ) - .map_err(|e| Error::unexpected("failed to parse JWT header").with_source(e))?; + .expect("JWT header must be JSON"); assert_eq!( - header, + header_value, json!({ - "alg": "RS256", - "typ": "JWT", - "x5t": "thumbprint" + "alg": header.alg, + "typ": header.typ, + "x5t": header.x5t }) ); + assert_eq!( + URL_SAFE_NO_PAD + .decode(parts[1]) + .expect("JWT claims must decode"), + serde_json::to_vec(claims).expect("claims must serialize") + ); let signature = URL_SAFE_NO_PAD .decode(parts[2]) - .map_err(|e| Error::unexpected("failed to decode JWT signature").with_source(e))?; + .expect("JWT signature must decode"); let signature = Signature::try_from(signature.as_slice()) - .map_err(|e| Error::unexpected("failed to parse JWT signature").with_source(e))?; + .expect("JWT signature must be a PKCS#1 v1.5 signature"); + let private_key = + RsaPrivateKey::from_pkcs8_pem(std::str::from_utf8(pem).expect("PEM must be UTF-8")) + .or_else(|_| { + RsaPrivateKey::from_pkcs1_pem( + std::str::from_utf8(pem).expect("PEM must be UTF-8"), + ) + }) + .expect("test PEM must parse"); 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))?; + .expect("JWT signature must verify"); + } + + #[test] + fn encode_rs256_pem_keeps_jws_shape_and_verifiable_signature() { + let _ = install_default(TestCryptoProvider); + let private_key = private_key(); + let header = Header { + alg: "RS256", + typ: "JWT", + x5t: "thumbprint", + }; + let claims = Claims { + iss: "client", + sub: "client", + aud: "https://example.com/token", + exp: 1, + }; + + for pem in [ + private_key + .to_pkcs8_pem(rsa::pkcs8::LineEnding::LF) + .expect("test key must encode as PKCS#8"), + private_key + .to_pkcs1_pem(rsa::pkcs1::LineEnding::LF) + .expect("test key must encode as PKCS#1"), + ] { + let jwt = encode_rs256_pem(&header, &claims, pem.as_bytes()) + .expect("JWT encoding must succeed"); + verify(&header, &claims, &jwt, pem.as_bytes()); + } + } + + #[test] + fn encode_rs256_pem_rejects_malformed_key_material() { + let _ = install_default(TestCryptoProvider); + let err = encode_rs256_pem( + &Header { + alg: "RS256", + typ: "JWT", + x5t: "thumbprint", + }, + &Claims { + iss: "client", + sub: "client", + aud: "https://example.com/token", + exp: 1, + }, + b"not a private key", + ) + .expect_err("malformed private key must fail"); - Ok(()) + assert_eq!(err.kind(), crate::ErrorKind::CredentialInvalid); } } diff --git a/core/src/lib.rs b/core/src/lib.rs index 324e35ee..6c3deba4 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -173,19 +173,24 @@ //! //! 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"))] +#[cfg(feature = "jwt")] pub mod jwt; pub mod time; pub mod utils; +#[cfg(all(test, feature = "jwt"))] +mod test_support; + mod api; pub use self::api::GrantCredential; pub use self::api::GrantCredentialDyn; diff --git a/core/src/test_support.rs b/core/src/test_support.rs new file mode 100644 index 00000000..9c1cf0ea --- /dev/null +++ b/core/src/test_support.rs @@ -0,0 +1,79 @@ +// 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. + +//! Test-only cryptographic provider for `reqsign-core` unit tests. +//! +//! `reqsign-core` cannot use `reqsign-crypto-rustcrypto` in its own unit tests: +//! the dev-dependency would link a second, non-test instance of +//! `reqsign-core`, and installation would populate that instance's +//! `OnceLock` instead of the one used by the test. This local provider keeps +//! crypto dependencies dev-only and installs into the test instance. + +use crate::crypto::CryptoProvider; +use crate::{Error, Result}; + +#[derive(Debug)] +pub(crate) struct TestCryptoProvider; + +impl CryptoProvider for TestCryptoProvider { + fn sha1(&self, input: &[u8]) -> Result<[u8; 20]> { + use sha1::Digest; + Ok(sha1::Sha1::digest(input).into()) + } + + fn sha256(&self, input: &[u8]) -> Result<[u8; 32]> { + use sha2::Digest; + Ok(sha2::Sha256::digest(input).into()) + } + + fn hmac_sha1(&self, key: &[u8], input: &[u8]) -> Result<[u8; 20]> { + use hmac::{Hmac, KeyInit, Mac}; + let mut hmac = Hmac::::new_from_slice(key) + .map_err(|e| Error::unexpected("failed to initialize HMAC-SHA1").with_source(e))?; + hmac.update(input); + Ok(hmac.finalize().into_bytes().into()) + } + + fn hmac_sha256(&self, key: &[u8], input: &[u8]) -> Result<[u8; 32]> { + use hmac::{Hmac, KeyInit, Mac}; + let mut hmac = Hmac::::new_from_slice(key) + .map_err(|e| Error::unexpected("failed to initialize HMAC-SHA256").with_source(e))?; + hmac.update(input); + Ok(hmac.finalize().into_bytes().into()) + } + + fn rsa_pkcs1v15_sha256_sign(&self, private_key_pem: &[u8], message: &[u8]) -> Result> { + use rsa::pkcs1::DecodeRsaPrivateKey; + use rsa::pkcs1v15::SigningKey; + use rsa::pkcs8::DecodePrivateKey; + use rsa::rand_core::OsRng; + use rsa::sha2::Sha256; + 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 = SigningKey::::new(private_key); + let signature = signing_key.sign_with_rng(&mut OsRng, message); + Ok(signature.to_bytes().to_vec()) + } +} diff --git a/core/tests/crypto_provider_concurrency.rs b/core/tests/crypto_provider_concurrency.rs new file mode 100644 index 00000000..b3f36631 --- /dev/null +++ b/core/tests/crypto_provider_concurrency.rs @@ -0,0 +1,59 @@ +// 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 std::sync::{Arc, Barrier}; + +use reqsign_core::crypto::{get_default, install_default}; +use support::TestProvider; + +#[test] +fn concurrent_installation_elects_exactly_one_provider() { + const NAMES: [&str; 16] = [ + "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", + "eleven", "twelve", "thirteen", "fourteen", "fifteen", + ]; + + let barrier = Arc::new(Barrier::new(NAMES.len())); + let handles = NAMES + .into_iter() + .map(|name| { + let barrier = barrier.clone(); + std::thread::spawn(move || { + barrier.wait(); + install_default(TestProvider::new(name)) + }) + }) + .collect::>(); + + let results = handles + .into_iter() + .map(|handle| handle.join().expect("install thread must not panic")) + .collect::>(); + + let winners = results.iter().filter(|result| result.is_ok()).count(); + let installed = get_default().expect("one provider must be installed"); + + assert_eq!(winners, 1, "exactly one concurrent install must succeed"); + for rejected in results.iter().filter_map(|result| result.as_ref().err()) { + assert!( + !Arc::ptr_eq(rejected, installed), + "a rejected provider must not be the installed provider" + ); + } +} 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..ecf4b7af --- /dev/null +++ b/core/tests/crypto_provider_second_install.rs @@ -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. + +mod support; + +use std::sync::Arc; + +use reqsign_core::crypto::{get_default, install_default}; +use support::TestProvider; + +#[test] +fn second_installation_returns_the_rejected_provider_without_replacing_first() { + install_default(TestProvider::new("first")).expect("first install must succeed"); + let installed = Arc::as_ptr(get_default().expect("provider must be installed")); + + let rejected = + install_default(TestProvider::new("second")).expect_err("second install must be rejected"); + + assert_eq!( + Arc::as_ptr(get_default().expect("provider must stay installed")), + installed, + "the first provider must remain installed" + ); + assert_ne!( + Arc::as_ptr(&rejected), + installed, + "the error must return the provider that was not installed" + ); +} diff --git a/core/tests/crypto_provider_unset.rs b/core/tests/crypto_provider_unset.rs new file mode 100644 index 00000000..34cdbf4d --- /dev/null +++ b/core/tests/crypto_provider_unset.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. + +//! 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::ErrorKind; +use reqsign_core::crypto::get_default; +use reqsign_core::hash; + +#[test] +fn unset_provider_returns_config_invalid_without_panicking() { + assert!(get_default().is_none()); + + let err = hash::sha256(b"payload").expect_err("hashing without a provider must fail"); + assert_eq!(err.kind(), ErrorKind::ConfigInvalid); + assert!(!err.is_retryable()); + + let err = hash::sha1(b"payload").expect_err("hashing without a provider must fail"); + assert_eq!(err.kind(), ErrorKind::ConfigInvalid); + + let err = hash::hmac_sha256(b"key", b"payload").expect_err("HMAC without a provider must fail"); + assert_eq!(err.kind(), ErrorKind::ConfigInvalid); + + let err = + hash::base64_hmac_sha1(b"key", b"payload").expect_err("HMAC without a provider must fail"); + assert_eq!(err.kind(), ErrorKind::ConfigInvalid); +} + +#[cfg(feature = "jwt")] +#[test] +fn jwt_signing_without_a_provider_returns_config_invalid() { + #[derive(serde::Serialize)] + struct Empty {} + let err = reqsign_core::jwt::encode_rs256_pem(&Empty {}, &Empty {}, b"not used") + .expect_err("JWT signing without a provider must fail"); + assert_eq!(err.kind(), ErrorKind::ConfigInvalid); +} diff --git a/core/tests/support/mod.rs b/core/tests/support/mod.rs new file mode 100644 index 00000000..0877ea93 --- /dev/null +++ b/core/tests/support/mod.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. + +#![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]) + } +} diff --git a/crypto/boring/Cargo.toml b/crypto/boring/Cargo.toml new file mode 100644 index 00000000..afa979f2 --- /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 = "0.1.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.3.1", path = "../../services/aws-core" } +reqsign-aws-v4 = { version = "3.4.1", path = "../../services/aws-v4" } +reqsign-crypto-rustcrypto = { version = "3.3.4", 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..cbe138e4 --- /dev/null +++ b/crypto/boring/tests/parity.rs @@ -0,0 +1,288 @@ +// 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() +} + +fn install_boring() { + let _ = BoringCryptoProvider::install_default(); +} + +#[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() { + install_boring(); + + 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::new(), &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..3b5243ed --- /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 = "3.3.4" + +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..cf8cb37f --- /dev/null +++ b/crypto/rustcrypto/tests/core_hash.rs @@ -0,0 +1,106 @@ +// 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::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; + +fn install_provider() { + let _ = RustCryptoProvider::install_default(); +} + +#[test] +fn hashes_match_published_vectors_with_expected_widths() { + install_provider(); + + assert_eq!( + hex::encode(sha1(b"abc").expect("SHA-1 must succeed")), + "a9993e364706816aba3e25717850c26c9cd0d89d" + ); + assert_eq!( + hex::encode(sha256(b"abc").expect("SHA-256 must succeed")), + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + assert_eq!(sha1(b"abc").expect("SHA-1 must succeed").len(), 20); + assert_eq!(sha256(b"abc").expect("SHA-256 must succeed").len(), 32); + + assert_eq!( + hex_sha1(b"abc").expect("hex SHA-1 must succeed"), + "a9993e364706816aba3e25717850c26c9cd0d89d" + ); + assert_eq!( + hex_sha256(b"abc").expect("hex SHA-256 must succeed"), + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); +} + +#[test] +fn hmac_matches_rfc_vectors_with_expected_widths() { + install_provider(); + + let key = [0x0b; 20]; + assert_eq!( + hex::encode(hmac_sha1(&key, b"Hi There").expect("HMAC-SHA1 must succeed")), + "b617318655057264e28bc0b6fb378c8ef146be00" + ); + assert_eq!( + hex::encode(hmac_sha256(&key, b"Hi There").expect("HMAC-SHA256 must succeed")), + "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7" + ); + assert_eq!( + hmac_sha1(&key, b"Hi There") + .expect("HMAC-SHA1 must succeed") + .len(), + 20 + ); + assert_eq!( + hmac_sha256(&key, b"Hi There") + .expect("HMAC-SHA256 must succeed") + .len(), + 32 + ); + + assert_eq!( + hex_hmac_sha1(&key, b"Hi There").expect("hex HMAC-SHA1 must succeed"), + "b617318655057264e28bc0b6fb378c8ef146be00" + ); + assert_eq!( + hex_hmac_sha256(&key, b"Hi There").expect("hex HMAC-SHA256 must succeed"), + "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7" + ); + assert_eq!( + base64_hmac_sha1(&key, b"Hi There").expect("base64 HMAC-SHA1 must succeed"), + "thcxhlUFcmTii8C2+zeMjvFGvgA=" + ); + assert_eq!( + base64_hmac_sha256(&key, b"Hi There").expect("base64 HMAC-SHA256 must succeed"), + "sDRMYdjbOFNcqK/OrwvxK4gdwgDJgz2nJuk3bC4yz/c=" + ); +} + +#[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..5342f45b --- /dev/null +++ b/crypto/rustcrypto/tests/provider.rs @@ -0,0 +1,336 @@ +// 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 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; +use rsa::signature::Verifier as _; + +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_match_published_vectors() { + let provider = provider(); + assert_eq!( + hex(&provider.sha1(b"abc").expect("SHA-1 must succeed")), + "a9993e364706816aba3e25717850c26c9cd0d89d" + ); + assert_eq!( + hex(&provider.sha256(b"abc").expect("SHA-256 must succeed")), + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + assert_eq!( + hex(&provider + .sha256(&vec![b'a'; 1_000_000]) + .expect("large SHA-256 must succeed")), + "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0" + ); +} + +#[test] +fn hmac_matches_rfc_vectors_at_block_boundaries() { + let provider = provider(); + + assert_eq!( + hex(&provider + .hmac_sha256(&[0x0b; 20], b"Hi There") + .expect("HMAC-SHA256 must succeed")), + "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7" + ); + assert_eq!( + hex(&provider + .hmac_sha1( + &[0xaa; 80], + b"Test Using Larger Than Block-Size Key - Hash Key First" + ) + .expect("HMAC-SHA1 must succeed")), + "aa4ae5e15272d00e95705637ce8a3b55ed402112" + ); + assert_eq!( + hex(&provider + .hmac_sha256( + &[0xaa; 131], + b"Test Using Larger Than Block-Size Key - Hash Key First" + ) + .expect("HMAC-SHA256 must succeed")), + "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54" + ); + + for (key, expected) in [ + ( + &b""[..], + "2b31f75fad699604041bb9a4e191657b10d638d3e1c0a3d79b8a1db8b1ed0826", + ), + ( + &b"k"[..], + "82de63a94b14635375eafcc20afd3629397e17ed1a9e79c128ca8e8f3a0cc7ab", + ), + ( + &[0u8; 64][..], + "2b31f75fad699604041bb9a4e191657b10d638d3e1c0a3d79b8a1db8b1ed0826", + ), + ( + &[0u8; 65][..], + "a0ade4ba44e1645ce9bd9bb9519260e658ea825e7ec2703144fbc77b76f9e567", + ), + ] { + assert_eq!( + hex(&provider + .hmac_sha256(key, b"boundary message") + .expect("HMAC-SHA256 boundary must succeed")), + expected + ); + } +} + +#[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..c28148cb --- /dev/null +++ b/docs/crypto-provider.md @@ -0,0 +1,301 @@ +# 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 one process-wide +`reqsign_core::crypto::CryptoProvider` installed by the application at startup. + +The change is deliberately breaking: a missing 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. + +## 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. + +## Registration + +```rust +pub fn install_default( + provider: impl CryptoProvider, +) -> std::result::Result<(), Arc>; + +pub fn get_default() -> Option<&'static Arc>; +``` + +Installation is backed by `OnceLock>` and 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`. +- `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. +- Reqsign never installs a provider implicitly and never falls back to a + bundled implementation. + +Applications own the choice of provider. Top-level binaries and services call +`install_default` once during startup. Integrating middleware, such as OpenDAL, +must not install a provider on behalf of its users: doing so would take away the +application's choice and can race with the application's own initialization. +Middleware should document the requirement and let the application fail with a +clear `ConfigInvalid` error if it has not installed one. + +## Failure Semantics + +| Condition | Error kind | Retryable | +| --- | --- | --- | +| No provider installed | `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 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 a provider is missing, 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 now return `Result` and delegate +to the installed provider: + +```rust +pub fn sha1(content: &[u8]) -> Result<[u8; 20]>; +pub fn sha256(content: &[u8]) -> Result<[u8; 32]>; +pub fn hmac_sha1(key: &[u8], content: &[u8]) -> Result<[u8; 20]>; +pub fn hmac_sha256(key: &[u8], content: &[u8]) -> Result<[u8; 32]>; +pub fn hex_sha1(content: &[u8]) -> Result; +pub fn hex_sha256(content: &[u8]) -> Result; +pub fn hex_hmac_sha1(key: &[u8], content: &[u8]) -> Result; +pub fn hex_hmac_sha256(key: &[u8], content: &[u8]) -> Result; +pub fn base64_hmac_sha1(key: &[u8], content: &[u8]) -> Result; +pub fn base64_hmac_sha256(key: &[u8], content: &[u8]) -> Result; +``` + +`reqsign_core::jwt` no longer exposes an `rsa` type. The typed +`encode_rs256(&H, &C, &RsaPrivateKey)` entry point is removed. The byte-based +entry point remains and delegates RSA signing to the provider: + +```rust +pub fn encode_rs256_pem( + header: &H, + claims: &C, + private_key_pem: &[u8], +) -> Result; +``` + +Enabling the `jwt` feature adds `serde` and `serde_json`; it does not add `rsa` +or any other cryptographic implementation. + +## Official Providers + +### `reqsign-crypto-rustcrypto` + +Location: `crypto/rustcrypto`. Workspace member. Version follows the core +crate's lockstep line. + +`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 (`0.1.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`. It does not install it. +`default_context()` remains limited to runtime components (`FileRead`, +`HttpSend`, `Env`, `CommandExecute`) and never registers a crypto provider. + +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 + +Install one provider once during startup, before constructing signers or calling +signing operations: + +```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 +provider. Applications that intentionally compose several libraries should +install their chosen provider before any of them are initialized. + +### 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 `?`. 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 in `azure-storage`; the thumbprint uses the provider's SHA-1 and the + client assertion uses `jwt::encode_rs256_pem`. +- Google service-account signing encodes the provider's RSA signature as hex; + client-side credential access boundary encryption uses AES-GCM through the + provider and gets its nonce from `fill_random`. + +### Removed APIs + +- `reqsign_core::jwt::encode_rs256(&H, &C, &RsaPrivateKey)` is removed. + Use `encode_rs256_pem` with PEM bytes. +- Hash and MAC helpers return `Result`. +- `reqsign-core` no longer provides crypto implementations, so a process that + signs or hashes without installing a provider fails with `ConfigInvalid`. + +## Verification + +The repository verifies this contract with: + +- Separate `reqsign-core` integration test binaries for the unset provider, + early lookup, rejected second installation, and concurrent installation. +- 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. +- `cargo tree --edges normal` checks that no core or service production graph + contains a cryptographic implementation crate. +- `cargo check -p reqsign-crypto-rustcrypto --target wasm32-unknown-unknown`, + the workspace test suite, doc tests, formatting, clippy with `-D warnings`, + license headers, and the standalone BoringSSL workflow. 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 9cc7d482..7db6a3b2 100644 --- a/reqsign/README.md +++ b/reqsign/README.md @@ -42,7 +42,10 @@ 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). The +provider is re-exported but not installed automatically; applications call +`RustCryptoProvider::install_default()` once during startup. To use specific services only: @@ -59,10 +62,13 @@ The easiest way to get started is using the default signers provided for each se ```rust,ignore use anyhow::Result; -use reqsign::aws; +use reqsign::{RustCryptoProvider, aws}; #[tokio::main] async fn main() -> Result<()> { + RustCryptoProvider::install_default() + .map_err(|_| anyhow::anyhow!("a CryptoProvider is already installed"))?; + // Create a default signer for AWS S3 in us-east-1 // This will automatically: // - Set up HTTP client and file reader @@ -91,11 +97,14 @@ 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<()> { + RustCryptoProvider::install_default() + .map_err(|_| anyhow::anyhow!("a CryptoProvider is already installed"))?; + // Create a context with default implementations let ctx = default_context(); diff --git a/reqsign/examples/aws.rs b/reqsign/examples/aws.rs index 93ec32aa..8fd77091 100644 --- a/reqsign/examples/aws.rs +++ b/reqsign/examples/aws.rs @@ -19,6 +19,8 @@ use anyhow::Result; #[tokio::main] async fn main() -> Result<()> { + reqsign::RustCryptoProvider::install_default() + .expect("no CryptoProvider must be installed before this example"); // ANCHOR: quickstart use reqsign::aws; // Create a default signer for S3 in us-east-1 diff --git a/reqsign/examples/azure.rs b/reqsign/examples/azure.rs index 30555ba5..7c75f3a1 100644 --- a/reqsign/examples/azure.rs +++ b/reqsign/examples/azure.rs @@ -19,6 +19,8 @@ use anyhow::Result; #[tokio::main] async fn main() -> Result<()> { + reqsign::RustCryptoProvider::install_default() + .expect("no CryptoProvider must be installed before this example"); // ANCHOR: quickstart use reqsign::azure; // Create a default signer for Azure Storage diff --git a/reqsign/examples/custom_context.rs b/reqsign/examples/custom_context.rs index 25667c99..f7b77e1f 100644 --- a/reqsign/examples/custom_context.rs +++ b/reqsign/examples/custom_context.rs @@ -22,6 +22,8 @@ use reqsign_file_read_tokio::TokioFileRead; use reqsign_http_send_reqwest::ReqwestHttpSend; fn main() { + reqsign::RustCryptoProvider::install_default() + .expect("no CryptoProvider must be installed before this example"); let ctx = Context::new() .with_file_read(TokioFileRead) .with_http_send(ReqwestHttpSend::default()) diff --git a/reqsign/examples/custom_http.rs b/reqsign/examples/custom_http.rs index ee1324f5..6aa4771b 100644 --- a/reqsign/examples/custom_http.rs +++ b/reqsign/examples/custom_http.rs @@ -29,6 +29,8 @@ impl HttpSend for MyHttpSend { } fn main() { + reqsign::RustCryptoProvider::install_default() + .expect("no CryptoProvider must be installed before this example"); // This example only assembles the context; implement http_send before use. let _ctx = Context::new().with_http_send(MyHttpSend); } diff --git a/reqsign/examples/google.rs b/reqsign/examples/google.rs index 64d7341a..714faebb 100644 --- a/reqsign/examples/google.rs +++ b/reqsign/examples/google.rs @@ -19,6 +19,8 @@ use anyhow::Result; #[tokio::main] async fn main() -> Result<()> { + reqsign::RustCryptoProvider::install_default() + .expect("no CryptoProvider must be installed before this example"); // ANCHOR: quickstart use reqsign::google; // Create a default signer for Google Cloud Storage diff --git a/reqsign/examples/presign.rs b/reqsign/examples/presign.rs index 0a3973b4..ae3e94bd 100644 --- a/reqsign/examples/presign.rs +++ b/reqsign/examples/presign.rs @@ -20,6 +20,8 @@ use std::time::Duration; #[tokio::main] async fn main() -> anyhow::Result<()> { + reqsign::RustCryptoProvider::install_default() + .expect("no CryptoProvider must be installed before this example"); let signer = aws::default_signer("s3", "us-east-1"); let mut req = http::Request::get("https://s3.amazonaws.com/my-bucket/report.csv") .body(())? diff --git a/reqsign/examples/s3_express_grant.rs b/reqsign/examples/s3_express_grant.rs index e714b42f..3e83e143 100644 --- a/reqsign/examples/s3_express_grant.rs +++ b/reqsign/examples/s3_express_grant.rs @@ -23,6 +23,8 @@ use reqsign::{Granter, default_context}; #[tokio::main] async fn main() -> anyhow::Result<()> { + reqsign::RustCryptoProvider::install_default() + .expect("no CryptoProvider must be installed before this example"); let config = S3ExpressSessionConfig::from_bucket("my-bucket--usw2-az1--x-s3", "us-west-2")?; let grant = S3ExpressSessionGrant::new(S3ExpressSessionMode::ReadOnly); let granter = Granter::new( diff --git a/reqsign/examples/s3_express_sign.rs b/reqsign/examples/s3_express_sign.rs index 8e0d68fe..6c484b33 100644 --- a/reqsign/examples/s3_express_sign.rs +++ b/reqsign/examples/s3_express_sign.rs @@ -22,6 +22,8 @@ use reqsign::aws::{ #[tokio::main] async fn main() -> anyhow::Result<()> { + reqsign::RustCryptoProvider::install_default() + .expect("no CryptoProvider must be installed before this example"); let provider = S3ExpressSessionProvider::new( "my-bucket--usw2-az1--x-s3", DefaultCredentialProvider::new(), diff --git a/reqsign/examples/static_credentials.rs b/reqsign/examples/static_credentials.rs index 3e6c9aa3..b4197f00 100644 --- a/reqsign/examples/static_credentials.rs +++ b/reqsign/examples/static_credentials.rs @@ -17,6 +17,8 @@ #[tokio::main] async fn main() -> anyhow::Result<()> { + reqsign::RustCryptoProvider::install_default() + .expect("no CryptoProvider must be installed before this example"); // ANCHOR: static use reqsign::aws::{self, StaticCredentialProvider}; let signer = aws::default_signer("s3", "us-east-1").with_credential_provider( diff --git a/reqsign/src/context.rs b/reqsign/src/context.rs index e367fcda..25c7b027 100644 --- a/reqsign/src/context.rs +++ b/reqsign/src/context.rs @@ -31,6 +31,11 @@ use reqsign_http_send_reqwest::ReqwestHttpSend; /// - `ReqwestHttpSend` for HTTP requests /// - `OsEnv` for environment variable access /// +/// This function does not install a crypto provider. Applications must call +/// `reqsign::RustCryptoProvider::install_default()` once during startup (or +/// install another provider) before hashing or signing. Integrating middleware +/// must leave that choice to the application. +/// /// # Example /// /// ```no_run diff --git a/reqsign/src/lib.rs b/reqsign/src/lib.rs index 94663644..76956330 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 install it at startup; neither +// this facade nor `default_context` installs a provider implicitly. +#[cfg(feature = "default-crypto")] +pub use reqsign_crypto_rustcrypto::RustCryptoProvider; + // Context utilities #[cfg(feature = "default-context")] mod context; diff --git a/reqsign/tests/crypto.rs b/reqsign/tests/crypto.rs new file mode 100644 index 00000000..c5462193 --- /dev/null +++ b/reqsign/tests/crypto.rs @@ -0,0 +1,28 @@ +// 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 exposes a provider but must never install one implicitly. + +#[cfg(feature = "default-context")] +#[test] +fn default_context_does_not_install_a_crypto_provider() { + let _ = reqsign::default_context(); + assert!( + reqsign::crypto::get_default().is_none(), + "default_context must leave provider installation to the application" + ); +} diff --git a/services/aliyun-oss/Cargo.toml b/services/aliyun-oss/Cargo.toml index 6dc8ce7b..b90fbede 100644 --- a/services/aliyun-oss/Cargo.toml +++ b/services/aliyun-oss/Cargo.toml @@ -38,6 +38,8 @@ serde = { workspace = true } serde_json = { workspace = true } [dev-dependencies] +ctor = "1" +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..9251232c 100644 --- a/services/aliyun-oss/README.md +++ b/services/aliyun-oss/README.md @@ -6,6 +6,10 @@ 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 requires a process-wide `CryptoProvider`. Install one at startup +> before constructing signers; see +> [CryptoProvider](https://github.com/apache/reqsign/blob/main/docs/crypto-provider.md). + ## Quick Start ```rust diff --git a/services/aliyun-oss/src/assume_role.rs b/services/aliyun-oss/src/assume_role.rs index c0e69bd1..1f448ac4 100644 --- a/services/aliyun-oss/src/assume_role.rs +++ b/services/aliyun-oss/src/assume_role.rs @@ -168,7 +168,7 @@ pub(crate) fn signed_rpc_request( let signature = base64_hmac_sha1( format!("{access_key_secret}&").as_bytes(), string_to_sign.as_bytes(), - ); + )?; let url = format!( "{}/?{}&Signature={}", @@ -657,7 +657,8 @@ 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("base-sk&".as_bytes(), string_to_sign.as_bytes())?; assert_eq!( Some(expected_signature.as_str()), params.get("Signature").map(String::as_str) diff --git a/services/aliyun-oss/src/lib.rs b/services/aliyun-oss/src/lib.rs index 83b7de00..fa914851 100644 --- a/services/aliyun-oss/src/lib.rs +++ b/services/aliyun-oss/src/lib.rs @@ -258,3 +258,11 @@ pub use sign_request::{RequestSigner, SigningVersion}; mod provide_credential; pub use provide_credential::*; + +// Unit tests exercise signing paths, so install the test provider before +// any test in this binary runs. +#[cfg(test)] +#[ctor::ctor(unsafe)] +fn install_test_crypto_provider() { + let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +} diff --git a/services/aliyun-oss/src/provide_credential/assume_role.rs b/services/aliyun-oss/src/provide_credential/assume_role.rs index 0c736bd6..9e4d4cd5 100644 --- a/services/aliyun-oss/src/provide_credential/assume_role.rs +++ b/services/aliyun-oss/src/provide_credential/assume_role.rs @@ -455,7 +455,7 @@ mod tests { let expected_signature = base64_hmac_sha1( 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) diff --git a/services/aliyun-oss/src/sign_request.rs b/services/aliyun-oss/src/sign_request.rs index 6fb384ba..40065e61 100644 --- a/services/aliyun-oss/src/sign_request.rs +++ b/services/aliyun-oss/src/sign_request.rs @@ -239,7 +239,7 @@ impl RequestSigner { &additional_headers, )?; let signature = - base64_hmac_sha256(cred.access_key_secret.as_bytes(), string_to_sign.as_bytes()); + base64_hmac_sha256(cred.access_key_secret.as_bytes(), string_to_sign.as_bytes())?; let authorization = if additional_headers.is_empty() { format!( @@ -295,7 +295,7 @@ impl RequestSigner { &additional_headers, )?; let signature = - base64_hmac_sha256(cred.access_key_secret.as_bytes(), string_to_sign.as_bytes()); + base64_hmac_sha256(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) @@ -309,7 +309,7 @@ impl RequestSigner { ) -> 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()); + base64_hmac_sha1(cred.access_key_secret.as_bytes(), string_to_sign.as_bytes())?; // Add date header req.headers @@ -339,7 +339,7 @@ impl RequestSigner { 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()); + base64_hmac_sha1(cred.access_key_secret.as_bytes(), string_to_sign.as_bytes())?; let mut authentication = vec![ format!( @@ -497,7 +497,7 @@ 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); + let signature = self.build_v4_signature(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)?; @@ -707,7 +707,7 @@ 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(canonical_request.as_bytes())?)?; Ok(s) } @@ -717,14 +717,14 @@ impl RequestSigner { signing_time: Timestamp, region: &str, string_to_sign: &str, - ) -> String { + ) -> Result { let date_key = hmac_sha256( 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()); + )?; + 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()) } diff --git a/services/aliyun-oss/tests/common/mod.rs b/services/aliyun-oss/tests/common/mod.rs new file mode 100644 index 00000000..3b0c8c71 --- /dev/null +++ b/services/aliyun-oss/tests/common/mod.rs @@ -0,0 +1,24 @@ +// 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. + +// Every integration test binary installs the RustCrypto provider once before +// its tests run. Installation is process-wide, so concurrent or repeated +// initialization is intentionally ignored. +#[ctor::ctor(unsafe)] +fn install_test_crypto_provider() { + let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +} diff --git a/services/aliyun-oss/tests/credential_chain.rs b/services/aliyun-oss/tests/credential_chain.rs index e9f34891..60d37f51 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}; diff --git a/services/aliyun-oss/tests/main.rs b/services/aliyun-oss/tests/main.rs index a7ffbe32..a93c0ce0 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; diff --git a/services/aws-core/Cargo.toml b/services/aws-core/Cargo.toml index 77b85e31..7f97cbc7 100644 --- a/services/aws-core/Cargo.toml +++ b/services/aws-core/Cargo.toml @@ -42,9 +42,10 @@ rust-ini = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } serde_urlencoded = "0.7" -sha1 = { workspace = true } [dev-dependencies] +ctor = "1" +reqsign-crypto-rustcrypto = { workspace = true } anyhow = { workspace = true } dotenvy = { workspace = true } env_logger = { workspace = true } diff --git a/services/aws-core/src/assume_role.rs b/services/aws-core/src/assume_role.rs index 32565b79..fbc1630f 100644 --- a/services/aws-core/src/assume_role.rs +++ b/services/aws-core/src/assume_role.rs @@ -221,7 +221,7 @@ impl AssumeRoleOperation { Bytes::from(self.parameters.clone()), ) }; - let payload_hash = hex_sha256(&body); + let payload_hash = hex_sha256(&body)?; http::Request::builder() .method(method) @@ -746,7 +746,7 @@ mod tests { .headers() .get(X_AMZ_CONTENT_SHA_256) .expect("payload hash must be present"), - &hex_sha256(request.body()) + &hex_sha256(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..9edee4d6 100644 --- a/services/aws-core/src/lib.rs +++ b/services/aws-core/src/lib.rs @@ -52,10 +52,21 @@ mod tests { #[test] fn empty_string_sha256_matches_computed_digest() { - assert_eq!(EMPTY_STRING_SHA256, hex_sha256(b"")); + assert_eq!( + EMPTY_STRING_SHA256, + hex_sha256(b"").expect("SHA-256 must succeed") + ); assert_eq!( EMPTY_STRING_SHA256, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" ); } } + +// Unit tests exercise signing paths, so install the test provider before +// any test in this binary runs. +#[cfg(test)] +#[ctor::ctor(unsafe)] +fn install_test_crypto_provider() { + let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +} diff --git a/services/aws-core/src/provide_credential/sso/session.rs b/services/aws-core/src/provide_credential/sso/session.rs index 965e51fd..dd03712c 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; @@ -46,7 +47,7 @@ impl SessionKey { .join(".aws") .join("sso") .join("cache") - .join(format!("{}.json", hex_sha1(name.as_bytes()))); + .join(format!("{}.json", hex_sha1(name.as_bytes())?)); Ok(SessionKey { path: path.to_string_lossy().into_owned(), config_path: config.config_path.clone(), @@ -295,11 +296,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..868f9a88 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; @@ -54,7 +54,10 @@ impl Files { fn token(&self, home: &str, name: &str, value: Value) { self.put( - &format!("{home}/.aws/sso/cache/{}.json", hex_sha1(name.as_bytes())), + &format!( + "{home}/.aws/sso/cache/{}.json", + hex_sha1(name.as_bytes()).expect("SSO cache key hashing must succeed") + ), value.to_string(), ); } diff --git a/services/aws-core/tests/common/mod.rs b/services/aws-core/tests/common/mod.rs new file mode 100644 index 00000000..3b0c8c71 --- /dev/null +++ b/services/aws-core/tests/common/mod.rs @@ -0,0 +1,24 @@ +// 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. + +// Every integration test binary installs the RustCrypto provider once before +// its tests run. Installation is process-wide, so concurrent or repeated +// initialization is intentionally ignored. +#[ctor::ctor(unsafe)] +fn install_test_crypto_provider() { + let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +} diff --git a/services/aws-core/tests/shared_config.rs b/services/aws-core/tests/shared_config.rs index 74e87b7c..47c771b4 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}; diff --git a/services/aws-v4/Cargo.toml b/services/aws-v4/Cargo.toml index 000f90b0..f79ababb 100644 --- a/services/aws-v4/Cargo.toml +++ b/services/aws-v4/Cargo.toml @@ -40,6 +40,8 @@ reqsign-core = { workspace = true } serde = { workspace = true } [dev-dependencies] +ctor = "1" +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 2a8dd548..e9352b90 100644 --- a/services/aws-v4/README.md +++ b/services/aws-v4/README.md @@ -2,6 +2,10 @@ AWS SigV4 signing implementation for `reqsign`. +> Signing requires a process-wide `CryptoProvider`. Install one at startup +> before constructing signers; see +> [CryptoProvider](https://github.com/apache/reqsign/blob/main/docs/crypto-provider.md). + ## Quick Start ```rust,no_run @@ -87,7 +91,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") diff --git a/services/aws-v4/benches/aws.rs b/services/aws-v4/benches/aws.rs index 3d484d43..cf5bcde1 100644 --- a/services/aws-v4/benches/aws.rs +++ b/services/aws-v4/benches/aws.rs @@ -45,6 +45,9 @@ static RUNTIME: LazyLock = LazyLock::new(|| { }); pub fn bench(c: &mut Criterion) { + reqsign_crypto_rustcrypto::RustCryptoProvider::install_default() + .expect("no CryptoProvider must be installed before this benchmark"); + let mut group = c.benchmark_group("aws_v4"); group.bench_function("reqsign", |b| { diff --git a/services/aws-v4/examples/dynamodb_sign.rs b/services/aws-v4/examples/dynamodb_sign.rs index 29fb36f2..e5b3af43 100644 --- a/services/aws-v4/examples/dynamodb_sign.rs +++ b/services/aws-v4/examples/dynamodb_sign.rs @@ -25,6 +25,9 @@ use serde_json::json; #[tokio::main] async fn main() -> Result<()> { + reqsign_crypto_rustcrypto::RustCryptoProvider::install_default() + .expect("no CryptoProvider must be installed before this example"); + // Initialize logging let _ = env_logger::builder().is_test(true).try_init(); @@ -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(&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(&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(&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..6b5baeca 100644 --- a/services/aws-v4/examples/s3_express_sign.rs +++ b/services/aws-v4/examples/s3_express_sign.rs @@ -24,6 +24,9 @@ use reqwest::Client; #[tokio::main] async fn main() -> Result<()> { + reqsign_crypto_rustcrypto::RustCryptoProvider::install_default() + .expect("no CryptoProvider must be installed before this example"); + // Initialize logging for debugging let _ = env_logger::builder().is_test(true).try_init(); diff --git a/services/aws-v4/examples/s3_sign.rs b/services/aws-v4/examples/s3_sign.rs index eb73fb0b..af68ccf8 100644 --- a/services/aws-v4/examples/s3_sign.rs +++ b/services/aws-v4/examples/s3_sign.rs @@ -24,6 +24,9 @@ use reqwest::Client; #[tokio::main] async fn main() -> Result<()> { + reqsign_crypto_rustcrypto::RustCryptoProvider::install_default() + .expect("no CryptoProvider must be installed before this example"); + // Initialize logging for debugging let _ = env_logger::builder().is_test(true).try_init(); diff --git a/services/aws-v4/src/assume_role.rs b/services/aws-v4/src/assume_role.rs index 0ef7cbcd..043ebdc4 100644 --- a/services/aws-v4/src/assume_role.rs +++ b/services/aws-v4/src/assume_role.rs @@ -604,7 +604,7 @@ mod tests { .expect("payload hash must be set") .to_str() .expect("payload hash must be text"), - hex_sha256(&request.body) + hex_sha256(&request.body).expect("SHA-256 must succeed") ); assert_eq!( request diff --git a/services/aws-v4/src/lib.rs b/services/aws-v4/src/lib.rs index 0946987c..0d9ca846 100644 --- a/services/aws-v4/src/lib.rs +++ b/services/aws-v4/src/lib.rs @@ -191,3 +191,11 @@ 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; + +// Unit tests exercise signing paths, so install the test provider before +// any test in this binary runs. +#[cfg(test)] +#[ctor::ctor(unsafe)] +fn install_test_crypto_provider() { + let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +} diff --git a/services/aws-v4/src/sign_request.rs b/services/aws-v4/src/sign_request.rs index 5084eab6..2096e540 100644 --- a/services/aws-v4/src/sign_request.rs +++ b/services/aws-v4/src/sign_request.rs @@ -57,12 +57,13 @@ const CREDENTIAL_OPERATION_HEADROOM: Duration = Duration::from_secs(10); /// ``` /// use reqsign_aws_v4::EMPTY_STRING_SHA256; /// use reqsign_core::hash::hex_sha256; +/// # let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); /// /// 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") @@ -248,7 +249,7 @@ impl SignRequest for RequestSigner { &canonical_query, self.percent_encoding_mode, )?; - let encoded_req = hex_sha256(creq.as_bytes()); + let encoded_req = hex_sha256(creq.as_bytes())?; // Scope: "20220313///aws4_request" let scope = format!( @@ -284,8 +285,8 @@ impl SignRequest for RequestSigner { debug!("calculated string to sign: {string_to_sign}"); let signing_key = - generate_signing_key(&cred.secret_access_key, now, &self.region, &self.service); - let signature = hex_hmac_sha256(&signing_key, string_to_sign.as_bytes()); + generate_signing_key(&cred.secret_access_key, now, &self.region, &self.service)?; + let signature = hex_hmac_sha256(&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)?; @@ -388,17 +389,22 @@ fn authentication_query( query } -fn generate_signing_key(secret: &str, time: Timestamp, region: &str, service: &str) -> Vec { +fn generate_signing_key( + secret: &str, + time: Timestamp, + region: &str, + service: &str, +) -> Result> { // Sign secret let secret = format!("AWS4{secret}"); // Sign date - let sign_date = hmac_sha256(secret.as_bytes(), time.format_date().as_bytes()); + let sign_date = hmac_sha256(secret.as_bytes(), time.format_date().as_bytes())?; // Sign region - let sign_region = hmac_sha256(sign_date.as_slice(), region.as_bytes()); + let sign_region = hmac_sha256(sign_date.as_slice(), region.as_bytes())?; // Sign service - let sign_service = hmac_sha256(sign_region.as_slice(), service.as_bytes()); + let sign_service = hmac_sha256(sign_region.as_slice(), service.as_bytes())?; // Sign request - hmac_sha256(sign_service.as_slice(), "aws4_request".as_bytes()) + Ok(hmac_sha256(sign_service.as_slice(), "aws4_request".as_bytes())?.to_vec()) } #[cfg(test)] @@ -1110,7 +1116,7 @@ mod tests { HeaderValue::from_str(&content.len().to_string()).expect("must be valid"), ); - let body = hex_sha256(content.as_bytes()); + let body = hex_sha256(content.as_bytes()).expect("SHA-256 must succeed"); req.headers_mut().insert( "x-amz-content-sha256", HeaderValue::from_str(&body).expect("must be valid"), diff --git a/services/aws-v4/tests/common/mod.rs b/services/aws-v4/tests/common/mod.rs new file mode 100644 index 00000000..3b0c8c71 --- /dev/null +++ b/services/aws-v4/tests/common/mod.rs @@ -0,0 +1,24 @@ +// 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. + +// Every integration test binary installs the RustCrypto provider once before +// its tests run. Installation is process-wide, so concurrent or repeated +// initialization is intentionally ignored. +#[ctor::ctor(unsafe)] +fn install_test_crypto_provider() { + let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +} 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-v4a/Cargo.toml b/services/aws-v4a/Cargo.toml index 08e49f4a..bd5ee8b5 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 } @@ -39,6 +38,9 @@ zeroize = { workspace = true } anyhow = { workspace = true } aws-credential-types = "1.1.8" aws-sigv4 = { version = "1.2.0", features = ["sigv4a"] } +ctor = "1" 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..5e2fd6cc 100644 --- a/services/aws-v4a/README.md +++ b/services/aws-v4a/README.md @@ -7,6 +7,10 @@ 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 requires a process-wide `CryptoProvider`. Install one at startup +> before constructing signers; 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..c95aef8a 100644 --- a/services/aws-v4a/src/lib.rs +++ b/services/aws-v4a/src/lib.rs @@ -34,3 +34,11 @@ 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; + +// Unit tests exercise signing paths, so install the test provider before +// any test in this binary runs. +#[cfg(test)] +#[ctor::ctor(unsafe)] +fn install_test_crypto_provider() { + let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +} diff --git a/services/aws-v4a/src/sign_request.rs b/services/aws-v4a/src/sign_request.rs index 5170a708..e9d84cc7 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 @@ -166,7 +171,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(canonical_request.as_bytes())?; let scope = format!("{}/{}/aws4_request", now.format_date(), self.service); debug!("calculated scope: {scope}"); @@ -176,7 +181,7 @@ impl SignRequest for RequestSigner { 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 signature = calculate_signature(&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 +270,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(signing_key: &[u8; 32], string_to_sign: &[u8]) -> Result { + let provider = crypto::get_default().ok_or_else(|| { + Error::config_invalid( + "no CryptoProvider is installed; install one during application startup", + ) + })?; + 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( + 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 +297,15 @@ 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(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 +336,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 +419,9 @@ 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 scalar = generate_signing_key(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 +433,7 @@ mod tests { "865ed22a7eadc9c5cb9d2cbaca1b3699139fedc5043dc6661864218330c8e518" ); - let signature = calculate_signature(&signing_key, HEADER_STRING_TO_SIGN.as_bytes()); + let signature = calculate_signature(&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"); @@ -503,7 +518,7 @@ mod tests { }; format!( "AWS4-ECDSA-P256-SHA256\n20150830T123600Z\n20150830/service/aws4_request\n{}", - hex_sha256(canonical_request.as_bytes()), + hex_sha256(canonical_request.as_bytes()).expect("SHA-256 must succeed"), ) } @@ -525,9 +540,12 @@ 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 scalar = generate_signing_key(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 {}", diff --git a/services/azure-storage/Cargo.toml b/services/azure-storage/Cargo.toml index 34ebb360..c41b386d 100644 --- a/services/azure-storage/Cargo.toml +++ b/services/azure-storage/Cargo.toml @@ -38,14 +38,14 @@ 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] +ctor = "1" +reqsign-crypto-rustcrypto = { workspace = true } asyncband = { workspace = true, features = ["semaphore"] } env_logger = { workspace = true } reqsign-command-execute-tokio = { workspace = true } diff --git a/services/azure-storage/README.md b/services/azure-storage/README.md index 1d7ed6f2..18c031a2 100644 --- a/services/azure-storage/README.md +++ b/services/azure-storage/README.md @@ -5,6 +5,10 @@ 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 requires a process-wide `CryptoProvider`. Install one at startup +> before constructing signers; see +> [CryptoProvider](https://github.com/apache/reqsign/blob/main/docs/crypto-provider.md). + ## Quick Start ```rust diff --git a/services/azure-storage/src/lib.rs b/services/azure-storage/src/lib.rs index 5a4e3b76..7301b8f5 100644 --- a/services/azure-storage/src/lib.rs +++ b/services/azure-storage/src/lib.rs @@ -192,3 +192,11 @@ pub use sign_request::RequestSigner; mod provide_credential; pub use provide_credential::*; + +// Unit tests exercise signing paths, so install the test provider before +// any test in this binary runs. +#[cfg(test)] +#[ctor::ctor(unsafe)] +fn install_test_crypto_provider() { + let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_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..c45809b8 100644 --- a/services/azure-storage/src/provide_credential/client_certificate.rs +++ b/services/azure-storage/src/provide_credential/client_certificate.rs @@ -25,11 +25,8 @@ use crate::provide_credential::entra::{ use base64::Engine; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use reqsign_core::time::Timestamp; -use reqsign_core::{Context, ProvideCredential}; -use rsa::RsaPrivateKey; -use rsa::pkcs8::DecodePrivateKey; +use 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 +96,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,21 +137,13 @@ impl ClientCertificateCredentialProvider { reqsign_core::Error::credential_invalid("PEM does not contain a private key") })?; - // Parse private key - let private_key = RsaPrivateKey::from_pkcs8_pem(&private_key_pem).map_err(|e| { - reqsign_core::Error::credential_invalid(format!( - "Failed to parse private key from PEM: {e}" - )) - })?; - - Ok((cert_der, private_key)) + Ok((cert_der, private_key_pem.into_bytes())) } /// Calculate certificate thumbprint (x5t) /// 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, cert_der: &[u8]) -> Result { + Ok(URL_SAFE_NO_PAD.encode(hash::sha1(cert_der)?)) } /// Create JWT client assertion @@ -163,7 +152,7 @@ impl ClientCertificateCredentialProvider { 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 +173,10 @@ impl ClientCertificateCredentialProvider { let header = ClientAssertionHeader { alg: "RS256", typ: "JWT", - x5t: self.calculate_thumbprint(cert_der), + x5t: self.calculate_thumbprint(cert_der)?, }; - reqsign_core::jwt::encode_rs256(&header, &claims, private_key) + reqsign_core::jwt::encode_rs256_pem(&header, &claims, private_key_pem) } /// Exchange client assertion for access token @@ -289,11 +278,11 @@ impl ProvideCredential for ClientCertificateCredentialProvider { }; // Load certificate and private key - let (cert_der, private_key) = self.load_certificate(ctx, &certificate_path).await?; + let (cert_der, private_key_pem) = self.load_certificate(ctx, &certificate_path).await?; // Create client assertion let client_assertion = - self.create_client_assertion(&tenant_id, &client_id, &cert_der, &private_key)?; + self.create_client_assertion(&tenant_id, &client_id, &cert_der, &private_key_pem)?; // Exchange for access token let token_response = self @@ -319,7 +308,9 @@ 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 thumbprint = provider + .calculate_thumbprint(cert_der) + .expect("thumbprint calculation must succeed"); // Should produce a valid base64url encoded hash assert!(!thumbprint.is_empty()); diff --git a/services/azure-storage/src/service_sas.rs b/services/azure-storage/src/service_sas.rs index 7ca97d07..49dab550 100644 --- a/services/azure-storage/src/service_sas.rs +++ b/services/azure-storage/src/service_sas.rs @@ -701,11 +701,14 @@ impl ServiceSharedAccessSignature { .join("\n") } - fn signature_with_decoded_key(&self, decoded_key: &[u8]) -> String { + fn signature_with_decoded_key(&self, decoded_key: &[u8]) -> reqsign_core::Result { hash::base64_hmac_sha256(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, + 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 +731,16 @@ impl ServiceSharedAccessSignature { elements.push(( "sig".to_string(), - self.signature_with_decoded_key(decoded_key), + self.signature_with_decoded_key(decoded_key)?, )); - elements + Ok(elements) } /// Generate SAS query parameters. pub fn token(&self) -> Result> { let decoded_key = hash::base64_decode(&self.key)?; - Ok(self.token_with_decoded_key(&decoded_key)) + self.token_with_decoded_key(&decoded_key) } } @@ -945,7 +948,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(&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 { diff --git a/services/azure-storage/src/sign_request.rs b/services/azure-storage/src/sign_request.rs index 48387cdf..c64f06c9 100644 --- a/services/azure-storage/src/sign_request.rs +++ b/services/azure-storage/src/sign_request.rs @@ -320,7 +320,7 @@ impl SignRequest for RequestSigner { 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(token.as_bytes())?, version: version.to_string(), }; @@ -405,7 +405,8 @@ impl SignRequest for RequestSigner { } let signer_token = signer.token().map_err(|e| { - reqsign_core::Error::unexpected( + reqsign_core::Error::new( + e.kind(), "failed to generate user delegation SAS token", ) .with_source(e) @@ -470,8 +471,11 @@ impl SignRequest for RequestSigner { } let signer_token = signer.token().map_err(|e| { - reqsign_core::Error::unexpected("failed to generate service SAS token") - .with_source(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)?); } @@ -482,7 +486,7 @@ impl SignRequest for RequestSigner { .with_source(e) })?; let signature = - base64_hmac_sha256(&decode_content, string_to_sign.as_bytes()); + base64_hmac_sha256(&decode_content, string_to_sign.as_bytes())?; sctx.headers.insert(header::AUTHORIZATION, { let mut value: HeaderValue = diff --git a/services/azure-storage/src/user_delegation.rs b/services/azure-storage/src/user_delegation.rs index 2350d2e6..d026aba2 100644 --- a/services/azure-storage/src/user_delegation.rs +++ b/services/azure-storage/src/user_delegation.rs @@ -465,10 +465,7 @@ 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(&decoded_key, string_to_sign.as_bytes()) } pub(crate) fn token(&self) -> Result> { diff --git a/services/azure-storage/src/user_delegation_sas.rs b/services/azure-storage/src/user_delegation_sas.rs index 7a496567..06b3a29f 100644 --- a/services/azure-storage/src/user_delegation_sas.rs +++ b/services/azure-storage/src/user_delegation_sas.rs @@ -672,13 +672,13 @@ impl UserDelegationSasGranter { &self, 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(bearer_token.as_bytes())?, service_version: USER_DELEGATION_SERVICE_VERSION, - } + }) } fn key_covers( @@ -726,7 +726,9 @@ impl GrantCredential for UserDelegationSasGranter { let Ok(times) = self.operation_times(expires_in) else { return now + BEARER_TOKEN_OPERATION_HEADROOM; }; - let cache_key = self.cache_key(&endpoint, token); + let Ok(cache_key) = self.cache_key(&endpoint, token) else { + return now + BEARER_TOKEN_OPERATION_HEADROOM; + }; if self.cached_key(&cache_key, ×).is_some() { now } else { @@ -757,7 +759,7 @@ impl GrantCredential for UserDelegationSasGranter { )); } - let cache_key = self.cache_key(&endpoint, token); + let cache_key = self.cache_key(&endpoint, token)?; let cached = self.cached_key(&cache_key, ×); let (key, fetched) = if let Some(key) = cached { (key, false) @@ -829,7 +831,7 @@ impl GrantCredential for UserDelegationSasGranter { } let pairs = signer.token().map_err(|e| { - Error::unexpected("failed to generate Azure user delegation SAS").with_source(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); diff --git a/services/azure-storage/tests/common/mod.rs b/services/azure-storage/tests/common/mod.rs new file mode 100644 index 00000000..3b0c8c71 --- /dev/null +++ b/services/azure-storage/tests/common/mod.rs @@ -0,0 +1,24 @@ +// 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. + +// Every integration test binary installs the RustCrypto provider once before +// its tests run. Installation is process-wide, so concurrent or repeated +// initialization is intentionally ignored. +#[ctor::ctor(unsafe)] +fn install_test_crypto_provider() { + let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +} 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/google/Cargo.toml b/services/google/Cargo.toml index f0c7f458..235c7f92 100644 --- a/services/google/Cargo.toml +++ b/services/google/Cargo.toml @@ -31,7 +31,6 @@ all-features = true [features] credential-access-boundary-client-side = [ - "dep:aes-gcm", "dep:base64", "dep:prost", "dep:zeroize", @@ -39,18 +38,17 @@ credential-access-boundary-client-side = [ default = [] [dependencies] -aes-gcm = { workspace = true, features = ["zeroize"], optional = true } asyncband = { workspace = true } base64 = { workspace = true, optional = 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"] } @@ -60,10 +58,14 @@ zeroize = { workspace = true, optional = true } reqsign-core = { workspace = true, features = ["jwt"] } [dev-dependencies] +aes-gcm = { workspace = true, features = ["zeroize"] } asyncband = { workspace = true, features = ["semaphore"] } +ctor = "1" 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..7ff12f40 100644 --- a/services/google/README.md +++ b/services/google/README.md @@ -7,6 +7,10 @@ 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 requires a process-wide `CryptoProvider`. Install one at startup +> before constructing signers; see +> [CryptoProvider](https://github.com/apache/reqsign/blob/main/docs/crypto-provider.md). + ## Quick Start ```rust,no_run diff --git a/services/google/src/credential_access_boundary/client_side.rs b/services/google/src/credential_access_boundary/client_side.rs index 55225a95..61a779cd 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}; @@ -574,7 +573,7 @@ impl ClientSideCredentialAccessBoundaryGranter { })?; Ok(IntermediaryCacheKey { endpoint: STS_ENDPOINT, - source_authority: hex_sha256(source.access_token.as_bytes()), + source_authority: hex_sha256(source.access_token.as_bytes())?, source_expires_at, }) } @@ -653,8 +652,14 @@ 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 provider = crypto::get_default().ok_or_else(|| { + Error::config_invalid( + "no CryptoProvider is installed; install one during application startup", + ) + })?; + let mut nonce = [0u8; AES_GCM_NONCE_BYTES]; + provider.fill_random(&mut nonce)?; + Ok(nonce) } #[cfg(test)] @@ -829,20 +834,12 @@ 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"))?; + let provider = crypto::get_default().ok_or_else(|| { + Error::config_invalid( + "no CryptoProvider is installed; install one during application startup", + ) + })?; + 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 +1065,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}; diff --git a/services/google/src/lib.rs b/services/google/src/lib.rs index 9231bb9a..c5919110 100644 --- a/services/google/src/lib.rs +++ b/services/google/src/lib.rs @@ -54,3 +54,11 @@ pub use provide_credential::{ FileCredentialProvider, ServiceAccountTokenCredentialProvider, StaticCredentialProvider, TokenCredentialProvider, VmMetadataCredentialProvider, WellKnownCredentialProvider, }; + +// Unit tests exercise signing paths, so install the test provider before +// any test in this binary runs. +#[cfg(test)] +#[ctor::ctor(unsafe)] +fn install_test_crypto_provider() { + let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +} diff --git a/services/google/src/sign_request.rs b/services/google/src/sign_request.rs index 35cbfb7d..b784a31a 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, Error as ReqsignError, Result, SignRequest, SigningCredential, SigningRequest, crypto, + hash::hex_sha256, time::*, }; use crate::constants::{ @@ -300,7 +297,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(sa.private_key.as_bytes())?, scope: scope.clone(), }; @@ -428,7 +425,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(creq.as_bytes())?; let scope = format!( "{}/{}/{}/goog4_request", @@ -455,14 +452,15 @@ impl RequestSigner { } 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 provider = crypto::get_default().ok_or_else(|| { + ReqsignError::config_invalid( + "no CryptoProvider is installed; install one during application startup", + ) })?; - let signing_key = SigningKey::::new(private_key); - let signature = signing_key.sign_with_rng(&mut rng, string_to_sign.as_bytes()); + 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( @@ -874,6 +872,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}; diff --git a/services/google/tests/common/mod.rs b/services/google/tests/common/mod.rs new file mode 100644 index 00000000..3b0c8c71 --- /dev/null +++ b/services/google/tests/common/mod.rs @@ -0,0 +1,24 @@ +// 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. + +// Every integration test binary installs the RustCrypto provider once before +// its tests run. Installation is process-wide, so concurrent or repeated +// initialization is intentionally ignored. +#[ctor::ctor(unsafe)] +fn install_test_crypto_provider() { + let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +} diff --git a/services/google/tests/credential_access_boundary.rs b/services/google/tests/credential_access_boundary.rs index 25d17d2e..911b8d9f 100644 --- a/services/google/tests/credential_access_boundary.rs +++ b/services/google/tests/credential_access_boundary.rs @@ -17,6 +17,8 @@ #![cfg(feature = "credential-access-boundary-client-side")] +mod common; + use std::env; use log::warn; diff --git a/services/google/tests/explicit_credential_access_boundary.rs b/services/google/tests/explicit_credential_access_boundary.rs index 122217c5..18a9bc4e 100644 --- a/services/google/tests/explicit_credential_access_boundary.rs +++ b/services/google/tests/explicit_credential_access_boundary.rs @@ -15,6 +15,8 @@ // 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}; 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..29095260 100644 --- a/services/google/tests/oauth_token_endpoint.rs +++ b/services/google/tests/oauth_token_endpoint.rs @@ -15,6 +15,8 @@ // specific language governing permissions and limitations // under the License. +mod common; + use std::sync::{Arc, Mutex, OnceLock}; use bytes::Bytes; diff --git a/services/google/tests/service_account_token.rs b/services/google/tests/service_account_token.rs index d6d02b6a..9e20e34c 100644 --- a/services/google/tests/service_account_token.rs +++ b/services/google/tests/service_account_token.rs @@ -15,6 +15,8 @@ // specific language governing permissions and limitations // under the License. +mod common; + use std::env; use log::warn; diff --git a/services/huaweicloud-obs/Cargo.toml b/services/huaweicloud-obs/Cargo.toml index 61c2a59d..cdf57cb7 100644 --- a/services/huaweicloud-obs/Cargo.toml +++ b/services/huaweicloud-obs/Cargo.toml @@ -36,6 +36,8 @@ serde = { workspace = true } serde_json = { workspace = true } [dev-dependencies] +ctor = "1" +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..d9189ebe 100644 --- a/services/huaweicloud-obs/README.md +++ b/services/huaweicloud-obs/README.md @@ -21,6 +21,10 @@ 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 requires a process-wide `CryptoProvider`. Install one at startup +> before constructing signers; see +> [CryptoProvider](https://github.com/apache/reqsign/blob/main/docs/crypto-provider.md). + ## Quick Start ```rust,no_run diff --git a/services/huaweicloud-obs/src/agency.rs b/services/huaweicloud-obs/src/agency.rs index b1cc4854..3e3dc1ae 100644 --- a/services/huaweicloud-obs/src/agency.rs +++ b/services/huaweicloud-obs/src/agency.rs @@ -507,16 +507,16 @@ 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(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(canonical_request.as_bytes())? ); - let signature = hex_hmac_sha256(secret_access_key.as_bytes(), string_to_sign.as_bytes()); + let signature = hex_hmac_sha256(secret_access_key.as_bytes(), string_to_sign.as_bytes())?; Ok(format!( "{SDK_HMAC_SHA256} Access={access_key_id}, SignedHeaders={signed_headers}, Signature={signature}" diff --git a/services/huaweicloud-obs/src/lib.rs b/services/huaweicloud-obs/src/lib.rs index 955fdda5..c2d0af6b 100644 --- a/services/huaweicloud-obs/src/lib.rs +++ b/services/huaweicloud-obs/src/lib.rs @@ -30,3 +30,11 @@ mod provide_credential; pub use provide_credential::*; mod constants; + +// Unit tests exercise signing paths, so install the test provider before +// any test in this binary runs. +#[cfg(test)] +#[ctor::ctor(unsafe)] +fn install_test_crypto_provider() { + let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +} diff --git a/services/huaweicloud-obs/src/sign_request.rs b/services/huaweicloud-obs/src/sign_request.rs index cb1efb65..cffccbb0 100644 --- a/services/huaweicloud-obs/src/sign_request.rs +++ b/services/huaweicloud-obs/src/sign_request.rs @@ -125,7 +125,7 @@ impl SignRequest for RequestSigner { 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()); + base64_hmac_sha1(cred.secret_access_key.as_bytes(), string_to_sign.as_bytes())?; let final_uri = match method { SigningMethod::Header => { diff --git a/services/huaweicloud-obs/tests/common/mod.rs b/services/huaweicloud-obs/tests/common/mod.rs new file mode 100644 index 00000000..3b0c8c71 --- /dev/null +++ b/services/huaweicloud-obs/tests/common/mod.rs @@ -0,0 +1,24 @@ +// 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. + +// Every integration test binary installs the RustCrypto provider once before +// its tests run. Installation is process-wide, so concurrent or repeated +// initialization is intentionally ignored. +#[ctor::ctor(unsafe)] +fn install_test_crypto_provider() { + let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +} diff --git a/services/huaweicloud-obs/tests/credential_chain.rs b/services/huaweicloud-obs/tests/credential_chain.rs index 5c8ccbad..62e525dc 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; diff --git a/services/oracle/Cargo.toml b/services/oracle/Cargo.toml index 88ce3198..a9dd45da 100644 --- a/services/oracle/Cargo.toml +++ b/services/oracle/Cargo.toml @@ -32,11 +32,13 @@ base64 = { workspace = true } http = { workspace = true } log = { workspace = true } reqsign-core = { workspace = true } -rsa = { workspace = true } rust-ini = { workspace = true } [dev-dependencies] +ctor = "1" 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..d2a8a307 100644 --- a/services/oracle/README.md +++ b/services/oracle/README.md @@ -6,6 +6,10 @@ 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 requires a process-wide `CryptoProvider`. Install one at startup +> before constructing signers; see +> [CryptoProvider](https://github.com/apache/reqsign/blob/main/docs/crypto-provider.md). + ## Quick Start ```rust,no_run diff --git a/services/oracle/src/lib.rs b/services/oracle/src/lib.rs index 4632912d..325ef008 100644 --- a/services/oracle/src/lib.rs +++ b/services/oracle/src/lib.rs @@ -37,3 +37,11 @@ pub use provide_credential::{ ConfigFileCredentialProvider, DefaultCredentialProvider, DefaultCredentialProviderBuilder, EnvCredentialProvider, StaticCredentialProvider, }; + +// Unit tests exercise signing paths, so install the test provider before +// any test in this binary runs. +#[cfg(test)] +#[ctor::ctor(unsafe)] +fn install_test_crypto_provider() { + let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +} diff --git a/services/oracle/src/sign_request.rs b/services/oracle/src/sign_request.rs index d0aeb7ef..850aae86 100644 --- a/services/oracle/src/sign_request.rs +++ b/services/oracle/src/sign_request.rs @@ -22,11 +22,9 @@ use http::request::Parts; 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 reqsign_core::{ + Context, Error, Result, SignRequest, SigningCredential, SigningRequest, crypto, +}; use std::fmt::Write; use std::time::Duration; @@ -103,21 +101,17 @@ 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 = crypto::get_default().ok_or_else(|| { + Error::config_invalid( + "no CryptoProvider is installed; install one during application startup", + ) + })?; + 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 +202,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; diff --git a/services/oracle/tests/common/mod.rs b/services/oracle/tests/common/mod.rs new file mode 100644 index 00000000..3b0c8c71 --- /dev/null +++ b/services/oracle/tests/common/mod.rs @@ -0,0 +1,24 @@ +// 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. + +// Every integration test binary installs the RustCrypto provider once before +// its tests run. Installation is process-wide, so concurrent or repeated +// initialization is intentionally ignored. +#[ctor::ctor(unsafe)] +fn install_test_crypto_provider() { + let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +} diff --git a/services/oracle/tests/config_profiles.rs b/services/oracle/tests/config_profiles.rs index 1b7d33e1..c174f1b3 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; diff --git a/services/oracle/tests/credential_chain.rs b/services/oracle/tests/credential_chain.rs index cf1236e6..dec5aabb 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; diff --git a/services/oracle/tests/private_key_formats.rs b/services/oracle/tests/private_key_formats.rs index 3cae0cb1..a81a9818 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}; diff --git a/services/tencent-cos/Cargo.toml b/services/tencent-cos/Cargo.toml index a7a41819..8e1d67ae 100644 --- a/services/tencent-cos/Cargo.toml +++ b/services/tencent-cos/Cargo.toml @@ -36,6 +36,8 @@ serde = { workspace = true } serde_json = { workspace = true } [dev-dependencies] +ctor = "1" +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..ef23a805 100644 --- a/services/tencent-cos/README.md +++ b/services/tencent-cos/README.md @@ -6,6 +6,10 @@ The default credential provider checks Tencent Cloud environment variables and then web identity configuration. It supports both header authentication and presigned query authentication. +> Signing requires a process-wide `CryptoProvider`. Install one at startup +> before constructing signers; see +> [CryptoProvider](https://github.com/apache/reqsign/blob/main/docs/crypto-provider.md). + ## Quick Start ```rust,no_run diff --git a/services/tencent-cos/src/get_federation_token.rs b/services/tencent-cos/src/get_federation_token.rs index 72a8a636..eb64db27 100644 --- a/services/tencent-cos/src/get_federation_token.rs +++ b/services/tencent-cos/src/get_federation_token.rs @@ -331,20 +331,20 @@ 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(&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(canonical_request.as_bytes())? ); let secret_date = hmac_sha256( 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(&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 authorization = format!( "TC3-HMAC-SHA256 Credential={}/{credential_scope}, SignedHeaders={signed_headers}, Signature={signature}", credential.secret_id diff --git a/services/tencent-cos/src/lib.rs b/services/tencent-cos/src/lib.rs index 7be93aa5..bffc5e44 100644 --- a/services/tencent-cos/src/lib.rs +++ b/services/tencent-cos/src/lib.rs @@ -32,3 +32,11 @@ pub use sign_request::RequestSigner; mod provide_credential; pub use provide_credential::*; + +// Unit tests exercise signing paths, so install the test provider before +// any test in this binary runs. +#[cfg(test)] +#[ctor::ctor(unsafe)] +fn install_test_crypto_provider() { + let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +} diff --git a/services/tencent-cos/src/sign_request.rs b/services/tencent-cos/src/sign_request.rs index f9396f8c..4e89a185 100644 --- a/services/tencent-cos/src/sign_request.rs +++ b/services/tencent-cos/src/sign_request.rs @@ -101,7 +101,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(&signing_req, cred, now, expires)?; signing_req .headers @@ -117,7 +117,7 @@ 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(&signing_req, cred, now, Duration::from_secs(3600))?; signing_req .headers @@ -151,9 +151,9 @@ fn build_signature( 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(cred.secret_key.as_bytes(), key_time.as_bytes())?; let (param_list, param_string) = canonical_query(ctx); debug!("param list: {param_list}"); @@ -201,16 +201,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(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(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) { diff --git a/services/tencent-cos/tests/common/mod.rs b/services/tencent-cos/tests/common/mod.rs new file mode 100644 index 00000000..3b0c8c71 --- /dev/null +++ b/services/tencent-cos/tests/common/mod.rs @@ -0,0 +1,24 @@ +// 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. + +// Every integration test binary installs the RustCrypto provider once before +// its tests run. Installation is process-wide, so concurrent or repeated +// initialization is intentionally ignored. +#[ctor::ctor(unsafe)] +fn install_test_crypto_provider() { + let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +} diff --git a/services/tencent-cos/tests/credential_chain.rs b/services/tencent-cos/tests/credential_chain.rs index 210eaf90..553775ef 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}; diff --git a/services/tencent-cos/tests/main.rs b/services/tencent-cos/tests/main.rs index 87b5c633..e9858ed6 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; diff --git a/services/tencent-cos/tests/web_identity_live.rs b/services/tencent-cos/tests/web_identity_live.rs index 43c8555e..b583ffb9 100644 --- a/services/tencent-cos/tests/web_identity_live.rs +++ b/services/tencent-cos/tests/web_identity_live.rs @@ -23,6 +23,8 @@ //! 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; diff --git a/services/volcengine-tos/Cargo.toml b/services/volcengine-tos/Cargo.toml index fa5816cb..b8a00261 100644 --- a/services/volcengine-tos/Cargo.toml +++ b/services/volcengine-tos/Cargo.toml @@ -36,6 +36,8 @@ serde = { workspace = true } serde_json = { workspace = true } [dev-dependencies] +ctor = "1" +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..a15ff6d8 100644 --- a/services/volcengine-tos/README.md +++ b/services/volcengine-tos/README.md @@ -26,6 +26,10 @@ the default credential chain is unchanged. full presigned URL lifetime. Header signing continues to check the signing time. +> Signing requires a process-wide `CryptoProvider`. Install one at startup +> before constructing signers; see +> [CryptoProvider](https://github.com/apache/reqsign/blob/main/docs/crypto-provider.md). + ## Quick Start ```rust,no_run diff --git a/services/volcengine-tos/src/assume_role.rs b/services/volcengine-tos/src/assume_role.rs index 1cc9cec7..643429ee 100644 --- a/services/volcengine-tos/src/assume_role.rs +++ b/services/volcengine-tos/src/assume_role.rs @@ -410,15 +410,15 @@ impl AssumeRoleGranter { ); let string_to_sign = format!( "HMAC-SHA256\n{date}\n{credential_scope}\n{}", - hex_sha256(canonical_request.as_bytes()) + hex_sha256(canonical_request.as_bytes())? ); let signing_key = derive_signing_key( &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(&signing_key, string_to_sign.as_bytes())?; let authorization = format!( "HMAC-SHA256 Credential={}/{credential_scope}, SignedHeaders={signed_headers}, Signature={signature}", credential.access_key_id @@ -562,11 +562,11 @@ 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(secret: &str, date: &str, region: &str, service: &str) -> Result> { + 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())?; + Ok(hmac_sha256(&service_key, b"request")?.to_vec()) } #[derive(Deserialize)] diff --git a/services/volcengine-tos/src/lib.rs b/services/volcengine-tos/src/lib.rs index 75fde31a..54aef830 100644 --- a/services/volcengine-tos/src/lib.rs +++ b/services/volcengine-tos/src/lib.rs @@ -32,3 +32,11 @@ mod uri; pub use uri::{percent_encode_path, percent_encode_query}; pub use sign_request::RequestSigner; + +// Unit tests exercise signing paths, so install the test provider before +// any test in this binary runs. +#[cfg(test)] +#[ctor::ctor(unsafe)] +fn install_test_crypto_provider() { + let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +} diff --git a/services/volcengine-tos/src/sign_request.rs b/services/volcengine-tos/src/sign_request.rs index c1350be6..f92aa41e 100644 --- a/services/volcengine-tos/src/sign_request.rs +++ b/services/volcengine-tos/src/sign_request.rs @@ -179,8 +179,8 @@ 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(&cred.secret_access_key, &date_only, &self.region)?; + let signature = hex_hmac_sha256(&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)?; @@ -417,20 +417,20 @@ fn canonical_request_hash( canonical_request.push_str(payload_hash); - let hash = hex_sha256(canonical_request.as_bytes()); + let hash = hex_sha256(canonical_request.as_bytes())?; Ok((hash, canonical_request)) } -fn generate_signing_key(secret: &str, date: &str, region: &str) -> Vec { +fn generate_signing_key(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(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(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(sign_region.as_slice(), "tos".as_bytes())?; // Sign request - hmac_sha256(sign_service.as_slice(), "request".as_bytes()) + Ok(hmac_sha256(sign_service.as_slice(), "request".as_bytes())?.to_vec()) } #[cfg(test)] diff --git a/services/volcengine-tos/tests/common/mod.rs b/services/volcengine-tos/tests/common/mod.rs new file mode 100644 index 00000000..3b0c8c71 --- /dev/null +++ b/services/volcengine-tos/tests/common/mod.rs @@ -0,0 +1,24 @@ +// 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. + +// Every integration test binary installs the RustCrypto provider once before +// its tests run. Installation is process-wide, so concurrent or repeated +// initialization is intentionally ignored. +#[ctor::ctor(unsafe)] +fn install_test_crypto_provider() { + let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +} diff --git a/services/volcengine-tos/tests/presigned.rs b/services/volcengine-tos/tests/presigned.rs index e3fb9052..68a578b7 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; @@ -132,7 +134,7 @@ 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(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..c6241ceb 100644 --- a/services/volcengine-tos/tests/signing_diagnostics.rs +++ b/services/volcengine-tos/tests/signing_diagnostics.rs @@ -15,6 +15,8 @@ // specific language governing permissions and limitations // under the License. +mod common; + use std::sync::{Mutex, Once}; use std::time::Duration; diff --git a/website/docs/architecture.md b/website/docs/architecture.md index a50bd992..68666891 100644 --- a/website/docs/architecture.md +++ b/website/docs/architecture.md @@ -103,6 +103,27 @@ 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 not a `Context` capability. Reqsign resolves every hash, MAC, +asymmetric signature, AES-GCM operation, and random draw through one +process-wide `CryptoProvider` installed by the application at startup: + +```rust +use reqsign::RustCryptoProvider; + +RustCryptoProvider::install_default() + .map_err(|_| "a CryptoProvider is already installed")?; +``` + +`reqsign-core` and the service crates contain no cryptographic implementation, +so signing without an installed provider returns `ConfigInvalid`. The facade's +`default-crypto` feature supplies the RustCrypto provider but does not install +it; `default_context()` does not install it either. Applications choose the +provider, and integrating middleware such as OpenDAL must leave that choice to +the application. 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/guides/testing.md b/website/docs/guides/testing.md index df9dc40e..906ec47d 100644 --- a/website/docs/guides/testing.md +++ b/website/docs/guides/testing.md @@ -33,9 +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}; +RustCryptoProvider::install_default() + .map_err(|_| "a CryptoProvider is already installed")?; + let signer = Signer::new( Context::new(), // no I/O needed with static credentials StaticCredentialProvider::new("AKIDEXAMPLE", "example-secret-key"), 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) From e7d4074a8cf70037e8cd8484757b9951663464c9 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Thu, 19 Nov 2026 18:21:46 +0100 Subject: [PATCH 02/11] chore(aws-core): drop the unused hex dependency SHA-1 cache keys now come from reqsign_core::hash, so aws-core no longer uses the hex crate directly. --- services/aws-core/Cargo.toml | 1 - 1 file changed, 1 deletion(-) diff --git a/services/aws-core/Cargo.toml b/services/aws-core/Cargo.toml index 7f97cbc7..1bb9f484 100644 --- a/services/aws-core/Cargo.toml +++ b/services/aws-core/Cargo.toml @@ -32,7 +32,6 @@ bytes = { workspace = true } futures = { workspace = true } futures-timer = { version = "3", features = ["wasm-bindgen"] } form_urlencoded = { workspace = true } -hex = { workspace = true } http = { workspace = true } log = { workspace = true } percent-encoding = { workspace = true } From 8a67a2f2104ae3f99687ef5f10f2488870eb0181 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Thu, 19 Nov 2026 18:39:40 +0100 Subject: [PATCH 03/11] docs: require CryptoProvider before credential loading State that installation must precede credential loading that uses crypto, and explain how generic credential chains surface Ok(None) while selected identities such as AWS SSO propagate the underlying error. Clarify that installation is at-most-once rather than idempotent, note Google service-account invalid key behavior, and check every optional dependency path per root in the production crypto graph gate. --- .github/workflows/ci.yml | 6 +++++- core/src/crypto.rs | 6 +++--- docs/crypto-provider.md | 28 +++++++++++++++++++++++----- 3 files changed, 31 insertions(+), 9 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e9c355b2..a8d424f6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -60,8 +60,12 @@ jobs: 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 -p "$package" --edges normal | grep -Eq ' (sha1|sha2|hmac|rsa|p256|aes-gcm) v'; then + if cargo tree -p "$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 diff --git a/core/src/crypto.rs b/core/src/crypto.rs index 422cee4d..8b605023 100644 --- a/core/src/crypto.rs +++ b/core/src/crypto.rs @@ -22,9 +22,9 @@ //! signing, encryption and random generation performed by reqsign goes through //! the installed provider. //! -//! A process can install at most one provider. The installation is idempotent -//! from the caller's perspective: later attempts return the provider they tried -//! to install and leave the first provider in place. +//! A process can install at most one provider. Installation is not +//! idempotent: later attempts return the provider they tried to install and +//! leave the first provider in place. use std::fmt::Debug; use std::sync::{Arc, OnceLock}; diff --git a/docs/crypto-provider.md b/docs/crypto-provider.md index c28148cb..1f263c60 100644 --- a/docs/crypto-provider.md +++ b/docs/crypto-provider.md @@ -98,6 +98,8 @@ most once per process. 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. @@ -228,8 +230,12 @@ their own minimal `CryptoProvider`. ### Applications -Install one provider once during startup, before constructing signers or calling -signing operations: +Install one provider once during startup, before constructing signers and before +any credential loading that may use cryptography. For example, AWS SSO computes +its cache key with SHA-1, Google service-account exchange signs a JWT, and Azure +client certificate authentication signs a client assertion while loading a +credential. Installing later can change a configuration error into credential +absence. ```rust use reqsign::RustCryptoProvider; @@ -247,6 +253,15 @@ A failure from `install_default` means another component already installed a provider. Applications that intentionally compose several libraries should install their chosen provider before any of them are initialized. +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 +missing 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; installing 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 @@ -271,7 +286,8 @@ Notable service-specific details: client assertion uses `jwt::encode_rs256_pem`. - Google service-account signing encodes the provider's RSA signature as hex; client-side credential access boundary encryption uses AES-GCM through the - provider and gets its nonce from `fill_random`. + provider and gets its nonce from `fill_random`. Malformed service-account key + material returns `CredentialInvalid` while signing the exchange JWT. ### Removed APIs @@ -294,8 +310,10 @@ The repository verifies this contract with: - 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. -- `cargo tree --edges normal` checks that no core or service production graph - contains a cryptographic implementation crate. +- 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, and the standalone BoringSSL workflow. From 30157277d9dd14b6ae2aa01b28e1bf7365727674 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Thu, 19 Nov 2026 19:32:28 +0100 Subject: [PATCH 04/11] feat(core): resolve CryptoProvider through Context Add explicit Context::with_crypto bindings and context fallbacks. Crypto resolution now prefers an explicit binding, then the process-wide install, then the fallback, and otherwise fails with ConfigInvalid at the point of use. Contexts never install or freeze the global slot, so a provider installed after a context was created still takes precedence over its fallback. The facade's default_context supplies RustCrypto as a fallback when default-crypto is enabled, making default signers and examples work without startup boilerplate while preserving explicit and global overrides. Bare Context::new() still has no provider. Thread the selected provider through signing, credential, and granting paths and through standalone hash, JWT PEM, and Azure service SAS entry points. Update tests to bind providers locally, add resolution-priority and facade feature coverage, update caller documentation, and classify reqsign-crypto-rustcrypto as an internal website crate so the provider catalog validator accepts the new workspace member. --- .github/workflows/ci.yml | 4 + AGENTS.md | 11 +- README.md | 14 +- core/src/context.rs | 67 ++++++ core/src/crypto.rs | 23 +- core/src/hash.rs | 65 +++--- core/src/jwt.rs | 30 ++- core/tests/crypto_provider_context.rs | 95 +++++++++ core/tests/crypto_provider_unset.rs | 28 +-- core/tests/support/mod.rs | 22 ++ crypto/boring/tests/parity.rs | 9 +- crypto/rustcrypto/tests/core_hash.rs | 44 ++-- docs/crypto-provider.md | 197 ++++++++++++------ reqsign/README.md | 23 +- reqsign/examples/aws.rs | 2 - reqsign/examples/azure.rs | 2 - reqsign/examples/custom_context.rs | 3 +- reqsign/examples/custom_http.rs | 6 +- reqsign/examples/google.rs | 2 - reqsign/examples/presign.rs | 2 - reqsign/examples/s3_express_grant.rs | 2 - reqsign/examples/s3_express_sign.rs | 2 - reqsign/examples/static_credentials.rs | 2 - reqsign/src/context.rs | 39 ++-- reqsign/tests/crypto.rs | 85 +++++++- .../tests/crypto_without_default_crypto.rs | 31 +++ reqsign/tests/default_signer.rs | 84 ++++++++ services/aliyun-oss/Cargo.toml | 1 - services/aliyun-oss/README.md | 8 +- .../aliyun-oss/examples/oss_operations.rs | 2 + services/aliyun-oss/src/assume_role.rs | 27 ++- services/aliyun-oss/src/lib.rs | 7 +- .../src/provide_credential/assume_role.rs | 10 +- .../assume_role_with_oidc.rs | 12 +- .../src/provide_credential/config_file.rs | 6 +- .../provide_credential/credentials_file.rs | 6 +- .../src/provide_credential/credentials_uri.rs | 12 +- .../src/provide_credential/default.rs | 34 +-- .../src/provide_credential/ecs_ram_role.rs | 12 +- .../aliyun-oss/src/provide_credential/env.rs | 12 +- .../src/provide_credential/oss_profile.rs | 6 +- .../src/provide_credential/static.rs | 2 +- services/aliyun-oss/src/sign_request.rs | 141 ++++++++++--- services/aliyun-oss/tests/common/mod.rs | 10 +- services/aliyun-oss/tests/credential_chain.rs | 8 +- services/aliyun-oss/tests/main.rs | 2 +- services/aws-core/Cargo.toml | 1 - services/aws-core/src/assume_role.rs | 14 +- services/aws-core/src/lib.rs | 16 +- .../assume_role_with_web_identity.rs | 10 +- .../src/provide_credential/cognito.rs | 2 +- .../src/provide_credential/default.rs | 28 +-- .../aws-core/src/provide_credential/ecs.rs | 24 +-- .../aws-core/src/provide_credential/env.rs | 8 +- .../src/provide_credential/process.rs | 4 +- .../src/provide_credential/profile.rs | 10 +- .../src/provide_credential/sso/session.rs | 3 +- .../src/provide_credential/sso/tests.rs | 5 +- .../aws-core/src/provide_credential/static.rs | 2 +- services/aws-core/tests/common/mod.rs | 10 +- services/aws-core/tests/shared_config.rs | 2 +- services/aws-v4/Cargo.toml | 1 - services/aws-v4/README.md | 11 +- services/aws-v4/benches/aws.rs | 4 +- services/aws-v4/examples/dynamodb_sign.rs | 12 +- services/aws-v4/examples/s3_express_sign.rs | 4 +- services/aws-v4/examples/s3_sign.rs | 4 +- services/aws-v4/src/assume_role.rs | 69 +++--- services/aws-v4/src/lib.rs | 7 +- .../provide_credential/s3_express_session.rs | 26 +-- services/aws-v4/src/s3_access_grants.rs | 30 +-- services/aws-v4/src/sign_request.rs | 88 +++++--- services/aws-v4/tests/common/mod.rs | 10 +- .../aws-v4/tests/credential_providers/mod.rs | 4 +- services/aws-v4/tests/signing/mod.rs | 2 +- services/aws-v4a/Cargo.toml | 1 - services/aws-v4a/README.md | 5 +- services/aws-v4a/src/lib.rs | 7 +- services/aws-v4a/src/sign_request.rs | 99 ++++++--- services/azure-storage/Cargo.toml | 1 - services/azure-storage/README.md | 11 +- .../azure-storage/examples/blob_storage.rs | 2 + services/azure-storage/src/lib.rs | 7 +- .../src/provide_credential/azure_pipelines.rs | 2 +- .../provide_credential/client_certificate.rs | 28 ++- .../src/provide_credential/default.rs | 4 +- .../src/provide_credential/env.rs | 8 +- .../src/provide_credential/static_provider.rs | 10 +- .../provide_credential/workload_identity.rs | 2 +- services/azure-storage/src/service_sas.rs | 84 ++++++-- services/azure-storage/src/sign_request.rs | 29 ++- services/azure-storage/src/user_delegation.rs | 9 +- .../azure-storage/src/user_delegation_sas.rs | 58 +++--- services/azure-storage/tests/common/mod.rs | 10 +- .../tests/credential_providers/default.rs | 4 +- .../tests/credential_providers/mod.rs | 2 +- .../azure-storage/tests/signing/sas_token.rs | 8 +- .../azure-storage/tests/signing/shared_key.rs | 10 +- services/google/Cargo.toml | 1 - services/google/README.md | 8 +- services/google/examples/chain_logging.rs | 2 + services/google/examples/custom_chain.rs | 2 + .../credential_access_boundary/client_side.rs | 144 +++++++------ .../credential_access_boundary/server_side.rs | 28 +-- services/google/src/lib.rs | 7 +- .../google/src/provide_credential/default.rs | 16 +- .../provide_credential/external_account.rs | 49 +++-- .../impersonated_service_account.rs | 2 +- .../service_account_token.rs | 28 ++- .../src/provide_credential/static_provider.rs | 6 +- .../src/provide_credential/vm_metadata.rs | 4 +- .../src/service_account_impersonation.rs | 16 +- services/google/src/sign_request.rs | 108 ++++++---- services/google/tests/common/mod.rs | 11 +- .../tests/credential_access_boundary.rs | 6 +- .../google/tests/credential_providers/mod.rs | 4 +- .../explicit_credential_access_boundary.rs | 10 +- services/google/tests/oauth_token_endpoint.rs | 12 +- .../google/tests/service_account_token.rs | 6 +- services/google/tests/signing/signed_url.rs | 2 +- services/google/tests/signing/standard.rs | 2 +- services/huaweicloud-obs/Cargo.toml | 1 - services/huaweicloud-obs/README.md | 8 +- .../huaweicloud-obs/examples/chain_logging.rs | 2 + .../huaweicloud-obs/examples/custom_chain.rs | 2 + services/huaweicloud-obs/src/agency.rs | 37 +++- services/huaweicloud-obs/src/credential.rs | 13 +- services/huaweicloud-obs/src/lib.rs | 7 +- .../src/provide_credential/default.rs | 10 +- .../src/provide_credential/env.rs | 8 +- .../src/provide_credential/static.rs | 2 +- services/huaweicloud-obs/src/sign_request.rs | 29 ++- services/huaweicloud-obs/tests/common/mod.rs | 10 +- .../huaweicloud-obs/tests/credential_chain.rs | 10 +- services/oracle/Cargo.toml | 1 - services/oracle/README.md | 8 +- .../oracle/examples/oracle_chain_logging.rs | 2 + services/oracle/src/lib.rs | 7 +- .../src/provide_credential/config_file.rs | 2 +- .../oracle/src/provide_credential/default.rs | 8 +- services/oracle/src/provide_credential/env.rs | 8 +- .../oracle/src/provide_credential/static_.rs | 2 +- services/oracle/src/sign_request.rs | 14 +- services/oracle/tests/common/mod.rs | 10 +- services/oracle/tests/config_profiles.rs | 4 +- services/oracle/tests/credential_chain.rs | 8 +- services/oracle/tests/private_key_formats.rs | 9 +- services/tencent-cos/Cargo.toml | 1 - services/tencent-cos/README.md | 8 +- .../examples/tencent_chain_logging.rs | 2 + .../tencent-cos/src/get_federation_token.rs | 44 ++-- services/tencent-cos/src/lib.rs | 7 +- .../assume_role_with_web_identity.rs | 2 +- .../src/provide_credential/default.rs | 10 +- .../tencent-cos/src/provide_credential/env.rs | 8 +- .../src/provide_credential/static.rs | 2 +- services/tencent-cos/src/sign_request.rs | 25 ++- services/tencent-cos/tests/common/mod.rs | 10 +- .../tencent-cos/tests/credential_chain.rs | 10 +- services/tencent-cos/tests/main.rs | 4 +- .../tencent-cos/tests/web_identity_live.rs | 4 +- services/volcengine-tos/Cargo.toml | 1 - services/volcengine-tos/README.md | 8 +- services/volcengine-tos/src/assume_role.rs | 62 +++--- services/volcengine-tos/src/lib.rs | 7 +- .../src/provide_credential/default.rs | 8 +- .../src/provide_credential/env.rs | 8 +- .../src/provide_credential/static.rs | 4 +- services/volcengine-tos/src/sign_request.rs | 60 ++++-- services/volcengine-tos/tests/common/mod.rs | 10 +- services/volcengine-tos/tests/presigned.rs | 7 +- .../tests/signing_diagnostics.rs | 11 +- website/data/providers.json | 6 +- website/docs/architecture.md | 30 ++- website/docs/guides/testing.md | 6 +- 175 files changed, 1953 insertions(+), 1132 deletions(-) create mode 100644 core/tests/crypto_provider_context.rs create mode 100644 reqsign/tests/crypto_without_default_crypto.rs create mode 100644 reqsign/tests/default_signer.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a8d424f6..58e7c65d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -145,6 +145,10 @@ jobs: env: RUST_LOG: DEBUG RUST_BACKTRACE: full + - name: Facade crypto feature tests + run: | + cargo test -p reqsign --all-features --test crypto --test default_signer + cargo test -p 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/AGENTS.md b/AGENTS.md index 574fad54..b57dcc2c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -42,12 +42,13 @@ security boundary and its relationship to OpenDAL and other host applications. ### Crypto Provider -All signing cryptography goes through the process-wide -`reqsign_core::crypto::CryptoProvider`. `reqsign-core` and every `services/*` -crate carry no production cryptographic implementation. Follow +All signing cryptography goes through a `reqsign_core::crypto::CryptoProvider` +resolved by `Context` (explicit binding, then the process-wide registration, +then the context fallback). `reqsign-core` and every `services/*` crate carry no +production cryptographic implementation. Follow [docs/crypto-provider.md](docs/crypto-provider.md) as the source of truth for -the provider contract, installation ownership, error semantics, and the -official RustCrypto/BoringSSL implementations. +the provider contract, resolution and installation ownership, error semantics, +and the official RustCrypto/BoringSSL implementations. ### Default Credential Provider diff --git a/README.md b/README.md index 59f8fac3..42d78853 100644 --- a/README.md +++ b/README.md @@ -22,14 +22,11 @@ The simplest way to use `reqsign` is with the default signers provided by each s ```rust use anyhow::Result; -use reqsign::{RustCryptoProvider, aws}; +use reqsign::aws; #[tokio::main] async fn main() -> Result<()> { - // Install the process-wide crypto provider once, before any signing. - RustCryptoProvider::install_default() - .map_err(|_| anyhow::anyhow!("a CryptoProvider is already installed"))?; - + // The facade's default context carries the RustCrypto fallback. // Create a default signer for S3 in us-east-1 // This will automatically: // - Load credentials from environment variables, config files, or IAM roles @@ -67,11 +64,10 @@ use reqsign_http_send_reqwest::ReqwestHttpSend; #[tokio::main] async fn main() -> Result<()> { - RustCryptoProvider::install_default() - .map_err(|_| anyhow::anyhow!("a CryptoProvider is already installed"))?; - - // Build your own context with specific implementations + // Build your own context with specific implementations. + // A bare Context has no fallback, 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/src/context.rs b/core/src/context.rs index 2e14995c..3eed68ca 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`], then a fallback set with +/// [`Context::with_crypto_fallback`]. A bare `Context::new()` has none of these +/// and returns [`crate::ErrorKind::ConfigInvalid`] when crypto is first needed. +/// Creating or cloning a context never installs or freezes a global provider. +/// /// ## Example /// /// ``` @@ -46,6 +56,8 @@ pub struct Context { http: Arc, env: Arc, cmd: Arc, + crypto: Option>, + crypto_fallback: Option>, } impl Debug for Context { @@ -55,6 +67,8 @@ impl Debug for Context { .field("http", &self.http) .field("env", &self.env) .field("cmd", &self.cmd) + .field("crypto", &self.crypto) + .field("crypto_fallback", &self.crypto_fallback) .finish() } } @@ -87,6 +101,8 @@ impl Context { http: Arc::new(NoopHttpSend), env: Arc::new(NoopEnv), cmd: Arc::new(NoopCommandExecute), + crypto: None, + crypto_fallback: None, } } @@ -114,6 +130,57 @@ 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 + } + + /// Set a fallback cryptographic provider for this context. + /// + /// The fallback is used only when no provider is bound explicitly with + /// [`Context::with_crypto`] and no process-wide provider has been installed + /// with [`crate::crypto::install_default`]. It does not install a + /// process-wide provider. Facades use this to make their default context + /// usable without taking away an application's later provider choice. + pub fn with_crypto_fallback(mut self, provider: impl CryptoProvider) -> Self { + self.crypto_fallback = 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`]; + /// 3. the context fallback set with [`Context::with_crypto_fallback`]. + /// + /// If none is available this returns [`crate::ErrorKind::ConfigInvalid`] at + /// the point of use. Resolution never installs or freezes a provider, so a + /// process-wide installation performed after this context was created is + /// observed by later operations through the same context. + 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()); + } + if let Some(provider) = &self.crypto_fallback { + 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 index 8b605023..e94247f7 100644 --- a/core/src/crypto.rs +++ b/core/src/crypto.rs @@ -17,14 +17,17 @@ //! Process-wide cryptographic provider. //! -//! Reqsign does not bundle a cryptographic implementation. Applications install -//! one [`CryptoProvider`] at startup with [`install_default`]. All hashing, -//! signing, encryption and random generation performed by reqsign goes through -//! the installed 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`], then the context +//! fallback set with +//! [`Context::with_crypto_fallback`](crate::Context::with_crypto_fallback). //! -//! A process can install at most one provider. Installation is not +//! 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. +//! 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}; @@ -131,11 +134,3 @@ pub fn install_default( pub fn get_default() -> Option<&'static Arc> { DEFAULT_PROVIDER.get() } - -pub(crate) fn require_default() -> Result<&'static Arc> { - get_default().ok_or_else(|| { - Error::config_invalid( - "no CryptoProvider is installed; install one during application startup", - ) - }) -} diff --git a/core/src/hash.rs b/core/src/hash.rs index 3b126a41..4d752d37 100644 --- a/core/src/hash.rs +++ b/core/src/hash.rs @@ -17,12 +17,15 @@ //! Hash related utils. //! -//! Encoding helpers are pure functions. Digest and MAC helpers use the -//! process-wide [`crate::crypto::CryptoProvider`] and return an error when no -//! provider is installed or the installed provider cannot serve the operation. +//! 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::crypto; -use crate::{Error, Result}; +use crate::Error; +use crate::Result; +use crate::crypto::CryptoProvider; use base64::Engine; use base64::prelude::BASE64_STANDARD; @@ -39,51 +42,63 @@ pub fn base64_decode(content: &str) -> crate::Result> { } /// SHA1 digest. -pub fn sha1(content: &[u8]) -> Result<[u8; 20]> { - crypto::require_default()?.sha1(content) +pub fn sha1(provider: &dyn CryptoProvider, content: &[u8]) -> Result<[u8; 20]> { + provider.sha1(content) } /// SHA256 digest. -pub fn sha256(content: &[u8]) -> Result<[u8; 32]> { - crypto::require_default()?.sha256(content) +pub fn sha256(provider: &dyn CryptoProvider, content: &[u8]) -> Result<[u8; 32]> { + provider.sha256(content) } /// HMAC with SHA1 hash. -pub fn hmac_sha1(key: &[u8], content: &[u8]) -> Result<[u8; 20]> { - crypto::require_default()?.hmac_sha1(key, content) +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]) -> Result<[u8; 32]> { - crypto::require_default()?.hmac_sha256(key, content) +pub fn hmac_sha256(provider: &dyn CryptoProvider, key: &[u8], content: &[u8]) -> Result<[u8; 32]> { + provider.hmac_sha256(key, content) } /// Hex encoded SHA1 hash. -pub fn hex_sha1(content: &[u8]) -> Result { - Ok(hex::encode(sha1(content)?)) +pub fn hex_sha1(provider: &dyn CryptoProvider, content: &[u8]) -> Result { + Ok(hex::encode(sha1(provider, content)?)) } /// Hex encoded SHA256 hash. -pub fn hex_sha256(content: &[u8]) -> Result { - Ok(hex::encode(sha256(content)?)) +pub fn hex_sha256(provider: &dyn CryptoProvider, content: &[u8]) -> Result { + Ok(hex::encode(sha256(provider, content)?)) } /// Base64 encoded HMAC with SHA256 hash. -pub fn base64_hmac_sha256(key: &[u8], content: &[u8]) -> Result { - Ok(base64_encode(&hmac_sha256(key, content)?)) +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. -pub fn hex_hmac_sha1(key: &[u8], content: &[u8]) -> Result { - Ok(hex::encode(hmac_sha1(key, content)?)) +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. -pub fn hex_hmac_sha256(key: &[u8], content: &[u8]) -> Result { - Ok(hex::encode(hmac_sha256(key, content)?)) +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]) -> Result { - Ok(base64_encode(&hmac_sha1(key, content)?)) +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 index 8f8d4df9..c2135fa3 100644 --- a/core/src/jwt.rs +++ b/core/src/jwt.rs @@ -21,16 +21,24 @@ use base64::Engine; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use serde::Serialize; -use crate::crypto; -use crate::{Error, Result}; +use crate::Error; +use crate::Result; +use crate::crypto::CryptoProvider; /// Encode a JWS compact JWT using an RSA private key in PKCS#8 or PKCS#1 PEM /// format. /// /// 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. -/// Signing is performed by the installed [`crypto::CryptoProvider`]. -pub fn encode_rs256_pem(header: &H, claims: &C, private_key_pem: &[u8]) -> Result +/// Signing is performed by `provider`, which callers with a +/// [`Context`](crate::Context) resolve with +/// [`Context::crypto_provider`](crate::Context::crypto_provider). +pub fn encode_rs256_pem( + provider: &dyn CryptoProvider, + header: &H, + claims: &C, + private_key_pem: &[u8], +) -> Result where H: Serialize, C: Serialize, @@ -39,8 +47,7 @@ where let encoded_claims = encode_json(claims)?; let signing_input = format!("{encoded_header}.{encoded_claims}"); - let signature = crypto::require_default()? - .rsa_pkcs1v15_sha256_sign(private_key_pem, signing_input.as_bytes())?; + let signature = provider.rsa_pkcs1v15_sha256_sign(private_key_pem, signing_input.as_bytes())?; Ok(format!( "{signing_input}.{}", @@ -60,7 +67,7 @@ where #[cfg(test)] mod tests { use super::*; - use crate::crypto::install_default; + use crate::Context; use crate::test_support::TestCryptoProvider; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use rsa::RsaPrivateKey; @@ -137,7 +144,8 @@ mod tests { #[test] fn encode_rs256_pem_keeps_jws_shape_and_verifiable_signature() { - let _ = install_default(TestCryptoProvider); + let ctx = Context::new().with_crypto(TestCryptoProvider); + let provider = ctx.crypto_provider().expect("test provider must resolve"); let private_key = private_key(); let header = Header { alg: "RS256", @@ -159,7 +167,7 @@ mod tests { .to_pkcs1_pem(rsa::pkcs1::LineEnding::LF) .expect("test key must encode as PKCS#1"), ] { - let jwt = encode_rs256_pem(&header, &claims, pem.as_bytes()) + let jwt = encode_rs256_pem(provider, &header, &claims, pem.as_bytes()) .expect("JWT encoding must succeed"); verify(&header, &claims, &jwt, pem.as_bytes()); } @@ -167,8 +175,10 @@ mod tests { #[test] fn encode_rs256_pem_rejects_malformed_key_material() { - let _ = install_default(TestCryptoProvider); + let ctx = Context::new().with_crypto(TestCryptoProvider); + let provider = ctx.crypto_provider().expect("test provider must resolve"); let err = encode_rs256_pem( + provider, &Header { alg: "RS256", typ: "JWT", diff --git a/core/tests/crypto_provider_context.rs b/core/tests/crypto_provider_context.rs new file mode 100644 index 00000000..18ddd337 --- /dev/null +++ b/core/tests/crypto_provider_context.rs @@ -0,0 +1,95 @@ +// 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_late_global_then_fallback() { + let fallback = Context::new().with_crypto_fallback(ByteProvider(1)); + assert!( + get_default().is_none(), + "creating a context must not install" + ); + + assert_eq!( + hash::sha256( + fallback.crypto_provider().expect("fallback must resolve"), + b"x" + ) + .expect("fallback hashing must succeed"), + [1; 32] + ); + + let explicit = Context::new() + .with_crypto(ByteProvider(2)) + .with_crypto_fallback(ByteProvider(3)); + assert_eq!( + hash::sha256( + explicit.crypto_provider().expect("explicit must resolve"), + b"x" + ) + .expect("explicit hashing must succeed"), + [2; 32] + ); + + install_default(ByteProvider(9)).expect("global installation must succeed"); + + // The same context was constructed before the global installation. The + // global provider must now override its fallback. + assert_eq!( + hash::sha256( + fallback.crypto_provider().expect("global must resolve"), + b"x" + ) + .expect("global hashing must succeed"), + [9; 32] + ); + 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_unset.rs b/core/tests/crypto_provider_unset.rs index 34cdbf4d..f420fc93 100644 --- a/core/tests/crypto_provider_unset.rs +++ b/core/tests/crypto_provider_unset.rs @@ -18,35 +18,17 @@ //! 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; -use reqsign_core::hash; #[test] -fn unset_provider_returns_config_invalid_without_panicking() { +fn bare_context_without_a_provider_returns_config_invalid() { assert!(get_default().is_none()); - let err = hash::sha256(b"payload").expect_err("hashing without a provider must fail"); + 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()); - - let err = hash::sha1(b"payload").expect_err("hashing without a provider must fail"); - assert_eq!(err.kind(), ErrorKind::ConfigInvalid); - - let err = hash::hmac_sha256(b"key", b"payload").expect_err("HMAC without a provider must fail"); - assert_eq!(err.kind(), ErrorKind::ConfigInvalid); - - let err = - hash::base64_hmac_sha1(b"key", b"payload").expect_err("HMAC without a provider must fail"); - assert_eq!(err.kind(), ErrorKind::ConfigInvalid); -} - -#[cfg(feature = "jwt")] -#[test] -fn jwt_signing_without_a_provider_returns_config_invalid() { - #[derive(serde::Serialize)] - struct Empty {} - let err = reqsign_core::jwt::encode_rs256_pem(&Empty {}, &Empty {}, b"not used") - .expect_err("JWT signing without a provider must fail"); - assert_eq!(err.kind(), ErrorKind::ConfigInvalid); } diff --git a/core/tests/support/mod.rs b/core/tests/support/mod.rs index 0877ea93..bda533ba 100644 --- a/core/tests/support/mod.rs +++ b/core/tests/support/mod.rs @@ -50,3 +50,25 @@ impl CryptoProvider for TestProvider { 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/tests/parity.rs b/crypto/boring/tests/parity.rs index cbe138e4..86b105af 100644 --- a/crypto/boring/tests/parity.rs +++ b/crypto/boring/tests/parity.rs @@ -38,10 +38,6 @@ fn rustcrypto() -> RustCryptoProvider { RustCryptoProvider::new() } -fn install_boring() { - let _ = BoringCryptoProvider::install_default(); -} - #[test] fn hashes_and_hmacs_match_rustcrypto() { let boring = boring(); @@ -229,8 +225,7 @@ fn fill_random_produces_distinct_nonzero_bytes() { #[tokio::test] async fn aws_sigv4_end_to_end_matches_an_independent_hmac_implementation() { - install_boring(); - + 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(), @@ -244,7 +239,7 @@ async fn aws_sigv4_end_to_end_matches_an_independent_hmac_implementation() { .0; RequestSigner::new("s3", "test-region") - .sign_request(&Context::new(), &mut parts, Some(&credential), None) + .sign_request(&context, &mut parts, Some(&credential), None) .await .expect("AWS SigV4 signing must succeed"); diff --git a/crypto/rustcrypto/tests/core_hash.rs b/crypto/rustcrypto/tests/core_hash.rs index cf8cb37f..aa7754f6 100644 --- a/crypto/rustcrypto/tests/core_hash.rs +++ b/crypto/rustcrypto/tests/core_hash.rs @@ -22,75 +22,79 @@ use reqsign_core::hash::{ }; use reqsign_crypto_rustcrypto::RustCryptoProvider; -fn install_provider() { - let _ = RustCryptoProvider::install_default(); -} - #[test] fn hashes_match_published_vectors_with_expected_widths() { - install_provider(); + let provider = RustCryptoProvider::new(); assert_eq!( - hex::encode(sha1(b"abc").expect("SHA-1 must succeed")), + hex::encode(sha1(&provider, b"abc").expect("SHA-1 must succeed")), "a9993e364706816aba3e25717850c26c9cd0d89d" ); assert_eq!( - hex::encode(sha256(b"abc").expect("SHA-256 must succeed")), + hex::encode(sha256(&provider, b"abc").expect("SHA-256 must succeed")), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" ); - assert_eq!(sha1(b"abc").expect("SHA-1 must succeed").len(), 20); - assert_eq!(sha256(b"abc").expect("SHA-256 must succeed").len(), 32); + assert_eq!( + sha1(&provider, b"abc").expect("SHA-1 must succeed").len(), + 20 + ); + assert_eq!( + sha256(&provider, b"abc") + .expect("SHA-256 must succeed") + .len(), + 32 + ); assert_eq!( - hex_sha1(b"abc").expect("hex SHA-1 must succeed"), + hex_sha1(&provider, b"abc").expect("hex SHA-1 must succeed"), "a9993e364706816aba3e25717850c26c9cd0d89d" ); assert_eq!( - hex_sha256(b"abc").expect("hex SHA-256 must succeed"), + hex_sha256(&provider, b"abc").expect("hex SHA-256 must succeed"), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" ); } #[test] fn hmac_matches_rfc_vectors_with_expected_widths() { - install_provider(); + let provider = RustCryptoProvider::new(); let key = [0x0b; 20]; assert_eq!( - hex::encode(hmac_sha1(&key, b"Hi There").expect("HMAC-SHA1 must succeed")), + hex::encode(hmac_sha1(&provider, &key, b"Hi There").expect("HMAC-SHA1 must succeed")), "b617318655057264e28bc0b6fb378c8ef146be00" ); assert_eq!( - hex::encode(hmac_sha256(&key, b"Hi There").expect("HMAC-SHA256 must succeed")), + hex::encode(hmac_sha256(&provider, &key, b"Hi There").expect("HMAC-SHA256 must succeed")), "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7" ); assert_eq!( - hmac_sha1(&key, b"Hi There") + hmac_sha1(&provider, &key, b"Hi There") .expect("HMAC-SHA1 must succeed") .len(), 20 ); assert_eq!( - hmac_sha256(&key, b"Hi There") + hmac_sha256(&provider, &key, b"Hi There") .expect("HMAC-SHA256 must succeed") .len(), 32 ); assert_eq!( - hex_hmac_sha1(&key, b"Hi There").expect("hex HMAC-SHA1 must succeed"), + hex_hmac_sha1(&provider, &key, b"Hi There").expect("hex HMAC-SHA1 must succeed"), "b617318655057264e28bc0b6fb378c8ef146be00" ); assert_eq!( - hex_hmac_sha256(&key, b"Hi There").expect("hex HMAC-SHA256 must succeed"), + hex_hmac_sha256(&provider, &key, b"Hi There").expect("hex HMAC-SHA256 must succeed"), "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7" ); assert_eq!( - base64_hmac_sha1(&key, b"Hi There").expect("base64 HMAC-SHA1 must succeed"), + base64_hmac_sha1(&provider, &key, b"Hi There").expect("base64 HMAC-SHA1 must succeed"), "thcxhlUFcmTii8C2+zeMjvFGvgA=" ); assert_eq!( - base64_hmac_sha256(&key, b"Hi There").expect("base64 HMAC-SHA256 must succeed"), + base64_hmac_sha256(&provider, &key, b"Hi There").expect("base64 HMAC-SHA256 must succeed"), "sDRMYdjbOFNcqK/OrwvxK4gdwgDJgz2nJuk3bC4yz/c=" ); } diff --git a/docs/crypto-provider.md b/docs/crypto-provider.md index 1f263c60..68164bfb 100644 --- a/docs/crypto-provider.md +++ b/docs/crypto-provider.md @@ -8,11 +8,12 @@ this document are legacy debt; new work and reviews must follow it. 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 one process-wide -`reqsign_core::crypto::CryptoProvider` installed by the application at startup. +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 missing provider, or a provider that -does not implement a requested operation, returns +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: @@ -80,7 +81,42 @@ 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. -## Registration +## 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 with_crypto_fallback(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. the context fallback set with `Context::with_crypto_fallback`; +4. 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()`. Resolution reads +the current global registration on every call, so a global provider installed +after a context was created takes precedence over that context's fallback for +later operations through the same context. An explicit `with_crypto` binding +continues to win over a later global installation. Cloning a context preserves +its explicit and fallback bindings. + +`Context::new()` sets no explicit provider and no fallback. Portable core code +must either bind a provider on the context or install a global one. The facade's +`default_context()` is the exception described below: it supplies a fallback. + +## Global Registration ```rust pub fn install_default( @@ -90,8 +126,8 @@ pub fn install_default( pub fn get_default() -> Option<&'static Arc>; ``` -Installation is backed by `OnceLock>` and succeeds at -most once per process. +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 @@ -103,31 +139,30 @@ most once per process. - `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. -- Reqsign never installs a provider implicitly and never falls back to a - bundled implementation. -Applications own the choice of provider. Top-level binaries and services call -`install_default` once during startup. Integrating middleware, such as OpenDAL, -must not install a provider on behalf of its users: doing so would take away the +Applications own the process-wide choice. A top-level application may call +`install_default()` once to override facade fallbacks and any other context that +has no explicit provider. 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. -Middleware should document the requirement and let the application fail with a -clear `ConfigInvalid` error if it has not installed one. +Middleware may set a fallback on a context it owns, but it must not write the +process-wide slot. ## Failure Semantics | Condition | Error kind | Retryable | | --- | --- | --- | -| No provider installed | `ConfigInvalid` | no | +| 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 installing or changing a provider cannot -succeed. `CredentialInvalid` identifies key material supplied by the caller or -loaded from a credential source. +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 a provider is missing, an operation is unsupported, +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. @@ -140,28 +175,33 @@ pub fn base64_encode(content: &[u8]) -> String; pub fn base64_decode(content: &str) -> Result>; ``` -The digest, MAC, and encoded digest/MAC helpers now return `Result` and delegate -to the installed provider: +The digest, MAC, and encoded digest/MAC helpers require an explicitly supplied +provider and return `Result`: ```rust -pub fn sha1(content: &[u8]) -> Result<[u8; 20]>; -pub fn sha256(content: &[u8]) -> Result<[u8; 32]>; -pub fn hmac_sha1(key: &[u8], content: &[u8]) -> Result<[u8; 20]>; -pub fn hmac_sha256(key: &[u8], content: &[u8]) -> Result<[u8; 32]>; -pub fn hex_sha1(content: &[u8]) -> Result; -pub fn hex_sha256(content: &[u8]) -> Result; -pub fn hex_hmac_sha1(key: &[u8], content: &[u8]) -> Result; -pub fn hex_hmac_sha256(key: &[u8], content: &[u8]) -> Result; -pub fn base64_hmac_sha1(key: &[u8], content: &[u8]) -> Result; -pub fn base64_hmac_sha256(key: &[u8], content: &[u8]) -> Result; +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::jwt` no longer exposes an `rsa` type. The typed `encode_rs256(&H, &C, &RsaPrivateKey)` entry point is removed. The byte-based -entry point remains and delegates RSA signing to the provider: +entry point remains and requires the selected provider: ```rust pub fn encode_rs256_pem( + provider: &dyn CryptoProvider, header: &H, claims: &C, private_key_pem: &[u8], @@ -171,6 +211,10 @@ pub fn encode_rs256_pem( Enabling the `jwt` feature adds `serde` and `serde_json`; it does not add `rsa` or any other cryptographic implementation. +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` @@ -218,9 +262,19 @@ default = ["default-context", "default-crypto"] default-crypto = ["dep:reqsign-crypto-rustcrypto"] ``` -`default-crypto` re-exports `RustCryptoProvider`. It does not install it. -`default_context()` remains limited to runtime components (`FileRead`, -`HttpSend`, `Env`, `CommandExecute`) and never registers a crypto provider. +`default-crypto` re-exports `RustCryptoProvider`. When it is enabled, +`default_context()` sets that provider as a **context fallback** and never +as the process-wide provider. `default_context()` therefore works without +startup boilerplate, while a global installation performed later still takes +precedence and an explicit `with_crypto` binding still wins. + +Without `default-crypto`, `default_context()` has no fallback and resolves a +provider only from an explicit binding or a process-wide installation. +`Context::new()` never has a fallback. + +The facade's per-service `default_signer(...)` helpers use `default_context()`, +so they inherit the same behavior: usable with the default feature set, and +still governed by explicit and global overrides. Applications that select a different backend disable `default-crypto` and take the backend crate directly. Applications that use only hashing can provide @@ -228,14 +282,12 @@ their own minimal `CryptoProvider`. ## Migration -### Applications +### Applications and bare core users -Install one provider once during startup, before constructing signers and before -any credential loading that may use cryptography. For example, AWS SSO computes -its cache key with SHA-1, Google service-account exchange signs a JWT, and Azure -client certificate authentication signs a client assertion while loading a -credential. Installing later can change a configuration error into credential -absence. +Facade users can keep using `default_context()` or a per-service +`default_signer(...)` without installing anything. To select one provider for +the whole application, install it once at startup; this overrides facade +fallbacks: ```rust use reqsign::RustCryptoProvider; @@ -250,17 +302,23 @@ fn main() -> Result<(), Box> { ``` A failure from `install_default` means another component already installed a -provider. Applications that intentionally compose several libraries should -install their chosen provider before any of them are initialized. +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 and JWT helpers take the provider directly; +there is 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 -missing 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; installing before credential loading is -what makes the missing-provider `ConfigInvalid` visible. +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 @@ -269,12 +327,14 @@ what makes the missing-provider `ConfigInvalid` visible. 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 `?`. 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. +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: @@ -284,6 +344,7 @@ Notable service-specific details: - Azure client certificate authentication keeps the certificate/key PEM splitting in `azure-storage`; the thumbprint uses the provider's SHA-1 and the client assertion uses `jwt::encode_rs256_pem`. +- Azure `ServiceSharedAccessSignature::token` takes the resolved provider. - Google service-account signing encodes the provider's RSA signature as hex; client-side credential access boundary encryption uses AES-GCM through the provider and gets its nonce from `fill_random`. Malformed service-account key @@ -292,28 +353,38 @@ Notable service-specific details: ### Removed APIs - `reqsign_core::jwt::encode_rs256(&H, &C, &RsaPrivateKey)` is removed. - Use `encode_rs256_pem` with PEM bytes. -- Hash and MAC helpers return `Result`. -- `reqsign-core` no longer provides crypto implementations, so a process that - signs or hashes without installing a provider fails with `ConfigInvalid`. + Use `encode_rs256_pem(provider, ...)` with PEM bytes. +- Hash and MAC helpers take `&dyn CryptoProvider` and return `Result`. +- `reqsign-core` no longer provides crypto implementations, so a context with no + provider binding, global provider, or fallback fails with `ConfigInvalid` at + the point of use. ## Verification The repository verifies this contract with: -- Separate `reqsign-core` integration test binaries for the unset provider, - early lookup, rejected second installation, and concurrent installation. +- 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 a + context used before global installation, the global override of its fallback, + explicit priority over global, and independent providers on distinct + contexts. +- Facade tests with and without `default-crypto`, including a default signer + that signs through the fallback 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. + 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, and the standalone BoringSSL workflow. + license headers, the standalone BoringSSL workflow, and the website provider + catalog validator. diff --git a/reqsign/README.md b/reqsign/README.md index 7db6a3b2..afe63e81 100644 --- a/reqsign/README.md +++ b/reqsign/README.md @@ -43,9 +43,12 @@ reqsign = "0.20" ``` By default, this includes `default-context` (a ready-to-use context using -`reqwest` and `tokio`) and `default-crypto` (the RustCrypto provider). The -provider is re-exported but not installed automatically; applications call -`RustCryptoProvider::install_default()` once during startup. +`reqwest` and `tokio`) and `default-crypto` (the RustCrypto provider). +`default-crypto` makes `default_context()` use RustCrypto as a context +fallback, so default signers work without startup boilerplate. The fallback is +not a process-wide installation: an application can call +`RustCryptoProvider::install_default()` to override it, and an explicit +`Context::with_crypto` binding always wins. To use specific services only: @@ -62,13 +65,11 @@ The easiest way to get started is using the default signers provided for each se ```rust,ignore use anyhow::Result; -use reqsign::{RustCryptoProvider, aws}; +use reqsign::aws; #[tokio::main] async fn main() -> Result<()> { - RustCryptoProvider::install_default() - .map_err(|_| anyhow::anyhow!("a CryptoProvider is already installed"))?; - + // The facade's default context carries the RustCrypto fallback. // Create a default signer for AWS S3 in us-east-1 // This will automatically: // - Set up HTTP client and file reader @@ -102,14 +103,14 @@ use reqsign::aws::{DefaultCredentialProvider, RequestSigner}; #[tokio::main] async fn main() -> Result<()> { - RustCryptoProvider::install_default() - .map_err(|_| anyhow::anyhow!("a CryptoProvider is already installed"))?; - // Create a context with default implementations + // (including the RustCrypto fallback 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 has no fallback, 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); diff --git a/reqsign/examples/aws.rs b/reqsign/examples/aws.rs index 8fd77091..93ec32aa 100644 --- a/reqsign/examples/aws.rs +++ b/reqsign/examples/aws.rs @@ -19,8 +19,6 @@ use anyhow::Result; #[tokio::main] async fn main() -> Result<()> { - reqsign::RustCryptoProvider::install_default() - .expect("no CryptoProvider must be installed before this example"); // ANCHOR: quickstart use reqsign::aws; // Create a default signer for S3 in us-east-1 diff --git a/reqsign/examples/azure.rs b/reqsign/examples/azure.rs index 7c75f3a1..30555ba5 100644 --- a/reqsign/examples/azure.rs +++ b/reqsign/examples/azure.rs @@ -19,8 +19,6 @@ use anyhow::Result; #[tokio::main] async fn main() -> Result<()> { - reqsign::RustCryptoProvider::install_default() - .expect("no CryptoProvider must be installed before this example"); // ANCHOR: quickstart use reqsign::azure; // Create a default signer for Azure Storage diff --git a/reqsign/examples/custom_context.rs b/reqsign/examples/custom_context.rs index f7b77e1f..2bd73257 100644 --- a/reqsign/examples/custom_context.rs +++ b/reqsign/examples/custom_context.rs @@ -22,9 +22,8 @@ use reqsign_file_read_tokio::TokioFileRead; use reqsign_http_send_reqwest::ReqwestHttpSend; fn main() { - reqsign::RustCryptoProvider::install_default() - .expect("no CryptoProvider must be installed before this example"); 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 6aa4771b..7856833a 100644 --- a/reqsign/examples/custom_http.rs +++ b/reqsign/examples/custom_http.rs @@ -29,8 +29,8 @@ impl HttpSend for MyHttpSend { } fn main() { - reqsign::RustCryptoProvider::install_default() - .expect("no CryptoProvider must be installed before this example"); // 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/examples/google.rs b/reqsign/examples/google.rs index 714faebb..64d7341a 100644 --- a/reqsign/examples/google.rs +++ b/reqsign/examples/google.rs @@ -19,8 +19,6 @@ use anyhow::Result; #[tokio::main] async fn main() -> Result<()> { - reqsign::RustCryptoProvider::install_default() - .expect("no CryptoProvider must be installed before this example"); // ANCHOR: quickstart use reqsign::google; // Create a default signer for Google Cloud Storage diff --git a/reqsign/examples/presign.rs b/reqsign/examples/presign.rs index ae3e94bd..0a3973b4 100644 --- a/reqsign/examples/presign.rs +++ b/reqsign/examples/presign.rs @@ -20,8 +20,6 @@ use std::time::Duration; #[tokio::main] async fn main() -> anyhow::Result<()> { - reqsign::RustCryptoProvider::install_default() - .expect("no CryptoProvider must be installed before this example"); let signer = aws::default_signer("s3", "us-east-1"); let mut req = http::Request::get("https://s3.amazonaws.com/my-bucket/report.csv") .body(())? diff --git a/reqsign/examples/s3_express_grant.rs b/reqsign/examples/s3_express_grant.rs index 3e83e143..e714b42f 100644 --- a/reqsign/examples/s3_express_grant.rs +++ b/reqsign/examples/s3_express_grant.rs @@ -23,8 +23,6 @@ use reqsign::{Granter, default_context}; #[tokio::main] async fn main() -> anyhow::Result<()> { - reqsign::RustCryptoProvider::install_default() - .expect("no CryptoProvider must be installed before this example"); let config = S3ExpressSessionConfig::from_bucket("my-bucket--usw2-az1--x-s3", "us-west-2")?; let grant = S3ExpressSessionGrant::new(S3ExpressSessionMode::ReadOnly); let granter = Granter::new( diff --git a/reqsign/examples/s3_express_sign.rs b/reqsign/examples/s3_express_sign.rs index 6c484b33..8e0d68fe 100644 --- a/reqsign/examples/s3_express_sign.rs +++ b/reqsign/examples/s3_express_sign.rs @@ -22,8 +22,6 @@ use reqsign::aws::{ #[tokio::main] async fn main() -> anyhow::Result<()> { - reqsign::RustCryptoProvider::install_default() - .expect("no CryptoProvider must be installed before this example"); let provider = S3ExpressSessionProvider::new( "my-bucket--usw2-az1--x-s3", DefaultCredentialProvider::new(), diff --git a/reqsign/examples/static_credentials.rs b/reqsign/examples/static_credentials.rs index b4197f00..3e6c9aa3 100644 --- a/reqsign/examples/static_credentials.rs +++ b/reqsign/examples/static_credentials.rs @@ -17,8 +17,6 @@ #[tokio::main] async fn main() -> anyhow::Result<()> { - reqsign::RustCryptoProvider::install_default() - .expect("no CryptoProvider must be installed before this example"); // ANCHOR: static use reqsign::aws::{self, StaticCredentialProvider}; let signer = aws::default_signer("s3", "us-east-1").with_credential_provider( diff --git a/reqsign/src/context.rs b/reqsign/src/context.rs index 25c7b027..660c319e 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,11 +33,14 @@ use reqsign_http_send_reqwest::ReqwestHttpSend; /// - `TokioFileRead` for file reading (non-WASM only) /// - `ReqwestHttpSend` for HTTP requests /// - `OsEnv` for environment variable access +/// - `RustCryptoProvider` as a context fallback when `default-crypto` is enabled /// -/// This function does not install a crypto provider. Applications must call -/// `reqsign::RustCryptoProvider::install_default()` once during startup (or -/// install another provider) before hashing or signing. Integrating middleware -/// must leave that choice to the application. +/// The fallback makes `reqsign` examples and default signers usable without +/// installation boilerplate. It does not touch the process-wide registration: +/// a provider installed later with `RustCryptoProvider::install_default()` (or +/// another global provider) takes precedence for this context, and an explicit +/// `Context::with_crypto` binding still wins. Integrating middleware must leave +/// provider installation to the application. /// /// # Example /// @@ -71,18 +77,19 @@ 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 = ctx.with_crypto_fallback(RustCryptoProvider::new()); + + ctx } diff --git a/reqsign/tests/crypto.rs b/reqsign/tests/crypto.rs index c5462193..21227bcf 100644 --- a/reqsign/tests/crypto.rs +++ b/reqsign/tests/crypto.rs @@ -15,14 +15,87 @@ // specific language governing permissions and limitations // under the License. -//! The facade exposes a provider but must never install one implicitly. +//! The facade supplies a fallback but never installs a global provider. #[cfg(feature = "default-context")] #[test] -fn default_context_does_not_install_a_crypto_provider() { - let _ = reqsign::default_context(); - assert!( - reqsign::crypto::get_default().is_none(), - "default_context must leave provider installation to the application" +fn default_context_uses_fallback_without_installing_global_and_global_wins_later() { + 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]) + } + } + + assert!(get_default().is_none()); + let ctx = reqsign::default_context(); + assert!(get_default().is_none(), "default_context must not install"); + assert_eq!( + reqsign::hash::base64_encode( + &hash::sha256( + ctx.crypto_provider().expect("fallback must resolve"), + b"abc" + ) + .expect("fallback hashing must succeed") + ), + "ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0=" + ); + + let explicit = Context::new().with_crypto(TestProvider(2)); + install_default(TestProvider(9)).expect("global installation must succeed"); + + assert_eq!( + hash::sha256(ctx.crypto_provider().expect("global must resolve"), b"x") + .expect("global hashing must succeed"), + [9; 32], + "a provider installed after default_context() must override its fallback" + ); + 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..a27a0a22 --- /dev/null +++ b/reqsign/tests/crypto_without_default_crypto.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. + +//! This binary is built with `--no-default-features --features default-context`. + +#![cfg(all(feature = "default-context", not(feature = "default-crypto")))] + +use reqsign::ErrorKind; + +#[test] +fn default_context_without_default_crypto_has_no_fallback() { + assert!(reqsign::crypto::get_default().is_none()); + let err = reqsign::default_context() + .crypto_provider() + .expect_err("default-context alone must not resolve a provider"); + assert_eq!(err.kind(), ErrorKind::ConfigInvalid); +} diff --git a/reqsign/tests/default_signer.rs b/reqsign/tests/default_signer.rs new file mode 100644 index 00000000..5b88af24 --- /dev/null +++ b/reqsign/tests/default_signer.rs @@ -0,0 +1,84 @@ +// 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; +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")) + } +} + +#[tokio::test] +async fn default_signer_signs_with_the_context_fallback() { + let signer = default_signer("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 facade crypto fallback"); + 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("s3", "test-region") + .with_context(context) + .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 b90fbede..80a1d5c2 100644 --- a/services/aliyun-oss/Cargo.toml +++ b/services/aliyun-oss/Cargo.toml @@ -38,7 +38,6 @@ serde = { workspace = true } serde_json = { workspace = true } [dev-dependencies] -ctor = "1" reqsign-crypto-rustcrypto = { workspace = true } bytes = { workspace = true } dotenvy = { workspace = true } diff --git a/services/aliyun-oss/README.md b/services/aliyun-oss/README.md index 9251232c..f814489d 100644 --- a/services/aliyun-oss/README.md +++ b/services/aliyun-oss/README.md @@ -6,13 +6,15 @@ 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 requires a process-wide `CryptoProvider`. Install one at startup -> before constructing signers; see +> 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()` fallback. A bare `Context::new()` has no fallback. 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, @@ -26,7 +28,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 1f448ac4..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,6 +168,7 @@ 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(), )?; @@ -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,8 +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) @@ -669,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")) @@ -695,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")); @@ -722,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")); @@ -738,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 fa914851..cc8b0fb1 100644 --- a/services/aliyun-oss/src/lib.rs +++ b/services/aliyun-oss/src/lib.rs @@ -259,10 +259,7 @@ pub use sign_request::{RequestSigner, SigningVersion}; mod provide_credential; pub use provide_credential::*; -// Unit tests exercise signing paths, so install the test provider before -// any test in this binary runs. #[cfg(test)] -#[ctor::ctor(unsafe)] -fn install_test_crypto_provider() { - let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +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 9e4d4cd5..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,6 +454,7 @@ 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(), )?; @@ -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 40065e61..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, ) -> 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 index 3b0c8c71..864b1164 100644 --- a/services/aliyun-oss/tests/common/mod.rs +++ b/services/aliyun-oss/tests/common/mod.rs @@ -15,10 +15,8 @@ // specific language governing permissions and limitations // under the License. -// Every integration test binary installs the RustCrypto provider once before -// its tests run. Installation is process-wide, so concurrent or repeated -// initialization is intentionally ignored. -#[ctor::ctor(unsafe)] -fn install_test_crypto_provider() { - let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +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 60d37f51..6d66d37d 100644 --- a/services/aliyun-oss/tests/credential_chain.rs +++ b/services/aliyun-oss/tests/credential_chain.rs @@ -54,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); @@ -98,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); @@ -129,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); @@ -141,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 a93c0ce0..cc89839f 100644 --- a/services/aliyun-oss/tests/main.rs +++ b/services/aliyun-oss/tests/main.rs @@ -43,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()).expect("SHA-256 must succeed") + &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 9edee4d6..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,9 +57,10 @@ mod tests { #[test] fn empty_string_sha256_matches_computed_digest() { + let provider = reqsign_crypto_rustcrypto::RustCryptoProvider::new(); assert_eq!( EMPTY_STRING_SHA256, - hex_sha256(b"").expect("SHA-256 must succeed") + hex_sha256(&provider, b"").expect("SHA-256 must succeed") ); assert_eq!( EMPTY_STRING_SHA256, @@ -62,11 +68,3 @@ mod tests { ); } } - -// Unit tests exercise signing paths, so install the test provider before -// any test in this binary runs. -#[cfg(test)] -#[ctor::ctor(unsafe)] -fn install_test_crypto_provider() { - let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); -} 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 0e5b5252..cbdf9662 100644 --- a/services/aws-core/src/provide_credential/default.rs +++ b/services/aws-core/src/provide_credential/default.rs @@ -339,7 +339,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); @@ -367,7 +367,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); @@ -394,7 +394,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); @@ -433,7 +433,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); @@ -461,7 +461,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); @@ -486,7 +486,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); @@ -524,7 +524,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); @@ -565,7 +565,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); @@ -603,7 +603,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, @@ -640,7 +640,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()), @@ -682,7 +682,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 { @@ -733,7 +733,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) @@ -769,7 +769,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) @@ -804,7 +804,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 53fac75b..f0974997 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/sso/session.rs b/services/aws-core/src/provide_credential/sso/session.rs index dd03712c..47f6f859 100644 --- a/services/aws-core/src/provide_credential/sso/session.rs +++ b/services/aws-core/src/provide_credential/sso/session.rs @@ -43,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(), diff --git a/services/aws-core/src/provide_credential/sso/tests.rs b/services/aws-core/src/provide_credential/sso/tests.rs index 868f9a88..6dbba4e2 100644 --- a/services/aws-core/src/provide_credential/sso/tests.rs +++ b/services/aws-core/src/provide_credential/sso/tests.rs @@ -53,10 +53,11 @@ 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()).expect("SSO cache key hashing must succeed") + hex_sha1(&provider, name.as_bytes()).expect("SSO cache key hashing must succeed") ), value.to_string(), ); @@ -137,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/tests/common/mod.rs b/services/aws-core/tests/common/mod.rs index 3b0c8c71..864b1164 100644 --- a/services/aws-core/tests/common/mod.rs +++ b/services/aws-core/tests/common/mod.rs @@ -15,10 +15,8 @@ // specific language governing permissions and limitations // under the License. -// Every integration test binary installs the RustCrypto provider once before -// its tests run. Installation is process-wide, so concurrent or repeated -// initialization is intentionally ignored. -#[ctor::ctor(unsafe)] -fn install_test_crypto_provider() { - let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +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 47c771b4..ba1b6598 100644 --- a/services/aws-core/tests/shared_config.rs +++ b/services/aws-core/tests/shared_config.rs @@ -54,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 f79ababb..b9070b79 100644 --- a/services/aws-v4/Cargo.toml +++ b/services/aws-v4/Cargo.toml @@ -40,7 +40,6 @@ reqsign-core = { workspace = true } serde = { workspace = true } [dev-dependencies] -ctor = "1" reqsign-crypto-rustcrypto = { workspace = true } anyhow = { workspace = true } aws-credential-types = "1.1.8" diff --git a/services/aws-v4/README.md b/services/aws-v4/README.md index e9352b90..86e57b8d 100644 --- a/services/aws-v4/README.md +++ b/services/aws-v4/README.md @@ -2,13 +2,15 @@ AWS SigV4 signing implementation for `reqsign`. -> Signing requires a process-wide `CryptoProvider`. Install one at startup -> before constructing signers; see +> 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()` fallback. A bare `Context::new()` has no fallback. 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; @@ -16,7 +18,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); @@ -184,6 +186,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::{ @@ -201,7 +204,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 cf5bcde1..c26a2d2b 100644 --- a/services/aws-v4/benches/aws.rs +++ b/services/aws-v4/benches/aws.rs @@ -45,9 +45,6 @@ static RUNTIME: LazyLock = LazyLock::new(|| { }); pub fn bench(c: &mut Criterion) { - reqsign_crypto_rustcrypto::RustCryptoProvider::install_default() - .expect("no CryptoProvider must be installed before this benchmark"); - let mut group = c.benchmark_group("aws_v4"); group.bench_function("reqsign", |b| { @@ -59,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 e5b3af43..8f42c758 100644 --- a/services/aws-v4/examples/dynamodb_sign.rs +++ b/services/aws-v4/examples/dynamodb_sign.rs @@ -25,17 +25,17 @@ use serde_json::json; #[tokio::main] async fn main() -> Result<()> { - reqsign_crypto_rustcrypto::RustCryptoProvider::install_default() - .expect("no CryptoProvider must be installed before this example"); - // Initialize logging let _ = env_logger::builder().is_test(true).try_init(); // 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); @@ -72,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(); @@ -107,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(); @@ -143,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 6b5baeca..4283aa4a 100644 --- a/services/aws-v4/examples/s3_express_sign.rs +++ b/services/aws-v4/examples/s3_express_sign.rs @@ -24,9 +24,6 @@ use reqwest::Client; #[tokio::main] async fn main() -> Result<()> { - reqsign_crypto_rustcrypto::RustCryptoProvider::install_default() - .expect("no CryptoProvider must be installed before this example"); - // Initialize logging for debugging let _ = env_logger::builder().is_test(true).try_init(); @@ -35,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 af68ccf8..49de7473 100644 --- a/services/aws-v4/examples/s3_sign.rs +++ b/services/aws-v4/examples/s3_sign.rs @@ -24,9 +24,6 @@ use reqwest::Client; #[tokio::main] async fn main() -> Result<()> { - reqsign_crypto_rustcrypto::RustCryptoProvider::install_default() - .expect("no CryptoProvider must be installed before this example"); - // Initialize logging for debugging let _ = env_logger::builder().is_test(true).try_init(); @@ -35,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 043ebdc4..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).expect("SHA-256 must succeed") + 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 0d9ca846..0e29c43c 100644 --- a/services/aws-v4/src/lib.rs +++ b/services/aws-v4/src/lib.rs @@ -192,10 +192,7 @@ pub use reqsign_aws_core::{ProcessCredentialProvider, SSOCredentialProvider}; pub const EMPTY_STRING_SHA256: &str = reqsign_aws_core::EMPTY_STRING_SHA256; -// Unit tests exercise signing paths, so install the test provider before -// any test in this binary runs. #[cfg(test)] -#[ctor::ctor(unsafe)] -fn install_test_crypto_provider() { - let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +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 2096e540..26083be4 100644 --- a/services/aws-v4/src/sign_request.rs +++ b/services/aws-v4/src/sign_request.rs @@ -57,13 +57,13 @@ const CREDENTIAL_OPERATION_HEADROOM: Duration = Duration::from_secs(10); /// ``` /// use reqsign_aws_v4::EMPTY_STRING_SHA256; /// use reqsign_core::hash::hex_sha256; -/// # let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); /// +/// 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).expect("SHA-256 must succeed") +/// hex_sha256(&provider, body).expect("SHA-256 must succeed") /// }; /// /// let request = http::Request::put("https://s3.amazonaws.com/mybucket/hello.txt") @@ -203,7 +203,7 @@ impl SignRequest for RequestSigner { async fn sign_request( &self, - _: &Context, + ctx: &Context, req: &mut Parts, credential: Option<&Self::Credential>, expires_in: Option, @@ -211,6 +211,7 @@ impl SignRequest for RequestSigner { let Some(cred) = 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); @@ -249,7 +250,7 @@ impl SignRequest for RequestSigner { &canonical_query, self.percent_encoding_mode, )?; - let encoded_req = hex_sha256(creq.as_bytes())?; + let encoded_req = hex_sha256(crypto, creq.as_bytes())?; // Scope: "20220313///aws4_request" let scope = format!( @@ -284,9 +285,14 @@ impl SignRequest for RequestSigner { }; debug!("calculated string to sign: {string_to_sign}"); - let signing_key = - generate_signing_key(&cred.secret_access_key, now, &self.region, &self.service)?; - let signature = hex_hmac_sha256(&signing_key, string_to_sign.as_bytes())?; + let signing_key = generate_signing_key( + crypto, + &cred.secret_access_key, + now, + &self.region, + &self.service, + )?; + let signature = hex_hmac_sha256(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)?; @@ -390,6 +396,7 @@ fn authentication_query( } fn generate_signing_key( + provider: &dyn reqsign_core::crypto::CryptoProvider, secret: &str, time: Timestamp, region: &str, @@ -398,13 +405,13 @@ fn generate_signing_key( // Sign secret let secret = format!("AWS4{secret}"); // Sign date - let sign_date = hmac_sha256(secret.as_bytes(), time.format_date().as_bytes())?; + let sign_date = hmac_sha256(provider, secret.as_bytes(), time.format_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(), service.as_bytes())?; + let sign_service = hmac_sha256(provider, sign_region.as_slice(), service.as_bytes())?; // Sign request - Ok(hmac_sha256(sign_service.as_slice(), "aws4_request".as_bytes())?.to_vec()) + Ok(hmac_sha256(provider, sign_service.as_slice(), "aws4_request".as_bytes())?.to_vec()) } #[cfg(test)] @@ -579,7 +586,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( @@ -608,7 +620,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); @@ -664,7 +681,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, @@ -684,7 +701,7 @@ mod tests { .with_standard_session_token() .with_time(now) .sign_request( - &Context::new(), + &crate::test_context(), &mut iam_parts, Some(&credential), expires_in, @@ -756,7 +773,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, @@ -780,7 +797,7 @@ mod tests { .with_standard_session_token() .with_time(now) .sign_request( - &Context::new(), + &crate::test_context(), &mut iam_parts, Some(&credential), expires_in, @@ -831,7 +848,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 { @@ -874,7 +896,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"); @@ -913,7 +935,7 @@ mod tests { calls: calls.clone(), }; let signer = Signer::new( - Context::new(), + crate::test_context(), provider, RequestSigner::new("s3", "test").with_time(now), ); @@ -958,7 +980,7 @@ mod tests { calls: calls.clone(), }; let signer = Signer::new( - Context::new(), + crate::test_context(), provider, RequestSigner::new("s3", "test").with_time(now), ); @@ -1116,7 +1138,8 @@ mod tests { HeaderValue::from_str(&content.len().to_string()).expect("must be valid"), ); - let body = hex_sha256(content.as_bytes()).expect("SHA-256 must succeed"); + 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"), @@ -1261,7 +1284,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)), @@ -1465,7 +1488,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)), @@ -1522,7 +1545,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 "); @@ -1530,7 +1558,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)), @@ -1630,7 +1658,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"); @@ -1708,7 +1736,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"); @@ -1788,7 +1816,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") @@ -1869,7 +1897,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 index 3b0c8c71..864b1164 100644 --- a/services/aws-v4/tests/common/mod.rs +++ b/services/aws-v4/tests/common/mod.rs @@ -15,10 +15,8 @@ // specific language governing permissions and limitations // under the License. -// Every integration test binary installs the RustCrypto provider once before -// its tests run. Installation is process-wide, so concurrent or repeated -// initialization is intentionally ignored. -#[ctor::ctor(unsafe)] -fn install_test_crypto_provider() { - let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +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/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/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 bd5ee8b5..e460f17a 100644 --- a/services/aws-v4a/Cargo.toml +++ b/services/aws-v4a/Cargo.toml @@ -38,7 +38,6 @@ zeroize = { workspace = true } anyhow = { workspace = true } aws-credential-types = "1.1.8" aws-sigv4 = { version = "1.2.0", features = ["sigv4a"] } -ctor = "1" form_urlencoded = { workspace = true } p256 = { workspace = true } pretty_assertions = { workspace = true } diff --git a/services/aws-v4a/README.md b/services/aws-v4a/README.md index 5e2fd6cc..cc71d65b 100644 --- a/services/aws-v4a/README.md +++ b/services/aws-v4a/README.md @@ -7,8 +7,9 @@ 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 requires a process-wide `CryptoProvider`. Install one at startup -> before constructing signers; see +> 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()` fallback. A bare `Context::new()` has no fallback. See > [CryptoProvider](https://github.com/apache/reqsign/blob/main/docs/crypto-provider.md). ```rust diff --git a/services/aws-v4a/src/lib.rs b/services/aws-v4a/src/lib.rs index c95aef8a..e23e52f7 100644 --- a/services/aws-v4a/src/lib.rs +++ b/services/aws-v4a/src/lib.rs @@ -35,10 +35,7 @@ pub use reqsign_aws_core::{IMDSv2RegionProvider, Profile, SharedConfig}; pub use reqsign_aws_core::{ProcessCredentialProvider, SSOCredentialProvider}; pub use sign_request::RequestSigner; -// Unit tests exercise signing paths, so install the test provider before -// any test in this binary runs. #[cfg(test)] -#[ctor::ctor(unsafe)] -fn install_test_crypto_provider() { - let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +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 e9d84cc7..da4f0219 100644 --- a/services/aws-v4a/src/sign_request.rs +++ b/services/aws-v4a/src/sign_request.rs @@ -123,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, @@ -131,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); @@ -171,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}"); @@ -179,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)?; @@ -270,17 +274,17 @@ fn string_to_sign(now: Timestamp, scope: &str, encoded_request: &str) -> Result< Ok(output) } -fn calculate_signature(signing_key: &[u8; 32], string_to_sign: &[u8]) -> Result { - let provider = crypto::get_default().ok_or_else(|| { - Error::config_invalid( - "no CryptoProvider is installed; install one during application startup", - ) - })?; +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( + provider: &dyn crypto::CryptoProvider, access_key_id: &str, secret_access_key: &str, ) -> Result> { @@ -297,7 +301,11 @@ fn generate_signing_key( 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; } @@ -419,7 +427,8 @@ mod tests { #[test] fn signing_key_matches_aws_public_key_vector() -> AnyResult<()> { - let scalar = 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); @@ -433,7 +442,7 @@ mod tests { "865ed22a7eadc9c5cb9d2cbaca1b3699139fedc5043dc6661864218330c8e518" ); - let signature = calculate_signature(&scalar, 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"); @@ -451,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"); @@ -476,7 +490,7 @@ mod tests { .0; signer() .sign_request( - &Context::new(), + &crate::test_context(), &mut parts, Some(&credential()), Some(Duration::from_secs(3600)), @@ -518,7 +532,11 @@ mod tests { }; format!( "AWS4-ECDSA-P256-SHA256\n20150830T123600Z\n20150830/service/aws4_request\n{}", - hex_sha256(canonical_request.as_bytes()).expect("SHA-256 must succeed"), + hex_sha256( + &reqsign_crypto_rustcrypto::RustCryptoProvider::new(), + canonical_request.as_bytes(), + ) + .expect("SHA-256 must succeed"), ) } @@ -540,7 +558,8 @@ mod tests { let signature_bytes = hex::decode(signature)?; let signature = DerSignature::try_from(signature_bytes.as_slice()) .expect("signature must use DER encoding"); - let scalar = 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!( @@ -639,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)); @@ -687,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); @@ -718,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); @@ -785,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() { @@ -822,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 c41b386d..4d54e9e1 100644 --- a/services/azure-storage/Cargo.toml +++ b/services/azure-storage/Cargo.toml @@ -44,7 +44,6 @@ pem = { workspace = true } reqsign-core = { workspace = true, features = ["jwt"] } [dev-dependencies] -ctor = "1" reqsign-crypto-rustcrypto = { workspace = true } asyncband = { workspace = true, features = ["semaphore"] } env_logger = { workspace = true } diff --git a/services/azure-storage/README.md b/services/azure-storage/README.md index 18c031a2..cde28ec1 100644 --- a/services/azure-storage/README.md +++ b/services/azure-storage/README.md @@ -5,13 +5,15 @@ 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 requires a process-wide `CryptoProvider`. Install one at startup -> before constructing signers; see +> 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()` fallback. A bare `Context::new()` has no fallback. 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}; @@ -20,7 +22,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()); @@ -115,6 +117,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::{ @@ -130,7 +133,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 7301b8f5..ecc96be3 100644 --- a/services/azure-storage/src/lib.rs +++ b/services/azure-storage/src/lib.rs @@ -193,10 +193,7 @@ pub use sign_request::RequestSigner; mod provide_credential; pub use provide_credential::*; -// Unit tests exercise signing paths, so install the test provider before -// any test in this binary runs. #[cfg(test)] -#[ctor::ctor(unsafe)] -fn install_test_crypto_provider() { - let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +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 c45809b8..08054211 100644 --- a/services/azure-storage/src/provide_credential/client_certificate.rs +++ b/services/azure-storage/src/provide_credential/client_certificate.rs @@ -24,6 +24,7 @@ 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, hash}; use serde::Serialize; @@ -142,13 +143,18 @@ impl ClientCertificateCredentialProvider { /// Calculate certificate thumbprint (x5t) /// Azure AD expects SHA1 thumbprint for x5t field - fn calculate_thumbprint(&self, cert_der: &[u8]) -> Result { - Ok(URL_SAFE_NO_PAD.encode(hash::sha1(cert_der)?)) + 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], @@ -173,10 +179,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_pem(&header, &claims, private_key_pem) + reqsign_core::jwt::encode_rs256_pem(provider, &header, &claims, private_key_pem) } /// Exchange client assertion for access token @@ -277,12 +283,19 @@ impl ProvideCredential for ClientCertificateCredentialProvider { _ => return Ok(None), }; + let provider = ctx.crypto_provider()?; + // Load certificate and private key 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_pem)?; + 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 @@ -308,8 +321,9 @@ mod tests { // Test certificate DER (simplified example) let cert_der = b"test certificate"; let provider = ClientCertificateCredentialProvider::new(); + let crypto = reqsign_crypto_rustcrypto::RustCryptoProvider::new(); let thumbprint = provider - .calculate_thumbprint(cert_der) + .calculate_thumbprint(&crypto, cert_der) .expect("thumbprint calculation must succeed"); // Should produce a valid base64url encoded hash 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 49dab550..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,12 +702,17 @@ impl ServiceSharedAccessSignature { .join("\n") } - fn signature_with_decoded_key(&self, decoded_key: &[u8]) -> reqsign_core::Result { - 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, + provider: &dyn CryptoProvider, decoded_key: &[u8], ) -> reqsign_core::Result> { let mut elements: Vec<(String, String)> = vec![ @@ -731,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)?, )); 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)?; - self.token_with_decoded_key(&decoded_key) + self.token_with_decoded_key(provider, &decoded_key) } } @@ -890,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, @@ -949,7 +959,7 @@ impl GrantCredential for ServiceSasGranter { } let pairs = signer - .token_with_decoded_key(&decoded_key) + .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(); @@ -1035,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}")) @@ -1202,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)), ) @@ -1217,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(), ); @@ -1261,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); @@ -1296,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 ); } @@ -1315,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)), ) @@ -1349,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); @@ -1384,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); @@ -1397,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(), @@ -1411,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(), @@ -1422,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(), @@ -1445,7 +1481,7 @@ mod tests { ) .with_time(now); let output = Granter::new( - Context::new(), + crate::test_context(), StaticCredentialProvider::new_shared_key("account", &key), operation, ) @@ -1456,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(), ); @@ -1490,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)), @@ -1537,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 c64f06c9..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,7 +408,7 @@ impl SignRequest for RequestSigner { signer = signer.with_version(version); } - let signer_token = signer.token().map_err(|e| { + let signer_token = signer.token(provider).map_err(|e| { reqsign_core::Error::new( e.kind(), "failed to generate user delegation SAS token", @@ -449,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(), @@ -470,7 +475,7 @@ impl SignRequest for RequestSigner { signer = signer.with_version(version); } - let signer_token = signer.token().map_err(|e| { + let signer_token = signer.token(provider).map_err(|e| { reqsign_core::Error::new( e.kind(), "failed to generate service SAS token", @@ -480,13 +485,17 @@ impl SignRequest for RequestSigner { 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 = @@ -805,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; @@ -868,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); @@ -901,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); @@ -946,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); @@ -1092,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 d026aba2..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,10 +466,10 @@ impl UserDelegationSharedAccessSignature { let string_to_sign = fields.join("\n"); let decoded_key = hash::base64_decode(&self.key.value)?; - 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()), @@ -504,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 06b3a29f..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,13 +671,14 @@ impl UserDelegationSasGranter { fn cache_key( &self, + provider: &dyn CryptoProvider, endpoint: &ParsedEndpoint, bearer_token: &str, ) -> 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, }) } @@ -720,20 +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 Ok(cache_key) = self.cache_key(&endpoint, token) else { - return now + BEARER_TOKEN_OPERATION_HEADROOM; - }; - 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( @@ -748,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()?; @@ -759,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) @@ -830,7 +824,7 @@ impl GrantCredential for UserDelegationSasGranter { signer = signer.with_ip(ip); } - let pairs = signer.token().map_err(|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); @@ -1093,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( @@ -1161,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), @@ -1219,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), @@ -1238,7 +1232,7 @@ mod tests { let token = token.to_string(); let signer = Signer::new( - Context::new(), + crate::test_context(), FixedCredentialProvider(output), RequestSigner::new(), ); @@ -1267,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), @@ -1294,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), @@ -1349,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), @@ -1399,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", @@ -1469,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", @@ -1536,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", @@ -1590,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", @@ -1645,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), @@ -1672,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( @@ -1741,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", ".", ".."] { @@ -1818,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 index 3b0c8c71..864b1164 100644 --- a/services/azure-storage/tests/common/mod.rs +++ b/services/azure-storage/tests/common/mod.rs @@ -15,10 +15,8 @@ // specific language governing permissions and limitations // under the License. -// Every integration test binary installs the RustCrypto provider once before -// its tests run. Installation is process-wide, so concurrent or repeated -// initialization is intentionally ignored. -#[ctor::ctor(unsafe)] -fn install_test_crypto_provider() { - let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +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/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 235c7f92..f7fef8a9 100644 --- a/services/google/Cargo.toml +++ b/services/google/Cargo.toml @@ -60,7 +60,6 @@ reqsign-core = { workspace = true, features = ["jwt"] } [dev-dependencies] aes-gcm = { workspace = true, features = ["zeroize"] } asyncband = { workspace = true, features = ["semaphore"] } -ctor = "1" dotenvy = { workspace = true } env_logger = { workspace = true } reqsign-crypto-rustcrypto = { workspace = true } diff --git a/services/google/README.md b/services/google/README.md index 7ff12f40..1d49f218 100644 --- a/services/google/README.md +++ b/services/google/README.md @@ -7,19 +7,21 @@ 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 requires a process-wide `CryptoProvider`. Install one at startup -> before constructing signers; see +> 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()` fallback. A bare `Context::new()` has no fallback. 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 61a779cd..2b3ff4ee 100644 --- a/services/google/src/credential_access_boundary/client_side.rs +++ b/services/google/src/credential_access_boundary/client_side.rs @@ -276,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, @@ -565,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", @@ -573,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, }) } @@ -581,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 @@ -642,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 @@ -652,11 +661,6 @@ impl ClientSideCredentialAccessBoundaryGranter { .ok_or_else(|| Error::unexpected("test CAB nonce queue is empty")); } - let provider = crypto::get_default().ok_or_else(|| { - Error::config_invalid( - "no CryptoProvider is installed; install one during application startup", - ) - })?; let mut nonce = [0u8; AES_GCM_NONCE_BYTES]; provider.fill_random(&mut nonce)?; Ok(nonce) @@ -699,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(), @@ -833,12 +840,12 @@ impl TinkAesGcmKey { }) } - fn encrypt(&self, restrictions: &[u8], nonce: &[u8; AES_GCM_NONCE_BYTES]) -> Result> { - let provider = crypto::get_default().ok_or_else(|| { - Error::config_invalid( - "no CryptoProvider is installed; install one during application startup", - ) - })?; + 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 = @@ -1386,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), @@ -1421,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"); @@ -1475,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, ) @@ -1590,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), )])), @@ -1636,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, ) @@ -1651,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 { @@ -1730,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()), )])), @@ -1766,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), )])), @@ -1786,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, @@ -1802,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), )])), @@ -1838,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); @@ -1910,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)); } @@ -1937,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), )])), @@ -1954,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), )])), @@ -1974,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) @@ -2014,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) @@ -2053,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 @@ -2084,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 { @@ -2140,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)); @@ -2175,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({ @@ -2227,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 { @@ -2273,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({ @@ -2320,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 = { @@ -2368,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 @@ -2399,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]]), @@ -2425,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), )])), @@ -2436,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(()) @@ -2463,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"}"#, )])), @@ -2479,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, ) @@ -2508,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/lib.rs b/services/google/src/lib.rs index c5919110..ba1405ea 100644 --- a/services/google/src/lib.rs +++ b/services/google/src/lib.rs @@ -55,10 +55,7 @@ pub use provide_credential::{ TokenCredentialProvider, VmMetadataCredentialProvider, WellKnownCredentialProvider, }; -// Unit tests exercise signing paths, so install the test provider before -// any test in this binary runs. #[cfg(test)] -#[ctor::ctor(unsafe)] -fn install_test_crypto_provider() { - let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +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..e0d187e6 100644 --- a/services/google/src/provide_credential/service_account_token.rs +++ b/services/google/src/provide_credential/service_account_token.rs @@ -270,7 +270,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 +298,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( + provider, &JwtHeader::rs256(), &Claims::new(&service_account.client_email, scope, token_uri, now)?, service_account.private_key.as_bytes(), @@ -508,7 +516,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 +561,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 +570,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 +614,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 +632,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 +661,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 +724,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 +751,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 b784a31a..0fbecb1d 100644 --- a/services/google/src/sign_request.rs +++ b/services/google/src/sign_request.rs @@ -27,8 +27,8 @@ use std::sync::{Arc, Mutex as SyncMutex, Weak}; use std::time::Duration; use reqsign_core::{ - Context, Error as ReqsignError, Result, SignRequest, SigningCredential, SigningRequest, crypto, - hash::hex_sha256, time::*, + Context, Result, SignRequest, SigningCredential, SigningRequest, crypto, hash::hex_sha256, + time::*, }; use crate::constants::{ @@ -297,7 +297,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(), }; @@ -338,8 +338,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( + provider, &JwtHeader::rs256(), &Claims::new(&sa.client_email, scope), sa.private_key.as_bytes(), @@ -407,6 +409,7 @@ impl RequestSigner { fn build_string_to_sign( &self, + provider: &dyn crypto::CryptoProvider, req: &mut SigningRequest, client_email: &str, now: Timestamp, @@ -425,7 +428,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", @@ -451,12 +454,11 @@ impl RequestSigner { Ok((string_to_sign, authentication_query)) } - fn sign_with_service_account(private_key_pem: &str, string_to_sign: &str) -> Result { - let provider = crypto::get_default().ok_or_else(|| { - ReqsignError::config_invalid( - "no CryptoProvider is installed; install one during application startup", - ) - })?; + 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())?; @@ -465,6 +467,7 @@ impl RequestSigner { fn build_signed_query_with_service_account( &self, + provider: &dyn crypto::CryptoProvider, parts: &mut http::request::Parts, service_account: &ServiceAccount, expires_in: Duration, @@ -473,10 +476,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 = @@ -562,8 +573,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?; @@ -620,8 +636,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(), @@ -1001,7 +1021,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"); @@ -1047,7 +1067,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, @@ -1078,7 +1100,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(), @@ -1113,7 +1135,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(), @@ -1150,7 +1172,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)), @@ -1206,7 +1228,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); @@ -1233,7 +1255,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!( @@ -1261,7 +1283,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, @@ -1285,7 +1307,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") @@ -1318,7 +1344,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"); @@ -1385,7 +1411,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", )); @@ -1425,7 +1451,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", )); @@ -1491,7 +1517,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", )); @@ -1543,7 +1569,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", )); @@ -1593,7 +1619,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", )); @@ -1620,7 +1646,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", )); @@ -1645,7 +1671,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", )); @@ -1692,7 +1718,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", @@ -1759,7 +1785,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", )); @@ -1817,7 +1843,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", )); @@ -1882,7 +1908,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)); @@ -1903,7 +1929,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, @@ -1928,7 +1954,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", @@ -1964,7 +1990,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 index 3b0c8c71..e0593842 100644 --- a/services/google/tests/common/mod.rs +++ b/services/google/tests/common/mod.rs @@ -15,10 +15,9 @@ // specific language governing permissions and limitations // under the License. -// Every integration test binary installs the RustCrypto provider once before -// its tests run. Installation is process-wide, so concurrent or repeated -// initialization is intentionally ignored. -#[ctor::ctor(unsafe)] -fn install_test_crypto_provider() { - let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +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 911b8d9f..6b23fee7 100644 --- a/services/google/tests/credential_access_boundary.rs +++ b/services/google/tests/credential_access_boundary.rs @@ -23,7 +23,7 @@ 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, @@ -50,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, @@ -70,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 18a9bc4e..1ffa91de 100644 --- a/services/google/tests/explicit_credential_access_boundary.rs +++ b/services/google/tests/explicit_credential_access_boundary.rs @@ -23,7 +23,7 @@ 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, @@ -92,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()), ) @@ -193,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), ) @@ -219,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), ) @@ -251,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/oauth_token_endpoint.rs b/services/google/tests/oauth_token_endpoint.rs index 29095260..05bf39f6 100644 --- a/services/google/tests/oauth_token_endpoint.rs +++ b/services/google/tests/oauth_token_endpoint.rs @@ -22,7 +22,7 @@ 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, @@ -116,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 { @@ -154,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)?; @@ -222,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?; @@ -303,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:?}"); @@ -332,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 9e20e34c..2ca8db56 100644 --- a/services/google/tests/service_account_token.rs +++ b/services/google/tests/service_account_token.rs @@ -20,7 +20,7 @@ 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, @@ -54,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), ) @@ -67,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 cdf57cb7..ddb2da8c 100644 --- a/services/huaweicloud-obs/Cargo.toml +++ b/services/huaweicloud-obs/Cargo.toml @@ -36,7 +36,6 @@ serde = { workspace = true } serde_json = { workspace = true } [dev-dependencies] -ctor = "1" reqsign-crypto-rustcrypto = { workspace = true } bytes = { workspace = true } env_logger = { workspace = true } diff --git a/services/huaweicloud-obs/README.md b/services/huaweicloud-obs/README.md index d9189ebe..e11a7ce1 100644 --- a/services/huaweicloud-obs/README.md +++ b/services/huaweicloud-obs/README.md @@ -21,17 +21,19 @@ 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 requires a process-wide `CryptoProvider`. Install one at startup -> before constructing signers; see +> 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()` fallback. A bare `Context::new()` has no fallback. 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 3e3dc1ae..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 c2d0af6b..2cfc51ff 100644 --- a/services/huaweicloud-obs/src/lib.rs +++ b/services/huaweicloud-obs/src/lib.rs @@ -31,10 +31,7 @@ pub use provide_credential::*; mod constants; -// Unit tests exercise signing paths, so install the test provider before -// any test in this binary runs. #[cfg(test)] -#[ctor::ctor(unsafe)] -fn install_test_crypto_provider() { - let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +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 cffccbb0..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 index 3b0c8c71..864b1164 100644 --- a/services/huaweicloud-obs/tests/common/mod.rs +++ b/services/huaweicloud-obs/tests/common/mod.rs @@ -15,10 +15,8 @@ // specific language governing permissions and limitations // under the License. -// Every integration test binary installs the RustCrypto provider once before -// its tests run. Installation is process-wide, so concurrent or repeated -// initialization is intentionally ignored. -#[ctor::ctor(unsafe)] -fn install_test_crypto_provider() { - let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +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 62e525dc..b498f6fc 100644 --- a/services/huaweicloud-obs/tests/credential_chain.rs +++ b/services/huaweicloud-obs/tests/credential_chain.rs @@ -53,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); @@ -97,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); @@ -128,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); @@ -140,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); @@ -170,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 a9dd45da..e805399d 100644 --- a/services/oracle/Cargo.toml +++ b/services/oracle/Cargo.toml @@ -35,7 +35,6 @@ reqsign-core = { workspace = true } rust-ini = { workspace = true } [dev-dependencies] -ctor = "1" env_logger = "0.11" reqsign-crypto-rustcrypto = { workspace = true } rsa = { workspace = true } diff --git a/services/oracle/README.md b/services/oracle/README.md index d2a8a307..74439df2 100644 --- a/services/oracle/README.md +++ b/services/oracle/README.md @@ -6,18 +6,20 @@ 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 requires a process-wide `CryptoProvider`. Install one at startup -> before constructing signers; see +> 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()` fallback. A bare `Context::new()` has no fallback. 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 325ef008..4f5f7e60 100644 --- a/services/oracle/src/lib.rs +++ b/services/oracle/src/lib.rs @@ -38,10 +38,7 @@ pub use provide_credential::{ EnvCredentialProvider, StaticCredentialProvider, }; -// Unit tests exercise signing paths, so install the test provider before -// any test in this binary runs. #[cfg(test)] -#[ctor::ctor(unsafe)] -fn install_test_crypto_provider() { - let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +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 850aae86..071edc54 100644 --- a/services/oracle/src/sign_request.rs +++ b/services/oracle/src/sign_request.rs @@ -22,9 +22,7 @@ use http::request::Parts; use http::{HeaderMap, HeaderName, Method}; use log::debug; use reqsign_core::time::Timestamp; -use reqsign_core::{ - Context, Error, Result, SignRequest, SigningCredential, SigningRequest, crypto, -}; +use reqsign_core::{Context, Error, Result, SignRequest, SigningCredential, SigningRequest}; use std::fmt::Write; use std::time::Duration; @@ -104,11 +102,7 @@ impl SignRequest for RequestSigner { // 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?; - let provider = crypto::get_default().ok_or_else(|| { - Error::config_invalid( - "no CryptoProvider is installed; install one during application startup", - ) - })?; + 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); @@ -249,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() @@ -264,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 index 3b0c8c71..864b1164 100644 --- a/services/oracle/tests/common/mod.rs +++ b/services/oracle/tests/common/mod.rs @@ -15,10 +15,8 @@ // specific language governing permissions and limitations // under the License. -// Every integration test binary installs the RustCrypto provider once before -// its tests run. Installation is process-wide, so concurrent or repeated -// initialization is intentionally ignored. -#[ctor::ctor(unsafe)] -fn install_test_crypto_provider() { - let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +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 c174f1b3..0bf43a04 100644 --- a/services/oracle/tests/config_profiles.rs +++ b/services/oracle/tests/config_profiles.rs @@ -106,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()), @@ -332,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 dec5aabb..fa2217fb 100644 --- a/services/oracle/tests/credential_chain.rs +++ b/services/oracle/tests/credential_chain.rs @@ -55,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); @@ -99,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); @@ -131,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); @@ -143,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 a81a9818..0c6c2b6f 100644 --- a/services/oracle/tests/private_key_formats.rs +++ b/services/oracle/tests/private_key_formats.rs @@ -59,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 { @@ -359,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 8e1d67ae..2b28fd20 100644 --- a/services/tencent-cos/Cargo.toml +++ b/services/tencent-cos/Cargo.toml @@ -36,7 +36,6 @@ serde = { workspace = true } serde_json = { workspace = true } [dev-dependencies] -ctor = "1" reqsign-crypto-rustcrypto = { workspace = true } bytes = { workspace = true } dotenvy = { workspace = true } diff --git a/services/tencent-cos/README.md b/services/tencent-cos/README.md index ef23a805..657f060e 100644 --- a/services/tencent-cos/README.md +++ b/services/tencent-cos/README.md @@ -6,17 +6,19 @@ The default credential provider checks Tencent Cloud environment variables and then web identity configuration. It supports both header authentication and presigned query authentication. -> Signing requires a process-wide `CryptoProvider`. Install one at startup -> before constructing signers; see +> 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()` fallback. A bare `Context::new()` has no fallback. 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 eb64db27..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 bffc5e44..8261446e 100644 --- a/services/tencent-cos/src/lib.rs +++ b/services/tencent-cos/src/lib.rs @@ -33,10 +33,7 @@ pub use sign_request::RequestSigner; mod provide_credential; pub use provide_credential::*; -// Unit tests exercise signing paths, so install the test provider before -// any test in this binary runs. #[cfg(test)] -#[ctor::ctor(unsafe)] -fn install_test_crypto_provider() { - let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +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 4e89a185..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, ) -> 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,11 +205,11 @@ 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())?; Ok(format!( "q-sign-algorithm=sha1&q-ak={}&q-sign-time={}&q-key-time={}&q-header-list={}&q-url-param-list={}&q-signature={}", @@ -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 index 3b0c8c71..864b1164 100644 --- a/services/tencent-cos/tests/common/mod.rs +++ b/services/tencent-cos/tests/common/mod.rs @@ -15,10 +15,8 @@ // specific language governing permissions and limitations // under the License. -// Every integration test binary installs the RustCrypto provider once before -// its tests run. Installation is process-wide, so concurrent or repeated -// initialization is intentionally ignored. -#[ctor::ctor(unsafe)] -fn install_test_crypto_provider() { - let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +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 553775ef..344f301c 100644 --- a/services/tencent-cos/tests/credential_chain.rs +++ b/services/tencent-cos/tests/credential_chain.rs @@ -56,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); @@ -100,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); @@ -128,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); @@ -140,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); @@ -170,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 e9858ed6..a43eb6b9 100644 --- a/services/tencent-cos/tests/main.rs +++ b/services/tencent-cos/tests/main.rs @@ -29,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}; @@ -48,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 b583ffb9..1b491f94 100644 --- a/services/tencent-cos/tests/web_identity_live.rs +++ b/services/tencent-cos/tests/web_identity_live.rs @@ -31,7 +31,7 @@ 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}; @@ -104,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 b8a00261..01e200f8 100644 --- a/services/volcengine-tos/Cargo.toml +++ b/services/volcengine-tos/Cargo.toml @@ -36,7 +36,6 @@ serde = { workspace = true } serde_json = { workspace = true } [dev-dependencies] -ctor = "1" reqsign-crypto-rustcrypto = { workspace = true } anyhow = { workspace = true } bytes = { workspace = true } diff --git a/services/volcengine-tos/README.md b/services/volcengine-tos/README.md index a15ff6d8..69a80cde 100644 --- a/services/volcengine-tos/README.md +++ b/services/volcengine-tos/README.md @@ -26,17 +26,19 @@ the default credential chain is unchanged. full presigned URL lifetime. Header signing continues to check the signing time. -> Signing requires a process-wide `CryptoProvider`. Install one at startup -> before constructing signers; see +> 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()` fallback. A bare `Context::new()` has no fallback. 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 643429ee..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) -> Result> { - 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())?; - Ok(hmac_sha256(&service_key, b"request")?.to_vec()) +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 54aef830..33592ecf 100644 --- a/services/volcengine-tos/src/lib.rs +++ b/services/volcengine-tos/src/lib.rs @@ -33,10 +33,7 @@ pub use uri::{percent_encode_path, percent_encode_query}; pub use sign_request::RequestSigner; -// Unit tests exercise signing paths, so install the test provider before -// any test in this binary runs. #[cfg(test)] -#[ctor::ctor(unsafe)] -fn install_test_crypto_provider() { - let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +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 f92aa41e..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) -> Result> { +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 - Ok(hmac_sha256(sign_service.as_slice(), "request".as_bytes())?.to_vec()) + 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 index 3b0c8c71..864b1164 100644 --- a/services/volcengine-tos/tests/common/mod.rs +++ b/services/volcengine-tos/tests/common/mod.rs @@ -15,10 +15,8 @@ // specific language governing permissions and limitations // under the License. -// Every integration test binary installs the RustCrypto provider once before -// its tests run. Installation is process-wide, so concurrent or repeated -// initialization is intentionally ignored. -#[ctor::ctor(unsafe)] -fn install_test_crypto_provider() { - let _ = reqsign_crypto_rustcrypto::RustCryptoProvider::install_default(); +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 68a578b7..efaad669 100644 --- a/services/volcengine-tos/tests/presigned.rs +++ b/services/volcengine-tos/tests/presigned.rs @@ -35,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!( @@ -134,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 c6241ceb..fcf8a9f9 100644 --- a/services/volcengine-tos/tests/signing_diagnostics.rs +++ b/services/volcengine-tos/tests/signing_diagnostics.rs @@ -21,7 +21,7 @@ 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"; @@ -95,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(); @@ -131,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 f77b300d..60bdcdee 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 used as the facade default context fallback." }, { "name": "reqsign-aws-core", diff --git a/website/docs/architecture.md b/website/docs/architecture.md index 68666891..a50e1ffc 100644 --- a/website/docs/architecture.md +++ b/website/docs/architecture.md @@ -105,24 +105,32 @@ browser-backed implementations. See ## Crypto provider -Cryptography is not a `Context` capability. Reqsign resolves every hash, MAC, -asymmetric signature, AES-GCM operation, and random draw through one -process-wide `CryptoProvider` installed by the application at startup: +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()`, then the context fallback: ```rust -use reqsign::RustCryptoProvider; +use reqsign::{Context, RustCryptoProvider, Signer}; +// Explicit provider for this context. +let ctx = Context::new().with_crypto(RustCryptoProvider::new()); + +// Or let an application select one provider for every fallback context. RustCryptoProvider::install_default() .map_err(|_| "a CryptoProvider is already installed")?; ``` -`reqsign-core` and the service crates contain no cryptographic implementation, -so signing without an installed provider returns `ConfigInvalid`. The facade's -`default-crypto` feature supplies the RustCrypto provider but does not install -it; `default_context()` does not install it either. Applications choose the -provider, and integrating middleware such as OpenDAL must leave that choice to -the application. See [CryptoProvider](https://github.com/apache/reqsign/blob/main/docs/crypto-provider.md) for the full -contract and error semantics. +`reqsign-core` and the service crates contain no cryptographic implementation. +A bare `Context::new()` has no provider or fallback and returns `ConfigInvalid` +when signing needs crypto. The facade's `default-crypto` feature sets RustCrypto +as a fallback on `default_context()` without touching the process-wide slot, so +default signers work out of the box and a later global installation still 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 diff --git a/website/docs/guides/testing.md b/website/docs/guides/testing.md index 906ec47d..e3731eae 100644 --- a/website/docs/guides/testing.md +++ b/website/docs/guides/testing.md @@ -36,11 +36,9 @@ rather than asserting a timestamp-dependent signature: use reqsign::{Context, RustCryptoProvider, Signer}; use reqsign::aws::{RequestSigner, StaticCredentialProvider}; -RustCryptoProvider::install_default() - .map_err(|_| "a CryptoProvider is already installed")?; - 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"), ); From b69fbe56983bc66672592b3dcc50a71c1f679b32 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Thu, 19 Nov 2026 20:13:30 +0100 Subject: [PATCH 05/11] refactor(core): remove the CryptoProvider fallback layer Keep one explicit Context binding and resolve it before the process-wide default. When default-crypto is enabled, default_context binds RustCrypto only if the global slot is empty at construction; otherwise it leaves the context unbound. This avoids a third resolution layer while keeping default signers and examples free of install boilerplate. Update docs, caller-facing notes, and isolated tests for install-before- construction, OnceLock non-occupation, feature-off behavior, and explicit provider priority. --- AGENTS.md | 12 ++-- README.md | 4 +- core/src/context.rs | 32 ++------- core/src/crypto.rs | 4 +- core/tests/crypto_provider_context.rs | 33 ++++----- docs/crypto-provider.md | 69 +++++++++---------- reqsign/README.md | 16 ++--- reqsign/src/context.rs | 21 +++--- reqsign/tests/crypto.rs | 42 ++++++----- .../tests/crypto_without_default_crypto.rs | 38 +++++++++- reqsign/tests/default_signer.rs | 4 +- services/aliyun-oss/README.md | 3 +- services/aws-v4/README.md | 3 +- services/aws-v4a/README.md | 3 +- services/azure-storage/README.md | 3 +- services/google/README.md | 3 +- services/huaweicloud-obs/README.md | 3 +- services/oracle/README.md | 3 +- services/tencent-cos/README.md | 3 +- services/volcengine-tos/README.md | 3 +- website/data/providers.json | 2 +- website/docs/architecture.md | 13 ++-- 22 files changed, 172 insertions(+), 145 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index b57dcc2c..f247a2c9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -43,12 +43,12 @@ 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, -then the context fallback). `reqsign-core` and every `services/*` crate carry no -production cryptographic implementation. 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. +resolved by `Context` (explicit binding, then the process-wide registration). +`reqsign-core` and every `services/*` crate carry no production cryptographic +implementation. 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 diff --git a/README.md b/README.md index 42d78853..b8223146 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ use reqsign::aws; #[tokio::main] async fn main() -> Result<()> { - // The facade's default context carries the RustCrypto fallback. + // The facade's default context binds RustCrypto when no global provider is installed. // Create a default signer for S3 in us-east-1 // This will automatically: // - Load credentials from environment variables, config files, or IAM roles @@ -65,7 +65,7 @@ use reqsign_http_send_reqwest::ReqwestHttpSend; #[tokio::main] async fn main() -> Result<()> { // Build your own context with specific implementations. - // A bare Context has no fallback, so bind the provider explicitly. + // A bare Context starts unbound, so bind the provider explicitly. let ctx = Context::new() .with_crypto(RustCryptoProvider::new()) .with_file_read(TokioFileRead) diff --git a/core/src/context.rs b/core/src/context.rs index 3eed68ca..fc3675bb 100644 --- a/core/src/context.rs +++ b/core/src/context.rs @@ -36,8 +36,7 @@ use std::sync::Arc; /// /// 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`], then a fallback set with -/// [`Context::with_crypto_fallback`]. A bare `Context::new()` has none of these +/// with [`crate::crypto::install_default`]. A bare `Context::new()` has neither /// and returns [`crate::ErrorKind::ConfigInvalid`] when crypto is first needed. /// Creating or cloning a context never installs or freezes a global provider. /// @@ -57,7 +56,6 @@ pub struct Context { env: Arc, cmd: Arc, crypto: Option>, - crypto_fallback: Option>, } impl Debug for Context { @@ -68,7 +66,6 @@ impl Debug for Context { .field("env", &self.env) .field("cmd", &self.cmd) .field("crypto", &self.crypto) - .field("crypto_fallback", &self.crypto_fallback) .finish() } } @@ -102,7 +99,6 @@ impl Context { env: Arc::new(NoopEnv), cmd: Arc::new(NoopCommandExecute), crypto: None, - crypto_fallback: None, } } @@ -140,31 +136,18 @@ impl Context { self } - /// Set a fallback cryptographic provider for this context. - /// - /// The fallback is used only when no provider is bound explicitly with - /// [`Context::with_crypto`] and no process-wide provider has been installed - /// with [`crate::crypto::install_default`]. It does not install a - /// process-wide provider. Facades use this to make their default context - /// usable without taking away an application's later provider choice. - pub fn with_crypto_fallback(mut self, provider: impl CryptoProvider) -> Self { - self.crypto_fallback = 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`]; - /// 3. the context fallback set with [`Context::with_crypto_fallback`]. + /// [`crate::crypto::install_default`]. /// - /// If none is available this returns [`crate::ErrorKind::ConfigInvalid`] at - /// the point of use. Resolution never installs or freezes a provider, so a - /// process-wide installation performed after this context was created is - /// observed by later operations through the same context. + /// 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()); @@ -172,9 +155,6 @@ impl Context { if let Some(provider) = crypto::get_default() { return Ok(provider.as_ref()); } - if let Some(provider) = &self.crypto_fallback { - 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", diff --git a/core/src/crypto.rs b/core/src/crypto.rs index e94247f7..65d54dff 100644 --- a/core/src/crypto.rs +++ b/core/src/crypto.rs @@ -20,9 +20,7 @@ //! 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`], then the context -//! fallback set with -//! [`Context::with_crypto_fallback`](crate::Context::with_crypto_fallback). +//! 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 diff --git a/core/tests/crypto_provider_context.rs b/core/tests/crypto_provider_context.rs index 18ddd337..ca2fd4f6 100644 --- a/core/tests/crypto_provider_context.rs +++ b/core/tests/crypto_provider_context.rs @@ -22,25 +22,14 @@ use reqsign_core::{Context, hash}; use support::ByteProvider; #[test] -fn context_resolution_prefers_explicit_then_late_global_then_fallback() { - let fallback = Context::new().with_crypto_fallback(ByteProvider(1)); +fn context_resolution_prefers_explicit_then_global() { + let bare = Context::new(); assert!( - get_default().is_none(), - "creating a context must not install" - ); - - assert_eq!( - hash::sha256( - fallback.crypto_provider().expect("fallback must resolve"), - b"x" - ) - .expect("fallback hashing must succeed"), - [1; 32] + bare.crypto_provider().is_err(), + "a bare context must fail before a global provider exists" ); - let explicit = Context::new() - .with_crypto(ByteProvider(2)) - .with_crypto_fallback(ByteProvider(3)); + let explicit = Context::new().with_crypto(ByteProvider(2)); assert_eq!( hash::sha256( explicit.crypto_provider().expect("explicit must resolve"), @@ -50,17 +39,21 @@ fn context_resolution_prefers_explicit_then_late_global_then_fallback() { [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"); - // The same context was constructed before the global installation. The - // global provider must now override its fallback. assert_eq!( hash::sha256( - fallback.crypto_provider().expect("global must resolve"), + unbound.crypto_provider().expect("global must resolve"), b"x" ) .expect("global hashing must succeed"), - [9; 32] + [9; 32], + "an unbound context must observe the process-wide provider" ); assert_eq!( hash::sha256( diff --git a/docs/crypto-provider.md b/docs/crypto-provider.md index 68164bfb..7e0375ff 100644 --- a/docs/crypto-provider.md +++ b/docs/crypto-provider.md @@ -88,7 +88,6 @@ but it must not be required to serialize signing operations for correctness. ```rust impl Context { pub fn with_crypto(self, provider: impl CryptoProvider) -> Self; - pub fn with_crypto_fallback(self, provider: impl CryptoProvider) -> Self; pub fn crypto_provider(&self) -> Result<&dyn CryptoProvider>; } ``` @@ -98,23 +97,21 @@ impl Context { 1. the provider bound with `Context::with_crypto`; 2. the process-wide provider installed with `reqsign_core::crypto::install_default`; -3. the context fallback set with `Context::with_crypto_fallback`; -4. otherwise `ErrorKind::ConfigInvalid`. +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()`. Resolution reads -the current global registration on every call, so a global provider installed -after a context was created takes precedence over that context's fallback for -later operations through the same context. An explicit `with_crypto` binding -continues to win over a later global installation. Cloning a context preserves -its explicit and fallback bindings. +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()` sets no explicit provider and no fallback. Portable core code -must either bind a provider on the context or install a global one. The facade's -`default_context()` is the exception described below: it supplies a fallback. +`Context::new()` starts with neither an explicit binding nor a global provider. +Portable core code must either 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 @@ -140,13 +137,12 @@ Global installation is optional and backed by 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 may call -`install_default()` once to override facade fallbacks and any other context that -has no explicit provider. Integrating middleware, such as OpenDAL, must not +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. -Middleware may set a fallback on a context it owns, but it must not write the -process-wide slot. ## Failure Semantics @@ -263,18 +259,19 @@ default-crypto = ["dep:reqsign-crypto-rustcrypto"] ``` `default-crypto` re-exports `RustCryptoProvider`. When it is enabled, -`default_context()` sets that provider as a **context fallback** and never -as the process-wide provider. `default_context()` therefore works without -startup boilerplate, while a global installation performed later still takes -precedence and an explicit `with_crypto` binding still wins. +`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()` has no fallback and resolves a -provider only from an explicit binding or a process-wide installation. -`Context::new()` never has a fallback. +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 use `default_context()`, -so they inherit the same behavior: usable with the default feature set, and -still governed by explicit and global overrides. +so they inherit the same behavior. Explicit `with_crypto` bindings always win; +a global provider is used when it was installed before the context was +constructed. Applications that select a different backend disable `default-crypto` and take the backend crate directly. Applications that use only hashing can provide @@ -286,8 +283,8 @@ their own minimal `CryptoProvider`. Facade users can keep using `default_context()` or a per-service `default_signer(...)` without installing anything. To select one provider for -the whole application, install it once at startup; this overrides facade -fallbacks: +the whole application, install it once before constructing facade contexts; +contexts that were already bound to RustCrypto keep their binding: ```rust use reqsign::RustCryptoProvider; @@ -356,8 +353,8 @@ Notable service-specific details: Use `encode_rs256_pem(provider, ...)` with PEM bytes. - Hash and MAC helpers take `&dyn CryptoProvider` and return `Result`. - `reqsign-core` no longer provides crypto implementations, so a context with no - provider binding, global provider, or fallback fails with `ConfigInvalid` at - the point of use. + provider binding and no global provider fails with `ConfigInvalid` at the + point of use. ## Verification @@ -365,13 +362,13 @@ 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 a - context used before global installation, the global override of its fallback, - explicit priority over global, and independent providers on distinct + 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 a default signer - that signs through the fallback and a signer whose explicitly selected - provider is used. +- 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, diff --git a/reqsign/README.md b/reqsign/README.md index afe63e81..2ed01fa7 100644 --- a/reqsign/README.md +++ b/reqsign/README.md @@ -44,11 +44,11 @@ reqsign = "0.20" 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()` use RustCrypto as a context -fallback, so default signers work without startup boilerplate. The fallback is -not a process-wide installation: an application can call -`RustCryptoProvider::install_default()` to override it, and an explicit -`Context::with_crypto` binding always wins. +`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: @@ -69,7 +69,7 @@ use reqsign::aws; #[tokio::main] async fn main() -> Result<()> { - // The facade's default context carries the RustCrypto fallback. + // The facade's default context binds RustCrypto when no global provider is installed. // Create a default signer for AWS S3 in us-east-1 // This will automatically: // - Set up HTTP client and file reader @@ -104,11 +104,11 @@ use reqsign::aws::{DefaultCredentialProvider, RequestSigner}; #[tokio::main] async fn main() -> Result<()> { // Create a context with default implementations - // (including the RustCrypto fallback when default-crypto is enabled). + // (including a RustCrypto binding when default-crypto is enabled). let ctx = default_context(); // Or build your own context with specific implementations. - // A bare Context has no fallback, so bind the provider explicitly. + // 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) diff --git a/reqsign/src/context.rs b/reqsign/src/context.rs index 660c319e..eb5153a2 100644 --- a/reqsign/src/context.rs +++ b/reqsign/src/context.rs @@ -33,14 +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` as a context fallback when `default-crypto` is enabled +/// - `RustCryptoProvider` bound to the context when `default-crypto` is enabled +/// and no process-wide provider is installed at construction time /// -/// The fallback makes `reqsign` examples and default signers usable without -/// installation boilerplate. It does not touch the process-wide registration: -/// a provider installed later with `RustCryptoProvider::install_default()` (or -/// another global provider) takes precedence for this context, and an explicit -/// `Context::with_crypto` binding still wins. Integrating middleware must leave -/// provider installation to the application. +/// 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 /// @@ -89,7 +90,11 @@ pub fn default_context() -> Context { .with_env(OsEnv); #[cfg(feature = "default-crypto")] - let ctx = ctx.with_crypto_fallback(RustCryptoProvider::new()); + let ctx = if reqsign_core::crypto::get_default().is_none() { + ctx.with_crypto(RustCryptoProvider::new()) + } else { + ctx + }; ctx } diff --git a/reqsign/tests/crypto.rs b/reqsign/tests/crypto.rs index 21227bcf..3a62d8bb 100644 --- a/reqsign/tests/crypto.rs +++ b/reqsign/tests/crypto.rs @@ -15,11 +15,11 @@ // specific language governing permissions and limitations // under the License. -//! The facade supplies a fallback but never installs a global provider. +//! The facade binds RustCrypto only when the global slot is empty. #[cfg(feature = "default-context")] #[test] -fn default_context_uses_fallback_without_installing_global_and_global_wins_later() { +fn default_context_binds_rustcrypto_without_installing_global() { use reqsign::crypto::{CryptoProvider, get_default, install_default}; use reqsign::hash; use reqsign::{Context, Result}; @@ -45,29 +45,39 @@ fn default_context_uses_fallback_without_installing_global_and_global_wins_later } } + 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_eq!( - reqsign::hash::base64_encode( - &hash::sha256( - ctx.crypto_provider().expect("fallback must resolve"), - b"abc" - ) - .expect("fallback hashing must succeed") - ), - "ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0=" - ); + assert_sha256_abc(&ctx); - let explicit = Context::new().with_crypto(TestProvider(2)); install_default(TestProvider(9)).expect("global installation must succeed"); + assert_sha256_abc(&ctx); + let after_global = reqsign::default_context(); assert_eq!( - hash::sha256(ctx.crypto_provider().expect("global must resolve"), b"x") - .expect("global hashing must succeed"), + hash::sha256( + after_global.crypto_provider().expect("global must resolve"), + b"x" + ) + .expect("global hashing must succeed"), [9; 32], - "a provider installed after default_context() must override its fallback" + "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"), diff --git a/reqsign/tests/crypto_without_default_crypto.rs b/reqsign/tests/crypto_without_default_crypto.rs index a27a0a22..1321e7ae 100644 --- a/reqsign/tests/crypto_without_default_crypto.rs +++ b/reqsign/tests/crypto_without_default_crypto.rs @@ -20,12 +20,46 @@ #![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_has_no_fallback() { +fn default_context_without_default_crypto_uses_explicit_or_global_only() { assert!(reqsign::crypto::get_default().is_none()); - let err = reqsign::default_context() + 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 index 5b88af24..b6a33d2e 100644 --- a/reqsign/tests/default_signer.rs +++ b/reqsign/tests/default_signer.rs @@ -43,7 +43,7 @@ impl CryptoProvider for UnsupportedProvider { } #[tokio::test] -async fn default_signer_signs_with_the_context_fallback() { +async fn default_signer_signs_with_the_context_provider() { let signer = default_signer("s3", "test-region") .with_credential_provider(StaticCredentialProvider::new("access-key", "secret-key")); let mut parts = http::Request::get("https://example.amazonaws.com/object") @@ -55,7 +55,7 @@ async fn default_signer_signs_with_the_context_fallback() { signer .sign(&mut parts, None) .await - .expect("default signer must use the facade crypto fallback"); + .expect("default signer must use the context crypto provider"); assert!( parts.headers[http::header::AUTHORIZATION] .to_str() diff --git a/services/aliyun-oss/README.md b/services/aliyun-oss/README.md index f814489d..f4f16d19 100644 --- a/services/aliyun-oss/README.md +++ b/services/aliyun-oss/README.md @@ -8,7 +8,8 @@ This crate provides signing support for Alibaba Cloud Object Storage Service (OS > 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()` fallback. A bare `Context::new()` has no fallback. See +> `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 diff --git a/services/aws-v4/README.md b/services/aws-v4/README.md index 86e57b8d..bc8cc118 100644 --- a/services/aws-v4/README.md +++ b/services/aws-v4/README.md @@ -4,7 +4,8 @@ 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()` fallback. A bare `Context::new()` has no fallback. See +> `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 diff --git a/services/aws-v4a/README.md b/services/aws-v4a/README.md index cc71d65b..d5036d99 100644 --- a/services/aws-v4a/README.md +++ b/services/aws-v4a/README.md @@ -9,7 +9,8 @@ signed request to be accepted in multiple AWS regions. See the > 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()` fallback. A bare `Context::new()` has no fallback. See +> `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 diff --git a/services/azure-storage/README.md b/services/azure-storage/README.md index cde28ec1..346c5b95 100644 --- a/services/azure-storage/README.md +++ b/services/azure-storage/README.md @@ -7,7 +7,8 @@ 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()` fallback. A bare `Context::new()` has no fallback. See +> `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 diff --git a/services/google/README.md b/services/google/README.md index 1d49f218..a99a54d2 100644 --- a/services/google/README.md +++ b/services/google/README.md @@ -9,7 +9,8 @@ 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()` fallback. A bare `Context::new()` has no fallback. See +> `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 diff --git a/services/huaweicloud-obs/README.md b/services/huaweicloud-obs/README.md index e11a7ce1..40f92a24 100644 --- a/services/huaweicloud-obs/README.md +++ b/services/huaweicloud-obs/README.md @@ -23,7 +23,8 @@ 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()` fallback. A bare `Context::new()` has no fallback. See +> `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 diff --git a/services/oracle/README.md b/services/oracle/README.md index 74439df2..7329369a 100644 --- a/services/oracle/README.md +++ b/services/oracle/README.md @@ -8,7 +8,8 @@ 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()` fallback. A bare `Context::new()` has no fallback. See +> `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 diff --git a/services/tencent-cos/README.md b/services/tencent-cos/README.md index 657f060e..e896c6ba 100644 --- a/services/tencent-cos/README.md +++ b/services/tencent-cos/README.md @@ -8,7 +8,8 @@ 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()` fallback. A bare `Context::new()` has no fallback. See +> `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 diff --git a/services/volcengine-tos/README.md b/services/volcengine-tos/README.md index 69a80cde..3d82f705 100644 --- a/services/volcengine-tos/README.md +++ b/services/volcengine-tos/README.md @@ -28,7 +28,8 @@ the default credential chain is unchanged. > 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()` fallback. A bare `Context::new()` has no fallback. See +> `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 diff --git a/website/data/providers.json b/website/data/providers.json index 60bdcdee..5fa640c6 100644 --- a/website/data/providers.json +++ b/website/data/providers.json @@ -7,7 +7,7 @@ }, { "name": "reqsign-crypto-rustcrypto", - "role": "Pure-Rust CryptoProvider backend, re-exported by the reqsign facade's default-crypto feature and used as the facade default context fallback." + "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 a50e1ffc..bd296963 100644 --- a/website/docs/architecture.md +++ b/website/docs/architecture.md @@ -109,7 +109,7 @@ 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()`, then the context fallback: +`RustCryptoProvider::install_default()`: ```rust use reqsign::{Context, RustCryptoProvider, Signer}; @@ -117,16 +117,17 @@ use reqsign::{Context, RustCryptoProvider, Signer}; // Explicit provider for this context. let ctx = Context::new().with_crypto(RustCryptoProvider::new()); -// Or let an application select one provider for every fallback context. +// 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()` has no provider or fallback and returns `ConfigInvalid` -when signing needs crypto. The facade's `default-crypto` feature sets RustCrypto -as a fallback on `default_context()` without touching the process-wide slot, so -default signers work out of the box and a later global installation still wins. +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) From 186df2915b3d074d245925403e259dd96e808129 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Thu, 19 Nov 2026 20:32:18 +0100 Subject: [PATCH 06/11] docs: clarify context provider resolution without a global default State that a bare Context has no explicit binding, not that a global provider is absent from the process. --- core/src/context.rs | 7 ++++--- docs/crypto-provider.md | 8 ++++---- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/core/src/context.rs b/core/src/context.rs index fc3675bb..a85dbc94 100644 --- a/core/src/context.rs +++ b/core/src/context.rs @@ -36,9 +36,10 @@ use std::sync::Arc; /// /// 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 neither -/// and returns [`crate::ErrorKind::ConfigInvalid`] when crypto is first needed. -/// Creating or cloning a context never installs or freezes a global provider. +/// 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 /// diff --git a/docs/crypto-provider.md b/docs/crypto-provider.md index 7e0375ff..23ca4ed8 100644 --- a/docs/crypto-provider.md +++ b/docs/crypto-provider.md @@ -108,10 +108,10 @@ 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 with neither an explicit binding nor a global provider. -Portable core code must either 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. +`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 From 6daa77f0a4b9c373095dfaaa027d32edf605a669 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 05:53:33 +0100 Subject: [PATCH 07/11] chore: version crypto backends independently at 1.0.0 Start reqsign-crypto-rustcrypto and reqsign-crypto-boring on independent 1.0.0 lines. Update the workspace dependency, Boring's RustCrypto dev dependency, and the versioning documentation while keeping core, service, and facade versions unchanged. --- AGENTS.md | 2 ++ Cargo.toml | 2 +- crypto/boring/Cargo.toml | 4 ++-- crypto/rustcrypto/Cargo.toml | 2 +- docs/crypto-provider.md | 9 ++++++--- 5 files changed, 12 insertions(+), 7 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index f247a2c9..d1ba9afb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -86,6 +86,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 5f6d7b54..a250d255 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,7 +35,7 @@ reqsign-aws-v4a = { version = "3.1.1", 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 = "3.3.4", path = "crypto/rustcrypto" } +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.3.1", path = "services/google" } reqsign-http-send-reqwest = { version = "4.0.9", path = "context/http-send-reqwest" } diff --git a/crypto/boring/Cargo.toml b/crypto/boring/Cargo.toml index afa979f2..9854bd29 100644 --- a/crypto/boring/Cargo.toml +++ b/crypto/boring/Cargo.toml @@ -17,7 +17,7 @@ [package] name = "reqsign-crypto-boring" -version = "0.1.0" +version = "1.0.0" categories = ["authentication", "cryptography"] description = "BoringSSL backend for reqsign." @@ -41,6 +41,6 @@ http = "1" p256 = { version = "0.14.0", default-features = false, features = ["ecdsa"] } reqsign-aws-core = { version = "3.3.1", path = "../../services/aws-core" } reqsign-aws-v4 = { version = "3.4.1", path = "../../services/aws-v4" } -reqsign-crypto-rustcrypto = { version = "3.3.4", path = "../rustcrypto" } +reqsign-crypto-rustcrypto = { version = "1.0.0", path = "../rustcrypto" } sha2 = "0.11" tokio = { version = "1", features = ["macros", "rt"] } diff --git a/crypto/rustcrypto/Cargo.toml b/crypto/rustcrypto/Cargo.toml index 3b5243ed..c473abe1 100644 --- a/crypto/rustcrypto/Cargo.toml +++ b/crypto/rustcrypto/Cargo.toml @@ -17,7 +17,7 @@ [package] name = "reqsign-crypto-rustcrypto" -version = "3.3.4" +version = "1.0.0" categories = ["authentication", "cryptography"] description = "RustCrypto backend for reqsign." diff --git a/docs/crypto-provider.md b/docs/crypto-provider.md index 23ca4ed8..0080ff55 100644 --- a/docs/crypto-provider.md +++ b/docs/crypto-provider.md @@ -23,6 +23,9 @@ Two provider crates ship with this design: - `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 @@ -215,8 +218,8 @@ Azure Storage's `ServiceSharedAccessSignature::token` takes ### `reqsign-crypto-rustcrypto` -Location: `crypto/rustcrypto`. Workspace member. Version follows the core -crate's lockstep line. +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. @@ -245,7 +248,7 @@ 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 (`0.1.0` initially), is verified by +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`. From 8fe3577b69aaa602b937775198020b5561fcecab Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 06:26:04 +0100 Subject: [PATCH 08/11] refactor: move RS256 JWT formatting into services Remove the public reqsign_core::jwt module and jwt feature, along with core's optional serde/serde_json dependencies and the JWT-only test support/dev dependencies. Azure now formats its client-certificate RS256 assertion privately, and Google shares one private crate-local JWT helper between request signing and service-account token exchange. Both keep the existing headers, claims, unpadded JWS encoding, PKCS#8/PKCS#1 support, and provider error semantics. Google's base64 dependency is now always available, while the former optional-feature wiring is removed. Port the JWT contract tests to the service helpers and update the design/caller documentation. --- AGENTS.md | 9 +- core/Cargo.toml | 9 - core/src/jwt.rs | 199 ------------------ core/src/lib.rs | 5 - core/src/test_support.rs | 79 ------- docs/crypto-provider.md | 42 ++-- services/azure-storage/Cargo.toml | 2 +- .../provide_credential/client_certificate.rs | 138 +++++++++++- services/google/Cargo.toml | 6 +- services/google/src/jwt.rs | 176 ++++++++++++++++ services/google/src/lib.rs | 1 + .../service_account_token.rs | 3 +- services/google/src/sign_request.rs | 3 +- 13 files changed, 343 insertions(+), 329 deletions(-) delete mode 100644 core/src/jwt.rs delete mode 100644 core/src/test_support.rs create mode 100644 services/google/src/jwt.rs diff --git a/AGENTS.md b/AGENTS.md index d1ba9afb..117d247d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -45,10 +45,11 @@ security boundary and its relationship to OpenDAL and other host applications. 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. 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. +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 diff --git a/core/Cargo.toml b/core/Cargo.toml index 479e387a..4f545b9c 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -29,7 +29,6 @@ rust-version.workspace = true [features] default = [] -jwt = ["dep:serde", "dep:serde_json"] [dependencies] anyhow = { workspace = true } @@ -42,10 +41,6 @@ jiff = { workspace = true } log = { workspace = true } percent-encoding = { workspace = true } -# Optional dependencies -serde = { workspace = true, optional = true } -serde_json = { workspace = true, optional = true } - [target.'cfg(target_os = "windows")'.dependencies] windows-sys = { version = "0.61.0", features = [ "Win32_Foundation", @@ -56,7 +51,3 @@ windows-sys = { version = "0.61.0", features = [ [dev-dependencies] asyncband = { workspace = true, features = ["oneshot"] } futures = { workspace = true } -hmac = { workspace = true } -rsa = { workspace = true } -sha1 = { workspace = true } -sha2 = { workspace = true } diff --git a/core/src/jwt.rs b/core/src/jwt.rs deleted file mode 100644 index c2135fa3..00000000 --- a/core/src/jwt.rs +++ /dev/null @@ -1,199 +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 serde::Serialize; - -use crate::Error; -use crate::Result; -use crate::crypto::CryptoProvider; - -/// Encode a JWS compact JWT using an RSA private key in PKCS#8 or PKCS#1 PEM -/// format. -/// -/// 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. -/// Signing is performed by `provider`, which callers with a -/// [`Context`](crate::Context) resolve with -/// [`Context::crypto_provider`](crate::Context::crypto_provider). -pub fn encode_rs256_pem( - 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 crate::Context; - use crate::test_support::TestCryptoProvider; - use base64::engine::general_purpose::URL_SAFE_NO_PAD; - use rsa::RsaPrivateKey; - use rsa::pkcs1::{DecodeRsaPrivateKey, EncodeRsaPrivateKey}; - use rsa::pkcs1v15::{Signature, VerifyingKey}; - use rsa::pkcs8::{DecodePrivateKey, EncodePrivateKey}; - use rsa::rand_core::OsRng; - use rsa::sha2::Sha256; - 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, - } - - fn private_key() -> RsaPrivateKey { - RsaPrivateKey::new(&mut OsRng, 1024).expect("test RSA key generation must work") - } - - fn verify(header: &Header<'_>, claims: &Claims<'_>, jwt: &str, pem: &[u8]) { - let parts = jwt.split('.').collect::>(); - assert_eq!(parts.len(), 3); - - let header_value: serde_json::Value = serde_json::from_slice( - &URL_SAFE_NO_PAD - .decode(parts[0]) - .expect("JWT header must decode"), - ) - .expect("JWT header must be JSON"); - assert_eq!( - header_value, - json!({ - "alg": header.alg, - "typ": header.typ, - "x5t": header.x5t - }) - ); - assert_eq!( - URL_SAFE_NO_PAD - .decode(parts[1]) - .expect("JWT claims must decode"), - serde_json::to_vec(claims).expect("claims must serialize") - ); - - let signature = URL_SAFE_NO_PAD - .decode(parts[2]) - .expect("JWT signature must decode"); - let signature = Signature::try_from(signature.as_slice()) - .expect("JWT signature must be a PKCS#1 v1.5 signature"); - let private_key = - RsaPrivateKey::from_pkcs8_pem(std::str::from_utf8(pem).expect("PEM must be UTF-8")) - .or_else(|_| { - RsaPrivateKey::from_pkcs1_pem( - std::str::from_utf8(pem).expect("PEM must be UTF-8"), - ) - }) - .expect("test PEM must parse"); - let verifying_key = VerifyingKey::::new(private_key.to_public_key()); - verifying_key - .verify(format!("{}.{}", parts[0], parts[1]).as_bytes(), &signature) - .expect("JWT signature must verify"); - } - - #[test] - fn encode_rs256_pem_keeps_jws_shape_and_verifiable_signature() { - let ctx = Context::new().with_crypto(TestCryptoProvider); - let provider = ctx.crypto_provider().expect("test provider must resolve"); - let private_key = private_key(); - let header = Header { - alg: "RS256", - typ: "JWT", - x5t: "thumbprint", - }; - let claims = Claims { - iss: "client", - sub: "client", - aud: "https://example.com/token", - exp: 1, - }; - - for pem in [ - private_key - .to_pkcs8_pem(rsa::pkcs8::LineEnding::LF) - .expect("test key must encode as PKCS#8"), - private_key - .to_pkcs1_pem(rsa::pkcs1::LineEnding::LF) - .expect("test key must encode as PKCS#1"), - ] { - let jwt = encode_rs256_pem(provider, &header, &claims, pem.as_bytes()) - .expect("JWT encoding must succeed"); - verify(&header, &claims, &jwt, pem.as_bytes()); - } - } - - #[test] - fn encode_rs256_pem_rejects_malformed_key_material() { - let ctx = Context::new().with_crypto(TestCryptoProvider); - let provider = ctx.crypto_provider().expect("test provider must resolve"); - let err = encode_rs256_pem( - provider, - &Header { - alg: "RS256", - typ: "JWT", - x5t: "thumbprint", - }, - &Claims { - iss: "client", - sub: "client", - aud: "https://example.com/token", - exp: 1, - }, - b"not a private key", - ) - .expect_err("malformed private key must fail"); - - assert_eq!(err.kind(), crate::ErrorKind::CredentialInvalid); - } -} diff --git a/core/src/lib.rs b/core/src/lib.rs index 6c3deba4..d7ebd842 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -183,14 +183,9 @@ pub mod crypto; pub mod hash; -#[cfg(feature = "jwt")] -pub mod jwt; pub mod time; pub mod utils; -#[cfg(all(test, feature = "jwt"))] -mod test_support; - mod api; pub use self::api::GrantCredential; pub use self::api::GrantCredentialDyn; diff --git a/core/src/test_support.rs b/core/src/test_support.rs deleted file mode 100644 index 9c1cf0ea..00000000 --- a/core/src/test_support.rs +++ /dev/null @@ -1,79 +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. - -//! Test-only cryptographic provider for `reqsign-core` unit tests. -//! -//! `reqsign-core` cannot use `reqsign-crypto-rustcrypto` in its own unit tests: -//! the dev-dependency would link a second, non-test instance of -//! `reqsign-core`, and installation would populate that instance's -//! `OnceLock` instead of the one used by the test. This local provider keeps -//! crypto dependencies dev-only and installs into the test instance. - -use crate::crypto::CryptoProvider; -use crate::{Error, Result}; - -#[derive(Debug)] -pub(crate) struct TestCryptoProvider; - -impl CryptoProvider for TestCryptoProvider { - fn sha1(&self, input: &[u8]) -> Result<[u8; 20]> { - use sha1::Digest; - Ok(sha1::Sha1::digest(input).into()) - } - - fn sha256(&self, input: &[u8]) -> Result<[u8; 32]> { - use sha2::Digest; - Ok(sha2::Sha256::digest(input).into()) - } - - fn hmac_sha1(&self, key: &[u8], input: &[u8]) -> Result<[u8; 20]> { - use hmac::{Hmac, KeyInit, Mac}; - let mut hmac = Hmac::::new_from_slice(key) - .map_err(|e| Error::unexpected("failed to initialize HMAC-SHA1").with_source(e))?; - hmac.update(input); - Ok(hmac.finalize().into_bytes().into()) - } - - fn hmac_sha256(&self, key: &[u8], input: &[u8]) -> Result<[u8; 32]> { - use hmac::{Hmac, KeyInit, Mac}; - let mut hmac = Hmac::::new_from_slice(key) - .map_err(|e| Error::unexpected("failed to initialize HMAC-SHA256").with_source(e))?; - hmac.update(input); - Ok(hmac.finalize().into_bytes().into()) - } - - fn rsa_pkcs1v15_sha256_sign(&self, private_key_pem: &[u8], message: &[u8]) -> Result> { - use rsa::pkcs1::DecodeRsaPrivateKey; - use rsa::pkcs1v15::SigningKey; - use rsa::pkcs8::DecodePrivateKey; - use rsa::rand_core::OsRng; - use rsa::sha2::Sha256; - 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 = SigningKey::::new(private_key); - let signature = signing_key.sign_with_rng(&mut OsRng, message); - Ok(signature.to_bytes().to_vec()) - } -} diff --git a/docs/crypto-provider.md b/docs/crypto-provider.md index 0080ff55..26c698d4 100644 --- a/docs/crypto-provider.md +++ b/docs/crypto-provider.md @@ -194,21 +194,12 @@ 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::jwt` no longer exposes an `rsa` type. The typed -`encode_rs256(&H, &C, &RsaPrivateKey)` entry point is removed. The byte-based -entry point remains and requires the selected provider: - -```rust -pub fn encode_rs256_pem( - provider: &dyn CryptoProvider, - header: &H, - claims: &C, - private_key_pem: &[u8], -) -> Result; -``` - -Enabling the `jwt` feature adds `serde` and `serde_json`; it does not add `rsa` -or any other cryptographic implementation. +`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 @@ -308,8 +299,8 @@ 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 and JWT helpers take the provider directly; -there is no implicit lookup. +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 @@ -342,18 +333,21 @@ Notable service-specific details: `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 in `azure-storage`; the thumbprint uses the provider's SHA-1 and the - client assertion uses `jwt::encode_rs256_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; - 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. + 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 -- `reqsign_core::jwt::encode_rs256(&H, &C, &RsaPrivateKey)` is removed. - Use `encode_rs256_pem(provider, ...)` with PEM bytes. +- 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 diff --git a/services/azure-storage/Cargo.toml b/services/azure-storage/Cargo.toml index 4d54e9e1..171fc0bc 100644 --- a/services/azure-storage/Cargo.toml +++ b/services/azure-storage/Cargo.toml @@ -41,7 +41,6 @@ serde_json = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] pem = { workspace = true } -reqsign-core = { workspace = true, features = ["jwt"] } [dev-dependencies] reqsign-crypto-rustcrypto = { workspace = true } @@ -51,4 +50,5 @@ 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/src/provide_credential/client_certificate.rs b/services/azure-storage/src/provide_credential/client_certificate.rs index 08054211..9f0932ff 100644 --- a/services/azure-storage/src/provide_credential/client_certificate.rs +++ b/services/azure-storage/src/provide_credential/client_certificate.rs @@ -141,6 +141,33 @@ impl ClientCertificateCredentialProvider { Ok((cert_der, private_key_pem.into_bytes())) } + /// 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( @@ -182,7 +209,7 @@ impl ClientCertificateCredentialProvider { x5t: self.calculate_thumbprint(provider, cert_der)?, }; - reqsign_core::jwt::encode_rs256_pem(provider, &header, &claims, private_key_pem) + Self::encode_rs256_jws(provider, &header, &claims, private_key_pem) } /// Exchange client assertion for access token @@ -333,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/google/Cargo.toml b/services/google/Cargo.toml index f7fef8a9..77125ab3 100644 --- a/services/google/Cargo.toml +++ b/services/google/Cargo.toml @@ -31,7 +31,6 @@ all-features = true [features] credential-access-boundary-client-side = [ - "dep:base64", "dep:prost", "dep:zeroize", ] @@ -39,7 +38,7 @@ default = [] [dependencies] asyncband = { workspace = true } -base64 = { workspace = true, optional = true } +base64 = { workspace = true } bytes = { workspace = true } form_urlencoded = { workspace = true } hex = { workspace = true } @@ -54,9 +53,6 @@ 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"] } 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 ba1405ea..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::{ diff --git a/services/google/src/provide_credential/service_account_token.rs b/services/google/src/provide_credential/service_account_token.rs index e0d187e6..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"; @@ -304,7 +305,7 @@ fn build_token_request( 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)?, diff --git a/services/google/src/sign_request.rs b/services/google/src/sign_request.rs index 0fbecb1d..b621fdf3 100644 --- a/services/google/src/sign_request.rs +++ b/services/google/src/sign_request.rs @@ -36,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. @@ -340,7 +341,7 @@ impl RequestSigner { 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), From 73ef4045ca21c31d3aa2061af0d073d24f7e02e7 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 07:03:18 +0100 Subject: [PATCH 09/11] ci: use long package flags in targeted commands Apply the review suggestions for the per-root dependency gate, core and RustCrypto WASM checks, and the facade crypto feature tests. --- .github/workflows/ci.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 58e7c65d..f3d31591 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -64,7 +64,7 @@ jobs: # 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 -p "$package" --all-features --target all --edges normal --prefix none \ + 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 @@ -125,8 +125,8 @@ jobs: - name: Check run: | rustup target add wasm32-unknown-unknown - cargo check -p reqsign-core --target wasm32-unknown-unknown - cargo check -p reqsign-crypto-rustcrypto --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 @@ -147,7 +147,7 @@ jobs: RUST_BACKTRACE: full - name: Facade crypto feature tests run: | - cargo test -p reqsign --all-features --test crypto --test default_signer + cargo test --package reqsign --all-features --test crypto --test default_signer cargo test -p reqsign --no-default-features --features default-context --test crypto_without_default_crypto - name: Doc Test run: cargo +nightly test --doc --all-features --workspace From 1824705d4b80824393a33c3dabe8a150d068acfa Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 09:26:07 +0100 Subject: [PATCH 10/11] docs: explain the deliberate CryptoProvider surface Document that the provider exposes the focused digest, HMAC, signature, encryption, and random-generation operations Reqsign needs, and that one provider serves all operations at runtime. --- core/src/crypto.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/core/src/crypto.rs b/core/src/crypto.rs index 65d54dff..eeed186e 100644 --- a/core/src/crypto.rs +++ b/core/src/crypto.rs @@ -34,6 +34,14 @@ 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 From 970c07a1da4baffe18efabac8feec1855df026ba Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 10:19:28 +0100 Subject: [PATCH 11/11] test: keep crypto provider coverage deterministic Use --package in the facade crypto CI command, drop the redundant threaded install stress test, and keep deterministic install assertions. Compare hash helpers with provider raw bytes instead of pinned digests, and verify the RustCrypto adapter against direct primitives. --- .github/workflows/ci.yml | 2 +- core/tests/crypto_provider_concurrency.rs | 59 ---------- core/tests/crypto_provider_second_install.rs | 37 +++--- crypto/rustcrypto/tests/core_hash.rs | 83 ++++++------- crypto/rustcrypto/tests/provider.rs | 116 +++++++++---------- 5 files changed, 114 insertions(+), 183 deletions(-) delete mode 100644 core/tests/crypto_provider_concurrency.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f3d31591..1bd77f62 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -148,7 +148,7 @@ jobs: - name: Facade crypto feature tests run: | cargo test --package reqsign --all-features --test crypto --test default_signer - cargo test -p reqsign --no-default-features --features default-context --test crypto_without_default_crypto + 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/core/tests/crypto_provider_concurrency.rs b/core/tests/crypto_provider_concurrency.rs deleted file mode 100644 index b3f36631..00000000 --- a/core/tests/crypto_provider_concurrency.rs +++ /dev/null @@ -1,59 +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. - -mod support; - -use std::sync::{Arc, Barrier}; - -use reqsign_core::crypto::{get_default, install_default}; -use support::TestProvider; - -#[test] -fn concurrent_installation_elects_exactly_one_provider() { - const NAMES: [&str; 16] = [ - "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", - "eleven", "twelve", "thirteen", "fourteen", "fifteen", - ]; - - let barrier = Arc::new(Barrier::new(NAMES.len())); - let handles = NAMES - .into_iter() - .map(|name| { - let barrier = barrier.clone(); - std::thread::spawn(move || { - barrier.wait(); - install_default(TestProvider::new(name)) - }) - }) - .collect::>(); - - let results = handles - .into_iter() - .map(|handle| handle.join().expect("install thread must not panic")) - .collect::>(); - - let winners = results.iter().filter(|result| result.is_ok()).count(); - let installed = get_default().expect("one provider must be installed"); - - assert_eq!(winners, 1, "exactly one concurrent install must succeed"); - for rejected in results.iter().filter_map(|result| result.as_ref().err()) { - assert!( - !Arc::ptr_eq(rejected, installed), - "a rejected provider must not be the installed provider" - ); - } -} diff --git a/core/tests/crypto_provider_second_install.rs b/core/tests/crypto_provider_second_install.rs index ecf4b7af..2d46ffc9 100644 --- a/core/tests/crypto_provider_second_install.rs +++ b/core/tests/crypto_provider_second_install.rs @@ -17,27 +17,36 @@ mod support; -use std::sync::Arc; - use reqsign_core::crypto::{get_default, install_default}; -use support::TestProvider; +use support::ByteProvider; #[test] fn second_installation_returns_the_rejected_provider_without_replacing_first() { - install_default(TestProvider::new("first")).expect("first install must succeed"); - let installed = Arc::as_ptr(get_default().expect("provider must be installed")); + 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(TestProvider::new("second")).expect_err("second install must be rejected"); + let rejected = install_default(ByteProvider(2)).expect_err("second install must be rejected"); assert_eq!( - Arc::as_ptr(get_default().expect("provider must stay installed")), - installed, - "the first provider must remain installed" - ); - assert_ne!( - Arc::as_ptr(&rejected), - installed, + 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/crypto/rustcrypto/tests/core_hash.rs b/crypto/rustcrypto/tests/core_hash.rs index aa7754f6..508e3598 100644 --- a/crypto/rustcrypto/tests/core_hash.rs +++ b/crypto/rustcrypto/tests/core_hash.rs @@ -15,6 +15,7 @@ // 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, @@ -22,80 +23,72 @@ use reqsign_core::hash::{ }; 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 hashes_match_published_vectors_with_expected_widths() { +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!( - hex::encode(sha1(&provider, b"abc").expect("SHA-1 must succeed")), - "a9993e364706816aba3e25717850c26c9cd0d89d" - ); - assert_eq!( - hex::encode(sha256(&provider, b"abc").expect("SHA-256 must succeed")), - "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" - ); - assert_eq!( - sha1(&provider, b"abc").expect("SHA-1 must succeed").len(), - 20 + sha1(&provider, INPUT).expect("SHA-1 must succeed"), + expected_sha1 ); assert_eq!( - sha256(&provider, b"abc") - .expect("SHA-256 must succeed") - .len(), - 32 + 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, b"abc").expect("hex SHA-1 must succeed"), - "a9993e364706816aba3e25717850c26c9cd0d89d" + hex_sha1(&provider, INPUT).expect("hex SHA-1 must succeed"), + hex::encode(expected_sha1) ); assert_eq!( - hex_sha256(&provider, b"abc").expect("hex SHA-256 must succeed"), - "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + hex_sha256(&provider, INPUT).expect("hex SHA-256 must succeed"), + hex::encode(expected_sha256) ); } #[test] -fn hmac_matches_rfc_vectors_with_expected_widths() { +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"); - let key = [0x0b; 20]; - assert_eq!( - hex::encode(hmac_sha1(&provider, &key, b"Hi There").expect("HMAC-SHA1 must succeed")), - "b617318655057264e28bc0b6fb378c8ef146be00" - ); - assert_eq!( - hex::encode(hmac_sha256(&provider, &key, b"Hi There").expect("HMAC-SHA256 must succeed")), - "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7" - ); assert_eq!( - hmac_sha1(&provider, &key, b"Hi There") - .expect("HMAC-SHA1 must succeed") - .len(), - 20 + hmac_sha1(&provider, KEY, INPUT).expect("HMAC-SHA1 must succeed"), + expected_sha1 ); assert_eq!( - hmac_sha256(&provider, &key, b"Hi There") - .expect("HMAC-SHA256 must succeed") - .len(), - 32 + 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, b"Hi There").expect("hex HMAC-SHA1 must succeed"), - "b617318655057264e28bc0b6fb378c8ef146be00" + hex_hmac_sha1(&provider, KEY, INPUT).expect("hex HMAC-SHA1 must succeed"), + hex::encode(expected_sha1) ); assert_eq!( - hex_hmac_sha256(&provider, &key, b"Hi There").expect("hex HMAC-SHA256 must succeed"), - "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7" + hex_hmac_sha256(&provider, KEY, INPUT).expect("hex HMAC-SHA256 must succeed"), + hex::encode(expected_sha256) ); assert_eq!( - base64_hmac_sha1(&provider, &key, b"Hi There").expect("base64 HMAC-SHA1 must succeed"), - "thcxhlUFcmTii8C2+zeMjvFGvgA=" + base64_hmac_sha1(&provider, KEY, INPUT).expect("base64 HMAC-SHA1 must succeed"), + hash::base64_encode(&expected_sha1) ); assert_eq!( - base64_hmac_sha256(&provider, &key, b"Hi There").expect("base64 HMAC-SHA256 must succeed"), - "sDRMYdjbOFNcqK/OrwvxK4gdwgDJgz2nJuk3bC4yz/c=" + base64_hmac_sha256(&provider, KEY, INPUT).expect("base64 HMAC-SHA256 must succeed"), + hash::base64_encode(&expected_sha256) ); } diff --git a/crypto/rustcrypto/tests/provider.rs b/crypto/rustcrypto/tests/provider.rs index 5342f45b..a63cf578 100644 --- a/crypto/rustcrypto/tests/provider.rs +++ b/crypto/rustcrypto/tests/provider.rs @@ -15,6 +15,7 @@ // 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}; @@ -23,8 +24,10 @@ 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; +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"); @@ -53,87 +56,72 @@ fn installs_one_process_wide_provider() { } #[test] -fn hashes_match_published_vectors() { +fn hashes_delegate_to_the_expected_algorithms() { let provider = provider(); - assert_eq!( - hex(&provider.sha1(b"abc").expect("SHA-1 must succeed")), - "a9993e364706816aba3e25717850c26c9cd0d89d" - ); - assert_eq!( - hex(&provider.sha256(b"abc").expect("SHA-256 must succeed")), - "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" - ); - assert_eq!( - hex(&provider - .sha256(&vec![b'a'; 1_000_000]) - .expect("large SHA-256 must succeed")), - "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0" - ); + 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_matches_rfc_vectors_at_block_boundaries() { +fn hmac_handles_block_boundaries_without_changing_key_or_input() { let provider = provider(); + let input = b"POST /object?uploadId=example HTTP/1.1"; - assert_eq!( - hex(&provider - .hmac_sha256(&[0x0b; 20], b"Hi There") - .expect("HMAC-SHA256 must succeed")), - "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7" - ); - assert_eq!( - hex(&provider - .hmac_sha1( - &[0xaa; 80], - b"Test Using Larger Than Block-Size Key - Hash Key First" - ) - .expect("HMAC-SHA1 must succeed")), - "aa4ae5e15272d00e95705637ce8a3b55ed402112" - ); - assert_eq!( - hex(&provider - .hmac_sha256( - &[0xaa; 131], - b"Test Using Larger Than Block-Size Key - Hash Key First" - ) - .expect("HMAC-SHA256 must succeed")), - "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54" - ); - - for (key, expected) in [ - ( - &b""[..], - "2b31f75fad699604041bb9a4e191657b10d638d3e1c0a3d79b8a1db8b1ed0826", - ), - ( - &b"k"[..], - "82de63a94b14635375eafcc20afd3629397e17ed1a9e79c128ca8e8f3a0cc7ab", - ), - ( - &[0u8; 64][..], - "2b31f75fad699604041bb9a4e191657b10d638d3e1c0a3d79b8a1db8b1ed0826", - ), - ( - &[0u8; 65][..], - "a0ade4ba44e1645ce9bd9bb9519260e658ea825e7ec2703144fbc77b76f9e567", - ), + for key in [ + &b""[..], + &b"k"[..], + &[0u8; 64][..], + &[0u8; 65][..], + &[0xaa; 80][..], + &[0xaa; 131][..], ] { assert_eq!( - hex(&provider - .hmac_sha256(key, b"boundary message") - .expect("HMAC-SHA256 boundary must succeed")), - expected + 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 verifying_key = RsaVerifyingKey::::new(public_key); let large_message = vec![b'x'; 100_000]; for message in [&b""[..], b"message", large_message.as_slice()] {