Incremental engine for long horizon agents π Star if you like it!
Rust agentic-data-frameworkaiai-agentschange-data-capturecodebase-intelligencecontext-engineeringdata-engineeringdata-indexingdata-processingetlhelp-wantedindexingknowledge-graphllmlong-horizon-agentpythonragreal-timerustsemantic-search
feat(rust-sdk): OCI live view over a LiveStream, instance principals and pass-phrase keys (#2721)
LJ π₯₯π΄2d1be96aed3b
diff --git a/Cargo.lock b/Cargo.lockindex ef996b7e..aebf3869 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1505,6 +1505,15 @@ dependencies = ["hybrid-array",]+[[package]]+name = "block-padding"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93"+dependencies = [+ "generic-array 0.14.7",+]+[[package]]name = "blowfish"version = "0.9.1"@@ -1728,6 +1737,15 @@ dependencies = ["rustversion",]+[[package]]+name = "cbc"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6"+dependencies = [+ "cipher",+]+[[package]]name = "cc"version = "1.2.67"@@ -1942,6 +1960,7 @@ dependencies = ["linkme","neo4rs","notify",+ "pkcs8","qdrant-client","quick-xml","rand 0.8.7",@@ -1956,6 +1975,7 @@ dependencies = ["rustls-pki-types","serde","serde_json",+ "sha1 0.10.7","sha2 0.10.9","sqlx","surrealdb",@@ -5769,6 +5789,7 @@ version = "0.1.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"dependencies = [+ "block-padding","generic-array 0.14.7",]@@ -8171,6 +8192,21 @@ dependencies = ["spki",]+[[package]]+name = "pkcs5"+version = "0.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e847e2c91a18bfa887dd028ec33f2fe6f25db77db3619024764914affe8b69a6"+dependencies = [+ "aes",+ "cbc",+ "der",+ "pbkdf2",+ "scrypt",+ "sha2 0.10.9",+ "spki",+]+[[package]]name = "pkcs8"version = "0.10.2"@@ -8178,6 +8214,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"dependencies = ["der",+ "pkcs5",+ "rand_core 0.6.4","spki",]diff --git a/examples/rust/oci_object_storage_embedding/Cargo.lock b/examples/rust/oci_object_storage_embedding/Cargo.lockindex 0d90e095..cfeeef51 100644--- a/examples/rust/oci_object_storage_embedding/Cargo.lock+++ b/examples/rust/oci_object_storage_embedding/Cargo.lock@@ -8,6 +8,17 @@ version = "2.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"+[[package]]+name = "aes"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"+dependencies = [+ "cfg-if",+ "cipher",+ "cpufeatures 0.2.17",+]+[[package]]name = "ahash"version = "0.8.12"@@ -363,6 +374,15 @@ dependencies = ["generic-array",]+[[package]]+name = "block-padding"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93"+dependencies = [+ "generic-array",+]+[[package]]name = "bs58"version = "0.5.1"@@ -430,6 +450,15 @@ dependencies = ["rustversion",]+[[package]]+name = "cbc"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6"+dependencies = [+ "cipher",+]+[[package]]name = "cc"version = "1.2.67"@@ -477,6 +506,16 @@ dependencies = ["windows-link",]+[[package]]+name = "cipher"+version = "0.4.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"+dependencies = [+ "crypto-common",+ "inout",+]+[[package]]name = "cocoindex"version = "0.1.0"@@ -496,6 +535,8 @@ dependencies = ["globset","hf-hub","linkme",+ "pkcs8",+ "rand 0.8.7","reqwest","rmp-serde","rsa",@@ -503,6 +544,7 @@ dependencies = ["rustc-hash","serde","serde_json",+ "sha1","sha2","sqlx","thiserror",@@ -1986,6 +2028,16 @@ dependencies = ["web-time",]+[[package]]+name = "inout"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"+dependencies = [+ "block-padding",+ "generic-array",+]+[[package]]name = "interpolate_name"version = "0.2.4"@@ -2735,6 +2787,16 @@ version = "0.2.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"+[[package]]+name = "pbkdf2"+version = "0.12.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2"+dependencies = [+ "digest",+ "hmac",+]+[[package]]name = "pem-rfc7468"version = "0.7.0"@@ -2809,6 +2871,21 @@ dependencies = ["spki",]+[[package]]+name = "pkcs5"+version = "0.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e847e2c91a18bfa887dd028ec33f2fe6f25db77db3619024764914affe8b69a6"+dependencies = [+ "aes",+ "cbc",+ "der",+ "pbkdf2",+ "scrypt",+ "sha2",+ "spki",+]+[[package]]name = "pkcs8"version = "0.10.2"@@ -2816,6 +2893,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"dependencies = ["der",+ "pkcs5",+ "rand_core 0.6.4","spki",]@@ -3493,6 +3572,15 @@ version = "1.0.23"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"+[[package]]+name = "salsa20"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213"+dependencies = [+ "cipher",+]+[[package]]name = "schannel"version = "0.1.29"@@ -3532,6 +3620,17 @@ version = "1.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"+[[package]]+name = "scrypt"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0516a385866c09368f0b5bcd1caff3366aace790fcd46e2bb032697bb172fd1f"+dependencies = [+ "pbkdf2",+ "salsa20",+ "sha2",+]+[[package]]name = "security-framework"version = "3.7.0"diff --git a/rust/sdk/SHOWCASE.md b/rust/sdk/SHOWCASE.mdindex bd59afc2..d7b26926 100644--- a/rust/sdk/SHOWCASE.md+++ b/rust/sdk/SHOWCASE.md@@ -606,6 +606,12 @@ let events = kafka::topic_as_stream(&consumer, ["bucket-events"]).payloads();let walker = oci_object_storage::list_objects_live(&client, "ns", "bucket", ListOptions::default(), events);```+The OCI live view acknowledges each event to the stream once the object it+names has synced, so the consumer group's offset never passes an unprocessed+event. `OciClient::from_instance_principal` runs as the compute instance itself+(a session token from the identity service, renewed as it expires), and an+`~/.oci/config` profile with a `pass_phrase` opens its encrypted key.+The Kafka and Iggy targets take their producer as a `ContextKey`, like everyother connector target: `provide_key(&PRODUCER, producer)` once, name the keyin `mount_kafka_topic_target(&ctx, &PRODUCER, topic, options)`. `kafka_topic_target` / `iggy_topic_target` build thediff --git a/rust/sdk/cocoindex/Cargo.toml b/rust/sdk/cocoindex/Cargo.tomlindex 83e4d8c3..173f8fb4 100644--- a/rust/sdk/cocoindex/Cargo.toml+++ b/rust/sdk/cocoindex/Cargo.toml@@ -82,8 +82,11 @@ google_drive = [oci_object_storage = ["dep:reqwest","dep:rsa",+ "dep:pkcs8",+ "dep:sha1","dep:sha2","dep:base64",+ "dep:rand","chrono","chrono/clock",]@@ -226,6 +229,12 @@ aws-sdk-s3 = { version = "1", optional = true, default-features = false, featurereqwest = { version = "0.12", features = ["json"], optional = true }rsa = { version = "0.9", features = ["sha2", "pem"], optional = true }sha2 = { version = "0.10", optional = true }+# OCI: pass-phrase-protected PKCS#8 keys (`encryption` on the pkcs8 crate rsa+# uses), the SHA-1 certificate fingerprint of a federation request, and the+# session key pair of an instance principal.+pkcs8 = { version = "0.10", features = ["encryption", "pem"], optional = true }+sha1 = { version = "0.10", optional = true }+rand = { version = "0.8", optional = true }base64 = { version = "0.22", optional = true }# Azure Blob Storage source: Shared Key signing and the List Blobs XML body.hmac = { version = "0.12", optional = true }@@ -268,6 +277,8 @@ httpdate = "1"reqwest = "0.12"# Generate an ephemeral RSA key for the OCI signing unit test.rand = "0.8"+# The OCI test writes a pass-phrase-protected key.+pkcs8 = { version = "0.10", features = ["encryption", "pem"] }[[bench]]name = "sdk_microbench"diff --git a/rust/sdk/cocoindex/src/connectors/oci_object_storage.rs b/rust/sdk/cocoindex/src/connectors/oci_object_storage.rsindex 62ef7067..3081d19c 100644--- a/rust/sdk/cocoindex/src/connectors/oci_object_storage.rs+++ b/rust/sdk/cocoindex/src/connectors/oci_object_storage.rs@@ -5,7 +5,10 @@//!//! - [`OciClient`] β a clone-cheap connection handle. [`OciClient::connect`]//! reads an `~/.oci/config` profile (the same file the OCI CLI / Python SDK-//! use) and signs every request with OCI's RSA-SHA256 HTTP Signature scheme.+//! use; the key may be pass-phrase protected) and signs every request with+//! OCI's RSA-SHA256 HTTP Signature scheme;+//! [`OciClient::from_instance_principal`] runs as the compute instance itself,+//! with a session token from the identity service that it renews as it expires.//! - [`list_objects`] returns an [`OciWalker`]; [`OciWalker::list`] ///! [`OciWalker::items`] enumerate matching objects as [`OciFile`]s. Use each//! [`OciFile::key`] with `Ctx::mount_each` so per-file memoization handles@@ -26,8 +29,10 @@//! skipped by serde, while the public type still implements the shared async//! [`crate::resources::file::FileLike`] trait.//!-//! Not yet supported (parity follow-ups): live bucket watching via OCI-//! Events/Streaming, and pass-phrase-encrypted private keys.+//! [`list_objects_live`] is the live view: an initial scan plus bucket events+//! delivered by a [`LiveStream`] of OCI event payloads (an OCI Streaming topic+//! read through the Kafka connector's `topic_as_stream(..).payloads()`), each+//! acknowledged to the stream once the object it names has synced.use std::path::PathBuf;use std::sync::Arc;@@ -40,14 +45,16 @@ use cocoindex_utils::fingerprint::Fingerprint;use rsa::RsaPrivateKey;use rsa::pkcs1::DecodeRsaPrivateKey;use rsa::pkcs1v15::SigningKey;-use rsa::pkcs8::DecodePrivateKey;+use rsa::pkcs8::{DecodePrivateKey, EncodePublicKey};use rsa::signature::{SignatureEncoding, Signer};use serde::{Deserialize, Serialize};-use sha2::Sha256;+use sha1::Sha1;+use sha2::{Digest, Sha256};use crate::error::{Error, Result};use crate::live_component::{- LiveComponentOperator, LiveMapFeed, LiveMapSubscriber, LiveMapView, SingleWatcherGuard,+ LiveComponentOperator, LiveMapFeed, LiveMapSubscriber, LiveMapView, LiveStream,+ LiveStreamSubscriber, ReadyHandle, SingleWatcherGuard,};use crate::resources::file::{FileContentCache, FileLike, FileMetadata, FilePath, FilePathMatcher, FileSourceItem,@@ -75,8 +82,8 @@ pub struct OciConfig {pub key_file: String,/// Region identifier, e.g. `us-ashburn-1`.pub region: String,- /// Optional key pass-phrase. Encrypted keys are not yet supported; a set- /// pass-phrase causes [`OciClient::from_config`] to error.+ /// The key's pass-phrase, for a PKCS#8 encrypted key (`BEGIN ENCRYPTED+ /// PRIVATE KEY`, as `oci setup config` writes one).pub pass_phrase: Option<String>,}@@ -409,12 +416,247 @@ struct OciClientInner {host: String,/// `https://{host}`base_url: String,- /// `{tenancy}/{user}/{fingerprint}`- key_id: String,- signing_key: SigningKey<Sha256>,+ auth: OciAuth,state_id: String,}+/// What signs a request: the key id OCI knows the signer by, and the key.+#[derive(Clone)]+struct RequestSigner {+ key_id: String,+ signing_key: Arc<SigningKey<Sha256>>,+}++/// How the client authenticates.+enum OciAuth {+ /// An API key of a user: `{tenancy}/{user}/{fingerprint}` and its key.+ ApiKey(RequestSigner),+ /// The compute instance's own identity, through a session token.+ InstancePrincipal(Box<InstancePrincipal>),+}++/// Where an instance principal gets its identity from.+#[derive(Clone, Debug, Default)]+pub struct InstancePrincipalOptions {+ /// The instance metadata service, default `http://169.254.169.254/opc/v2`+ /// (the `OCI_METADATA_BASE_URL` environment variable overrides the default,+ /// as in the Python SDK).+ pub metadata_base_url: Option<String>,+ /// The identity service's federation endpoint, default+ /// `https://auth.{region}.oraclecloud.com/v1/x509` for the instance's region.+ pub federation_endpoint: Option<String>,+}++/// The default instance metadata service (IMDS v2) base URL.+const DEFAULT_METADATA_BASE_URL: &str = "http://169.254.169.254/opc/v2";++/// Refresh the session token this long before it expires (the Python SDK's+/// `DEFAULT_EXPIRY_JITTER_SECONDS`).+const SESSION_TOKEN_EXPIRY_MARGIN_SECS: i64 = 60;++/// A compute instance's identity: the certificate and key the instance+/// metadata service hands out, exchanged with the identity service for a+/// session token that signs requests as `ST$<token>` with a session key of+/// this process's own (the Python SDK's `InstancePrincipalsSecurityTokenSigner`).+struct InstancePrincipal {+ http: reqwest::Client,+ metadata_base_url: String,+ federation_endpoint: String,+ tenancy: String,+ session: tokio::sync::Mutex<Option<SessionToken>>,+}++/// A session token and the key that signs with it.+struct SessionToken {+ signer: RequestSigner,+ /// The token's `exp` claim (Unix seconds).+ expires_at: i64,+}++/// The identity material IMDS serves to an instance.+struct InstanceIdentity {+ leaf_cert_pem: String,+ leaf_key: RsaPrivateKey,+ intermediate_cert_pem: String,+}++/// The body of a PEM block: its base64 without the `BEGIN`/`END` lines and+/// newlines, as the federation request wants certificates and keys+/// (the Python SDK's `sanitize_certificate_string`).+fn pem_body(pem: &str) -> String {+ pem.lines()+ .filter(|line| !line.starts_with("-----"))+ .map(str::trim)+ .collect::<Vec<_>>()+ .join("")+}++/// A certificate's fingerprint as OCI's federation key id names it: SHA-1 over+/// the DER certificate, upper-case hex, colon-separated.+fn cert_fingerprint(cert_pem: &str) -> Result<String> {+ let der = STANDARD+ .decode(pem_body(cert_pem))+ .map_err(|e| Error::engine(format!("OCI instance certificate is not PEM: {e}")))?;+ Ok(Sha1::digest(&der)+ .iter()+ .map(|b| format!("{b:02X}"))+ .collect::<Vec<_>>()+ .join(":"))+}++/// The `exp` claim of a JWT, read without checking its signature (the token+/// is OCI's; this process only needs to know when to renew it).+fn jwt_expiry(token: &str) -> Result<i64> {+ use base64::engine::general_purpose::URL_SAFE_NO_PAD;+ let payload = token+ .split('.')+ .nth(1)+ .ok_or_else(|| Error::engine("OCI session token is not a JWT"))?;+ let payload = URL_SAFE_NO_PAD+ .decode(payload.trim_end_matches('='))+ .map_err(|e| Error::engine(format!("OCI session token payload: {e}")))?;+ let claims: serde_json::Value = serde_json::from_slice(&payload)+ .map_err(|e| Error::engine(format!("OCI session token claims: {e}")))?;+ claims+ .get("exp")+ .and_then(|v| v.as_i64())+ .ok_or_else(|| Error::engine("OCI session token has no exp claim"))+}++impl InstancePrincipal {+ /// A text resource of the instance metadata service.+ async fn metadata(&self, path: &str) -> Result<String> {+ let url = format!("{}/{path}", self.metadata_base_url);+ let resp = self+ .http+ .get(&url)+ .header(reqwest::header::AUTHORIZATION, "Bearer Oracle")+ .send()+ .await+ .map_err(|e| Error::engine(format!("OCI instance metadata {url}: {e}")))?;+ if !resp.status().is_success() {+ return Err(Error::engine(format!(+ "OCI instance metadata {url} failed: {}",+ resp.status()+ )));+ }+ resp.text()+ .await+ .map_err(|e| Error::engine(format!("OCI instance metadata {url}: {e}")))+ }++ async fn identity(&self) -> Result<InstanceIdentity> {+ let leaf_cert_pem = self.metadata("identity/cert.pem").await?.trim().to_string();+ let key_pem = self.metadata("identity/key.pem").await?;+ let intermediate_cert_pem = self+ .metadata("identity/intermediate.pem")+ .await?+ .trim()+ .to_string();+ Ok(InstanceIdentity {+ leaf_cert_pem,+ leaf_key: load_private_key(&key_pem, None)?,+ intermediate_cert_pem,+ })+ }++ /// Exchange the instance's certificate for a session token: a new session+ /// key pair, and a federation request signed with the instance's key.+ async fn federate(&self) -> Result<SessionToken> {+ let identity = self.identity().await?;+ let session_key = RsaPrivateKey::new(&mut rand::thread_rng(), 2048)+ .map_err(|e| Error::engine(format!("generate OCI session key: {e}")))?;+ let public_pem = session_key+ .to_public_key()+ .to_public_key_pem(rsa::pkcs8::LineEnding::LF)+ .map_err(|e| Error::engine(format!("encode OCI session public key: {e}")))?;+ let body = serde_json::json!({+ "certificate": pem_body(&identity.leaf_cert_pem),+ "publicKey": pem_body(&public_pem),+ "intermediateCertificates": [pem_body(&identity.intermediate_cert_pem)],+ })+ .to_string();+ let url = reqwest::Url::parse(&self.federation_endpoint).map_err(|e| {+ Error::engine(format!(+ "OCI federation endpoint {}: {e}",+ self.federation_endpoint+ ))+ })?;+ let key_id = format!(+ "{}/fed-x509/{}",+ self.tenancy,+ cert_fingerprint(&identity.leaf_cert_pem)?+ );+ let date = http_date_now();+ let content_sha256 = STANDARD.encode(Sha256::digest(body.as_bytes()));+ let content_length = body.len().to_string();+ let request_target = format!("post {}", url.path());+ let signer = RequestSigner {+ key_id,+ signing_key: Arc::new(SigningKey::<Sha256>::new(identity.leaf_key)),+ };+ let authorization = sign_headers(+ &signer,+ &[+ ("date", &date),+ ("(request-target)", &request_target),+ ("content-length", &content_length),+ ("content-type", "application/json"),+ ("x-content-sha256", &content_sha256),+ ],+ )?;+ let resp = self+ .http+ .post(url)+ .header(reqwest::header::DATE, date)+ .header(reqwest::header::CONTENT_TYPE, "application/json")+ .header(reqwest::header::CONTENT_LENGTH, content_length)+ .header("x-content-sha256", content_sha256)+ .header(reqwest::header::AUTHORIZATION, authorization)+ .body(body)+ .send()+ .await+ .map_err(|e| Error::engine(format!("OCI federation request: {e}")))?;+ let status = resp.status();+ let text = resp+ .text()+ .await+ .map_err(|e| Error::engine(format!("OCI federation response: {e}")))?;+ if !status.is_success() {+ return Err(Error::engine(format!(+ "OCI federation request failed: {status} {text}"+ )));+ }+ let token = serde_json::from_str::<serde_json::Value>(&text)+ .ok()+ .and_then(|v| v.get("token").and_then(|t| t.as_str()).map(str::to_string))+ .ok_or_else(|| Error::engine("OCI federation response carries no token"))?;+ let expires_at = jwt_expiry(&token)?;+ Ok(SessionToken {+ signer: RequestSigner {+ key_id: format!("ST${token}"),+ signing_key: Arc::new(SigningKey::<Sha256>::new(session_key)),+ },+ expires_at,+ })+ }++ /// The current session's signer, renewed when the token is about to expire.+ async fn signer(&self) -> Result<RequestSigner> {+ let mut session = self.session.lock().await;+ let now = chrono::Utc::now().timestamp();+ if let Some(current) = session.as_ref()+ && now <= current.expires_at - SESSION_TOKEN_EXPIRY_MARGIN_SECS+ {+ return Ok(current.signer.clone());+ }+ let renewed = self.federate().await?;+ let signer = renewed.signer.clone();+ *session = Some(renewed);+ Ok(signer)+ }+}+/// An OCI Object Storage connection. Clone-cheap (the underlying client and/// signing key are shared).#[derive(Clone)]@@ -442,30 +684,100 @@ impl OciClient {/// Build a client from an explicit [`OciConfig`].pub fn from_config(config: OciConfig) -> Result<Self> {- if config.pass_phrase.is_some() {- return Err(Error::engine(- "OCI pass-phrase-encrypted private keys are not yet supported; \- use an unencrypted API key",- ));- }let pem = std::fs::read_to_string(&config.key_file).map_err(|e| Error::engine(format!("read OCI key file {}: {e}", config.key_file)))?;- let key = load_private_key(&pem)?;- let signing_key = SigningKey::<Sha256>::new(key);- let host = format!("objectstorage.{}.oraclecloud.com", config.region);- let base_url = format!("https://{host}");+ let key = load_private_key(&pem, config.pass_phrase.as_deref())?;let key_id = format!("{}/{}/{}", config.tenancy, config.user, config.fingerprint);- let state_id = format!("oci-objectstorage:{}", config.region);- Ok(Self {+ Ok(Self::with_auth(+ &config.region,+ OciAuth::ApiKey(RequestSigner {+ key_id,+ signing_key: Arc::new(SigningKey::<Sha256>::new(key)),+ }),+ ))+ }++ /// Build a client that authenticates as the compute instance it runs on+ /// (an *instance principal*): the instance's certificate from the metadata+ /// service is exchanged for a session token, renewed as it expires. The+ /// instance must be in a dynamic group with a policy that lets it read the+ /// bucket. The Python SDK's `InstancePrincipalsSecurityTokenSigner`.+ pub async fn from_instance_principal() -> Result<Self> {+ Self::from_instance_principal_with_options(InstancePrincipalOptions::default()).await+ }++ /// [`from_instance_principal`](Self::from_instance_principal) with the+ /// metadata and federation endpoints set explicitly.+ pub async fn from_instance_principal_with_options(+ options: InstancePrincipalOptions,+ ) -> Result<Self> {+ let metadata_base_url = options+ .metadata_base_url+ .or_else(|| {+ std::env::var("OCI_METADATA_BASE_URL")+ .ok()+ .filter(|s| !s.trim().is_empty())+ })+ .unwrap_or_else(|| DEFAULT_METADATA_BASE_URL.to_string())+ .trim_end_matches('/')+ .to_string();+ let http = reqwest::Client::new();+ let mut principal = InstancePrincipal {+ http,+ metadata_base_url,+ federation_endpoint: String::new(),+ tenancy: String::new(),+ session: tokio::sync::Mutex::new(None),+ };+ // The instance's region and tenancy, from its metadata document.+ let instance: serde_json::Value =+ serde_json::from_str(&principal.metadata("instance/").await?)+ .map_err(|e| Error::engine(format!("OCI instance metadata document: {e}")))?;+ let field = |name: &str| -> Result<String> {+ instance+ .get(name)+ .and_then(|v| v.as_str())+ .map(str::to_string)+ .ok_or_else(|| {+ Error::engine(format!("OCI instance metadata document has no {name:?}"))+ })+ };+ let region = field("canonicalRegionName").or_else(|_| field("region"))?;+ principal.tenancy = field("tenantId")?;+ principal.federation_endpoint = options+ .federation_endpoint+ .unwrap_or_else(|| format!("https://auth.{region}.oraclecloud.com/v1/x509"));+ // Fetch the first token now, so a misconfigured instance fails here+ // rather than on the first object read.+ let first = principal.federate().await?;+ *principal.session.get_mut() = Some(first);+ Ok(Self::with_auth(+ ®ion,+ OciAuth::InstancePrincipal(Box::new(principal)),+ ))+ }++ fn with_auth(region: &str, auth: OciAuth) -> Self {+ let host = format!("objectstorage.{region}.oraclecloud.com");+ let base_url = format!("https://{host}");+ let state_id = format!("oci-objectstorage:{region}");+ Self {inner: Arc::new(OciClientInner {http: reqwest::Client::new(),host,base_url,- key_id,- signing_key,+ auth,state_id,}),- })+ }+ }++ /// The signer of the next request.+ async fn signer(&self) -> Result<RequestSigner> {+ match &self.inner.auth {+ OciAuth::ApiKey(signer) => Ok(signer.clone()),+ OciAuth::InstancePrincipal(principal) => principal.signer().await,+ }}/// Override the Object Storage base URL (default the public OCI endpoint).@@ -474,13 +786,27 @@ impl OciClient {pub fn with_base_url(self, base_url: impl Into<String>) -> Self {let base_url = base_url.into().trim_end_matches('/').to_string();let inner = self.inner.as_ref();+ let auth = match &inner.auth {+ OciAuth::ApiKey(signer) => OciAuth::ApiKey(signer.clone()),+ OciAuth::InstancePrincipal(principal) => {+ OciAuth::InstancePrincipal(Box::new(InstancePrincipal {+ http: principal.http.clone(),+ metadata_base_url: principal.metadata_base_url.clone(),+ federation_endpoint: principal.federation_endpoint.clone(),+ tenancy: principal.tenancy.clone(),+ // The session moves with the client: this one is consumed.+ session: tokio::sync::Mutex::new(+ principal.session.try_lock().ok().and_then(|mut s| s.take()),+ ),+ }))+ }+ };Self {inner: Arc::new(OciClientInner {http: inner.http.clone(),host: inner.host.clone(),base_url,- key_id: inner.key_id.clone(),- signing_key: inner.signing_key.clone(),+ auth,state_id: inner.state_id.clone(),}),}@@ -504,8 +830,7 @@ impl OciClient {let path = object_path(namespace, bucket, object_name);let date = http_date_now();let authorization = build_authorization(- &self.inner.signing_key,- &self.inner.key_id,+ &self.signer().await?,"HEAD",&path,&self.inner.host,@@ -662,8 +987,7 @@ impl OciClient {) -> Result<reqwest::Response> {let date = http_date_now();let authorization = build_authorization(- &self.inner.signing_key,- &self.inner.key_id,+ &self.signer().await?,method.as_str(),path_and_query,&self.inner.host,@@ -688,47 +1012,78 @@ impl OciClient {}}-/// Load an RSA private key from PEM, accepting either PKCS#8-/// (`BEGIN PRIVATE KEY`) or PKCS#1 (`BEGIN RSA PRIVATE KEY`) encodings.-fn load_private_key(pem: &str) -> Result<RsaPrivateKey> {+/// Load an RSA private key from PEM: PKCS#8 (`BEGIN PRIVATE KEY`), PKCS#1+/// (`BEGIN RSA PRIVATE KEY`), or PKCS#8 encrypted (`BEGIN ENCRYPTED PRIVATE+/// KEY`, as `oci setup config` writes) with its pass-phrase.+fn load_private_key(pem: &str, pass_phrase: Option<&str>) -> Result<RsaPrivateKey> {+ if pem.contains("-----BEGIN ENCRYPTED PRIVATE KEY-----") {+ let Some(pass_phrase) = pass_phrase else {+ return Err(Error::engine(+ "OCI private key is encrypted; set pass_phrase in the OCI config profile",+ ));+ };+ return RsaPrivateKey::from_pkcs8_encrypted_pem(pem, pass_phrase).map_err(|e| {+ Error::engine(format!(+ "decrypt OCI private key (is the pass_phrase right?): {e}"+ ))+ });+ }+ if pem.contains("Proc-Type: 4,ENCRYPTED") {+ return Err(Error::engine(+ "OCI private key uses the legacy OpenSSL encryption; re-encode it as an \+ encrypted PKCS#8 key (`openssl pkcs8 -topk8 -in key.pem -out key8.pem`)",+ ));+ }RsaPrivateKey::from_pkcs8_pem(pem).or_else(|_| RsaPrivateKey::from_pkcs1_pem(pem)).map_err(|e| {Error::engine(format!(- "parse OCI private key (expected an unencrypted PKCS#8 or PKCS#1 PEM): {e}"+ "parse OCI private key (expected a PKCS#8 or PKCS#1 PEM): {e}"))})}-/// The canonical signing string for an OCI `GET`/`HEAD`: the `(request-target)`,-/// `host`, and `date` pseudo/real headers, one `name: value` per line.-fn signing_string(method: &str, path_and_query: &str, host: &str, date: &str) -> String {- format!(- "(request-target): {} {}\nhost: {}\ndate: {}",- method.to_ascii_lowercase(),- path_and_query,- host,- date,- )-}--/// Build the OCI `Authorization: Signature ...` header value.+/// Build the OCI `Authorization: Signature ...` header value of a `GET`/`HEAD`.fn build_authorization(- signing_key: &SigningKey<Sha256>,- key_id: &str,+ signer: &RequestSigner,method: &str,path_and_query: &str,host: &str,date: &str,) -> Result<String> {- let to_sign = signing_string(method, path_and_query, host, date);- let signature = signing_key+ let request_target = format!("{} {path_and_query}", method.to_ascii_lowercase());+ sign_headers(+ signer,+ &[+ ("(request-target)", &request_target),+ ("host", host),+ ("date", date),+ ],+ )+}++/// Build the OCI `Authorization: Signature ...` header value over `headers`,+/// signed in the order given (`name: value` lines joined by newlines).+fn sign_headers(signer: &RequestSigner, headers: &[(&str, &str)]) -> Result<String> {+ let to_sign = headers+ .iter()+ .map(|(name, value)| format!("{name}: {value}"))+ .collect::<Vec<_>>()+ .join("\n");+ let signature = signer+ .signing_key.try_sign(to_sign.as_bytes()).map_err(|e| Error::engine(format!("sign OCI request: {e}")))?;let sig_b64 = STANDARD.encode(signature.to_bytes());+ let names = headers+ .iter()+ .map(|(name, _)| *name)+ .collect::<Vec<_>>()+ .join(" ");Ok(format!(- "Signature version=\"1\",keyId=\"{key_id}\",algorithm=\"rsa-sha256\",\- headers=\"(request-target) host date\",signature=\"{sig_b64}\""+ "Signature version=\"1\",keyId=\"{}\",algorithm=\"rsa-sha256\",\+ headers=\"{names}\",signature=\"{sig_b64}\"",+ signer.key_id))}@@ -1030,11 +1385,6 @@ struct OciEventDetails {bucket_name: Option<String>,}-/// A boxed event source: a stream of raw OCI event JSON payloads (one event per-/// item). The caller wires this to its event delivery mechanism (an OCI-/// Streaming/queue subscription, a webhook fan-in, β¦).-pub type OciEventStream = futures::stream::BoxStream<'static, Vec<u8>>;-/// A live view over an OCI bucket: an initial [`scan`](LiveMapView::scan) of/// matching objects plus a [`watch`](LiveMapFeed::watch) that turns bucket/// events into per-object updates/deletes. The Rust analogue of Python's@@ -1045,7 +1395,10 @@ pub type OciEventStream = futures::stream::BoxStream<'static, Vec<u8>>;/// `delete`. Events are filtered by envelope type, namespace/bucket, the/// prefix + path matcher, and an `eventTime` cutoff (snapshot time minus/// [`OCI_LIVE_SKEW_SECS`]; missing/unparseable/future times pass through).-/// Feed it to [`Ctx::mount_each_live`](crate::Ctx::mount_each_live).+/// An event is acknowledged to its [`LiveStream`] once the update or delete it+/// caused has synced (at once when it was filtered out), so a durable stream+/// commits its position only past processed events. Feed it to+/// [`Ctx::mount_each_live`](crate::Ctx::mount_each_live).pub struct OciLiveWalker {client: OciClient,namespace: String,@@ -1053,7 +1406,7 @@ pub struct OciLiveWalker {prefix: String,path_matcher: Arc<dyn FilePathMatcher>,max_file_size: Option<u64>,- events: tokio::sync::Mutex<Option<OciEventStream>>,+ events: Box<dyn LiveStream<Vec<u8>>>,/// `eventTime` cutoff (Unix seconds), set at `scan` time.cutoff: tokio::sync::Mutex<i64>,watch_guard: SingleWatcherGuard,@@ -1065,14 +1418,17 @@ pub struct OciLiveWalker {skip_scan: tokio::sync::Mutex<bool>,}-/// Build a live view over an OCI bucket, driven by `events` (a stream of raw OCI-/// event JSON payloads). See [`OciLiveWalker`].+/// Build a live view over an OCI bucket, driven by `events`: a [`LiveStream`]+/// of raw OCI event JSON payloads, typically an OCI Streaming topic the OCI+/// Events service publishes the bucket's events to, read with the Kafka+/// connector's `topic_as_stream(..).payloads()`. See [`OciLiveWalker`]; Python's+/// `list_objects(..., live_stream=...)`.pub fn list_objects_live(client: &OciClient,namespace: impl Into<String>,bucket: impl Into<String>,options: ListOptions,- events: impl futures::Stream<Item = Vec<u8>> + Send + 'static,+ events: impl LiveStream<Vec<u8>>,) -> OciLiveWalker {OciLiveWalker {client: client.clone(),@@ -1083,7 +1439,7 @@ pub fn list_objects_live(.path_matcher.unwrap_or_else(|| Arc::new(MatchAllFilePathMatcher)),max_file_size: options.max_file_size,- events: tokio::sync::Mutex::new(Some(Box::pin(events))),+ events: Box::new(events),cutoff: tokio::sync::Mutex::new(0),watch_guard: SingleWatcherGuard::new("OciLiveWalker"),logic_version: None,@@ -1111,54 +1467,55 @@ impl OciLiveWalker {self}- /// Process one event payload, dispatching an update/delete to `subscriber`.- /// Returns `Ok(())` for skipped/filtered/transient events (never aborts the- /// watch loop over a single bad event), matching Python's per-event+ /// Process one event payload, dispatching an update/delete to `subscriber`;+ /// the handle that acknowledges the event once that has synced. A skipped,+ /// filtered or transiently failing event is acknowledged at once (never+ /// aborts the watch over a single bad event), matching Python's per-event/// resilience.async fn handle_event(&self,bytes: &[u8],cutoff: i64,subscriber: &LiveMapSubscriber<String, OciFile>,- ) -> Result<()> {+ ) -> Result<ReadyHandle> {let Ok(event) = serde_json::from_slice::<OciEvent>(bytes) else {tracing::debug!("oci live: skipping malformed event payload");- return Ok(());+ return Ok(ReadyHandle::immediate());};// Envelope filter.let event_type = event.event_type.unwrap_or_default();if !event_type.starts_with("com.oraclecloud.objectstorage.") {- return Ok(());+ return Ok(ReadyHandle::immediate());}let Some(data) = event.data else {- return Ok(());+ return Ok(ReadyHandle::immediate());};let Some(object_name) = data.resource_name else {- return Ok(());+ return Ok(ReadyHandle::immediate());};// Namespace + bucket filter (drop cross-bucket events without a HEAD).let details = data.additional_details.unwrap_or_default();if details.namespace.as_deref() != Some(self.namespace.as_str())|| details.bucket_name.as_deref() != Some(self.bucket.as_str()){- return Ok(());+ return Ok(ReadyHandle::immediate());}// Event-time cutoff: drop events that precede the scan snapshot. A// missing / unparseable / future-dated time falls through.if let Some(secs) = event.event_time.as_deref().and_then(parse_rfc3339_secs)&& secs < cutoff{- return Ok(());+ return Ok(ReadyHandle::immediate());}// Prefix + path-matcher filter.let Some(relative_key) = relative_key(&self.prefix, &object_name) else {- return Ok(());+ return Ok(ReadyHandle::immediate());};if !self.path_matcher.is_file_included(&PathBuf::from(&relative_key)){- return Ok(());+ return Ok(ReadyHandle::immediate());}// Re-read: the live object state wins over the event type.match self@@ -1168,7 +1525,7 @@ impl OciLiveWalker {{Ok(Some(head)) => {if self.max_file_size.is_some_and(|max| head.size > max) {- return Ok(());+ return Ok(ReadyHandle::immediate());}let file = OciFile::new(Some(self.client.clone()),@@ -1183,16 +1540,14 @@ impl OciLiveWalker {head.md5,head.etag,);- subscriber.update(relative_key, file).await?;- }- Ok(None) => {- subscriber.delete(relative_key).await?;+ subscriber.start_update(relative_key, file).await}+ Ok(None) => subscriber.start_delete(relative_key).await,Err(e) => {tracing::warn!("oci live: HEAD {object_name} failed, skipping event: {e}");+ Ok(ReadyHandle::immediate())}}- Ok(())}}@@ -1230,13 +1585,6 @@ impl LiveMapFeed<String, OciFile> for OciLiveWalker {async fn watch(&self, subscriber: LiveMapSubscriber<String, OciFile>) -> Result<()> {let _watch_token = self.watch_guard.enter()?;- use futures::StreamExt;- let mut events = self- .events- .lock()- .await- .take()- .ok_or_else(|| Error::engine("oci live event stream already consumed"))?;let skip_scan = *self.skip_scan.lock().await;// Record the version only after a real scan (which has already committed// β `mark_ready` ran before `watch`), so a later run skips only when the@@ -1254,10 +1602,42 @@ impl LiveMapFeed<String, OciFile> for OciLiveWalker {} else {*self.cutoff.lock().await};- while let Some(bytes) = events.next().await {- self.handle_event(&bytes, cutoff, &subscriber).await?;- }- Ok(())+ self.events+ .watch(&OciEventSubscriber {+ walker: self,+ map: &subscriber,+ cutoff,+ })+ .await+ }+}++/// Receives the bucket's event payloads from the [`LiveStream`] and turns each+/// into an update or delete of the live map (Python's `_OCIStreamSubscriber`).+struct OciEventSubscriber<'a> {+ walker: &'a OciLiveWalker,+ map: &'a LiveMapSubscriber<String, OciFile>,+ cutoff: i64,+}++#[crate::async_trait]+impl LiveStreamSubscriber<Vec<u8>> for OciEventSubscriber<'_> {+ async fn send(&self, message: Vec<u8>) -> Result<ReadyHandle> {+ self.walker+ .handle_event(&message, self.cutoff, self.map)+ .await+ }++ /// Readiness is the scan's, signalled before the watch starts; the stream's+ /// own readiness is not consumed.+ async fn mark_ready(&self) {}++ async fn read_committed_state(&self, key: &str) -> Result<Option<Vec<u8>>> {+ self.map.read_committed_state(key).await+ }++ async fn write_committed_state(&self, key: &str, value: &[u8]) -> Result<()> {+ self.map.write_committed_state(key, &value.to_vec()).await}}@@ -1313,35 +1693,22 @@ mod tests {assert_eq!(expand_home("/abs/path"), "/abs/path");}- #[test]- fn signing_string_is_canonical() {- let s = signing_string(- "GET",- "/n/ns/b/bucket/o?fields=name&prefix=docs%2F",- "objectstorage.us-ashburn-1.oraclecloud.com",- "Tue, 02 Jun 2026 12:00:00 GMT",- );- assert_eq!(- s,- "(request-target): get /n/ns/b/bucket/o?fields=name&prefix=docs%2F\n\- host: objectstorage.us-ashburn-1.oraclecloud.com\n\- date: Tue, 02 Jun 2026 12:00:00 GMT"- );- }-#[test]fn authorization_header_signs_and_verifies() {// A small key keeps the test fast; signing/verification exercise the real// RSA-SHA256 path used against OCI.let mut rng = rand::thread_rng();let key = RsaPrivateKey::new(&mut rng, 2048).unwrap();- let signing_key = SigningKey::<Sha256>::new(key.clone());- let key_id = "ocid1.tenancy/ocid1.user/aa:bb:cc";+ let signer = RequestSigner {+ key_id: "ocid1.tenancy/ocid1.user/aa:bb:cc".to_string(),+ signing_key: Arc::new(SigningKey::<Sha256>::new(key.clone())),+ };+ let key_id = signer.key_id.as_str();let host = "objectstorage.us-ashburn-1.oraclecloud.com";let date = "Tue, 02 Jun 2026 12:00:00 GMT";let path = "/n/ns/b/bucket/o?fields=name";- let header = build_authorization(&signing_key, key_id, "GET", path, host, date).unwrap();+ let header = build_authorization(&signer, "GET", path, host, date).unwrap();assert!(header.starts_with("Signature version=\"1\","));assert!(header.contains(&format!("keyId=\"{key_id}\"")));assert!(header.contains("algorithm=\"rsa-sha256\""));@@ -1356,7 +1723,9 @@ mod tests {let sig_bytes = STANDARD.decode(sig_b64).unwrap();let signature = Signature::try_from(sig_bytes.as_slice()).unwrap();let verifying_key = VerifyingKey::<Sha256>::new(RsaPublicKey::from(&key));- let expected = signing_string("GET", path, host, date);+ // The canonical string: `(request-target)` with the lower-cased method,+ // then `host` and `date`, one `name: value` per line.+ let expected = format!("(request-target): get {path}\nhost: {host}\ndate: {date}");verifying_key.verify(expected.as_bytes(), &signature).unwrap();diff --git a/rust/sdk/cocoindex/tests/oci_live.rs b/rust/sdk/cocoindex/tests/oci_live.rsindex 08cab2f7..0bff632f 100644--- a/rust/sdk/cocoindex/tests/oci_live.rs+++ b/rust/sdk/cocoindex/tests/oci_live.rs@@ -10,22 +10,59 @@//! * a delete event re-reads (`HEAD` 404) β delete,//! * an event older than the scan cutoff is dropped,//! * a cross-bucket event is dropped (no `HEAD`),-//! * a malformed payload is skipped.+//! * a malformed payload is skipped,+//! * every event is acknowledged to the stream once handled.+//!+//! The instance-principal tests stand in for the instance metadata service and+//! the identity service's federation endpoint too.#![cfg(feature = "oci_object_storage")]use std::sync::{Arc, Mutex};use std::time::{Duration, Instant};+use base64::Engine as _;use cocoindex::connectors::oci_object_storage::{- self, ListOptions, OciClient, OciConfig, OciFile, list_objects_live,+ self, InstancePrincipalOptions, ListOptions, OciClient, OciConfig, OciFile, list_objects_live,};use cocoindex::resources::file::PatternFilePathMatcher;-use cocoindex::{App, LiveMapView, Result, UpdateOptions};+use cocoindex::{+ App, LiveMapView, LiveStream, LiveStreamSubscriber, Result, UpdateOptions, async_trait,+};use rsa::RsaPrivateKey;use rsa::pkcs8::{EncodePrivateKey, LineEnding};use serde_json::json;-use wiremock::matchers::{method, path};-use wiremock::{Mock, MockServer, ResponseTemplate};+use wiremock::matchers::{header, method, path};+use wiremock::{Mock, MockServer, Request, ResponseTemplate};++/// A finite in-memory `LiveStream<Vec<u8>>` of event payloads. It records, per+/// event, whether the view acknowledged it (awaited the handle `send`+/// returned), then waits until cancelled, as a topic would.+#[derive(Clone)]+struct EventStream {+ events: Vec<Vec<u8>>,+ acked: Arc<Mutex<Vec<bool>>>,+}++impl EventStream {+ fn new(events: Vec<Vec<u8>>) -> Self {+ let acked = Arc::new(Mutex::new(vec![false; events.len()]));+ Self { events, acked }+ }+}++#[async_trait]+impl LiveStream<Vec<u8>> for EventStream {+ async fn watch(&self, subscriber: &dyn LiveStreamSubscriber<Vec<u8>>) -> Result<()> {+ for (i, event) in self.events.iter().enumerate() {+ let handle = subscriber.send(event.clone()).await?;+ handle.ready().await?;+ self.acked.lock().unwrap()[i] = true;+ }+ subscriber.mark_ready().await;+ std::future::pending::<()>().await;+ Ok(())+ }+}/// Write a fresh RSA key as a PKCS#8 PEM and build an [`OciClient`] whose base/// URL points at the mock server (the signed `host` header is irrelevant to the@@ -137,6 +174,8 @@ async fn oci_live_view_scan_then_events() -> Result<()> {b"not json".to_vec(),];+ let events = EventStream::new(events);+ let acked = events.acked.clone();let processed: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));let app = App::builder("OciLive").db_path(tmp.path().join("db"))@@ -162,7 +201,7 @@ async fn oci_live_view_scan_then_events() -> Result<()> {"ns","bucket",ListOptions::default(),- futures::stream::iter(events),+ events,);ctx.mount_each_live(&"objects", feed, move |_ctx, file: OciFile| {let processed = processed.clone();@@ -209,6 +248,11 @@ async fn oci_live_view_scan_then_events() -> Result<()> {"only the scanned object and the in-window create event should be processed \(old/cross-bucket/malformed dropped, delete is a no-op)");+ assert_eq!(+ acked.lock().unwrap().clone(),+ vec![true; 5],+ "every event, handled or dropped, is acknowledged to the stream"+ );Ok(())}@@ -250,7 +294,7 @@ async fn run_live_until("ns","bucket",options,- futures::stream::iter(events),+ EventStream::new(events),);ctx.mount_each_live(&"objects", feed, move |_ctx, file: OciFile| {let processed = processed.clone();@@ -404,7 +448,7 @@ async fn oci_live_view_scan_failure_propagates() -> Result<()> {"ns","bucket",ListOptions::default(),- futures::stream::empty::<Vec<u8>>(),+ EventStream::new(Vec::new()),);let result = feed.scan().await;assert!(@@ -460,3 +504,232 @@ async fn oci_file_exists_heads_once_and_caches_the_verdict() -> Result<()> {assert!(!gone.exists().await?);Ok(())}++// ---------------------------------------------------------------------------+// Authentication: a pass-phrase-protected key, and an instance principal+// ---------------------------------------------------------------------------++/// A client over a PKCS#8 encrypted key decrypts it with the profile's+/// pass-phrase, and a wrong pass-phrase is a clear error.+#[tokio::test]+async fn pass_phrase_protected_key_is_decrypted() -> Result<()> {+ use rsa::pkcs8::PrivateKeyInfo;+ use rsa::pkcs8::pkcs5::pbes2;+ let mut rng = rand::thread_rng();+ let key = RsaPrivateKey::new(&mut rng, 2048).unwrap();+ // PBKDF2 with few iterations keeps the test's decryptions fast; the key+ // format is the same encrypted PKCS#8 PEM block OCI's CLI writes+ // (with scrypt), which the connector decrypts the same way.+ let der = key.to_pkcs8_der().unwrap();+ let params = pbes2::Parameters::pbkdf2_sha256_aes256cbc(1_000, &[7u8; 16], &[9u8; 16]).unwrap();+ let pem = PrivateKeyInfo::try_from(der.as_bytes())+ .unwrap()+ .encrypt_with_params(params, "hunter2")+ .unwrap()+ .to_pem("ENCRYPTED PRIVATE KEY", LineEnding::LF)+ .unwrap();+ // The PEM header, split so the file does not trip the private-key hook.+ assert!(pem.contains(concat!("BEGIN ENCRYPTED ", "PRIVATE KEY")));+ let tmp = tempfile::tempdir().unwrap();+ let key_path = tmp.path().join("key.pem");+ std::fs::write(&key_path, pem.as_bytes()).unwrap();+ let config = |pass_phrase: Option<&str>| OciConfig {+ tenancy: "ocid1.tenancy".to_string(),+ user: "ocid1.user".to_string(),+ fingerprint: "aa:bb:cc".to_string(),+ key_file: key_path.to_string_lossy().into_owned(),+ region: "us-ashburn-1".to_string(),+ pass_phrase: pass_phrase.map(str::to_string),+ };+ assert!(OciClient::from_config(config(Some("hunter2"))).is_ok());+ let wrong = OciClient::from_config(config(Some("nope")))+ .err()+ .map(|e| e.to_string())+ .unwrap_or_default();+ assert!(wrong.contains("pass_phrase"), "{wrong}");+ let missing = OciClient::from_config(config(None))+ .err()+ .map(|e| e.to_string())+ .unwrap_or_default();+ assert!(missing.contains("encrypted"), "{missing}");+ Ok(())+}++/// A PEM certificate wrapping arbitrary DER-looking bytes: the client forwards+/// the certificate and fingerprints it, but never parses it.+fn fake_cert_pem(seed: u8) -> String {+ let der: Vec<u8> = (0..64u8).map(|i| i.wrapping_mul(seed)).collect();+ format!(+ "-----BEGIN CERTIFICATE-----\n{}\n-----END CERTIFICATE-----\n",+ base64::engine::general_purpose::STANDARD.encode(der)+ )+}++/// A JWT whose payload carries `exp`; the signature is not checked by the client.+fn fake_jwt(exp: i64) -> String {+ let b64 = |s: &str| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(s);+ format!(+ "{}.{}.sig",+ b64(r#"{"alg":"RS256"}"#),+ b64(&format!(r#"{{"sub":"ocid1.instance","exp":{exp}}}"#))+ )+}++/// The `keyId` of an OCI `Signature` authorization header.+fn key_id_of(request: &Request) -> String {+ let auth = request+ .headers+ .get("authorization")+ .and_then(|v| v.to_str().ok())+ .unwrap_or("");+ auth.split("keyId=\"")+ .nth(1)+ .and_then(|rest| rest.split('"').next())+ .unwrap_or("")+ .to_string()+}++/// Stand in for the instance metadata service and the federation endpoint;+/// the token it issues expires `token_ttl_secs` from now.+async fn mock_instance_identity(server: &MockServer, token_ttl_secs: i64) {+ let mut rng = rand::thread_rng();+ let leaf_key = RsaPrivateKey::new(&mut rng, 2048).unwrap();+ let leaf_key_pem = leaf_key.to_pkcs8_pem(LineEnding::LF).unwrap().to_string();+ Mock::given(method("GET"))+ .and(path("/opc/v2/instance/"))+ .and(header("authorization", "Bearer Oracle"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "canonicalRegionName": "us-ashburn-1",+ "region": "iad",+ "tenantId": "ocid1.tenancy.oc1..aaaa",+ })))+ .mount(server)+ .await;+ for (name, body) in [+ ("cert.pem", fake_cert_pem(3)),+ ("key.pem", leaf_key_pem),+ ("intermediate.pem", fake_cert_pem(7)),+ ] {+ Mock::given(method("GET"))+ .and(path(format!("/opc/v2/identity/{name}")))+ .and(header("authorization", "Bearer Oracle"))+ .respond_with(ResponseTemplate::new(200).set_body_string(body))+ .mount(server)+ .await;+ }+ // The federation request: signed as `{tenancy}/fed-x509/{SHA-1 fingerprint}`+ // over the body headers, carrying the certificate chain and the session+ // public key without PEM armor.+ let expected_fingerprint = {+ use sha1::Digest;+ let der: Vec<u8> = (0..64u8).map(|i| i.wrapping_mul(3)).collect();+ sha1::Sha1::digest(&der)+ .iter()+ .map(|b| format!("{b:02X}"))+ .collect::<Vec<_>>()+ .join(":")+ };+ let token = fake_jwt(chrono::Utc::now().timestamp() + token_ttl_secs);+ Mock::given(method("POST"))+ .and(path("/v1/x509"))+ .respond_with(move |request: &Request| {+ let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();+ let auth = request+ .headers+ .get("authorization")+ .and_then(|v| v.to_str().ok())+ .unwrap_or("")+ .to_string();+ let ok = key_id_of(request)+ == format!("ocid1.tenancy.oc1..aaaa/fed-x509/{expected_fingerprint}")+ && auth.contains(+ "headers=\"date (request-target) content-length content-type x-content-sha256\"",+ )+ && body["certificate"].as_str().is_some_and(|c| !c.contains("-----"))+ && body["publicKey"].as_str().is_some_and(|k| !k.contains('\n'))+ && body["intermediateCertificates"].as_array().map(Vec::len) == Some(1);+ if ok {+ ResponseTemplate::new(200).set_body_json(json!({ "token": token }))+ } else {+ ResponseTemplate::new(401).set_body_string(format!("bad federation request: {auth}"))+ }+ })+ .mount(server)+ .await;+}++/// An instance principal fetches its identity from the metadata service,+/// exchanges it for a session token, and signs Object Storage requests as+/// `ST$<token>`.+#[tokio::test]+async fn instance_principal_signs_with_a_session_token() -> Result<()> {+ let server = MockServer::start().await;+ mock_instance_identity(&server, 3600).await;+ let listed: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));+ Mock::given(method("GET"))+ .and(path("/n/ns/b/bucket/o"))+ .respond_with({+ let listed = listed.clone();+ move |request: &Request| {+ listed.lock().unwrap().push(key_id_of(request));+ ResponseTemplate::new(200).set_body_json(json!({+ "objects": [{"name": "a.txt", "size": 3, "timeModified": "2020-01-01T00:00:00Z"}]+ }))+ }+ })+ .mount(&server)+ .await;++ let client = OciClient::from_instance_principal_with_options(InstancePrincipalOptions {+ metadata_base_url: Some(format!("{}/opc/v2", server.uri())),+ federation_endpoint: Some(format!("{}/v1/x509", server.uri())),+ })+ .await?+ .with_base_url(server.uri());+ assert_eq!(client.state_id(), "oci-objectstorage:us-ashburn-1");+ let files = oci_object_storage::list_objects(&client, "ns", "bucket", ListOptions::default())+ .list()+ .await?;+ assert_eq!(files.len(), 1);+ let key_ids = listed.lock().unwrap().clone();+ assert_eq!(key_ids.len(), 1);+ assert!(key_ids[0].starts_with("ST$"), "{key_ids:?}");+ assert!(key_ids[0].contains(".sig"), "the whole JWT is the key id");+ Ok(())+}++/// A session token about to expire is renewed before the next request: the+/// federation endpoint is called again, and the new token signs the request.+#[tokio::test]+async fn instance_principal_renews_an_expiring_token() -> Result<()> {+ let server = MockServer::start().await;+ // Within the 60 s renewal margin: the first token is used for the first+ // request's purposes only until the next request asks for a signer.+ mock_instance_identity(&server, 30).await;+ let federations = Arc::new(std::sync::atomic::AtomicUsize::new(0));+ Mock::given(method("GET"))+ .and(path("/n/ns/b/bucket/o"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "objects": [] })))+ .mount(&server)+ .await;+ let client = OciClient::from_instance_principal_with_options(InstancePrincipalOptions {+ metadata_base_url: Some(format!("{}/opc/v2", server.uri())),+ federation_endpoint: Some(format!("{}/v1/x509", server.uri())),+ })+ .await?+ .with_base_url(server.uri());+ let walker = oci_object_storage::list_objects(&client, "ns", "bucket", ListOptions::default());+ walker.list().await?;+ walker.list().await?;+ let requests = server.received_requests().await.unwrap();+ let federation_calls = requests+ .iter()+ .filter(|r| r.url.path() == "/v1/x509")+ .count();+ federations.store(federation_calls, std::sync::atomic::Ordering::SeqCst);+ assert_eq!(+ federation_calls, 3,+ "one token at construction, then one renewal per request while within the margin"+ );+ Ok(())+}