From d742d0677baf61033de4fa86a07402ae40dca09a Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:14:53 +0100 Subject: [PATCH 1/2] refactor(crypto): confine implementation dependencies to crypto/* --- .github/scripts/check_crypto_dependencies.py | 159 +++++++++++ .../scripts/test_check_crypto_dependencies.py | 180 ++++++++++++ .github/workflows/ci.yml | 5 + Cargo.toml | 7 - crypto/rustcrypto/Cargo.toml | 14 +- docs/crypto-provider.md | 19 +- services/aws-v4/Cargo.toml | 1 - services/aws-v4/tests/signing/standard.rs | 3 +- services/aws-v4a/Cargo.toml | 1 - services/aws-v4a/src/sign_request.rs | 165 ++++++++--- services/azure-storage/Cargo.toml | 1 - .../provide_credential/client_certificate.rs | 37 +-- .../tests/fixtures/rsa_pkcs1.pem | 27 ++ .../tests/fixtures/rsa_pkcs8.pem | 28 ++ services/google/Cargo.toml | 2 - .../credential_access_boundary/client_side.rs | 257 +++++++++++++----- services/google/src/jwt.rs | 40 +-- .../service_account_token.rs | 10 +- services/google/src/sign_request.rs | 24 +- services/google/tests/fixtures/rsa_pkcs1.pem | 27 ++ services/google/tests/fixtures/rsa_pkcs8.pem | 28 ++ .../google/tests/fixtures/rsa_pkcs8_alt.pem | 28 ++ services/google/tests/oauth_token_endpoint.rs | 15 +- services/oracle/Cargo.toml | 1 - services/oracle/src/sign_request.rs | 14 +- services/oracle/tests/common/mod.rs | 85 +++++- services/oracle/tests/config_profiles.rs | 24 +- .../oracle/tests/fixtures/rsa-2048-pkcs1.pem | 27 ++ .../oracle/tests/fixtures/rsa-2048-pkcs8.pem | 28 ++ .../oracle/tests/fixtures/rsa-2048-public.pem | 9 + services/oracle/tests/private_key_formats.rs | 127 +++++---- 31 files changed, 1086 insertions(+), 307 deletions(-) create mode 100644 .github/scripts/check_crypto_dependencies.py create mode 100644 .github/scripts/test_check_crypto_dependencies.py create mode 100644 services/azure-storage/tests/fixtures/rsa_pkcs1.pem create mode 100644 services/azure-storage/tests/fixtures/rsa_pkcs8.pem create mode 100644 services/google/tests/fixtures/rsa_pkcs1.pem create mode 100644 services/google/tests/fixtures/rsa_pkcs8.pem create mode 100644 services/google/tests/fixtures/rsa_pkcs8_alt.pem create mode 100644 services/oracle/tests/fixtures/rsa-2048-pkcs1.pem create mode 100644 services/oracle/tests/fixtures/rsa-2048-pkcs8.pem create mode 100644 services/oracle/tests/fixtures/rsa-2048-public.pem diff --git a/.github/scripts/check_crypto_dependencies.py b/.github/scripts/check_crypto_dependencies.py new file mode 100644 index 00000000..66c1fcd7 --- /dev/null +++ b/.github/scripts/check_crypto_dependencies.py @@ -0,0 +1,159 @@ +# 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. + +"""Reject direct cryptographic implementation dependencies outside crypto/*. + +The check walks every manifest so it sees declarations that Cargo metadata +would omit, including unused workspace entries, renamed packages, target +specific tables, and build/dev dependency kinds. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +import sys +import tomllib + +FORBIDDEN_PACKAGES = frozenset( + { + "sha1", + "sha2", + "hmac", + "rsa", + "p256", + "aes-gcm", + "getrandom", + "boring", + "openssl", + "ring", + "aws-lc-rs", + } +) +SKIPPED_DIRECTORIES = frozenset({"target", ".git"}) +DEPENDENCY_TABLES = ("dependencies", "dev-dependencies", "build-dependencies") + + +@dataclass(frozen=True) +class Violation: + manifest: str + table: str + key: str + package: str + + def __str__(self) -> str: + return ( + f"{self.manifest}: [{self.table}] {self.key} resolves to " + f"cryptographic implementation crate {self.package!r}" + ) + + +def dependency_package( + key: str, + value: object, + workspace_packages: dict[str, str], +) -> str: + if isinstance(value, str): + return key + if isinstance(value, dict): + package = value.get("package") + if isinstance(package, str): + return package + if value.get("workspace") is True: + return workspace_packages.get(key, key) + return key + + +def table_paths(manifest: dict[str, object]) -> list[tuple[str, object]]: + paths: list[tuple[str, object]] = [] + for table in DEPENDENCY_TABLES: + if table in manifest: + paths.append((table, manifest[table])) + target = manifest.get("target") + if isinstance(target, dict): + for target_name, target_table in target.items(): + if not isinstance(target_table, dict): + continue + for table in DEPENDENCY_TABLES: + if table in target_table: + paths.append((f"target.{target_name}.{table}", target_table[table])) + return paths + + +def collect_workspace_packages(root: Path) -> tuple[dict[str, str], dict[str, object]]: + manifest_path = root / "Cargo.toml" + if not manifest_path.is_file(): + return {}, {} + with manifest_path.open("rb") as file: + manifest = tomllib.load(file) + workspace = manifest.get("workspace") + dependencies = workspace.get("dependencies", {}) if isinstance(workspace, dict) else {} + if not isinstance(dependencies, dict): + dependencies = {} + packages = { + key: dependency_package(key, value, {}) + for key, value in dependencies.items() + } + return packages, dependencies + + +def check_repository(root: Path) -> list[Violation]: + workspace_packages, workspace_dependencies = collect_workspace_packages(root) + violations: list[Violation] = [] + + if workspace_dependencies: + for key, value in workspace_dependencies.items(): + package = dependency_package(key, value, workspace_packages) + if package in FORBIDDEN_PACKAGES: + violations.append( + Violation("Cargo.toml", "workspace.dependencies", key, package) + ) + + for manifest_path in sorted(root.rglob("Cargo.toml")): + relative = manifest_path.relative_to(root) + if any(part in SKIPPED_DIRECTORIES for part in relative.parts): + continue + if relative.parts[0] == "crypto": + continue + with manifest_path.open("rb") as file: + manifest = tomllib.load(file) + for table, dependencies in table_paths(manifest): + if not isinstance(dependencies, dict): + continue + for key, value in dependencies.items(): + package = dependency_package(key, value, workspace_packages) + if package in FORBIDDEN_PACKAGES: + violations.append( + Violation(relative.as_posix(), table, key, package) + ) + + return violations + + +def main(argv: list[str]) -> int: + root = Path(argv[1]) if len(argv) > 1 else Path(__file__).resolve().parents[2] + violations = check_repository(root) + if not violations: + print("crypto dependency boundary is clean") + return 0 + for violation in violations: + print(violation, file=sys.stderr) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv)) diff --git a/.github/scripts/test_check_crypto_dependencies.py b/.github/scripts/test_check_crypto_dependencies.py new file mode 100644 index 00000000..eb09e7dd --- /dev/null +++ b/.github/scripts/test_check_crypto_dependencies.py @@ -0,0 +1,180 @@ +# 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. + +from pathlib import Path +import tempfile +import textwrap +import unittest + +from check_crypto_dependencies import check_repository + + +class CryptoDependencyBoundaryTest(unittest.TestCase): + def check(self, files: dict[str, str]): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + for relative, content in files.items(): + path = root / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(textwrap.dedent(content)) + return check_repository(root) + + def test_normal_dependency_outside_crypto_is_rejected(self): + violations = self.check( + { + "Cargo.toml": """\ + [workspace] + members = ["service"] + """, + "service/Cargo.toml": """\ + [dependencies] + sha2 = "0.11" + """, + } + ) + self.assertEqual( + [(item.table, item.key, item.package) for item in violations], + [("dependencies", "sha2", "sha2")], + ) + + def test_renamed_dependency_is_checked_by_package_name(self): + violations = self.check( + { + "Cargo.toml": """\ + [workspace] + members = ["service"] + """, + "service/Cargo.toml": """\ + [dependencies] + crypto-hash = { package = "sha2", version = "0.11" } + """, + } + ) + self.assertEqual(violations[0].package, "sha2") + self.assertEqual(violations[0].key, "crypto-hash") + + def test_target_specific_build_dependency_is_rejected(self): + violations = self.check( + { + "Cargo.toml": """\ + [workspace] + members = ["service"] + """, + "service/Cargo.toml": """\ + [target.'cfg(unix)'.build-dependencies] + ring = "0.17" + """, + } + ) + self.assertEqual(violations[0].table, "target.cfg(unix).build-dependencies") + self.assertEqual(violations[0].package, "ring") + + def test_unused_workspace_alias_is_rejected(self): + violations = self.check( + { + "Cargo.toml": """\ + [workspace] + members = ["service"] + + [workspace.dependencies] + crypto-random = { package = "getrandom", version = "0.3" } + """, + "service/Cargo.toml": """\ + [dependencies] + anyhow = "1" + """, + } + ) + self.assertEqual( + [(item.table, item.key, item.package) for item in violations], + [("workspace.dependencies", "crypto-random", "getrandom")], + ) + + def test_workspace_alias_used_by_a_member_is_rejected_in_both_places(self): + violations = self.check( + { + "Cargo.toml": """\ + [workspace] + members = ["service"] + + [workspace.dependencies] + crypto-hash = { package = "sha2", version = "0.11" } + """, + "service/Cargo.toml": """\ + [dependencies] + crypto-hash = { workspace = true } + """, + } + ) + self.assertEqual( + {(item.manifest, item.table) for item in violations}, + { + ("Cargo.toml", "workspace.dependencies"), + ("service/Cargo.toml", "dependencies"), + }, + ) + + def test_crypto_members_and_allowed_dependencies_are_ignored(self): + violations = self.check( + { + "Cargo.toml": """\ + [workspace] + members = ["crypto/backend", "service"] + """, + "crypto/backend/Cargo.toml": """\ + [dependencies] + sha2 = "0.11" + rsa = "0.10" + + [target.'cfg(not(target_arch = "wasm32"))'.dependencies] + getrandom = "0.3" + """, + "service/Cargo.toml": """\ + [dependencies] + reqsign-crypto-rustcrypto = { path = "../crypto/backend" } + base64 = "0.23" + zeroize = "1" + + [dev-dependencies] + aws-sigv4 = "1.2" + """, + } + ) + self.assertEqual(violations, []) + + def test_target_directory_is_not_scanned(self): + violations = self.check( + { + "Cargo.toml": """\ + [workspace] + members = ["service"] + """, + "service/Cargo.toml": """\ + [dependencies] + anyhow = "1" + """, + "target/package/example/Cargo.toml": """\ + [dependencies] + sha1 = "0.11" + """, + } + ) + self.assertEqual(violations, []) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1bd77f62..4ce2b385 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -71,6 +71,11 @@ jobs: fi done + - name: Check direct crypto dependencies + run: | + python3 .github/scripts/check_crypto_dependencies.py + python3 -m unittest discover -s .github/scripts -p 'test_check_crypto_dependencies.py' + licenses: runs-on: ubuntu-latest timeout-minutes: 10 diff --git a/Cargo.toml b/Cargo.toml index 8368adb1..7aa999d9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -46,7 +46,6 @@ reqsign-tencent-cos = { version = "3.1.0", path = "services/tencent-cos" } reqsign-volcengine-tos = { version = "3.2.0", path = "services/volcengine-tos" } # Crates.io dependencies -aes-gcm = { version = "0.11", default-features = false, features = ["aes", "alloc"] } anyhow = "1" asyncband = { version = "0.8.0", features = ["mutex"] } base64 = { version = "0.23", default-features = false, features = ["std"] } @@ -56,25 +55,19 @@ dotenvy = "0.15" env_logger = "0.11" form_urlencoded = "1" futures = "0.3" -getrandom = "0.3" hex = "0.4" -hmac = "0.13" http = "1" jiff = "1.0.1" log = "0.4" -p256 = { version = "0.14.0", default-features = false, features = ["ecdsa"] } pem = "4.0" percent-encoding = "2" pretty_assertions = "1.3" prost = "0.14" quick-xml = { version = "0.42.0", features = ["serialize"] } reqwest = { version = "0.13.1", default-features = false } -rsa = { version = "0.10.0", features = ["pkcs1v15", "pkcs5"] } rust-ini = { version = "0.21" } serde = { version = "1", features = ["derive"] } serde_json = { version = "1" } -sha1 = "0.11" -sha2 = { version = "0.11", features = ["oid"] } tempfile = "3.8" tokio = { version = "1", default-features = false } zeroize = "1" diff --git a/crypto/rustcrypto/Cargo.toml b/crypto/rustcrypto/Cargo.toml index 36321b42..a13aa1b8 100644 --- a/crypto/rustcrypto/Cargo.toml +++ b/crypto/rustcrypto/Cargo.toml @@ -28,16 +28,16 @@ repository.workspace = true rust-version.workspace = true [dependencies] -hmac = { workspace = true } -p256 = { workspace = true } +hmac = "0.13" +p256 = { version = "0.14.0", default-features = false, features = ["ecdsa"] } reqsign-core = { workspace = true } -sha1 = { workspace = true } -sha2 = { workspace = true } +sha1 = "0.11" +sha2 = { version = "0.11", features = ["oid"] } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -aes-gcm = { workspace = true } -getrandom = { workspace = true } -rsa = { workspace = true } +aes-gcm = { version = "0.11", default-features = false, features = ["aes", "alloc"] } +getrandom = "0.3" +rsa = { version = "0.10.0", features = ["pkcs1v15", "pkcs5"] } [dev-dependencies] hex = { workspace = true } diff --git a/docs/crypto-provider.md b/docs/crypto-provider.md index c052e993..fe1aad40 100644 --- a/docs/crypto-provider.md +++ b/docs/crypto-provider.md @@ -315,10 +315,17 @@ loading is what makes the missing-provider `ConfigInvalid` visible. ### Core and Service Crates -`reqsign-core` and every `services/*` crate have no production dependency on -`sha1`, `sha2`, `hmac`, `rsa`, `p256`, or `aes-gcm`. Those crates remain -permitted as `dev-dependencies` for verification. Encoding (`base64`, `hex`) and -secret zeroization (`zeroize`) remain ordinary dependencies where needed. +No crate outside `crypto/*` may declare a direct dependency on a raw +cryptographic implementation crate such as `sha1`, `sha2`, `hmac`, `rsa`, +`p256`, `aes-gcm`, `getrandom`, `boring`, `openssl`, `ring`, or `aws-lc-rs`. +This applies to `[dependencies]`, `[dev-dependencies]`, and +`[build-dependencies]`, including target-specific tables, renamed packages, and +root `[workspace.dependencies]`. Provider crates such as +`reqsign-crypto-rustcrypto` remain permitted as dependencies and +dev-dependencies. Encoding (`base64`, `hex`), PEM parsing (`pem`), secret +zeroization (`zeroize`), and interoperability reference harnesses such as +`aws-sigv4` remain ordinary dependencies where needed. Backend crates under +`crypto/*` own primitive verification and cross-backend parity. All former hash and MAC call sites propagate `?` and resolve the provider from the `Context` supplied to the signing, granting, or credential-loading entry @@ -380,6 +387,10 @@ The repository verifies this contract with: confirms that no core or service production graph contains a cryptographic implementation crate, without workspace feature unification hiding optional paths. +- A manifest check rejects direct cryptographic implementation dependencies + outside `crypto/*` in every dependency kind, including target-specific and + renamed declarations, and rejects unused entries in root + `[workspace.dependencies]`. - `cargo check -p reqsign-crypto-rustcrypto --target wasm32-unknown-unknown`, the workspace test suite, doc tests, formatting, clippy with `-D warnings`, license headers, the standalone BoringSSL workflow, and the website provider diff --git a/services/aws-v4/Cargo.toml b/services/aws-v4/Cargo.toml index 627a18ad..4668fbe3 100644 --- a/services/aws-v4/Cargo.toml +++ b/services/aws-v4/Cargo.toml @@ -54,7 +54,6 @@ pretty_assertions = { workspace = true } reqsign-http-send-reqwest = { workspace = true } reqwest = { workspace = true, features = ["default-tls"] } serde_json = { workspace = true } -sha2 = { workspace = true } tempfile = { workspace = true } tokio = { workspace = true, features = ["full"] } diff --git a/services/aws-v4/tests/signing/standard.rs b/services/aws-v4/tests/signing/standard.rs index da644ffc..d32d1db6 100644 --- a/services/aws-v4/tests/signing/standard.rs +++ b/services/aws-v4/tests/signing/standard.rs @@ -19,7 +19,6 @@ use super::{init_signing_test, load_static_credential, send_signed_request}; use anyhow::Result; use http::{Method, Request, StatusCode}; use log::warn; -use sha2::{Digest, Sha256}; use std::str::FromStr; #[tokio::test] @@ -67,7 +66,7 @@ async fn test_put_object() -> Result<()> { let cred = load_static_credential()?; let body = "Hello, World!"; - let body_digest = hex::encode(Sha256::digest(body.as_bytes())); + let body_digest = reqsign_core::hash::hex_sha256(ctx.crypto_provider()?, body.as_bytes())?; let mut req = Request::new(body.to_string()); req.headers_mut().insert( diff --git a/services/aws-v4a/Cargo.toml b/services/aws-v4a/Cargo.toml index 81462414..4cd4e2b3 100644 --- a/services/aws-v4a/Cargo.toml +++ b/services/aws-v4a/Cargo.toml @@ -39,7 +39,6 @@ anyhow = { workspace = true } aws-credential-types = "1.1.8" aws-sigv4 = { version = "1.2.0", features = ["sigv4a"] } form_urlencoded = { workspace = true } -p256 = { workspace = true } pretty_assertions = { workspace = true } reqsign-crypto-rustcrypto = { workspace = true } tokio = { workspace = true, features = ["full"] } diff --git a/services/aws-v4a/src/sign_request.rs b/services/aws-v4a/src/sign_request.rs index da4f0219..2a005a49 100644 --- a/services/aws-v4a/src/sign_request.rs +++ b/services/aws-v4a/src/sign_request.rs @@ -343,11 +343,10 @@ 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; + use reqsign_core::crypto::CryptoProvider; + use std::sync::{Arc, Mutex}; use crate::PercentEncodingMode; @@ -355,6 +354,10 @@ mod tests { const ACCESS_KEY_ID: &str = "AKIDEXAMPLE"; const SECRET_ACCESS_KEY: &str = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"; const HEADER_STRING_TO_SIGN: &str = "AWS4-ECDSA-P256-SHA256\n20150830T123600Z\n20150830/service/aws4_request\ncf59db423e841c8b7e3444158185aa261b724a5c27cbe762676f3eed19f4dc02"; + const SIGNING_KEY_SCALAR: &str = + "7efc8c0e65a324242818c5a50c891c6060b6a00717b7ba3cbe3c5d765be9259c"; + // A fixed DER signature for the published SigV4a signing input above. + const SIGNATURE_DER_HEX: &str = "304502206c8e97f7ed2541ed924ade73b4acf7c40156ee796b1f57156c77319278c93042022100f933779aa3fcbd0279217cd671618552026d099cd2e1770225a5167ac5b6bcfd"; const RAW_QUERY: &str = "slash=%2F&literal-plus=+&double=%252F&dup=first&dup=second&empty=&flag&"; const ENCODING_QUERY: &str = "key=value&slash=%2F&empty=&dup=first&dup=second"; @@ -426,33 +429,103 @@ mod tests { } #[test] - fn signing_key_matches_aws_public_key_vector() -> AnyResult<()> { + fn signing_key_matches_aws_crt_vector() -> AnyResult<()> { let provider = reqsign_crypto_rustcrypto::RustCryptoProvider::new(); let scalar = generate_signing_key(&provider, ACCESS_KEY_ID, SECRET_ACCESS_KEY)?; - let signing_key = P256SigningKey::from_slice(scalar.as_slice()) - .expect("derived scalar must be a valid P-256 key"); - let public_key = signing_key.verifying_key().to_sec1_point(false); - assert_eq!( - hex::encode(public_key.x().expect("uncompressed key has x")), - "b6618f6a65740a99e650b33b6b4b5bd0d43b176d721a3edfea7e7d2d56d936b1" - ); - assert_eq!( - hex::encode(public_key.y().expect("uncompressed key has y")), - "865ed22a7eadc9c5cb9d2cbaca1b3699139fedc5043dc6661864218330c8e518" - ); + // The scalar uniquely determines the AWS CRT public key (x, y); this + // fixed value is the KDF output for the published get-vanilla vector. + assert_eq!(hex::encode(scalar.as_slice()), SIGNING_KEY_SCALAR); + Ok(()) + } + + #[test] + fn signature_input_and_der_hex_are_recorded() -> AnyResult<()> { + let der = hex::decode(SIGNATURE_DER_HEX)?; + let provider = RecordingProvider::returning(der.clone()); + let scalar = *generate_signing_key( + &reqsign_crypto_rustcrypto::RustCryptoProvider::new(), + ACCESS_KEY_ID, + SECRET_ACCESS_KEY, + )?; 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"); - signing_key - .verifying_key() - .verify(HEADER_STRING_TO_SIGN.as_bytes(), &signature) - .expect("generated signature must verify"); + + assert_eq!(signature, SIGNATURE_DER_HEX); + let calls = provider.calls(); + assert_eq!(calls.len(), 1); + assert_eq!(calls[0].scalar, scalar); + assert_eq!(calls[0].message, HEADER_STRING_TO_SIGN.as_bytes()); + assert_eq!(calls[0].signature, der); Ok(()) } + #[derive(Clone, Debug)] + struct EcdsaCall { + scalar: [u8; 32], + message: Vec, + signature: Vec, + } + + #[derive(Clone, Debug, Default)] + struct RecordingProvider { + calls: Arc>>, + response: Option>, + } + + impl RecordingProvider { + fn new() -> Self { + Self::default() + } + + fn returning(signature: Vec) -> Self { + Self { + response: Some(signature), + ..Self::default() + } + } + + fn calls(&self) -> Vec { + self.calls.lock().expect("lock poisoned").clone() + } + } + + impl CryptoProvider for RecordingProvider { + fn sha1(&self, input: &[u8]) -> reqsign_core::Result<[u8; 20]> { + reqsign_crypto_rustcrypto::RustCryptoProvider::new().sha1(input) + } + + fn sha256(&self, input: &[u8]) -> reqsign_core::Result<[u8; 32]> { + reqsign_crypto_rustcrypto::RustCryptoProvider::new().sha256(input) + } + + fn hmac_sha1(&self, key: &[u8], input: &[u8]) -> reqsign_core::Result<[u8; 20]> { + reqsign_crypto_rustcrypto::RustCryptoProvider::new().hmac_sha1(key, input) + } + + fn hmac_sha256(&self, key: &[u8], input: &[u8]) -> reqsign_core::Result<[u8; 32]> { + reqsign_crypto_rustcrypto::RustCryptoProvider::new().hmac_sha256(key, input) + } + + fn ecdsa_p256_sha256_sign( + &self, + private_key_scalar: &[u8; 32], + message: &[u8], + ) -> reqsign_core::Result> { + let signature = match &self.response { + Some(signature) => signature.clone(), + None => reqsign_crypto_rustcrypto::RustCryptoProvider::new() + .ecdsa_p256_sha256_sign(private_key_scalar, message)?, + }; + self.calls.lock().expect("lock poisoned").push(EcdsaCall { + scalar: *private_key_scalar, + message: message.to_vec(), + signature: signature.clone(), + }); + Ok(signature) + } + } + #[tokio::test] async fn signs_headers_with_regionless_scope() -> AnyResult<()> { let mut parts = Request::get("https://example.amazonaws.com/") @@ -540,7 +613,11 @@ mod tests { ) } - fn verify_encoding_signature(request: &Request<()>, string_to_sign: &str) -> AnyResult<()> { + fn verify_encoding_signature( + request: &Request<()>, + string_to_sign: &str, + provider: &RecordingProvider, + ) -> AnyResult<()> { let signature = if let Some(authorization) = request.headers().get(header::AUTHORIZATION) { authorization .to_str()? @@ -555,19 +632,21 @@ mod tests { .1 .into_owned() }; - let signature_bytes = hex::decode(signature)?; - let signature = DerSignature::try_from(signature_bytes.as_slice()) - .expect("signature must use DER encoding"); - 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!( - signing_key - .verifying_key() - .verify(string_to_sign.as_bytes(), &signature) - .is_ok(), - "signature must verify the expected canonical request for {}", + + let calls = provider.calls(); + assert_eq!(calls.len(), 1, "one ECDSA call per signed request"); + let call = &calls[0]; + assert_eq!(hex::encode(call.scalar), SIGNING_KEY_SCALAR); + assert_eq!( + call.message, + string_to_sign.as_bytes(), + "signature input must match the independently assembled canonical request for {}", + request.uri(), + ); + assert_eq!( + signature, + hex::encode(&call.signature), + "wire signature must be the provider's DER bytes as hex for {}", request.uri(), ); Ok(()) @@ -656,10 +735,11 @@ mod tests { let uri = format!("https://example.amazonaws.com{path}?{ENCODING_QUERY}"); let expected = sign_with_aws_sdk(&uri, sdk_mode, expires_in)?; let (mut parts, body) = Request::get(&uri).body(())?.into_parts(); + let provider = RecordingProvider::new(); let request_signer = signer().with_percent_encoding_mode(mode); request_signer .sign_request( - &crate::test_context(), + &crate::test_context().with_crypto(provider.clone()), &mut parts, Some(&credential()), expires_in, @@ -681,11 +761,10 @@ mod tests { assert_eq!(actual.uri().to_string(), uri); } - // ECDSA signatures may differ. Both must verify against the - // same literal canonical path, not merely have equal fields. + // The AWS SDK uses a different ECDSA nonce, so compare its + // fields above and verify our signature input independently. let string_to_sign = encoding_string_to_sign(canonical_path, expires_in); - verify_encoding_signature(&expected, &string_to_sign)?; - verify_encoding_signature(&actual, &string_to_sign)?; + verify_encoding_signature(&actual, &string_to_sign, &provider)?; } } } @@ -709,10 +788,11 @@ mod tests { for expires_in in [None, Some(Duration::from_secs(3600))] { let uri = format!("https://example.amazonaws.com{path}?{ENCODING_QUERY}"); let (mut parts, body) = Request::get(&uri).body(())?.into_parts(); + let provider = RecordingProvider::new(); let request_signer = signer().with_percent_encoding_mode(mode); request_signer .sign_request( - &crate::test_context(), + &crate::test_context().with_crypto(provider.clone()), &mut parts, Some(&credential()), expires_in, @@ -734,6 +814,7 @@ mod tests { verify_encoding_signature( &actual, &encoding_string_to_sign(canonical_path, expires_in), + &provider, )?; } } diff --git a/services/azure-storage/Cargo.toml b/services/azure-storage/Cargo.toml index 171fc0bc..b944f85b 100644 --- a/services/azure-storage/Cargo.toml +++ b/services/azure-storage/Cargo.toml @@ -50,5 +50,4 @@ 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 b0dc4421..39b407c1 100644 --- a/services/azure-storage/src/provide_credential/client_certificate.rs +++ b/services/azure-storage/src/provide_credential/client_certificate.rs @@ -362,15 +362,11 @@ mod tests { #[test] fn client_assertion_is_three_unpadded_verifiable_segments_for_both_pem_formats() { - use rsa::Generate; - use rsa::PrivateKey; - use rsa::pkcs1::EncodeRsaPrivateKey; - use rsa::pkcs1v15::{Signature, VerifyingKey}; - use rsa::pkcs8::{EncodePrivateKey, LineEnding}; - use rsa::sha2::Sha256; - use rsa::signature::Verifier; - - let key = PrivateKey::generate(); + const RSA_PKCS8: &[u8] = include_bytes!("../../tests/fixtures/rsa_pkcs8.pem"); + const RSA_PKCS1: &[u8] = include_bytes!("../../tests/fixtures/rsa_pkcs1.pem"); + // Fixed RS256 vector for the fixture key. The signature was cross-checked + // with an independent RSA implementation before being recorded here. + const EXPECTED_JWT: &str = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsIng1dCI6Ijcxd3N5NGxsS0l6dFZyd25qa0U5RGMyVDY4YyJ9.eyJhdWQiOiJodHRwczovL2V4YW1wbGUuY29tL3Rva2VuIiwiZXhwIjoxLCJpc3MiOiJjbGllbnQiLCJqdGkiOiJqdGkiLCJuYmYiOjAsInN1YiI6ImNsaWVudCJ9.XrtIVf1jpj4EdPs4uEKh_MpYwk3ItE8ggsRe5ra4uTt4sRPIiKoNjGxG4FEJ_3Olo61tOhiBAxabdvq4Wo0JMEsrH2npV558kds9TYnsBdYKTPrWyqmJLRHAgDS5HW7shbCclHyKYPJUGbPCDmW14lCjZMWDP0ClJ6KoQjnkiO8R5RbhnqadxpDxPGJajQ1TMvlh55b8uTl8nY9MRJKCbZzFoGeYZOOET-Xasw73XKIlm0vb-Ke-GXvJMtjsfseMP5hP8RIRb8eKFHppta8FiAVEF_GJjLx7CmsRgoHjkl5UqwA86VW4NBwNj32XeSoVXtHQGBvXK3SV4aKgR9PWBg"; let provider = reqsign_crypto_rustcrypto::RustCryptoProvider::new(); let certificate_provider = ClientCertificateCredentialProvider::new(); let cert_der = b"test certificate"; @@ -391,19 +387,12 @@ mod tests { 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"), - ] { + for pem in [RSA_PKCS8, RSA_PKCS1] { let jwt = ClientCertificateCredentialProvider::encode_rs256_jws( - &provider, - &header, - &claims, - pem.as_bytes(), + &provider, &header, &claims, pem, ) .expect("JWT encoding must succeed"); + assert_eq!(jwt, EXPECTED_JWT); let parts = jwt.split('.').collect::>(); assert_eq!(parts.len(), 3); assert!(parts.iter().all(|part| !part.contains('='))); @@ -432,16 +421,6 @@ mod tests { "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"); } } diff --git a/services/azure-storage/tests/fixtures/rsa_pkcs1.pem b/services/azure-storage/tests/fixtures/rsa_pkcs1.pem new file mode 100644 index 00000000..e288b7c1 --- /dev/null +++ b/services/azure-storage/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/services/azure-storage/tests/fixtures/rsa_pkcs8.pem b/services/azure-storage/tests/fixtures/rsa_pkcs8.pem new file mode 100644 index 00000000..97f97b4d --- /dev/null +++ b/services/azure-storage/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/services/google/Cargo.toml b/services/google/Cargo.toml index 690ec7c1..7cb739ac 100644 --- a/services/google/Cargo.toml +++ b/services/google/Cargo.toml @@ -54,7 +54,6 @@ tokio = { workspace = true, features = ["time"] } zeroize = { workspace = true, optional = true } [dev-dependencies] -aes-gcm = { workspace = true, features = ["zeroize"] } asyncband = { workspace = true, features = ["semaphore"] } dotenvy = { workspace = true } env_logger = { workspace = true } @@ -62,5 +61,4 @@ 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/src/credential_access_boundary/client_side.rs b/services/google/src/credential_access_boundary/client_side.rs index 2b3ff4ee..0fd4bacd 100644 --- a/services/google/src/credential_access_boundary/client_side.rs +++ b/services/google/src/credential_access_boundary/client_side.rs @@ -1072,8 +1072,6 @@ 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}; @@ -1083,10 +1081,105 @@ mod tests { use bytes::Bytes; use http::header::{AUTHORIZATION, HeaderMap}; use reqsign_core::{ErrorKind, Granter, HttpSend, ProvideCredential, Signer, time::Timestamp}; + use reqsign_crypto_rustcrypto::RustCryptoProvider; use super::*; use crate::{CredentialAccessBoundaryPermissions, RequestSigner, ServiceAccount}; + // Protobuf for one bucket-wide viewer rule on example-bucket. + const VIEWER_GRANT_PROTO: &[u8] = &[ + 10, 95, 10, 58, 47, 47, 115, 116, 111, 114, 97, 103, 101, 46, 103, 111, 111, 103, 108, 101, + 97, 112, 105, 115, 46, 99, 111, 109, 47, 112, 114, 111, 106, 101, 99, 116, 115, 47, 95, 47, + 98, 117, 99, 107, 101, 116, 115, 47, 101, 120, 97, 109, 112, 108, 101, 45, 98, 117, 99, + 107, 101, 116, 18, 33, 105, 110, 82, 111, 108, 101, 58, 114, 111, 108, 101, 115, 47, 115, + 116, 111, 114, 97, 103, 101, 46, 111, 98, 106, 101, 99, 116, 86, 105, 101, 119, 101, 114, + ]; + + #[derive(Clone, Debug, Default)] + struct AesCall { + key: Vec, + nonce: [u8; AES_GCM_NONCE_BYTES], + aad: Vec, + plaintext: Vec, + } + + #[derive(Clone, Debug, Default)] + struct TestCryptoProvider { + aes_calls: Arc>>, + } + + impl TestCryptoProvider { + fn new() -> Self { + Self::default() + } + + fn aes_calls(&self) -> Vec { + self.aes_calls.lock().expect("lock poisoned").clone() + } + } + + impl crypto::CryptoProvider for TestCryptoProvider { + fn sha1(&self, input: &[u8]) -> Result<[u8; 20]> { + RustCryptoProvider::new().sha1(input) + } + + fn sha256(&self, input: &[u8]) -> Result<[u8; 32]> { + RustCryptoProvider::new().sha256(input) + } + + fn hmac_sha1(&self, key: &[u8], input: &[u8]) -> Result<[u8; 20]> { + RustCryptoProvider::new().hmac_sha1(key, input) + } + + fn hmac_sha256(&self, key: &[u8], input: &[u8]) -> Result<[u8; 32]> { + RustCryptoProvider::new().hmac_sha256(key, input) + } + + fn rsa_pkcs1v15_sha256_sign( + &self, + private_key_pem: &[u8], + message: &[u8], + ) -> Result> { + RustCryptoProvider::new().rsa_pkcs1v15_sha256_sign(private_key_pem, message) + } + + fn ecdsa_p256_sha256_sign( + &self, + private_key_scalar: &[u8; 32], + message: &[u8], + ) -> Result> { + RustCryptoProvider::new().ecdsa_p256_sha256_sign(private_key_scalar, message) + } + + fn aes_gcm_encrypt( + &self, + key: &[u8], + nonce: &[u8; 12], + aad: &[u8], + plaintext: &[u8], + ) -> Result> { + self.aes_calls.lock().expect("lock poisoned").push(AesCall { + key: key.to_vec(), + nonce: *nonce, + aad: aad.to_vec(), + plaintext: plaintext.to_vec(), + }); + // Keep the plaintext recoverable while still returning the + // ciphertext||tag shape the production framing expects. + let mut output = plaintext.to_vec(); + output.extend_from_slice(&[0x5a; 16]); + Ok(output) + } + + fn fill_random(&self, dest: &mut [u8]) -> Result<()> { + RustCryptoProvider::new().fill_random(dest) + } + } + + fn test_context() -> Context { + Context::new().with_crypto(TestCryptoProvider::new()) + } + // This is the access-boundary session key returned by Google's // MockStsTransport in google-auth-library-java. It is a serialized Tink // AES-256-GCM keyset and contains no production credential material. @@ -1330,17 +1423,15 @@ mod tests { .try_into() .expect("nonce must have the expected length"); let ciphertext = &encrypted[nonce_offset + AES_GCM_NONCE_BYTES..]; - let plaintext = match key.key_value.len() { - 16 => Aes128Gcm::new_from_slice(&key.key_value) - .expect("AES-128 key must initialize") - .decrypt(&Array(nonce), ciphertext), - 32 => Aes256Gcm::new_from_slice(&key.key_value) - .expect("AES-256 key must initialize") - .decrypt(&Array(nonce), ciphertext), - _ => panic!("unexpected test key length"), - } - .expect("restrictions must decrypt"); - let restrictions = ClientSideAccessBoundary::decode(plaintext.as_slice()) + assert!( + matches!(key.key_value.len(), 16 | 32), + "Tink session key must select AES-128 or AES-256" + ); + // TestCryptoProvider returns plaintext||tag so the framing can be + // inspected without a second AES implementation in this crate. + assert!(ciphertext.ends_with(&[0x5a; 16])); + let plaintext = &ciphertext[..ciphertext.len() - 16]; + let restrictions = ClientSideAccessBoundary::decode(plaintext) .expect("restrictions must be a CAB protobuf"); (intermediary.to_string(), nonce, restrictions) } @@ -1373,6 +1464,55 @@ mod tests { ) } + #[tokio::test] + async fn captures_tink_key_nonce_aad_and_plaintext() -> Result<()> { + let now = timestamp("2030-01-01T00:00:00Z"); + let provider = TestCryptoProvider::new(); + let http = MockHttpSend::new([success_response("intermediary", Some(3600))]); + let operation = ClientSideCredentialAccessBoundaryGranter::new(viewer_bucket_grant()) + .with_time(now) + .with_nonces([[7; AES_GCM_NONCE_BYTES]]); + + let output = operation + .grant_credential( + &Context::new() + .with_crypto(provider.clone()) + .with_http_send(http), + &source_token("source", Some(now + Duration::from_secs(2 * 60 * 60))), + None, + ) + .await + .expect("client-side grant must succeed"); + + let calls = provider.aes_calls(); + assert_eq!(calls.len(), 1); + let key = TinkAesGcmKey::parse(GOOGLE_AUTH_LIBRARY_SESSION_KEY) + .expect("official session key must parse"); + assert_eq!(calls[0].key, key.key_value.as_slice()); + assert_eq!(calls[0].nonce, [7; AES_GCM_NONCE_BYTES]); + assert!(calls[0].aad.is_empty()); + assert_eq!(calls[0].plaintext, VIEWER_GRANT_PROTO); + + let token = &output_token(&output).access_token; + let (_, encoded) = token + .split_once('.') + .expect("client-issued token must contain two parts"); + let encrypted = URL_SAFE_NO_PAD + .decode(encoded) + .expect("restrictions must be unpadded base64url"); + assert_eq!( + encrypted, + [ + key.output_prefix.as_slice(), + &[7; AES_GCM_NONCE_BYTES], + VIEWER_GRANT_PROTO, + &[0x5a; 16], + ] + .concat() + ); + Ok(()) + } + #[test] fn matches_google_auth_library_tink_aes_gcm_vector() { let key = TinkAesGcmKey::parse(GOOGLE_AUTH_LIBRARY_SESSION_KEY) @@ -1432,11 +1572,7 @@ mod tests { let source = source_token("source+token/with=reserved", Some(source_expiry)); operation - .grant_credential( - &crate::test_context().with_http_send(http.clone()), - &source, - None, - ) + .grant_credential(&test_context().with_http_send(http.clone()), &source, None) .await .expect("client-side grant must succeed"); @@ -1490,7 +1626,7 @@ mod tests { let http = MockHttpSend::new([success_response("intermediary", Some(3600))]); let output = operation .grant_credential( - &crate::test_context().with_http_send(http), + &test_context().with_http_send(http), &source_token("source", Some(now + Duration::from_secs(2 * 60 * 60))), None, ) @@ -1605,7 +1741,7 @@ mod tests { .with_nonces([[9; AES_GCM_NONCE_BYTES]]); let output = operation .grant_credential( - &crate::test_context().with_http_send(MockHttpSend::new([success_response( + &test_context().with_http_send(MockHttpSend::new([success_response( "intermediary", Some(3600), )])), @@ -1651,7 +1787,7 @@ mod tests { .with_time(now); let err = operation .grant_credential( - &crate::test_context().with_http_send(http.clone()), + &test_context().with_http_send(http.clone()), &source_token("source", Some(now + Duration::from_secs(2 * 60 * 60))), None, ) @@ -1666,7 +1802,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 = crate::test_context().with_http_send(http.clone()); + let ctx = test_context().with_http_send(http.clone()); let operation = ClientSideCredentialAccessBoundaryGranter::new(viewer_bucket_grant()).with_time(now); let valid_token = Token { @@ -1745,7 +1881,7 @@ mod tests { .with_nonces([[4; AES_GCM_NONCE_BYTES]]); let output = operation .grant_credential( - &crate::test_context().with_http_send(MockHttpSend::new([success_response( + &test_context().with_http_send(MockHttpSend::new([success_response( "intermediary", Some(MAX_ACCESS_TOKEN_LIFETIME.as_secs()), )])), @@ -1781,7 +1917,7 @@ mod tests { let explicit = operation .grant_credential( - &crate::test_context().with_http_send(MockHttpSend::new([success_response( + &test_context().with_http_send(MockHttpSend::new([success_response( "explicit", Some(3600), )])), @@ -1801,7 +1937,7 @@ mod tests { .with_time_after_request(response_time); let err = missing_expiration_operation .grant_credential( - &crate::test_context() + &test_context() .with_http_send(MockHttpSend::new([success_response("inherited", None)])), &source, None, @@ -1817,7 +1953,7 @@ mod tests { .with_nonces([[3; AES_GCM_NONCE_BYTES]]); let clamped = clamped_operation .grant_credential( - &crate::test_context().with_http_send(MockHttpSend::new([success_response( + &test_context().with_http_send(MockHttpSend::new([success_response( "clamped", Some(3 * 60 * 60), )])), @@ -1853,7 +1989,7 @@ mod tests { let http = MockHttpSend::new([response]); let err = ClientSideCredentialAccessBoundaryGranter::new(viewer_bucket_grant()) .with_time(now) - .grant_credential(&crate::test_context().with_http_send(http), &source, None) + .grant_credential(&test_context().with_http_send(http), &source, None) .await .expect_err("malformed response must fail"); assert_eq!(err.kind(), ErrorKind::Unexpected); @@ -1925,17 +2061,18 @@ mod tests { ]; for key in keys { - 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"); + let err = + ClientSideCredentialAccessBoundaryGranter::new(viewer_bucket_grant()) + .with_time(now) + .grant_credential( + &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)); } @@ -1951,7 +2088,7 @@ mod tests { .with_time_after_request(now + Duration::from_secs(31 * 60)); let err = post_io .grant_credential( - &crate::test_context().with_http_send(MockHttpSend::new([success_response( + &test_context().with_http_send(MockHttpSend::new([success_response( "intermediary", Some(3600), )])), @@ -1968,7 +2105,7 @@ mod tests { .with_nonces([[4; AES_GCM_NONCE_BYTES]]); let err = post_generation .grant_credential( - &crate::test_context().with_http_send(MockHttpSend::new([success_response( + &test_context().with_http_send(MockHttpSend::new([success_response( "intermediary", Some(60 * 60), )])), @@ -1988,7 +2125,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 = crate::test_context().with_http_send(http.clone()); + let ctx = test_context().with_http_send(http.clone()); let first = operation .grant_credential(&ctx, &source, None) @@ -2028,7 +2165,7 @@ mod tests { [3; AES_GCM_NONCE_BYTES], ]); let source = source_token("source", Some(now + Duration::from_secs(3 * 60 * 60))); - let ctx = crate::test_context().with_http_send(http.clone()); + let ctx = test_context().with_http_send(http.clone()); let first = operation .grant_credential(&ctx, &source, None) @@ -2067,7 +2204,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 = crate::test_context().with_http_send(http.clone()); + let ctx = test_context().with_http_send(http.clone()); operation .grant_credential(&ctx, &source, None) .await @@ -2098,7 +2235,7 @@ mod tests { (0..INTERMEDIARY_CACHE_CAPACITY + 2) .map(|index| [index as u8; AES_GCM_NONCE_BYTES]), ); - let ctx = crate::test_context().with_http_send(http.clone()); + let ctx = test_context().with_http_send(http.clone()); let source_expiry = now + Duration::from_secs(2 * 60 * 60); for index in 0..=INTERMEDIARY_CACHE_CAPACITY { @@ -2154,7 +2291,7 @@ mod tests { [2; AES_GCM_NONCE_BYTES], [3; AES_GCM_NONCE_BYTES], ]); - let ctx = crate::test_context().with_http_send(http.clone()); + let ctx = 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)); @@ -2189,7 +2326,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 = crate::test_context().with_http_send(http.clone()); + let ctx = test_context().with_http_send(http.clone()); let expiry = now + Duration::from_secs(2 * 60 * 60); let first = tokio::spawn({ @@ -2241,7 +2378,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 = crate::test_context().with_http_send(http.clone()); + let ctx = 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 { @@ -2287,7 +2424,7 @@ mod tests { let operation = ClientSideCredentialAccessBoundaryGranter::new(viewer_bucket_grant()) .with_time(now) .with_nonces([[3; AES_GCM_NONCE_BYTES]]); - let ctx = crate::test_context().with_http_send(http.clone()); + let ctx = test_context().with_http_send(http.clone()); let source = source_token("source", Some(now + Duration::from_secs(2 * 60 * 60))); let leader = tokio::spawn({ @@ -2334,7 +2471,7 @@ mod tests { let operation = ClientSideCredentialAccessBoundaryGranter::new(viewer_bucket_grant()) .with_time(now) .with_nonces([[5; AES_GCM_NONCE_BYTES]]); - let ctx = crate::test_context().with_http_send(http.clone()); + let ctx = test_context().with_http_send(http.clone()); let source = source_token("source", Some(now + Duration::from_secs(2 * 60 * 60))); let cancelled = { @@ -2382,7 +2519,7 @@ mod tests { "tenant/", CredentialAccessBoundaryPermissions::OBJECT_VIEWER, )); - let ctx = crate::test_context().with_http_send(http.clone()); + let ctx = test_context().with_http_send(http.clone()); let source = source_token("source", Some(now + Duration::from_secs(2 * 60 * 60))); let bucket_output = bucket @@ -2413,7 +2550,7 @@ mod tests { let (provider, provider_calls) = FixedCredentialProvider::new(source); let http = MockHttpSend::new([success_response("intermediary", Some(3600))]); let granter = Granter::new( - crate::test_context().with_http_send(http.clone()), + 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]]), @@ -2439,7 +2576,7 @@ mod tests { .with_nonces([[8; AES_GCM_NONCE_BYTES]]); let output = operation .grant_credential( - &crate::test_context().with_http_send(MockHttpSend::new([success_response( + &test_context().with_http_send(MockHttpSend::new([success_response( "intermediary", Some(3600), )])), @@ -2450,11 +2587,7 @@ 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( - crate::test_context(), - provider, - RequestSigner::new("storage"), - ); + let signer = Signer::new(test_context(), provider, RequestSigner::new("storage")); let mut parts = http::Request::get("https://storage.googleapis.com/example-bucket/customer/object") .body(()) @@ -2481,7 +2614,7 @@ mod tests { ClientSideCredentialAccessBoundaryGranter::new(viewer_bucket_grant()).with_time(now); let err = operation .grant_credential( - &crate::test_context().with_http_send(MockHttpSend::new([response( + &test_context().with_http_send(MockHttpSend::new([response( http::StatusCode::BAD_REQUEST, r#"{"error":"invalid_grant","error_description":"source-secret raw-response-secret"}"#, )])), @@ -2497,7 +2630,7 @@ mod tests { let err = operation .grant_credential( - &crate::test_context().with_http_send(SecretTransportError), + &test_context().with_http_send(SecretTransportError), &source, None, ) @@ -2526,11 +2659,7 @@ mod tests { ); let http = MockHttpSend::new([success_response("intermediary-secret", Some(3600))]); let output = operation - .grant_credential( - &crate::test_context().with_http_send(http.clone()), - &source, - None, - ) + .grant_credential(&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/jwt.rs b/services/google/src/jwt.rs index 3f365b88..69ff78a5 100644 --- a/services/google/src/jwt.rs +++ b/services/google/src/jwt.rs @@ -61,15 +61,14 @@ mod tests { use base64::engine::general_purpose::URL_SAFE_NO_PAD; use reqsign_core::ErrorKind; use reqsign_crypto_rustcrypto::RustCryptoProvider; - use rsa::Generate; - use rsa::PrivateKey; - use rsa::pkcs1::EncodeRsaPrivateKey; - use rsa::pkcs1v15::{Signature, VerifyingKey}; - use rsa::pkcs8::{EncodePrivateKey, LineEnding}; - use rsa::sha2::Sha256; - use rsa::signature::Verifier; use serde::Serialize; + const RSA_PKCS8: &[u8] = include_bytes!("../tests/fixtures/rsa_pkcs8.pem"); + const RSA_PKCS1: &[u8] = include_bytes!("../tests/fixtures/rsa_pkcs1.pem"); + // Fixed RS256 vector for the fixture key. The signature was cross-checked + // with an independent RSA implementation before being recorded here. + const EXPECTED_JWT: &str = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzaWduZXJAZXhhbXBsZS5jb20iLCJzY29wZSI6Imh0dHBzOi8vd3d3Lmdvb2dsZWFwaXMuY29tL2F1dGgvZGV2c3RvcmFnZS5yZWFkX3dyaXRlIiwiYXVkIjoiaHR0cHM6Ly9vYXV0aDIuZ29vZ2xlYXBpcy5jb20vdG9rZW4iLCJleHAiOjEsImlhdCI6MH0.dbgmn-wCYhHG77IXPjkokZQ6c5zh9d5aZNm9x7VuBYKh3xHNyg33416VjStvOu9f5dFgJOar_V6PR_zkdP7uEUz9ZY_sd1G6Yz3bomInSYpHm05dHRr-b5Sa0MiqWusmfl-8LYJQe_hVi6PXPM0cMFUi1OyAQslUm74_HbJGnsTtrUb7hdsX6KBfDzaUB414sMjYoai8rsyqbqUrq1-7aDnmAVzPmMtBzANdncj3the_yD_-r1hPK5cbj0roz-DtrDHzrIacikeYnu26-RY2xLNB-qiwzlHbGuMAOTLfBsnu3t9-E-aFO9bf8pkKLWl38vsAhHqMxcYo6BxbQpkghg"; + #[derive(Serialize)] struct Header<'a> { alg: &'a str, @@ -85,10 +84,6 @@ mod tests { iat: u64, } - fn private_key() -> PrivateKey { - PrivateKey::generate() - } - fn decode_json(segment: &str) -> serde_json::Value { serde_json::from_slice( &URL_SAFE_NO_PAD @@ -100,7 +95,6 @@ mod tests { #[test] fn formats_three_unpadded_verifiable_segments_for_both_pem_formats() { - let key = private_key(); let provider = RustCryptoProvider::new(); let header = Header { alg: "RS256", @@ -114,14 +108,10 @@ mod tests { 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"); + for pem in [RSA_PKCS8, RSA_PKCS1] { + let jwt = + encode_rs256(&provider, &header, &claims, pem).expect("JWT encoding must succeed"); + assert_eq!(jwt, EXPECTED_JWT); let parts = jwt.split('.').collect::>(); assert_eq!(parts.len(), 3); assert!(parts.iter().all(|part| !part.contains('='))); @@ -139,16 +129,6 @@ mod tests { "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"); } } diff --git a/services/google/src/provide_credential/service_account_token.rs b/services/google/src/provide_credential/service_account_token.rs index 65dd4e7f..ff72cd76 100644 --- a/services/google/src/provide_credential/service_account_token.rs +++ b/services/google/src/provide_credential/service_account_token.rs @@ -352,9 +352,6 @@ mod tests { use http::{HeaderMap, Method}; use reqsign_core::hash::base64_decode; use reqsign_core::{ErrorKind, FileRead, Granter, HttpSend, StaticEnv, time::Timestamp}; - use rsa::Generate; - use rsa::PrivateKey; - use rsa::pkcs8::{EncodePrivateKey, LineEnding}; use serde_json::Value; use crate::{ @@ -445,13 +442,8 @@ mod tests { } fn service_account() -> ServiceAccount { - let key = PrivateKey::generate(); - let private_key = key - .to_pkcs8_pem(LineEnding::LF) - .expect("test RSA key must encode") - .to_string(); ServiceAccount { - private_key, + private_key: include_str!("../../tests/fixtures/rsa_pkcs8.pem").to_string(), client_email: "provider@example.iam.gserviceaccount.com".to_string(), } } diff --git a/services/google/src/sign_request.rs b/services/google/src/sign_request.rs index 9966aed7..87ed474a 100644 --- a/services/google/src/sign_request.rs +++ b/services/google/src/sign_request.rs @@ -909,8 +909,6 @@ mod tests { use bytes::Bytes; use http::header; use reqsign_core::{ErrorKind, HttpSend, ProvideCredential, Signer}; - use rsa::Generate; - use rsa::pkcs8::{EncodePrivateKey, LineEnding}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; @@ -1291,12 +1289,8 @@ mod tests { #[tokio::test] async fn service_account_exchange_preserves_optional_expiration_response() -> Result<()> { - let private_key = rsa::PrivateKey::generate() - .to_pkcs8_pem(LineEnding::LF) - .expect("private key must encode") - .to_string(); let credential = Credential::with_service_account(ServiceAccount { - private_key, + private_key: include_str!("../tests/fixtures/rsa_pkcs8.pem").to_string(), client_email: "signer@example.iam.gserviceaccount.com".to_string(), }); let mut parts = http::Request::get("https://storage.googleapis.com/bucket/object") @@ -1418,12 +1412,15 @@ mod tests { } fn test_service_account(client_email: &str) -> ServiceAccount { - let private_key = rsa::PrivateKey::generate() - .to_pkcs8_pem(LineEnding::LF) - .expect("private key must encode") - .to_string(); ServiceAccount { - private_key, + private_key: include_str!("../tests/fixtures/rsa_pkcs8.pem").to_string(), + client_email: client_email.to_string(), + } + } + + fn test_service_account_with_alternate_key(client_email: &str) -> ServiceAccount { + ServiceAccount { + private_key: include_str!("../tests/fixtures/rsa_pkcs8_alt.pem").to_string(), client_email: client_email.to_string(), } } @@ -1933,7 +1930,8 @@ mod tests { 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)); + let key_2 = + Credential::with_service_account(test_service_account_with_alternate_key(email)); let signer = RequestSigner::new("storage"); let mut parts = http::Request::get("https://storage.googleapis.com/bucket/object") diff --git a/services/google/tests/fixtures/rsa_pkcs1.pem b/services/google/tests/fixtures/rsa_pkcs1.pem new file mode 100644 index 00000000..e288b7c1 --- /dev/null +++ b/services/google/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/services/google/tests/fixtures/rsa_pkcs8.pem b/services/google/tests/fixtures/rsa_pkcs8.pem new file mode 100644 index 00000000..97f97b4d --- /dev/null +++ b/services/google/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/services/google/tests/fixtures/rsa_pkcs8_alt.pem b/services/google/tests/fixtures/rsa_pkcs8_alt.pem new file mode 100644 index 00000000..8a4fa33f --- /dev/null +++ b/services/google/tests/fixtures/rsa_pkcs8_alt.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDCafkFcf/LcTab +anS0+ykbN1Oj/N/vM08ikn949bMw8wgB+L0Ae0aEcb1v4W5xNdfWPoW2dqMwqwPv +jId/OxpHlT7usqfGYIkAiXjG11sog53fG3cz86F5WAoli0K88E04GGIfhW4kOvcC +7G3WAcaXd0bjoQmpje4Fc0P+fMbNFSIOweDdBEX7rG2al3KhUl73ktb2zFusO3Ug +SA9woIhxHiOxP18jtOsFXZUNaC4/1fhM/iVOZb8+uwIiqGbZHBQDaRQexX4PUC4K +1BcPLHeyJxTf/Wn4jp24b4E+hkG2d8ZhKaEcDR8xbE3NukxpjAUyHWYZGKqb6QRY +hsFgIuCLAgMBAAECggEAFNlQ1hd9yIn5bVz9wLjclX7EmVCm4oaR79GzxOYzKMaE +rygce17nrDrBsiwD8DUc0pd9jG3tnexWbYvtrfnJyC/GV3UmTpJkrtTknwz89CZ6 +jttprahswnrBX88EQbHS03dd8nvDLjR6mpV98+uDKhQlsIdBENitKWgikbnnh0To +XWJpGqwQDzGYkR1dDuK9Z8XDcs1msQogRktpeHS/H8t9kfjWwUoQd1mQoM/pdA/K +7sBXen4VofUGiIZ3hKHv4PQgxEc5A58d0aQQUpgnuMwolw9UJ/ojjPb7OgrYWueY +CXnWEZ6q/2wD/EJ8byhVGGyFMCjPel1IoIwVNLoc/QKBgQD0WpdLiBAUVAmHANMw +PHhw5SR15lvsS4yZf5aGcbBfnk9y/gh+IZ3zenxwvd7+HwzjA0sAejcdoRU8X0nM +xcVWFfxDxT63d+fl/hCGmVifQ26aznTPjz1B/HFP4e26i5fRyAPp57Sy4Bx6a9L0 +K8KRCOBNN5W10LOpXNtcRXazhwKBgQDLrg4eInHZ7zYrTWql3HWtmwlVqSyTZd/I +hQpMh4FXCHBWJ8DByZIruvWKYjn485EzmQwjv4oCuqLPcCzWfRaBmYa1wcTL8H3i +MMSiU7RNWIxdRdMPUvXdOJCW6dGGRaSUOLkjN8qDfiHTEaFiOPzC13LQT1nMFSdL +s/QVa2oz3QKBgQDW8Y1eyqxiRV4wHGCpcLf9jwNYlq9Ll1VxfRM65mzgX5DBtYZg +9U9M6vTl849heIzMcIwcOmWbMaRNfACeGWYyCJrkPnCh0N7zqF5/GAsl5Zo4oN2N +6xFWpypBu5pz2vFMfqY6rjB8nLlQUuK5GHlJPUaZhgiya4hutZjcfNoipwKBgAPA +TeRCMCSaYj4D6/3oBIbQ/ygDuJ1yV9/Ci4EDUd9/eUos60DmbHm/tLv6uSSbn8X6 +gJ277lfEhjEZ2MmOfjae1DtOuUgkQr1CtqxirERsaBFjstJqbbrISulsnv5BFBni +vY4nfeRUE11myrkbYZRZEXVCsN2wWgvr4YfvdYJFAoGBAOqMhpU0I0dhuxKz8Xiq +RzWXfxg6i73tAEyqOROpE1YVv/6KFKW/u2E5lHiarQ9UdlixQsU6eOvx2OqgAdaK +X7l3rnmC4w5QHCvbCwTV0zyRcqiylaJCiV41JFWI8zRzPraK2JG8jbIgqwPvMAFw +Yda4kN95XfxGCb5S3Ut/Eo8o +-----END PRIVATE KEY----- diff --git a/services/google/tests/oauth_token_endpoint.rs b/services/google/tests/oauth_token_endpoint.rs index 75c96855..32052373 100644 --- a/services/google/tests/oauth_token_endpoint.rs +++ b/services/google/tests/oauth_token_endpoint.rs @@ -17,7 +17,7 @@ mod common; -use std::sync::{Arc, Mutex, OnceLock}; +use std::sync::{Arc, Mutex}; use bytes::Bytes; use http::{Request, Response, StatusCode}; @@ -29,9 +29,6 @@ use reqsign_google::{ ServerSideCredentialAccessBoundaryGranter, ServiceAccount, ServiceAccountTokenCredentialProvider, StaticCredentialProvider, }; -use rsa::Generate; -use rsa::PrivateKey; -use rsa::pkcs8::{EncodePrivateKey, LineEnding}; use serde::Deserialize; use serde_json::{Value, json}; @@ -63,16 +60,8 @@ impl HttpSend for MockHttp { } fn service_account() -> ServiceAccount { - static KEY: OnceLock = OnceLock::new(); ServiceAccount { - private_key: KEY - .get_or_init(|| { - PrivateKey::generate() - .to_pkcs8_pem(LineEnding::LF) - .unwrap() - .to_string() - }) - .clone(), + private_key: include_str!("fixtures/rsa_pkcs8.pem").into(), client_email: "test@example.iam.gserviceaccount.com".into(), } } diff --git a/services/oracle/Cargo.toml b/services/oracle/Cargo.toml index 23d50c05..83da4ee2 100644 --- a/services/oracle/Cargo.toml +++ b/services/oracle/Cargo.toml @@ -37,7 +37,6 @@ rust-ini = { workspace = true } [dev-dependencies] env_logger = "0.11" reqsign-crypto-rustcrypto = { workspace = true } -rsa = { workspace = true } reqsign-file-read-tokio = { workspace = true } reqsign-http-send-reqwest = { workspace = true } tokio = { version = "1", features = ["test-util", "macros", "rt-multi-thread"] } diff --git a/services/oracle/src/sign_request.rs b/services/oracle/src/sign_request.rs index 91fa3dee..b2f0bf78 100644 --- a/services/oracle/src/sign_request.rs +++ b/services/oracle/src/sign_request.rs @@ -196,8 +196,6 @@ fn single_header_value<'a>(headers: &'a HeaderMap, name: &HeaderName) -> Result< mod tests { use super::*; use reqsign_core::FileRead; - use rsa::Generate; - use rsa::pkcs8::{EncodePrivateKey, LineEnding}; 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=&"; @@ -236,13 +234,11 @@ mod tests { string_to_sign.contains(&format!("(request-target): get /object%2Fname?{RAW_QUERY}")) ); - let private_key = rsa::PrivateKey::generate(); - let private_key = private_key - .to_pkcs8_pem(LineEnding::LF) - .expect("private key must encode") - .as_bytes() - .to_vec(); - let ctx = crate::test_context().with_file_read(StaticFileRead(private_key)); + let ctx = crate::test_context().with_file_read(StaticFileRead( + include_str!("../tests/fixtures/rsa-2048-pkcs8.pem") + .as_bytes() + .to_vec(), + )); let mut parts = http::Request::get(&original_uri).body(())?.into_parts().0; RequestSigner::new() diff --git a/services/oracle/tests/common/mod.rs b/services/oracle/tests/common/mod.rs index 864b1164..243c485b 100644 --- a/services/oracle/tests/common/mod.rs +++ b/services/oracle/tests/common/mod.rs @@ -15,8 +15,89 @@ // specific language governing permissions and limitations // under the License. -use reqsign_core::Context; +use std::sync::{Arc, Mutex}; + +use reqsign_core::crypto::CryptoProvider; +use reqsign_core::{Context, Result}; +use reqsign_crypto_rustcrypto::RustCryptoProvider; pub fn test_context() -> Context { - Context::new().with_crypto(reqsign_crypto_rustcrypto::RustCryptoProvider::new()) + Context::new().with_crypto(RustCryptoProvider::new()) +} + +#[allow(dead_code)] +#[derive(Clone, Debug)] +pub struct RsaCall { + pub pem: Vec, + pub message: Vec, + pub signature: Vec, +} + +/// Delegates every operation to RustCrypto while recording RSA signing calls. +#[allow(dead_code)] +#[derive(Clone, Debug, Default)] +pub struct RecordingProvider { + rsa_calls: Arc>>, +} + +#[allow(dead_code)] +impl RecordingProvider { + pub fn new() -> Self { + Self::default() + } + + pub fn rsa_calls(&self) -> Vec { + self.rsa_calls.lock().expect("lock poisoned").clone() + } +} + +impl CryptoProvider for RecordingProvider { + fn sha1(&self, input: &[u8]) -> Result<[u8; 20]> { + RustCryptoProvider::new().sha1(input) + } + + fn sha256(&self, input: &[u8]) -> Result<[u8; 32]> { + RustCryptoProvider::new().sha256(input) + } + + fn hmac_sha1(&self, key: &[u8], input: &[u8]) -> Result<[u8; 20]> { + RustCryptoProvider::new().hmac_sha1(key, input) + } + + fn hmac_sha256(&self, key: &[u8], input: &[u8]) -> Result<[u8; 32]> { + RustCryptoProvider::new().hmac_sha256(key, input) + } + + fn rsa_pkcs1v15_sha256_sign(&self, private_key_pem: &[u8], message: &[u8]) -> Result> { + let signature = + RustCryptoProvider::new().rsa_pkcs1v15_sha256_sign(private_key_pem, message)?; + self.rsa_calls.lock().expect("lock poisoned").push(RsaCall { + pem: private_key_pem.to_vec(), + message: message.to_vec(), + signature: signature.clone(), + }); + Ok(signature) + } + + fn ecdsa_p256_sha256_sign( + &self, + private_key_scalar: &[u8; 32], + message: &[u8], + ) -> Result> { + RustCryptoProvider::new().ecdsa_p256_sha256_sign(private_key_scalar, message) + } + + fn aes_gcm_encrypt( + &self, + key: &[u8], + nonce: &[u8; 12], + aad: &[u8], + plaintext: &[u8], + ) -> Result> { + RustCryptoProvider::new().aes_gcm_encrypt(key, nonce, aad, plaintext) + } + + fn fill_random(&self, dest: &mut [u8]) -> Result<()> { + RustCryptoProvider::new().fill_random(dest) + } } diff --git a/services/oracle/tests/config_profiles.rs b/services/oracle/tests/config_profiles.rs index 2910be49..0703e9a7 100644 --- a/services/oracle/tests/config_profiles.rs +++ b/services/oracle/tests/config_profiles.rs @@ -21,6 +21,7 @@ use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::time::Duration; +use crate::common::RecordingProvider; use base64::{Engine as _, engine::general_purpose::STANDARD}; use http::header::{AUTHORIZATION, DATE}; use reqsign_core::time::Timestamp; @@ -30,12 +31,6 @@ use reqsign_core::{ use reqsign_oracle::{ ConfigFileCredentialProvider, Credential, DefaultCredentialProvider, RequestSigner, }; -use rsa::Generate; -use rsa::PrivateKey; -use rsa::pkcs1v15::{Signature, VerifyingKey}; -use rsa::pkcs8::{EncodePrivateKey, LineEnding}; -use rsa::sha2::Sha256; -use rsa::signature::Verifier; const CONFIG_PATH: &str = "/synthetic/oci/config"; const DEFAULT_KEY: &str = "/synthetic/keys/default.pem"; @@ -397,12 +392,11 @@ async fn default_chain_loads_inherited_profile_and_respects_removed_slot() -> Re #[tokio::test] async fn inherited_profile_produces_a_verifiable_signed_request() -> anyhow::Result<()> { - let key = PrivateKey::generate(); + const RSA_PKCS8_PEM: &str = include_str!("fixtures/rsa-2048-pkcs8.pem"); let (ctx, files) = context(&(defaults() + "[ADMIN]\nuser=admin-user\n"), Some("ADMIN")); - files.insert( - DEFAULT_KEY, - key.to_pkcs8_pem(LineEnding::LF)?.as_bytes().to_vec(), - ); + files.insert(DEFAULT_KEY, RSA_PKCS8_PEM.as_bytes().to_vec()); + let provider = RecordingProvider::new(); + let ctx = ctx.with_crypto(provider.clone()); let mut parts = http::Request::get("https://iaas.example.com/instances?name=a%2Fb&name=c+d") .header("x-original", "preserved") .body(())? @@ -424,15 +418,17 @@ async fn inherited_profile_produces_a_verifiable_signed_request() -> anyhow::Res .and_then(|value| value.strip_suffix('"')) .expect("signature must exist"); let signature = STANDARD.decode(signature)?; - let signature = Signature::try_from(signature.as_slice())?; let signing_input = format!( "date: {}\n(request-target): get {}\nhost: {}", parts.headers[DATE].to_str()?, original_uri.path_and_query().unwrap(), original_uri.authority().unwrap() ); - VerifyingKey::::new(key.to_public_key()) - .verify(signing_input.as_bytes(), &signature)?; + let calls = provider.rsa_calls(); + assert_eq!(calls.len(), 1); + assert_eq!(calls[0].pem, RSA_PKCS8_PEM.as_bytes()); + assert_eq!(calls[0].message, signing_input.as_bytes()); + assert_eq!(signature, calls[0].signature); assert_eq!(files.reads(), [CONFIG_PATH, DEFAULT_KEY]); Ok(()) } diff --git a/services/oracle/tests/fixtures/rsa-2048-pkcs1.pem b/services/oracle/tests/fixtures/rsa-2048-pkcs1.pem new file mode 100644 index 00000000..e288b7c1 --- /dev/null +++ b/services/oracle/tests/fixtures/rsa-2048-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/services/oracle/tests/fixtures/rsa-2048-pkcs8.pem b/services/oracle/tests/fixtures/rsa-2048-pkcs8.pem new file mode 100644 index 00000000..97f97b4d --- /dev/null +++ b/services/oracle/tests/fixtures/rsa-2048-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/services/oracle/tests/fixtures/rsa-2048-public.pem b/services/oracle/tests/fixtures/rsa-2048-public.pem new file mode 100644 index 00000000..90fa9f46 --- /dev/null +++ b/services/oracle/tests/fixtures/rsa-2048-public.pem @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnsTjUJMw3j44uhVLoMcT +JUCXXaF2OrjThNXEthwArpnNhkrd3TGKamz7VIUsXYL3lB6OgOCGsodWARqGfINI +9B4oY0am6AfQvW4w4g2UZuoDPwhNR3cx20JOFV8/XVvHkaQcTtG9tZeHrkb6f3Kx +UOPjYquU88JVWOJJTW70T540HW6aj+kOWR4UulJKHPRvkgxQX85f4UHXnz0XWvLm +KWSNbMv2EyOHwMGnTDk5fwxevkAr14iUuWBRiku/54n1FaXc28fbJOdrml22NUWq +C8AZZuJo3pFmdZ35Xzzbf636SNh3inbLN7ys4h1or2yZq5UsiKUkQLBKFNrD5iLw +rQIDAQAB +-----END PUBLIC KEY----- diff --git a/services/oracle/tests/private_key_formats.rs b/services/oracle/tests/private_key_formats.rs index 1e9940da..4b1b91da 100644 --- a/services/oracle/tests/private_key_formats.rs +++ b/services/oracle/tests/private_key_formats.rs @@ -17,31 +17,21 @@ mod common; -use std::sync::LazyLock; - use base64::{Engine as _, engine::general_purpose::STANDARD}; use http::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, DATE}; use http::{Method, request::Parts}; use reqsign_core::{Context, ErrorKind, FileRead, Result, SignRequest, Signer}; use reqsign_oracle::{Credential, RequestSigner, StaticCredentialProvider}; -use rsa::Generate; -use rsa::PrivateKey; -use rsa::pkcs1::EncodeRsaPrivateKey; -use rsa::pkcs1v15::{Signature, VerifyingKey}; -use rsa::pkcs8::{EncodePrivateKey, EncodePublicKey, LineEnding}; -use rsa::sha2::Sha256; -use rsa::signature::Verifier; + +use crate::common::RecordingProvider; const KEY_PATH: &str = "test-key.pem"; +const RSA_PKCS8_PEM: &str = include_str!("fixtures/rsa-2048-pkcs8.pem"); +const RSA_PKCS1_PEM: &str = include_str!("fixtures/rsa-2048-pkcs1.pem"); +const RSA_PUBLIC_PEM: &str = include_str!("fixtures/rsa-2048-public.pem"); const RSA_ENCRYPTED_PEM: &str = include_str!("fixtures/rsa-2048-pkcs8-encrypted.pem"); const REQUEST_URI: &str = "https://iaas.example.com:8443/20160918/instances?name=a%2Fb&name=c+%20d"; -fn private_key() -> &'static PrivateKey { - // Generate one ephemeral key for all formats; never read a developer's OCI files. - static KEY: LazyLock = LazyLock::new(PrivateKey::generate); - &KEY -} - struct KeyFile(Vec); impl std::fmt::Debug for KeyFile { @@ -57,8 +47,10 @@ impl FileRead for KeyFile { } } -fn context(pem: &str) -> Context { - crate::common::test_context().with_file_read(KeyFile(pem.as_bytes().to_vec())) +fn context(pem: &[u8], provider: RecordingProvider) -> Context { + crate::common::test_context() + .with_file_read(KeyFile(pem.to_vec())) + .with_crypto(provider) } fn credential() -> Credential { @@ -71,13 +63,17 @@ fn credential() -> Credential { } } -async fn sign(pem: &str, parts: &mut Parts) -> Result<()> { +async fn sign(pem: &[u8], parts: &mut Parts, provider: &RecordingProvider) -> Result<()> { let cred = credential(); - let provider = + let credential_provider = StaticCredentialProvider::new(&cred.user, &cred.tenancy, &cred.key_file, &cred.fingerprint); - Signer::new(context(pem), provider, RequestSigner::new()) - .sign(parts, None) - .await + Signer::new( + context(pem, provider.clone()), + credential_provider, + RequestSigner::new(), + ) + .sign(parts, None) + .await } fn authorization_param<'a>(authorization: &'a str, name: &str) -> anyhow::Result<&'a str> { @@ -98,7 +94,11 @@ fn signed_headers(parts: &Parts) -> anyhow::Result<&str> { authorization_param(authorization, "headers") } -fn verify_authorization(parts: &Parts) -> anyhow::Result<()> { +fn verify_authorization( + parts: &Parts, + pem: &[u8], + provider: &RecordingProvider, +) -> anyhow::Result<()> { let authorization = parts.headers[AUTHORIZATION].to_str()?; let mut signing_input = String::new(); @@ -145,14 +145,15 @@ fn verify_authorization(parts: &Parts) -> anyhow::Result<()> { } let signature_bytes = STANDARD.decode(authorization_param(authorization, "signature")?)?; - let signature = Signature::try_from(signature_bytes.as_slice())?; - let verifier = VerifyingKey::::new(private_key().to_public_key()); - verifier.verify(signing_input.as_bytes(), &signature)?; - assert!(verifier.verify(b"different request", &signature).is_err()); + let calls = provider.rsa_calls(); + assert_eq!(calls.len(), 1, "one RSA call per signed request"); + assert_eq!(calls[0].pem, pem); + assert_eq!(calls[0].message, signing_input.as_bytes()); + assert_eq!(signature_bytes, calls[0].signature); Ok(()) } -async fn verify_signed_request(pem: &str) -> anyhow::Result<()> { +async fn verify_signed_request(pem: &[u8]) -> anyhow::Result<()> { // Include a port, repeated query keys and escaped bytes in the signed target. let mut parts = http::Request::get(REQUEST_URI) .header("x-original", "preserved") @@ -160,8 +161,9 @@ async fn verify_signed_request(pem: &str) -> anyhow::Result<()> { .into_parts() .0; let original_uri = parts.uri.clone(); + let provider = RecordingProvider::new(); - sign(pem, &mut parts).await?; + sign(pem, &mut parts, &provider).await?; assert_eq!(parts.uri, original_uri); assert_eq!(parts.headers["x-original"], "preserved"); @@ -171,31 +173,39 @@ async fn verify_signed_request(pem: &str) -> anyhow::Result<()> { assert!(authorization.contains("algorithm=\"rsa-sha256\"")); assert_eq!(signed_headers(&parts)?, "date (request-target) host"); - verify_authorization(&parts)?; + verify_authorization(&parts, pem, &provider)?; Ok(()) } #[tokio::test] async fn pkcs1_private_keys_produce_valid_signatures() -> anyhow::Result<()> { - for line_ending in [LineEnding::LF, LineEnding::CRLF] { - let pem = private_key().to_pkcs1_pem(line_ending)?; - verify_signed_request(&pem).await?; + for crlf in [false, true] { + let pem = if crlf { + RSA_PKCS1_PEM.replace('\n', "\r\n") + } else { + RSA_PKCS1_PEM.to_string() + }; + verify_signed_request(pem.as_bytes()).await?; } Ok(()) } #[tokio::test] async fn pkcs8_private_keys_produce_valid_signatures() -> anyhow::Result<()> { - for line_ending in [LineEnding::LF, LineEnding::CRLF] { - let pem = private_key().to_pkcs8_pem(line_ending)?; - verify_signed_request(&pem).await?; + for crlf in [false, true] { + let pem = if crlf { + RSA_PKCS8_PEM.replace('\n', "\r\n") + } else { + RSA_PKCS8_PEM.to_string() + }; + verify_signed_request(pem.as_bytes()).await?; } Ok(()) } #[tokio::test] async fn post_signs_caller_supplied_body_metadata() -> anyhow::Result<()> { - let pem = private_key().to_pkcs8_pem(LineEnding::LF)?; + let pem = RSA_PKCS8_PEM; let body_sha256 = "V9Z20UJTvkvpJ50flBzKE32+6m2zJjweHpDMX/U4Uy0="; let mut parts = http::Request::builder() .method(Method::POST) @@ -209,7 +219,8 @@ async fn post_signs_caller_supplied_body_metadata() -> anyhow::Result<()> { .0; let original_uri = parts.uri.clone(); - sign(&pem, &mut parts).await?; + let provider = RecordingProvider::new(); + sign(pem.as_bytes(), &mut parts, &provider).await?; assert_eq!(parts.uri, original_uri); assert_eq!(parts.headers["x-original"], "preserved"); @@ -220,13 +231,13 @@ async fn post_signs_caller_supplied_body_metadata() -> anyhow::Result<()> { signed_headers(&parts)?, "date (request-target) host content-length content-type x-content-sha256" ); - verify_authorization(&parts)?; + verify_authorization(&parts, pem.as_bytes(), &provider)?; Ok(()) } #[tokio::test] async fn object_storage_put_without_body_metadata_keeps_generic_headers() -> anyhow::Result<()> { - let pem = private_key().to_pkcs8_pem(LineEnding::LF)?; + let pem = RSA_PKCS8_PEM; let mut parts = http::Request::put( "https://namespace.compat.objectstorage.us-phoenix-1.oraclecloud.com/b/bucket/o/object", ) @@ -235,20 +246,21 @@ async fn object_storage_put_without_body_metadata_keeps_generic_headers() -> any .into_parts() .0; - sign(&pem, &mut parts).await?; + let provider = RecordingProvider::new(); + sign(pem.as_bytes(), &mut parts, &provider).await?; assert_eq!(parts.headers["x-original"], "preserved"); assert_eq!(signed_headers(&parts)?, "date (request-target) host"); assert!(!parts.headers.contains_key(CONTENT_LENGTH)); assert!(!parts.headers.contains_key(CONTENT_TYPE)); assert!(!parts.headers.contains_key("x-content-sha256")); - verify_authorization(&parts)?; + verify_authorization(&parts, pem.as_bytes(), &provider)?; Ok(()) } #[tokio::test] async fn object_storage_upload_part_signs_supplied_content_length_only() -> anyhow::Result<()> { - let pem = private_key().to_pkcs8_pem(LineEnding::LF)?; + let pem = RSA_PKCS8_PEM; let mut parts = http::Request::builder() .method(Method::PUT) .uri("https://namespace.compat.objectstorage.us-phoenix-1.oraclecloud.com/b/bucket/o/object?uploadId=upload&partNumber=2") @@ -257,7 +269,8 @@ async fn object_storage_upload_part_signs_supplied_content_length_only() -> anyh .into_parts() .0; - sign(&pem, &mut parts).await?; + let provider = RecordingProvider::new(); + sign(pem.as_bytes(), &mut parts, &provider).await?; assert_eq!(parts.headers[CONTENT_LENGTH], "10485760"); assert_eq!( @@ -266,13 +279,13 @@ async fn object_storage_upload_part_signs_supplied_content_length_only() -> anyh ); assert!(!parts.headers.contains_key(CONTENT_TYPE)); assert!(!parts.headers.contains_key("x-content-sha256")); - verify_authorization(&parts)?; + verify_authorization(&parts, pem.as_bytes(), &provider)?; Ok(()) } #[tokio::test] async fn duplicate_signed_body_header_is_rejected_without_mutation() -> anyhow::Result<()> { - let pem = private_key().to_pkcs8_pem(LineEnding::LF)?; + let pem = RSA_PKCS8_PEM; let mut parts = http::Request::builder() .method(Method::POST) .uri("https://iaas.example.com/20160918/volumeAttachments") @@ -288,7 +301,7 @@ async fn duplicate_signed_body_header_is_rejected_without_mutation() -> anyhow:: .0; let original = parts.clone(); - let error = sign(&pem, &mut parts) + let error = sign(pem.as_bytes(), &mut parts, &RecordingProvider::new()) .await .expect_err("duplicate signed body headers must be rejected"); @@ -300,7 +313,7 @@ async fn duplicate_signed_body_header_is_rejected_without_mutation() -> anyhow:: Ok(()) } -async fn assert_rejected_without_mutation(pem: &str) -> anyhow::Result<()> { +async fn assert_rejected_without_mutation(pem: &[u8]) -> anyhow::Result<()> { let mut parts = http::Request::get("https://iaas.example.com/resource?key=%2F") .header("x-original", "preserved") .header(DATE, "Tue, 01 Jan 2030 00:00:00 GMT") @@ -310,7 +323,12 @@ async fn assert_rejected_without_mutation(pem: &str) -> anyhow::Result<()> { .0; let original = parts.clone(); let error = RequestSigner::new() - .sign_request(&context(pem), &mut parts, Some(&credential()), None) + .sign_request( + &context(pem, RecordingProvider::new()), + &mut parts, + Some(&credential()), + None, + ) .await .expect_err("invalid private key must be rejected"); @@ -324,25 +342,22 @@ async fn assert_rejected_without_mutation(pem: &str) -> anyhow::Result<()> { #[tokio::test] async fn public_keys_are_rejected_without_mutating_request() -> anyhow::Result<()> { - let pem = private_key() - .to_public_key() - .to_public_key_pem(LineEnding::LF)?; - assert_rejected_without_mutation(&pem).await + assert_rejected_without_mutation(RSA_PUBLIC_PEM.as_bytes()).await } #[tokio::test] async fn encrypted_private_keys_are_rejected_without_mutating_request() -> anyhow::Result<()> { - assert_rejected_without_mutation(RSA_ENCRYPTED_PEM).await + assert_rejected_without_mutation(RSA_ENCRYPTED_PEM.as_bytes()).await } #[tokio::test] async fn malformed_private_keys_are_rejected_without_mutating_request() -> anyhow::Result<()> { for pem in ["", "not a private key"] { - assert_rejected_without_mutation(pem).await?; + assert_rejected_without_mutation(pem.as_bytes()).await?; } for label in ["RSA PRIVATE KEY", "PRIVATE KEY"] { let pem = format!("-----BEGIN {label}-----\nbm90LWRlcg==\n-----END {label}-----\n"); - assert_rejected_without_mutation(&pem).await?; + assert_rejected_without_mutation(pem.as_bytes()).await?; } Ok(()) } From 2f96d157f6bfd60b1a7af9e0084fd53f06114595 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:29:37 +0100 Subject: [PATCH 2/2] fix(crypto): close dependency and signing test gaps --- .github/scripts/check_crypto_dependencies.py | 101 ++++++++++++------ .../scripts/test_check_crypto_dependencies.py | 55 ++++++---- docs/crypto-provider.md | 6 +- services/aws-v4a/src/sign_request.rs | 55 +++++++--- services/oracle/tests/private_key_formats.rs | 17 ++- 5 files changed, 148 insertions(+), 86 deletions(-) diff --git a/.github/scripts/check_crypto_dependencies.py b/.github/scripts/check_crypto_dependencies.py index 66c1fcd7..4a2f534e 100644 --- a/.github/scripts/check_crypto_dependencies.py +++ b/.github/scripts/check_crypto_dependencies.py @@ -18,8 +18,9 @@ """Reject direct cryptographic implementation dependencies outside crypto/*. The check walks every manifest so it sees declarations that Cargo metadata -would omit, including unused workspace entries, renamed packages, target -specific tables, and build/dev dependency kinds. +would omit, including unused workspace entries, standalone workspace +inheritance, renamed packages, target-specific tables, and both Cargo +dependency table spellings. """ from __future__ import annotations @@ -45,7 +46,14 @@ } ) SKIPPED_DIRECTORIES = frozenset({"target", ".git"}) -DEPENDENCY_TABLES = ("dependencies", "dev-dependencies", "build-dependencies") +# Cargo 1.87 accepts both hyphenated and underscored table names. +DEPENDENCY_TABLES = ( + "dependencies", + "dev-dependencies", + "dev_dependencies", + "build-dependencies", + "build_dependencies", +) @dataclass(frozen=True) @@ -70,15 +78,15 @@ def dependency_package( if isinstance(value, str): return key if isinstance(value, dict): + if value.get("workspace") is True: + return workspace_packages.get(key, key) package = value.get("package") if isinstance(package, str): return package - if value.get("workspace") is True: - return workspace_packages.get(key, key) return key -def table_paths(manifest: dict[str, object]) -> list[tuple[str, object]]: +def dependency_tables(manifest: dict[str, object]) -> list[tuple[str, object]]: paths: list[tuple[str, object]] = [] for table in DEPENDENCY_TABLES: if table in manifest: @@ -94,48 +102,71 @@ def table_paths(manifest: dict[str, object]) -> list[tuple[str, object]]: return paths -def collect_workspace_packages(root: Path) -> tuple[dict[str, str], dict[str, object]]: - manifest_path = root / "Cargo.toml" - if not manifest_path.is_file(): - return {}, {} - with manifest_path.open("rb") as file: - manifest = tomllib.load(file) +def workspace_dependencies(manifest: dict[str, object]) -> dict[str, object]: workspace = manifest.get("workspace") - dependencies = workspace.get("dependencies", {}) if isinstance(workspace, dict) else {} - if not isinstance(dependencies, dict): - dependencies = {} - packages = { - key: dependency_package(key, value, {}) - for key, value in dependencies.items() - } - return packages, dependencies + if not isinstance(workspace, dict): + return {} + dependencies = workspace.get("dependencies", {}) + return dependencies if isinstance(dependencies, dict) else {} + + +def parse_manifests(root: Path) -> dict[Path, tuple[Path, dict[str, object]]]: + manifests = {} + for manifest_path in sorted(root.rglob("Cargo.toml")): + relative = manifest_path.relative_to(root) + if any(part in SKIPPED_DIRECTORIES for part in relative.parts): + continue + with manifest_path.open("rb") as file: + manifests[manifest_path] = (relative, tomllib.load(file)) + return manifests + + +def owning_workspace( + manifest_path: Path, + root: Path, + manifests: dict[Path, tuple[Path, dict[str, object]]], +) -> Path | None: + directory = manifest_path.parent + while True: + candidate = directory / "Cargo.toml" + if candidate in manifests and isinstance(manifests[candidate][1].get("workspace"), dict): + return candidate + if directory == root: + return None + directory = directory.parent def check_repository(root: Path) -> list[Violation]: - workspace_packages, workspace_dependencies = collect_workspace_packages(root) + root = root.resolve() + manifests = parse_manifests(root) + workspace_packages = { + path: { + key: dependency_package(key, value, {}) + for key, value in workspace_dependencies(manifest).items() + } + for path, (_, manifest) in manifests.items() + if isinstance(manifest.get("workspace"), dict) + } violations: list[Violation] = [] - if workspace_dependencies: - for key, value in workspace_dependencies.items(): - package = dependency_package(key, value, workspace_packages) + for manifest_path, (relative, manifest) in manifests.items(): + if relative.parts[0] == "crypto": + continue + workspace_path = owning_workspace(manifest_path, root, manifests) + inherited_packages = workspace_packages.get(workspace_path, {}) + + for key, value in workspace_dependencies(manifest).items(): + package = dependency_package(key, value, {}) if package in FORBIDDEN_PACKAGES: violations.append( - Violation("Cargo.toml", "workspace.dependencies", key, package) + Violation(relative.as_posix(), "workspace.dependencies", key, package) ) - for manifest_path in sorted(root.rglob("Cargo.toml")): - relative = manifest_path.relative_to(root) - if any(part in SKIPPED_DIRECTORIES for part in relative.parts): - continue - if relative.parts[0] == "crypto": - continue - with manifest_path.open("rb") as file: - manifest = tomllib.load(file) - for table, dependencies in table_paths(manifest): + for table, dependencies in dependency_tables(manifest): if not isinstance(dependencies, dict): continue for key, value in dependencies.items(): - package = dependency_package(key, value, workspace_packages) + package = dependency_package(key, value, inherited_packages) if package in FORBIDDEN_PACKAGES: violations.append( Violation(relative.as_posix(), table, key, package) diff --git a/.github/scripts/test_check_crypto_dependencies.py b/.github/scripts/test_check_crypto_dependencies.py index eb09e7dd..0d5a962b 100644 --- a/.github/scripts/test_check_crypto_dependencies.py +++ b/.github/scripts/test_check_crypto_dependencies.py @@ -67,21 +67,28 @@ def test_renamed_dependency_is_checked_by_package_name(self): self.assertEqual(violations[0].package, "sha2") self.assertEqual(violations[0].key, "crypto-hash") - def test_target_specific_build_dependency_is_rejected(self): - violations = self.check( - { - "Cargo.toml": """\ - [workspace] - members = ["service"] - """, - "service/Cargo.toml": """\ - [target.'cfg(unix)'.build-dependencies] - ring = "0.17" - """, - } - ) - self.assertEqual(violations[0].table, "target.cfg(unix).build-dependencies") - self.assertEqual(violations[0].package, "ring") + def test_legacy_dependency_table_names_are_rejected(self): + for declared, expected in [ + ("build_dependencies", "build_dependencies"), + ("target.'cfg(unix)'.dev_dependencies", "target.cfg(unix).dev_dependencies"), + ]: + with self.subTest(table=declared): + violations = self.check( + { + "Cargo.toml": """\ + [workspace] + members = ["service"] + """, + "service/Cargo.toml": f"""\ + [{declared}] + backend = {{ package = "sha2", version = "0.11" }} + """, + } + ) + self.assertEqual( + [(item.table, item.key, item.package) for item in violations], + [(expected, "backend", "sha2")], + ) def test_unused_workspace_alias_is_rejected(self): violations = self.check( @@ -104,18 +111,22 @@ def test_unused_workspace_alias_is_rejected(self): [("workspace.dependencies", "crypto-random", "getrandom")], ) - def test_workspace_alias_used_by_a_member_is_rejected_in_both_places(self): + def test_standalone_workspace_inherited_alias_is_rejected_in_both_places(self): violations = self.check( { "Cargo.toml": """\ [workspace] - members = ["service"] + members = [] + exclude = ["tool"] + """, + "tool/Cargo.toml": """\ + [workspace] + resolver = "2" [workspace.dependencies] crypto-hash = { package = "sha2", version = "0.11" } - """, - "service/Cargo.toml": """\ - [dependencies] + + [dev-dependencies] crypto-hash = { workspace = true } """, } @@ -123,8 +134,8 @@ def test_workspace_alias_used_by_a_member_is_rejected_in_both_places(self): self.assertEqual( {(item.manifest, item.table) for item in violations}, { - ("Cargo.toml", "workspace.dependencies"), - ("service/Cargo.toml", "dependencies"), + ("tool/Cargo.toml", "workspace.dependencies"), + ("tool/Cargo.toml", "dev-dependencies"), }, ) diff --git a/docs/crypto-provider.md b/docs/crypto-provider.md index fe1aad40..7b421a18 100644 --- a/docs/crypto-provider.md +++ b/docs/crypto-provider.md @@ -320,8 +320,8 @@ cryptographic implementation crate such as `sha1`, `sha2`, `hmac`, `rsa`, `p256`, `aes-gcm`, `getrandom`, `boring`, `openssl`, `ring`, or `aws-lc-rs`. This applies to `[dependencies]`, `[dev-dependencies]`, and `[build-dependencies]`, including target-specific tables, renamed packages, and -root `[workspace.dependencies]`. Provider crates such as -`reqsign-crypto-rustcrypto` remain permitted as dependencies and +`[workspace.dependencies]` entries in any repo-local workspace. Provider crates +such as `reqsign-crypto-rustcrypto` remain permitted as dependencies and dev-dependencies. Encoding (`base64`, `hex`), PEM parsing (`pem`), secret zeroization (`zeroize`), and interoperability reference harnesses such as `aws-sigv4` remain ordinary dependencies where needed. Backend crates under @@ -389,7 +389,7 @@ The repository verifies this contract with: paths. - A manifest check rejects direct cryptographic implementation dependencies outside `crypto/*` in every dependency kind, including target-specific and - renamed declarations, and rejects unused entries in root + renamed declarations, and rejects unused entries in any repo-local `[workspace.dependencies]`. - `cargo check -p reqsign-crypto-rustcrypto --target wasm32-unknown-unknown`, the workspace test suite, doc tests, formatting, clippy with `-D warnings`, diff --git a/services/aws-v4a/src/sign_request.rs b/services/aws-v4a/src/sign_request.rs index 2a005a49..725e3692 100644 --- a/services/aws-v4a/src/sign_request.rs +++ b/services/aws-v4a/src/sign_request.rs @@ -613,25 +613,46 @@ mod tests { ) } - fn verify_encoding_signature( - request: &Request<()>, - string_to_sign: &str, - provider: &RecordingProvider, - ) -> AnyResult<()> { - let signature = if let Some(authorization) = request.headers().get(header::AUTHORIZATION) { - authorization + fn request_signature(request: &Request<()>) -> AnyResult { + if let Some(authorization) = request.headers().get(header::AUTHORIZATION) { + Ok(authorization .to_str()? .rsplit_once(", Signature=") .expect("authorization must contain signature") .1 - .to_string() + .to_string()) } else { - form_urlencoded::parse(request.uri().query().unwrap_or_default().as_bytes()) - .find(|(key, _)| key == "X-Amz-Signature") - .expect("presigned request must contain signature") - .1 - .into_owned() - }; + Ok( + form_urlencoded::parse(request.uri().query().unwrap_or_default().as_bytes()) + .find(|(key, _)| key == "X-Amz-Signature") + .expect("presigned request must contain signature") + .1 + .into_owned(), + ) + } + } + + fn sdk_signature(string_to_sign: &str) -> String { + let signing_key = v4a::generate_signing_key(ACCESS_KEY_ID, SECRET_ACCESS_KEY); + v4a::calculate_signature(signing_key, string_to_sign.as_bytes()) + } + + fn assert_signature_matches_sdk(request: &Request<()>, string_to_sign: &str) -> AnyResult<()> { + assert_eq!( + request_signature(request)?, + sdk_signature(string_to_sign), + "wire signature must match the AWS SDK signature for the independently assembled canonical request for {}", + request.uri(), + ); + Ok(()) + } + + fn verify_encoding_signature( + request: &Request<()>, + string_to_sign: &str, + provider: &RecordingProvider, + ) -> AnyResult<()> { + let signature = request_signature(request)?; let calls = provider.calls(); assert_eq!(calls.len(), 1, "one ECDSA call per signed request"); @@ -649,6 +670,7 @@ mod tests { "wire signature must be the provider's DER bytes as hex for {}", request.uri(), ); + assert_signature_matches_sdk(request, string_to_sign)?; Ok(()) } @@ -761,9 +783,10 @@ mod tests { assert_eq!(actual.uri().to_string(), uri); } - // The AWS SDK uses a different ECDSA nonce, so compare its - // fields above and verify our signature input independently. + // Compare both signatures against the independently + // assembled canonical request, not just against each other. let string_to_sign = encoding_string_to_sign(canonical_path, expires_in); + assert_signature_matches_sdk(&expected, &string_to_sign)?; verify_encoding_signature(&actual, &string_to_sign, &provider)?; } } diff --git a/services/oracle/tests/private_key_formats.rs b/services/oracle/tests/private_key_formats.rs index 4b1b91da..2261b21d 100644 --- a/services/oracle/tests/private_key_formats.rs +++ b/services/oracle/tests/private_key_formats.rs @@ -53,6 +53,11 @@ fn context(pem: &[u8], provider: RecordingProvider) -> Context { .with_crypto(provider) } +fn pem_with_line_ending(pem: &str, crlf: bool) -> String { + let lf = pem.replace("\r\n", "\n"); + if crlf { lf.replace('\n', "\r\n") } else { lf } +} + fn credential() -> Credential { Credential { tenancy: "test-tenancy".into(), @@ -180,11 +185,7 @@ async fn verify_signed_request(pem: &[u8]) -> anyhow::Result<()> { #[tokio::test] async fn pkcs1_private_keys_produce_valid_signatures() -> anyhow::Result<()> { for crlf in [false, true] { - let pem = if crlf { - RSA_PKCS1_PEM.replace('\n', "\r\n") - } else { - RSA_PKCS1_PEM.to_string() - }; + let pem = pem_with_line_ending(RSA_PKCS1_PEM, crlf); verify_signed_request(pem.as_bytes()).await?; } Ok(()) @@ -193,11 +194,7 @@ async fn pkcs1_private_keys_produce_valid_signatures() -> anyhow::Result<()> { #[tokio::test] async fn pkcs8_private_keys_produce_valid_signatures() -> anyhow::Result<()> { for crlf in [false, true] { - let pem = if crlf { - RSA_PKCS8_PEM.replace('\n', "\r\n") - } else { - RSA_PKCS8_PEM.to_string() - }; + let pem = pem_with_line_ending(RSA_PKCS8_PEM, crlf); verify_signed_request(pem.as_bytes()).await?; } Ok(())