Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(kms): add OCI Vault KMS as a secrets/encryption management backend (#14564)
Jagan9986e5c0c201
diff --git a/Cargo.lock b/Cargo.lockindex c1285ffbcb..caba887210 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3587,6 +3587,7 @@ dependencies = ["hyperswitch_interfaces","hyperswitch_masking","lettre",+ "oci_kms","once_cell","open-feature","prost 0.14.3",@@ -6493,6 +6494,25 @@ dependencies = ["url 2.5.4",]+[[package]]+name = "oci_kms"+version = "0.1.0"+dependencies = [+ "base64 0.22.1",+ "rand 0.8.5",+ "reqwest 0.12.7",+ "rsa",+ "serde",+ "serde_json",+ "sha2",+ "thiserror 1.0.69",+ "time 0.3.41",+ "tokio 1.48.0",+ "tracing",+ "url 2.5.4",+ "zeroize",+]+[[package]]name = "oid-registry"version = "0.7.1"diff --git a/config/config.example.toml b/config/config.example.tomlindex f125cee90f..200abd3f40 100644--- a/config/config.example.toml+++ b/config/config.example.toml@@ -1405,7 +1405,7 @@ region = "us-east-1" # The AWS region used by the AWS S3 for file storagebucket_name = "bucket1" # The AWS S3 bucket name for file storage[secrets_management]-secrets_manager = "aws_kms" # Secrets manager client to be used (no_encryption | aws_kms | hashicorp_vault | gcp_kms)+secrets_manager = "aws_kms" # Secrets manager client to be used (no_encryption | aws_kms | hashicorp_vault | gcp_kms | oci_kms)# Required only if `secrets_manager` above is set to "aws_kms"[secrets_management.aws_kms]@@ -1419,8 +1419,14 @@ location_id = "gcp_kms_location_id" # e.g. "global", "us-east1"key_ring_id = "gcp_kms_key_ring_id"key_id = "gcp_kms_key_id"+# Required only if `secrets_manager` above is set to "oci_kms". Authenticated via OKE+# Workload Identity (ambient) — no credentials go in this config.+[secrets_management.oci_kms]+vault_crypto_endpoint = "https://<vault>-crypto.kms.<region>.oci.oraclecloud.com"+key_id = "oci_kms_key_ocid"+[encryption_management]-encryption_manager = "aws_kms" # Encryption manager client to be used (no_encryption | aws_kms | gcp_kms)+encryption_manager = "aws_kms" # Encryption manager client to be used (no_encryption | aws_kms | gcp_kms | oci_kms)# Required only if `encryption_manager` above is set to "aws_kms"[encryption_management.aws_kms]@@ -1434,6 +1440,12 @@ location_id = "gcp_kms_location_id"key_ring_id = "gcp_kms_key_ring_id"key_id = "gcp_kms_key_id"+# Required only if `encryption_manager` above is set to "oci_kms". Authenticated via+# OKE Workload Identity (ambient) — no credentials go in this config.+[encryption_management.oci_kms]+vault_crypto_endpoint = "https://<vault>-crypto.kms.<region>.oci.oraclecloud.com"+key_id = "oci_kms_key_ocid"+[crm]crm_manager = "hubspot_proxy" # Crm manager client to be useddiff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.tomlindex 05f6cd7b7c..bd58f1a323 100644--- a/config/deployments/env_specific.toml+++ b/config/deployments/env_specific.toml@@ -369,7 +369,7 @@ private_key = "/path/to/private_key.pem"certificate = "/path/to/certificate.pem"[secrets_management]-secrets_manager = "aws_kms" # Secrets manager client to be used (no_encryption | aws_kms | hashicorp_vault | gcp_kms)+secrets_manager = "aws_kms" # Secrets manager client to be used (no_encryption | aws_kms | hashicorp_vault | gcp_kms | oci_kms)# Required only if `secrets_manager` above is set to "aws_kms"[secrets_management.aws_kms]@@ -383,8 +383,14 @@ location_id = "gcp_kms_location_id" # e.g. "global", "us-east1"key_ring_id = "gcp_kms_key_ring_id"key_id = "gcp_kms_key_id"+# Required only if `secrets_manager` above is set to "oci_kms". Authenticated via OKE+# Workload Identity (ambient) — no credentials go in this config.+[secrets_management.oci_kms]+vault_crypto_endpoint = "https://<vault>-crypto.kms.<region>.oci.oraclecloud.com"+key_id = "oci_kms_key_ocid"+[encryption_management]-encryption_manager = "aws_kms" # Encryption manager client to be used (no_encryption | aws_kms | gcp_kms)+encryption_manager = "aws_kms" # Encryption manager client to be used (no_encryption | aws_kms | gcp_kms | oci_kms)# Required only if `encryption_manager` above is set to "aws_kms"[encryption_management.aws_kms]@@ -398,6 +404,12 @@ location_id = "gcp_kms_location_id"key_ring_id = "gcp_kms_key_ring_id"key_id = "gcp_kms_key_id"+# Required only if `encryption_manager` above is set to "oci_kms". Authenticated via+# OKE Workload Identity (ambient) — no credentials go in this config.+[encryption_management.oci_kms]+vault_crypto_endpoint = "https://<vault>-crypto.kms.<region>.oci.oraclecloud.com"+key_id = "oci_kms_key_ocid"+[crm]crm_manager = "hubspot_proxy" # Crm manager client to be useddiff --git a/crates/drainer/Cargo.toml b/crates/drainer/Cargo.tomlindex f7ec8f000d..0b5ba7849e 100644--- a/crates/drainer/Cargo.toml+++ b/crates/drainer/Cargo.toml@@ -9,9 +9,10 @@ license.workspace = true[features]default = ["redis-rs"]-release = ["vergen", "external_services/aws_kms", "gcp_kms"]+release = ["vergen", "external_services/aws_kms", "gcp_kms", "oci_kms"]vergen = ["router_env/vergen"]gcp_kms = ["external_services/gcp_kms"]+oci_kms = ["external_services/oci_kms"]v1 = ["diesel_models/v1", "external_services/v1", "hyperswitch_interfaces/v1", "common_utils/v1", "storage_impl/v1", "storage_impl/olap"]v2 = ["diesel_models/v2", "external_services/v2", "hyperswitch_interfaces/v2", "common_utils/v2", "storage_impl/v2"]fred = ["redis_interface/fred", "redis_interface/metrics", "storage_impl/fred"]diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.tomlindex a436045038..9d26e23f04 100644--- a/crates/external_services/Cargo.toml+++ b/crates/external_services/Cargo.toml@@ -12,6 +12,7 @@ aws_kms = ["dep:aws-config", "dep:aws-sdk-kms"]email = ["dep:aws-config"]aws_s3 = ["dep:aws-config", "dep:aws-sdk-s3"]gcp_kms = ["dep:google-cloud-kms"]+oci_kms = ["dep:oci_kms"]hashicorp-vault = ["dep:vaultrs"]superposition = ["dep:open-feature",@@ -106,6 +107,7 @@ superposition_sdk = { version = "0.115.5", optional = true }common_utils = { version = "0.1.0", path = "../common_utils" }common_enums = { version = "0.1.0", path = "../common_enums" }hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces", default-features = false }+oci_kms = { version = "0.1.0", path = "../oci_kms", optional = true }hyperswitch_masking = "0.0.1"router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields",diff --git a/crates/external_services/src/lib.rs b/crates/external_services/src/lib.rsindex a23b0015cd..c4de17e207 100644--- a/crates/external_services/src/lib.rs+++ b/crates/external_services/src/lib.rs@@ -21,6 +21,8 @@ pub mod http_client;pub mod hubspot_proxy;pub mod managers;pub mod no_encryption;+#[cfg(feature = "oci_kms")]+pub mod oci_kms;#[cfg(feature = "superposition")]pub mod superposition;/// deserializers module_path@@ -131,7 +133,7 @@ pub mod consts {}/// Metrics for interactions with external systems.-#[cfg(any(feature = "aws_kms", feature = "gcp_kms"))]+#[cfg(any(feature = "aws_kms", feature = "gcp_kms", feature = "oci_kms"))]pub mod metrics {use router_env::{counter_metric, global_meter, histogram_metric_f64};@@ -156,6 +158,16 @@ pub mod metrics {histogram_metric_f64!(GCP_KMS_DECRYPT_TIME, GLOBAL_METER); // Histogram for GCP KMS decryption time (in sec)#[cfg(feature = "gcp_kms")]histogram_metric_f64!(GCP_KMS_ENCRYPT_TIME, GLOBAL_METER); // Histogram for GCP KMS encryption time (in sec)++ #[cfg(feature = "oci_kms")]+ counter_metric!(OCI_KMS_DECRYPTION_FAILURES, GLOBAL_METER); // No. of OCI KMS Decryption failures+ #[cfg(feature = "oci_kms")]+ counter_metric!(OCI_KMS_ENCRYPTION_FAILURES, GLOBAL_METER); // No. of OCI KMS Encryption failures++ #[cfg(feature = "oci_kms")]+ histogram_metric_f64!(OCI_KMS_DECRYPT_TIME, GLOBAL_METER); // Histogram for OCI KMS decryption time (in sec)+ #[cfg(feature = "oci_kms")]+ histogram_metric_f64!(OCI_KMS_ENCRYPT_TIME, GLOBAL_METER); // Histogram for OCI KMS encryption time (in sec)}/// Metrics for config-related operationsdiff --git a/crates/external_services/src/managers/encryption_management.rs b/crates/external_services/src/managers/encryption_management.rsindex b76bcc58a5..9cf189eb05 100644--- a/crates/external_services/src/managers/encryption_management.rs+++ b/crates/external_services/src/managers/encryption_management.rs@@ -3,7 +3,7 @@use std::sync::Arc;use common_utils::errors::CustomResult;-#[cfg(feature = "gcp_kms")]+#[cfg(any(feature = "gcp_kms", feature = "oci_kms"))]use error_stack::ResultExt;use hyperswitch_interfaces::encryption_interface::{EncryptionError, EncryptionManagementInterface,@@ -14,6 +14,8 @@ use crate::aws_kms;#[cfg(feature = "gcp_kms")]use crate::gcp_kms;use crate::no_encryption::core::NoEncryption;+#[cfg(feature = "oci_kms")]+use crate::oci_kms;/// Enum representing configuration options for encryption management.#[derive(Debug, Clone, Default, serde::Deserialize)]@@ -34,6 +36,13 @@ pub enum EncryptionManagementConfig {gcp_kms: gcp_kms::core::GcpKmsConfig,},+ /// OCI Vault KMS configuration+ #[cfg(feature = "oci_kms")]+ OciKms {+ /// OCI KMS config+ oci_kms: oci_kms::core::OciKmsConfig,+ },+/// Variant representing no encryption#[default]NoEncryption,@@ -57,6 +66,9 @@ impl EncryptionManagementConfig {#[cfg(feature = "gcp_kms")]Self::GcpKms { gcp_kms } => gcp_kms.validate(),+ #[cfg(feature = "oci_kms")]+ Self::OciKms { oci_kms } => oci_kms.validate(),+Self::NoEncryption => Ok(()),}}@@ -77,6 +89,14 @@ impl EncryptionManagementConfig {.attach_printable("Failed to create GCP KMS client")?,),+ #[cfg(feature = "oci_kms")]+ Self::OciKms { oci_kms } => Arc::new(+ oci_kms::core::OciKmsClient::new(oci_kms)+ .await+ .change_context(EncryptionError::EncryptionFailed)+ .attach_printable("Failed to create OCI KMS client")?,+ ),+Self::NoEncryption => Arc::new(NoEncryption),})}diff --git a/crates/external_services/src/managers/secrets_management.rs b/crates/external_services/src/managers/secrets_management.rsindex 3af62a5f5f..705dbdfd17 100644--- a/crates/external_services/src/managers/secrets_management.rs+++ b/crates/external_services/src/managers/secrets_management.rs@@ -1,7 +1,7 @@//! Secrets management util moduleuse common_utils::errors::CustomResult;-#[cfg(any(feature = "hashicorp-vault", feature = "gcp_kms"))]+#[cfg(any(feature = "hashicorp-vault", feature = "gcp_kms", feature = "oci_kms"))]use error_stack::ResultExt;use hyperswitch_interfaces::secrets_interface::{SecretManagementInterface, SecretsManagementError,@@ -14,6 +14,8 @@ use crate::gcp_kms;#[cfg(feature = "hashicorp-vault")]use crate::hashicorp_vault;use crate::no_encryption::core::NoEncryption;+#[cfg(feature = "oci_kms")]+use crate::oci_kms;/// Enum representing configuration options for secrets management.#[derive(Debug, Clone, Default, serde::Deserialize)]@@ -41,6 +43,13 @@ pub enum SecretsManagementConfig {hc_vault: hashicorp_vault::core::HashiCorpVaultConfig,},+ /// OCI Vault KMS configuration+ #[cfg(feature = "oci_kms")]+ OciKms {+ /// OCI KMS config+ oci_kms: oci_kms::core::OciKmsConfig,+ },+/// Variant representing no encryption#[default]NoEncryption,@@ -56,6 +65,8 @@ impl SecretsManagementConfig {Self::GcpKms { gcp_kms } => gcp_kms.validate(),#[cfg(feature = "hashicorp-vault")]Self::HashiCorpVault { hc_vault } => hc_vault.validate(),+ #[cfg(feature = "oci_kms")]+ Self::OciKms { oci_kms } => oci_kms.validate(),Self::NoEncryption => Ok(()),}}@@ -80,6 +91,11 @@ impl SecretsManagementConfig {.change_context(SecretsManagementError::ClientCreationFailed).map(|inner| -> Box<dyn SecretManagementInterface> { Box::new(inner) })}+ #[cfg(feature = "oci_kms")]+ Self::OciKms { oci_kms } => oci_kms::core::OciKmsClient::new(oci_kms)+ .await+ .change_context(SecretsManagementError::ClientCreationFailed)+ .map(|inner| -> Box<dyn SecretManagementInterface> { Box::new(inner) }),Self::NoEncryption => Ok(Box::new(NoEncryption)),}}diff --git a/crates/external_services/src/oci_kms.rs b/crates/external_services/src/oci_kms.rsnew file mode 100644index 0000000000..8f73cb3d39--- /dev/null+++ b/crates/external_services/src/oci_kms.rs@@ -0,0 +1,4 @@+//! OCI Vault KMS backend, built on the shared `oci_kms` client crate++pub mod core;+pub mod implementers;diff --git a/crates/external_services/src/oci_kms/core.rs b/crates/external_services/src/oci_kms/core.rsnew file mode 100644index 0000000000..208afe0f5e--- /dev/null+++ b/crates/external_services/src/oci_kms/core.rs@@ -0,0 +1,137 @@+//! Hyperswitch adapter over the shared [`oci_kms`](::oci_kms) client.+//!+//! The client itself (authentication, request signing, timeouts and retries) lives in the+//! standalone `oci_kms` crate so other services can share it. This adapter routes its clock+//! and entropy reads through `common_utils`, and adds Hyperswitch's logging and metrics.++use std::{sync::Arc, time::Instant};++use common_utils::errors::CustomResult;+use error_stack::{report, ResultExt};+pub use oci_kms::OciKmsConfig;+use router_env::logger;++use crate::metrics;++/// Client for OCI Vault KMS crypto operations.+#[derive(Clone, Debug)]+pub struct OciKmsClient {+ inner: oci_kms::OciKmsClient,+}++impl OciKmsClient {+ /// Constructs a new client; credentials are resolved lazily per call, not eagerly.+ pub async fn new(config: &OciKmsConfig) -> CustomResult<Self, OciKmsError> {+ let inner = oci_kms::OciKmsClient::with_environment(config, Arc::new(CommonUtilsSeams))+ .map_err(|error| report!(error).change_context(OciKmsError::ClientCreationFailed))?;+ Ok(Self { inner })+ }++ /// Decrypts base64-encoded ciphertext via OCI Vault KMS.+ pub async fn decrypt(&self, data: impl AsRef<[u8]>) -> CustomResult<String, OciKmsError> {+ let start = Instant::now();+ let ciphertext = std::str::from_utf8(data.as_ref())+ .change_context(OciKmsError::Utf8DecodingFailed)+ .attach_printable("Ciphertext input is not valid UTF-8")?;++ let plaintext = self.inner.decrypt(ciphertext).await.map_err(|error| {+ logger::error!(oci_kms_error = %error, "Failed to OCI KMS decrypt data");+ metrics::OCI_KMS_DECRYPTION_FAILURES.add(1, &[]);+ report!(error).change_context(OciKmsError::DecryptionFailed)+ })?;+ let output =+ String::from_utf8(plaintext).change_context(OciKmsError::Utf8DecodingFailed)?;++ metrics::OCI_KMS_DECRYPT_TIME.record(start.elapsed().as_secs_f64(), &[]);++ Ok(output)+ }++ /// Encrypts data via OCI Vault KMS, returning base64-encoded ciphertext.+ pub async fn encrypt(&self, data: impl AsRef<[u8]>) -> CustomResult<String, OciKmsError> {+ let start = Instant::now();++ let ciphertext = self.inner.encrypt(data.as_ref()).await.map_err(|error| {+ logger::error!(oci_kms_error = %error, "Failed to OCI KMS encrypt data");+ metrics::OCI_KMS_ENCRYPTION_FAILURES.add(1, &[]);+ report!(error).change_context(OciKmsError::EncryptionFailed)+ })?;++ metrics::OCI_KMS_ENCRYPT_TIME.record(start.elapsed().as_secs_f64(), &[]);++ Ok(ciphertext)+ }+}++/// Routes the client's clock and entropy reads through `common_utils`, so `deja` can replay+/// them.+#[derive(Debug)]+struct CommonUtilsSeams;++impl oci_kms::Environment for CommonUtilsSeams {+ fn now_unix_timestamp(&self) -> i64 {+ common_utils::date_time::now_unix_timestamp()+ }++ fn random_f64_unit(&self) -> f64 {+ common_utils::generate_random_f64_unit()+ }++ fn random_bytes(&self, len: usize) -> Vec<u8> {+ common_utils::generate_random_bytes(len)+ }+}++/// Errors that could occur during OCI Vault KMS operations.+#[derive(Debug, thiserror::Error)]+pub enum OciKmsError {+ /// An error occurred UTF-8 decoding input or output data.+ #[error("Failed UTF-8 decode of OCI KMS input/output data")]+ Utf8DecodingFailed,++ /// An error occurred when OCI KMS decrypting input data.+ #[error("Failed to OCI KMS decrypt input data")]+ DecryptionFailed,++ /// An error occurred when OCI KMS encrypting input data.+ #[error("Failed to OCI KMS encrypt input data")]+ EncryptionFailed,++ /// Failed while creating the OCI KMS client.+ #[error("Failed to create OCI KMS client")]+ ClientCreationFailed,+}++#[cfg(test)]+mod tests {+ use hyperswitch_interfaces::secrets_interface::SecretManagementInterface;+ use hyperswitch_masking::{PeekInterface, Secret};++ use super::*;++ fn env(name: &str) -> String {+ std::env::var(name).unwrap_or_else(|_| panic!("{name} must be set for live tests"))+ }++ /// The call Hyperswitch makes at startup for every secret in its config, through this+ /// adapter and its `common_utils` seams. Skipped by default; the `oci_kms` crate's `live`+ /// tests document the environment variables.+ #[tokio::test]+ #[ignore = "calls a real OCI Vault"]+ async fn get_secret_decrypts_a_config_secret() {+ let client = OciKmsClient::new(&OciKmsConfig {+ vault_crypto_endpoint: env("OCI_KMS_TEST_CRYPTO_ENDPOINT"),+ key_id: env("OCI_KMS_TEST_KEY_ID"),+ })+ .await+ .expect("client builds");++ let secret = SecretManagementInterface::get_secret(+ &client,+ Secret::new(env("OCI_KMS_TEST_CLI_CIPHERTEXT")),+ )+ .await+ .expect("get_secret succeeds");+ assert_eq!(secret.peek(), &env("OCI_KMS_TEST_CLI_PLAINTEXT"));+ }+}diff --git a/crates/external_services/src/oci_kms/implementers.rs b/crates/external_services/src/oci_kms/implementers.rsnew file mode 100644index 0000000000..f61d419f99--- /dev/null+++ b/crates/external_services/src/oci_kms/implementers.rs@@ -0,0 +1,41 @@+//! Trait implementations for OCI KMS client++use common_utils::errors::CustomResult;+use error_stack::ResultExt;+use hyperswitch_interfaces::{+ encryption_interface::{EncryptionError, EncryptionManagementInterface},+ secrets_interface::{SecretManagementInterface, SecretsManagementError},+};+use hyperswitch_masking::{PeekInterface, Secret};++use crate::oci_kms::core::OciKmsClient;++#[async_trait::async_trait]+impl EncryptionManagementInterface for OciKmsClient {+ async fn encrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError> {+ self.encrypt(input)+ .await+ .change_context(EncryptionError::EncryptionFailed)+ .map(|val| val.into_bytes())+ }++ async fn decrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError> {+ self.decrypt(input)+ .await+ .change_context(EncryptionError::DecryptionFailed)+ .map(|val| val.into_bytes())+ }+}++#[async_trait::async_trait]+impl SecretManagementInterface for OciKmsClient {+ async fn get_secret(+ &self,+ input: Secret<String>,+ ) -> CustomResult<Secret<String>, SecretsManagementError> {+ self.decrypt(input.peek())+ .await+ .change_context(SecretsManagementError::FetchSecretFailed)+ .map(Into::into)+ }+}diff --git a/crates/oci_kms/Cargo.toml b/crates/oci_kms/Cargo.tomlnew file mode 100644index 0000000000..c8160012b3--- /dev/null+++ b/crates/oci_kms/Cargo.toml@@ -0,0 +1,31 @@+[package]+name = "oci_kms"+description = "OCI Vault KMS crypto client: OKE Workload Identity, request signing, encrypt/decrypt and data keys"+version = "0.1.0"+edition.workspace = true+rust-version.workspace = true+readme = "README.md"+license.workspace = true++# Deliberately free of Hyperswitch crates (no `common_utils`, `router_env` or `error-stack`),+# so services outside this workspace can depend on it without pulling in Hyperswitch.+[dependencies]+base64 = "0.22.1"+rand = "0.8.5"+reqwest = { version = "0.12.7", default-features = false, features = ["rustls-tls"] }+rsa = { version = "0.9.8", features = ["sha2"] }+serde = { version = "1.0.219", features = ["derive"] }+serde_json = "1.0.140"+sha2 = "0.10.9"+thiserror = "1.0.69"+time = { version = "0.3.41", features = ["formatting", "macros"] }+tokio = { version = "1.48.0", features = ["rt", "sync", "time"] }+tracing = { workspace = true }+url = "2.5.4"+zeroize = "1.8.1"++[dev-dependencies]+tokio = { version = "1.48.0", features = ["macros", "rt-multi-thread"] }++[lints]+workspace = truediff --git a/crates/oci_kms/README.md b/crates/oci_kms/README.mdnew file mode 100644index 0000000000..2f530a07fc--- /dev/null+++ b/crates/oci_kms/README.md@@ -0,0 +1,42 @@+# OCI KMS++A client for the OCI Vault KMS crypto endpoint, shared by Hyperswitch services that keep their+secrets or data keys under an OCI Vault key.++There is no official OCI Rust SDK, and the community ones don't cover the KMS crypto endpoint, so+this crate implements what an SDK would otherwise hide:++- **Authentication.** Inside Kubernetes, OKE Workload Identity: an ephemeral RSA key pair is+ generated in memory and the pod's service account token is exchanged for a short-lived OCI+ session token. Nothing credential-bearing is written to disk. The service account token and+ cluster CA are read from kubelet's default mount paths; pods that project them elsewhere set+ `OCI_KUBERNETES_SERVICE_ACCOUNT_TOKEN_PATH` and `OCI_KUBERNETES_SERVICE_ACCOUNT_CERT_PATH`+ (the latter is the variable Oracle's SDKs read). Outside Kubernetes (local+ development, CI), the `oci` CLI's `~/.oci/config` (`OCI_CLI_CONFIG_FILE`, `OCI_CLI_PROFILE`).+- **Request signing**, OCI Signature v1.+- **Timeouts and retries**, with jittered exponential backoff on transport errors, 429 and 5xx.++It has no dependency on other Hyperswitch crates, so services outside this workspace can use it.++## Usage++```rust,ignore+let client = oci_kms::OciKmsClient::new(&oci_kms::OciKmsConfig {+ vault_crypto_endpoint: "https://<vault>-crypto.kms.<region>.oci.oraclecloud.com".into(),+ key_id: "ocid1.key.oc1...".into(),+})?;++// Config secrets: ciphertext produced once with `oci kms crypto encrypt`.+let plaintext: Vec<u8> = client.decrypt(ciphertext).await?;++// Envelope encryption: a fresh AES-256 data key, plus the same key wrapped by the vault key.+let data_key = client.generate_data_key().await?;+```++Services that need clock and entropy reads to go through their own instrumented functions (for+example, to make them replayable) pass an `Environment` to `OciKmsClient::with_environment`.++## Testing++Unit tests run with `cargo test -p oci_kms`. Tests against a real vault are `#[ignore]`d and read+their configuration from the environment; see the `live` module in `src/client.rs`.diff --git a/crates/oci_kms/src/client.rs b/crates/oci_kms/src/client.rsnew file mode 100644index 0000000000..1645459dc7--- /dev/null+++ b/crates/oci_kms/src/client.rs@@ -0,0 +1,516 @@+//! The OCI Vault KMS crypto-endpoint client.++use std::sync::Arc;++use base64::Engine;+use serde::{Deserialize, Serialize};+use zeroize::Zeroize;++use crate::{+ config::OciKmsConfig,+ credentials::CredentialCache,+ environment::{Environment, SystemEnvironment},+ error::OciKmsError,+ signing,+ transport::{self, AttemptError},+};++const BASE64_ENGINE: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD;++const ENCRYPT_PATH: &str = "/20180608/encrypt";+const DECRYPT_PATH: &str = "/20180608/decrypt";+const GENERATE_DATA_KEY_PATH: &str = "/20180608/generateDataEncryptionKey";++const ENCRYPTION_ALGORITHM: &str = "AES_256_GCM";+const DATA_KEY_LENGTH: usize = 32;++#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+struct EncryptDataDetails<'a> {+ key_id: &'a str,+ plaintext: String,+ encryption_algorithm: &'static str,+}++#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+struct DecryptDataDetails<'a> {+ key_id: &'a str,+ ciphertext: &'a str,+ encryption_algorithm: &'static str,+}++#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+struct GenerateKeyDetails<'a> {+ key_id: &'a str,+ include_plaintext_key: bool,+ key_shape: KeyShape,+}++#[derive(Serialize)]+struct KeyShape {+ algorithm: &'static str,+ length: usize,+}++#[derive(Deserialize)]+struct EncryptedData {+ ciphertext: String,+}++#[derive(Deserialize)]+struct DecryptedData {+ plaintext: String,+}++#[derive(Deserialize)]+struct GeneratedKey {+ ciphertext: String,+ plaintext: Option<String>,+}++/// A fresh AES-256 data key from [`OciKmsClient::generate_data_key`], for envelope encryption.+///+/// The plaintext key is zeroed on drop and redacted from `Debug`.+pub struct DataKey {+ plaintext: [u8; DATA_KEY_LENGTH],+ ciphertext: String,+}++impl DataKey {+ /// The plaintext key, to encrypt data with locally. Don't store it.+ pub fn plaintext(&self) -> &[u8; DATA_KEY_LENGTH] {+ &self.plaintext+ }++ /// The same key, encrypted under the vault key. Store this, and recover the plaintext+ /// later with [`OciKmsClient::decrypt`].+ pub fn ciphertext(&self) -> &str {+ &self.ciphertext+ }+}++impl Drop for DataKey {+ fn drop(&mut self) {+ self.plaintext.zeroize();+ }+}++impl std::fmt::Debug for DataKey {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("DataKey")+ .field("plaintext", &"<redacted>")+ .field("ciphertext", &self.ciphertext)+ .finish()+ }+}++/// Client for OCI Vault KMS crypto operations.+///+/// Cheap to clone: clones share the HTTP connection pool and the cached credentials.+/// Credentials are resolved on first use, not at construction.+#[derive(Clone)]+pub struct OciKmsClient {+ http_client: reqwest::Client,+ vault_crypto_endpoint: String,+ host: String,+ key_id: String,+ credentials: Arc<CredentialCache>,+ environment: Arc<dyn Environment>,+}++impl std::fmt::Debug for OciKmsClient {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("OciKmsClient")+ .field("vault_crypto_endpoint", &self.vault_crypto_endpoint)+ .field("key_id", &self.key_id)+ .finish()+ }+}++impl OciKmsClient {+ /// Constructs a client that reads the system clock and RNG directly.+ pub fn new(config: &OciKmsConfig) -> Result<Self, OciKmsError> {+ Self::with_environment(config, Arc::new(SystemEnvironment))+ }++ /// Constructs a client whose clock and entropy reads go through `environment`.+ pub fn with_environment(+ config: &OciKmsConfig,+ environment: Arc<dyn Environment>,+ ) -> Result<Self, OciKmsError> {+ let host = url::Url::parse(&config.vault_crypto_endpoint)+ .map_err(|error| {+ OciKmsError::InvalidConfig(format!("invalid vault crypto endpoint URL: {error}"))+ })?+ .host_str()+ .ok_or_else(|| {+ OciKmsError::InvalidConfig("vault crypto endpoint URL has no host".to_owned())+ })?+ .to_owned();++ let http_client = transport::client_builder()+ .build()+ .map_err(|error| OciKmsError::ClientCreationFailed(error.to_string()))?;++ Ok(Self {+ http_client,+ vault_crypto_endpoint: config+ .vault_crypto_endpoint+ .trim_end_matches('/')+ .to_owned(),+ host,+ key_id: config.key_id.clone(),+ credentials: Arc::new(CredentialCache::default()),+ environment,+ })+ }++ /// Encrypts `plaintext` (at most 4 KiB) under the vault key, returning OCI's base64+ /// ciphertext.+ pub async fn encrypt(&self, plaintext: &[u8]) -> Result<String, OciKmsError> {+ let request = EncryptDataDetails {+ key_id: &self.key_id,+ plaintext: BASE64_ENGINE.encode(plaintext),+ encryption_algorithm: ENCRYPTION_ALGORITHM,+ };+ let response: EncryptedData = self.call(ENCRYPT_PATH, &request).await?;+ Ok(response.ciphertext)+ }++ /// Decrypts OCI base64 `ciphertext`: from [`Self::encrypt`], [`DataKey::ciphertext`], or+ /// `oci kms crypto encrypt`.+ pub async fn decrypt(&self, ciphertext: &str) -> Result<Vec<u8>, OciKmsError> {+ let request = DecryptDataDetails {+ key_id: &self.key_id,+ ciphertext,+ encryption_algorithm: ENCRYPTION_ALGORITHM,+ };+ let response: DecryptedData = self.call(DECRYPT_PATH, &request).await?;+ BASE64_ENGINE.decode(response.plaintext).map_err(|error| {+ OciKmsError::InvalidResponse(format!("plaintext is not valid base64: {error}"))+ })+ }++ /// Generates a fresh AES-256 data key, returned both in plaintext and encrypted under the+ /// vault key.+ pub async fn generate_data_key(&self) -> Result<DataKey, OciKmsError> {+ let request = GenerateKeyDetails {+ key_id: &self.key_id,+ include_plaintext_key: true,+ key_shape: KeyShape {+ algorithm: "AES",+ length: DATA_KEY_LENGTH,+ },+ };+ let response: GeneratedKey = self.call(GENERATE_DATA_KEY_PATH, &request).await?;++ let mut decoded = BASE64_ENGINE+ .decode(response.plaintext.unwrap_or_default())+ .map_err(|error| {+ OciKmsError::InvalidResponse(format!("data key is not valid base64: {error}"))+ })?;+ let plaintext = <[u8; DATA_KEY_LENGTH]>::try_from(decoded.as_slice()).map_err(|_| {+ OciKmsError::InvalidResponse(format!(+ "data key is {} bytes, expected {DATA_KEY_LENGTH}",+ decoded.len()+ ))+ });+ decoded.zeroize();++ Ok(DataKey {+ plaintext: plaintext?,+ ciphertext: response.ciphertext,+ })+ }++ async fn call<Request, Response>(+ &self,+ path: &'static str,+ request: &Request,+ ) -> Result<Response, OciKmsError>+ where+ Request: Serialize,+ Response: serde::de::DeserializeOwned,+ {+ let body = serde_json::to_vec(request).map_err(|error| {+ OciKmsError::RequestFailed(format!("failed to serialize the request body: {error}"))+ })?;++ let response_body = transport::with_retries(self.environment.as_ref(), path, || {+ self.send_once(path, &body)+ })+ .await?;++ serde_json::from_str(&response_body).map_err(|error| {+ OciKmsError::InvalidResponse(format!("failed to parse the response body: {error}"))+ })+ }++ /// One signed attempt. Signed afresh on every call, since the signature covers `date`.+ async fn send_once(&self, path: &str, body: &[u8]) -> Result<String, AttemptError> {+ // Credential resolution retries on its own; a failure surfacing here is final.+ let credentials = self+ .credentials+ .current(self.environment.as_ref())+ .await+ .map_err(AttemptError::Fatal)?;++ let signed = signing::sign_post_request(+ self.environment.as_ref(),+ &credentials.key_id,+ &credentials.private_key,+ &self.host,+ path,+ body,+ )+ .map_err(AttemptError::Fatal)?;++ let response = self+ .http_client+ .post(format!("{}{path}", self.vault_crypto_endpoint))+ .header("date", signed.date)+ .header("authorization", signed.authorization)+ .header("content-type", "application/json")+ .header("x-content-sha256", signed.x_content_sha256)+ .header(+ "opc-request-id",+ transport::request_id(self.environment.as_ref()),+ )+ .body(body.to_vec())+ .send()+ .await+ .map_err(|error| {+ AttemptError::Retryable(OciKmsError::RequestFailed(format!(+ "failed to send the request: {error}"+ )))+ })?;++ let status = response.status();+ let response_body = response.text().await.map_err(|error| {+ AttemptError::Retryable(OciKmsError::RequestFailed(format!(+ "failed to read the response body: {error}"+ )))+ })?;++ if !status.is_success() {+ return Err(AttemptError::from_status(+ status,+ OciKmsError::UnexpectedStatus {+ status: status.as_u16(),+ body: response_body,+ },+ ));+ }++ Ok(response_body)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn config() -> OciKmsConfig {+ OciKmsConfig {+ vault_crypto_endpoint: "https://abc-crypto.kms.ap-mumbai-1.oci.oraclecloud.com"+ .to_string(),+ key_id: "ocid1.key.oc1.ap-mumbai-1.test".to_string(),+ }+ }++ #[test]+ fn new_extracts_host_and_trims_trailing_slash() {+ let client = OciKmsClient::new(&OciKmsConfig {+ vault_crypto_endpoint: "https://abc-crypto.kms.ap-mumbai-1.oci.oraclecloud.com/"+ .to_string(),+ ..config()+ })+ .expect("client should build from a valid endpoint");++ assert_eq!(+ client.host,+ "abc-crypto.kms.ap-mumbai-1.oci.oraclecloud.com"+ );+ assert_eq!(+ client.vault_crypto_endpoint,+ "https://abc-crypto.kms.ap-mumbai-1.oci.oraclecloud.com"+ );+ }++ #[test]+ fn new_rejects_an_invalid_endpoint() {+ let result = OciKmsClient::new(&OciKmsConfig {+ vault_crypto_endpoint: "not a url".to_string(),+ ..config()+ });+ assert!(matches!(result, Err(OciKmsError::InvalidConfig(_))));+ }++ #[test]+ fn data_key_debug_redacts_the_plaintext() {+ let key = DataKey {+ plaintext: [7; DATA_KEY_LENGTH],+ ciphertext: "wrapped".to_owned(),+ };+ let debug = format!("{key:?}");+ assert!(debug.contains("<redacted>"));+ assert!(!debug.contains('7'));+ }++ #[test]+ fn requests_serialize_with_ocis_camel_case_field_names() {+ let body = serde_json::to_value(GenerateKeyDetails {+ key_id: "k",+ include_plaintext_key: true,+ key_shape: KeyShape {+ algorithm: "AES",+ length: 32,+ },+ })+ .expect("serializable");+ assert_eq!(+ body,+ serde_json::json!({+ "keyId": "k",+ "includePlaintextKey": true,+ "keyShape": { "algorithm": "AES", "length": 32 }+ })+ );++ let body = serde_json::to_value(DecryptDataDetails {+ key_id: "k",+ ciphertext: "c",+ encryption_algorithm: ENCRYPTION_ALGORITHM,+ })+ .expect("serializable");+ assert_eq!(+ body,+ serde_json::json!({+ "keyId": "k",+ "ciphertext": "c",+ "encryptionAlgorithm": "AES_256_GCM"+ })+ );+ }++ /// Tests against a real OCI Vault. Skipped by default; run with:+ ///+ /// ```text+ /// OCI_KMS_TEST_CRYPTO_ENDPOINT=https://<vault>-crypto.kms.<region>.oci.oraclecloud.com \+ /// OCI_KMS_TEST_KEY_ID=ocid1.key.oc1... \+ /// OCI_KMS_TEST_CLI_CIPHERTEXT=<output of `oci kms crypto encrypt`> \+ /// OCI_KMS_TEST_CLI_PLAINTEXT=<the plaintext that was encrypted> \+ /// cargo test -p oci_kms live -- --ignored+ /// ```+ ///+ /// Outside Kubernetes, credentials come from `~/.oci/config` (`OCI_CLI_PROFILE` to pick one).+ /// Inside a pod, the same tests exercise OKE Workload Identity instead.+ mod live {+ use std::time::{Duration, Instant};++ use super::*;++ fn env(name: &str) -> String {+ std::env::var(name).unwrap_or_else(|_| panic!("{name} must be set for live tests"))+ }++ fn live_config() -> OciKmsConfig {+ OciKmsConfig {+ vault_crypto_endpoint: env("OCI_KMS_TEST_CRYPTO_ENDPOINT"),+ key_id: env("OCI_KMS_TEST_KEY_ID"),+ }+ }++ fn live_client() -> OciKmsClient {+ OciKmsClient::new(&live_config()).expect("client should build from the live config")+ }++ #[tokio::test]+ #[ignore = "calls a real OCI Vault"]+ async fn encrypt_then_decrypt_round_trips() {+ let client = live_client();++ let ciphertext = client.encrypt(b"s3cr3t!").await.expect("encrypt succeeds");+ assert_ne!(ciphertext.as_bytes(), b"s3cr3t!");+ // Printed so the OCI CLI can confirm it decrypts our ciphertext too.+ println!("OCI_KMS_LIVE_CIPHERTEXT={ciphertext}");++ let plaintext = client.decrypt(&ciphertext).await.expect("decrypt succeeds");+ assert_eq!(plaintext, b"s3cr3t!");+ }++ #[tokio::test]+ #[ignore = "calls a real OCI Vault"]+ async fn decrypts_ciphertext_made_by_the_oci_cli() {+ let plaintext = live_client()+ .decrypt(&env("OCI_KMS_TEST_CLI_CIPHERTEXT"))+ .await+ .expect("decrypt succeeds");+ assert_eq!(plaintext, env("OCI_KMS_TEST_CLI_PLAINTEXT").as_bytes());+ }++ #[tokio::test]+ #[ignore = "calls a real OCI Vault"]+ async fn generated_data_key_unwraps_to_its_plaintext() {+ let client = live_client();++ let data_key = client+ .generate_data_key()+ .await+ .expect("generate_data_key succeeds");+ assert_ne!(data_key.plaintext(), &[0; DATA_KEY_LENGTH]);++ let unwrapped = client+ .decrypt(data_key.ciphertext())+ .await+ .expect("decrypt succeeds");+ assert_eq!(unwrapped.as_slice(), data_key.plaintext());+ }++ #[tokio::test]+ #[ignore = "calls a real OCI Vault"]+ async fn decrypt_with_a_nonexistent_key_fails_without_retrying() {+ let mut config = live_config();+ config.key_id = format!("{}x", config.key_id);+ let client = OciKmsClient::new(&config).expect("client builds");++ let start = Instant::now();+ let result = client.decrypt(&env("OCI_KMS_TEST_CLI_CIPHERTEXT")).await;++ assert!(+ matches!(result, Err(OciKmsError::UnexpectedStatus { status, .. }) if status < 500),+ "expected a 4xx, got {result:?}"+ );+ println!("nonexistent key failed after {:?}", start.elapsed());+ }++ #[tokio::test]+ #[ignore = "needs OCI credentials; takes ~25s"]+ async fn unreachable_endpoint_times_out_and_retries() {+ let client = OciKmsClient::new(&OciKmsConfig {+ // TEST-NET-1 (RFC 5737): guaranteed unroutable, so every connect times out.+ vault_crypto_endpoint: "https://192.0.2.1".to_string(),+ key_id: env("OCI_KMS_TEST_KEY_ID"),+ })+ .expect("client builds");++ let start = Instant::now();+ let result = client.decrypt("ignored").await;+ let elapsed = start.elapsed();++ assert!(matches!(result, Err(OciKmsError::RequestFailed(_))));+ // Four attempts, each bounded by the 5s connect timeout.+ assert!(+ elapsed >= Duration::from_secs(15),+ "expected retries, failed after {elapsed:?}"+ );+ assert!(+ elapsed <= Duration::from_secs(40),+ "expected timeouts, took {elapsed:?}"+ );+ println!("unreachable endpoint failed after {elapsed:?}");+ }+ }+}diff --git a/crates/oci_kms/src/config.rs b/crates/oci_kms/src/config.rsnew file mode 100644index 0000000000..6f8f01a5eb--- /dev/null+++ b/crates/oci_kms/src/config.rs@@ -0,0 +1,64 @@+//! Configuration for an [`OciKmsClient`](crate::OciKmsClient).++/// Configuration parameters required for constructing an [`OciKmsClient`](crate::OciKmsClient).+///+/// Holds no credentials: those come from the environment (see the crate docs).+#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Deserialize)]+#[serde(default)]+pub struct OciKmsConfig {+ /// The vault's crypto endpoint (e.g. `https://<vault>-crypto.kms.<region>.oci.oraclecloud.com`),+ /// obtained once when the vault is created; doesn't change afterward.+ pub vault_crypto_endpoint: String,++ /// The full OCID of the KMS key used to encrypt/decrypt data.+ pub key_id: String,+}++impl OciKmsConfig {+ /// Verifies that the configuration is usable.+ pub fn validate(&self) -> Result<(), &'static str> {+ if self.vault_crypto_endpoint.trim().is_empty() {+ return Err("OCI KMS vault crypto endpoint must not be empty");+ }+ if self.key_id.trim().is_empty() {+ return Err("OCI KMS key ID must not be empty");+ }+ Ok(())+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn config() -> OciKmsConfig {+ OciKmsConfig {+ vault_crypto_endpoint: "https://abc-crypto.kms.ap-mumbai-1.oci.oraclecloud.com"+ .to_string(),+ key_id: "ocid1.key.oc1.ap-mumbai-1.test".to_string(),+ }+ }++ #[test]+ fn validate_succeeds_when_all_fields_are_set() {+ assert!(config().validate().is_ok());+ }++ #[test]+ fn validate_fails_when_vault_crypto_endpoint_is_empty() {+ let config = OciKmsConfig {+ vault_crypto_endpoint: String::new(),+ ..config()+ };+ assert!(config.validate().is_err());+ }++ #[test]+ fn validate_fails_when_key_id_is_blank() {+ let config = OciKmsConfig {+ key_id: " ".to_string(),+ ..config()+ };+ assert!(config.validate().is_err());+ }+}diff --git a/crates/oci_kms/src/config_file.rs b/crates/oci_kms/src/config_file.rsnew file mode 100644index 0000000000..06c978b307--- /dev/null+++ b/crates/oci_kms/src/config_file.rs@@ -0,0 +1,210 @@+//! Reads OCI credentials from `~/.oci/config`, the file the `oci` CLI writes.+//!+//! This is the off-cluster path — local development, CI, or any container that isn't an+//! OKE pod — and the counterpart to `~/.aws/credentials` and gcloud's ADC file. Supports+//! the two profile shapes the CLI produces: session-token auth (`oci session+//! authenticate`) and API-key auth. Only the `keyId` differs between them; both sign+//! identically, so `signing.rs` is unaware of which one is in play.++use std::{collections::HashMap, path::PathBuf};++use rsa::{pkcs1::DecodeRsaPrivateKey, pkcs8::DecodePrivateKey};++use crate::{+ credentials::{soft_expiry, OciCredentials},+ error::OciKmsError,+};++const CONFIG_PATH_VAR: &str = "OCI_CLI_CONFIG_FILE";+const PROFILE_VAR: &str = "OCI_CLI_PROFILE";+const DEFAULT_CONFIG_PATH: &str = "~/.oci/config";+const DEFAULT_PROFILE: &str = "DEFAULT";++pub(crate) fn credentials() -> Result<OciCredentials, OciKmsError> {+ let config_path =+ std::env::var(CONFIG_PATH_VAR).unwrap_or_else(|_| DEFAULT_CONFIG_PATH.to_owned());+ let profile_name = std::env::var(PROFILE_VAR).unwrap_or_else(|_| DEFAULT_PROFILE.to_owned());++ let config = std::fs::read_to_string(expand_home(&config_path)).map_err(|error| {+ OciKmsError::CredentialsUnavailable(format!(+ "not running in Kubernetes, and no OCI config file at {config_path} ({error}); run `oci session authenticate`, or set {CONFIG_PATH_VAR}"+ ))+ })?;++ let profile = parse_profile(&config, &profile_name).ok_or_else(|| {+ OciKmsError::CredentialsUnavailable(format!(+ "no profile named [{profile_name}] in {config_path}"+ ))+ })?;++ let private_key = load_private_key(required(&profile, "key_file")?)?;++ // Precedence matches `oci-go-sdk`'s `fileConfigurationProvider::KeyID`: a profile+ // carrying `user` is API-key auth, even when a session token sits alongside it.+ match profile.get("user") {+ Some(user) => {+ let tenancy = required(&profile, "tenancy")?;+ let fingerprint = required(&profile, "fingerprint")?;++ Ok(OciCredentials {+ key_id: format!("{tenancy}/{user}/{fingerprint}"),+ private_key,+ soft_expires_at: None,+ })+ }+ None => {+ let token_path = required(&profile, "security_token_file")?;+ let token = std::fs::read_to_string(expand_home(token_path))+ .map_err(|error| {+ OciKmsError::CredentialsUnavailable(format!(+ "failed to read the OCI session token file: {error}"+ ))+ })?+ .trim()+ .to_owned();++ Ok(OciCredentials {+ soft_expires_at: Some(soft_expiry(&token)?),+ key_id: format!("ST${token}"),+ private_key,+ })+ }+ }+}++fn parse_profile(config: &str, profile_name: &str) -> Option<HashMap<String, String>> {+ let mut current_section = None;+ let mut values = HashMap::new();++ for line in config.lines() {+ let line = line.trim();+ if line.is_empty() || line.starts_with('#') {+ continue;+ }++ if let Some(section) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {+ current_section = Some(section.trim().to_owned());+ continue;+ }++ if current_section.as_deref() == Some(profile_name) {+ if let Some((key, value)) = line.split_once('=') {+ values.insert(key.trim().to_ascii_lowercase(), value.trim().to_owned());+ }+ }+ }++ (!values.is_empty()).then_some(values)+}++fn required<'a>(+ profile: &'a HashMap<String, String>,+ key: &'static str,+) -> Result<&'a str, OciKmsError> {+ profile.get(key).map(String::as_str).ok_or_else(|| {+ OciKmsError::CredentialsUnavailable(format!("OCI config profile is missing `{key}`"))+ })+}++fn load_private_key(path: &str) -> Result<rsa::RsaPrivateKey, OciKmsError> {+ let contents = std::fs::read_to_string(expand_home(path)).map_err(|error| {+ OciKmsError::CredentialsUnavailable(format!(+ "failed to read the OCI private key at {path}: {error}"+ ))+ })?;+ let pem = pem_block(&contents);++ rsa::RsaPrivateKey::from_pkcs8_pem(&pem)+ .or_else(|_| rsa::RsaPrivateKey::from_pkcs1_pem(&pem))+ .map_err(|error| {+ OciKmsError::CredentialsUnavailable(format!(+ "failed to parse the OCI private key at {path}: {error}"+ ))+ })+}++/// The `oci` CLI appends an `OCI_API_KEY` label line after the PEM footer, which strict+/// PKCS#8 parsers reject. Keep only through the end of the PEM block.+fn pem_block(contents: &str) -> String {+ let mut block = String::new();+ for line in contents.lines() {+ block.push_str(line);+ block.push('\n');+ if line.starts_with("-----END") {+ break;+ }+ }+ block+}++fn expand_home(path: &str) -> PathBuf {+ match path.strip_prefix("~/") {+ Some(rest) => match std::env::var_os("HOME") {+ Some(home) => PathBuf::from(home).join(rest),+ None => PathBuf::from(path),+ },+ None => PathBuf::from(path),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ const CONFIG: &str = "\+[DEFAULT]+user=ocid1.user.oc1..default+fingerprint=aa:bb+# a comment+Tenancy = ocid1.tenancy.oc1..default+key_file=~/.oci/default.pem++[SESSION]+security_token_file=~/.oci/sessions/token+key_file=~/.oci/sessions/key.pem+";++ #[test]+ fn parse_profile_reads_only_the_requested_section() {+ let profile = parse_profile(CONFIG, "SESSION").expect("profile exists");+ assert_eq!(profile.len(), 2);+ assert_eq!(+ profile.get("security_token_file").map(String::as_str),+ Some("~/.oci/sessions/token")+ );+ assert!(!profile.contains_key("user"));+ }++ #[test]+ fn parse_profile_trims_and_lowercases_keys_and_skips_comments() {+ let profile = parse_profile(CONFIG, "DEFAULT").expect("profile exists");+ assert_eq!(+ profile.get("tenancy").map(String::as_str),+ Some("ocid1.tenancy.oc1..default")+ );+ assert_eq!(profile.len(), 4);+ }++ #[test]+ fn parse_profile_returns_none_for_a_missing_section() {+ assert!(parse_profile(CONFIG, "MISSING").is_none());+ }++ #[test]+ fn pem_block_drops_the_cli_label_after_the_footer() {+ // `pem_block` only looks for the `-----END` line, so the label doesn't matter.+ let contents = "-----BEGIN TEST BLOCK-----\nabc\n-----END TEST BLOCK-----\nOCI_API_KEY\n";+ assert_eq!(+ pem_block(contents),+ "-----BEGIN TEST BLOCK-----\nabc\n-----END TEST BLOCK-----\n"+ );+ }++ #[test]+ fn expand_home_leaves_absolute_paths_untouched() {+ assert_eq!(+ expand_home("/etc/oci/config"),+ PathBuf::from("/etc/oci/config")+ );+ }+}diff --git a/crates/oci_kms/src/credentials.rs b/crates/oci_kms/src/credentials.rsnew file mode 100644index 0000000000..ec8442cfc5--- /dev/null+++ b/crates/oci_kms/src/credentials.rs@@ -0,0 +1,149 @@+//! Resolves OCI signing credentials from the ambient environment, and caches them.+//!+//! Mirrors what the AWS and GCP SDKs do for their backends: no credentials in+//! service config, just a source picked from the environment. Inside Kubernetes that+//! is OKE Workload Identity; anywhere else it is the `~/.oci/config` the `oci` CLI writes.++use std::sync::Arc;++use base64::Engine;+use tokio::sync::Mutex;++use crate::{config_file, environment::Environment, error::OciKmsError, workload_identity};++/// Refresh at half the token's lifetime, matching `oci-go-sdk`'s `rpstValidForRatio`+/// and what `oci-python-sdk`'s `valid_with_half_expiration_time` ships.+const SOFT_EXPIRY_LIFETIME_RATIO: i64 = 2;+const REFRESH_BUFFER_SECONDS: i64 = 5 * 60;++/// A signing identity: the `keyId` header value and the key that signs for it.+/// Deliberately not `Debug` — neither field belongs in a log or a panic message.+pub(crate) struct OciCredentials {+ pub(crate) key_id: String,+ pub(crate) private_key: rsa::RsaPrivateKey,+ /// `None` for credentials that never expire, such as an API key.+ pub(crate) soft_expires_at: Option<i64>,+}++/// Caches credentials until their own soft-expiry. The lock is held across the refresh so+/// a burst of concurrent calls resolves once, not once each.+#[derive(Default)]+pub(crate) struct CredentialCache {+ cached: Mutex<Option<Arc<OciCredentials>>>,+}++impl CredentialCache {+ pub(crate) async fn current(+ &self,+ environment: &dyn Environment,+ ) -> Result<Arc<OciCredentials>, OciKmsError> {+ let mut cached = self.cached.lock().await;++ if let Some(credentials) = cached.as_ref() {+ if !is_stale(+ credentials.soft_expires_at,+ environment.now_unix_timestamp(),+ ) {+ return Ok(Arc::clone(credentials));+ }+ }++ let credentials = Arc::new(resolve(environment).await?);+ *cached = Some(Arc::clone(&credentials));++ Ok(credentials)+ }+}++/// Inside Kubernetes this is Workload Identity and nothing else — on-disk credentials are+/// never a fallback there, so a production pod can't quietly end up signing as whoever+/// last logged in with the `oci` CLI.+async fn resolve(environment: &dyn Environment) -> Result<OciCredentials, OciKmsError> {+ if workload_identity::in_kubernetes() {+ workload_identity::credentials(environment).await+ } else {+ config_file::credentials()+ }+}++#[derive(serde::Deserialize)]+struct TokenClaims {+ iat: i64,+ exp: i64,+}++/// Halfway point of a session token's real lifetime, from its own `iat`/`exp` claims. The+/// signature isn't verified: the token is trusted because of how it was obtained, exactly+/// as Oracle's own SDKs treat it.+pub(crate) fn soft_expiry(session_token: &str) -> Result<i64, OciKmsError> {+ let payload = session_token.split('.').nth(1).ok_or_else(|| {+ OciKmsError::CredentialsUnavailable("the OCI session token is not a JWT".to_owned())+ })?;++ let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD+ .decode(payload)+ .map_err(|error| {+ OciKmsError::CredentialsUnavailable(format!(+ "failed to base64 decode the session token payload: {error}"+ ))+ })?;++ let claims: TokenClaims = serde_json::from_slice(&payload).map_err(|error| {+ OciKmsError::CredentialsUnavailable(format!(+ "the session token payload is missing `iat`/`exp`: {error}"+ ))+ })?;++ Ok(claims.iat + (claims.exp - claims.iat) / SOFT_EXPIRY_LIFETIME_RATIO)+}++fn is_stale(soft_expires_at: Option<i64>, now: i64) -> bool {+ let Some(soft_expires_at) = soft_expires_at else {+ return false;+ };+ soft_expires_at <= now + REFRESH_BUFFER_SECONDS+}++#[cfg(test)]+mod tests {+ use super::*;++ fn jwt_with_payload(payload: &str) -> String {+ let encoded = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(payload);+ format!("header.{encoded}.signature")+ }++ #[test]+ fn soft_expiry_is_halfway_through_the_token_lifetime() {+ let token = jwt_with_payload(r#"{"iat":1000,"exp":4600}"#);+ assert_eq!(soft_expiry(&token).expect("valid token"), 2800);+ }++ #[test]+ fn soft_expiry_rejects_a_token_that_is_not_a_jwt() {+ assert!(soft_expiry("not-a-jwt").is_err());+ }++ #[test]+ fn soft_expiry_rejects_a_token_without_lifetime_claims() {+ let token = jwt_with_payload(r#"{"sub":"workload"}"#);+ assert!(soft_expiry(&token).is_err());+ }++ #[test]+ fn credentials_without_an_expiry_are_never_stale() {+ assert!(!is_stale(None, 1_000_000));+ }++ #[test]+ fn credentials_past_their_soft_expiry_are_stale() {+ assert!(is_stale(Some(0), 1_000_000));+ }++ #[test]+ fn credentials_within_the_refresh_buffer_are_stale() {+ let now = 1_000_000;+ assert!(is_stale(Some(now + REFRESH_BUFFER_SECONDS - 1), now));+ assert!(!is_stale(Some(now + REFRESH_BUFFER_SECONDS + 60), now));+ }+}diff --git a/crates/oci_kms/src/environment.rs b/crates/oci_kms/src/environment.rsnew file mode 100644index 0000000000..82d3e528ca--- /dev/null+++ b/crates/oci_kms/src/environment.rs@@ -0,0 +1,52 @@+//! The clock and entropy this crate reads, behind a trait a service can replace.++use rand::RngCore;++/// Every clock and entropy read the client makes, other than key material.+///+/// Services that route such reads through their own instrumented functions (Hyperswitch does,+/// so that `deja` can replay them) implement this and pass it to+/// [`OciKmsClient::with_environment`](crate::OciKmsClient::with_environment). Key material,+/// such as the Workload Identity session key, always comes from the OS RNG.+pub trait Environment: Send + Sync + std::fmt::Debug {+ /// Seconds since the Unix epoch. Used for the signed `date` header and token expiry.+ fn now_unix_timestamp(&self) -> i64;++ /// A uniform draw from `[0, 1)`. Used for retry backoff jitter.+ fn random_f64_unit(&self) -> f64;++ /// `len` random bytes. Used for `opc-request-id` values.+ fn random_bytes(&self, len: usize) -> Vec<u8>;+}++/// Reads the system clock and the thread-local RNG directly.+#[derive(Clone, Copy, Debug, Default)]+pub struct SystemEnvironment;++impl Environment for SystemEnvironment {+ fn now_unix_timestamp(&self) -> i64 {+ #[allow(+ clippy::disallowed_methods,+ reason = "this function IS the seam, for services that don't supply their own"+ )]+ time::OffsetDateTime::now_utc().unix_timestamp()+ }++ fn random_f64_unit(&self) -> f64 {+ #[allow(+ clippy::disallowed_methods,+ reason = "this function IS the seam, for services that don't supply their own"+ )]+ rand::random::<f64>()+ }++ fn random_bytes(&self, len: usize) -> Vec<u8> {+ let mut bytes = vec![0; len];+ #[allow(+ clippy::disallowed_methods,+ reason = "this function IS the seam, for services that don't supply their own"+ )]+ rand::thread_rng().fill_bytes(&mut bytes);+ bytes+ }+}diff --git a/crates/oci_kms/src/error.rs b/crates/oci_kms/src/error.rsnew file mode 100644index 0000000000..fcadf403a5--- /dev/null+++ b/crates/oci_kms/src/error.rs@@ -0,0 +1,43 @@+//! Errors returned by this crate.++/// Errors that could occur during OCI Vault KMS operations.+///+/// A plain error type rather than an `error_stack::Report`, so consuming services can wrap it+/// in whichever `error-stack` version they use. Each variant carries a human-readable detail.+#[derive(Debug, thiserror::Error)]+#[non_exhaustive]+pub enum OciKmsError {+ /// The [`OciKmsConfig`](crate::OciKmsConfig) is unusable, such as an invalid endpoint URL.+ #[error("invalid OCI KMS configuration: {0}")]+ InvalidConfig(String),++ /// The HTTP client couldn't be built.+ #[error("failed to build the OCI KMS HTTP client: {0}")]+ ClientCreationFailed(String),++ /// Signing credentials couldn't be obtained, from OKE Workload Identity inside Kubernetes+ /// or from the `oci` CLI config file outside it.+ #[error("OCI signing credentials unavailable: {0}")]+ CredentialsUnavailable(String),++ /// Constructing the OCI Signature v1 `Authorization` header failed.+ #[error("failed to sign the OCI request: {0}")]+ SigningFailed(String),++ /// The request couldn't be sent, or its response couldn't be read, after all retries.+ #[error("OCI KMS request failed: {0}")]+ RequestFailed(String),++ /// OCI answered with a non-success status, after all retries for retryable ones.+ #[error("OCI KMS returned HTTP {status}: {body}")]+ UnexpectedStatus {+ /// The HTTP status code.+ status: u16,+ /// The response body: OCI's `{"code", "message"}` error document.+ body: String,+ },++ /// OCI answered successfully, but with a body this client couldn't interpret.+ #[error("unexpected OCI KMS response: {0}")]+ InvalidResponse(String),+}diff --git a/crates/oci_kms/src/lib.rs b/crates/oci_kms/src/lib.rsnew file mode 100644index 0000000000..4ad91e3c53--- /dev/null+++ b/crates/oci_kms/src/lib.rs@@ -0,0 +1,17 @@+#![doc = include_str!("../README.md")]+#![warn(missing_docs, missing_debug_implementations)]++mod client;+mod config;+mod config_file;+mod credentials;+mod environment;+mod error;+mod signing;+mod transport;+mod workload_identity;++pub use client::{DataKey, OciKmsClient};+pub use config::OciKmsConfig;+pub use environment::{Environment, SystemEnvironment};+pub use error::OciKmsError;diff --git a/crates/oci_kms/src/signing.rs b/crates/oci_kms/src/signing.rsnew file mode 100644index 0000000000..c3a3a5ff28--- /dev/null+++ b/crates/oci_kms/src/signing.rs@@ -0,0 +1,208 @@+//! OCI Signature v1 request signing (RSA-SHA256 over a canonical header string).+//!+//! Pure and network-free: given credentials and request parts, produces the header+//! values a caller attaches itself. Implements Oracle's POST-signing scheme+//! (<https://docs.oracle.com/en-us/iaas/Content/API/Concepts/signingrequests.htm>),+//! the only one this backend needs since Encrypt/Decrypt are both POSTs.++use base64::Engine;+use rsa::{+ pkcs1v15::SigningKey,+ sha2::{Digest, Sha256},+ signature::{RandomizedSigner, SignatureEncoding},+ RsaPrivateKey,+};++use crate::{environment::Environment, error::OciKmsError};++const BASE64_ENGINE: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD;++/// Header order signed in both the canonical string and the `Authorization` header's+/// `headers` field — matches Oracle's POST-signing example verbatim.+const SIGNED_HEADERS: &str =+ "date (request-target) host content-length content-type x-content-sha256";++/// RFC 7231 IMF-fixdate, the form OCI requires in the signed `date` header.+const HTTP_DATE_FORMAT: &[time::format_description::FormatItem<'_>] = time::macros::format_description!(+ "[weekday repr:short], [day] [month repr:short] [year] [hour]:[minute]:[second] GMT"+);++/// Header values to attach to a signed request. `x_content_sha256` must be sent as a+/// literal header too, not just folded into the signature — OCI independently checks+/// it against the request body it received.+pub(crate) struct SignedHeaders {+ pub(crate) date: String,+ pub(crate) authorization: String,+ pub(crate) x_content_sha256: String,+}++/// Signs a POST request per OCI's Signature v1 scheme. `key_id` is the `keyId` value+/// (`ST$<session-token>` for Workload Identity). `path` includes any query string;+/// `host` is the request's Host header value (no scheme).+pub(crate) fn sign_post_request(+ environment: &dyn Environment,+ key_id: &str,+ private_key: &RsaPrivateKey,+ host: &str,+ path: &str,+ body: &[u8],+) -> Result<SignedHeaders, OciKmsError> {+ let date = http_date(environment.now_unix_timestamp())?;++ Ok(sign_post_request_at(+ date,+ key_id,+ private_key,+ host,+ path,+ body,+ ))+}++fn http_date(unix_timestamp: i64) -> Result<String, OciKmsError> {+ time::OffsetDateTime::from_unix_timestamp(unix_timestamp)+ .map_err(|error| OciKmsError::SigningFailed(format!("invalid clock reading: {error}")))?+ .format(HTTP_DATE_FORMAT)+ .map_err(|error| OciKmsError::SigningFailed(format!("failed to format the date: {error}")))+}++/// [`sign_post_request`] with the `date` header value supplied, so output is reproducible.+fn sign_post_request_at(+ date: String,+ key_id: &str,+ private_key: &RsaPrivateKey,+ host: &str,+ path: &str,+ body: &[u8],+) -> SignedHeaders {+ let content_length = body.len().to_string();+ let content_type = "application/json";+ let body_hash = BASE64_ENGINE.encode(Sha256::digest(body));++ let signing_string = format!(+ "date: {date}\n\+ (request-target): post {path}\n\+ host: {host}\n\+ content-length: {content_length}\n\+ content-type: {content_type}\n\+ x-content-sha256: {body_hash}"+ );++ // `sign_with_rng` (not the deterministic `sign`) blinds the RSA operation against+ // timing side channels — PKCS#1 v1.5 output is still deterministic either way.+ let signing_key = SigningKey::<Sha256>::new(private_key.clone());+ let mut rng = rand::rngs::OsRng;+ let signature = signing_key.sign_with_rng(&mut rng, signing_string.as_bytes());+ let encoded_signature = BASE64_ENGINE.encode(signature.to_bytes());++ let authorization = format!(+ "Signature version=\"1\",headers=\"{SIGNED_HEADERS}\",keyId=\"{key_id}\",\+ algorithm=\"rsa-sha256\",signature=\"{encoded_signature}\""+ );++ SignedHeaders {+ date,+ authorization,+ x_content_sha256: body_hash,+ }+}++#[cfg(test)]+mod tests {+ use rsa::{+ pkcs1v15::{Signature, VerifyingKey},+ signature::Verifier,+ };++ use super::*;++ const DATE: &str = "Thu, 05 Jan 2014 21:31:40 GMT";+ const HOST: &str = "iaas.us-phoenix-1.oraclecloud.com";+ const PATH: &str = "/20160918/volumeAttachments";+ const BODY: &[u8] = br#"{"compartmentId":"ocid1.compartment.oc1..aaaa"}"#;+ const KEY_ID: &str = "ocid1.tenancy.oc1..test/ocid1.user.oc1..test/fingerprint";++ /// Generated per run rather than checked in, so no private key lives in the repo.+ fn test_key() -> RsaPrivateKey {+ RsaPrivateKey::new(&mut rand::rngs::OsRng, 1024).expect("key generation succeeds")+ }++ /// Pulls the base64 `signature="..."` value out of an `Authorization` header.+ fn signature_of(authorization: &str) -> Vec<u8> {+ let encoded = authorization+ .split("signature=\"")+ .nth(1)+ .and_then(|rest| rest.strip_suffix('"'))+ .expect("authorization header carries a signature");+ BASE64_ENGINE.decode(encoded).expect("signature is base64")+ }++ #[test]+ fn x_content_sha256_is_the_base64_sha256_of_the_body() {+ let signed = sign_post_request_at(DATE.to_owned(), KEY_ID, &test_key(), HOST, PATH, b"");+ // SHA-256 of the empty string.+ assert_eq!(+ signed.x_content_sha256,+ "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU="+ );+ }++ #[test]+ fn authorization_header_has_the_oci_signature_v1_shape() {+ let signed = sign_post_request_at(DATE.to_owned(), KEY_ID, &test_key(), HOST, PATH, BODY);++ assert_eq!(signed.date, DATE);+ assert!(signed.authorization.starts_with(+ "Signature version=\"1\",\+ headers=\"date (request-target) host content-length content-type x-content-sha256\",\+ keyId=\"ocid1.tenancy.oc1..test/ocid1.user.oc1..test/fingerprint\",\+ algorithm=\"rsa-sha256\",\+ signature=\""+ ));+ }++ /// The signing string is written out literally here, in the exact form Oracle's docs+ /// specify for a POST, rather than rebuilt from the code under test. The signature only+ /// verifies if the code signed exactly this string, with RSA PKCS#1 v1.5 over SHA-256.+ #[test]+ fn signature_verifies_over_oracles_post_signing_string() {+ let private_key = test_key();+ let signed = sign_post_request_at(DATE.to_owned(), KEY_ID, &private_key, HOST, PATH, BODY);++ let expected_signing_string = "date: Thu, 05 Jan 2014 21:31:40 GMT\n\+ (request-target): post /20160918/volumeAttachments\n\+ host: iaas.us-phoenix-1.oraclecloud.com\n\+ content-length: 47\n\+ content-type: application/json\n\+ x-content-sha256: JL3n1o6nGMwsBAd+52/KQ24uJCKaE4r2X8cuX1MVPRw=";++ let signature = Signature::try_from(signature_of(&signed.authorization).as_slice())+ .expect("well-formed PKCS#1 v1.5 signature");+ VerifyingKey::<Sha256>::new(private_key.to_public_key())+ .verify(expected_signing_string.as_bytes(), &signature)+ .expect("signature verifies over Oracle's signing string");+ }++ #[test]+ fn signature_does_not_verify_over_a_different_signing_string() {+ let private_key = test_key();+ let signed = sign_post_request_at(DATE.to_owned(), KEY_ID, &private_key, HOST, PATH, BODY);++ let signature = Signature::try_from(signature_of(&signed.authorization).as_slice())+ .expect("well-formed PKCS#1 v1.5 signature");+ let verified = VerifyingKey::<Sha256>::new(private_key.to_public_key()).verify(+ b"date: Thu, 05 Jan 2014 21:31:41 GMT\n(request-target): post /20160918/volumeAttachments",+ &signature,+ );+ assert!(verified.is_err());+ }++ #[test]+ fn http_date_is_rfc_7231_in_gmt() {+ // 2014-01-02 09:05:07 UTC, a Thursday.+ assert_eq!(+ http_date(1_388_653_507).expect("valid timestamp"),+ "Thu, 02 Jan 2014 09:05:07 GMT"+ );+ }+}diff --git a/crates/oci_kms/src/transport.rs b/crates/oci_kms/src/transport.rsnew file mode 100644index 0000000000..c2d6a4ec9e--- /dev/null+++ b/crates/oci_kms/src/transport.rs@@ -0,0 +1,199 @@+//! Timeouts and retries shared by every outbound OCI call: the crypto endpoint and proxymux.+//!+//! The AWS and GCP SDKs ship both; this backend has no SDK. Without timeouts a hung endpoint+//! stalls pod startup indefinitely, and without retries a single throttled (429) response+//! during a scale-up fails the pod outright.++use std::{future::Future, time::Duration};++use crate::{environment::Environment, error::OciKmsError};++const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);+const REQUEST_TIMEOUT: Duration = Duration::from_secs(15);++const MAX_ATTEMPTS: u32 = 4;+const BASE_BACKOFF: Duration = Duration::from_millis(250);+const MAX_BACKOFF: Duration = Duration::from_secs(5);++/// A `reqwest` client builder with this backend's connect and request timeouts applied.+pub(crate) fn client_builder() -> reqwest::ClientBuilder {+ reqwest::Client::builder()+ .connect_timeout(CONNECT_TIMEOUT)+ .timeout(REQUEST_TIMEOUT)+}++/// A fresh `opc-request-id`: 32 lowercase hex characters, which OCI echoes in its logs and+/// error responses so a failed call can be traced.+pub(crate) fn request_id(environment: &dyn Environment) -> String {+ environment+ .random_bytes(16)+ .iter()+ .map(|byte| format!("{byte:02x}"))+ .collect()+}++/// Why a single attempt failed, and whether trying again could help.+pub(crate) enum AttemptError {+ /// Transport failure, timeout, throttling or a server-side error.+ Retryable(OciKmsError),+ /// Bad request, auth failure, or anything else a retry would only repeat.+ Fatal(OciKmsError),+}++impl AttemptError {+ /// Classifies a non-success HTTP response.+ pub(crate) fn from_status(status: reqwest::StatusCode, error: OciKmsError) -> Self {+ if is_retryable_status(status) {+ Self::Retryable(error)+ } else {+ Self::Fatal(error)+ }+ }+}++fn is_retryable_status(status: reqwest::StatusCode) -> bool {+ status == reqwest::StatusCode::TOO_MANY_REQUESTS || status.is_server_error()+}++/// Runs `attempt` up to [`MAX_ATTEMPTS`] times, backing off between retryable failures.+/// Each call to `attempt` must build its request afresh: OCI signatures cover the `date`+/// header, so a replayed request would be rejected.+pub(crate) async fn with_retries<T, F, Fut>(+ environment: &dyn Environment,+ operation: &'static str,+ mut attempt: F,+) -> Result<T, OciKmsError>+where+ F: FnMut() -> Fut,+ Fut: Future<Output = Result<T, AttemptError>>,+{+ let mut attempt_number = 1;+ loop {+ match attempt().await {+ Ok(value) => return Ok(value),+ Err(AttemptError::Retryable(error)) if attempt_number < MAX_ATTEMPTS => {+ let delay = backoff(environment, attempt_number);+ tracing::warn!(+ operation,+ attempt = attempt_number,+ ?delay,+ %error,+ "Retrying OCI request"+ );+ tokio::time::sleep(delay).await;+ attempt_number += 1;+ }+ Err(AttemptError::Retryable(error) | AttemptError::Fatal(error)) => return Err(error),+ }+ }+}++/// Exponential backoff with full jitter: uniform over `[0, min(MAX, BASE * 2^(n-1))]`, so+/// pods started together by a scale-up don't retry in lockstep.+fn backoff(environment: &dyn Environment, attempt_number: u32) -> Duration {+ backoff_ceiling(attempt_number).mul_f64(environment.random_f64_unit())+}++fn backoff_ceiling(attempt_number: u32) -> Duration {+ BASE_BACKOFF+ .saturating_mul(2u32.saturating_pow(attempt_number.saturating_sub(1)))+ .min(MAX_BACKOFF)+}++#[cfg(test)]+mod tests {+ use std::sync::atomic::{AtomicU32, Ordering};++ use super::*;+ use crate::environment::SystemEnvironment;++ fn failure() -> OciKmsError {+ OciKmsError::RequestFailed("test".to_owned())+ }++ #[test]+ fn request_id_is_32_hex_characters() {+ let id = request_id(&SystemEnvironment);+ assert_eq!(id.len(), 32);+ assert!(id+ .chars()+ .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()));+ }++ #[test]+ fn throttling_and_server_errors_are_retryable() {+ assert!(is_retryable_status(reqwest::StatusCode::TOO_MANY_REQUESTS));+ assert!(is_retryable_status(+ reqwest::StatusCode::INTERNAL_SERVER_ERROR+ ));+ assert!(is_retryable_status(+ reqwest::StatusCode::SERVICE_UNAVAILABLE+ ));+ }++ #[test]+ fn client_errors_are_not_retryable() {+ assert!(!is_retryable_status(reqwest::StatusCode::BAD_REQUEST));+ assert!(!is_retryable_status(reqwest::StatusCode::UNAUTHORIZED));+ assert!(!is_retryable_status(reqwest::StatusCode::FORBIDDEN));+ assert!(!is_retryable_status(reqwest::StatusCode::NOT_FOUND));+ }++ #[test]+ fn backoff_ceiling_doubles_then_caps() {+ assert_eq!(backoff_ceiling(1), Duration::from_millis(250));+ assert_eq!(backoff_ceiling(2), Duration::from_millis(500));+ assert_eq!(backoff_ceiling(3), Duration::from_secs(1));+ assert_eq!(backoff_ceiling(10), MAX_BACKOFF);+ assert_eq!(backoff_ceiling(u32::MAX), MAX_BACKOFF);+ }++ #[test]+ fn backoff_stays_within_ceiling() {+ for attempt_number in 1..=MAX_ATTEMPTS {+ assert!(backoff(&SystemEnvironment, attempt_number) <= backoff_ceiling(attempt_number));+ }+ }++ #[tokio::test]+ async fn retryable_failures_are_retried_until_success() {+ let attempts = AtomicU32::new(0);+ let result = with_retries(&SystemEnvironment, "test", || async {+ if attempts.fetch_add(1, Ordering::SeqCst) < 2 {+ Err(AttemptError::Retryable(failure()))+ } else {+ Ok("ok")+ }+ })+ .await;++ assert_eq!(result.ok(), Some("ok"));+ assert_eq!(attempts.load(Ordering::SeqCst), 3);+ }++ #[tokio::test]+ async fn fatal_failures_are_not_retried() {+ let attempts = AtomicU32::new(0);+ let result: Result<(), _> = with_retries(&SystemEnvironment, "test", || async {+ attempts.fetch_add(1, Ordering::SeqCst);+ Err(AttemptError::Fatal(failure()))+ })+ .await;++ assert!(result.is_err());+ assert_eq!(attempts.load(Ordering::SeqCst), 1);+ }++ #[tokio::test]+ async fn retries_stop_after_max_attempts() {+ let attempts = AtomicU32::new(0);+ let result: Result<(), _> = with_retries(&SystemEnvironment, "test", || async {+ attempts.fetch_add(1, Ordering::SeqCst);+ Err(AttemptError::Retryable(failure()))+ })+ .await;++ assert!(result.is_err());+ assert_eq!(attempts.load(Ordering::SeqCst), MAX_ATTEMPTS);+ }+}diff --git a/crates/oci_kms/src/workload_identity.rs b/crates/oci_kms/src/workload_identity.rsnew file mode 100644index 0000000000..54ddbd7cc5--- /dev/null+++ b/crates/oci_kms/src/workload_identity.rs@@ -0,0 +1,359 @@+//! Obtains OCI Workload Identity credentials from OKE's proxymux service.+//!+//! OKE writes no credentials to a pod's filesystem. Instead the client generates an+//! ephemeral RSA keypair in memory and trades the pod's own Kubernetes service account+//! token for a session token bound to that keypair. Ported from `oci-go-sdk`'s+//! `x509FederationClientForOkeWorkloadIdentity`+//! (`common/auth/federation_client_oke_workload_identity.go`).++use std::{ffi::OsString, path::PathBuf};++use base64::Engine;+use rsa::pkcs8::EncodePublicKey;++use crate::{+ credentials::{soft_expiry, OciCredentials},+ environment::Environment,+ error::OciKmsError,+ transport::{self, AttemptError},+};++const BASE64_ENGINE: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD;++// Fixed by Kubernetes and OKE rather than by a deployment, so not configurable. Each matches+// `oci-go-sdk` (`common/auth/resource_principal_key_provider.go`, `federation_client.go`),+// which hard-codes the same values.++/// The env var kubelet sets in every pod to the API server's address. The address itself is+/// read at runtime. Proxymux, an Oracle-managed control-plane service, answers on+/// [`PROXYMUX_PORT`] at that same address.+const KUBERNETES_HOST_VAR: &str = "KUBERNETES_SERVICE_HOST";+const PROXYMUX_PORT: u16 = 12250;+const PROXYMUX_PATH: &str = "/resourcePrincipalSessionTokens";++const SESSION_KEY_BITS: usize = 2048;++/// Proxymux returns the token already prefixed, and the `keyId` re-adds it.+const SECURITY_TOKEN_PREFIX: &str = "ST$";++// Where kubelet mounts the pod's service account token and the cluster CA by default. Pods+// that disable `automountServiceAccountToken` and project their own token elsewhere point+// these env vars at it. The CA variable is the one Oracle's SDKs read; the token variable+// follows its naming (the Go SDK offers that override only in code, via `WithSaTokenPath`).++const SERVICE_ACCOUNT_TOKEN_PATH_VAR: &str = "OCI_KUBERNETES_SERVICE_ACCOUNT_TOKEN_PATH";+const DEFAULT_SERVICE_ACCOUNT_TOKEN_PATH: &str =+ "/var/run/secrets/kubernetes.io/serviceaccount/token";++const CLUSTER_CA_PATH_VAR: &str = "OCI_KUBERNETES_SERVICE_ACCOUNT_CERT_PATH";+const DEFAULT_CLUSTER_CA_PATH: &str = "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt";++pub(crate) fn in_kubernetes() -> bool {+ std::env::var_os(KUBERNETES_HOST_VAR).is_some()+}++#[derive(serde::Serialize)]+struct SessionTokenRequest<'a> {+ #[serde(rename = "podKey")]+ pod_key: &'a str,+}++#[derive(serde::Deserialize)]+struct SessionTokenResponse {+ token: String,+}++pub(crate) async fn credentials(+ environment: &dyn Environment,+) -> Result<OciCredentials, OciKmsError> {+ let kubernetes_host = std::env::var(KUBERNETES_HOST_VAR).map_err(|error| {+ OciKmsError::CredentialsUnavailable(format!("{KUBERNETES_HOST_VAR} is unusable: {error}"))+ })?;++ let token_path = path_from_env(+ std::env::var_os(SERVICE_ACCOUNT_TOKEN_PATH_VAR),+ DEFAULT_SERVICE_ACCOUNT_TOKEN_PATH,+ );+ let service_account_token = std::fs::read_to_string(&token_path).map_err(|error| {+ OciKmsError::CredentialsUnavailable(format!(+ "failed to read the pod's Kubernetes service account token at {} ({error}); mount it there with `automountServiceAccountToken: true`, or set {SERVICE_ACCOUNT_TOKEN_PATH_VAR} to where it is projected",+ token_path.display()+ ))+ })?;++ let ca_path = path_from_env(+ std::env::var_os(CLUSTER_CA_PATH_VAR),+ DEFAULT_CLUSTER_CA_PATH,+ );+ let cluster_ca = std::fs::read(&ca_path).map_err(|error| {+ OciKmsError::CredentialsUnavailable(format!(+ "failed to read the Kubernetes cluster CA certificate at {} ({error}); set {CLUSTER_CA_PATH_VAR} if it is mounted elsewhere",+ ca_path.display()+ ))+ })?;++ let private_key = generate_session_key().await?;+ let public_key_pem = private_key+ .to_public_key()+ .to_public_key_pem(rsa::pkcs8::LineEnding::LF)+ .map_err(|error| {+ OciKmsError::CredentialsUnavailable(format!(+ "failed to encode the ephemeral session public key: {error}"+ ))+ })?;++ let body = serde_json::to_vec(&SessionTokenRequest {+ pod_key: &public_key_pem,+ })+ .map_err(|error| {+ OciKmsError::CredentialsUnavailable(format!(+ "failed to serialize the proxymux session token request: {error}"+ ))+ })?;++ let client = proxymux_client(&cluster_ca)?;+ let url = proxymux_url(&kubernetes_host);+ let response_body = transport::with_retries(environment, "oci_proxymux_session_token", || {+ request_session_token(+ environment,+ &client,+ &url,+ service_account_token.trim(),+ &body,+ )+ })+ .await?;++ let session_token = parse_session_token(&response_body)?;++ Ok(OciCredentials {+ soft_expires_at: Some(soft_expiry(&session_token)?),+ key_id: format!("{SECURITY_TOKEN_PREFIX}{session_token}"),+ private_key,+ })+}++async fn request_session_token(+ environment: &dyn Environment,+ client: &reqwest::Client,+ url: &str,+ service_account_token: &str,+ body: &[u8],+) -> Result<String, AttemptError> {+ let response = client+ .post(url)+ .bearer_auth(service_account_token)+ .header("content-type", "application/json")+ .header("opc-request-id", transport::request_id(environment))+ .body(body.to_vec())+ .send()+ .await+ .map_err(|error| {+ AttemptError::Retryable(OciKmsError::CredentialsUnavailable(format!(+ "failed to reach the OKE proxymux service: {error}"+ )))+ })?;++ let status = response.status();+ let response_body = response.text().await.map_err(|error| {+ AttemptError::Retryable(OciKmsError::CredentialsUnavailable(format!(+ "failed to read the proxymux response body: {error}"+ )))+ })?;++ if !status.is_success() {+ // Proxymux answers 403 when the cluster isn't an *enhanced* OKE cluster, which+ // is the usual cause and isn't otherwise obvious from the response.+ let hint = match status {+ reqwest::StatusCode::FORBIDDEN => " (Workload Identity needs an enhanced OKE cluster and a policy granting this service account access)",+ _ => "",+ };+ return Err(AttemptError::from_status(+ status,+ OciKmsError::CredentialsUnavailable(format!(+ "proxymux rejected the session token request with status {status}{hint}: {response_body}"+ )),+ ));+ }++ Ok(response_body)+}++/// The path an override env var names, or `default` when it's unset or empty.+fn path_from_env(override_value: Option<OsString>, default: &str) -> PathBuf {+ override_value+ .filter(|value| !value.is_empty())+ .map_or_else(|| PathBuf::from(default), PathBuf::from)+}++/// `KUBERNETES_SERVICE_HOST` is a bare IP, so an IPv6 address needs brackets in a URL.+fn proxymux_url(kubernetes_host: &str) -> String {+ if kubernetes_host.contains(':') && !kubernetes_host.starts_with('[') {+ format!("https://[{kubernetes_host}]:{PROXYMUX_PORT}{PROXYMUX_PATH}")+ } else {+ format!("https://{kubernetes_host}:{PROXYMUX_PORT}{PROXYMUX_PATH}")+ }+}++/// Trusts the cluster CA alone: this request carries the pod's Kubernetes identity as a+/// bearer token, so accepting any other issuer would risk handing it to an impostor.+/// No proxy is applied either: proxymux is reachable only from inside the cluster.+fn proxymux_client(cluster_ca_pem: &[u8]) -> Result<reqwest::Client, OciKmsError> {+ let certificates = reqwest::Certificate::from_pem_bundle(cluster_ca_pem).map_err(|error| {+ OciKmsError::CredentialsUnavailable(format!(+ "failed to parse the Kubernetes cluster CA certificate: {error}"+ ))+ })?;++ certificates+ .into_iter()+ .fold(+ transport::client_builder()+ .use_rustls_tls()+ .tls_built_in_root_certs(false),+ |builder, certificate| builder.add_root_certificate(certificate),+ )+ .no_proxy()+ .build()+ .map_err(|error| {+ OciKmsError::CredentialsUnavailable(format!(+ "failed to build the proxymux HTTP client: {error}"+ ))+ })+}++/// RSA keygen is CPU-bound and can run for hundreds of milliseconds, so keep it off the+/// async worker threads.+async fn generate_session_key() -> Result<rsa::RsaPrivateKey, OciKmsError> {+ tokio::task::spawn_blocking(|| {+ rsa::RsaPrivateKey::new(&mut rand::rngs::OsRng, SESSION_KEY_BITS)+ })+ .await+ .map_err(|error| {+ OciKmsError::CredentialsUnavailable(format!(+ "the session key generation task failed to complete: {error}"+ ))+ })?+ .map_err(|error| {+ OciKmsError::CredentialsUnavailable(format!(+ "failed to generate the ephemeral session key: {error}"+ ))+ })+}++/// Proxymux answers with a JSON string whose base64-decoded value is itself the JSON+/// `{"token": "ST$<jwt>"}`.+fn parse_session_token(response_body: &str) -> Result<String, OciKmsError> {+ let encoded: String = serde_json::from_str(response_body).map_err(|error| {+ OciKmsError::CredentialsUnavailable(format!(+ "the proxymux response was not a JSON string: {error}"+ ))+ })?;++ let decoded = BASE64_ENGINE.decode(encoded).map_err(|error| {+ OciKmsError::CredentialsUnavailable(format!(+ "failed to base64 decode the proxymux response: {error}"+ ))+ })?;++ let response: SessionTokenResponse = serde_json::from_slice(&decoded).map_err(|error| {+ OciKmsError::CredentialsUnavailable(format!(+ "failed to parse the decoded proxymux response: {error}"+ ))+ })?;++ Ok(response+ .token+ .strip_prefix(SECURITY_TOKEN_PREFIX)+ .unwrap_or(&response.token)+ .to_owned())+}++#[cfg(test)]+mod tests {+ use super::*;++ /// Wraps `inner` the way proxymux does: a JSON string holding base64 of the JSON body.+ fn proxymux_response(inner: &str) -> String {+ serde_json::to_string(&BASE64_ENGINE.encode(inner)).expect("serializable")+ }++ #[test]+ fn parse_session_token_strips_the_security_token_prefix() {+ let body = proxymux_response(r#"{"token":"ST$header.payload.signature"}"#);+ assert_eq!(+ parse_session_token(&body).expect("valid response"),+ "header.payload.signature"+ );+ }++ #[test]+ fn parse_session_token_accepts_an_unprefixed_token() {+ let body = proxymux_response(r#"{"token":"header.payload.signature"}"#);+ assert_eq!(+ parse_session_token(&body).expect("valid response"),+ "header.payload.signature"+ );+ }++ #[test]+ fn parse_session_token_rejects_a_plain_json_object() {+ assert!(parse_session_token(r#"{"token":"ST$abc"}"#).is_err());+ }++ #[test]+ fn parse_session_token_rejects_invalid_base64() {+ assert!(parse_session_token(r#""not base64!""#).is_err());+ }++ #[test]+ fn path_from_env_defaults_when_unset() {+ assert_eq!(+ path_from_env(None, DEFAULT_SERVICE_ACCOUNT_TOKEN_PATH),+ PathBuf::from("/var/run/secrets/kubernetes.io/serviceaccount/token")+ );+ }++ #[test]+ fn path_from_env_defaults_when_empty() {+ assert_eq!(+ path_from_env(Some(OsString::new()), DEFAULT_CLUSTER_CA_PATH),+ PathBuf::from("/var/run/secrets/kubernetes.io/serviceaccount/ca.crt")+ );+ }++ #[test]+ fn path_from_env_uses_the_override() {+ assert_eq!(+ path_from_env(+ Some(OsString::from("/var/run/secrets/tokens/oci-token")),+ DEFAULT_SERVICE_ACCOUNT_TOKEN_PATH+ ),+ PathBuf::from("/var/run/secrets/tokens/oci-token")+ );+ }++ #[test]+ fn proxymux_url_uses_an_ipv4_host_as_is() {+ assert_eq!(+ proxymux_url("10.96.0.1"),+ "https://10.96.0.1:12250/resourcePrincipalSessionTokens"+ );+ }++ #[test]+ fn proxymux_url_brackets_an_ipv6_host() {+ assert_eq!(+ proxymux_url("fd00::1"),+ "https://[fd00::1]:12250/resourcePrincipalSessionTokens"+ );+ }++ #[test]+ fn proxymux_url_keeps_an_already_bracketed_ipv6_host() {+ assert_eq!(+ proxymux_url("[fd00::1]"),+ "https://[fd00::1]:12250/resourcePrincipalSessionTokens"+ );+ }+}diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.tomlindex 1325cb2ae4..6711064f9f 100644--- a/crates/router/Cargo.toml+++ b/crates/router/Cargo.toml@@ -59,6 +59,7 @@ frm = []stripe = []gcp_kms = ["external_services/gcp_kms"]+oci_kms = ["external_services/oci_kms"]release = ["stripe","email",@@ -67,6 +68,7 @@ release = ["vergen","external_services/aws_kms","gcp_kms",+ "oci_kms","external_services/aws_s3","keymanager_mtls","keymanager_create",