From 6b0dfc1957fb6cb87d40b5c3bd6570aa7e8a896e Mon Sep 17 00:00:00 2001 From: Salman Mohammed Date: Wed, 25 Nov 2026 17:12:07 -0500 Subject: [PATCH] feat(search): sign OpenSearch requests with AWS SigV4 (#9947) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary The relay's OpenSearch client could only use HTTP basic auth. Amazon OpenSearch Serverless accepts only requests signed with AWS SigV4, and managed Amazon OpenSearch Service domains can require them, so the relay could not index into either. This PR adds optional SigV4 signing. It is off by default; basic auth and unauthenticated clusters work as before. | Variable | Meaning | | --- | --- | | `BUZZ_OPENSEARCH_AWS_SIGV4_SERVICE` | Turns signing on and names the signing service: `aoss` for a Serverless collection, `es` for a managed domain. Unset means no signing. | | `BUZZ_OPENSEARCH_AWS_REGION` | Region to sign for. Defaults to `AWS_REGION`, then `AWS_DEFAULT_REGION`. | The relay refuses to start when signing is set without a region, together with basic auth, without `BUZZ_OPENSEARCH_URL`, or with a service other than `es` or `aoss`. - **Credentials** come from the AWS default chain: environment variables, the shared profile, a web identity token, then the container or instance role. No keys are added to the relay's own settings. - **Refresh** (`aws_credentials.rs`): the `opensearch` crate asks its credentials provider on every request, and the AWS default chain does not cache. Used directly, every search and bulk write would call the token service or the instance metadata endpoint. The relay keeps one set of credentials and reloads it five minutes before it expires (every 15 minutes for credentials without an expiry). Each load builds the AWS provider anew, because a kept one never rereads the shared profile; a key rotated there is picked up at the next load. Concurrent requests share one load, whether it succeeds or fails: the next load starts at least 30 s after the last one ended, and requests in between use the valid set or fail at once. A first load is bounded at 30 s. A reload while the current set is still valid is bounded at 5 s, and if it fails the current set stays in use. - **Logging:** a failed credential load logs only the kind of error, because the causes can carry what a `credential_process` helper printed. The AWS SDK logs the full cause itself under `aws_config` at warn level, which the relay's default log filter leaves out; the deployment doc says how to turn it on and what it can contain. Credentials are never logged, and the config's `Debug` output shows only the service and region. - **Dependencies:** enables the `opensearch` crate's `aws-auth` feature and adds `aws-config` for the credential chain. ### Worth knowing - The region is not read from the shared AWS profile file, only from the variables above. - Right after a Serverless collection became active, the first signed request got HTTP 401 once; the same run passed 45 s later. The indexer already retries such failures. - A Serverless collection does not support `_refresh`, which only the tests' `SearchIndex::refresh` uses. ### Related issue N/A. Closest existing work: #9838 (the OpenSearch index this client writes to) and #9862. No duplicate found. ### Testing - Unit tests: startup validation of the new settings; credentials are loaded once, survive a failed reload, a failed first load is not repeated per request, requests waiting on a stalled load share its one failure, and a key rotated in a shared profile file is picked up. - Local, unauthenticated OpenSearch 2.19.3: the `postgres_opensearch_search` suite, plus index create, bulk write, search, bulk delete and index delete through `SearchIndex`. - Verified against an Amazon OpenSearch Serverless collection through `SearchIndex` with `aoss` signing and credentials from a shared profile: alias check, index create, bulk write of documents with `community:event_id` ids, search (3 hits), bulk delete of one document, search (2 hits), index delete. On the same collection an unsigned client got HTTP 403 for search and bulk write, and a client signing for `es` got HTTP 403. - The relay binary refuses to start with signing and no region, and with signing plus basic auth. - Not run: a managed domain (`es` signing), and the web identity, container and instance role credential sources. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Salman Mohammed Co-authored-by: Claude Fable 5.2 --- .env.example | 2 + Cargo.lock | 406 ++++++++++++++++++ Cargo.toml | 5 +- crates/buzz-relay/src/config.rs | 126 +++++- crates/buzz-search/Cargo.toml | 3 + crates/buzz-search/src/aws_credentials.rs | 340 +++++++++++++++ crates/buzz-search/src/lib.rs | 1 + crates/buzz-search/src/opensearch.rs | 35 ++ .../tests/postgres_opensearch_consistency.rs | 2 + .../tests/postgres_opensearch_search.rs | 4 + crates/buzz-search/tests/search_suite/mod.rs | 1 + docs/opensearch-search-deployment.md | 18 + 12 files changed, 941 insertions(+), 2 deletions(-) create mode 100644 crates/buzz-search/src/aws_credentials.rs diff --git a/.env.example b/.env.example index b180396006..b5bc988d33 100644 --- a/.env.example +++ b/.env.example @@ -187,6 +187,8 @@ BUZZ_PUSH_GATEWAY_DELIVERY_URL=https://push.buzz.xyz/v1/deliveries/apns # BUZZ_OPENSEARCH_URL=http://localhost:9200 # BUZZ_OPENSEARCH_USERNAME= # BUZZ_OPENSEARCH_PASSWORD= +# BUZZ_OPENSEARCH_AWS_SIGV4_SERVICE=aoss +# BUZZ_OPENSEARCH_AWS_REGION=us-east-1 # BUZZ_OPENSEARCH_PREVIEW=true # BUZZ_SEARCH_INDEXER_WORKERS=1 diff --git a/Cargo.lock b/Cargo.lock index 74f1b02270..ea2ada04d6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -498,6 +498,49 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" +[[package]] +name = "aws-config" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "939e256cfe0ed68e96d32f194339d88210d5c10685cff0787400158f852c6819" +dependencies = [ + "aws-credential-types", + "aws-runtime", + "aws-sdk-sso", + "aws-sdk-ssooidc", + "aws-sdk-sts", + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-json", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", + "aws-types", + "bytes", + "fastrand", + "hex", + "http", + "sha1 0.10.6", + "time", + "tokio", + "tracing", + "url", + "zeroize", +] + +[[package]] +name = "aws-credential-types" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "576e8da35751dc85409ec1cd15999f692c277a1fbe9336780fe6f15e49dd637d" +dependencies = [ + "aws-smithy-async", + "aws-smithy-runtime-api", + "aws-smithy-types", + "zeroize", +] + [[package]] name = "aws-creds" version = "0.39.1" @@ -547,6 +590,325 @@ dependencies = [ "thiserror 2.0.18", ] +[[package]] +name = "aws-runtime" +version = "1.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a0cc2144962cc5e358467b16e3d82981b1d424a7c3d34602be0036103814a1a" +dependencies = [ + "aws-credential-types", + "aws-sigv4", + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-types", + "aws-types", + "bytes", + "bytes-utils", + "fastrand", + "http", + "http-body", + "percent-encoding", + "pin-project-lite", + "tracing", + "uuid", +] + +[[package]] +name = "aws-sdk-sso" +version = "1.117.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5316813498fa9c403877007934ae448aa44b18136f58051f8fa3c5b79b44bdc6" +dependencies = [ + "arc-swap", + "aws-credential-types", + "aws-runtime", + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-json", + "aws-smithy-observability", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", + "aws-types", + "bytes", + "fastrand", + "http", + "regex-lite", + "tracing", +] + +[[package]] +name = "aws-sdk-ssooidc" +version = "1.119.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31db35e5662787b786daba15f431e4393c7ea512b70fa112bd048d1f3ecf877a" +dependencies = [ + "arc-swap", + "aws-credential-types", + "aws-runtime", + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-json", + "aws-smithy-observability", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", + "aws-types", + "bytes", + "fastrand", + "http", + "regex-lite", + "tracing", +] + +[[package]] +name = "aws-sdk-sts" +version = "1.122.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a10491638d9e560db90c484dbc77d73b8ad202780cdc9b9e92180603acb07ada" +dependencies = [ + "arc-swap", + "aws-credential-types", + "aws-runtime", + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-json", + "aws-smithy-observability", + "aws-smithy-query", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", + "aws-smithy-xml", + "aws-types", + "fastrand", + "http", + "regex-lite", + "tracing", +] + +[[package]] +name = "aws-sigv4" +version = "1.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d3d48355cb86b15ccbb38b8bc6b87500c824ee4ed8cbc10a961b435242b5e16" +dependencies = [ + "aws-credential-types", + "aws-smithy-http", + "aws-smithy-runtime-api", + "aws-smithy-types", + "bytes", + "form_urlencoded", + "hex", + "hmac 0.13.0", + "http", + "percent-encoding", + "sha2 0.11.0", + "time", + "tracing", +] + +[[package]] +name = "aws-smithy-async" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de681a9df7ff79823b759ee17061076ec049cd61a8fa28ece4293d89c9f6964e" +dependencies = [ + "futures-util", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "aws-smithy-http" +version = "0.64.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba8960956e0ee0ca3f3161e62913a61bc65a7ef638ca3ef1d4c7159f8443e398" +dependencies = [ + "aws-smithy-runtime-api", + "aws-smithy-types", + "bytes", + "bytes-utils", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "percent-encoding", + "pin-project-lite", + "tracing", +] + +[[package]] +name = "aws-smithy-http-client" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeca69f65362f7375891008ea525fd440ad6db1836458ac188c87b126804114e" +dependencies = [ + "aws-smithy-async", + "aws-smithy-runtime-api", + "aws-smithy-types", + "h2", + "http", + "hyper", + "hyper-rustls", + "hyper-util", + "pin-project-lite", + "rustls", + "rustls-native-certs", + "rustls-pki-types", + "tokio", + "tokio-rustls", + "tower 0.5.3", + "tracing", +] + +[[package]] +name = "aws-smithy-json" +version = "0.65.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f6835fb38bc6fc8c91e584b0366eb4ff595e5c485134dbf4f0bdeaa18856666" +dependencies = [ + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", +] + +[[package]] +name = "aws-smithy-observability" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e86338c869539a581bf161247762a6e87f92c5c075060057b5ed6d06632ed0c" +dependencies = [ + "aws-smithy-runtime-api", +] + +[[package]] +name = "aws-smithy-query" +version = "0.64.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "165f6265342a313ad6f7a1ac17a0cdba30c522039d3f41d8d6871ce8a2b34ecd" +dependencies = [ + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", + "aws-smithy-xml", + "urlencoding", +] + +[[package]] +name = "aws-smithy-runtime" +version = "1.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79cef0c41e8ca40f74f68ed8ee4d1ddbde12bb847b95ef9b3c025681ddfae58a" +dependencies = [ + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-http-client", + "aws-smithy-observability", + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", + "bytes", + "fastrand", + "http", + "http-body", + "http-body-util", + "pin-project-lite", + "tokio", + "tracing", +] + +[[package]] +name = "aws-smithy-runtime-api" +version = "1.19.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06788004dea79018413f381891da6dcca23196acd79c4d51b767fbdacc76eae4" +dependencies = [ + "aws-smithy-async", + "aws-smithy-runtime-api-macros", + "aws-smithy-types", + "bytes", + "http", + "pin-project-lite", + "tokio", + "tracing", + "zeroize", +] + +[[package]] +name = "aws-smithy-runtime-api-macros" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce237f890a2283c9b328955c3b0918d2d5bf66a1cb6ceccd36a0047246fbc6e6" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "aws-smithy-schema" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bec8dae1015a6d959a5faf86fbdf77486cfe19e4ccb6ee009d8a46efc45028a4" +dependencies = [ + "aws-smithy-runtime-api", + "aws-smithy-types", + "http", +] + +[[package]] +name = "aws-smithy-types" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55752025c39c0e094962fd73f1c57014b191f678612e517f219468e575af9822" +dependencies = [ + "base64-simd", + "bytes", + "bytes-utils", + "http", + "http-body", + "http-body-util", + "itoa", + "num-integer", + "pin-project-lite", + "ryu", + "serde", + "time", +] + +[[package]] +name = "aws-smithy-xml" +version = "0.64.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6581618a2fd006159016d1c36881d94d61b4a017f4a8d631310875e18252413" +dependencies = [ + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", + "xmlparser", +] + +[[package]] +name = "aws-types" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ba0d970d3947bb064d2ae1d823efa186c1dbde88f88afa8f6549946e5d8deee" +dependencies = [ + "aws-credential-types", + "aws-smithy-async", + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", + "rustc_version", + "tracing", +] + [[package]] name = "axum" version = "0.8.9" @@ -655,6 +1017,16 @@ version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +[[package]] +name = "base64-simd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "339abbe78e73178762e23bea9dfd08e697eb3f3301cd4be981c0f78ba5859195" +dependencies = [ + "outref", + "vsimd", +] + [[package]] name = "base64ct" version = "1.8.3" @@ -1553,6 +1925,8 @@ dependencies = [ name = "buzz-search" version = "0.1.0" dependencies = [ + "aws-config", + "aws-credential-types", "axum", "buzz-core", "buzz-datastore-tracing", @@ -1697,6 +2071,16 @@ version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" +[[package]] +name = "bytes-utils" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dafe3a8757b027e2be6e4e5601ed563c55989fcf1546e933c66c8eb3a058d35" +dependencies = [ + "bytes", + "either", +] + [[package]] name = "bzip2" version = "0.4.4" @@ -6976,6 +7360,10 @@ version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af6815a23449a0860c8fe049a828c3589d3ad56d3b5875d0d1f340d1291871e" dependencies = [ + "aws-credential-types", + "aws-sigv4", + "aws-smithy-runtime-api", + "aws-types", "base64 0.22.1", "bytes", "dyn-clone", @@ -7221,6 +7609,12 @@ dependencies = [ "memchr", ] +[[package]] +name = "outref" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e" + [[package]] name = "p256" version = "0.14.0" @@ -11513,6 +11907,12 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" +[[package]] +name = "vsimd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64" + [[package]] name = "vtparse" version = "0.6.2" @@ -12506,6 +12906,12 @@ version = "0.8.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ae8337f8a065cfc972643663ea4279e04e7256de865aa66fe25cec5fb912d3f" +[[package]] +name = "xmlparser" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66fee0b777b0f5ac1c69bb06d361268faafa61cd4682ae064a171c16c433e9e4" + [[package]] name = "xmltree" version = "0.10.3" diff --git a/Cargo.toml b/Cargo.toml index 72313f1864..67c3f98414 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -109,7 +109,10 @@ jsonwebtoken = { version = "10.4.0", default-features = false, features = ["aws_ # HTTP client (webhook delivery) reqwest = { version = "0.13", features = ["json", "rustls", "stream"], default-features = false } -opensearch = { version = "2.4", default-features = false, features = ["rustls-tls"] } +opensearch = { version = "2.4", default-features = false, features = ["rustls-tls", "aws-auth"] } +# AWS credential chain, for SigV4-signed OpenSearch requests +aws-config = "1" +aws-credential-types = "1" # Cryptography sha2 = "0.11" diff --git a/crates/buzz-relay/src/config.rs b/crates/buzz-relay/src/config.rs index 1e1a871a67..4f6a0afc78 100644 --- a/crates/buzz-relay/src/config.rs +++ b/crates/buzz-relay/src/config.rs @@ -306,7 +306,8 @@ pub struct Config { pub storage_usage_delivery_url: Option, /// OpenSearch cluster for message search (`BUZZ_OPENSEARCH_URL`, with - /// optional `BUZZ_OPENSEARCH_USERNAME` and `BUZZ_OPENSEARCH_PASSWORD`). + /// optional `BUZZ_OPENSEARCH_USERNAME` and `BUZZ_OPENSEARCH_PASSWORD`, or + /// `BUZZ_OPENSEARCH_AWS_SIGV4_SERVICE` and `BUZZ_OPENSEARCH_AWS_REGION`). /// When set, admitted messages are queued in the search outbox and the /// indexer keeps the index up to date; searches still use Postgres. pub opensearch: Option, @@ -1042,6 +1043,17 @@ impl Config { parse_bool("BUZZ_OPENSEARCH_PREVIEW", false)?, ) .map_err(ConfigError::InvalidValue)?; + let aws_region = match optional_utf8_env("AWS_REGION")? { + Some(region) if !region.trim().is_empty() => Some(region), + _ => optional_utf8_env("AWS_DEFAULT_REGION")?, + }; + let opensearch = with_opensearch_aws_sigv4( + opensearch, + optional_utf8_env("BUZZ_OPENSEARCH_AWS_SIGV4_SERVICE")?, + optional_utf8_env("BUZZ_OPENSEARCH_AWS_REGION")?, + aws_region, + ) + .map_err(ConfigError::InvalidValue)?; let search_indexer_workers = parse_search_indexer_workers(optional_utf8_env("BUZZ_SEARCH_INDEXER_WORKERS")?) .map_err(ConfigError::InvalidValue)?; @@ -1734,10 +1746,55 @@ fn parse_opensearch_config( Ok(Some(buzz_search::opensearch::OpenSearchConfig { url: parsed.to_string(), basic_auth, + aws_sigv4: None, index_prefix: buzz_search::opensearch::DEFAULT_INDEX_PREFIX.to_string(), })) } +/// Add AWS SigV4 request signing to the OpenSearch settings. +/// `BUZZ_OPENSEARCH_AWS_SIGV4_SERVICE` turns it on and names the signing +/// service: `es` for a managed domain, `aoss` for a Serverless collection. +/// The region is `BUZZ_OPENSEARCH_AWS_REGION`, or else the AWS environment's +/// own (`aws_region`). Empty values count as unset. +/// +/// Signing replaces basic auth, so the two together are refused, as is +/// signing without a region. +fn with_opensearch_aws_sigv4( + opensearch: Option, + service: Option, + region: Option, + aws_region: Option, +) -> Result, String> { + let set = |value: Option| { + value + .map(|value| value.trim().to_string()) + .filter(|value| !value.is_empty()) + }; + let (service, region) = (set(service), set(region)); + let Some(service) = service else { + if region.is_some() { + return Err( + "BUZZ_OPENSEARCH_AWS_REGION needs BUZZ_OPENSEARCH_AWS_SIGV4_SERVICE".into(), + ); + } + return Ok(opensearch); + }; + let Some(mut opensearch) = opensearch else { + return Err("BUZZ_OPENSEARCH_AWS_SIGV4_SERVICE needs BUZZ_OPENSEARCH_URL".into()); + }; + if !matches!(service.as_str(), "es" | "aoss") { + return Err("BUZZ_OPENSEARCH_AWS_SIGV4_SERVICE must be es (a managed domain) or aoss (a Serverless collection)".into()); + } + if opensearch.basic_auth.is_some() { + return Err("set BUZZ_OPENSEARCH_AWS_SIGV4_SERVICE or BUZZ_OPENSEARCH_USERNAME and BUZZ_OPENSEARCH_PASSWORD, not both".into()); + } + let Some(region) = region.or(set(aws_region)) else { + return Err("BUZZ_OPENSEARCH_AWS_SIGV4_SERVICE needs a region: set BUZZ_OPENSEARCH_AWS_REGION or AWS_REGION".into()); + }; + opensearch.aws_sigv4 = Some(buzz_search::opensearch::AwsSigV4 { service, region }); + Ok(Some(opensearch)) +} + #[cfg(test)] mod tests { use super::*; @@ -1811,6 +1868,73 @@ mod tests { } } + #[test] + fn opensearch_aws_sigv4_is_off_by_default_and_validated() { + let some = |value: &str| Some(value.to_string()); + let cluster = |username: Option, password: Option| { + parse_opensearch_config(some("https://search.example.org"), username, password, true) + .unwrap() + }; + let signing = |config: Option| { + config.and_then(|config| config.aws_sigv4) + }; + + let unsigned = + with_opensearch_aws_sigv4(cluster(None, None), None, some(" "), some("us-east-1")); + assert_eq!(signing(unsigned.unwrap()), None); + let basic = with_opensearch_aws_sigv4( + cluster(some("relay"), some("secret")), + None, + None, + some("us-east-1"), + ); + assert!(basic.unwrap().unwrap().basic_auth.is_some()); + + for (service, region, aws_region, expected) in [ + ("aoss", some("eu-west-1"), some("us-east-1"), "eu-west-1"), + ("es", None, some("us-east-1"), "us-east-1"), + ] { + let signed = + with_opensearch_aws_sigv4(cluster(None, None), some(service), region, aws_region); + let signed = signing(signed.unwrap()).unwrap(); + assert_eq!( + (signed.service.as_str(), signed.region.as_str()), + (service, expected) + ); + } + + for (opensearch, service, region, aws_region, why) in [ + (cluster(None, None), some("aoss"), None, None, "no region"), + ( + cluster(None, None), + some("s3"), + some("us-east-1"), + None, + "unknown service", + ), + ( + cluster(some("relay"), some("secret")), + some("aoss"), + some("us-east-1"), + None, + "with basic auth", + ), + (None, some("aoss"), some("us-east-1"), None, "no URL"), + ( + cluster(None, None), + None, + some("us-east-1"), + None, + "region without service", + ), + ] { + assert!( + with_opensearch_aws_sigv4(opensearch, service, region, aws_region).is_err(), + "{why}" + ); + } + } + #[test] fn klipy_config_debug_redacts_the_api_key() { let config = KlipyConfig { diff --git a/crates/buzz-search/Cargo.toml b/crates/buzz-search/Cargo.toml index 61c1012fff..8b38f5b9e2 100644 --- a/crates/buzz-search/Cargo.toml +++ b/crates/buzz-search/Cargo.toml @@ -18,12 +18,15 @@ tracing = { workspace = true } metrics = { workspace = true } tokio = { workspace = true } opensearch = { workspace = true } +aws-config = { workspace = true } +aws-credential-types = { workspace = true } serde_json = { workspace = true } hex = { workspace = true } chrono = { workspace = true } rand = { workspace = true } [dev-dependencies] +tokio = { workspace = true, features = ["test-util"] } nostr = { workspace = true } axum = { workspace = true } reqwest = { workspace = true } diff --git a/crates/buzz-search/src/aws_credentials.rs b/crates/buzz-search/src/aws_credentials.rs new file mode 100644 index 0000000000..af9e9a9dc3 --- /dev/null +++ b/crates/buzz-search/src/aws_credentials.rs @@ -0,0 +1,340 @@ +//! AWS credentials for signing OpenSearch requests. +//! +//! The OpenSearch client asks its credentials provider on every request, and +//! the AWS default chain does not cache: used directly, each search and bulk +//! write would call the token service or the instance metadata endpoint. +//! [`CachedCredentials`] keeps one set and reloads it shortly before it +//! expires, so a long-running relay follows role rotation. + +use std::future::Future; +use std::time::{Duration, SystemTime}; + +use aws_config::default_provider::credentials::DefaultCredentialsChain; +use aws_config::Region; +use aws_credential_types::provider::error::CredentialsError; +use aws_credential_types::provider::{self, future, ProvideCredentials}; +use aws_credential_types::Credentials; +use tokio::sync::Mutex; +use tokio::time::Instant; + +/// Reload this long before the credentials expire. +const REFRESH_BEFORE_EXPIRY: Duration = Duration::from_secs(5 * 60); + +/// Reload credentials that carry no expiry this often, so a rotated key in +/// the environment's files is picked up. +const WITHOUT_EXPIRY_TTL: Duration = Duration::from_secs(15 * 60); + +/// The shortest time from the end of one load to the start of the next, +/// after a success or a failure. A source that is down, or that hands out +/// credentials already near their expiry, is asked this often and not once +/// per request. +const MIN_LOAD_INTERVAL: Duration = Duration::from_secs(30); + +/// Bound on a load when there are no valid credentials to fall back on, so +/// a stalled credential source cannot hold requests. +const LOAD_TIMEOUT: Duration = Duration::from_secs(30); + +/// Bound on a reload while the current credentials are still valid: the +/// request goes on with those instead of waiting. +const REFRESH_TIMEOUT: Duration = Duration::from_secs(5); + +/// The AWS default credential chain: environment, shared profile, web +/// identity token, container role, then instance role. +pub(crate) fn default_chain(region: Region) -> impl ProvideCredentials { + Rebuilt { + build: move || { + DefaultCredentialsChain::builder() + .region(region.clone()) + .build() + }, + } +} + +/// A provider built anew for every load. The AWS providers read the shared +/// profile files once and keep what they read, so one kept across loads +/// would go on signing with a key that has since been rotated out. +struct Rebuilt { + build: B, +} + +impl std::fmt::Debug for Rebuilt { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Rebuilt").finish_non_exhaustive() + } +} + +impl ProvideCredentials for Rebuilt +where + B: Fn() -> F + Send + Sync, + F: Future + Send, + P: ProvideCredentials, +{ + fn provide_credentials<'a>(&'a self) -> future::ProvideCredentials<'a> + where + Self: 'a, + { + future::ProvideCredentials::new(async { + let provider = (self.build)().await; + provider.provide_credentials().await + }) + } +} + +/// Credentials from `source`, loaded once and reused until shortly before +/// they expire. Concurrent requests share one load, whether it succeeds or +/// fails. +pub(crate) struct CachedCredentials

{ + source: P, + state: Mutex, +} + +struct State { + /// The last credentials loaded. + credentials: Option, + /// No load before this time. `None` until the first load. + next_load: Option, +} + +impl

CachedCredentials

{ + pub(crate) fn new(source: P) -> Self { + Self { + source, + state: Mutex::new(State { + credentials: None, + next_load: None, + }), + } + } +} + +impl

std::fmt::Debug for CachedCredentials

{ + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CachedCredentials").finish_non_exhaustive() + } +} + +impl CachedCredentials

{ + async fn credentials(&self) -> provider::Result { + let mut state = self.state.lock().await; + let now = SystemTime::now(); + let valid = state + .credentials + .clone() + .filter(|credentials| credentials.expiry().is_none_or(|expiry| now < expiry)); + if state.next_load.is_some_and(|next| Instant::now() < next) { + return valid.ok_or_else(|| { + CredentialsError::not_loaded("loading AWS credentials failed moments ago") + }); + } + let timeout = if valid.is_some() { + REFRESH_TIMEOUT + } else { + LOAD_TIMEOUT + }; + let loaded = tokio::time::timeout(timeout, self.source.provide_credentials()).await; + // The wait for the next load starts when this one ends: requests + // that queued behind a slow load must not each start another. + let until = + |expiry: SystemTime| expiry.duration_since(SystemTime::now()).unwrap_or_default(); + // A credential helper can hand out a set whose expiry has passed. It + // signs nothing, so it counts as a failed load and is not asked for + // again on every request. + let arrived_expired = matches!( + &loaded, + Ok(Ok(credentials)) if credentials.expiry().is_some_and(|expiry| until(expiry).is_zero()) + ); + let error = match loaded { + Ok(Ok(_)) if arrived_expired => { + CredentialsError::provider_error("the credentials loaded had already expired") + } + Ok(Ok(credentials)) => { + let wait = match credentials.expiry().map(until) { + Some(left) => left + .saturating_sub(REFRESH_BEFORE_EXPIRY) + .max(MIN_LOAD_INTERVAL) + .min(left), + None => WITHOUT_EXPIRY_TTL, + }; + state.next_load = Some(Instant::now() + wait); + state.credentials = Some(credentials.clone()); + return Ok(credentials); + } + Ok(Err(error)) => error, + Err(_) => CredentialsError::provider_timed_out(timeout), + }; + // Only the kind of error is logged. Its causes can carry the output + // of a credential helper, which may hold secrets. + tracing::warn!( + %error, + arrived_expired, + "loading AWS credentials for OpenSearch failed" + ); + // A failed reload is no reason to stop while the old set still works. + // Without one, requests fail at once until the next load is due. + let wait = match valid.as_ref().and_then(Credentials::expiry).map(until) { + Some(left) => MIN_LOAD_INTERVAL.min(left), + None => MIN_LOAD_INTERVAL, + }; + state.next_load = Some(Instant::now() + wait); + valid.ok_or(error) + } +} + +impl ProvideCredentials for CachedCredentials

{ + fn provide_credentials<'a>(&'a self) -> future::ProvideCredentials<'a> + where + Self: 'a, + { + future::ProvideCredentials::new(self.credentials()) + } +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::{AtomicUsize, Ordering}; + + // The names that replace these live in a crate this one does not + // depend on directly. + #[allow(deprecated)] + use aws_config::profile::profile_file::{ProfileFileKind, ProfileFiles}; + use aws_config::profile::ProfileFileCredentialsProvider; + + use super::*; + + /// Succeeds `successes` times with credentials that expire at `expiry`, + /// then fails, counting the loads. + #[derive(Debug)] + struct Source { + successes: usize, + expiry: SystemTime, + loads: AtomicUsize, + } + + impl ProvideCredentials for Source { + fn provide_credentials<'a>(&'a self) -> future::ProvideCredentials<'a> + where + Self: 'a, + { + let load = self.loads.fetch_add(1, Ordering::SeqCst); + future::ProvideCredentials::ready(if load < self.successes { + Ok(Credentials::new( + format!("access-{load}"), + "secret", + None, + Some(self.expiry), + "test", + )) + } else { + Err(CredentialsError::not_loaded("source is down")) + }) + } + } + + fn cache(successes: usize) -> CachedCredentials { + cache_expiring(successes, SystemTime::now() + Duration::from_secs(3600)) + } + + fn cache_expiring(successes: usize, expiry: SystemTime) -> CachedCredentials { + CachedCredentials::new(Source { + successes, + expiry, + loads: AtomicUsize::new(0), + }) + } + + async fn access_key(cached: &CachedCredentials) -> Option { + let credentials = cached.provide_credentials().await.ok()?; + Some(credentials.access_key_id().to_string()) + } + + /// Make the next request reload, as when the credentials near expiry. + async fn reload_is_due

(cached: &CachedCredentials

) { + cached.state.lock().await.next_load = None; + } + + #[tokio::test] + async fn credentials_are_loaded_once_and_survive_a_failed_reload() { + let cached = cache(2); + assert_eq!(access_key(&cached).await.as_deref(), Some("access-0")); + assert_eq!(access_key(&cached).await.as_deref(), Some("access-0")); + reload_is_due(&cached).await; + assert_eq!(access_key(&cached).await.as_deref(), Some("access-1")); + + // The source goes down: the valid set stays in use, and the source + // is not asked again on the next request. + reload_is_due(&cached).await; + assert_eq!(access_key(&cached).await.as_deref(), Some("access-1")); + assert_eq!(access_key(&cached).await.as_deref(), Some("access-1")); + assert_eq!(cached.source.loads.load(Ordering::SeqCst), 3); + } + + #[tokio::test] + async fn a_failed_first_load_is_not_repeated_per_request() { + let cached = cache(0); + assert_eq!(access_key(&cached).await, None); + assert_eq!(access_key(&cached).await, None); + assert_eq!(cached.source.loads.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn credentials_that_arrive_expired_are_not_reloaded_per_request() { + let cached = cache_expiring(usize::MAX, SystemTime::now() - Duration::from_secs(60)); + assert_eq!(access_key(&cached).await, None); + assert_eq!(access_key(&cached).await, None); + assert_eq!(cached.source.loads.load(Ordering::SeqCst), 1); + } + + /// Never answers, counting the loads. + #[derive(Debug, Default)] + struct Stalled { + loads: AtomicUsize, + } + + impl ProvideCredentials for Stalled { + fn provide_credentials<'a>(&'a self) -> future::ProvideCredentials<'a> + where + Self: 'a, + { + self.loads.fetch_add(1, Ordering::SeqCst); + future::ProvideCredentials::new(std::future::pending()) + } + } + + #[tokio::test(start_paused = true)] + async fn requests_waiting_on_a_stalled_load_share_its_failure() { + let cached = CachedCredentials::new(Stalled::default()); + let (first, second) = tokio::join!(access_key(&cached), access_key(&cached)); + assert_eq!((first, second), (None, None)); + assert_eq!(cached.source.loads.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + #[allow(deprecated)] + async fn a_key_rotated_in_the_shared_profile_is_picked_up() { + let path = + std::env::temp_dir().join(format!("buzz-search-rotation-{}", std::process::id())); + let profile = |key: &str| { + let text = format!("[default]\naws_access_key_id = {key}\naws_secret_access_key = x\n"); + std::fs::write(&path, text).expect("write the profile file"); + }; + let cached = CachedCredentials::new(Rebuilt { + build: || async { + let files = ProfileFiles::builder() + .with_file(ProfileFileKind::Credentials, &path) + .build(); + ProfileFileCredentialsProvider::builder() + .profile_files(files) + .profile_name("default") + .build() + }, + }); + + profile("before"); + assert_eq!(access_key(&cached).await.as_deref(), Some("before")); + profile("after"); + reload_is_due(&cached).await; + let rotated = access_key(&cached).await; + let _ = std::fs::remove_file(&path); + assert_eq!(rotated.as_deref(), Some("after")); + } +} diff --git a/crates/buzz-search/src/lib.rs b/crates/buzz-search/src/lib.rs index 4e7ded874e..c967358116 100644 --- a/crates/buzz-search/src/lib.rs +++ b/crates/buzz-search/src/lib.rs @@ -29,6 +29,7 @@ //! filters on the community first. A query bound to community //! A cannot return events stored under community B, by construction. +mod aws_credentials; #[doc(hidden)] pub mod cancel; /// Search error types. diff --git a/crates/buzz-search/src/opensearch.rs b/crates/buzz-search/src/opensearch.rs index 487242beac..74b61e9621 100644 --- a/crates/buzz-search/src/opensearch.rs +++ b/crates/buzz-search/src/opensearch.rs @@ -13,6 +13,8 @@ use std::ops::Range; use std::time::Duration; +use aws_config::Region; +use aws_credential_types::provider::SharedCredentialsProvider; use buzz_core::CommunityId; use buzz_db::search_outbox::SearchDocument; use opensearch::auth::Credentials; @@ -27,6 +29,7 @@ use opensearch::params::VersionType; use opensearch::{BulkOperation, BulkParts, OpenSearch, SearchParts}; use serde_json::{json, Value}; +use crate::aws_credentials::{default_chain, CachedCredentials}; use crate::query::{normalized_search_text, page_bounds, PageBounds}; use crate::{ ChannelScope, SearchError, SearchHit, SearchMode, SearchQuery, SearchResult, SearchSort, @@ -92,6 +95,9 @@ pub struct OpenSearchConfig { pub url: String, /// HTTP basic credentials, if the cluster needs them. pub basic_auth: Option<(String, String)>, + /// Sign requests with AWS SigV4, if the cluster needs it. Not combined + /// with basic credentials. + pub aws_sigv4: Option, /// Prefix of the alias and index names. The relay always uses /// [`DEFAULT_INDEX_PREFIX`]; tests set their own to share a cluster. pub index_prefix: String, @@ -105,11 +111,24 @@ impl std::fmt::Debug for OpenSearchConfig { "basic_auth", &self.basic_auth.as_ref().map(|(user, _)| user), ) + .field("aws_sigv4", &self.aws_sigv4) .field("index_prefix", &self.index_prefix) .finish() } } +/// AWS SigV4 request signing, for Amazon OpenSearch Service. Credentials come +/// from the AWS default chain (environment, shared profile, web identity +/// token, container role, instance role) and are reloaded before they expire. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AwsSigV4 { + /// Signing service name: `es` for a managed domain, `aoss` for a + /// Serverless collection. + pub service: String, + /// AWS region of the cluster, for example `us-east-1`. + pub region: String, +} + /// The message index on one OpenSearch cluster. #[derive(Clone)] pub struct SearchIndex { @@ -137,6 +156,21 @@ impl SearchIndex { if let Some((user, password)) = &config.basic_auth { transport = transport.auth(Credentials::Basic(user.clone(), password.clone())); } + if let Some(sigv4) = &config.aws_sigv4 { + if config.basic_auth.is_some() { + return Err(SearchError::Engine( + "basic auth and AWS SigV4 cannot be combined".into(), + )); + } + let region = Region::new(sigv4.region.clone()); + let credentials = CachedCredentials::new(default_chain(region.clone())); + transport = transport + .auth(Credentials::AwsSigV4( + SharedCredentialsProvider::new(credentials), + region, + )) + .service_name(&sigv4.service); + } let transport = transport .build() .map_err(|_| SearchError::Engine("OpenSearch client setup failed".into()))?; @@ -728,6 +762,7 @@ mod tests { let index = SearchIndex::new(&OpenSearchConfig { url, basic_auth: None, + aws_sigv4: None, index_prefix: DEFAULT_INDEX_PREFIX.into(), }) .expect("client"); diff --git a/crates/buzz-search/tests/postgres_opensearch_consistency.rs b/crates/buzz-search/tests/postgres_opensearch_consistency.rs index eebab78816..85b1e8db40 100644 --- a/crates/buzz-search/tests/postgres_opensearch_consistency.rs +++ b/crates/buzz-search/tests/postgres_opensearch_consistency.rs @@ -144,6 +144,7 @@ impl Proxy { SearchIndex::new(&OpenSearchConfig { url: self.url.clone(), basic_auth: None, + aws_sigv4: None, index_prefix: prefix.into(), }) .expect("proxied client") @@ -1402,6 +1403,7 @@ async fn run(db: &Db, seed: u64, ops: usize) -> Result> { let direct = SearchIndex::new(&OpenSearchConfig { url: opensearch_url(), basic_auth: None, + aws_sigv4: None, index_prefix: prefix.clone(), }) .expect("client"); diff --git a/crates/buzz-search/tests/postgres_opensearch_search.rs b/crates/buzz-search/tests/postgres_opensearch_search.rs index 3c9e97483f..b421f58d7d 100644 --- a/crates/buzz-search/tests/postgres_opensearch_search.rs +++ b/crates/buzz-search/tests/postgres_opensearch_search.rs @@ -89,6 +89,7 @@ async fn sync_index() -> (SearchIndex, String) { let index = SearchIndex::new(&OpenSearchConfig { url: opensearch_url(), basic_auth: None, + aws_sigv4: None, index_prefix: prefix.clone(), }) .expect("OpenSearch client"); @@ -268,6 +269,7 @@ async fn admission_queues_while_opensearch_is_unreachable() { let unreachable = SearchIndex::new(&OpenSearchConfig { url: "http://127.0.0.1:9".into(), basic_auth: None, + aws_sigv4: None, index_prefix: "unreachable-".into(), }) .expect("client"); @@ -321,6 +323,7 @@ async fn a_failed_bulk_item_keeps_only_its_own_row() { let index = SearchIndex::new(&OpenSearchConfig { url: opensearch_url(), basic_auth: None, + aws_sigv4: None, index_prefix: prefix.clone(), }) .expect("client"); @@ -1069,6 +1072,7 @@ impl Proxy { SearchIndex::new(&OpenSearchConfig { url: self.url.clone(), basic_auth: None, + aws_sigv4: None, index_prefix: prefix.into(), }) .expect("proxied client") diff --git a/crates/buzz-search/tests/search_suite/mod.rs b/crates/buzz-search/tests/search_suite/mod.rs index 0dc8f00fb1..033f22a4ea 100644 --- a/crates/buzz-search/tests/search_suite/mod.rs +++ b/crates/buzz-search/tests/search_suite/mod.rs @@ -121,6 +121,7 @@ pub async fn test_index() -> SearchIndex { url: std::env::var("BUZZ_TEST_OPENSEARCH_URL") .unwrap_or_else(|_| "http://localhost:9200".to_string()), basic_auth: None, + aws_sigv4: None, index_prefix: format!("test-{}-", Uuid::new_v4().simple()), }) .expect("OpenSearch client"); diff --git a/docs/opensearch-search-deployment.md b/docs/opensearch-search-deployment.md index dfc0450e07..269837168b 100644 --- a/docs/opensearch-search-deployment.md +++ b/docs/opensearch-search-deployment.md @@ -8,9 +8,27 @@ messages stored before it was set. Searches still run on Postgres. | --- | --- | | `BUZZ_OPENSEARCH_URL` | HTTP(S) cluster URL without credentials, query or fragment. Unset turns indexing off. | | `BUZZ_OPENSEARCH_USERNAME`, `BUZZ_OPENSEARCH_PASSWORD` | Optional basic auth. Set both or neither. | +| `BUZZ_OPENSEARCH_AWS_SIGV4_SERVICE` | Optional AWS SigV4 request signing, for Amazon OpenSearch Service: `es` for a managed domain, `aoss` for a Serverless collection. Unset turns signing off. Not combined with basic auth. | +| `BUZZ_OPENSEARCH_AWS_REGION` | Region to sign for. Defaults to `AWS_REGION`, then `AWS_DEFAULT_REGION`. Signing needs one of them. | | `BUZZ_SEARCH_INDEXER_WORKERS` | Indexer workers on the relay that holds the lease: 1 to 32, default 1. Each holds one connection from `BUZZ_DB_POOL_SIZE` for the length of a bulk request, so leave the pool room for them. | | `BUZZ_OPENSEARCH_PREVIEW` | Required with the URL for now, because deleting a community leaves its messages in the index. Use it only on relays without real data. | +## AWS request signing + +With signing on, the relay takes credentials from the standard AWS chain: +environment variables, the shared profile, a web identity token, then the +container or instance role. It reloads them before they expire, and static +keys every 15 minutes, so role credentials and a key changed in the shared +profile are picked up without a restart. The identity needs HTTP access to +the domain or, for Serverless, a data access policy on the collection and its +`buzz-*` indexes plus `aoss:APIAccessAll`. + +When a load fails, the relay logs only the kind of error. For the cause, add +`aws_config=warn` to `RUST_LOG`. That output can include what a +`credential_process` helper printed, so make sure the helper prints no +secrets. A helper should also bound its own run time: the relay gives up on a +load that takes too long but does not stop a helper that hangs. + ## Rollout order 1. Deploy a release that lists `search_outbox` and `search_backfill` as