diff --git a/CHANGELOG.md b/CHANGELOG.md index 728b057e77..12b9383503 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/). * AGS1 readers now require `StandardKeyMetadata::file_length` and reject missing or invalid lengths without falling back to a storage stat. AGS1-encrypted manifests, manifest lists, and Puffin files written by earlier development builds without this field must be rewritten using a build that can still read them before upgrading. This matches the Java client's read contract. * `iceberg_catalog_loader::BoxedCatalogBuilder` has a new required method, `with_runtime`. Types implementing `CatalogBuilder` get it through the blanket impl; types implementing `BoxedCatalogBuilder` directly (for example, a wrapper around another `Box`) must implement it, typically by forwarding the runtime to the builder they wrap. * `Transaction::commit` now returns `ErrorKind::PreconditionFailed` for read-only tables (`Table::readonly()`, e.g. from `StaticTable::into_table` or `TableBuilder::readonly(true)`), including empty transactions, which previously returned the table unchanged. Java treats an empty transaction on a static table as a no-op. +* `iceberg_storage_opendal::OpenDalStorage` and its variants are now `#[non_exhaustive]`. The `S3`, `Gcs` and `Azdls` variants have a new `credential_provider` field, and `Azdls` a new `sas_tokens` field. Code outside the crate can no longer build a variant with a struct literal or match the enum exhaustively: build storages with `OpenDalStorageFactory` instead, and add `..` to variant patterns and a wildcard arm to `match` expressions. +* `iceberg-storage-opendal` now uses OpenDAL 0.59. Code that names OpenDAL types through it, such as the `config` of an `OpenDalStorage` variant, must use that version. +* `abfs://` and `wasb://` locations without a configured endpoint now connect over `https` instead of `http`, as in Java. Configure an explicit `http://` endpoint, such as a local emulator's, to keep plaintext connections. +* `gcs.no-auth` now enables anonymous access only for a true value (`true`, `t`, `1` or `on`). Previously any value, including `false`, enabled it. ## [v0.10.1] - 2026-07-28 diff --git a/Cargo.lock b/Cargo.lock index 2b057687b7..6dc6f6c7f4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -114,56 +114,12 @@ dependencies = [ "libc", ] -[[package]] -name = "anstream" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" -dependencies = [ - "anstyle", - "anstyle-parse", - "anstyle-query", - "anstyle-wincon", - "colorchoice", - "is_terminal_polyfill", - "utf8parse", -] - [[package]] name = "anstyle" version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" -[[package]] -name = "anstyle-parse" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" -dependencies = [ - "utf8parse", -] - -[[package]] -name = "anstyle-query" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "anstyle-wincon" -version = "3.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" -dependencies = [ - "anstyle", - "once_cell_polyfill", - "windows-sys 0.61.2", -] - [[package]] name = "anyhow" version = "1.0.103" @@ -530,6 +486,15 @@ dependencies = [ "syn", ] +[[package]] +name = "asyncband" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d2050892d4691cf110586070786712b504985a4d37ed64a9cd8a402718e1706" +dependencies = [ + "hashbrown 0.17.1", +] + [[package]] name = "atoi" version = "2.0.0" @@ -1388,46 +1353,6 @@ dependencies = [ "inout 0.2.2", ] -[[package]] -name = "clap" -version = "4.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" -dependencies = [ - "clap_builder", - "clap_derive", -] - -[[package]] -name = "clap_builder" -version = "4.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" -dependencies = [ - "anstream", - "anstyle", - "clap_lex", - "strsim", -] - -[[package]] -name = "clap_derive" -version = "4.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" -dependencies = [ - "heck 0.5.0", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "clap_lex" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" - [[package]] name = "cmake" version = "0.1.58" @@ -1443,19 +1368,13 @@ version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" -[[package]] -name = "colorchoice" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" - [[package]] name = "colored" version = "3.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34" dependencies = [ - "windows-sys 0.48.0", + "windows-sys 0.61.2", ] [[package]] @@ -1694,16 +1613,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "ctor" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "424e0138278faeb2b401f174ad17e715c829512d74f3d1e81eb43365c2e0590e" -dependencies = [ - "ctor-proc-macro", - "dtor", -] - [[package]] name = "ctor" version = "1.0.8" @@ -1714,12 +1623,6 @@ dependencies = [ "linktime-proc-macro", ] -[[package]] -name = "ctor-proc-macro" -version = "0.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52560adf09603e58c9a7ee1fe1dcb95a16927b17c127f0ac02d6e768a0e25bc1" - [[package]] name = "ctr" version = "0.9.2" @@ -1972,6 +1875,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "dispatch2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" +dependencies = [ + "bitflags 2.13.0", + "objc2", +] + [[package]] name = "displaydoc" version = "0.2.6" @@ -2022,21 +1935,6 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1435fa1053d8b2fbbe9be7e97eca7f33d37b28409959813daefc1446a14247f1" -[[package]] -name = "dtor" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "404d02eeb088a82cfd873006cb713fe411306c7d182c344905e101fb1167d301" -dependencies = [ - "dtor-proc-macro", -] - -[[package]] -name = "dtor-proc-macro" -version = "0.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f678cf4a922c215c63e0de95eb1ff08a958a81d47e485cf9da1e27bf6305cfa5" - [[package]] name = "dunce" version = "1.0.5" @@ -2606,18 +2504,21 @@ checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" [[package]] name = "hf-xet" -version = "1.5.2" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "430b33fa84f92796d4d263070b6c0d3ca219df7b9a0e1853ee431029b1612bcd" +checksum = "f24754aef4f6c3d57bc4a0dc2648ca74487050eda01c361b3eefa11feeafd662" dependencies = [ + "anyhow", "async-trait", "bytes", "http 1.5.0", "more-asserts", "serde", + "serde_json", "thiserror 2.0.18", "tokio", "tokio-util", + "tokio_with_wasm", "tracing", "uuid", "xet-client", @@ -2993,6 +2894,7 @@ dependencies = [ "itertools 0.13.0", "mockito", "moka", + "rand 0.9.5", "reqwest 0.12.28", "serde", "serde_derive", @@ -3001,6 +2903,7 @@ dependencies = [ "tokio", "tracing", "typed-builder", + "typetag", "uuid", ] @@ -3093,9 +2996,12 @@ dependencies = [ "iceberg", "iceberg-property-macro", "iceberg_test_utils", + "mockito", "opendal", "reqsign-aws-v4", + "reqsign-azure-storage", "reqsign-core", + "reqsign-google", "reqwest 0.12.28", "serde", "serde_json", @@ -3292,12 +3198,6 @@ version = "2.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" -[[package]] -name = "is_terminal_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" - [[package]] name = "itertools" version = "0.13.0" @@ -3688,15 +3588,6 @@ dependencies = [ "digest 0.11.3", ] -[[package]] -name = "mea" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2640d335e7273dacdcf51044026139b2e269c3bb0dfc3f8cb3496b85e3f6a42c" -dependencies = [ - "slab", -] - [[package]] name = "memchr" version = "2.8.2" @@ -4037,6 +3928,15 @@ dependencies = [ "syn", ] +[[package]] +name = "objc2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" +dependencies = [ + "objc2-encode", +] + [[package]] name = "objc2-core-foundation" version = "0.3.2" @@ -4044,6 +3944,24 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" dependencies = [ "bitflags 2.13.0", + "dispatch2", + "objc2", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +dependencies = [ + "bitflags 2.13.0", + "objc2", ] [[package]] @@ -4056,6 +3974,17 @@ dependencies = [ "objc2-core-foundation", ] +[[package]] +name = "objc2-open-directory" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb82bed227edf5201dfedf072bba4015a33d3d4a98519837295a90f0a23f676d" +dependencies = [ + "objc2", + "objc2-core-foundation", + "objc2-foundation", +] + [[package]] name = "objc2-system-configuration" version = "0.3.2" @@ -4071,12 +4000,6 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" -[[package]] -name = "once_cell_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" - [[package]] name = "oneshot" version = "0.1.13" @@ -4091,11 +4014,11 @@ checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" [[package]] name = "opendal" -version = "0.58.1" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f20562cc7447fcc915fc5c23df305a412ea80a733c9f2fd9e2d267e2815be6d" +checksum = "46081824c74bac9f68f0bc4408077f77b0e315c006514719c97af1c2227ac2d2" dependencies = [ - "ctor 1.0.8", + "ctor", "opendal-core", "opendal-http-transport-reqwest", "opendal-layer-concurrent-limit", @@ -4113,11 +4036,12 @@ dependencies = [ [[package]] name = "opendal-core" -version = "0.58.1" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec75551ff4cf3e57da98979f6a937aaa9ddb3915bf68cc17d03df733be6646ed" +checksum = "33d5a635dfea36a7a0c3bbb2ca34c97af17f98dd69b0cdf31a1d436a346e0a12" dependencies = [ "anyhow", + "asyncband", "base64 0.23.0", "bytes", "futures", @@ -4125,7 +4049,6 @@ dependencies = [ "jiff", "log", "md-5 0.11.0", - "mea", "percent-encoding", "quick-xml", "reqsign-core", @@ -4139,9 +4062,9 @@ dependencies = [ [[package]] name = "opendal-http-transport-reqwest" -version = "0.58.1" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad4d4f19c3ce01126a30611f8e544eaa217104a278c889ac17c9374fe4f9e4ef" +checksum = "fc025e163c43993e30cf1829a30b791934e5b0f7cd4d7e03acc902a9efb7e8f5" dependencies = [ "bytes", "futures", @@ -4153,21 +4076,21 @@ dependencies = [ [[package]] name = "opendal-layer-concurrent-limit" -version = "0.58.1" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "249ac5b0aa5a7a6c3737342d10456067937f9c9a6f3f02544271f7908ab91081" +checksum = "06b44bdf694cccb7d90515b3eac6623975a2813abf4f5c438b4949a329d6a45b" dependencies = [ + "asyncband", "futures", "http 1.5.0", - "mea", "opendal-core", ] [[package]] name = "opendal-layer-logging" -version = "0.58.1" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c75411ab00f77851ff086b686c1e9ca8175ac18c15afa2cb75b9036436cb06c" +checksum = "520d3de5d246c82a246c431ef0f52b8d2f091c7c49a3fd7a6f0ff519b1e7725f" dependencies = [ "log", "opendal-core", @@ -4175,9 +4098,9 @@ dependencies = [ [[package]] name = "opendal-layer-retry" -version = "0.58.1" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80b7738bd5f233ad8da39af9b9316b9b7a4eaddd91e8e32a1e19b7030688121d" +checksum = "2a02c59479b047878f4a0f269f23c847f24d67d1ff19f2b20fdd5a3bceefd451" dependencies = [ "backon", "log", @@ -4186,9 +4109,9 @@ dependencies = [ [[package]] name = "opendal-layer-timeout" -version = "0.58.1" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a704141924500f3803c05ed871b53305d2a2f11cb5ef20160c3ee688a1857f66" +checksum = "afffa0cf8a6690b3b44cc510816ba675638eb236699a7d449e44ac3344bafd36" dependencies = [ "opendal-core", "tokio", @@ -4196,15 +4119,15 @@ dependencies = [ [[package]] name = "opendal-service-azdls" -version = "0.58.1" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e3c406729935fe214ce574d68681a1ff7e0b322548f14094912bdbfe50e5c53" +checksum = "afeb287cf2b03ab8d99d77a8e9687e908eb7898e2da1af6ccd00590c7095cae6" dependencies = [ + "asyncband", "base64 0.23.0", "bytes", "http 1.5.0", "log", - "mea", "opendal-core", "opendal-service-azure-common", "quick-xml", @@ -4217,9 +4140,9 @@ dependencies = [ [[package]] name = "opendal-service-azure-common" -version = "0.58.1" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7348c88edf15af435b7be930077746b569fac5e738c1bf6a363b675e7317c9df" +checksum = "bdf9c9d0bfd1fa3638eec485c7f3448252cbb5a81774a2aa7abadc3e4f1ea43e" dependencies = [ "http 1.5.0", "opendal-core", @@ -4227,9 +4150,9 @@ dependencies = [ [[package]] name = "opendal-service-fs" -version = "0.58.1" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "826c4e17a30643b888fe983897f9a4b23b07066e1d069727a923cc8fb419a702" +checksum = "70768b8f5af6996a494e784a1dc2a76b5cf890c422aff31ad094319bde98feb7" dependencies = [ "bytes", "log", @@ -4241,9 +4164,9 @@ dependencies = [ [[package]] name = "opendal-service-gcs" -version = "0.58.1" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "007f3fba63c21e516c956b891e96ff9892d8175662bfb781cdada9d3766a11e6" +checksum = "f9e5197fce0cd5929db9129a7e71e503841aa20bea4f1dcc54ab097a5f3652e9" dependencies = [ "async-trait", "bytes", @@ -4258,13 +4181,14 @@ dependencies = [ "serde", "serde_json", "tokio", + "uuid", ] [[package]] name = "opendal-service-hdfs-native" -version = "0.58.1" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bdeb0c6fd99ffe3acf9c58f9664842ea549e4fd984c8202a5e656d18de46dae4" +checksum = "81a6ea279df6bc6cf0e849481cf3c629b0bec77d04ef927f1ea87b40e7ffac20" dependencies = [ "bytes", "futures", @@ -4276,10 +4200,11 @@ dependencies = [ [[package]] name = "opendal-service-hf" -version = "0.58.1" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b41fd41eb7ed03c5e66cefda61e8e117808ffd2908f2916737cb020a6beb02c7" +checksum = "32c1a4076d933180b66b57a0f305e48f2de1a72b50648114cb9943a8bc9e28b8" dependencies = [ + "asyncband", "bytes", "hf-xet", "http 1.5.0", @@ -4292,9 +4217,9 @@ dependencies = [ [[package]] name = "opendal-service-oss" -version = "0.58.1" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd528ec2d49c5ca69e674ffed7b3e0686fb9cfcfea0596870de381467fda4f1b" +checksum = "30e973fcebfa413432c024c41d65fad8034b22c065250c587e0c3a70f1a27eb6" dependencies = [ "bytes", "http 1.5.0", @@ -4309,9 +4234,9 @@ dependencies = [ [[package]] name = "opendal-service-s3" -version = "0.58.1" +version = "0.59.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58e80cdf192d7eff05feed747894d64f81905ac4eaf132edf7ea270abdd2d663" +checksum = "0932321e27c712a30ef72db56b12f31e41e9f0d2d3841d63a91bc8075cd8f0ef" dependencies = [ "base64 0.23.0", "bytes", @@ -4490,11 +4415,11 @@ dependencies = [ [[package]] name = "pem" -version = "3.0.6" +version = "4.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120" dependencies = [ - "base64 0.22.1", + "base64 0.23.0", "serde_core", ] @@ -4780,7 +4705,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf" dependencies = [ "anyhow", - "itertools 0.13.0", + "itertools 0.14.0", "proc-macro2", "quote", "syn", @@ -4889,9 +4814,9 @@ checksum = "5a651516ddc9168ebd67b24afd085a718be02f8858fe406591b013d101ce2f40" [[package]] name = "quick-xml" -version = "0.41.0" +version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" dependencies = [ "memchr", "serde", @@ -5195,9 +5120,9 @@ dependencies = [ [[package]] name = "reqsign-aws-core" -version = "3.1.0" +version = "3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d63b56638bb3cc7bd376a7cdce1ba3089777a08f47e4097888f2d784cc3f46c" +checksum = "d38c902d8ec745bd9eadd1abbcbe227f4c1fc2926b2ec8929f89234af3114500" dependencies = [ "bytes", "form_urlencoded", @@ -5216,9 +5141,9 @@ dependencies = [ [[package]] name = "reqsign-aws-v4" -version = "3.2.0" +version = "3.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a0c499f4ed12d04c3d4c78fe4cb01aee22c9dae22848c14db2c6313d9df9f43" +checksum = "906bfd028f96bfe73fdb892ce26f3b3f99b4f30feb9bd024be58bd6657f68b2b" dependencies = [ "bytes", "http 1.5.0", @@ -5231,11 +5156,12 @@ dependencies = [ [[package]] name = "reqsign-azure-storage" -version = "3.1.2" +version = "3.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2824e7da3c2cc42ac3406c674eb57c89127fdcd97f3a73c608cfc680505ea134" +checksum = "7260e6c1d89422ba62d624a32c491b561386fb364ac4bf0959c740e34b251a2e" dependencies = [ "anyhow", + "asyncband", "base64 0.23.0", "bytes", "form_urlencoded", @@ -5252,14 +5178,14 @@ dependencies = [ [[package]] name = "reqsign-core" -version = "3.3.0" +version = "3.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4ac1510872d9481205975d264deb39c109797e5068cc882ed9064270eaae5fa" +checksum = "85fed85c436b6b920e4b36310f699a77771a91e38ae483df48447bd7d162671c" dependencies = [ "anyhow", + "asyncband", "base64 0.23.0", "bytes", - "futures", "hex", "hmac 0.13.0", "http 1.5.0", @@ -5276,9 +5202,9 @@ dependencies = [ [[package]] name = "reqsign-file-read-tokio" -version = "3.0.4" +version = "3.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "663d9d55abd0df0830ef0ae43708297cc1371cf4e8ca91f3ac813c309cca8c98" +checksum = "586a8e198057773f9616901fd723a4bc186812b9765bc0f20368661d6169d906" dependencies = [ "anyhow", "reqsign-core", @@ -5915,7 +5841,6 @@ dependencies = [ "cfg-if 1.0.4", "cpufeatures 0.2.17", "digest 0.10.7", - "sha2-asm", ] [[package]] @@ -5929,15 +5854,6 @@ dependencies = [ "digest 0.11.3", ] -[[package]] -name = "sha2-asm" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b845214d6175804686b2bd482bcffe96651bb2d1200742b712003504a2dac1ab" -dependencies = [ - "cc", -] - [[package]] name = "sharded-slab" version = "0.1.7" @@ -6435,15 +6351,16 @@ dependencies = [ [[package]] name = "sysinfo" -version = "0.38.4" +version = "0.39.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92ab6a2f8bfe508deb3c6406578252e491d299cbbf3bc0529ecc3313aee4a52f" +checksum = "d2071df9448915b71c4fe6d25deaf1c22f12bd234f01540b77312bb8e41361e6" dependencies = [ "libc", "memchr", "ntapi", "objc2-core-foundation", "objc2-io-kit", + "objc2-open-directory", "windows", ] @@ -6493,7 +6410,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.3.4", + "getrandom 0.4.3", "once_cell", "rustix", "windows-sys 0.61.2", @@ -6700,6 +6617,30 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio_with_wasm" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34e40fbbbd95441133fe9483f522db15dbfd26dc636164ebd8f2dd28759a6aa6" +dependencies = [ + "js-sys", + "tokio", + "tokio_with_wasm_proc", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "tokio_with_wasm_proc" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d01145a2c788d6aae4cd653afec1e8332534d7d783d01897cefcafe4428de992" +dependencies = [ + "quote", + "syn", +] + [[package]] name = "toml" version = "1.1.3+spec-1.1.0" @@ -7040,12 +6981,6 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" -[[package]] -name = "utf8parse" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" - [[package]] name = "uuid" version = "1.26.0" @@ -7369,7 +7304,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.48.0", + "windows-sys 0.61.2", ] [[package]] @@ -7754,20 +7689,19 @@ dependencies = [ [[package]] name = "xet-client" -version = "1.5.2" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e1e496dcbe6a09017acdfaf48e1a646735e7ff5b2a49e2c7e081cca77a59bc8" +checksum = "15500e5fc9e17be15224f9e34cb07d41fb2805d9dbbf7bd3507c982fd1eb3efd" dependencies = [ "anyhow", "async-trait", "base64 0.22.1", "bytes", - "clap", + "chrono", "crc32fast", "futures", "http 1.5.0", "hyper", - "lazy_static", "more-asserts", "rand 0.10.2", "redb", @@ -7781,10 +7715,11 @@ dependencies = [ "thiserror 2.0.18", "tokio", "tokio-retry", + "tokio_with_wasm", "tracing", - "tracing-subscriber", "url", "urlencoding", + "uuid", "web-time", "xet-core-structures", "xet-runtime", @@ -7792,24 +7727,21 @@ dependencies = [ [[package]] name = "xet-core-structures" -version = "1.5.2" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb838aa8eb67d730af301584cf003caad407487606058292a6750711b603fbee" +checksum = "5080d5803c8bf15fa56ef934050a46b225801bad3ea4cb8bb3c46c5c37976516" dependencies = [ "async-trait", "base64 0.22.1", "blake3", "bytemuck", "bytes", - "clap", "countio", - "csv", "futures", "futures-util", "getrandom 0.4.3", "heapify", "itertools 0.14.0", - "lazy_static", "lz4_flex 0.13.1", "more-asserts", "rand 0.10.2", @@ -7817,7 +7749,6 @@ dependencies = [ "safe-transmute", "serde", "static_assertions", - "tempfile", "thiserror 2.0.18", "tokio", "tokio-util", @@ -7829,32 +7760,31 @@ dependencies = [ [[package]] name = "xet-data" -version = "1.5.2" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67fd409bef621411a9d9013798540bb8036cb2678f03ab39af89a5e88034ed8c" +checksum = "1287a1657fb67de846030f6605a9960dcdad401c467b490657e6e909d2e0d1c0" dependencies = [ "anyhow", "async-trait", "bytes", "chrono", - "clap", "gearhash", "http 1.5.0", "itertools 0.14.0", - "lazy_static", "more-asserts", "rand 0.10.2", "serde", "serde_json", - "sha2 0.10.9", + "sha2 0.11.0", "tempfile", "thiserror 2.0.18", "tokio", "tokio-util", + "tokio_with_wasm", "tracing", "url", "uuid", - "walkdir", + "web-time", "xet-client", "xet-core-structures", "xet-runtime", @@ -7862,9 +7792,9 @@ dependencies = [ [[package]] name = "xet-runtime" -version = "1.5.2" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15d8f121c33866f7648b737abe70d0e2dd9c0af4ffdd7219207531d0283aa63d" +checksum = "921953c885ce83e02b21e8d26444b75c78c9e83076699ced08d5c6fc1cdb48ac" dependencies = [ "anyhow", "async-trait", @@ -7872,13 +7802,12 @@ dependencies = [ "chrono", "colored", "const-str", - "ctor 0.6.3", + "ctor", "dirs", "futures", "git-version", "humantime", "konst", - "lazy_static", "libc", "more-asserts", "oneshot", @@ -7892,9 +7821,11 @@ dependencies = [ "thiserror 2.0.18", "tokio", "tokio-util", + "tokio_with_wasm", "tracing", "tracing-appender", "tracing-subscriber", + "web-time", "whoami 2.1.2", "winapi", ] diff --git a/Cargo.toml b/Cargo.toml index d4804d8821..bd72c65469 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -111,7 +111,7 @@ moka = "0.12.10" motore-macros = "0.4.3" murmur3 = "0.5.2" once_cell = "1.20" -opendal = "0.58" +opendal = "0.59" ordered-float = "4" parquet = "59.2" pilota = "0.11.10" diff --git a/crates/catalog/rest/Cargo.toml b/crates/catalog/rest/Cargo.toml index a43970bf7f..f5ad734197 100644 --- a/crates/catalog/rest/Cargo.toml +++ b/crates/catalog/rest/Cargo.toml @@ -44,14 +44,16 @@ http = { workspace = true } iceberg = { workspace = true } itertools = { workspace = true } moka = { workspace = true, features = ["sync"] } +rand = { workspace = true } reqwest = { workspace = true } serde = { workspace = true } serde_derive = { workspace = true } serde_json = { workspace = true } sha2 = { workspace = true, optional = true } -tokio = { workspace = true } +tokio = { workspace = true, features = ["time"] } tracing = { workspace = true } typed-builder = { workspace = true } +typetag = { workspace = true } uuid = { workspace = true, features = ["v4"] } [dev-dependencies] @@ -61,7 +63,7 @@ iceberg_test_utils = { path = "../../test_utils", features = ["tests"] } mockito = { workspace = true } # `stream` lets tests build a streaming body to exercise HttpRequestBody::Streaming. reqwest = { workspace = true, features = ["stream"] } -tokio = { workspace = true } +tokio = { workspace = true, features = ["macros", "net", "test-util", "time"] } [lints] workspace = true diff --git a/crates/catalog/rest/public-api.txt b/crates/catalog/rest/public-api.txt index ff080def7a..4284de2f63 100644 --- a/crates/catalog/rest/public-api.txt +++ b/crates/catalog/rest/public-api.txt @@ -235,6 +235,7 @@ impl iceberg_catalog_rest::AuthManager for iceberg_catalog_rest::NoopAuthManager pub fn iceberg_catalog_rest::NoopAuthManager::catalog_session<'life0, 'life1, 'life2, 'async_trait>(&'life0 self, _client: &'life1 iceberg_catalog_rest::HttpClient, _props: &'life2 std::collections::hash::map::HashMap) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait pub fn iceberg_catalog_rest::NoopAuthManager::contextual_session<'life0, 'life1, 'async_trait>(&'life0 self, context: &'life1 iceberg::catalog::session::SessionContext, catalog_session: alloc::sync::Arc) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait pub fn iceberg_catalog_rest::NoopAuthManager::init_session<'life0, 'life1, 'life2, 'async_trait>(&'life0 self, _client: &'life1 iceberg_catalog_rest::HttpClient, _props: &'life2 std::collections::hash::map::HashMap) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait +pub fn iceberg_catalog_rest::NoopAuthManager::table_session<'life0, 'life1, 'life2, 'life3, 'async_trait>(&'life0 self, _client: &'life1 iceberg_catalog_rest::HttpClient, _table: &'life2 iceberg::catalog::TableIdent, _props: &'life3 std::collections::hash::map::HashMap, parent: alloc::sync::Arc) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait, 'life3: 'async_trait pub struct iceberg_catalog_rest::OAuth2Manager impl iceberg_catalog_rest::OAuth2Manager pub fn iceberg_catalog_rest::OAuth2Manager::new(token_endpoint: impl core::convert::Into) -> Self @@ -248,6 +249,7 @@ impl iceberg_catalog_rest::AuthManager for iceberg_catalog_rest::OAuth2Manager pub fn iceberg_catalog_rest::OAuth2Manager::catalog_session<'life0, 'life1, 'life2, 'async_trait>(&'life0 self, client: &'life1 iceberg_catalog_rest::HttpClient, props: &'life2 std::collections::hash::map::HashMap) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait pub fn iceberg_catalog_rest::OAuth2Manager::contextual_session<'life0, 'life1, 'async_trait>(&'life0 self, context: &'life1 iceberg::catalog::session::SessionContext, catalog_session: alloc::sync::Arc) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait pub fn iceberg_catalog_rest::OAuth2Manager::init_session<'life0, 'life1, 'life2, 'async_trait>(&'life0 self, client: &'life1 iceberg_catalog_rest::HttpClient, props: &'life2 std::collections::hash::map::HashMap) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait +pub fn iceberg_catalog_rest::OAuth2Manager::table_session<'life0, 'life1, 'life2, 'life3, 'async_trait>(&'life0 self, _client: &'life1 iceberg_catalog_rest::HttpClient, _table: &'life2 iceberg::catalog::TableIdent, props: &'life3 std::collections::hash::map::HashMap, parent: alloc::sync::Arc) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait, 'life3: 'async_trait pub struct iceberg_catalog_rest::RegisterTableRequest pub iceberg_catalog_rest::RegisterTableRequest::metadata_location: alloc::string::String pub iceberg_catalog_rest::RegisterTableRequest::name: alloc::string::String @@ -411,13 +413,16 @@ pub trait iceberg_catalog_rest::AuthManager: core::fmt::Debug + core::marker::Se pub fn iceberg_catalog_rest::AuthManager::catalog_session<'life0, 'life1, 'life2, 'async_trait>(&'life0 self, client: &'life1 iceberg_catalog_rest::HttpClient, props: &'life2 std::collections::hash::map::HashMap) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait pub fn iceberg_catalog_rest::AuthManager::contextual_session<'life0, 'life1, 'async_trait>(&'life0 self, context: &'life1 iceberg::catalog::session::SessionContext, catalog_session: alloc::sync::Arc) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait pub fn iceberg_catalog_rest::AuthManager::init_session<'life0, 'life1, 'life2, 'async_trait>(&'life0 self, client: &'life1 iceberg_catalog_rest::HttpClient, props: &'life2 std::collections::hash::map::HashMap) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait +pub fn iceberg_catalog_rest::AuthManager::table_session<'life0, 'life1, 'life2, 'life3, 'async_trait>(&'life0 self, _client: &'life1 iceberg_catalog_rest::HttpClient, _table: &'life2 iceberg::catalog::TableIdent, _props: &'life3 std::collections::hash::map::HashMap, parent: alloc::sync::Arc) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait, 'life3: 'async_trait impl iceberg_catalog_rest::AuthManager for iceberg_catalog_rest::NoopAuthManager pub fn iceberg_catalog_rest::NoopAuthManager::catalog_session<'life0, 'life1, 'life2, 'async_trait>(&'life0 self, _client: &'life1 iceberg_catalog_rest::HttpClient, _props: &'life2 std::collections::hash::map::HashMap) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait pub fn iceberg_catalog_rest::NoopAuthManager::contextual_session<'life0, 'life1, 'async_trait>(&'life0 self, context: &'life1 iceberg::catalog::session::SessionContext, catalog_session: alloc::sync::Arc) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait pub fn iceberg_catalog_rest::NoopAuthManager::init_session<'life0, 'life1, 'life2, 'async_trait>(&'life0 self, _client: &'life1 iceberg_catalog_rest::HttpClient, _props: &'life2 std::collections::hash::map::HashMap) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait +pub fn iceberg_catalog_rest::NoopAuthManager::table_session<'life0, 'life1, 'life2, 'life3, 'async_trait>(&'life0 self, _client: &'life1 iceberg_catalog_rest::HttpClient, _table: &'life2 iceberg::catalog::TableIdent, _props: &'life3 std::collections::hash::map::HashMap, parent: alloc::sync::Arc) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait, 'life3: 'async_trait impl iceberg_catalog_rest::AuthManager for iceberg_catalog_rest::OAuth2Manager pub fn iceberg_catalog_rest::OAuth2Manager::catalog_session<'life0, 'life1, 'life2, 'async_trait>(&'life0 self, client: &'life1 iceberg_catalog_rest::HttpClient, props: &'life2 std::collections::hash::map::HashMap) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait pub fn iceberg_catalog_rest::OAuth2Manager::contextual_session<'life0, 'life1, 'async_trait>(&'life0 self, context: &'life1 iceberg::catalog::session::SessionContext, catalog_session: alloc::sync::Arc) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait pub fn iceberg_catalog_rest::OAuth2Manager::init_session<'life0, 'life1, 'life2, 'async_trait>(&'life0 self, client: &'life1 iceberg_catalog_rest::HttpClient, props: &'life2 std::collections::hash::map::HashMap) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait +pub fn iceberg_catalog_rest::OAuth2Manager::table_session<'life0, 'life1, 'life2, 'life3, 'async_trait>(&'life0 self, _client: &'life1 iceberg_catalog_rest::HttpClient, _table: &'life2 iceberg::catalog::TableIdent, props: &'life3 std::collections::hash::map::HashMap, parent: alloc::sync::Arc) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait, 'life3: 'async_trait pub trait iceberg_catalog_rest::AuthSession: core::fmt::Debug + core::marker::Send + core::marker::Sync pub fn iceberg_catalog_rest::AuthSession::authenticate<'life0, 'life1, 'async_trait>(&'life0 self, request: &'life1 mut iceberg_catalog_rest::HttpRequest) -> core::pin::Pin> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait diff --git a/crates/catalog/rest/src/auth/mod.rs b/crates/catalog/rest/src/auth/mod.rs index a3aab4df90..797878d04e 100644 --- a/crates/catalog/rest/src/auth/mod.rs +++ b/crates/catalog/rest/src/auth/mod.rs @@ -29,11 +29,13 @@ use std::sync::Arc; use async_trait::async_trait; #[cfg(feature = "sigv4")] pub use aws_credential_types::Credentials; -use iceberg::{Result, SessionContext}; +use iceberg::{Error, ErrorKind, Result, SessionContext, TableIdent}; pub use oauth2::OAuth2Manager; +pub(crate) use oauth2::static_token_session; #[cfg(feature = "sigv4")] pub use sigv4::{PayloadHashMode, SigV4Signer}; +use crate::catalog::{REST_CATALOG_PROP_AUTH_TYPE, RestCatalogConfig}; use crate::client::HttpClient; use crate::request::HttpRequest; @@ -42,6 +44,32 @@ pub const AUTH_TYPE_NONE: &str = "none"; /// `rest.auth.type` value selecting OAuth2 token authentication. pub const AUTH_TYPE_OAUTH2: &str = "oauth2"; +/// Builds the auth manager selected by the `rest.auth.type` configuration, +/// like Java's `AuthManagers.loadAuthManager`. +pub(crate) fn load_auth_manager(config: &RestCatalogConfig) -> Result> { + let auth_type = config.auth_type(); + // Java parity (`AuthManagers`): make the inference visible so users + // configure the type explicitly. + if auth_type == AUTH_TYPE_OAUTH2 && !config.has_explicit_auth_type() { + tracing::warn!( + "Inferring {REST_CATALOG_PROP_AUTH_TYPE}={AUTH_TYPE_OAUTH2} from the configured \ + OAuth properties; set it explicitly to avoid this warning" + ); + } + match auth_type.as_str() { + AUTH_TYPE_NONE => Ok(Arc::new(NoopAuthManager)), + AUTH_TYPE_OAUTH2 => Ok(Arc::new(OAuth2Manager::from_config(config)?)), + other => Err(Error::new( + ErrorKind::DataInvalid, + format!( + "unknown '{REST_CATALOG_PROP_AUTH_TYPE}': {other}; use \ + `RestSessionCatalogBuilder::with_auth_manager` or \ + `RestCatalogBuilder::with_auth_manager` to inject a custom auth manager" + ), + )), + } +} + /// Creates the [`AuthSession`]s used to authenticate REST catalog requests. /// /// A manager is exclusively scoped to one catalog and must not be reused by @@ -53,10 +81,10 @@ pub const AUTH_TYPE_OAUTH2: &str = "oauth2"; /// the context-specific sessions that [`AuthManager::contextual_session`] /// derives from it may rely on the state established by that call. /// -/// [`Self::init_session`] and [`Self::catalog_session`] are handed the -/// catalog's [`HttpClient`], which an implementation may clone and store for -/// its own requests (e.g. a token exchange) so that they share the catalog's -/// connection pool and configuration. +/// [`Self::init_session`], [`Self::catalog_session`] and [`Self::table_session`] +/// are handed the catalog's [`HttpClient`], which an implementation may clone +/// and store for its own requests (e.g. a token exchange) so that they share +/// the catalog's connection pool and configuration. #[async_trait] pub trait AuthManager: Debug + Send + Sync { /// Session used for the initial `/v1/config` handshake, given the @@ -108,6 +136,26 @@ pub trait AuthManager: Debug + Send + Sync { let _ = context; Ok(catalog_session) } + + /// Returns a session for requests associated with `table`. + /// + /// Currently only requests for the table's vended storage credentials use + /// it; other table operations use the contextual session. + /// + /// `props` are the unmerged properties returned by the table endpoint, and + /// `parent` is the contextual session of the operation that loaded the + /// table. The default preserves `parent`; managers should return a child + /// session only when the table properties contain an authentication + /// override. + async fn table_session( + &self, + _client: &HttpClient, + _table: &TableIdent, + _props: &HashMap, + parent: Arc, + ) -> Result> { + Ok(parent) + } } /// Authenticates outgoing REST catalog requests. diff --git a/crates/catalog/rest/src/auth/oauth2.rs b/crates/catalog/rest/src/auth/oauth2.rs index aad91996a8..a7beb95c3e 100644 --- a/crates/catalog/rest/src/auth/oauth2.rs +++ b/crates/catalog/rest/src/auth/oauth2.rs @@ -22,7 +22,7 @@ use std::sync::Arc; use async_trait::async_trait; use http::StatusCode; use iceberg::sensitive::SensitiveString; -use iceberg::{Error, ErrorKind, Result}; +use iceberg::{Error, ErrorKind, Result, TableIdent}; use reqwest::header::HeaderMap; use tokio::sync::Mutex; @@ -46,8 +46,9 @@ struct OAuth2Params { /// Iceberg REST catalogs. /// /// A configured `token` is used directly; otherwise `credential` is exchanged -/// for a token at the token endpoint and cached. The cached token is shared -/// across sessions so it survives the config handshake. +/// for a token at the token endpoint and cached. The cached token is shared by +/// the init and catalog sessions so it survives the config handshake; +/// table-specific tokens use isolated sessions. pub struct OAuth2Manager { token: Arc>>, init_params: OAuth2Params, @@ -144,13 +145,39 @@ impl AuthManager for OAuth2Manager { ) -> Result> { Ok(Arc::new(self.session_from(client, props).await?)) } + + /// Like Java, only a `token` in the table config overrides the parent + /// session; a table-level `credential` is ignored. Unlike Java, the token is + /// used as-is and never refreshed, and token-type exchange keys are ignored, + /// because this manager implements neither token refresh nor token exchange. + async fn table_session( + &self, + _client: &HttpClient, + _table: &TableIdent, + props: &HashMap, + parent: Arc, + ) -> Result> { + Ok(match props.get("token") { + Some(token) => static_token_session(token), + None => parent, + }) + } +} + +/// A session that authenticates with `token` as a bearer token, which is never +/// refreshed. +pub(crate) fn static_token_session(token: &str) -> Arc { + Arc::new(OAuth2Session { + token: Arc::new(Mutex::new(Some(SensitiveString::from(token.to_string())))), + token_source: TokenSource::StaticToken, + }) } impl OAuth2Manager { /// Builds a session from the manager's options with `props` merged onto /// them, so an injected manager keeps whatever a property doesn't - /// override. The manager's token cell is shared with every session it - /// builds, so a token cached during the handshake survives it. + /// override. The manager's token cell is shared by the init and catalog + /// sessions, so a token cached during the handshake survives it. async fn session_from( &self, client: &HttpClient, @@ -287,15 +314,21 @@ impl ClientCredentialsConfig { let body = response.body(); let auth_res: TokenResponse = if status == StatusCode::OK { + // A token response holds the token, and serde's errors quote the + // values they reject, so neither the body nor the error is kept. Ok(serde_json::from_slice(body).map_err(|e| { Error::new( ErrorKind::Unexpected, - "Failed to parse response from rest catalog server!", + format!( + "Failed to parse response from rest catalog server: {:?} error at \ + line {}, column {}", + e.classify(), + e.line(), + e.column() + ), ) .with_context("operation", "auth") .with_context("url", self.token_endpoint.clone()) - .with_context("json", String::from_utf8_lossy(body)) - .with_source(e) })?) } else { let e: ErrorResponse = serde_json::from_slice(body).map_err(|e| { @@ -380,4 +413,84 @@ mod tests { "Bearer tok-static" ); } + + #[tokio::test] + async fn test_table_session_inherits_parent_unless_token_is_overridden() { + let manager = OAuth2Manager::new("http://localhost/unused").with_token("catalog-token"); + let client = test_client(); + let parent = manager + .catalog_session(&client, &HashMap::new()) + .await + .unwrap(); + let table = TableIdent::from_strs(["namespace", "table"]).unwrap(); + + let inherited = manager + .table_session(&client, &table, &HashMap::new(), Arc::clone(&parent)) + .await + .unwrap(); + assert!(Arc::ptr_eq(&parent, &inherited)); + + let overridden = manager + .table_session( + &client, + &table, + &HashMap::from([("token".to_string(), "table-token".to_string())]), + Arc::clone(&parent), + ) + .await + .unwrap(); + assert!(!Arc::ptr_eq(&parent, &overridden)); + + let mut parent_request = HttpRequest::new( + Client::new() + .get("https://rest.example.com/catalog") + .build() + .unwrap(), + ); + parent.authenticate(&mut parent_request).await.unwrap(); + assert_eq!( + parent_request.headers().get("authorization").unwrap(), + "Bearer catalog-token" + ); + + let mut table_request = HttpRequest::new( + Client::new() + .get("https://rest.example.com/table") + .build() + .unwrap(), + ); + overridden.authenticate(&mut table_request).await.unwrap(); + assert_eq!( + table_request.headers().get("authorization").unwrap(), + "Bearer table-token" + ); + } + + #[tokio::test] + async fn test_unparsable_token_response_is_not_quoted() { + let mut server = mockito::Server::new_async().await; + let mock = server + .mock("POST", "/v1/oauth/tokens") + .with_status(200) + .with_body(r#"{"access_token":"SECRET-TOKEN","token_type":7}"#) + .create_async() + .await; + let manager = OAuth2Manager::new(format!("{}/v1/oauth/tokens", server.url())) + .with_credential(Some("client".to_string()), "secret".to_string()); + let session = manager + .catalog_session(&test_client(), &HashMap::new()) + .await + .unwrap(); + + let mut request = HttpRequest::new( + Client::new() + .get("https://rest.example.com/catalog") + .build() + .unwrap(), + ); + let error = session.authenticate(&mut request).await.unwrap_err(); + let error = format!("{error:?}"); + assert!(!error.contains("SECRET-TOKEN"), "{error}"); + mock.assert_async().await; + } } diff --git a/crates/catalog/rest/src/catalog.rs b/crates/catalog/rest/src/catalog.rs index b39869df44..16cea01342 100644 --- a/crates/catalog/rest/src/catalog.rs +++ b/crates/catalog/rest/src/catalog.rs @@ -42,12 +42,11 @@ use reqwest::{Client, Method, StatusCode, Url}; use tokio::sync::OnceCell; use typed_builder::TypedBuilder; -use crate::auth::{ - AUTH_TYPE_NONE, AUTH_TYPE_OAUTH2, AuthManager, AuthSession, NoopAuthManager, OAuth2Manager, -}; +use crate::auth::{AUTH_TYPE_NONE, AUTH_TYPE_OAUTH2, AuthManager, AuthSession, load_auth_manager}; use crate::client::{ HttpClient, deserialize_catalog_response, deserialize_unexpected_catalog_error, }; +use crate::credential::{RestVendedCredentialProviderFactory, build_vended_credential_provider}; use crate::endpoint::{Endpoint, V1_NAMESPACE_EXISTS, V1_TABLE_EXISTS}; use crate::request::HttpRequest; use crate::response::HttpResponse; @@ -64,6 +63,12 @@ pub const REST_CATALOG_PROP_WAREHOUSE: &str = "warehouse"; /// Disable header redaction in error logs and `Debug` output (defaults to /// false for security) pub const REST_CATALOG_PROP_DISABLE_HEADER_REDACTION: &str = "disable-header-redaction"; +/// Identifier of the server-side scan plan sent with credential requests as +/// `planId`, as in Java's `RESTCatalogProperties.REST_SCAN_PLAN_ID`. +pub(crate) const REST_CATALOG_PROP_SCAN_PLAN_ID: &str = "rest-scan-plan-id"; +/// Encoded view chain sent with credential requests as `referenced-by`, as in +/// Java's `RESTCatalogProperties.REST_REFERENCED_BY`. +pub(crate) const REST_CATALOG_PROP_REFERENCED_BY: &str = "rest-referenced-by"; /// Authentication scheme: `none` or `oauth2`. When unset, `oauth2` is used /// if a `token`, `credential` or `oauth2-server-uri` is configured, `none` /// otherwise. @@ -320,10 +325,52 @@ impl RestCatalogConfig { /// Returns true if the `disable-header-redaction` property is set to "true". /// Defaults to false for security (headers are redacted by default). pub(crate) fn disable_header_redaction(&self) -> bool { + disable_header_redaction_from_props(&self.props).unwrap_or(false) + } + + /// The configured auth scheme: explicit `rest.auth.type` (matched + /// case-insensitively) when set; otherwise `oauth2` when a `token`, + /// `credential` or `oauth2-server-uri` is configured (preserving + /// pre-`rest.auth.type` setups), `none` when none is. + pub(crate) fn auth_type(&self) -> String { self.props - .get(REST_CATALOG_PROP_DISABLE_HEADER_REDACTION) - .map(|v| v.eq_ignore_ascii_case("true")) - .unwrap_or(false) + .get(REST_CATALOG_PROP_AUTH_TYPE) + // Matched case-insensitively, as the other flag properties are. + .map(|auth_type| auth_type.to_ascii_lowercase()) + .unwrap_or_else(|| { + if self.token().is_some() + || self.credential().is_some() + || self.explicit_oauth2_server_uri().is_some() + { + AUTH_TYPE_OAUTH2.to_string() + } else { + AUTH_TYPE_NONE.to_string() + } + }) + } + + /// Whether `rest.auth.type` is set explicitly rather than inferred. + pub(crate) fn has_explicit_auth_type(&self) -> bool { + self.props.contains_key(REST_CATALOG_PROP_AUTH_TYPE) + } + + /// The properties handed to the [`AuthManager`], with the catalog `uri` + /// and `warehouse` made explicit. + pub(crate) fn auth_props(&self) -> HashMap { + // `oauth2-server-uri` stays absent unless explicitly configured, so an + // injected manager keeps its own endpoint. The resolved `uri` and + // `warehouse` ARE passed: the builder moved them off the props, and + // the built-in manager recomputes its token endpoint from the URI. + let mut props = self.props.clone(); + props.insert(REST_CATALOG_PROP_URI.to_string(), self.uri.clone()); + if let Some(warehouse) = &self.warehouse { + // A fallback only: after the handshake the merged props hold + // the resolved warehouse, server override included. + props + .entry(REST_CATALOG_PROP_WAREHOUSE.to_string()) + .or_insert_with(|| warehouse.clone()); + } + props } /// Builds the table cache for freshness-aware loading, or `None` when @@ -429,6 +476,13 @@ pub(crate) fn extra_headers_from_props(props: &HashMap) -> Resul Ok(headers) } +/// The `disable-header-redaction` property, when set. +pub(crate) fn disable_header_redaction_from_props(props: &HashMap) -> Option { + props + .get(REST_CATALOG_PROP_DISABLE_HEADER_REDACTION) + .map(|value| value.eq_ignore_ascii_case("true")) +} + /// The default OAuth2 token endpoint for a catalog `uri`. pub(crate) fn default_token_endpoint(uri: &str) -> String { [uri, PATH_V1, "oauth", "tokens"].join("/") @@ -527,7 +581,7 @@ impl RestCatalogClient { // it before deriving the catalog session. let catalog_config = { let init_session = auth_manager - .init_session(&http_client, &Self::auth_props(user_config)) + .init_session(&http_client, &user_config.auth_props()) .await?; Self::load_config(&http_client, init_session.as_ref(), user_config).await? }; @@ -542,7 +596,7 @@ impl RestCatalogClient { // The manager is handed an unauthenticated client: its own // requests must not be signed by the session it is deriving. let catalog_session = auth_manager - .catalog_session(&http_client, &Self::auth_props(&config)) + .catalog_session(&http_client, &config.auth_props()) .await?; Ok(Self { @@ -582,25 +636,6 @@ impl RestCatalogClient { .await } - /// The properties handed to the [`AuthManager`], with the catalog `uri` - /// and `warehouse` made explicit. - fn auth_props(config: &RestCatalogConfig) -> HashMap { - // `oauth2-server-uri` stays absent unless explicitly configured, so an - // injected manager keeps its own endpoint. The resolved `uri` and - // `warehouse` ARE passed: the builder moved them off the props, and - // the built-in manager recomputes its token endpoint from the URI. - let mut props = config.props.clone(); - props.insert(REST_CATALOG_PROP_URI.to_string(), config.uri.clone()); - if let Some(warehouse) = &config.warehouse { - // A fallback only: after the handshake the merged props hold - // the resolved warehouse, server override included. - props - .entry(REST_CATALOG_PROP_WAREHOUSE.to_string()) - .or_insert_with(|| warehouse.clone()); - } - props - } - /// Loads the runtime config from the server using `user_config`. /// /// It's required for a REST catalog to update its config after creation. @@ -856,57 +891,13 @@ impl RestSessionCatalog { } } - /// The configured auth scheme: explicit `rest.auth.type` (matched - /// case-insensitively) when set; otherwise `oauth2` when a `token`, - /// `credential` or `oauth2-server-uri` is configured (preserving - /// pre-`rest.auth.type` setups), `none` when none is. - fn auth_type(config: &RestCatalogConfig) -> String { - config - .props - .get(REST_CATALOG_PROP_AUTH_TYPE) - // Matched case-insensitively, as the other flag properties are. - .map(|auth_type| auth_type.to_ascii_lowercase()) - .unwrap_or_else(|| { - if config.token().is_some() - || config.credential().is_some() - || config.explicit_oauth2_server_uri().is_some() - { - AUTH_TYPE_OAUTH2.to_string() - } else { - AUTH_TYPE_NONE.to_string() - } - }) - } - /// Resolves the auth manager: a `with_auth_manager` override wins, /// otherwise one is built from the `rest.auth.type` configuration. fn resolve_auth_manager(&self) -> Result> { if let Some(auth_manager) = &self.auth_manager_override { return Ok(auth_manager.clone()); } - let config = &self.user_config; - let auth_type = Self::auth_type(config); - // Java parity (`AuthManagers`): make the inference visible so users - // configure the type explicitly. - if auth_type == AUTH_TYPE_OAUTH2 && !config.props.contains_key(REST_CATALOG_PROP_AUTH_TYPE) - { - tracing::warn!( - "Inferring {REST_CATALOG_PROP_AUTH_TYPE}={AUTH_TYPE_OAUTH2} from the configured \ - OAuth properties; set it explicitly to avoid this warning" - ); - } - match auth_type.as_str() { - AUTH_TYPE_NONE => Ok(Arc::new(NoopAuthManager)), - AUTH_TYPE_OAUTH2 => Ok(Arc::new(OAuth2Manager::from_config(config)?)), - other => Err(Error::new( - ErrorKind::DataInvalid, - format!( - "unknown '{REST_CATALOG_PROP_AUTH_TYPE}': {other}; use \ - `RestSessionCatalogBuilder::with_auth_manager` or \ - `RestCatalogBuilder::with_auth_manager` to inject a custom auth manager" - ), - )), - } + load_auth_manager(&self.user_config) } /// Gets the [`RestCatalogClient`] from the catalog. @@ -946,22 +937,28 @@ impl RestSessionCatalog { } } + /// Builds the FileIO for `table` from the catalog properties and, when + /// loaded from a table response, its `config` overridden by the user + /// properties. async fn load_file_io( &self, + context: &SessionContext, + table: &TableIdent, metadata_location: Option<&str>, - extra_config: Option>, + table_config: Option>, ) -> Result { - let mut props = self.client().await?.config.props.clone(); - if let Some(config) = extra_config { - props.extend(config); + let client = self.client().await?; + let mut props = client.config.props.clone(); + if let Some(table_config) = &table_config { + props.extend(table_config.clone()); + props.extend(self.user_config.props.clone()); } // If the warehouse is a logical identifier instead of a URL we don't want // to raise an exception - let warehouse_path = match self.client().await?.config.warehouse.as_deref() { + let warehouse_path = match client.config.warehouse.as_deref() { Some(url) if Url::parse(url).is_ok() => Some(url), - Some(_) => None, - None => None, + _ => None, }; if metadata_location.or(warehouse_path).is_none() { @@ -982,9 +979,42 @@ impl RestSessionCatalog { ) })?; - let file_io = FileIOBuilder::new(factory).with_props(props).build(); + // If the catalog vends refreshable credentials for this table's storage, + // attach a provider so the backend re-fetches them before they expire. + // Credential requests are authenticated for the operation's context. + // Only catalog authentication resolved from the properties can be + // rebuilt after FileIO serialization: the built-in auth managers + // derive no contextual session, so a rebuilt provider authenticates + // the same way. + let table_config = table_config.unwrap_or_default(); + let credential_provider = build_vended_credential_provider( + &client.http_client, + client.auth_manager.as_ref(), + async || { + client + .auth_manager + .contextual_session(context, Arc::clone(&client.catalog_session)) + .await + }, + RestVendedCredentialProviderFactory::new( + &client.config.uri, + table.clone(), + self.user_config.auth_type(), + !self.user_config.has_explicit_auth_type(), + &table_config, + ), + &props, + &table_config, + self.auth_manager_override.is_none(), + ) + .await?; + + let mut builder = FileIOBuilder::new(factory).with_props(props); + if let Some(provider) = credential_provider { + builder = builder.with_credential_provider(provider); + } - Ok(file_io) + Ok(builder.build()) } } @@ -1288,14 +1318,13 @@ impl SessionCatalog for RestSessionCatalog { "Metadata location missing in `create_table` response!", ))?; - let config = response - .config - .into_iter() - .chain(self.user_config.props.clone()) - .collect(); - let file_io = self - .load_file_io(Some(metadata_location), Some(config)) + .load_file_io( + context, + &table_ident, + Some(metadata_location), + Some(response.config), + ) .await?; let mut table_builder = Table::builder() @@ -1385,14 +1414,13 @@ impl SessionCatalog for RestSessionCatalog { .keys() .any(|key| is_short_lived_credential(key)); - let config = response - .config - .into_iter() - .chain(self.user_config.props.clone()) - .collect(); - let file_io = self - .load_file_io(response.metadata_location.as_deref(), Some(config)) + .load_file_io( + context, + table_ident, + response.metadata_location.as_deref(), + Some(response.config), + ) .await?; let mut table_builder = Table::builder() @@ -1543,7 +1571,14 @@ impl SessionCatalog for RestSessionCatalog { "Metadata location missing in `register_table` response!", ))?; - let file_io = self.load_file_io(Some(metadata_location), None).await?; + let file_io = self + .load_file_io( + context, + table_ident, + Some(metadata_location), + Some(response.config), + ) + .await?; let mut table_builder = Table::builder() .identifier(table_ident.clone()) @@ -1623,7 +1658,12 @@ impl SessionCatalog for RestSessionCatalog { }; let file_io = self - .load_file_io(Some(&response.metadata_location), None) + .load_file_io( + context, + commit.identifier(), + Some(&response.metadata_location), + None, + ) .await?; let mut table_builder = Table::builder() @@ -1820,7 +1860,10 @@ mod tests { use std::sync::{Arc, Mutex}; use chrono::{TimeZone, Utc}; - use iceberg::io::LocalFsStorageFactory; + use iceberg::io::{ + LocalFsStorageFactory, MemoryStorageFactory, Storage, StorageConfig, + StorageCredentialProvider, + }; use iceberg::spec::{ FormatVersion, NestedField, NullOrder, Operation, PrimitiveType, Schema, Snapshot, SnapshotLog, SortDirection, SortField, SortOrder, Summary, Transform, Type, @@ -1833,7 +1876,7 @@ mod tests { use uuid::uuid; use super::*; - use crate::auth::AuthSession; + use crate::auth::{AuthSession, NoopAuthManager, NoopSession, OAuth2Manager}; use crate::request::HttpRequest; #[derive(Debug)] @@ -4865,6 +4908,361 @@ mod tests { load_table_mock.assert_async().await } + #[tokio::test] + async fn test_load_table_attaches_the_vended_credential_provider() { + let mut server = Server::new_async().await; + let config_mock = create_config_mock(&mut server).await; + let mut load_response: serde_json::Value = serde_json::from_reader(BufReader::new( + File::open(format!( + "{}/testdata/load_table_response.json", + env!("CARGO_MANIFEST_DIR") + )) + .unwrap(), + )) + .unwrap(); + load_response["config"]["client.refresh-credentials-endpoint"] = + json!("/v1/namespaces/ns1/tables/test1/credentials"); + load_response["config"]["token"] = json!("table-token"); + let load_table_mock = server + .mock("GET", "/v1/namespaces/ns1/tables/test1") + .with_status(200) + .with_body(load_response.to_string()) + .create_async() + .await; + let expires_at = (std::time::SystemTime::now() + Duration::from_secs(3600)) + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis(); + let credentials_mock = server + .mock("GET", "/v1/namespaces/ns1/tables/test1/credentials") + .match_header("authorization", "Bearer table-token") + .with_status(200) + .with_body( + json!({"storage-credentials": [{ + "prefix": "s3://warehouse", + "config": { + "s3.access-key-id": "VENDED_AK", + "s3.secret-access-key": "SK", + "s3.session-token": "TOK", + "s3.session-token-expires-at-ms": expires_at.to_string(), + }, + }]}) + .to_string(), + ) + .create_async() + .await; + + let catalog = RestCatalog::new( + SessionContext::empty(), + RestCatalogConfig::builder().uri(server.url()).build(), + None, + Some(Arc::new(LocalFsStorageFactory)), + Runtime::current(), + None, + ); + let table = catalog + .load_table(&TableIdent::from_strs(["ns1", "test1"]).unwrap()) + .await + .unwrap(); + + assert!( + format!("{:?}", table.file_io()).contains("RestVendedCredentialProvider"), + "the table's FileIO holds the provider" + ); + // The serialized provider rebuilds, and refreshes with the table token. + let serialized: serde_json::Value = + serde_json::from_slice(&table.file_io().serialize_all().unwrap()).unwrap(); + let factory: Arc = + serde_json::from_value(serialized["credential_provider"].clone()).unwrap(); + let config = StorageConfig::new().with_props( + serialized["config"]["props"] + .as_object() + .unwrap() + .iter() + .map(|(key, value)| (key.clone(), value.as_str().unwrap().to_string())), + ); + let credential = factory + .build(&config) + .unwrap() + .load_credential("s3://warehouse/database/table/data.parquet") + .await + .unwrap(); + assert_eq!( + credential + .config() + .get("s3.access-key-id") + .map(String::as_str), + Some("VENDED_AK") + ); + + config_mock.assert_async().await; + load_table_mock.assert_async().await; + credentials_mock.assert_async().await; + } + + /// Authenticates every request as `Bearer {token}`. + #[derive(Debug)] + struct BearerSession(String); + + #[async_trait] + impl AuthSession for BearerSession { + async fn authenticate(&self, request: &mut HttpRequest) -> Result<()> { + request.headers_mut().insert( + "authorization", + format!("Bearer {}", self.0).parse().unwrap(), + ); + Ok(()) + } + } + + /// Authenticates contextual requests as the context's identity. + #[derive(Debug)] + struct IdentityAuthManager; + + #[async_trait] + impl AuthManager for IdentityAuthManager { + async fn init_session( + &self, + _client: &HttpClient, + _props: &HashMap, + ) -> Result> { + Ok(Box::new(NoopSession)) + } + + async fn catalog_session( + &self, + _client: &HttpClient, + _props: &HashMap, + ) -> Result> { + Ok(Arc::new(NoopSession)) + } + + async fn contextual_session( + &self, + context: &SessionContext, + _catalog_session: Arc, + ) -> Result> { + Ok(Arc::new(BearerSession(format!( + "for-{}", + context.identity().unwrap_or_default() + )))) + } + } + + /// Counts the contextual sessions it derives. + #[derive(Debug, Default)] + struct CountingAuthManager { + contextual_sessions: Arc, + } + + #[async_trait] + impl AuthManager for CountingAuthManager { + async fn init_session( + &self, + _client: &HttpClient, + _props: &HashMap, + ) -> Result> { + Ok(Box::new(NoopSession)) + } + + async fn catalog_session( + &self, + _client: &HttpClient, + _props: &HashMap, + ) -> Result> { + Ok(Arc::new(NoopSession)) + } + + async fn contextual_session( + &self, + _context: &SessionContext, + catalog_session: Arc, + ) -> Result> { + self.contextual_sessions + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(catalog_session) + } + } + + #[tokio::test] + async fn test_load_table_without_refresh_endpoint_derives_no_extra_session() { + let mut server = Server::new_async().await; + let config_mock = create_config_mock(&mut server).await; + let load_table_mock = server + .mock("GET", "/v1/namespaces/ns1/tables/test1") + .with_status(200) + .with_body_from_file(format!( + "{}/testdata/load_table_response.json", + env!("CARGO_MANIFEST_DIR") + )) + .create_async() + .await; + + let auth_manager = CountingAuthManager::default(); + let contextual_sessions = Arc::clone(&auth_manager.contextual_sessions); + let catalog = RestCatalog::new( + SessionContext::empty(), + RestCatalogConfig::builder().uri(server.url()).build(), + Some(Box::new(auth_manager)), + Some(Arc::new(LocalFsStorageFactory)), + Runtime::current(), + None, + ); + catalog + .load_table(&TableIdent::from_strs(["ns1", "test1"]).unwrap()) + .await + .unwrap(); + + // Only the load request is authenticated: without refreshable + // credentials, building the table's FileIO makes no auth calls. + assert_eq!( + contextual_sessions.load(std::sync::atomic::Ordering::SeqCst), + 1 + ); + config_mock.assert_async().await; + load_table_mock.assert_async().await; + } + + /// Memory storage that keeps the credential provider `FileIO` hands it. + #[derive(Debug, Default, serde::Serialize, serde::Deserialize)] + struct ProviderCapturingFactory { + #[serde(skip)] + provider: Arc>>>, + } + + #[typetag::serde] + impl StorageFactory for ProviderCapturingFactory { + fn build(&self, config: &StorageConfig) -> Result> { + MemoryStorageFactory.build(config) + } + + fn build_with_credential_provider( + &self, + config: &StorageConfig, + credential_provider: Option>, + ) -> Result> { + *self.provider.lock().unwrap() = credential_provider; + self.build(config) + } + } + + #[tokio::test] + async fn test_vended_credentials_use_the_contextual_session() { + let mut server = Server::new_async().await; + let config_mock = create_config_mock(&mut server).await; + let mut load_response: serde_json::Value = serde_json::from_reader(BufReader::new( + File::open(format!( + "{}/testdata/load_table_response.json", + env!("CARGO_MANIFEST_DIR") + )) + .unwrap(), + )) + .unwrap(); + load_response["config"]["client.refresh-credentials-endpoint"] = + json!("/v1/namespaces/ns1/tables/test1/credentials"); + let load_table_mock = server + .mock("GET", "/v1/namespaces/ns1/tables/test1") + .match_header("authorization", "Bearer for-alice") + .with_status(200) + .with_body(load_response.to_string()) + .create_async() + .await; + let expires_at = (std::time::SystemTime::now() + Duration::from_secs(3600)) + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis(); + let credentials_mock = server + .mock("GET", "/v1/namespaces/ns1/tables/test1/credentials") + .match_header("authorization", "Bearer for-alice") + .with_status(200) + .with_body( + json!({"storage-credentials": [{ + "prefix": "s3://warehouse", + "config": { + "s3.access-key-id": "VENDED_AK", + "s3.secret-access-key": "SK", + "s3.session-token": "TOK", + "s3.session-token-expires-at-ms": expires_at.to_string(), + }, + }]}) + .to_string(), + ) + .create_async() + .await; + + let factory = Arc::new(ProviderCapturingFactory::default()); + let catalog = RestCatalog::new( + SessionContext::builder() + .identity("alice".to_string()) + .build(), + RestCatalogConfig::builder().uri(server.url()).build(), + Some(Box::new(IdentityAuthManager)), + Some(factory.clone()), + Runtime::current(), + None, + ); + let table = catalog + .load_table(&TableIdent::from_strs(["ns1", "test1"]).unwrap()) + .await + .unwrap(); + // Building the storage hands the provider to the factory. + table.file_io().exists("memory:/probe").await.unwrap(); + let provider = factory.provider.lock().unwrap().clone().unwrap(); + + // The refresh is authenticated for the context that loaded the table. + provider + .load_credential("s3://warehouse/database/table/data.parquet") + .await + .unwrap(); + config_mock.assert_async().await; + load_table_mock.assert_async().await; + credentials_mock.assert_async().await; + } + + #[tokio::test] + async fn test_injected_auth_manager_file_io_serializes_without_provider() { + let mut server = Server::new_async().await; + let config_mock = create_config_mock(&mut server).await; + let mut load_response: serde_json::Value = serde_json::from_reader(BufReader::new( + File::open(format!( + "{}/testdata/load_table_response.json", + env!("CARGO_MANIFEST_DIR") + )) + .unwrap(), + )) + .unwrap(); + load_response["config"]["client.refresh-credentials-endpoint"] = + json!("/v1/namespaces/ns1/tables/test1/credentials"); + let load_table_mock = server + .mock("GET", "/v1/namespaces/ns1/tables/test1") + .with_status(200) + .with_body(load_response.to_string()) + .create_async() + .await; + + let catalog = RestCatalog::new( + SessionContext::empty(), + RestCatalogConfig::builder().uri(server.url()).build(), + Some(Box::new(NoopAuthManager)), + Some(Arc::new(LocalFsStorageFactory)), + Runtime::current(), + None, + ); + let table = catalog + .load_table(&TableIdent::from_strs(["ns1", "test1"]).unwrap()) + .await + .unwrap(); + + // The FileIO serializes with its static credentials; the provider, which + // cannot be rebuilt with an injected AuthManager, is dropped. + let serialized: serde_json::Value = + serde_json::from_slice(&table.file_io().serialize_all().unwrap()).unwrap(); + assert!(serialized.get("credential_provider").is_none()); + + config_mock.assert_async().await; + load_table_mock.assert_async().await; + } + #[tokio::test] async fn test_update_table_404() { let mut server = Server::new_async().await; @@ -4993,6 +5391,45 @@ mod tests { register_table_mock.assert_async().await; } + #[tokio::test] + async fn test_register_table_attaches_the_vended_credential_provider() { + let mut server = Server::new_async().await; + let config_mock = create_config_mock(&mut server).await; + let mut response: serde_json::Value = serde_json::from_reader(BufReader::new( + File::open(format!( + "{}/testdata/load_table_response.json", + env!("CARGO_MANIFEST_DIR") + )) + .unwrap(), + )) + .unwrap(); + response["config"]["client.refresh-credentials-endpoint"] = + json!("/v1/namespaces/ns1/tables/test1/credentials"); + let register_table_mock = server + .mock("POST", "/v1/namespaces/ns1/register") + .with_status(200) + .with_body(response.to_string()) + .create_async() + .await; + + let catalog = session_catalog(RestCatalogConfig::builder().uri(server.url()).build()); + let table = catalog + .register_table( + &SessionContext::empty(), + &TableIdent::from_strs(["ns1", "test1"]).unwrap(), + "s3://warehouse/database/table/metadata/00001-5f2f8166-244c-4eae-ac36-384ecdec81fc.gz.metadata.json".to_string(), + ) + .await + .unwrap(); + + assert!( + format!("{:?}", table.file_io()).contains("RestVendedCredentialProvider"), + "the registered table's FileIO holds the provider" + ); + config_mock.assert_async().await; + register_table_mock.assert_async().await; + } + #[tokio::test] async fn test_register_table_404() { let mut server = Server::new_async().await; diff --git a/crates/catalog/rest/src/client.rs b/crates/catalog/rest/src/client.rs index f81f86574b..7e500db75e 100644 --- a/crates/catalog/rest/src/client.rs +++ b/crates/catalog/rest/src/client.rs @@ -25,6 +25,7 @@ use serde::de::DeserializeOwned; use crate::RestCatalogConfig; use crate::auth::AuthSession; +use crate::catalog::{disable_header_redaction_from_props, explicit_headers_from_props}; use crate::request::HttpRequest; use crate::response::HttpResponse; @@ -115,6 +116,24 @@ impl HttpClient { }) } + /// Derives a client for table-scoped requests. + /// + /// The connection pool and catalog headers are inherited, and headers in + /// the effective table properties override them. As in Java, an explicit + /// `header.Authorization` takes precedence over the session that + /// authenticates a request. + pub(crate) fn for_table(&self, props: &HashMap) -> Result { + let mut extra_headers = self.extra_headers.clone(); + extra_headers.extend(explicit_headers_from_props(props)?); + + Ok(Self { + client: self.client.clone(), + extra_headers, + disable_header_redaction: disable_header_redaction_from_props(props) + .unwrap_or(self.disable_header_redaction), + }) + } + /// Testing only: the bearer token `session` would attach. /// /// Authenticates a throwaway request (never sent) and reads the header @@ -184,55 +203,48 @@ pub(crate) fn deserialize_catalog_response( }) } -/// Returns true if the header may carry a secret (matched by substring, so -/// e.g. `x-client-secret` is covered along with `authorization`). -fn is_sensitive_header(name: &str) -> bool { - let name_lower = name.to_lowercase(); - [ - "auth", - "token", - "secret", - "key", - "password", - "cookie", - "credential", - ] - .iter() - .any(|pattern| name_lower.contains(pattern)) -} - -/// Redacts sensitive headers and returns a debug-formatted string. +/// Formats headers for errors and `Debug` output. /// -/// If `disable_redaction` is true, returns all headers without redaction. -/// Otherwise, replaces sensitive header values with `[REDACTED]`. +/// Like Java, every header value is redacted, as any header may carry a +/// secret. With `disable_redaction`, values are shown as they are. pub(crate) fn format_headers_redacted(headers: &HeaderMap, disable_redaction: bool) -> String { - if disable_redaction { - // Return all headers as-is without redaction - let all: HashMap<&str, &str> = headers - .iter() - .filter_map(|(name, value)| value.to_str().ok().map(|v| (name.as_str(), v))) - .collect(); - return format!("{all:?}"); - } - - // Redact sensitive headers by replacing their values with "[REDACTED]" - let redacted: HashMap<&str, &str> = headers + let headers: HashMap<&str, &str> = headers .iter() .filter_map(|(name, value)| { - if is_sensitive_header(name.as_str()) { - Some((name.as_str(), "[REDACTED]")) + let value = if disable_redaction { + value.to_str().ok()? } else { - value.to_str().ok().map(|v| (name.as_str(), v)) - } + "[REDACTED]" + }; + Some((name.as_str(), value)) }) .collect(); - format!("{redacted:?}") + format!("{headers:?}") } /// Deserializes a unexpected catalog response into an error. pub(crate) fn deserialize_unexpected_catalog_error( response: HttpResponse, disable_header_redaction: bool, +) -> Error { + unexpected_catalog_error(response, disable_header_redaction, true) +} + +/// Builds an unexpected catalog error without retaining the response body. +/// +/// Credential endpoints use this because even an unsuccessful response may +/// contain credential material that must not be surfaced through an error. +pub(crate) fn unexpected_catalog_error_without_body( + response: HttpResponse, + disable_header_redaction: bool, +) -> Error { + unexpected_catalog_error(response, disable_header_redaction, false) +} + +fn unexpected_catalog_error( + response: HttpResponse, + disable_header_redaction: bool, + include_body: bool, ) -> Error { let err = Error::new( ErrorKind::Unexpected, @@ -248,12 +260,49 @@ pub(crate) fn deserialize_unexpected_catalog_error( if bytes.is_empty() { return err; } - err.with_context("json", String::from_utf8_lossy(bytes)) + if include_body { + return err.with_context("json", String::from_utf8_lossy(bytes)); + } + // Without the body, keep only the catalog's error description. + match serde_json::from_slice::(bytes) { + Ok(CatalogErrorResponse { error }) => err + .with_context("type", error.r#type) + .with_context("code", error.code.to_string()) + .with_context("message", error.message), + Err(_) => err, + } +} + +/// The parts of a REST catalog error response that describe the error. +#[derive(serde::Deserialize)] +struct CatalogErrorResponse { + error: CatalogError, +} + +#[derive(serde::Deserialize)] +struct CatalogError { + message: String, + r#type: String, + code: u16, } #[cfg(test)] mod tests { use super::*; + use crate::catalog::REST_CATALOG_PROP_DISABLE_HEADER_REDACTION; + + #[derive(Debug)] + struct TableSession; + + #[async_trait::async_trait] + impl AuthSession for TableSession { + async fn authenticate(&self, request: &mut HttpRequest) -> Result<()> { + request + .headers_mut() + .insert("authorization", "Bearer table-token".parse().unwrap()); + Ok(()) + } + } #[tokio::test] async fn test_a_truncated_body_error_names_the_url() { @@ -313,7 +362,7 @@ mod tests { #[test] fn test_unexpected_error_carries_status_headers_and_body() { // Everything a user needs to diagnose an unexpected status, with the - // sensitive headers held back. + // header values held back. let mut headers = HeaderMap::new(); headers.insert("authorization", "Bearer leaked".parse().unwrap()); headers.insert("x-request-id", "abc123".parse().unwrap()); @@ -330,9 +379,26 @@ mod tests { assert!(err.contains("418"), "{err}"); assert!(err.contains("x-request-id"), "{err}"); - assert!(err.contains("abc123"), "{err}"); assert!(err.contains("nope"), "{err}"); assert!(!err.contains("leaked"), "{err}"); + assert!(!err.contains("abc123"), "{err}"); + } + + #[test] + fn test_unexpected_error_can_omit_a_secret_body() { + let response = HttpResponse::new( + http::StatusCode::INTERNAL_SERVER_ERROR, + HeaderMap::new(), + br#"{"secret": "do-not-expose"}"#.to_vec(), + ); + + let err = format!( + "{:?}", + unexpected_catalog_error_without_body(response, false) + ); + + assert!(err.contains("500"), "{err}"); + assert!(!err.contains("do-not-expose"), "{err}"); } #[tokio::test] @@ -368,6 +434,80 @@ mod tests { mock.assert_async().await; } + #[tokio::test] + async fn test_table_client_uses_table_session_and_explicit_headers() { + let mut server = mockito::Server::new_async().await; + let table_session = server + .mock("GET", "/session") + .match_header("authorization", "Bearer table-token") + .match_header("x-catalog", "catalog") + .with_status(200) + .create_async() + .await; + let explicit_header = server + .mock("GET", "/header") + .match_header("authorization", "Bearer explicit-header") + .with_status(200) + .create_async() + .await; + + let config = RestCatalogConfig::builder() + .uri(server.url()) + .props(HashMap::from([( + "header.x-catalog".to_string(), + "catalog".to_string(), + )])) + .build(); + let catalog_client = HttpClient::new(&config).unwrap(); + let get = |client: &HttpClient, path: &str| { + HttpRequest::build(client.request(Method::GET, format!("{}{path}", server.url()))) + .unwrap() + }; + + // The table session authenticates, and catalog headers are inherited. + let session_client = catalog_client.for_table(&HashMap::new()).unwrap(); + session_client + .query_catalog(&TableSession, get(&session_client, "/session")) + .await + .unwrap(); + table_session.assert_async().await; + + // An explicit Authorization header in the effective properties wins + // over the session, as in Java. + let header_client = catalog_client + .for_table(&HashMap::from([( + "header.Authorization".to_string(), + "Bearer explicit-header".to_string(), + )])) + .unwrap(); + header_client + .query_catalog(&TableSession, get(&header_client, "/header")) + .await + .unwrap(); + explicit_header.assert_async().await; + } + + #[test] + fn test_table_client_redaction_follows_the_table_properties() { + let catalog_client = HttpClient::new( + &RestCatalogConfig::builder() + .uri("http://localhost".to_string()) + .build(), + ) + .unwrap(); + assert!(!catalog_client.disable_header_redaction()); + + let inherited = catalog_client.for_table(&HashMap::new()).unwrap(); + assert!(!inherited.disable_header_redaction()); + let disabled = catalog_client + .for_table(&HashMap::from([( + REST_CATALOG_PROP_DISABLE_HEADER_REDACTION.to_string(), + "true".to_string(), + )])) + .unwrap(); + assert!(disabled.disable_header_redaction()); + } + #[test] fn test_format_headers_redacted_empty() { let headers = HeaderMap::new(); @@ -376,17 +516,38 @@ mod tests { } #[test] - fn test_format_headers_redacted_non_sensitive() { + fn test_format_headers_redacted_redacts_every_value() { let mut headers = HeaderMap::new(); + headers.insert("authorization", "Bearer secret-token".parse().unwrap()); + headers.insert( + "set-cookie", + "CF_Authorization=sensitive-session-token; Path=/; Secure;" + .parse() + .unwrap(), + ); + headers.insert("x-custom-signature", "unmatched-secret".parse().unwrap()); headers.insert("content-type", "application/json".parse().unwrap()); - headers.insert("x-request-id", "abc123".parse().unwrap()); let result = format_headers_redacted(&headers, false); - assert!(result.contains("content-type")); - assert!(result.contains("application/json")); - assert!(result.contains("x-request-id")); - assert!(result.contains("abc123")); + // Every header name is shown, with its value redacted. + for name in [ + "authorization", + "set-cookie", + "x-custom-signature", + "content-type", + ] { + assert!(result.contains(name), "{result}"); + } + for value in [ + "secret-token", + "sensitive-session-token", + "unmatched-secret", + "application/json", + ] { + assert!(!result.contains(value), "{result}"); + } + assert!(result.contains("[REDACTED]")); } #[tokio::test] @@ -414,81 +575,6 @@ mod tests { assert!(out.contains("[REDACTED]")); } - #[test] - fn test_format_headers_redacted_filters_sensitive() { - let mut headers = HeaderMap::new(); - headers.insert("authorization", "Bearer secret-token".parse().unwrap()); - headers.insert("content-type", "application/json".parse().unwrap()); - - let result = format_headers_redacted(&headers, false); - - // Sensitive header should be present but with redacted value - assert!(result.contains("authorization")); - assert!(result.contains("[REDACTED]")); - // Sensitive value should NOT be present - assert!(!result.contains("secret-token")); - // Non-sensitive header should be present with actual value - assert!(result.contains("content-type")); - assert!(result.contains("application/json")); - } - - #[test] - fn test_format_headers_redacted_filters_set_cookie() { - let mut headers = HeaderMap::new(); - headers.insert( - "set-cookie", - "CF_Authorization=sensitive-session-token; Path=/; Secure;" - .parse() - .unwrap(), - ); - headers.insert("server", "cloudflare".parse().unwrap()); - - let result = format_headers_redacted(&headers, false); - - // Sensitive header should be present but with redacted value - assert!(result.contains("set-cookie")); - assert!(result.contains("[REDACTED]")); - // Sensitive value should NOT be present - assert!(!result.contains("sensitive-session-token")); - // Non-sensitive header should be present with actual value - assert!(result.contains("server")); - assert!(result.contains("cloudflare")); - } - - #[test] - fn test_format_headers_redacted_filters_all_sensitive() { - let mut headers = HeaderMap::new(); - headers.insert("authorization", "Bearer token".parse().unwrap()); - headers.insert("proxy-authorization", "Basic creds".parse().unwrap()); - headers.insert("set-cookie", "session=abc".parse().unwrap()); - headers.insert("cookie", "session=abc".parse().unwrap()); - headers.insert("x-api-key", "api-key-123".parse().unwrap()); - headers.insert("x-auth-token", "auth-token-456".parse().unwrap()); - headers.insert("x-request-id", "req-123".parse().unwrap()); - - let result = format_headers_redacted(&headers, false); - - // All sensitive headers should be present but with redacted values - assert!(result.contains("authorization")); - assert!(result.contains("proxy-authorization")); - assert!(result.contains("set-cookie")); - assert!(result.contains("cookie")); - assert!(result.contains("x-api-key")); - assert!(result.contains("x-auth-token")); - assert!(result.contains("[REDACTED]")); - - // Ensure no sensitive values leaked - assert!(!result.contains("Bearer token")); - assert!(!result.contains("Basic creds")); - assert!(!result.contains("session=abc")); - assert!(!result.contains("api-key-123")); - assert!(!result.contains("auth-token-456")); - - // Non-sensitive header should be present with actual value - assert!(result.contains("x-request-id")); - assert!(result.contains("req-123")); - } - #[test] fn test_format_headers_with_redaction_disabled() { let mut headers = HeaderMap::new(); diff --git a/crates/catalog/rest/src/credential.rs b/crates/catalog/rest/src/credential.rs new file mode 100644 index 0000000000..4c7cb5b1f5 --- /dev/null +++ b/crates/catalog/rest/src/credential.rs @@ -0,0 +1,4326 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Vended storage credentials from a REST catalog. +//! +//! A REST catalog can vend short-lived storage credentials whose lifetime the +//! client does not control. [`RestVendedCredentialProvider`] implements the +//! core [`StorageCredentialProvider`] trait so storage backends re-fetch those +//! credentials from the catalog's table credentials endpoint before they +//! expire, keeping long-running jobs authenticated instead of failing with a +//! `403` once the initial token's TTL elapses. +//! +//! Unlike the Java client, which has one provider per cloud SDK, this is a +//! single backend-agnostic provider with an independent endpoint and cache for +//! each configured cloud. The path being accessed selects the cloud cache. Like +//! Java's `StorageCredential`, the returned [`StorageCredential`] holds the +//! backend's storage properties, which the storage adapter turns into its own +//! credential. This preserves Java's per-cloud credential selection and +//! prefetch policies while supporting mixed-cloud tables through a resolving +//! FileIO. Unlike Java's scheduled refresh, which permanently stops +//! after a failed fetch, transient failures are retried here with jittered +//! exponential backoff while an unexpired credential remains available. +//! +//! Like Java's `VendedCredentialsProvider`, a provider is rebuilt from the +//! FileIO properties after [`FileIO`](iceberg::io::FileIO) serialization and +//! connects to the catalog lazily in the receiving process. This requires +//! catalog authentication that can be rebuilt from `rest.auth.type`. +//! +//! # Adding a cloud +//! +//! The refresh policy for each cloud lives in one [`CloudRefresh`] constant. To +//! add a backend, teach its storage adapter to read its credential properties +//! from a [`StorageCredential`]. Then write its `parse_*` function, add a +//! `CloudRefresh` constant, and list it in [`CloudRefresh::SUPPORTED`]. + +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use async_trait::async_trait; +use iceberg::io::{ + ADLS_REFRESH_CREDENTIALS_ENABLED, ADLS_REFRESH_CREDENTIALS_ENDPOINT, + ADLS_SAS_TOKEN_EXPIRES_AT_MS_PREFIX, ADLS_SAS_TOKEN_PREFIX, AWS_REFRESH_CREDENTIALS_ENABLED, + AWS_REFRESH_CREDENTIALS_ENDPOINT, GCS_REFRESH_CREDENTIALS_ENABLED, + GCS_REFRESH_CREDENTIALS_ENDPOINT, GCS_TOKEN, GCS_TOKEN_EXPIRES_AT, S3_ACCESS_KEY_ID, + S3_SECRET_ACCESS_KEY, S3_SESSION_TOKEN, S3_SESSION_TOKEN_EXPIRES_AT_MS, StorageConfig, + StorageCredential, StorageCredentialProvider, StorageCredentialProviderFactory, +}; +use iceberg::{Error, ErrorKind, Result, TableIdent}; +use rand::Rng; +use reqwest::{Method, Url}; +use serde::{Deserialize, Serialize}; +use tokio::sync::{Mutex, OnceCell}; + +use crate::auth::{ + AUTH_TYPE_NONE, AuthManager, AuthSession, load_auth_manager, static_token_session, +}; +use crate::catalog::{ + REST_CATALOG_PROP_AUTH_TYPE, REST_CATALOG_PROP_REFERENCED_BY, REST_CATALOG_PROP_SCAN_PLAN_ID, + RestCatalogConfig, +}; +use crate::client::{HttpClient, unexpected_catalog_error_without_body}; +use crate::request::HttpRequest; +use crate::response::HttpResponse; +use crate::types::LoadCredentialsResponse; + +type CredentialParser = fn( + config: &HashMap, + prefix: String, + expiry: Expiry, +) -> Result; +type KeyedSeedCredentialParser = + fn(config: &HashMap) -> HashMap; +type KeyedSeedPathResolver = fn(path: &str) -> Result; + +/// Whether a credential must declare when it expires. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Expiry { + /// Credentials from the refresh endpoint are temporary, so they must. + Required, + /// Initial credentials in the table properties may omit it. Like Java, + /// the catalog is asked for credentials first, but one without an expiry + /// never expires, so it keeps being served while refresh fails. + Optional, +} + +/// A credential vended by the catalog, with the expiry its config declares. +#[derive(Clone)] +struct VendedCredential { + credential: Arc, + /// `None` when the credential declares no expiry, so it never expires. + expires_at: Option, +} + +enum SeedStrategy { + /// One credential stored in the backend's flat properties, for every + /// location with one of the scheme prefixes, like Java's root clients. + Flat { prefixes: &'static [&'static str] }, + /// Credentials selected by a backend-specific key derived from each path. + Keyed(KeyedSeedStrategy), +} + +struct KeyedSeedStrategy { + parse_credentials: KeyedSeedCredentialParser, + resolve_path: KeyedSeedPathResolver, +} + +struct KeyedSeedPath { + /// Seed keys for the path, most specific first. + keys: Vec, + scope: String, +} + +/// Cloud-specific details regarding vended-credential refresh. +/// +/// It contains the location schemes it backs, the property keys it is configured +/// with, and how to parse its credential. The generic provider stays free of +/// any per-cloud knowledge. +struct CloudRefresh { + /// Location URL schemes this backend serves. + schemes: &'static [&'static str], + /// Table property naming the refresh endpoint (absolute or catalog-relative). + endpoint_key: &'static str, + /// Table property controlling refresh; only missing or case-insensitive `"true"` enables it. + enabled_key: &'static str, + /// Table property that must be present for refresh to apply, as in Java, + /// where it decides whether the backend uses vended credentials at all. + required_key: Option<&'static str>, + /// Whether to jitter successful prefetch times like AWS `CachedSupplier`. + jitter_prefetch: bool, + /// Parse a complete credential from catalog-supplied properties. + parse_credential: CredentialParser, + /// For flat seeds, a property whose presence means the table properties + /// carry a seed credential, so failing to parse it is worth a warning. + seed_key: Option<&'static str>, + /// How initial credentials in the table properties are selected. + seed_strategy: SeedStrategy, +} + +impl CloudRefresh { + /// S3 / AWS + const AWS: Self = Self { + schemes: &["s3", "s3a", "s3n"], + endpoint_key: AWS_REFRESH_CREDENTIALS_ENDPOINT, + enabled_key: AWS_REFRESH_CREDENTIALS_ENABLED, + required_key: None, + jitter_prefetch: true, + parse_credential: parse_s3_credential, + seed_key: Some(S3_ACCESS_KEY_ID), + // `s3` also covers `s3a` and `s3n` locations. + seed_strategy: SeedStrategy::Flat { prefixes: &["s3"] }, + }; + /// Google Cloud Storage + const GCP: Self = Self { + schemes: &["gs", "gcs"], + endpoint_key: GCS_REFRESH_CREDENTIALS_ENDPOINT, + enabled_key: GCS_REFRESH_CREDENTIALS_ENABLED, + // Java's GCS client only refreshes a vended OAuth2 token; without + // one it uses Google's default credentials. + required_key: Some(GCS_TOKEN), + jitter_prefetch: false, + parse_credential: parse_gcs_credential, + seed_key: Some(GCS_TOKEN), + seed_strategy: SeedStrategy::Flat { + prefixes: &["gs", "gcs"], + }, + }; + /// Azure Data Lake Storage + const AZURE: Self = Self { + schemes: &["abfs", "abfss", "wasb", "wasbs"], + endpoint_key: ADLS_REFRESH_CREDENTIALS_ENDPOINT, + enabled_key: ADLS_REFRESH_CREDENTIALS_ENABLED, + required_key: None, + jitter_prefetch: false, + parse_credential: parse_azdls_credential, + // Keyed seeds warn as they are parsed. + seed_key: None, + seed_strategy: SeedStrategy::Keyed(KeyedSeedStrategy { + parse_credentials: parse_azdls_account_seeds, + resolve_path: resolve_azdls_seed_path, + }), + }; + + /// Backends with refresh support + const SUPPORTED: &[Self] = &[Self::AWS, Self::GCP, Self::AZURE]; + + fn matches_location(&self, location: &str) -> bool { + self.schemes + .iter() + .any(|scheme| location.eq_ignore_ascii_case(scheme)) + || scheme_of(location).is_some_and(|scheme| self.schemes.contains(&scheme.as_str())) + } +} + +/// Time source for the credential cache, replaced in tests. +pub(crate) trait Clock: Send + Sync { + /// Wall-clock time, against which credential expiries are compared. + fn now(&self) -> SystemTime; + /// Monotonic time, against which failure backoff is measured. + fn instant(&self) -> Instant; +} + +/// The system clock. +pub(crate) struct SystemClock; + +impl Clock for SystemClock { + fn now(&self) -> SystemTime { + SystemTime::now() + } + + fn instant(&self) -> Instant { + Instant::now() + } +} + +/// Re-fetch a credential once it is within this window of expiry, so a fresh +/// token is in hand before the object store would reject the old one. +const REFRESH_BUFFER: Duration = Duration::from_mins(5); + +/// AWS keeps at least one minute between its jittered prefetch time and expiry. +const MIN_REFRESH_BUFFER: Duration = Duration::from_mins(1); + +/// Initial ceiling for failure backoff. Equal jitter chooses from half this +/// value through the full value. +const INITIAL_FAILURE_BACKOFF: Duration = Duration::from_secs(1); + +/// Maximum delay between failed refresh attempts. +const MAX_FAILURE_BACKOFF: Duration = Duration::from_secs(30); + +/// How long a location waits before asking the catalog again after it +/// answered without a credential for it. +const NOT_VENDED_RECHECK: Duration = Duration::from_secs(30); + +/// How long a credentials request, including connecting to the catalog, may +/// take before it counts as a failed refresh. +const FETCH_TIMEOUT: Duration = Duration::from_secs(30); + +/// A cached vended credential and its refresh schedule. +#[derive(Clone)] +struct CachedEntry { + credential: Arc, + /// `None` for a credential that never expires. + expires_at: Option, + /// When this entry becomes eligible for prefetch, or `None` when it never + /// needs refreshing. + refresh_at: Option, +} + +impl CachedEntry { + fn new(vended: VendedCredential, jitter_prefetch: bool, now: SystemTime) -> Self { + let VendedCredential { + credential, + expires_at, + } = vended; + Self { + credential, + expires_at, + refresh_at: expires_at + .map(|expires_at| prefetch_time(now, expires_at, jitter_prefetch)), + } + } + + /// Seed entries are immediately due when they declare no expiry, as Java + /// only uses a complete temporary credential from the table properties, or + /// when they are already inside the nominal five-minute window. Otherwise + /// AWS applies the same jitter as it does to a freshly fetched value. + /// + /// A seed without an expiry is therefore refreshed first, and serves only + /// while refresh fails. + fn seed(vended: VendedCredential, jitter_prefetch: bool, now: SystemTime) -> Self { + let due = vended.expires_at.is_none_or(|expires_at| { + now.checked_add(REFRESH_BUFFER) + .is_none_or(|refresh_boundary| refresh_boundary >= expires_at) + }); + let mut entry = Self::new(vended, jitter_prefetch, now); + if due { + entry.refresh_at = Some(UNIX_EPOCH); + } + entry + } + + fn is_fresh(&self, now: SystemTime) -> bool { + self.refresh_at.is_none_or(|refresh_at| now < refresh_at) + } + + fn is_unexpired(&self, now: SystemTime) -> bool { + self.expires_at.is_none_or(|expires_at| now < expires_at) + } +} + +/// Parsed entries from one successful credentials response. +struct ParsedCredentials { + entries: Vec, + errors: Vec, +} + +struct CredentialError { + prefix: String, + error: Error, +} + +/// Cached credentials plus failure-backoff state. +/// +/// A failed fetch fails for every prefix of the table, so backoff after a +/// failed fetch or an invalid credential is shared by the whole cloud. +struct CacheState { + entries: Vec, + /// Prefixes whose credential in the last successful response was invalid. + /// Paths under them must not use a broader credential: the catalog scoped + /// them more tightly. + failed_prefixes: HashSet, + consecutive_failures: u32, + failure_backoff_until: Option, + /// Why the last refresh failed, reported while refresh is backed off. + last_failure: Option, + /// When to ask again for locations a successful response vended no usable + /// credential for, keyed by the prefix of their expired credential, or the + /// empty string when no credential covers them. These locations do not + /// back off refresh for the others, and a credential the catalog vends for + /// them later is used as soon as any response caches it. + not_vended_until: HashMap, +} + +impl CacheState { + fn new(entries: Vec) -> Self { + Self { + entries, + failed_prefixes: HashSet::new(), + consecutive_failures: 0, + failure_backoff_until: None, + last_failure: None, + not_vended_until: HashMap::new(), + } + } + + /// The cached credential with the longest prefix covering `path`, even if + /// it has expired: the catalog scoped that prefix separately, so a broader + /// credential must not stand in for it. + fn longest_match(&self, path: &str) -> Option<&CachedEntry> { + let selected = StorageCredential::select( + self.entries.iter().map(|entry| entry.credential.as_ref()), + path, + )?; + self.entries + .iter() + .find(|entry| std::ptr::eq(entry.credential.as_ref(), selected)) + } + + fn entry_mut(&mut self, prefix: &str) -> Option<&mut CachedEntry> { + self.entries + .iter_mut() + .find(|entry| entry.credential.prefix() == prefix) + } + + /// Whether a failed prefix covering `path` is narrower than `credential`'s. + fn masks(&self, path: &str, credential: Option<&StorageCredential>) -> bool { + let prefix_len = credential.map(|credential| credential.prefix().len()); + self.failed_prefixes.iter().any(|failed| { + prefix_covers(failed, path) && prefix_len.is_none_or(|len| failed.len() > len) + }) + } + + /// Cache `entry`, replacing any entry with the same prefix, and return its + /// prefix. + fn insert(&mut self, entry: CachedEntry) -> String { + let prefix = entry.credential.prefix().to_owned(); + self.entries + .retain(|cached| cached.credential.prefix() != prefix); + self.entries.push(entry); + prefix + } + + fn record_success(&mut self) { + self.consecutive_failures = 0; + self.failure_backoff_until = None; + self.last_failure = None; + } + + fn record_failure(&mut self, error: &Error, now: Instant) { + self.consecutive_failures = self.consecutive_failures.saturating_add(1); + let backoff = failure_backoff(self.consecutive_failures); + self.failure_backoff_until = now.checked_add(backoff); + self.last_failure = Some(error.to_string()); + // Backends log failed loads only at debug level, as they recur on every + // request, so each failed refresh is reported here. + tracing::warn!( + "failed to refresh vended credentials ({} consecutive failures), \ + retrying in {backoff:?}: {error}", + self.consecutive_failures + ); + } + + /// Replace cached credentials with the fetched ones, prefix by prefix, + /// and record the prefixes whose credential was invalid in this response. + /// + /// An unexpired cached credential survives when the response carries no + /// valid replacement for its prefix, so an absent or malformed entry never + /// evicts a usable credential. Returns the prefixes the response replaced. + fn merge(&mut self, fetched: Vec, errors: &[CredentialError]) -> HashSet { + let fetched_prefixes = fetched + .iter() + .map(|entry| entry.credential.prefix().to_owned()) + .collect::>(); + // A response names every prefix of the table, so a prefix it omits is + // no longer scoped separately: a fetched credential that covers it + // replaces its cached one. A prefix whose credential is invalid keeps + // its cached one. + let failed_prefixes = errors + .iter() + .map(|error| error.prefix.clone()) + .collect::>(); + self.entries.retain(|entry| { + let prefix = entry.credential.prefix(); + failed_prefixes.contains(prefix) + || !fetched + .iter() + .any(|fetched| fetched.credential.covers(prefix)) + }); + self.entries.extend(fetched); + self.failed_prefixes = failed_prefixes; + fetched_prefixes + } +} + +struct ConfiguredCloud { + cloud: &'static CloudRefresh, + endpoint: String, + cache: Mutex, + /// Initial property credentials whose scope cannot be represented by a + /// single leading URI prefix, keyed according to the cloud strategy. + keyed_seeds: HashMap, + /// Only one caller fetches at a time. The cache lock is deliberately + /// separate so other callers can keep using an unexpired credential while + /// the refresh is in flight. + refresh: Mutex<()>, +} + +impl ConfiguredCloud { + fn new( + cloud: &'static CloudRefresh, + endpoint: String, + entries: Vec, + keyed_seeds: HashMap, + ) -> Self { + Self { + cloud, + endpoint, + cache: Mutex::new(CacheState::new(entries)), + keyed_seeds, + refresh: Mutex::new(()), + } + } + + /// Configure `cloud` from the FileIO properties, or `None` when they + /// advertise no enabled refresh endpoint for it. + fn configure( + cloud: &'static CloudRefresh, + base_uri: &str, + props: &HashMap, + now: SystemTime, + ) -> Option { + let enabled = props + .get(cloud.enabled_key) + .is_none_or(|value| value.eq_ignore_ascii_case("true")) + && cloud + .required_key + .is_none_or(|key| props.get(key).is_some_and(|value| !value.is_empty())); + let endpoint = props + .get(cloud.endpoint_key) + .filter(|endpoint| enabled && !endpoint.is_empty()) + .map(|endpoint| resolve_endpoint(base_uri, endpoint))?; + + let mut entries = Vec::new(); + let mut keyed_seeds = HashMap::new(); + match &cloud.seed_strategy { + SeedStrategy::Flat { prefixes } => { + entries.extend(prefixes.iter().filter_map( + |prefix| match (cloud.parse_credential)( + props, + prefix.to_string(), + Expiry::Optional, + ) { + Ok(vended) => Some(CachedEntry::seed(vended, cloud.jitter_prefetch, now)), + Err(error) => { + if cloud.seed_key.is_some_and(|key| props.contains_key(key)) { + warn_unusable_seed(&error); + } + None + } + }, + )); + } + SeedStrategy::Keyed(strategy) => { + keyed_seeds = (strategy.parse_credentials)(props) + .into_iter() + .map(|(key, credential)| { + ( + key, + CachedEntry::seed(credential, cloud.jitter_prefetch, now), + ) + }) + .collect(); + } + } + Some(Self::new(cloud, endpoint, entries, keyed_seeds)) + } + + fn keyed_seed_for_path(&self, path: &str) -> Result> { + let SeedStrategy::Keyed(strategy) = &self.cloud.seed_strategy else { + return Ok(None); + }; + let resolved = (strategy.resolve_path)(path)?; + let Some(seed) = resolved + .keys + .iter() + .find_map(|key| self.keyed_seeds.get(key)) + else { + return Ok(None); + }; + let credential = StorageCredential::new(resolved.scope, seed.credential.config().clone()); + // The scope is normalized, e.g. with a lowercase scheme, so it may not + // cover the path as written; the path then fetches its credential. + Ok(credential.covers(path).then_some(CachedEntry { + credential: Arc::new(credential), + expires_at: seed.expires_at, + refresh_at: seed.refresh_at, + })) + } +} + +/// Serializable recipe for rebuilding a [`RestVendedCredentialProvider`] from +/// the FileIO properties, mirroring how Java rebuilds its provider on workers. +#[derive(Clone, Serialize, Deserialize)] +pub(crate) struct RestVendedCredentialProviderFactory { + /// Catalog URI, used to resolve relative refresh endpoints. + catalog_uri: String, + table: TableIdent, + /// The `rest.auth.type` the catalog resolved, so a rebuilt provider uses + /// the same auth manager even when the merged FileIO properties would + /// infer another one. + auth_type: String, + /// Whether `auth_type` was inferred rather than configured. Like Java, + /// a table `token` then authenticates a catalog without auth. + auth_type_inferred: bool, + /// The auth-related part of the unmerged config returned by the table + /// endpoint, from which the auth manager derives a table session. Keeping + /// it separate prevents local FileIO overrides from masking table auth. + table_auth: HashMap, +} + +/// Table config keys that may override authentication in a table session. +const TABLE_AUTH_KEYS: &[&str] = &["token"]; + +impl RestVendedCredentialProviderFactory { + pub(crate) fn new( + catalog_uri: impl Into, + table: TableIdent, + auth_type: impl Into, + auth_type_inferred: bool, + table_config: &HashMap, + ) -> Self { + Self { + catalog_uri: catalog_uri.into(), + table, + auth_type: auth_type.into(), + auth_type_inferred, + table_auth: table_config + .iter() + .filter(|(key, _)| TABLE_AUTH_KEYS.contains(&key.as_str())) + .map(|(key, value)| (key.clone(), value.clone())) + .collect(), + } + } + + /// The table token that authenticates credential requests of a catalog + /// without auth. Java's credential providers infer OAuth2 from a `token` + /// unless `rest.auth.type` is configured. + fn bearer_table_token(&self) -> Option<&str> { + (self.auth_type == AUTH_TYPE_NONE && self.auth_type_inferred) + .then(|| self.table_auth.get("token").map(String::as_str)) + .flatten() + } + + /// Connect to the catalog from the FileIO properties, as the catalog would. + async fn connect(&self, props: &HashMap) -> Result { + let mut config_props = props.clone(); + config_props.insert( + REST_CATALOG_PROP_AUTH_TYPE.to_string(), + self.auth_type.clone(), + ); + let config = RestCatalogConfig::builder() + .uri(self.catalog_uri.clone()) + .props(config_props) + .build(); + let auth_manager = load_auth_manager(&config)?; + let http_client = HttpClient::new(&config)?; + let catalog_session = auth_manager + .catalog_session(&http_client, &config.auth_props()) + .await?; + table_client( + &http_client, + auth_manager.as_ref(), + catalog_session, + &self.table, + props, + &self.table_auth, + self.bearer_table_token(), + ) + .await + } +} + +impl std::fmt::Debug for RestVendedCredentialProviderFactory { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RestVendedCredentialProviderFactory") + .field("catalog_uri", &self.catalog_uri) + .field("table", &self.table) + .finish_non_exhaustive() + } +} + +#[typetag::serde(name = "RestVendedCredentialProviderFactory")] +impl StorageCredentialProviderFactory for RestVendedCredentialProviderFactory { + fn build(&self, config: &StorageConfig) -> Result> { + let provider = + RestVendedCredentialProvider::configure(self, config.props()).ok_or_else(|| { + Error::new( + ErrorKind::DataInvalid, + "FileIO configuration no longer configures vended credentials", + ) + })?; + Ok(Arc::new(RestVendedCredentialProvider { + factory: Some(self.clone()), + ..provider + })) + } +} + +/// A table-scoped catalog client and the session that authenticates it. +pub(crate) struct TableClient { + http_client: HttpClient, + session: Arc, +} + +impl TableClient { + /// Sends `request`, authenticated by the table session. + async fn query_catalog(&self, request: HttpRequest) -> Result { + self.http_client + .query_catalog(self.session.as_ref(), request) + .await + } +} + +impl std::fmt::Debug for TableClient { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // Sessions may hold secrets. + f.debug_struct("TableClient") + .field("http_client", &self.http_client) + .finish_non_exhaustive() + } +} + +/// Derive the table-scoped client used for credential requests. +/// +/// The auth manager derives the table session from `parent`, unless a +/// `bearer_table_token` authenticates instead. +async fn table_client( + http_client: &HttpClient, + auth_manager: &dyn AuthManager, + parent: Arc, + table: &TableIdent, + props: &HashMap, + table_config: &HashMap, + bearer_table_token: Option<&str>, +) -> Result { + let session = match bearer_table_token { + Some(token) => static_token_session(token), + None => { + auth_manager + .table_session(http_client, table, table_config, parent) + .await? + } + }; + Ok(TableClient { + http_client: http_client.for_table(props)?, + session, + }) +} + +/// Serves vended credentials for a table, refreshing them from the REST +/// catalog's table credentials endpoint. +/// +/// Each cloud cache is seeded with the credentials from the initial +/// table properties (when complete) and re-fetched from its endpoint as they +/// near expiry. +pub(crate) struct RestVendedCredentialProvider { + /// Table-scoped catalog client. Set when the catalog builds the provider, + /// and connected on first refresh after deserialization. + client: OnceCell, + /// Rebuilds this provider in another process. `None` when the catalog + /// authentication cannot be rebuilt from properties. + factory: Option, + /// Effective FileIO properties, which supply catalog connection settings. + props: HashMap, + /// Query parameters sent with every credentials request. + query_params: Vec<(&'static str, String)>, + /// Independently configured endpoint and cache for each backing cloud. + clouds: Vec, + clock: Arc, +} + +impl RestVendedCredentialProvider { + /// Configure a provider without a catalog connection, or `None` when no + /// supported cloud advertises an enabled refresh endpoint. + fn configure( + factory: &RestVendedCredentialProviderFactory, + props: &HashMap, + ) -> Option { + let clock: Arc = Arc::new(SystemClock); + let now = clock.now(); + let clouds = CloudRefresh::SUPPORTED + .iter() + .filter_map(|cloud| ConfiguredCloud::configure(cloud, &factory.catalog_uri, props, now)) + .collect::>(); + (!clouds.is_empty()).then(|| Self { + client: OnceCell::new(), + factory: None, + props: props.clone(), + query_params: credentials_query_params(props), + clouds, + clock, + }) + } + + fn configured_cloud_for_location(&self, location: &str) -> Option<&ConfiguredCloud> { + self.clouds + .iter() + .find(|configured| configured.cloud.matches_location(location)) + } + + async fn client(&self) -> Result<&TableClient> { + self.client + .get_or_try_init(|| async { + let factory = self.factory.as_ref().ok_or_else(|| { + Error::new( + ErrorKind::Unexpected, + "vended credential provider has no catalog connection", + ) + })?; + factory.connect(&self.props).await + }) + .await + } + + /// Fetch fresh credentials from the catalog's credentials endpoint. + async fn fetch(&self, configured: &ConfiguredCloud) -> Result { + let cloud = configured.cloud; + let client = self.client().await?; + let url = credentials_url(&configured.endpoint, &self.query_params)?; + let request = HttpRequest::build(client.http_client.request(Method::GET, url))?; + let response = client.query_catalog(request).await?; + + if !response.status().is_success() { + return Err(unexpected_catalog_error_without_body( + response, + client.http_client.disable_header_redaction(), + )); + } + + // Credential responses contain secrets, and serde's errors quote the + // values they reject, so only the error's category and position are + // reported. + let parsed: LoadCredentialsResponse = + serde_json::from_slice(response.body()).map_err(|error| { + Error::new( + ErrorKind::Unexpected, + format!( + "failed to parse vended credential response: {:?} error at line {}, \ + column {}", + error.classify(), + error.line(), + error.column() + ), + ) + })?; + let now = self.clock.now(); + let mut entries = Vec::new(); + let mut errors = Vec::new(); + for credential in parsed + .storage_credentials + .into_iter() + .filter(|credential| cloud.matches_location(&credential.prefix)) + { + let prefix = credential.prefix; + let parsed = + (cloud.parse_credential)(&credential.config, prefix.clone(), Expiry::Required) + .map(|vended| CachedEntry::new(vended, cloud.jitter_prefetch, now)) + .and_then(|entry| { + if entry.is_unexpired(now) { + Ok(entry) + } else { + Err(Error::new( + ErrorKind::DataInvalid, + "invalid vended credential: credential is already expired", + )) + } + }); + match parsed { + Ok(entry) => entries.push(entry), + Err(error) => errors.push(CredentialError { prefix, error }), + } + } + Ok(ParsedCredentials { entries, errors }) + } + + async fn refresh_credential( + &self, + configured: &ConfiguredCloud, + path: &str, + fallback: Option, + ) -> Result> { + // A stalled catalog must fail the refresh rather than hold the + // single-flight guard, which every caller without a usable credential + // waits on. + let fetched = tokio::time::timeout(FETCH_TIMEOUT, self.fetch(configured)) + .await + .unwrap_or_else(|_| { + Err(Error::new( + ErrorKind::Unexpected, + format!("vended credential request timed out after {FETCH_TIMEOUT:?}"), + )) + }); + let now = self.clock.now(); + let instant = self.clock.instant(); + let mut cache = configured.cache.lock().await; + + let (fetched_prefixes, failure) = match fetched { + Ok(ParsedCredentials { entries, errors }) => { + let fetched_prefixes = cache.merge(entries, &errors); + // The most specific error for `path`. + let failure = errors + .into_iter() + .filter(|error| prefix_covers(&error.prefix, path)) + .max_by_key(|error| error.prefix.len()) + .map(|error| error.error); + (Some(fetched_prefixes), failure) + } + Err(error) => (None, Some(error)), + }; + + let selected = cache + .longest_match(path) + .map(|entry| entry.credential.prefix().to_owned()); + // A keyed seed is only cached once served as the fallback. + let seed = selected + .is_none() + .then(|| fallback.clone().filter(|seed| seed.is_unexpired(now))) + .flatten(); + let candidate = match &selected { + Some(prefix) => cache + .entries + .iter() + .find(|entry| entry.credential.prefix() == prefix) + .map(|entry| entry.credential.clone()), + None => seed.as_ref().map(|seed| seed.credential.clone()), + }; + if cache.masks(path, candidate.as_deref()) { + let error = failure.unwrap_or_else(|| masked_credential_error(path)); + cache.record_failure(&error, instant); + return Err(error); + } + + let prefix = selected.or_else(|| seed.map(|seed| cache.insert(seed))); + let Some(entry) = prefix.as_deref().and_then(|prefix| cache.entry_mut(prefix)) else { + // Keyed like `cache_decision`: by the expired keyed seed it falls + // back to, if any. + let key = fallback + .as_ref() + .map_or("", |fallback| fallback.credential.prefix()); + return Err(not_vended(&mut cache, key, path, failure, instant)); + }; + let refreshed = fetched_prefixes + .as_ref() + .is_some_and(|fetched| fetched.contains(entry.credential.prefix())); + if refreshed { + // A catalog may return the same credential until shortly before + // it expires. Treat one that is no newer like no answer, so the + // checks stay few as expiry approaches. + if let Some(expires_at) = entry.expires_at + && fallback + .as_ref() + .and_then(|previous| previous.expires_at) + .is_some_and(|previous| expires_at <= previous) + { + entry.refresh_at = Some(recheck_time(now, expires_at)); + } + let credential = entry.credential.clone(); + cache.record_success(); + return Ok(credential); + } + if !entry.is_unexpired(now) { + let prefix = entry.credential.prefix().to_owned(); + return Err(not_vended(&mut cache, &prefix, path, failure, instant)); + } + + let credential = entry.credential.clone(); + // A failed fetch always reports its error as the failure. + match failure { + None => { + // The catalog answered without a newer credential for this + // path, for example when it replaced a scheme-wide credential + // with scoped ones. Keep the current credential and check + // again later instead of on every access. + entry.refresh_at = entry + .expires_at + .map(|expires_at| recheck_time(now, expires_at)); + cache.record_success(); + } + // Graceful degradation: while a credential for this path remains + // usable, serve it and retry after jittered backoff. Expired + // credentials are never served. + Some(error) => cache.record_failure(&error, instant), + } + Ok(credential) + } +} + +impl std::fmt::Debug for RestVendedCredentialProvider { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RestVendedCredentialProvider") + .field("configured_clouds", &self.clouds.len()) + .finish_non_exhaustive() + } +} + +enum CacheDecision { + Use(Arc), + Refresh(Option), + /// Refresh is backed off after the failure described, if known. + Backoff(Option), + /// The catalog recently vended no usable credential for the location. + NotVended, +} + +/// The error for a location without a usable credential after a refresh. +/// +/// A failed fetch or an invalid credential for the location backs off refresh +/// for the whole cloud. A successful response that simply vends nothing for +/// it, as for a file outside the table's locations, only delays asking again +/// for this location, keyed by `prefix`. +fn not_vended( + cache: &mut CacheState, + prefix: &str, + path: &str, + failure: Option, + now: Instant, +) -> Error { + match failure { + Some(error) => { + cache.record_failure(&error, now); + error + } + None => { + cache.record_success(); + cache.not_vended_until.retain(|_, until| now < *until); + if let Some(until) = now.checked_add(NOT_VENDED_RECHECK) { + cache.not_vended_until.insert(prefix.to_owned(), until); + } + not_vended_error(path) + } + } +} + +fn not_vended_error(path: &str) -> Error { + Error::new( + ErrorKind::Unexpected, + format!("no unexpired vended credential matches storage location: {path}"), + ) +} + +fn masked_credential_error(path: &str) -> Error { + Error::new( + ErrorKind::DataInvalid, + format!("the catalog vended an invalid credential for storage location: {path}"), + ) +} + +fn refresh_backoff_error(path: &str, last_failure: Option) -> Error { + let error = Error::new( + ErrorKind::Unexpected, + format!("vended credential refresh is temporarily backed off for storage location: {path}"), + ); + match last_failure { + Some(last_failure) => error.with_context("last_failure", last_failure), + None => error, + } +} + +async fn cache_decision( + configured: &ConfiguredCloud, + path: &str, + clock: &dyn Clock, +) -> Result { + let keyed_seed = configured.keyed_seed_for_path(path)?; + let cache = configured.cache.lock().await; + let now = clock.now(); + let instant = clock.instant(); + let current = cache + .longest_match(path) + .cloned() + .or(keyed_seed) + .filter(|entry| !cache.masks(path, Some(&*entry.credential))); + + if let Some(entry) = current.as_ref().filter(|entry| entry.is_fresh(now)) { + return Ok(CacheDecision::Use(entry.credential.clone())); + } + + if cache + .failure_backoff_until + .is_some_and(|retry_at| instant < retry_at) + { + return Ok(current + .filter(|entry| entry.is_unexpired(now)) + .map(|entry| CacheDecision::Use(entry.credential)) + .unwrap_or_else(|| CacheDecision::Backoff(cache.last_failure.clone()))); + } + + // A masked path reports its invalid credential when refreshed. + if current + .as_ref() + .is_none_or(|entry| !entry.is_unexpired(now)) + && !cache.masks(path, None) + { + let prefix = current + .as_ref() + .map_or("", |entry| entry.credential.prefix()); + if cache + .not_vended_until + .get(prefix) + .is_some_and(|until| instant < *until) + { + return Ok(CacheDecision::NotVended); + } + } + + Ok(CacheDecision::Refresh(current)) +} + +#[async_trait] +impl StorageCredentialProvider for RestVendedCredentialProvider { + fn supports_path(&self, path: &str) -> bool { + self.configured_cloud_for_location(path).is_some() + } + + async fn load_credential(&self, path: &str) -> Result> { + let configured = self.configured_cloud_for_location(path).ok_or_else(|| { + Error::new( + ErrorKind::FeatureUnsupported, + format!("vended credentials are not configured for storage location: {path}"), + ) + })?; + + let current = match cache_decision(configured, path, self.clock.as_ref()).await? { + CacheDecision::Use(credential) => return Ok(credential), + CacheDecision::Refresh(current) => current, + CacheDecision::Backoff(last_failure) => { + return Err(refresh_backoff_error(path, last_failure)); + } + CacheDecision::NotVended => return Err(not_vended_error(path)), + }; + + // One caller refreshes, while concurrent callers immediately keep using the + // unexpired cached credential. With no usable credential, callers wait + // for the in-flight refresh instead. + let usable = current + .as_ref() + .filter(|entry| entry.is_unexpired(self.clock.now())); + let _refresh_guard = if let Some(entry) = usable { + match configured.refresh.try_lock() { + Ok(guard) => guard, + Err(_) => return Ok(entry.credential.clone()), + } + } else { + configured.refresh.lock().await + }; + + // Another caller may have completed a refresh between our cache check + // and acquiring the single-flight guard. + let current = match cache_decision(configured, path, self.clock.as_ref()).await? { + CacheDecision::Use(credential) => return Ok(credential), + CacheDecision::Refresh(current) => current, + CacheDecision::Backoff(last_failure) => { + return Err(refresh_backoff_error(path, last_failure)); + } + CacheDecision::NotVended => return Err(not_vended_error(path)), + }; + + self.refresh_credential(configured, path, current).await + } + + fn factory(&self) -> Result> { + match &self.factory { + Some(factory) => Ok(Arc::new(factory.clone())), + None => Err(Error::new( + ErrorKind::FeatureUnsupported, + "the vended credential provider cannot be serialized because the REST catalog \ + uses an injected AuthManager, which cannot be rebuilt in another process", + )), + } + } +} + +/// Compute the prefetch time of a credential obtained at `now`. +/// +/// Like Java, a credential is refreshed [`REFRESH_BUFFER`] before it expires. +/// Unlike Java, the buffer is capped at half the remaining lifetime: a +/// credential vended with a shorter lifetime would otherwise be due on +/// arrival, and every file operation would fetch again. +fn prefetch_time(now: SystemTime, expires_at: SystemTime, jitter: bool) -> SystemTime { + let lifetime = expires_at.duration_since(now).unwrap_or_default(); + let buffer = REFRESH_BUFFER.min(lifetime / 2); + let base = expires_at.checked_sub(buffer).unwrap_or(UNIX_EPOCH); + if !jitter { + return base; + } + + // The minimum distance from expiry shrinks with a capped buffer. + let min_buffer = + buffer.mul_f64(MIN_REFRESH_BUFFER.as_secs_f64() / REFRESH_BUFFER.as_secs_f64()); + let jitter_millis = buffer.saturating_sub(min_buffer).as_millis() as u64; + if jitter_millis == 0 { + return base; + } + base.checked_add(Duration::from_millis( + rand::rng().random_range(0..jitter_millis), + )) + .unwrap_or(base) +} + +/// When to ask the catalog again for a newer credential after it answered +/// that none exists: at the regular prefetch time, which is halfway to expiry +/// within ten minutes of it, or not at all once less than twice +/// [`MIN_REFRESH_BUFFER`] remains, so the checks stay few as expiry approaches. +fn recheck_time(now: SystemTime, expires_at: SystemTime) -> SystemTime { + let remaining = expires_at.duration_since(now).unwrap_or_default(); + if remaining <= MIN_REFRESH_BUFFER * 2 { + expires_at + } else { + prefetch_time(now, expires_at, false) + } +} + +/// Equal-jitter exponential backoff. The random lower half avoids both hot +/// retry loops and synchronized retries across clients. +fn failure_backoff(consecutive_failures: u32) -> Duration { + let exponent = consecutive_failures.saturating_sub(1).min(5); + let ceiling = INITIAL_FAILURE_BACKOFF + .checked_mul(1 << exponent) + .unwrap_or(MAX_FAILURE_BACKOFF) + .min(MAX_FAILURE_BACKOFF); + let ceiling_millis = ceiling.as_millis() as u64; + let floor_millis = ceiling_millis / 2; + Duration::from_millis(rand::rng().random_range(floor_millis..=ceiling_millis)) +} + +/// Build a credential provider for a table, or `None` when no supported cloud +/// advertises an enabled refresh endpoint. +/// +/// `parent_session` derives the contextual session of the operation loading +/// the table, from which `auth_manager` derives a table session when the table +/// config overrides authentication. It is only called when a provider is +/// built, so a table without refreshable credentials makes no auth calls. +/// `props` contains the effective FileIO properties after applying local +/// overrides, and therefore supplies headers and client policy. `portable` +/// states whether the catalog authentication can be rebuilt from `props` in +/// another process, which makes the provider serializable. +pub(crate) async fn build_vended_credential_provider( + http_client: &HttpClient, + auth_manager: &dyn AuthManager, + parent_session: impl AsyncFnOnce() -> Result>, + factory: RestVendedCredentialProviderFactory, + props: &HashMap, + table_config: &HashMap, + portable: bool, +) -> Result>> { + let Some(provider) = RestVendedCredentialProvider::configure(&factory, props) else { + return Ok(None); + }; + + // An injected auth manager decides on table sessions itself, given the + // whole table config. + let client = table_client( + http_client, + auth_manager, + parent_session().await?, + &factory.table, + props, + table_config, + portable.then(|| factory.bearer_table_token()).flatten(), + ) + .await?; + Ok(Some(Arc::new(RestVendedCredentialProvider { + client: OnceCell::new_with(Some(client)), + factory: portable.then_some(factory), + ..provider + }))) +} + +/// The `referenced-by` query parameter. Its value is already percent-encoded. +const REFERENCED_BY_QUERY_PARAMETER: &str = "referenced-by"; + +/// Query parameters for credentials requests, like Java's +/// `RESTUtil.credentialsQueryParams`. +fn credentials_query_params(props: &HashMap) -> Vec<(&'static str, String)> { + [ + (REST_CATALOG_PROP_SCAN_PLAN_ID, "planId"), + ( + REST_CATALOG_PROP_REFERENCED_BY, + REFERENCED_BY_QUERY_PARAMETER, + ), + ] + .into_iter() + .filter_map(|(property, parameter)| props.get(property).map(|value| (parameter, value.clone()))) + .collect() +} + +/// The credentials request URL. Like Java's `HTTPRequest.requestUri`, the +/// already encoded `referenced-by` value is appended verbatim instead of being +/// encoded again. +fn credentials_url(endpoint: &str, query_params: &[(&str, String)]) -> Result { + let mut url = Url::parse(endpoint).map_err(|error| { + Error::new( + ErrorKind::DataInvalid, + format!("invalid credentials endpoint: {endpoint}"), + ) + .with_source(error) + })?; + for (parameter, value) in query_params { + if *parameter != REFERENCED_BY_QUERY_PARAMETER { + url.query_pairs_mut().append_pair(parameter, value); + } + } + if let Some((_, referenced_by)) = query_params + .iter() + .find(|(parameter, _)| *parameter == REFERENCED_BY_QUERY_PARAMETER) + { + let query = match url.query() { + Some(query) => format!("{query}&{REFERENCED_BY_QUERY_PARAMETER}={referenced_by}"), + None => format!("{REFERENCED_BY_QUERY_PARAMETER}={referenced_by}"), + }; + url.set_query(Some(&query)); + } + Ok(url) +} + +/// Resolve a possibly-relative refresh endpoint against the catalog base URI. +/// +/// Absolute endpoints are used as-is and receive the catalog credentials, as +/// in Java. The catalog is trusted to advertise only its own endpoints. +fn resolve_endpoint(base_uri: &str, endpoint: &str) -> String { + if endpoint.starts_with("http://") || endpoint.starts_with("https://") { + return endpoint.to_string(); + } + + let base = base_uri.trim_end_matches('/'); + let separator = if endpoint.starts_with('/') { "" } else { "/" }; + format!("{base}{separator}{endpoint}") +} + +/// Whether the credential `prefix` covers `location`, as in +/// [`StorageCredential::covers`]. +fn prefix_covers(prefix: &str, location: &str) -> bool { + !prefix.is_empty() && location.starts_with(prefix) +} + +/// The URL scheme of `location`, lowercased (e.g. `"s3"` for `s3://bucket/k`). +fn scheme_of(location: &str) -> Option { + Url::parse(location) + .ok() + .map(|url| url.scheme().to_string()) +} + +/// Parse a complete S3 credential supplied by the catalog. +fn parse_s3_credential( + config: &HashMap, + prefix: String, + expiry: Expiry, +) -> Result { + let mut credential_config = copy_required(config, &[S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY])?; + // Temporary credentials carry a session token; static keys do not. + copy_expiring(config, &mut credential_config, S3_SESSION_TOKEN, expiry)?; + let expires_at = copy_expiring( + config, + &mut credential_config, + S3_SESSION_TOKEN_EXPIRES_AT_MS, + expiry, + )? + .map(|_| required_epoch_millis(config, S3_SESSION_TOKEN_EXPIRES_AT_MS)) + .transpose()?; + Ok(VendedCredential { + expires_at, + credential: Arc::new(StorageCredential::new(prefix, credential_config)), + }) +} + +/// Parse a complete GCS credential supplied by the catalog. +fn parse_gcs_credential( + config: &HashMap, + prefix: String, + expiry: Expiry, +) -> Result { + let mut credential_config = copy_required(config, &[GCS_TOKEN])?; + let expires_at = copy_expiring(config, &mut credential_config, GCS_TOKEN_EXPIRES_AT, expiry)? + .map(|_| required_epoch_millis(config, GCS_TOKEN_EXPIRES_AT)) + .transpose()?; + Ok(VendedCredential { + expires_at, + credential: Arc::new(StorageCredential::new(prefix, credential_config)), + }) +} + +/// Copy `key` into `credential_config`, returning its value. The key must be +/// present when `expiry` is [`Expiry::Required`]. +fn copy_expiring( + config: &HashMap, + credential_config: &mut HashMap, + key: &str, + expiry: Expiry, +) -> Result> { + let value = match expiry { + Expiry::Required => Some(required_nonempty(config, key)?), + Expiry::Optional => config.get(key).filter(|value| !value.is_empty()).cloned(), + }; + if let Some(value) = &value { + credential_config.insert(key.to_string(), value.clone()); + } + Ok(value) +} + +/// Warn that an initial credential in the table properties cannot be used, so +/// that the request the first access sends to the catalog has an explanation. +fn warn_unusable_seed(error: &Error) { + tracing::warn!( + "ignoring the vended credential in the table properties, which will be fetched \ + from the catalog instead: {error}" + ); +} + +/// The non-empty values of `keys` in `config`, which must all be present. +fn copy_required( + config: &HashMap, + keys: &[&str], +) -> Result> { + keys.iter() + .map(|key| Ok((key.to_string(), required_nonempty(config, key)?))) + .collect() +} + +/// Parse a complete account-specific ADLS SAS credential supplied by the catalog. +fn parse_azdls_credential( + config: &HashMap, + prefix: String, + expiry: Expiry, +) -> Result { + let location = AzdlsLocation::parse(&prefix)?; + let (suffix, sas_token) = location + .token_keys() + .into_iter() + .find_map(|key| azdls_sas_tokens(config).find(|(suffix, _)| *suffix == key)) + .ok_or_else(|| { + Error::new( + ErrorKind::DataInvalid, + format!( + "invalid vended credential: no {ADLS_SAS_TOKEN_PREFIX}* token for {}", + location.host + ), + ) + })?; + azdls_vended_credential(config, prefix, suffix, sas_token, expiry) +} + +/// The vended credential for the SAS token under `suffix`, which must have an +/// expiry under the same suffix. +fn azdls_vended_credential( + config: &HashMap, + prefix: String, + suffix: &str, + sas_token: &str, + expiry: Expiry, +) -> Result { + let expiry_key = format!("{ADLS_SAS_TOKEN_EXPIRES_AT_MS_PREFIX}{suffix}"); + let mut credential_config = HashMap::from([( + format!("{ADLS_SAS_TOKEN_PREFIX}{suffix}"), + sas_token.to_string(), + )]); + let expires_at = copy_expiring(config, &mut credential_config, &expiry_key, expiry)? + .map(|_| required_epoch_millis(config, &expiry_key)) + .transpose()?; + Ok(VendedCredential { + credential: Arc::new(StorageCredential::new(prefix, credential_config)), + expires_at, + }) +} + +/// Parse every complete account-specific ADLS credential from the initial +/// table properties, keyed by their key suffix. Unlike a URI prefix, the host +/// of an Azure location occurs after the filesystem, so these seeds are +/// selected by host, or by account for keys that name only one. Their prefix +/// is set once a location selects them. +fn parse_azdls_account_seeds( + config: &HashMap, +) -> HashMap { + azdls_sas_tokens(config) + .filter_map(|(suffix, token)| { + match azdls_vended_credential(config, String::new(), suffix, token, Expiry::Optional) { + Ok(vended) => Some((suffix.to_string(), vended)), + Err(error) => { + warn_unusable_seed(&error); + None + } + } + }) + .collect() +} + +/// Account-specific SAS tokens as `(key suffix, token)`. A suffix names a host +/// such as `account.dfs.core.windows.net`, as in Java, or only the account. +fn azdls_sas_tokens(config: &HashMap) -> impl Iterator { + config.iter().filter_map(|(key, token)| { + let suffix = key.strip_prefix(ADLS_SAS_TOKEN_PREFIX)?; + (!suffix.is_empty() && !token.is_empty()).then_some((suffix, token.as_str())) + }) +} + +fn resolve_azdls_seed_path(location: &str) -> Result { + let location = AzdlsLocation::parse(location)?; + let keys = location.token_keys(); + let mut url = location.url; + // Without a trailing slash, the scope also covers the container root. + url.set_path(""); + url.set_query(None); + url.set_fragment(None); + Ok(KeyedSeedPath { + keys, + scope: url.to_string(), + }) +} + +/// An ADLS location, with the host and account that select its SAS token. +struct AzdlsLocation { + url: Url, + /// Host, e.g. `account.dfs.core.windows.net`. + host: String, + /// Storage account. + account: String, +} + +impl AzdlsLocation { + fn parse(location: &str) -> Result { + let url = Url::parse(location).map_err(|error| { + Error::new( + ErrorKind::DataInvalid, + format!("invalid ADLS storage location: {location}"), + ) + .with_source(error) + })?; + if !CloudRefresh::AZURE.schemes.contains(&url.scheme()) { + return Err(Error::new( + ErrorKind::DataInvalid, + format!("invalid ADLS storage location scheme: {}", url.scheme()), + )); + } + let host = url.host_str().unwrap_or_default().to_string(); + let account = host + .split('.') + .next() + .filter(|account| !account.is_empty()) + .map(str::to_owned) + .ok_or_else(|| { + Error::new( + ErrorKind::DataInvalid, + format!("ADLS storage location has no account name: {location}"), + ) + })?; + Ok(Self { url, host, account }) + } + + /// SAS token key suffixes for this location, most specific first: the + /// exact host, as in Java, then the account alone, as sent for older Java + /// versions and PyIceberg. A key that names only the account matches every + /// host of an account with that name, including one in another cloud; a + /// host-keyed token matches only its host. + fn token_keys(&self) -> Vec { + vec![self.host.clone(), self.account.clone()] + } +} + +fn required_nonempty(config: &HashMap, key: &str) -> Result { + config + .get(key) + .filter(|value| !value.is_empty()) + .cloned() + .ok_or_else(|| { + Error::new( + ErrorKind::DataInvalid, + format!("invalid vended credential: {key} is missing or empty"), + ) + }) +} + +fn required_epoch_millis(config: &HashMap, key: &str) -> Result { + let value = required_nonempty(config, key)?; + parse_epoch_millis(&value).ok_or_else(|| { + Error::new( + ErrorKind::DataInvalid, + format!("invalid vended credential: {key} is not a valid epoch-millisecond timestamp"), + ) + }) +} + +/// Parse an epoch-millisecond timestamp into a [`SystemTime`]. +fn parse_epoch_millis(millis: &str) -> Option { + millis + .parse() + .ok() + .and_then(|millis| UNIX_EPOCH.checked_add(Duration::from_millis(millis))) +} + +#[cfg(test)] +mod tests { + use std::sync::{Barrier, mpsc}; + + use mockito::{Matcher, Server}; + + use super::*; + use crate::auth::{ + AUTH_TYPE_NONE, AUTH_TYPE_OAUTH2, NoopAuthManager, NoopSession, OAuth2Manager, + }; + + fn epoch_millis(time: SystemTime) -> String { + time.duration_since(UNIX_EPOCH) + .unwrap() + .as_millis() + .to_string() + } + + fn s3_vended(prefix: &str, access_key_id: &str, expires_at: SystemTime) -> VendedCredential { + VendedCredential { + credential: Arc::new(StorageCredential::new( + prefix, + HashMap::from([ + (S3_ACCESS_KEY_ID.to_string(), access_key_id.to_string()), + (S3_SECRET_ACCESS_KEY.to_string(), "secret".to_string()), + ]), + )), + expires_at: Some(expires_at), + } + } + + fn s3_access_key_id(credential: &StorageCredential) -> &str { + credential + .config() + .get(S3_ACCESS_KEY_ID) + .expect("an S3 credential") + } + + fn gcs_token(credential: &StorageCredential) -> &str { + credential + .config() + .get(GCS_TOKEN) + .expect("a GCS credential") + } + + fn sas_token(credential: &StorageCredential) -> &str { + credential + .config() + .iter() + .find(|(key, _)| key.starts_with(ADLS_SAS_TOKEN_PREFIX)) + .map(|(_, token)| token.as_str()) + .expect("an ADLS credential") + } + + /// A previously cached entry: like a seed, its age is unknown, so it is due + /// once inside the nominal refresh window. + fn cached_s3(prefix: &str, access_key_id: &str, expires_at: SystemTime) -> CachedEntry { + CachedEntry::seed( + s3_vended(prefix, access_key_id, expires_at), + false, + SystemTime::now(), + ) + } + + /// A table client for `base_uri` without authentication. + fn test_table_client(base_uri: &str) -> TableClient { + TableClient { + http_client: test_client(base_uri), + session: Arc::new(NoopSession), + } + } + + fn test_client(base_uri: &str) -> HttpClient { + let config = RestCatalogConfig::builder() + .uri(base_uri.to_string()) + .build(); + HttpClient::new(&config).unwrap() + } + + fn test_factory( + base_uri: &str, + table_config: Option<&HashMap>, + ) -> RestVendedCredentialProviderFactory { + RestVendedCredentialProviderFactory::new( + base_uri, + test_table(), + AUTH_TYPE_OAUTH2, + true, + &table_config.cloned().unwrap_or_default(), + ) + } + + /// A provider whose AWS cache starts with `entries`. + fn provider_with_cached_s3( + base_uri: &str, + entries: Vec, + ) -> RestVendedCredentialProvider { + RestVendedCredentialProvider { + client: OnceCell::new_with(Some(test_table_client(base_uri))), + factory: None, + props: HashMap::new(), + query_params: Vec::new(), + clouds: vec![ConfiguredCloud::new( + &CloudRefresh::AWS, + format!("{base_uri}/v1/credentials"), + entries, + HashMap::new(), + )], + clock: Arc::new(SystemClock), + } + } + + fn aws_refresh_props(endpoint: &str) -> HashMap { + HashMap::from([( + CloudRefresh::AWS.endpoint_key.to_string(), + endpoint.to_string(), + )]) + } + + fn with_s3_seed( + mut props: HashMap, + access_key_id: &str, + expires_at: SystemTime, + ) -> HashMap { + props.extend([ + (S3_ACCESS_KEY_ID.to_string(), access_key_id.to_string()), + (S3_SECRET_ACCESS_KEY.to_string(), "SEED_SK".to_string()), + (S3_SESSION_TOKEN.to_string(), "SEED_TOK".to_string()), + ( + S3_SESSION_TOKEN_EXPIRES_AT_MS.to_string(), + epoch_millis(expires_at), + ), + ]); + props + } + + fn test_table() -> TableIdent { + TableIdent::from_strs(["namespace", "table"]).unwrap() + } + + async fn build_test_provider( + client: HttpClient, + base_uri: &str, + props: &HashMap, + table_auth_props: Option<&HashMap>, + ) -> Result>> { + build_vended_credential_provider( + &client, + &NoopAuthManager, + async || Ok(Arc::new(NoopSession) as Arc), + test_factory(base_uri, table_auth_props), + props, + table_auth_props.unwrap_or(&HashMap::new()), + true, + ) + .await + } + + async fn test_provider( + base_uri: &str, + props: &HashMap, + ) -> Arc { + build_test_provider(test_client(base_uri), base_uri, props, None) + .await + .expect("provider construction should succeed") + .expect("provider should be built") + } + + fn s3_response(prefix: &str, access_key_id: &str, expires_at: SystemTime) -> String { + let expires_at = epoch_millis(expires_at); + format!( + r#"{{"storage-credentials":[{{"prefix":"{prefix}","config":{{"s3.access-key-id":"{access_key_id}","s3.secret-access-key":"SK","s3.session-token":"TOK","s3.session-token-expires-at-ms":"{expires_at}"}}}}]}}"# + ) + } + + #[test] + fn resolve_endpoint_matches_java_semantics() { + assert_eq!( + resolve_endpoint("https://catalog/", "https://other/creds"), + "https://other/creds" + ); + assert_eq!( + resolve_endpoint("https://catalog", "http://other/creds"), + "http://other/creds" + ); + assert_eq!( + resolve_endpoint("https://catalog", "v1/creds"), + "https://catalog/v1/creds" + ); + assert_eq!( + resolve_endpoint("https://catalog/", "v1/creds"), + "https://catalog/v1/creds" + ); + // All trailing slashes stripped from the base (Java stripTrailingSlash). + assert_eq!( + resolve_endpoint("https://catalog///", "/v1/creds"), + "https://catalog/v1/creds" + ); + // Existing leading slashes on the endpoint are preserved, not collapsed + // (matches Java's resolveEndpoint, which only prepends when absent). + assert_eq!( + resolve_endpoint("https://catalog/", "//v1/creds"), + "https://catalog//v1/creds" + ); + } + + #[test] + fn cloud_selection_accepts_root_prefixes_and_url_schemes() { + let supported = |location: &str| { + CloudRefresh::SUPPORTED + .iter() + .any(|cloud| cloud.matches_location(location)) + }; + // Java uses these root prefixes for its fallback clients and accepts + // credentials scoped directly to them. + assert!(supported("s3")); + assert!(supported("gs")); + assert!(supported("s3://b/k")); + assert!(supported("S3://b/k")); + assert!(supported("s3a://b/k")); + assert!(supported("s3n://b/k")); + assert!(supported("gs://b/k")); + assert!(supported("gcs://b/k")); + assert!(supported("abfs")); + assert!(supported("abfss://fs@acct.dfs.core.windows.net/k")); + assert!(supported("wasb://fs@acct.blob.core.windows.net/k")); + assert!(supported("wasbs://fs@acct.blob.core.windows.net/k")); + assert!(!supported("not a url")); + assert!(CloudRefresh::AWS.matches_location("s3://bucket/path")); + assert!(!CloudRefresh::AWS.matches_location("s3evil://bucket/path")); + } + + #[test] + fn parses_s3_credential() { + let prefix = || "s3://bucket".to_string(); + let mut config = HashMap::new(); + assert!(parse_s3_credential(&config, prefix(), Expiry::Required).is_err()); + config.insert(S3_ACCESS_KEY_ID.to_string(), "AK".to_string()); + assert!(parse_s3_credential(&config, prefix(), Expiry::Required).is_err()); + config.insert(S3_SECRET_ACCESS_KEY.to_string(), "SK".to_string()); + assert!(parse_s3_credential(&config, prefix(), Expiry::Required).is_err()); + config.insert(S3_SESSION_TOKEN.to_string(), "TOK".to_string()); + config.insert( + S3_SESSION_TOKEN_EXPIRES_AT_MS.to_string(), + "not-a-timestamp".to_string(), + ); + assert!(parse_s3_credential(&config, prefix(), Expiry::Required).is_err()); + + config.insert( + S3_SESSION_TOKEN_EXPIRES_AT_MS.to_string(), + "1500".to_string(), + ); + config.insert("unrelated".to_string(), "value".to_string()); + let vended = parse_s3_credential(&config, prefix(), Expiry::Required).unwrap(); + assert_eq!(vended.credential.prefix(), "s3://bucket"); + assert_eq!( + vended.expires_at, + Some(UNIX_EPOCH + Duration::from_millis(1500)) + ); + // Only the credential's own properties are kept. + config.remove("unrelated"); + assert_eq!(vended.credential.config(), &config); + } + + #[test] + fn parse_gcs_requires_token_and_expiry() { + let prefix = || "gs://bucket".to_string(); + let mut config = HashMap::new(); + assert!(parse_gcs_credential(&config, prefix(), Expiry::Required).is_err()); + config.insert(GCS_TOKEN.to_string(), "ya29.token".to_string()); + assert!(parse_gcs_credential(&config, prefix(), Expiry::Required).is_err()); + + config.insert(GCS_TOKEN_EXPIRES_AT.to_string(), "2000".to_string()); + let vended = parse_gcs_credential(&config, prefix(), Expiry::Required).unwrap(); + assert_eq!(vended.credential.prefix(), "gs://bucket"); + assert_eq!(gcs_token(&vended.credential), "ya29.token"); + assert_eq!( + vended.expires_at, + Some(UNIX_EPOCH + Duration::from_millis(2000)) + ); + } + + #[test] + fn parse_azdls_requires_account_specific_token_and_expiry() { + let prefix = "abfss://container@account1.dfs.core.windows.net/table"; + let token_key = format!("{ADLS_SAS_TOKEN_PREFIX}account1"); + let expiry_key = format!("{ADLS_SAS_TOKEN_EXPIRES_AT_MS_PREFIX}account1"); + let mut config = HashMap::new(); + + assert!(parse_azdls_credential(&config, prefix.to_string(), Expiry::Required).is_err()); + config.insert(token_key, "sv=2026&sig=secret".to_string()); + assert!(parse_azdls_credential(&config, prefix.to_string(), Expiry::Required).is_err()); + config.insert(expiry_key, "2500".to_string()); + + let vended = parse_azdls_credential(&config, prefix.to_string(), Expiry::Required).unwrap(); + assert_eq!(vended.credential.prefix(), prefix); + assert_eq!( + vended.expires_at, + Some(UNIX_EPOCH + Duration::from_millis(2500)) + ); + assert_eq!(sas_token(&vended.credential), "sv=2026&sig=secret"); + assert_eq!(vended.credential.config(), &config); + } + + #[test] + fn azdls_tokens_match_the_exact_host_or_the_account() { + let expires = epoch_millis(SystemTime::now() + Duration::from_secs(3600)); + let config = HashMap::from([ + ( + format!("{ADLS_SAS_TOKEN_PREFIX}acct.dfs.core.windows.net"), + "host".to_string(), + ), + ( + format!("{ADLS_SAS_TOKEN_EXPIRES_AT_MS_PREFIX}acct.dfs.core.windows.net"), + expires.clone(), + ), + ]); + let token = |prefix: &str, config: &HashMap| { + parse_azdls_credential(config, prefix.to_string(), Expiry::Required) + .map(|vended| sas_token(&vended.credential).to_string()) + }; + + assert_eq!( + token("abfss://c@acct.dfs.core.windows.net/t", &config).unwrap(), + "host" + ); + // The same account name in another cloud is a different account. + assert!(token("abfss://c@acct.dfs.core.usgovcloudapi.net/t", &config).is_err()); + + // A key naming only the account matches any host of it, after the + // exact host. + let mut config = config; + config.extend([ + ( + format!("{ADLS_SAS_TOKEN_PREFIX}acct"), + "account".to_string(), + ), + ( + format!("{ADLS_SAS_TOKEN_EXPIRES_AT_MS_PREFIX}acct"), + expires, + ), + ]); + assert_eq!( + token("abfss://c@acct.dfs.core.windows.net/t", &config).unwrap(), + "host" + ); + assert_eq!( + token("abfss://c@acct.dfs.core.usgovcloudapi.net/t", &config).unwrap(), + "account" + ); + } + + #[test] + fn cached_entry_freshness() { + let far = cached_s3( + "s3", + "a", + SystemTime::now() + REFRESH_BUFFER + Duration::from_secs(60), + ); + // Within the buffer but not yet expired: stale for a fast-path read, but + // still usable for graceful degradation. + let soon = cached_s3("s3", "a", SystemTime::now() + Duration::from_secs(60)); + let past = cached_s3("s3", "a", SystemTime::now() - Duration::from_secs(60)); + + let now = SystemTime::now(); + assert!(far.is_fresh(now)); + assert!(!soon.is_fresh(now)); + assert!(soon.is_unexpired(now)); + assert!(!past.is_unexpired(now)); + } + + #[test] + fn prefetch_time_matches_cloud_policy() { + let now = SystemTime::now(); + let expires_at = now + Duration::from_secs(3600); + assert_eq!( + prefetch_time(now, expires_at, false), + expires_at - REFRESH_BUFFER + ); + + for _ in 0..16 { + let refresh_at = prefetch_time(now, expires_at, true); + assert!(refresh_at >= expires_at - REFRESH_BUFFER); + assert!(refresh_at < expires_at - MIN_REFRESH_BUFFER); + } + } + + #[test] + fn prefetch_buffer_is_capped_at_half_the_lifetime() { + let now = SystemTime::now(); + let expires_at = now + Duration::from_secs(120); + assert_eq!( + prefetch_time(now, expires_at, false), + now + Duration::from_secs(60) + ); + + for _ in 0..16 { + let refresh_at = prefetch_time(now, expires_at, true); + assert!(refresh_at >= now + Duration::from_secs(60)); + assert!(refresh_at < expires_at - Duration::from_secs(12)); + } + + // An already expired credential is due immediately. + assert_eq!(prefetch_time(now, now, true), now); + } + + #[test] + fn seed_inside_nominal_window_is_immediately_due() { + let credential = s3_vended( + "s3", + "a", + SystemTime::now() + REFRESH_BUFFER - Duration::from_secs(1), + ); + let entry = CachedEntry::seed(credential, true, SystemTime::now()); + let now = SystemTime::now(); + assert!(!entry.is_fresh(now)); + assert!(entry.is_unexpired(now)); + } + + #[test] + fn failure_backoff_is_jittered_and_capped() { + for (failures, ceiling) in [ + (1, Duration::from_secs(1)), + (2, Duration::from_secs(2)), + (5, Duration::from_secs(16)), + (6, MAX_FAILURE_BACKOFF), + (u32::MAX, MAX_FAILURE_BACKOFF), + ] { + for _ in 0..16 { + let backoff = failure_backoff(failures); + assert!(backoff >= ceiling / 2); + assert!(backoff <= ceiling); + } + } + } + + #[test] + fn longest_match_selects_the_longest_prefix_even_when_expired() { + let now = SystemTime::now(); + let far = now + REFRESH_BUFFER + Duration::from_secs(3600); + let cache = CacheState::new(vec![ + cached_s3("s3://bucket", "wide", far), + cached_s3("s3://bucket/warehouse/db", "narrow", far), + ]); + let got = cache.longest_match("s3://bucket/warehouse/db/t/f").unwrap(); + assert_eq!(s3_access_key_id(&got.credential), "narrow"); + assert!(cache.longest_match("s3://other/x").is_none()); + + // An expired narrower credential is still selected, so it is refreshed + // instead of being replaced by the broader one. + let cache = CacheState::new(vec![ + cached_s3("s3://bucket", "wide", far), + cached_s3( + "s3://bucket/table", + "expired", + now - Duration::from_secs(60), + ), + ]); + let expired = cache.longest_match("s3://bucket/table/f").unwrap(); + assert_eq!(s3_access_key_id(&expired.credential), "expired"); + assert!(!expired.is_unexpired(now)); + } + + #[tokio::test] + async fn provider_support_tracks_configured_cloud_endpoints() { + let client = test_client("http://cat"); + let props = aws_refresh_props("/v1/creds"); + + // The provider is configured independently of the table metadata scheme, + // but advertises support only for clouds whose endpoint is present. + let provider = build_test_provider(client.clone(), "http://cat", &props, None) + .await + .unwrap() + .unwrap(); + assert!(provider.supports_path("s3://b/k")); + assert!(!provider.supports_path("abfss://fs@acct.dfs.core.windows.net/k")); + let enabled = HashMap::from([ + ( + CloudRefresh::AWS.endpoint_key.to_string(), + "/v1/creds".to_string(), + ), + ( + CloudRefresh::AWS.enabled_key.to_string(), + "True".to_string(), + ), + ]); + assert!( + build_test_provider(client.clone(), "http://cat", &enabled, None) + .await + .unwrap() + .is_some() + ); + // No endpoint advertised. + assert!( + build_test_provider(client.clone(), "http://cat", &HashMap::new(), None) + .await + .unwrap() + .is_none() + ); + // Explicitly disabled. + let disabled = HashMap::from([ + ( + CloudRefresh::AWS.endpoint_key.to_string(), + "/v1/creds".to_string(), + ), + ( + CloudRefresh::AWS.enabled_key.to_string(), + "false".to_string(), + ), + ]); + assert!( + build_test_provider(client, "http://cat", &disabled, None) + .await + .unwrap() + .is_none() + ); + // Java's `Strings.isNullOrEmpty` check treats an empty endpoint as absent. + let empty = HashMap::from([(CloudRefresh::AWS.endpoint_key.to_string(), String::new())]); + let client = test_client("http://cat"); + assert!( + build_test_provider(client, "http://cat", &empty, None) + .await + .unwrap() + .is_none() + ); + } + + #[tokio::test] + async fn unchanged_refreshed_credential_is_not_refetched_near_expiry() { + let mut server = Server::new_async().await; + // Millisecond precision, as the catalog sends it. + let expires_at = UNIX_EPOCH + + Duration::from_millis( + (SystemTime::now() + Duration::from_secs(90)) + .duration_since(UNIX_EPOCH) + .unwrap() + .as_millis() as u64, + ); + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(s3_response("s3://bucket", "AK", expires_at)) + .create_async() + .await; + // The catalog returns the credential the cache already holds. + let provider = provider_with_cached_s3(&server.url(), vec![cached_s3( + "s3://bucket", + "AK", + expires_at, + )]); + + provider.load_credential("s3://bucket/f").await.unwrap(); + let cache = provider.clouds[0].cache.lock().await; + // With under two minutes left, there is no further check. + assert_eq!(cache.entries[0].refresh_at, Some(expires_at)); + drop(cache); + mock.assert_async().await; + } + + #[tokio::test] + async fn malformed_narrower_credential_is_not_masked_by_broader_one() { + let mut server = Server::new_async().await; + let expires = epoch_millis(SystemTime::now() + Duration::from_secs(3600)); + let body = format!( + r#"{{"storage-credentials":[ + {{"prefix":"s3://bucket","config":{{"s3.access-key-id":"BROAD_AK","s3.secret-access-key":"SK","s3.session-token":"TOK","s3.session-token-expires-at-ms":"{expires}"}}}}, + {{"prefix":"s3://bucket/table","config":{{"s3.access-key-id":"BAD"}}}} + ]}}"# + ); + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(body) + .create_async() + .await; + let provider = test_provider(&server.url(), &aws_refresh_props("/v1/credentials")).await; + + let error = provider + .load_credential("s3://bucket/table/f") + .await + .unwrap_err(); + assert!(error.message().contains("is missing or empty"), "{error}"); + // The cached broader credential does not mask the failure later either. + assert!( + provider + .load_credential("s3://bucket/table/other") + .await + .is_err() + ); + // Paths only the broader credential covers still use it. + assert_eq!( + s3_access_key_id( + &provider + .load_credential("s3://bucket/other/f") + .await + .unwrap() + ), + "BROAD_AK" + ); + mock.assert_async().await; + } + + #[tokio::test] + async fn failed_refreshes_do_not_duplicate_the_account_seed() { + let mut server = Server::new_async().await; + let mock = server + .mock("GET", "/v1/credentials") + .expect(2) + .with_status(503) + .create_async() + .await; + let host = "acct.dfs.core.windows.net"; + let azdls = |prefix: String, token: &str, expires_at: SystemTime| VendedCredential { + credential: Arc::new(StorageCredential::new( + prefix, + HashMap::from([(format!("{ADLS_SAS_TOKEN_PREFIX}{host}"), token.to_string())]), + )), + expires_at: Some(expires_at), + }; + let seed = CachedEntry::seed( + azdls( + String::new(), + "seed", + SystemTime::now() + Duration::from_secs(60), + ), + false, + SystemTime::now(), + ); + let configured = ConfiguredCloud::new( + &CloudRefresh::AZURE, + format!("{}/v1/credentials", server.url()), + Vec::new(), + HashMap::from([(host.to_string(), seed)]), + ); + let provider = RestVendedCredentialProvider { + client: OnceCell::new_with(Some(test_table_client(&server.url()))), + factory: None, + props: HashMap::new(), + query_params: Vec::new(), + clouds: vec![configured], + clock: Arc::new(SystemClock), + }; + let path = format!("abfss://c@{host}/data/f.parquet"); + + for _ in 0..2 { + let fallback = configured_seed(&provider, &path); + let credential = provider + .refresh_credential(&provider.clouds[0], &path, fallback) + .await + .unwrap(); + assert_eq!(sas_token(&credential), "seed"); + } + // The seed is cached once. + assert_eq!(provider.clouds[0].cache.lock().await.entries.len(), 1); + mock.assert_async().await; + } + + fn configured_seed(provider: &RestVendedCredentialProvider, path: &str) -> Option { + provider.clouds[0].keyed_seed_for_path(path).unwrap() + } + + #[tokio::test] + async fn expired_narrower_credential_does_not_fall_back_to_a_broader_one() { + let mut server = Server::new_async().await; + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(503) + .create_async() + .await; + let seed = CachedEntry::seed( + s3_vended( + "s3", + "SEED_AK", + SystemTime::now() + Duration::from_secs(3600), + ), + false, + SystemTime::now(), + ); + let expired = CachedEntry::new( + s3_vended( + "s3://bucket/table", + "OLD_AK", + SystemTime::now() - Duration::from_secs(1), + ), + false, + SystemTime::now(), + ); + let provider = provider_with_cached_s3(&server.url(), vec![seed, expired]); + + // The catalog scoped the table prefix separately, so its expired + // credential is refreshed instead of being served by the broader + // seed, and a failed refresh fails and backs off. + let error = provider + .load_credential("s3://bucket/table/f") + .await + .unwrap_err() + .to_string(); + assert!(error.contains("unexpected status code"), "{error}"); + let error = provider + .load_credential("s3://bucket/table/f") + .await + .unwrap_err() + .to_string(); + assert!(error.contains("backed off"), "{error}"); + // Other locations still use the seed. + assert_eq!( + s3_access_key_id( + &provider + .load_credential("s3://bucket/other/f") + .await + .unwrap() + ), + "SEED_AK" + ); + mock.assert_async().await; + } + + #[tokio::test] + async fn failed_prefix_clears_once_the_catalog_stops_naming_it() { + let mut server = Server::new_async().await; + let expires = epoch_millis(SystemTime::now() + Duration::from_secs(3600)); + let broad = format!( + r#"{{"prefix":"s3://bucket","config":{{"s3.access-key-id":"BROAD_AK","s3.secret-access-key":"SK","s3.session-token":"TOK","s3.session-token-expires-at-ms":"{expires}"}}}}"# + ); + let responses = [ + format!( + r#"{{"storage-credentials":[{broad},{{"prefix":"s3://bucket/table","config":{{"s3.access-key-id":"BAD"}}}}]}}"# + ), + // The catalog fixes the table by vending only the broader credential. + format!(r#"{{"storage-credentials":[{broad}]}}"#), + ]; + let fetches = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let counter = Arc::clone(&fetches); + let mock = server + .mock("GET", "/v1/credentials") + .expect(2) + .with_status(200) + .with_header("content-type", "application/json") + .with_body_from_request(move |_| { + let fetch = counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + responses[fetch.min(1)].clone().into_bytes() + }) + .create_async() + .await; + let provider = provider_with_cached_s3(&server.url(), Vec::new()); + + assert!( + provider + .load_credential("s3://bucket/table/f") + .await + .is_err() + ); + // Skip the backoff, then a later fetch no longer names the prefix. + provider.clouds[0].cache.lock().await.failure_backoff_until = None; + provider.clouds[0].cache.lock().await.entries[0].refresh_at = Some(UNIX_EPOCH); + assert_eq!( + s3_access_key_id( + &provider + .load_credential("s3://bucket/table/f") + .await + .unwrap() + ), + "BROAD_AK" + ); + mock.assert_async().await; + } + + #[tokio::test] + async fn azdls_seed_is_served_consistently_when_a_broader_credential_fails() { + let mut server = Server::new_async().await; + let host = "acct.dfs.core.windows.net"; + // The catalog's credential for the whole container has no expiry. + let body = format!( + r#"{{"storage-credentials":[{{"prefix":"abfss://c@{host}","config":{{"adls.sas-token.{host}":"sv=2026&sig=bad"}}}}]}}"# + ); + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(body) + .create_async() + .await; + let props = HashMap::from([ + ( + CloudRefresh::AZURE.endpoint_key.to_string(), + "/v1/credentials".to_string(), + ), + ( + format!("{ADLS_SAS_TOKEN_PREFIX}{host}"), + "sv=2026&sig=seed".to_string(), + ), + ( + format!("{ADLS_SAS_TOKEN_EXPIRES_AT_MS_PREFIX}{host}"), + epoch_millis(SystemTime::now() + Duration::from_secs(120)), + ), + ]); + let provider = test_provider(&server.url(), &props).await; + + // The failed prefix is not narrower than the seed, so the seed is + // served on the refresh and during the backoff that follows. + for _ in 0..2 { + let credential = provider + .load_credential(&format!("abfss://c@{host}/data.parquet")) + .await + .unwrap(); + assert_eq!(sas_token(&credential), "sv=2026&sig=seed"); + } + mock.assert_async().await; + } + + #[tokio::test] + async fn backoff_error_reports_the_last_failure() { + let mut server = Server::new_async().await; + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(503) + .create_async() + .await; + let provider = test_provider(&server.url(), &aws_refresh_props("/v1/credentials")).await; + + assert!( + provider + .load_credential("s3://bucket/table/f") + .await + .is_err() + ); + let error = provider + .load_credential("s3://bucket/table/f") + .await + .unwrap_err() + .to_string(); + assert!(error.contains("backed off"), "{error}"); + assert!(error.contains("unexpected status code"), "{error}"); + mock.assert_async().await; + } + + #[tokio::test] + async fn locations_the_catalog_does_not_vend_do_not_back_off_refresh() { + let mut server = Server::new_async().await; + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(s3_response( + "s3://bucket/table-a", + "AK", + SystemTime::now() + Duration::from_secs(3600), + )) + .create_async() + .await; + let provider = provider_with_cached_s3(&server.url(), Vec::new()); + + // A file outside the table's locations is not vended a credential. + for _ in 0..2 { + let error = provider + .load_credential("s3://other-bucket/f") + .await + .unwrap_err() + .to_string(); + assert!( + error.contains("no unexpired vended credential matches"), + "{error}" + ); + assert!(!error.contains("backed off"), "{error}"); + } + // That is not a refresh failure: covered locations are unaffected. + let cache = provider.clouds[0].cache.lock().await; + assert_eq!(cache.consecutive_failures, 0); + assert!(cache.failure_backoff_until.is_none()); + drop(cache); + assert_eq!( + s3_access_key_id( + &provider + .load_credential("s3://bucket/table-a/f") + .await + .unwrap() + ), + "AK" + ); + // The second miss did not ask the catalog again. + mock.assert_async().await; + } + + #[tokio::test(start_paused = true)] + async fn stalled_credential_requests_time_out_and_back_off() { + // Accepts connections and never answers. + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base_uri = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { + let mut open = Vec::new(); + while let Ok((stream, _)) = listener.accept().await { + open.push(stream); + } + }); + let provider = provider_with_cached_s3(&base_uri, Vec::new()); + + let error = provider + .load_credential("s3://bucket/table/f") + .await + .unwrap_err() + .to_string(); + assert!(error.contains("timed out"), "{error}"); + let error = provider + .load_credential("s3://bucket/table/f") + .await + .unwrap_err() + .to_string(); + assert!(error.contains("backed off"), "{error}"); + } + + /// A clock that only moves when advanced. + struct ManualClock { + start: (SystemTime, Instant), + elapsed: std::sync::Mutex, + } + + impl ManualClock { + fn new() -> Self { + Self { + start: (SystemTime::now(), Instant::now()), + elapsed: std::sync::Mutex::new(Duration::ZERO), + } + } + + fn advance(&self, duration: Duration) { + *self.elapsed.lock().unwrap() += duration; + } + } + + impl Clock for ManualClock { + fn now(&self) -> SystemTime { + self.start.0 + *self.elapsed.lock().unwrap() + } + + fn instant(&self) -> Instant { + self.start.1 + *self.elapsed.lock().unwrap() + } + } + + #[tokio::test] + async fn refresh_recovers_once_backoff_elapses() { + let mut server = Server::new_async().await; + let failure = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(503) + .create_async() + .await; + let clock = Arc::new(ManualClock::new()); + let provider = RestVendedCredentialProvider { + clock: clock.clone(), + ..provider_with_cached_s3(&server.url(), Vec::new()) + }; + let path = "s3://bucket/table/f"; + + assert!(provider.load_credential(path).await.is_err()); + let error = provider + .load_credential(path) + .await + .unwrap_err() + .to_string(); + assert!(error.contains("backed off"), "{error}"); + failure.assert_async().await; + + let success = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(s3_response( + "s3://bucket/table", + "AK", + clock.now() + Duration::from_secs(3600), + )) + .create_async() + .await; + clock.advance(MAX_FAILURE_BACKOFF); + assert_eq!( + s3_access_key_id(&provider.load_credential(path).await.unwrap()), + "AK" + ); + success.assert_async().await; + } + + #[tokio::test] + async fn static_keys_in_the_table_properties_serve_while_refresh_fails() { + let mut server = Server::new_async().await; + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(503) + .create_async() + .await; + let mut props = aws_refresh_props("/v1/credentials"); + props.extend([ + (S3_ACCESS_KEY_ID.to_string(), "STATIC_AK".to_string()), + (S3_SECRET_ACCESS_KEY.to_string(), "SK".to_string()), + ]); + let provider = test_provider(&server.url(), &props).await; + + // As in Java, the catalog is asked first. Keys without a session token + // or expiry never expire, so they serve while refresh fails. + for _ in 0..2 { + let credential = provider.load_credential("s3://bucket/f").await.unwrap(); + assert_eq!(s3_access_key_id(&credential), "STATIC_AK"); + assert!( + !credential + .config() + .contains_key(S3_SESSION_TOKEN_EXPIRES_AT_MS) + ); + } + mock.assert_async().await; + } + + #[tokio::test] + async fn static_keys_in_the_table_properties_are_rechecked_after_an_empty_response() { + let mut server = Server::new_async().await; + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(r#"{"storage-credentials":[]}"#) + .create_async() + .await; + let mut props = aws_refresh_props("/v1/credentials"); + props.extend([ + (S3_ACCESS_KEY_ID.to_string(), "STATIC_AK".to_string()), + (S3_SECRET_ACCESS_KEY.to_string(), "SK".to_string()), + ]); + let provider = test_provider(&server.url(), &props).await; + + // A catalog that vends nothing newer is not asked again on every + // access. + for _ in 0..3 { + let credential = provider.load_credential("s3://bucket/f").await.unwrap(); + assert_eq!(s3_access_key_id(&credential), "STATIC_AK"); + } + mock.assert_async().await; + } + + #[tokio::test] + async fn expired_account_seed_not_vended_is_rechecked_later() { + let mut server = Server::new_async().await; + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(r#"{"storage-credentials":[]}"#) + .create_async() + .await; + let host = "acct.dfs.core.windows.net"; + let expired_seed = CachedEntry::seed( + VendedCredential { + credential: Arc::new(StorageCredential::new( + String::new(), + HashMap::from([( + format!("{ADLS_SAS_TOKEN_PREFIX}{host}"), + "sv=2026&sig=seed".to_string(), + )]), + )), + expires_at: Some(SystemTime::now() - Duration::from_secs(1)), + }, + false, + SystemTime::now(), + ); + let provider = RestVendedCredentialProvider { + client: OnceCell::new_with(Some(test_table_client(&server.url()))), + factory: None, + props: HashMap::new(), + query_params: Vec::new(), + clouds: vec![ConfiguredCloud::new( + &CloudRefresh::AZURE, + format!("{}/v1/credentials", server.url()), + Vec::new(), + HashMap::from([(host.to_string(), expired_seed)]), + )], + clock: Arc::new(SystemClock), + }; + + // The catalog is asked once, not on every access. + for _ in 0..3 { + assert!( + provider + .load_credential(&format!("abfss://c@{host}/data/f.parquet")) + .await + .is_err() + ); + } + mock.assert_async().await; + } + + #[tokio::test] + async fn masked_locations_report_their_invalid_credential() { + let mut server = Server::new_async().await; + // The table's credential is invalid: it has no secret. + let mock = server + .mock("GET", "/v1/credentials") + .expect(2) + .with_status(200) + .with_header("content-type", "application/json") + .with_body( + r#"{"storage-credentials":[{"prefix":"s3://bucket/table","config":{"s3.access-key-id":"AK"}}]}"#, + ) + .create_async() + .await; + let provider = provider_with_cached_s3(&server.url(), Vec::new()); + + // A location outside the table starts a not-vended wait. + assert!(provider.load_credential("s3://other/f").await.is_err()); + // The table location still asks the catalog and reports why its + // credential cannot be used. + let error = provider + .load_credential("s3://bucket/table/f") + .await + .unwrap_err() + .to_string(); + assert!(error.contains("s3.secret-access-key"), "{error}"); + mock.assert_async().await; + } + + #[tokio::test] + async fn not_vended_locations_ask_again_after_the_recheck_delay() { + let mut server = Server::new_async().await; + let mock = server + .mock("GET", "/v1/credentials") + .expect(2) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(r#"{"storage-credentials":[]}"#) + .create_async() + .await; + let clock = Arc::new(ManualClock::new()); + let provider = RestVendedCredentialProvider { + clock: clock.clone(), + ..provider_with_cached_s3(&server.url(), Vec::new()) + }; + + for _ in 0..2 { + assert!(provider.load_credential("s3://other/f").await.is_err()); + } + clock.advance(NOT_VENDED_RECHECK); + assert!(provider.load_credential("s3://other/f").await.is_err()); + mock.assert_async().await; + } + + #[tokio::test] + async fn not_vended_locations_do_not_reset_each_others_recheck() { + let mut server = Server::new_async().await; + let mock = server + .mock("GET", "/v1/credentials") + .expect(2) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(r#"{"storage-credentials":[]}"#) + .create_async() + .await; + let expired = cached_s3( + "s3://bucket/table", + "OLD_AK", + SystemTime::now() - Duration::from_secs(1), + ); + let provider = provider_with_cached_s3(&server.url(), vec![expired]); + + // One location no credential covers, and one whose credential the + // catalog stopped vending, each ask the catalog once per recheck. + for _ in 0..3 { + for path in ["s3://other/f", "s3://bucket/table/f"] { + assert!(provider.load_credential(path).await.is_err()); + } + } + mock.assert_async().await; + } + + #[tokio::test] + async fn incomplete_keys_in_the_table_properties_are_fetched() { + let mut server = Server::new_async().await; + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(s3_response( + "s3", + "VENDED_AK", + SystemTime::now() + Duration::from_secs(3600), + )) + .create_async() + .await; + let mut props = aws_refresh_props("/v1/credentials"); + // A secret is required, so these keys are not a usable seed. + props.insert(S3_ACCESS_KEY_ID.to_string(), "STATIC_AK".to_string()); + let provider = test_provider(&server.url(), &props).await; + + let credential = provider.load_credential("s3://bucket/f").await.unwrap(); + assert_eq!(s3_access_key_id(&credential), "VENDED_AK"); + mock.assert_async().await; + } + + #[tokio::test] + async fn azdls_container_root_is_not_refetched_on_every_access() { + let mut server = Server::new_async().await; + let host = "acct.dfs.core.windows.net"; + let expires = epoch_millis(SystemTime::now() + Duration::from_secs(3600)); + let body = format!( + r#"{{"storage-credentials":[{{"prefix":"abfss://c@{host}/table","config":{{"adls.sas-token.{host}":"sv=2026&sig=table","adls.sas-token-expires-at-ms.{host}":"{expires}"}}}}]}}"# + ); + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(body) + .create_async() + .await; + // The account seed is inside its refresh window. + let props = HashMap::from([ + ( + CloudRefresh::AZURE.endpoint_key.to_string(), + "/v1/credentials".to_string(), + ), + ( + format!("{ADLS_SAS_TOKEN_PREFIX}{host}"), + "sv=2026&sig=seed".to_string(), + ), + ( + format!("{ADLS_SAS_TOKEN_EXPIRES_AT_MS_PREFIX}{host}"), + epoch_millis(SystemTime::now() + Duration::from_secs(240)), + ), + ]); + let provider = test_provider(&server.url(), &props).await; + + for _ in 0..5 { + let credential = provider + .load_credential(&format!("abfss://c@{host}")) + .await + .unwrap(); + assert_eq!(sas_token(&credential), "sv=2026&sig=seed"); + } + mock.assert_async().await; + } + + #[tokio::test] + async fn malformed_response_errors_do_not_quote_secrets() { + let mut server = Server::new_async().await; + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body( + r#"{"storage-credentials":[{"prefix":"s3://b","config":"s3.secret-access-key=TOPSECRET"}]}"#, + ) + .create_async() + .await; + let provider = test_provider(&server.url(), &aws_refresh_props("/v1/credentials")).await; + + for _ in 0..2 { + let error = provider + .load_credential("s3://b/f") + .await + .unwrap_err() + .to_string(); + assert!(!error.contains("TOPSECRET"), "{error}"); + } + mock.assert_async().await; + } + + #[tokio::test] + async fn catalog_error_messages_are_reported() { + let mut server = Server::new_async().await; + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(403) + .with_header("content-type", "application/json") + .with_body( + r#"{"error":{"message":"not allowed to access the table","type":"ForbiddenException","code":403}}"#, + ) + .create_async() + .await; + let provider = test_provider(&server.url(), &aws_refresh_props("/v1/credentials")).await; + + let error = provider + .load_credential("s3://b/f") + .await + .unwrap_err() + .to_string(); + assert!(error.contains("not allowed to access the table"), "{error}"); + assert!(error.contains("ForbiddenException"), "{error}"); + mock.assert_async().await; + } + + #[tokio::test] + async fn widened_scope_replaces_the_narrower_credential() { + let mut server = Server::new_async().await; + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(s3_response( + "s3://b", + "WIDE_AK", + SystemTime::now() + Duration::from_secs(3600), + )) + .create_async() + .await; + // The narrower credential is inside its refresh window. + let provider = provider_with_cached_s3(&server.url(), vec![cached_s3( + "s3://b/t", + "NARROW_AK", + SystemTime::now() + Duration::from_secs(240), + )]); + + for _ in 0..2 { + assert_eq!( + s3_access_key_id(&provider.load_credential("s3://b/t/f").await.unwrap()), + "WIDE_AK" + ); + } + assert_eq!(provider.clouds[0].cache.lock().await.entries.len(), 1); + mock.assert_async().await; + } + + #[tokio::test] + async fn azdls_seed_is_not_served_for_a_path_it_does_not_cover() { + let mut server = Server::new_async().await; + let host = "acct.dfs.core.windows.net"; + let expires = epoch_millis(SystemTime::now() + Duration::from_secs(3600)); + let body = format!( + r#"{{"storage-credentials":[{{"prefix":"ABFSS://c@{host}","config":{{"adls.sas-token.{host}":"sv=2026&sig=fetched","adls.sas-token-expires-at-ms.{host}":"{expires}"}}}}]}}"# + ); + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(body) + .create_async() + .await; + let props = HashMap::from([ + ( + CloudRefresh::AZURE.endpoint_key.to_string(), + "/v1/credentials".to_string(), + ), + ( + format!("{ADLS_SAS_TOKEN_PREFIX}{host}"), + "sv=2026&sig=seed".to_string(), + ), + ( + format!("{ADLS_SAS_TOKEN_EXPIRES_AT_MS_PREFIX}{host}"), + expires.clone(), + ), + ]); + let provider = test_provider(&server.url(), &props).await; + + // The seed's scope has a lowercase scheme, so it does not cover this + // path, which fetches a credential that does. + let path = format!("ABFSS://c@{host}/data.parquet"); + let credential = provider.load_credential(&path).await.unwrap(); + assert!(credential.covers(&path)); + assert_eq!(sas_token(&credential), "sv=2026&sig=fetched"); + mock.assert_async().await; + } + + #[tokio::test] + async fn concurrent_loads_without_a_usable_credential_fetch_once() { + let mut server = Server::new_async().await; + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(s3_response( + "s3://bucket", + "AK", + SystemTime::now() + Duration::from_secs(3600), + )) + .create_async() + .await; + let provider = test_provider(&server.url(), &aws_refresh_props("/v1/credentials")).await; + + // Waiters for the in-flight refresh use its result instead of fetching. + let loads = (0..8).map(|_| { + let provider = Arc::clone(&provider); + tokio::spawn(async move { provider.load_credential("s3://bucket/x/f").await }) + }); + for load in futures::future::join_all(loads).await { + assert_eq!(s3_access_key_id(&load.unwrap().unwrap()), "AK"); + } + mock.assert_async().await; + } + + #[tokio::test] + async fn failed_credential_requests_do_not_report_the_body() { + let mut server = Server::new_async().await; + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(500) + .with_header("content-type", "application/json") + .with_body( + r#"{"error":{"message":"internal error","type":"ServerError","code":500},"storage-credentials":[{"prefix":"s3://b","config":{"s3.secret-access-key":"TOPSECRET"}}]}"#, + ) + .create_async() + .await; + let provider = test_provider(&server.url(), &aws_refresh_props("/v1/credentials")).await; + + let error = provider + .load_credential("s3://b/f") + .await + .unwrap_err() + .to_string(); + assert!(error.contains("internal error"), "{error}"); + assert!(!error.contains("TOPSECRET"), "{error}"); + mock.assert_async().await; + } + + #[tokio::test] + async fn rebuilt_provider_does_not_infer_another_auth_type() { + let mut server = Server::new_async().await; + // The merged FileIO properties hold a `credential`, which would infer + // oauth2 and exchange it; the catalog resolved no auth. + let token_mock = server + .mock("POST", "/v1/oauth/tokens") + .expect(0) + .create_async() + .await; + let credentials_mock = server + .mock("GET", "/v1/credentials") + .match_header("authorization", Matcher::Missing) + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(s3_response( + "s3://bucket", + "AK", + SystemTime::now() + Duration::from_secs(3600), + )) + .create_async() + .await; + let mut props = aws_refresh_props("/v1/credentials"); + props.insert("credential".to_string(), "client:secret".to_string()); + let rebuilt = RestVendedCredentialProviderFactory::new( + server.url(), + test_table(), + AUTH_TYPE_NONE, + false, + &HashMap::new(), + ) + .build(&StorageConfig::new().with_props(props)) + .unwrap(); + + rebuilt.load_credential("s3://bucket/x/f").await.unwrap(); + token_mock.assert_async().await; + credentials_mock.assert_async().await; + } + + #[tokio::test] + async fn gcs_refresh_requires_a_vended_token() { + let mut props = HashMap::from([( + CloudRefresh::GCP.endpoint_key.to_string(), + "/v1/credentials".to_string(), + )]); + // Without a vended token, like Java, GCS keeps its default credentials. + assert!( + build_test_provider(test_client("http://cat"), "http://cat", &props, None) + .await + .unwrap() + .is_none() + ); + + props.insert(GCS_TOKEN.to_string(), "TOKEN".to_string()); + let provider = test_provider("http://cat", &props).await; + assert!(provider.supports_path("gs://bucket/x")); + } + + #[tokio::test] + async fn refresh_includes_java_query_parameters() { + let mut server = Server::new_async().await; + let body = s3_response( + "s3://bucket", + "AK", + SystemTime::now() + Duration::from_secs(3600), + ); + let mock = server + .mock("GET", "/v1/credentials") + // `referenced-by` is sent verbatim, without encoding `%` again. + .match_query(Matcher::Exact( + "planId=scan-plan-1&referenced-by=ns%1Fview,ns%1Fother".to_string(), + )) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(body) + .create_async() + .await; + + // No static creds -> no seed -> first load fetches from the endpoint. + let mut props = aws_refresh_props("/v1/credentials"); + props.extend([ + ( + REST_CATALOG_PROP_SCAN_PLAN_ID.to_string(), + "scan-plan-1".to_string(), + ), + ( + REST_CATALOG_PROP_REFERENCED_BY.to_string(), + "ns%1Fview,ns%1Fother".to_string(), + ), + ]); + + let provider = test_provider(&server.url(), &props).await; + let credential = provider + .load_credential("s3://bucket/warehouse/f") + .await + .unwrap(); + assert_eq!(credential.prefix(), "s3://bucket"); + assert_eq!(s3_access_key_id(&credential), "AK"); + assert_eq!( + credential + .config() + .get(S3_SESSION_TOKEN) + .map(String::as_str), + Some("TOK") + ); + mock.assert_async().await; + } + + #[tokio::test] + async fn successful_refresh_caches_entries_before_selecting_path() { + let mut server = Server::new_async().await; + let body = s3_response( + "s3://bucket/table-a", + "AK", + SystemTime::now() + Duration::from_secs(3600), + ); + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(body) + .create_async() + .await; + + let props = aws_refresh_props("/v1/credentials"); + let provider = test_provider(&server.url(), &props).await; + + assert!( + provider + .load_credential("s3://bucket/table-b/file") + .await + .is_err() + ); + // A successful response with no matching credential is negatively + // cached instead of immediately hitting the endpoint again. + assert!( + provider + .load_credential("s3://bucket/table-b/file") + .await + .is_err() + ); + assert_eq!( + s3_access_key_id( + &provider + .load_credential("s3://bucket/table-a/file") + .await + .unwrap() + ), + "AK" + ); + mock.assert_async().await; + } + + #[tokio::test] + async fn malformed_entry_does_not_discard_valid_entries() { + let mut server = Server::new_async().await; + let expires = epoch_millis(SystemTime::now() + Duration::from_secs(3600)); + let body = format!( + r#"{{"storage-credentials":[ + {{"prefix":"s3://bucket/invalid","config":{{"s3.access-key-id":"BAD"}}}}, + {{"prefix":"s3://bucket/valid","config":{{"s3.access-key-id":"AK","s3.secret-access-key":"SK","s3.session-token":"TOK","s3.session-token-expires-at-ms":"{expires}"}}}} + ]}}"# + ); + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(body) + .create_async() + .await; + + let props = aws_refresh_props("/v1/credentials"); + let provider = test_provider(&server.url(), &props).await; + + assert!( + provider + .load_credential("s3://bucket/invalid/file") + .await + .is_err() + ); + assert!( + provider + .load_credential("s3://bucket/invalid/file") + .await + .is_err() + ); + assert_eq!( + s3_access_key_id( + &provider + .load_credential("s3://bucket/valid/file") + .await + .unwrap() + ), + "AK" + ); + mock.assert_async().await; + } + + #[tokio::test] + async fn fresh_seed_is_served_without_fetching() { + let mut server = Server::new_async().await; + // Any call to the server is a failure: the fresh seed must be reused. + let mock = server + .mock("GET", Matcher::Any) + .expect(0) + .create_async() + .await; + + let props = with_s3_seed( + aws_refresh_props("/v1/credentials"), + "SEED_AK", + SystemTime::now() + Duration::from_secs(3600), + ); + + let provider = test_provider(&server.url(), &props).await; + let credential = provider.load_credential("s3://bucket/x/f").await.unwrap(); + + assert_eq!(credential.prefix(), "s3"); + assert_eq!(s3_access_key_id(&credential), "SEED_AK"); + mock.assert_async().await; + } + + #[tokio::test] + async fn fresh_azdls_seeds_are_scoped_and_served_without_fetching() { + let mut server = Server::new_async().await; + let mock = server + .mock("GET", Matcher::Any) + .expect(0) + .create_async() + .await; + let props = HashMap::from([ + ( + CloudRefresh::AZURE.endpoint_key.to_string(), + "/v1/credentials".to_string(), + ), + ( + format!("{ADLS_SAS_TOKEN_PREFIX}account1"), + "sv=2026&sig=seed".to_string(), + ), + ( + format!("{ADLS_SAS_TOKEN_EXPIRES_AT_MS_PREFIX}account1"), + epoch_millis(SystemTime::now() + Duration::from_secs(3600)), + ), + ( + format!("{ADLS_SAS_TOKEN_PREFIX}account2"), + "sv=2026&sig=other-seed".to_string(), + ), + ( + format!("{ADLS_SAS_TOKEN_EXPIRES_AT_MS_PREFIX}account2"), + epoch_millis(SystemTime::now() + Duration::from_secs(3600)), + ), + ]); + let provider = test_provider(&server.url(), &props).await; + + let credential = provider + .load_credential("abfss://container@account1.dfs.core.windows.net/table/data/a.parquet") + .await + .unwrap(); + assert_eq!( + credential.prefix(), + "abfss://container@account1.dfs.core.windows.net" + ); + assert_eq!(sas_token(&credential), "sv=2026&sig=seed"); + + let credential = provider + .load_credential("abfss://other-container@account2.dfs.core.windows.net/data/b.parquet") + .await + .unwrap(); + assert_eq!( + credential.prefix(), + "abfss://other-container@account2.dfs.core.windows.net" + ); + assert_eq!(sas_token(&credential), "sv=2026&sig=other-seed"); + mock.assert_async().await; + } + + #[tokio::test] + async fn invalid_azdls_path_is_rejected_before_refresh() { + let mut server = Server::new_async().await; + let mock = server + .mock("GET", Matcher::Any) + .expect(0) + .create_async() + .await; + let props = HashMap::from([( + CloudRefresh::AZURE.endpoint_key.to_string(), + "/v1/credentials".to_string(), + )]); + let provider = test_provider(&server.url(), &props).await; + + let error = provider + .load_credential("abfss:///data.parquet") + .await + .unwrap_err(); + + assert_eq!(error.kind(), ErrorKind::DataInvalid); + assert!(error.message().contains("no account name")); + mock.assert_async().await; + } + + #[tokio::test] + async fn failed_refresh_is_backed_off_while_credential_is_unexpired() { + let mut server = Server::new_async().await; + // A refresh is due (the seed is within the buffer) but the catalog errors. + let mock = server + .mock("GET", Matcher::Any) + .expect(1) + .with_status(500) + .create_async() + .await; + + // Seeded credential is within the refresh buffer but not yet expired. + let props = with_s3_seed( + aws_refresh_props("/v1/credentials"), + "SEED_AK", + SystemTime::now() + Duration::from_secs(60), + ); + + let provider = test_provider(&server.url(), &props).await; + // The first refresh fails, but the still-valid seed is served. Immediate + // follow-up operations stay inside the first jittered backoff window. + for _ in 0..2 { + let credential = provider.load_credential("s3://bucket/x/f").await.unwrap(); + assert_eq!(s3_access_key_id(&credential), "SEED_AK"); + } + mock.assert_async().await; + } + + #[tokio::test] + async fn empty_refresh_preserves_unexpired_seed() { + let mut server = Server::new_async().await; + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(r#"{"storage-credentials":[]}"#) + .create_async() + .await; + + let props = with_s3_seed( + aws_refresh_props("/v1/credentials"), + "SEED_AK", + SystemTime::now() + Duration::from_secs(60), + ); + let provider = test_provider(&server.url(), &props).await; + + for _ in 0..2 { + let credential = provider.load_credential("s3://bucket/x/f").await.unwrap(); + assert_eq!(s3_access_key_id(&credential), "SEED_AK"); + } + mock.assert_async().await; + } + + #[tokio::test] + async fn malformed_specific_refresh_prefers_fallback_over_valid_broader_entry() { + let mut server = Server::new_async().await; + let refreshed_expires = epoch_millis(SystemTime::now() + Duration::from_secs(3600)); + let body = format!( + r#"{{"storage-credentials":[ + {{"prefix":"s3://bucket/requested","config":{{"s3.access-key-id":"BAD"}}}}, + {{"prefix":"s3://bucket","config":{{"s3.access-key-id":"NEW_AK","s3.secret-access-key":"SK","s3.session-token":"TOK","s3.session-token-expires-at-ms":"{refreshed_expires}"}}}} + ]}}"# + ); + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(body) + .create_async() + .await; + + let provider = provider_with_cached_s3(&server.url(), vec![cached_s3( + "s3://bucket/requested", + "SEED_AK", + SystemTime::now() + Duration::from_secs(60), + )]); + + let fallback = provider + .load_credential("s3://bucket/requested/file") + .await + .unwrap(); + assert_eq!(s3_access_key_id(&fallback), "SEED_AK"); + + // The malformed specific replacement is a failed refresh for this path. + // Its still-valid fallback wins over the broader fetched credential and + // is backed off, so an immediate retry does not fetch again. + let fallback = provider + .load_credential("s3://bucket/requested/other-file") + .await + .unwrap(); + assert_eq!(s3_access_key_id(&fallback), "SEED_AK"); + + let refreshed = provider + .load_credential("s3://bucket/other/file") + .await + .unwrap(); + assert_eq!(s3_access_key_id(&refreshed), "NEW_AK"); + mock.assert_async().await; + } + + #[tokio::test] + async fn invalid_refresh_preserves_other_prefix_fallbacks() { + let mut server = Server::new_async().await; + let refreshed_expires = epoch_millis(SystemTime::now() + Duration::from_secs(3600)); + let expired = epoch_millis(SystemTime::now() - Duration::from_secs(60)); + let body = format!( + r#"{{"storage-credentials":[ + {{"prefix":"s3://bucket/table-a","config":{{"s3.access-key-id":"NEW_AK","s3.secret-access-key":"SK","s3.session-token":"TOK","s3.session-token-expires-at-ms":"{refreshed_expires}"}}}}, + {{"prefix":"s3://bucket/table-b","config":{{"s3.access-key-id":"BAD"}}}}, + {{"prefix":"s3://bucket/table-c","config":{{"s3.access-key-id":"EXPIRED_CK","s3.secret-access-key":"SK","s3.session-token":"TOK","s3.session-token-expires-at-ms":"{expired}"}}}} + ]}}"# + ); + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(body) + .create_async() + .await; + + let provider = provider_with_cached_s3(&server.url(), vec![ + cached_s3( + "s3://bucket/table-a", + "OLD_AK", + SystemTime::now() + Duration::from_secs(60), + ), + cached_s3( + "s3://bucket/table-b", + "OLDER_BK", + SystemTime::now() + Duration::from_secs(3600), + ), + cached_s3( + "s3://bucket/table-b", + "LATEST_BK", + SystemTime::now() + Duration::from_secs(3600), + ), + cached_s3( + "s3://bucket/table-c", + "VALID_CK", + SystemTime::now() + Duration::from_secs(3600), + ), + ]); + + let refreshed = provider + .load_credential("s3://bucket/table-a/file") + .await + .unwrap(); + assert_eq!(s3_access_key_id(&refreshed), "NEW_AK"); + + let fallback = provider + .load_credential("s3://bucket/table-b/file") + .await + .unwrap(); + assert_eq!(s3_access_key_id(&fallback), "LATEST_BK"); + + let fallback = provider + .load_credential("s3://bucket/table-c/file") + .await + .unwrap(); + assert_eq!(s3_access_key_id(&fallback), "VALID_CK"); + mock.assert_async().await; + } + + #[tokio::test] + async fn scoped_refresh_after_scheme_wide_seed_does_not_back_off() { + let mut server = Server::new_async().await; + let body = s3_response( + "s3://bucket/table", + "SCOPED_AK", + SystemTime::now() + Duration::from_secs(3600), + ); + let mock = server + .mock("GET", "/v1/credentials") + .expect(2) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(body) + .create_async() + .await; + + // The scheme-wide seed is inside its refresh window. + let seed = CachedEntry::seed( + s3_vended("s3", "SEED_AK", SystemTime::now() + Duration::from_secs(60)), + false, + SystemTime::now(), + ); + let provider = provider_with_cached_s3(&server.url(), vec![seed]); + + assert_eq!( + s3_access_key_id( + &provider + .load_credential("s3://bucket/table/data/f.parquet") + .await + .unwrap() + ), + "SCOPED_AK" + ); + // A location only the seed covers refreshes once, finds no newer + // credential, and keeps using the seed. This is not a failure, so the + // cloud is not backed off. + for location in ["s3://bucket/", "s3://bucket/", "s3://bucket/other/f"] { + assert_eq!( + s3_access_key_id(&provider.load_credential(location).await.unwrap()), + "SEED_AK" + ); + } + let cache = provider.clouds[0].cache.lock().await; + assert_eq!(cache.consecutive_failures, 0); + assert!(cache.failure_backoff_until.is_none()); + drop(cache); + mock.assert_async().await; + } + + #[tokio::test] + async fn scoped_refresh_after_azdls_account_seed_does_not_back_off() { + let mut server = Server::new_async().await; + let host = "account1.dfs.core.windows.net"; + let expires = epoch_millis(SystemTime::now() + Duration::from_secs(3600)); + let body = format!( + r#"{{"storage-credentials":[{{"prefix":"abfss://container@{host}/table","config":{{"adls.sas-token.{host}":"sv=2026&sig=scoped","adls.sas-token-expires-at-ms.{host}":"{expires}"}}}}]}}"# + ); + // One fetch for the container root, which finds nothing newer, and one + // for an account without credentials. A backed-off cloud would skip + // the second. + let mock = server + .mock("GET", "/v1/credentials") + .expect(2) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(body) + .create_async() + .await; + // The account seed is inside its refresh window. + let props = HashMap::from([ + ( + CloudRefresh::AZURE.endpoint_key.to_string(), + "/v1/credentials".to_string(), + ), + ( + format!("{ADLS_SAS_TOKEN_PREFIX}{host}"), + "sv=2026&sig=seed".to_string(), + ), + ( + format!("{ADLS_SAS_TOKEN_EXPIRES_AT_MS_PREFIX}{host}"), + epoch_millis(SystemTime::now() + Duration::from_secs(240)), + ), + ]); + let provider = test_provider(&server.url(), &props).await; + let sas_token = |credential: Arc| sas_token(&credential).to_string(); + + let root = format!("abfss://container@{host}/"); + for _ in 0..2 { + assert_eq!( + sas_token(provider.load_credential(&root).await.unwrap()), + "sv=2026&sig=seed" + ); + } + assert_eq!( + sas_token( + provider + .load_credential(&format!("{root}table/data.parquet")) + .await + .unwrap() + ), + "sv=2026&sig=scoped" + ); + assert!( + provider + .load_credential("abfss://container@account2.dfs.core.windows.net/a") + .await + .is_err() + ); + mock.assert_async().await; + } + + #[test] + fn recheck_time_stops_near_expiry() { + let now = SystemTime::now(); + assert_eq!( + recheck_time(now, now + Duration::from_secs(240)), + now + Duration::from_secs(120) + ); + let soon = now + MIN_REFRESH_BUFFER * 2; + assert_eq!(recheck_time(now, soon), soon); + // Longer lifetimes keep the regular prefetch time. + let later = now + Duration::from_secs(3600); + assert_eq!(recheck_time(now, later), later - REFRESH_BUFFER); + } + + #[tokio::test] + async fn concurrent_prefetch_serves_unexpired_credential_without_waiting() { + let mut server = Server::new_async().await; + let body = s3_response( + "s3://bucket", + "NEW_AK", + SystemTime::now() + Duration::from_secs(3600), + ); + let (started_tx, started_rx) = mpsc::channel(); + let release = Arc::new(Barrier::new(2)); + let callback_release = Arc::clone(&release); + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_chunked_body(move |writer| { + started_tx.send(()).unwrap(); + callback_release.wait(); + writer.write_all(body.as_bytes()) + }) + .create_async() + .await; + + let props = with_s3_seed( + aws_refresh_props("/v1/credentials"), + "SEED_AK", + SystemTime::now() + Duration::from_secs(60), + ); + let provider = test_provider(&server.url(), &props).await; + + let first_provider = Arc::clone(&provider); + let first = + tokio::spawn(async move { first_provider.load_credential("s3://bucket/x/f").await }); + tokio::task::spawn_blocking(move || { + started_rx.recv_timeout(Duration::from_secs(5)).unwrap() + }) + .await + .unwrap(); + + let second_provider = Arc::clone(&provider); + let second = + tokio::spawn(async move { second_provider.load_credential("s3://bucket/x/f").await }); + for _ in 0..100 { + if second.is_finished() { + break; + } + tokio::task::yield_now().await; + } + let completed_without_waiting = second.is_finished(); + release.wait(); + + assert!( + completed_without_waiting, + "a concurrent prefetch waited instead of using the unexpired credential" + ); + assert_eq!(s3_access_key_id(&second.await.unwrap().unwrap()), "SEED_AK"); + assert_eq!(s3_access_key_id(&first.await.unwrap().unwrap()), "NEW_AK"); + mock.assert_async().await; + } + + #[tokio::test] + async fn refresh_uses_table_scoped_token() { + let mut server = Server::new_async().await; + let body = s3_response( + "s3://bucket", + "AK", + SystemTime::now() + Duration::from_secs(3600), + ); + let mock = server + .mock("GET", "/v1/credentials") + .match_header("authorization", "Bearer table-token") + .with_status(200) + .with_header("content-type", "application/json") + .with_body(body) + .create_async() + .await; + + let config = RestCatalogConfig::builder() + .uri(server.url()) + .props(HashMap::from([( + "token".to_string(), + "catalog-token".to_string(), + )])) + .build(); + let client = HttpClient::new(&config).unwrap(); + let props = HashMap::from([ + ( + CloudRefresh::AWS.endpoint_key.to_string(), + "/v1/credentials".to_string(), + ), + // Local properties win in the FileIO configuration merge, but must + // not mask auth returned by the table endpoint. + ("token".to_string(), "user-token".to_string()), + ]); + let table_auth = HashMap::from([("token".to_string(), "table-token".to_string())]); + let auth_manager = OAuth2Manager::new(format!("{}/v1/oauth/tokens", server.url())); + let provider = build_vended_credential_provider( + &client, + &auth_manager, + async || Ok(Arc::new(NoopSession) as Arc), + test_factory(&server.url(), Some(&table_auth)), + &props, + &table_auth, + true, + ) + .await + .unwrap() + .unwrap(); + + provider.load_credential("s3://bucket/x/f").await.unwrap(); + mock.assert_async().await; + } + + #[tokio::test] + async fn effective_headers_override_raw_table_headers() { + let mut server = Server::new_async().await; + let body = s3_response( + "s3://bucket", + "AK", + SystemTime::now() + Duration::from_secs(3600), + ); + let mock = server + .mock("GET", "/v1/credentials") + .match_header("authorization", "Bearer local-header") + .with_status(200) + .with_header("content-type", "application/json") + .with_body(body) + .create_async() + .await; + + let client = test_client(&server.url()); + let props = HashMap::from([ + ( + CloudRefresh::AWS.endpoint_key.to_string(), + "/v1/credentials".to_string(), + ), + ( + "header.Authorization".to_string(), + "Bearer local-header".to_string(), + ), + ]); + let table_auth = HashMap::from([ + ("token".to_string(), "table-token".to_string()), + ( + "header.Authorization".to_string(), + "Bearer table-header".to_string(), + ), + ]); + let auth_manager = OAuth2Manager::new(format!("{}/v1/oauth/tokens", server.url())); + let provider = build_vended_credential_provider( + &client, + &auth_manager, + async || Ok(Arc::new(NoopSession) as Arc), + test_factory(&server.url(), Some(&table_auth)), + &props, + &table_auth, + true, + ) + .await + .unwrap() + .unwrap(); + + provider.load_credential("s3://bucket/x/f").await.unwrap(); + mock.assert_async().await; + } + + #[tokio::test] + async fn one_provider_refreshes_multiple_clouds() { + let mut server = Server::new_async().await; + let expires = epoch_millis(SystemTime::now() + Duration::from_secs(3600)); + let aws_body = s3_response( + "s3://bucket", + "AK", + SystemTime::now() + Duration::from_secs(3600), + ); + let gcp_body = format!( + r#"{{"storage-credentials":[{{"prefix":"gs://bucket","config":{{"gcs.oauth2.token":"GCS","gcs.oauth2.token-expires-at":"{expires}"}}}}]}}"# + ); + let aws_mock = server + .mock("GET", "/v1/aws-credentials") + .with_status(200) + .with_header("content-type", "application/json") + .with_body(aws_body) + .create_async() + .await; + let gcp_mock = server + .mock("GET", "/v1/gcp-credentials") + .with_status(200) + .with_header("content-type", "application/json") + .with_body(gcp_body) + .create_async() + .await; + + let props = HashMap::from([ + ( + CloudRefresh::AWS.endpoint_key.to_string(), + "/v1/aws-credentials".to_string(), + ), + ( + CloudRefresh::GCP.endpoint_key.to_string(), + "/v1/gcp-credentials".to_string(), + ), + // GCS refreshes only a vended token; this one already expired. + (GCS_TOKEN.to_string(), "EXPIRED".to_string()), + ( + GCS_TOKEN_EXPIRES_AT.to_string(), + epoch_millis(SystemTime::now() - Duration::from_secs(60)), + ), + ]); + let provider = test_provider(&server.url(), &props).await; + + assert!(provider.supports_path("s3://bucket/x")); + assert!(provider.supports_path("gs://bucket/x")); + assert_eq!( + s3_access_key_id(&provider.load_credential("s3://bucket/x").await.unwrap()), + "AK" + ); + assert_eq!( + gcs_token(&provider.load_credential("gs://bucket/x").await.unwrap()), + "GCS" + ); + aws_mock.assert_async().await; + gcp_mock.assert_async().await; + } + + #[tokio::test] + async fn host_keyed_azdls_credentials_match_java() { + let mut server = Server::new_async().await; + let host = "account1.dfs.core.windows.net"; + let expires = epoch_millis(SystemTime::now() + Duration::from_secs(3600)); + let prefix = format!("abfss://container@{host}/table"); + let body = format!( + r#"{{"storage-credentials":[{{"prefix":"{prefix}","config":{{"adls.sas-token.{host}":"sv=2026&sig=refreshed","adls.sas-token-expires-at-ms.{host}":"{expires}"}}}}]}}"# + ); + let mock = server + .mock("GET", "/v1/azure-credentials") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(body) + .create_async() + .await; + let props = HashMap::from([ + ( + CloudRefresh::AZURE.endpoint_key.to_string(), + "/v1/azure-credentials".to_string(), + ), + ( + format!("{ADLS_SAS_TOKEN_PREFIX}{host}"), + "sv=2026&sig=seed".to_string(), + ), + ( + format!("{ADLS_SAS_TOKEN_EXPIRES_AT_MS_PREFIX}{host}"), + epoch_millis(SystemTime::now() + Duration::from_secs(3600)), + ), + ]); + let provider = test_provider(&server.url(), &props).await; + let sas_token = |credential: Arc| sas_token(&credential).to_string(); + + // The host-keyed seed serves the account without fetching. + let seeded = provider + .load_credential(&format!("abfss://other@{host}/data.parquet")) + .await + .unwrap(); + assert_eq!(sas_token(seeded), "sv=2026&sig=seed"); + + // An account without a seed refreshes. The response is parsed with + // host-keyed tokens, and its entry then wins over the broader seed. + let uncovered = provider + .load_credential("abfss://container@account2.dfs.core.windows.net/table/a") + .await; + assert!(uncovered.is_err()); + let refreshed = provider + .load_credential(&format!("{prefix}/data.parquet")) + .await + .unwrap(); + assert_eq!(sas_token(refreshed), "sv=2026&sig=refreshed"); + mock.assert_async().await; + } + + #[tokio::test] + async fn refreshes_azdls_credentials() { + let mut server = Server::new_async().await; + let expires = epoch_millis(SystemTime::now() + Duration::from_secs(3600)); + let prefix = "abfss://container@account1.dfs.core.windows.net/table"; + let body = format!( + r#"{{"storage-credentials":[{{"prefix":"{prefix}","config":{{"adls.sas-token.account1":"sv=2026&sig=secret","adls.sas-token-expires-at-ms.account1":"{expires}"}}}}]}}"# + ); + let mock = server + .mock("GET", "/v1/azure-credentials") + .with_status(200) + .with_header("content-type", "application/json") + .with_body(body) + .create_async() + .await; + let props = HashMap::from([( + CloudRefresh::AZURE.endpoint_key.to_string(), + "/v1/azure-credentials".to_string(), + )]); + let provider = test_provider(&server.url(), &props).await; + + let credential = provider + .load_credential(&format!("{prefix}/data.parquet")) + .await + .unwrap(); + assert_eq!(sas_token(&credential), "sv=2026&sig=secret"); + mock.assert_async().await; + } + + #[tokio::test] + async fn refresh_failure_never_serves_expired_credential() { + let mut server = Server::new_async().await; + let mock = server + .mock("GET", Matcher::Any) + .expect(1) + .with_status(500) + .create_async() + .await; + + let props = with_s3_seed( + aws_refresh_props("/v1/credentials"), + "EXPIRED_AK", + SystemTime::now() - Duration::from_secs(60), + ); + + let provider = test_provider(&server.url(), &props).await; + + assert!(provider.load_credential("s3://bucket/x/f").await.is_err()); + assert!(provider.load_credential("s3://bucket/x/f").await.is_err()); + mock.assert_async().await; + } + + #[tokio::test] + async fn failed_azdls_refresh_uses_account_seed_until_expiry() { + let mut server = Server::new_async().await; + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(503) + .with_header("content-type", "application/json") + .with_body(r#"{"error":{"message":"unavailable","type":"test","code":503}}"#) + .create_async() + .await; + let props = HashMap::from([ + ( + CloudRefresh::AZURE.endpoint_key.to_string(), + "/v1/credentials".to_string(), + ), + ( + format!("{ADLS_SAS_TOKEN_PREFIX}account2"), + "sv=2026&sig=seed".to_string(), + ), + ( + format!("{ADLS_SAS_TOKEN_EXPIRES_AT_MS_PREFIX}account2"), + epoch_millis(SystemTime::now() + Duration::from_secs(60)), + ), + ]); + let provider = test_provider(&server.url(), &props).await; + let path = "abfss://container@account2.dfs.core.windows.net/data/a.parquet"; + + for _ in 0..2 { + let credential = provider.load_credential(path).await.unwrap(); + assert_eq!( + credential.prefix(), + "abfss://container@account2.dfs.core.windows.net" + ); + assert_eq!(sas_token(&credential), "sv=2026&sig=seed"); + } + mock.assert_async().await; + } + + #[tokio::test] + async fn sub_buffer_ttl_is_reused_until_half_its_lifetime() { + let mut server = Server::new_async().await; + // The vended TTL (60s) is shorter than REFRESH_BUFFER. Java would treat + // it as due on arrival and fetch on every operation; the capped buffer + // keeps it for half its lifetime. + let body = s3_response( + "s3://bucket", + "AK", + SystemTime::now() + Duration::from_secs(60), + ); + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(body) + .create_async() + .await; + + let provider = test_provider(&server.url(), &aws_refresh_props("/v1/credentials")).await; + + for _ in 0..2 { + let credential = provider.load_credential("s3://bucket/x/f").await.unwrap(); + assert_eq!(s3_access_key_id(&credential), "AK"); + } + mock.assert_async().await; + } + + #[tokio::test] + async fn refreshed_credentials_must_be_complete() { + let mut server = Server::new_async().await; + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body( + r#"{"storage-credentials":[{"prefix":"s3://bucket","config":{"s3.access-key-id":"AK","s3.secret-access-key":"SK"}}]}"#, + ) + .create_async() + .await; + + let provider = test_provider(&server.url(), &aws_refresh_props("/v1/credentials")).await; + let error = provider + .load_credential("s3://bucket/x/f") + .await + .unwrap_err(); + assert!(error.message().contains("is missing or empty"), "{error}"); + mock.assert_async().await; + } + + #[tokio::test] + async fn prefixes_match_locations_like_java() { + let mut server = Server::new_async().await; + let body = s3_response( + "s3://bucket/table", + "AK", + SystemTime::now() + Duration::from_secs(3600), + ); + let mock = server + .mock("GET", "/v1/credentials") + .expect(2) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(body) + .create_async() + .await; + + let provider = test_provider(&server.url(), &aws_refresh_props("/v1/credentials")).await; + // As in Java, prefixes are compared as plain strings. + for path in ["s3://bucket/table/f", "s3://bucket/table2/f"] { + assert_eq!( + s3_access_key_id(&provider.load_credential(path).await.unwrap()), + "AK" + ); + } + // `s3a` is another scheme, so this path is not covered and refreshes. + assert!( + provider + .load_credential("s3a://bucket/table/f") + .await + .is_err() + ); + mock.assert_async().await; + } + + #[tokio::test] + async fn serialized_provider_reconnects_from_properties() { + let mut server = Server::new_async().await; + let body = s3_response( + "s3://bucket", + "AK", + SystemTime::now() + Duration::from_secs(3600), + ); + let mock = server + .mock("GET", "/v1/credentials") + .match_header("authorization", "Bearer table-token") + .match_header("x-custom", "value") + .expect(2) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(body) + .create_async() + .await; + + let mut props = aws_refresh_props("/v1/credentials"); + props.extend([ + ("token".to_string(), "catalog-token".to_string()), + ("header.x-custom".to_string(), "value".to_string()), + ]); + let table_auth = HashMap::from([("token".to_string(), "table-token".to_string())]); + let provider = build_vended_credential_provider( + &test_client(&server.url()), + &OAuth2Manager::new(format!("{}/v1/oauth/tokens", server.url())), + async || Ok(Arc::new(NoopSession) as Arc), + test_factory(&server.url(), Some(&table_auth)), + &props, + &table_auth, + true, + ) + .await + .unwrap() + .unwrap(); + provider.load_credential("s3://bucket/x/f").await.unwrap(); + + let factory: Arc = + serde_json::from_str(&serde_json::to_string(&provider.factory().unwrap()).unwrap()) + .unwrap(); + let config = StorageConfig::new().with_props(props); + let rebuilt = factory.build(&config).unwrap(); + + // The rebuilt provider authenticates like the original one. + assert_eq!( + s3_access_key_id(&rebuilt.load_credential("s3://bucket/x/f").await.unwrap()), + "AK" + ); + // The rebuilt provider is itself serializable. + assert!(rebuilt.factory().is_ok()); + mock.assert_async().await; + } + + #[tokio::test] + async fn table_token_authenticates_without_catalog_auth() { + let mut server = Server::new_async().await; + let body = s3_response( + "s3://bucket", + "AK", + SystemTime::now() + Duration::from_secs(3600), + ); + // As in Java, a table token authenticates credential requests of a + // catalog without auth, in process and after the provider is rebuilt. + let mock = server + .mock("GET", "/v1/credentials") + .match_header("authorization", "Bearer table-token") + .expect(2) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(body) + .create_async() + .await; + + let props = aws_refresh_props("/v1/credentials"); + let factory = RestVendedCredentialProviderFactory::new( + server.url(), + test_table(), + AUTH_TYPE_NONE, + true, + &HashMap::from([("token".to_string(), "table-token".to_string())]), + ); + let provider = build_vended_credential_provider( + &test_client(&server.url()), + &NoopAuthManager, + async || Ok(Arc::new(NoopSession) as Arc), + factory.clone(), + &props, + &HashMap::from([("token".to_string(), "table-token".to_string())]), + true, + ) + .await + .unwrap() + .unwrap(); + provider.load_credential("s3://bucket/x/f").await.unwrap(); + + let rebuilt = factory + .build(&StorageConfig::new().with_props(props)) + .unwrap(); + rebuilt.load_credential("s3://bucket/x/f").await.unwrap(); + mock.assert_async().await; + } + + #[tokio::test] + async fn explicit_no_auth_ignores_the_table_token() { + let mut server = Server::new_async().await; + // As in Java, an explicit `rest.auth.type=none` is not overridden by a + // table token, in process and after the provider is rebuilt. + let mock = server + .mock("GET", "/v1/credentials") + .match_header("authorization", Matcher::Missing) + .expect(2) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(s3_response( + "s3://bucket", + "AK", + SystemTime::now() + Duration::from_secs(3600), + )) + .create_async() + .await; + let table_config = HashMap::from([("token".to_string(), "table-token".to_string())]); + let props = aws_refresh_props("/v1/credentials"); + let factory = RestVendedCredentialProviderFactory::new( + server.url(), + test_table(), + AUTH_TYPE_NONE, + false, + &table_config, + ); + let provider = build_vended_credential_provider( + &test_client(&server.url()), + &NoopAuthManager, + async || Ok(Arc::new(NoopSession) as Arc), + factory.clone(), + &props, + &table_config, + true, + ) + .await + .unwrap() + .unwrap(); + provider.load_credential("s3://bucket/x/f").await.unwrap(); + let rebuilt = factory + .build(&StorageConfig::new().with_props(props)) + .unwrap(); + rebuilt.load_credential("s3://bucket/x/f").await.unwrap(); + mock.assert_async().await; + } + + #[tokio::test] + async fn injected_auth_manager_receives_the_whole_table_config() { + #[derive(Debug, Default)] + struct RecordingAuthManager(std::sync::Mutex>); + + #[async_trait] + impl AuthManager for RecordingAuthManager { + async fn init_session( + &self, + _client: &HttpClient, + _props: &HashMap, + ) -> Result> { + unreachable!("only table sessions are created") + } + + async fn catalog_session( + &self, + _client: &HttpClient, + _props: &HashMap, + ) -> Result> { + unreachable!("only table sessions are created") + } + + async fn table_session( + &self, + _client: &HttpClient, + _table: &TableIdent, + props: &HashMap, + parent: Arc, + ) -> Result> { + let mut keys = props.keys().cloned().collect::>(); + keys.sort(); + *self.0.lock().unwrap() = keys; + Ok(parent) + } + } + + let manager = RecordingAuthManager::default(); + let table_config = HashMap::from([ + ("token".to_string(), "table-token".to_string()), + ("custom.auth".to_string(), "value".to_string()), + ]); + build_vended_credential_provider( + &test_client("http://cat"), + &manager, + async || Ok(Arc::new(NoopSession) as Arc), + test_factory("http://cat", Some(&table_config)), + &aws_refresh_props("/v1/creds"), + &table_config, + false, + ) + .await + .unwrap() + .unwrap(); + + assert_eq!(*manager.0.lock().unwrap(), vec![ + "custom.auth".to_string(), + "token".to_string() + ]); + } + + #[tokio::test] + async fn injected_auth_manager_decides_on_the_table_token() { + let mut server = Server::new_async().await; + let mock = server + .mock("GET", "/v1/credentials") + .match_header("authorization", Matcher::Missing) + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(s3_response( + "s3://bucket", + "AK", + SystemTime::now() + Duration::from_secs(3600), + )) + .create_async() + .await; + let provider = build_vended_credential_provider( + &test_client(&server.url()), + &NoopAuthManager, + async || Ok(Arc::new(NoopSession) as Arc), + RestVendedCredentialProviderFactory::new( + server.url(), + test_table(), + AUTH_TYPE_NONE, + true, + &HashMap::from([("token".to_string(), "table-token".to_string())]), + ), + &aws_refresh_props("/v1/credentials"), + &HashMap::from([("token".to_string(), "table-token".to_string())]), + false, + ) + .await + .unwrap() + .unwrap(); + + provider.load_credential("s3://bucket/x/f").await.unwrap(); + mock.assert_async().await; + } + + #[test] + fn factory_keeps_only_table_auth_config() { + let factory = RestVendedCredentialProviderFactory::new( + "http://cat", + test_table(), + AUTH_TYPE_OAUTH2, + true, + &HashMap::from([ + ("token".to_string(), "table-token".to_string()), + (S3_SECRET_ACCESS_KEY.to_string(), "SECRET".to_string()), + ]), + ); + assert_eq!( + factory.table_auth, + HashMap::from([("token".to_string(), "table-token".to_string())]) + ); + } + + #[tokio::test] + async fn provider_with_injected_auth_manager_is_not_serializable() { + let provider = build_vended_credential_provider( + &test_client("http://cat"), + &NoopAuthManager, + async || Ok(Arc::new(NoopSession) as Arc), + test_factory("http://cat", None), + &aws_refresh_props("/v1/creds"), + &HashMap::new(), + false, + ) + .await + .unwrap() + .unwrap(); + + let error = provider.factory().unwrap_err(); + assert_eq!(error.kind(), ErrorKind::FeatureUnsupported); + assert!(error.message().contains("injected AuthManager"), "{error}"); + } + + #[test] + fn factory_debug_omits_table_auth() { + let factory = test_factory( + "http://cat", + Some(&HashMap::from([( + "token".to_string(), + "secret-token".to_string(), + )])), + ); + let debug = format!("{factory:?}"); + assert!(!debug.contains("secret-token"), "{debug}"); + } +} diff --git a/crates/catalog/rest/src/lib.rs b/crates/catalog/rest/src/lib.rs index 29a171de61..8bee2d2ef0 100644 --- a/crates/catalog/rest/src/lib.rs +++ b/crates/catalog/rest/src/lib.rs @@ -88,6 +88,7 @@ mod auth; mod catalog; mod client; +mod credential; pub use client::HttpClient; mod request; pub use request::{HttpRequest, HttpRequestBody}; diff --git a/crates/catalog/rest/src/types.rs b/crates/catalog/rest/src/types.rs index 390521229e..00ba4c37c0 100644 --- a/crates/catalog/rest/src/types.rs +++ b/crates/catalog/rest/src/types.rs @@ -101,7 +101,7 @@ impl From for Error { } } -#[derive(Debug, Serialize, Deserialize)] +#[derive(Serialize, Deserialize)] pub(super) struct TokenResponse { pub(super) access_token: String, pub(super) token_type: String, @@ -205,7 +205,7 @@ pub struct RenameTableRequest { pub destination: TableIdent, } -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "kebab-case")] /// Result returned when a table is successfully loaded or created. /// @@ -231,7 +231,18 @@ pub struct LoadTableResult { pub storage_credentials: Option>, } -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +impl std::fmt::Debug for LoadTableResult { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("LoadTableResult") + .field("metadata_location", &self.metadata_location) + .field("metadata", &self.metadata) + .field("config_keys", &self.config.keys().collect::>()) + .field("storage_credentials", &self.storage_credentials) + .finish_non_exhaustive() + } +} + +#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)] /// Storage credential for a specific location prefix. /// /// Indicates a storage location prefix where the credential is relevant. Clients should @@ -244,6 +255,27 @@ pub struct StorageCredential { pub config: HashMap, } +impl std::fmt::Debug for StorageCredential { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("StorageCredential") + .field("prefix", &self.prefix) + .field("config_keys", &self.config.keys().collect::>()) + .finish_non_exhaustive() + } +} + +#[derive(Deserialize)] +#[serde(rename_all = "kebab-case")] +/// Response from the table credentials endpoint +/// (`GET /v1/{prefix}/namespaces/{namespace}/tables/{table}/credentials`). +/// +/// Returns freshly vended storage credentials so clients can refresh temporary +/// credentials before they expire. +pub(crate) struct LoadCredentialsResponse { + /// Storage credentials, one entry per location prefix. + pub(crate) storage_credentials: Vec, +} + #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "kebab-case")] /// Request to create a new table in a namespace. diff --git a/crates/iceberg/public-api.txt b/crates/iceberg/public-api.txt index 5f87d98810..d62f262569 100644 --- a/crates/iceberg/public-api.txt +++ b/crates/iceberg/public-api.txt @@ -810,11 +810,13 @@ pub async fn iceberg::io::FileIO::delete_prefix(&self, path: impl core::convert: pub async fn iceberg::io::FileIO::delete_stream(&self, paths: impl futures_core::stream::Stream + core::marker::Send + 'static) -> iceberg::Result<()> pub fn iceberg::io::FileIO::deserialize_all(bytes: &[u8]) -> iceberg::Result pub async fn iceberg::io::FileIO::exists(&self, path: impl core::convert::AsRef) -> iceberg::Result +pub fn iceberg::io::FileIO::has_credential_provider(&self) -> bool pub fn iceberg::io::FileIO::new_input(&self, path: impl core::convert::AsRef) -> iceberg::Result pub fn iceberg::io::FileIO::new_output(&self, path: impl core::convert::AsRef) -> iceberg::Result pub fn iceberg::io::FileIO::new_with_fs() -> Self pub fn iceberg::io::FileIO::new_with_memory() -> Self pub fn iceberg::io::FileIO::serialize_all(&self) -> iceberg::Result> +pub fn iceberg::io::FileIO::without_credential_provider(&self) -> Self impl core::clone::Clone for iceberg::io::FileIO pub fn iceberg::io::FileIO::clone(&self) -> iceberg::io::FileIO impl core::fmt::Debug for iceberg::io::FileIO @@ -824,6 +826,7 @@ impl iceberg::io::FileIOBuilder pub fn iceberg::io::FileIOBuilder::build(self) -> iceberg::io::FileIO pub fn iceberg::io::FileIOBuilder::config(&self) -> &iceberg::io::StorageConfig pub fn iceberg::io::FileIOBuilder::new(factory: alloc::sync::Arc) -> Self +pub fn iceberg::io::FileIOBuilder::with_credential_provider(self, provider: alloc::sync::Arc) -> Self pub fn iceberg::io::FileIOBuilder::with_prop(self, key: impl alloc::string::ToString, value: impl alloc::string::ToString) -> Self pub fn iceberg::io::FileIOBuilder::with_props(self, args: impl core::iter::traits::collect::IntoIterator) -> Self impl core::clone::Clone for iceberg::io::FileIOBuilder @@ -927,6 +930,7 @@ impl core::fmt::Debug for iceberg::io::LocalFsStorageFactory pub fn iceberg::io::LocalFsStorageFactory::fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result impl iceberg::io::StorageFactory for iceberg::io::LocalFsStorageFactory pub fn iceberg::io::LocalFsStorageFactory::build(&self, _config: &iceberg::io::StorageConfig) -> iceberg::Result> +pub fn iceberg::io::LocalFsStorageFactory::build_with_credential_provider(&self, config: &iceberg::io::StorageConfig, _credential_provider: core::option::Option>) -> iceberg::Result> impl serde_core::ser::Serialize for iceberg::io::LocalFsStorageFactory pub fn iceberg::io::LocalFsStorageFactory::serialize<__S>(&self, __serializer: __S) -> core::result::Result<<__S as serde_core::ser::Serializer>::Ok, <__S as serde_core::ser::Serializer>::Error> where __S: serde_core::ser::Serializer impl<'de> serde_core::de::Deserialize<'de> for iceberg::io::LocalFsStorageFactory @@ -965,6 +969,7 @@ impl core::fmt::Debug for iceberg::io::MemoryStorageFactory pub fn iceberg::io::MemoryStorageFactory::fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result impl iceberg::io::StorageFactory for iceberg::io::MemoryStorageFactory pub fn iceberg::io::MemoryStorageFactory::build(&self, _config: &iceberg::io::StorageConfig) -> iceberg::Result> +pub fn iceberg::io::MemoryStorageFactory::build_with_credential_provider(&self, config: &iceberg::io::StorageConfig, _credential_provider: core::option::Option>) -> iceberg::Result> impl serde_core::ser::Serialize for iceberg::io::MemoryStorageFactory pub fn iceberg::io::MemoryStorageFactory::serialize<__S>(&self, __serializer: __S) -> core::result::Result<<__S as serde_core::ser::Serializer>::Ok, <__S as serde_core::ser::Serializer>::Error> where __S: serde_core::ser::Serializer impl<'de> serde_core::de::Deserialize<'de> for iceberg::io::MemoryStorageFactory @@ -1077,14 +1082,35 @@ impl serde_core::ser::Serialize for iceberg::io::StorageConfig pub fn iceberg::io::StorageConfig::serialize<__S>(&self, __serializer: __S) -> core::result::Result<<__S as serde_core::ser::Serializer>::Ok, <__S as serde_core::ser::Serializer>::Error> where __S: serde_core::ser::Serializer impl<'de> serde_core::de::Deserialize<'de> for iceberg::io::StorageConfig pub fn iceberg::io::StorageConfig::deserialize<__D>(__deserializer: __D) -> core::result::Result::Error> where __D: serde_core::de::Deserializer<'de> +pub struct iceberg::io::StorageCredential +impl iceberg::io::StorageCredential +pub fn iceberg::io::StorageCredential::config(&self) -> &std::collections::hash::map::HashMap +pub fn iceberg::io::StorageCredential::covers(&self, location: &str) -> bool +pub fn iceberg::io::StorageCredential::new(prefix: impl core::convert::Into, config: std::collections::hash::map::HashMap) -> Self +pub fn iceberg::io::StorageCredential::prefix(&self) -> &str +pub fn iceberg::io::StorageCredential::select<'a>(credentials: impl core::iter::traits::collect::IntoIterator, location: &str) -> core::option::Option<&'a Self> +impl core::clone::Clone for iceberg::io::StorageCredential +pub fn iceberg::io::StorageCredential::clone(&self) -> iceberg::io::StorageCredential +impl core::cmp::Eq for iceberg::io::StorageCredential +impl core::cmp::PartialEq for iceberg::io::StorageCredential +pub fn iceberg::io::StorageCredential::eq(&self, other: &iceberg::io::StorageCredential) -> bool +impl core::fmt::Debug for iceberg::io::StorageCredential +pub fn iceberg::io::StorageCredential::fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::marker::StructuralPartialEq for iceberg::io::StorageCredential pub const iceberg::io::ADLS_ACCOUNT_KEY: &str pub const iceberg::io::ADLS_ACCOUNT_NAME: &str pub const iceberg::io::ADLS_AUTHORITY_HOST: &str pub const iceberg::io::ADLS_CLIENT_ID: &str pub const iceberg::io::ADLS_CLIENT_SECRET: &str pub const iceberg::io::ADLS_CONNECTION_STRING: &str +pub const iceberg::io::ADLS_REFRESH_CREDENTIALS_ENABLED: &str +pub const iceberg::io::ADLS_REFRESH_CREDENTIALS_ENDPOINT: &str pub const iceberg::io::ADLS_SAS_TOKEN: &str +pub const iceberg::io::ADLS_SAS_TOKEN_EXPIRES_AT_MS_PREFIX: &str +pub const iceberg::io::ADLS_SAS_TOKEN_PREFIX: &str pub const iceberg::io::ADLS_TENANT_ID: &str +pub const iceberg::io::AWS_REFRESH_CREDENTIALS_ENABLED: &str +pub const iceberg::io::AWS_REFRESH_CREDENTIALS_ENDPOINT: &str pub const iceberg::io::CLIENT_REGION: &str pub const iceberg::io::GCS_ALLOW_ANONYMOUS: &str pub const iceberg::io::GCS_CREDENTIALS_JSON: &str @@ -1092,8 +1118,11 @@ pub const iceberg::io::GCS_DISABLE_CONFIG_LOAD: &str pub const iceberg::io::GCS_DISABLE_VM_METADATA: &str pub const iceberg::io::GCS_NO_AUTH: &str pub const iceberg::io::GCS_PROJECT_ID: &str +pub const iceberg::io::GCS_REFRESH_CREDENTIALS_ENABLED: &str +pub const iceberg::io::GCS_REFRESH_CREDENTIALS_ENDPOINT: &str pub const iceberg::io::GCS_SERVICE_HOST: &str pub const iceberg::io::GCS_TOKEN: &str +pub const iceberg::io::GCS_TOKEN_EXPIRES_AT: &str pub const iceberg::io::GCS_USER_PROJECT: &str pub const iceberg::io::HDFS_HADOOP_CONF_PREFIX: &str pub const iceberg::io::HDFS_HOST: &str @@ -1117,6 +1146,7 @@ pub const iceberg::io::S3_PATH_STYLE_ACCESS: &str pub const iceberg::io::S3_REGION: &str pub const iceberg::io::S3_SECRET_ACCESS_KEY: &str pub const iceberg::io::S3_SESSION_TOKEN: &str +pub const iceberg::io::S3_SESSION_TOKEN_EXPIRES_AT_MS: &str pub const iceberg::io::S3_SSE_KEY: &str pub const iceberg::io::S3_SSE_MD5: &str pub const iceberg::io::S3_SSE_TYPE: &str @@ -1168,12 +1198,21 @@ pub fn iceberg::io::MemoryStorage::read<'life0, 'life1, 'async_trait>(&'life0 se pub fn iceberg::io::MemoryStorage::reader<'life0, 'life1, 'async_trait>(&'life0 self, path: &'life1 str) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait pub fn iceberg::io::MemoryStorage::write<'life0, 'life1, 'async_trait>(&'life0 self, path: &'life1 str, bs: bytes::bytes::Bytes) -> core::pin::Pin> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait pub fn iceberg::io::MemoryStorage::writer<'life0, 'life1, 'async_trait>(&'life0 self, path: &'life1 str) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait +pub trait iceberg::io::StorageCredentialProvider: core::fmt::Debug + core::marker::Send + core::marker::Sync +pub fn iceberg::io::StorageCredentialProvider::factory(&self) -> iceberg::Result> +pub fn iceberg::io::StorageCredentialProvider::load_credential<'life0, 'life1, 'async_trait>(&'life0 self, path: &'life1 str) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait +pub fn iceberg::io::StorageCredentialProvider::supports_path(&self, path: &str) -> bool +pub trait iceberg::io::StorageCredentialProviderFactory: core::fmt::Debug + core::marker::Send + core::marker::Sync + typetag::Serialize + typetag::Deserialize +pub fn iceberg::io::StorageCredentialProviderFactory::build(&self, config: &iceberg::io::StorageConfig) -> iceberg::Result> pub trait iceberg::io::StorageFactory: core::fmt::Debug + core::marker::Send + core::marker::Sync + typetag::Serialize + typetag::Deserialize pub fn iceberg::io::StorageFactory::build(&self, config: &iceberg::io::StorageConfig) -> iceberg::Result> +pub fn iceberg::io::StorageFactory::build_with_credential_provider(&self, config: &iceberg::io::StorageConfig, credential_provider: core::option::Option>) -> iceberg::Result> impl iceberg::io::StorageFactory for iceberg::io::LocalFsStorageFactory pub fn iceberg::io::LocalFsStorageFactory::build(&self, _config: &iceberg::io::StorageConfig) -> iceberg::Result> +pub fn iceberg::io::LocalFsStorageFactory::build_with_credential_provider(&self, config: &iceberg::io::StorageConfig, _credential_provider: core::option::Option>) -> iceberg::Result> impl iceberg::io::StorageFactory for iceberg::io::MemoryStorageFactory pub fn iceberg::io::MemoryStorageFactory::build(&self, _config: &iceberg::io::StorageConfig) -> iceberg::Result> +pub fn iceberg::io::MemoryStorageFactory::build_with_credential_provider(&self, config: &iceberg::io::StorageConfig, _credential_provider: core::option::Option>) -> iceberg::Result> pub mod iceberg::memory pub struct iceberg::memory::MemoryCatalog impl core::fmt::Debug for iceberg::memory::MemoryCatalog diff --git a/crates/iceberg/src/io/file_io.rs b/crates/iceberg/src/io/file_io.rs index 42eec4db56..f1d73ea6bf 100644 --- a/crates/iceberg/src/io/file_io.rs +++ b/crates/iceberg/src/io/file_io.rs @@ -16,13 +16,14 @@ // under the License. use std::ops::Range; -use std::sync::{Arc, OnceLock}; +use std::sync::{Arc, Once, OnceLock}; use bytes::Bytes; use futures::{Stream, StreamExt}; use super::storage::{ - LocalFsStorageFactory, MemoryStorageFactory, Storage, StorageConfig, StorageFactory, + LocalFsStorageFactory, MemoryStorageFactory, Storage, StorageConfig, StorageCredentialProvider, + StorageCredentialProviderFactory, StorageFactory, }; use crate::Result; @@ -65,6 +66,8 @@ pub struct FileIO { config: StorageConfig, /// Factory for creating storage instances factory: Arc, + /// Optional provider of refreshable, backend-specific credentials + credential_provider: Option>, /// Cached storage instance (lazily initialized) storage: Arc>>, } @@ -80,15 +83,33 @@ mod _serde { pub(super) struct SerializableFileIO<'a> { pub(super) config: &'a StorageConfig, pub(super) factory: &'a Arc, + #[serde(skip_serializing_if = "Option::is_none")] + pub(super) credential_provider: Option, } #[derive(Deserialize)] pub(super) struct DeserializedFileIO { pub(super) config: StorageConfig, pub(super) factory: Arc, + /// Kept as JSON, so that a provider factory the receiving binary does + /// not link can be dropped instead of failing the whole `FileIO`. + #[serde(default)] + pub(super) credential_provider: Option, } } +/// Warns that a `FileIO` crossing a process boundary loses its credential +/// provider. Engines may serialize a `FileIO` per task, so each cause, tracked +/// by its own `warned`, is reported once. +fn warn_once_without_provider(warned: &'static Once, reason: impl FnOnce() -> String) { + warned.call_once(|| { + tracing::warn!( + "{}; its credentials will not be refreshed after deserialization", + reason() + ) + }); +} + impl FileIO { /// Create a new FileIO backed by in-memory storage. /// @@ -97,6 +118,7 @@ impl FileIO { Self { config: StorageConfig::new(), factory: Arc::new(MemoryStorageFactory), + credential_provider: None, storage: Arc::new(OnceLock::new()), } } @@ -108,6 +130,7 @@ impl FileIO { Self { config: StorageConfig::new(), factory: Arc::new(LocalFsStorageFactory), + credential_provider: None, storage: Arc::new(OnceLock::new()), } } @@ -123,14 +146,38 @@ impl FileIO { /// /// All storage configuration properties are included in the serialized representation. These /// properties may contain credentials or other sensitive values, so the returned bytes must be - /// protected in transit and at rest by the application embedding this crate. + /// protected in transit and at rest by the application embedding this crate. A serialized + /// credential provider may likewise carry catalog authentication and vended credentials. /// /// Storage factories are serialized through [`typetag`](https://docs.rs/typetag). Third-party /// factories must use `#[typetag::serde]` on their [`StorageFactory`] implementation. + /// + /// A credential provider is serialized as the + /// [`StorageCredentialProviderFactory`] returned by + /// [`StorageCredentialProvider::factory`], and rebuilt on deserialization. A provider that + /// cannot be rebuilt in another process is left out with a warning, as with + /// [`FileIO::without_credential_provider`]: the deserialized `FileIO` uses the credentials in + /// its configuration, which are not refreshed. Storage factories that hold their own + /// credential sources, such as a custom AWS credential loader, still fail to serialize, as + /// leaving them out would leave no credentials at all. pub fn serialize_all(&self) -> Result> { + let credential_provider = self.credential_provider.as_ref().and_then(|provider| { + provider + .factory() + .and_then(|factory| Ok(serde_json::to_value(factory)?)) + .inspect_err(|error| { + static WARNED: Once = Once::new(); + warn_once_without_provider(&WARNED, || { + format!("serializing FileIO without its credential provider: {error}") + }) + }) + .ok() + }); + Ok(serde_json::to_vec(&_serde::SerializableFileIO { config: &self.config, factory: &self.factory, + credential_provider, })?) } @@ -139,15 +186,81 @@ impl FileIO { /// The receiving binary must use a compatible crate version and link the concrete factory /// implementation so it is registered with `typetag`. Backend-specific requirements are /// documented by each storage factory implementation. + /// + /// A credential provider is rebuilt when the binary links its factory implementation, such as + /// a catalog's. Otherwise, or when rebuilding fails, the `FileIO` is deserialized without + /// it and logs a warning, as [`FileIO::serialize_all`] does. pub fn deserialize_all(bytes: &[u8]) -> Result { - let _serde::DeserializedFileIO { config, factory } = serde_json::from_slice(bytes)?; + let _serde::DeserializedFileIO { + config, + factory, + credential_provider, + } = serde_json::from_slice(bytes)?; + let credential_provider = credential_provider.and_then(|provider_factory| { + // The factory may hold credentials, and serde errors quote the + // offending value, so only its type is reported. + let factory_type = provider_factory + .get("type") + .and_then(serde_json::Value::as_str) + .unwrap_or("unknown") + .to_owned(); + match serde_json::from_value::>( + provider_factory, + ) { + Ok(provider_factory) => provider_factory + .build(&config) + .inspect_err(|error| { + static WARNED: Once = Once::new(); + warn_once_without_provider(&WARNED, || { + format!( + "deserializing FileIO without its credential provider, which \ + could not be rebuilt: {error}" + ) + }) + }) + .ok(), + Err(_) => { + static WARNED: Once = Once::new(); + warn_once_without_provider(&WARNED, || { + format!( + "deserializing FileIO without its credential provider, whose \ + factory {factory_type} is not linked or does not match this version" + ) + }); + None + } + } + }); Ok(Self { config, factory, + credential_provider, storage: Arc::new(OnceLock::new()), }) } + /// Returns whether this `FileIO` has a credential provider to refresh its storage credentials. + /// + /// A deserialized `FileIO` has none when its provider could not be serialized or rebuilt; see + /// [`FileIO::serialize_all`] and [`FileIO::deserialize_all`]. + pub fn has_credential_provider(&self) -> bool { + self.credential_provider.is_some() + } + + /// Returns a copy of this `FileIO` without its credential provider. + /// + /// The copy uses only the credentials in its storage configuration, which are not refreshed. + /// Use this to serialize a `FileIO` without its credential provider, even when the provider + /// could be rebuilt in another process. + pub fn without_credential_provider(&self) -> Self { + Self { + config: self.config.clone(), + factory: Arc::clone(&self.factory), + credential_provider: None, + storage: Arc::new(OnceLock::new()), + } + } + /// Get the storage configuration. pub fn config(&self) -> &StorageConfig { &self.config @@ -163,8 +276,11 @@ impl FileIO { return Ok(storage.clone()); } - // Build the storage - let storage = self.factory.build(&self.config)?; + // Build the storage, passing any credential provider so backends that + // support refreshable credentials can wire it into their operators. + let storage = self + .factory + .build_with_credential_provider(&self.config, self.credential_provider.clone())?; // Try to set it (another thread might have set it first) let _ = self.storage.set(storage.clone()); @@ -247,6 +363,8 @@ pub struct FileIOBuilder { factory: Arc, /// Storage configuration config: StorageConfig, + /// Optional provider of refreshable, backend-specific credentials + credential_provider: Option>, } impl FileIOBuilder { @@ -255,6 +373,7 @@ impl FileIOBuilder { Self { factory, config: StorageConfig::new(), + credential_provider: None, } } @@ -280,11 +399,25 @@ impl FileIOBuilder { &self.config } + /// Attach a provider of refreshable, backend-specific credentials. + /// + /// Storage factories that cannot use the provider ignore it and use the + /// credentials in the configuration; the default implementation logs a + /// warning when it does. + pub fn with_credential_provider( + mut self, + provider: Arc, + ) -> Self { + self.credential_provider = Some(provider); + self + } + /// Builds [`FileIO`]. pub fn build(self) -> FileIO { FileIO { config: self.config, factory: self.factory, + credential_provider: self.credential_provider, storage: Arc::new(OnceLock::new()), } } @@ -442,18 +575,80 @@ impl OutputFile { #[cfg(test)] mod tests { + use std::collections::HashMap; use std::fs::{File, create_dir_all}; use std::io::Write; use std::path::Path; use std::sync::Arc; + use std::sync::atomic::{AtomicBool, Ordering}; + use async_trait::async_trait; use bytes::Bytes; use futures::AsyncReadExt; use futures::io::AllowStdIo; + use serde::{Deserialize, Serialize}; use tempfile::TempDir; use super::{FileIO, FileIOBuilder}; - use crate::io::{LocalFsStorageFactory, MemoryStorageFactory}; + use crate::Result; + use crate::io::{ + GCS_TOKEN, LocalFsStorageFactory, MemoryStorageFactory, Storage, StorageConfig, + StorageCredential, StorageCredentialProvider, StorageCredentialProviderFactory, + StorageFactory, + }; + + #[derive(Debug)] + struct TestCredentialProvider; + + #[async_trait] + impl StorageCredentialProvider for TestCredentialProvider { + fn supports_path(&self, _path: &str) -> bool { + true + } + + async fn load_credential(&self, _path: &str) -> Result> { + unreachable!("unsupported factories must ignore the provider") + } + } + + /// A provider rebuilt from the `FileIO` configuration, like a catalog provider. + #[derive(Debug)] + struct PortableCredentialProvider { + endpoint: Option, + } + + #[async_trait] + impl StorageCredentialProvider for PortableCredentialProvider { + fn supports_path(&self, _path: &str) -> bool { + true + } + + async fn load_credential(&self, _path: &str) -> Result> { + Ok(Arc::new(StorageCredential::new( + "gs", + HashMap::from([( + GCS_TOKEN.to_string(), + self.endpoint.clone().unwrap_or_default(), + )]), + ))) + } + + fn factory(&self) -> Result> { + Ok(Arc::new(PortableCredentialProviderFactory)) + } + } + + #[derive(Debug, Serialize, Deserialize)] + struct PortableCredentialProviderFactory; + + #[typetag::serde] + impl StorageCredentialProviderFactory for PortableCredentialProviderFactory { + fn build(&self, config: &StorageConfig) -> Result> { + Ok(Arc::new(PortableCredentialProvider { + endpoint: config.get("endpoint").cloned(), + })) + } + } fn create_local_file_io() -> FileIO { FileIO::new_with_fs() @@ -601,6 +796,182 @@ mod tests { assert_eq!(file_io.config().get("key2"), Some(&"value2".to_string())); } + /// Memory storage that records whether it was given a credential provider. + #[derive(Debug, Default, Serialize, Deserialize)] + struct ProviderRecordingFactory { + #[serde(skip)] + received_provider: Arc, + } + + #[typetag::serde] + impl StorageFactory for ProviderRecordingFactory { + fn build(&self, config: &StorageConfig) -> Result> { + self.build_with_credential_provider(config, None) + } + + fn build_with_credential_provider( + &self, + config: &StorageConfig, + credential_provider: Option>, + ) -> Result> { + self.received_provider + .store(credential_provider.is_some(), Ordering::SeqCst); + MemoryStorageFactory.build(config) + } + } + + #[tokio::test] + async fn test_file_io_passes_credential_provider_to_factory() { + let received_provider = Arc::new(AtomicBool::new(false)); + let file_io = FileIOBuilder::new(Arc::new(ProviderRecordingFactory { + received_provider: Arc::clone(&received_provider), + })) + .with_credential_provider(Arc::new(TestCredentialProvider)) + .build(); + + file_io.exists("memory://file").await.unwrap(); + assert!(received_provider.load(Ordering::SeqCst)); + } + + /// Memory storage from a factory that implements only `build`, so it uses + /// the default `build_with_credential_provider`. + #[derive(Debug, Serialize, Deserialize)] + struct BuildOnlyFactory; + + #[typetag::serde] + impl StorageFactory for BuildOnlyFactory { + fn build(&self, config: &StorageConfig) -> Result> { + MemoryStorageFactory.build(config) + } + } + + #[tokio::test] + async fn test_file_io_ignores_credentials_for_unsupported_factory() { + let file_io = FileIOBuilder::new(Arc::new(BuildOnlyFactory)) + .with_credential_provider(Arc::new(TestCredentialProvider)) + .build(); + + file_io + .new_output("memory://file") + .unwrap() + .write("data".into()) + .await + .unwrap(); + assert!(file_io.exists("memory://file").await.unwrap()); + } + + #[test] + fn test_file_io_drops_unserializable_credential_provider() { + let file_io = FileIOBuilder::new(Arc::new(MemoryStorageFactory)) + .with_prop("s3.access-key-id", "static-key") + .with_credential_provider(Arc::new(TestCredentialProvider)) + .build(); + + let deserialized = FileIO::deserialize_all(&file_io.serialize_all().unwrap()).unwrap(); + assert!(!deserialized.has_credential_provider()); + assert_eq!( + deserialized.config().get("s3.access-key-id"), + Some(&"static-key".to_string()) + ); + assert_eq!( + file_io.serialize_all().unwrap(), + file_io + .without_credential_provider() + .serialize_all() + .unwrap() + ); + } + + /// A provider whose factory cannot be serialized. + #[derive(Debug)] + struct UnserializableFactoryProvider; + + #[async_trait] + impl StorageCredentialProvider for UnserializableFactoryProvider { + fn supports_path(&self, _path: &str) -> bool { + true + } + + async fn load_credential(&self, _path: &str) -> Result> { + unreachable!("serialization tests never load credentials") + } + + fn factory(&self) -> Result> { + Ok(Arc::new(UnserializableFactory)) + } + } + + #[derive(Debug, Deserialize)] + struct UnserializableFactory; + + impl Serialize for UnserializableFactory { + fn serialize( + &self, + _serializer: S, + ) -> std::result::Result { + Err(serde::ser::Error::custom("cannot serialize")) + } + } + + #[typetag::serde] + impl StorageCredentialProviderFactory for UnserializableFactory { + fn build(&self, _config: &StorageConfig) -> Result> { + unreachable!("never serialized") + } + } + + #[test] + fn test_file_io_drops_provider_whose_factory_fails_to_serialize() { + let file_io = FileIOBuilder::new(Arc::new(MemoryStorageFactory)) + .with_credential_provider(Arc::new(UnserializableFactoryProvider)) + .build(); + + let deserialized = FileIO::deserialize_all(&file_io.serialize_all().unwrap()).unwrap(); + assert!(!deserialized.has_credential_provider()); + } + + #[test] + fn test_file_io_deserializes_without_unknown_credential_provider() { + let file_io = FileIOBuilder::new(Arc::new(MemoryStorageFactory)) + .with_prop("s3.access-key-id", "static-key") + .with_credential_provider(Arc::new(PortableCredentialProvider { endpoint: None })) + .build(); + // A receiving binary that does not link the provider's factory. + let mut serialized: serde_json::Value = + serde_json::from_slice(&file_io.serialize_all().unwrap()).unwrap(); + serialized["credential_provider"]["type"] = "UnlinkedProviderFactory".into(); + + let deserialized = + FileIO::deserialize_all(&serde_json::to_vec(&serialized).unwrap()).unwrap(); + assert!(!deserialized.has_credential_provider()); + assert_eq!( + deserialized.config().get("s3.access-key-id"), + Some(&"static-key".to_string()) + ); + } + + #[tokio::test] + async fn test_file_io_rebuilds_credential_provider_after_serialization() { + let file_io = FileIOBuilder::new(Arc::new(MemoryStorageFactory)) + .with_prop("endpoint", "https://catalog/credentials") + .with_credential_provider(Arc::new(PortableCredentialProvider { endpoint: None })) + .build(); + + let deserialized = FileIO::deserialize_all(&file_io.serialize_all().unwrap()).unwrap(); + assert!(deserialized.has_credential_provider()); + let credential = deserialized + .credential_provider + .unwrap() + .load_credential("gs://bucket/file") + .await + .unwrap(); + // The provider is rebuilt from the deserialized configuration. + assert_eq!( + credential.config().get(GCS_TOKEN).map(String::as_str), + Some("https://catalog/credentials") + ); + } + #[tokio::test] async fn test_memory_file_io_serialization_roundtrip() { let file_io = FileIOBuilder::new(Arc::new(MemoryStorageFactory)) diff --git a/crates/iceberg/src/io/storage/config/azdls.rs b/crates/iceberg/src/io/storage/config/azdls.rs index a9541e7791..833254a2af 100644 --- a/crates/iceberg/src/io/storage/config/azdls.rs +++ b/crates/iceberg/src/io/storage/config/azdls.rs @@ -36,6 +36,14 @@ pub const ADLS_ACCOUNT_NAME: &str = "adls.account-name"; pub const ADLS_ACCOUNT_KEY: &str = "adls.account-key"; /// The shared access signature. pub const ADLS_SAS_TOKEN: &str = "adls.sas-token"; +/// Prefix for account-specific shared access signatures vended by a catalog. +pub const ADLS_SAS_TOKEN_PREFIX: &str = "adls.sas-token."; +/// Prefix for the epoch-millisecond expiration of an account-specific SAS token. +pub const ADLS_SAS_TOKEN_EXPIRES_AT_MS_PREFIX: &str = "adls.sas-token-expires-at-ms."; +/// Table property naming the endpoint a catalog serves to refresh vended ADLS credentials. +pub const ADLS_REFRESH_CREDENTIALS_ENDPOINT: &str = "adls.refresh-credentials-endpoint"; +/// Table property enabling refresh of vended ADLS credentials. Defaults to `true`. +pub const ADLS_REFRESH_CREDENTIALS_ENABLED: &str = "adls.refresh-credentials-enabled"; /// The tenant-id. pub const ADLS_TENANT_ID: &str = "adls.tenant-id"; /// The client-id. diff --git a/crates/iceberg/src/io/storage/config/gcs.rs b/crates/iceberg/src/io/storage/config/gcs.rs index 99867e5dfc..122c5cc2ad 100644 --- a/crates/iceberg/src/io/storage/config/gcs.rs +++ b/crates/iceberg/src/io/storage/config/gcs.rs @@ -41,6 +41,12 @@ pub const GCS_NO_AUTH: &str = "gcs.no-auth"; pub const GCS_CREDENTIALS_JSON: &str = "gcs.credentials-json"; /// Google Cloud Storage token. pub const GCS_TOKEN: &str = "gcs.oauth2.token"; +/// Epoch-millisecond timestamp at which the vended GCS OAuth2 token expires. +pub const GCS_TOKEN_EXPIRES_AT: &str = "gcs.oauth2.token-expires-at"; +/// Table property naming the endpoint a catalog serves to refresh vended GCS OAuth2 credentials. +pub const GCS_REFRESH_CREDENTIALS_ENDPOINT: &str = "gcs.oauth2.refresh-credentials-endpoint"; +/// Table property enabling refresh of vended GCS OAuth2 credentials. Defaults to `true`. +pub const GCS_REFRESH_CREDENTIALS_ENABLED: &str = "gcs.oauth2.refresh-credentials-enabled"; /// Option to skip signing requests (e.g. for public buckets/folders). pub const GCS_ALLOW_ANONYMOUS: &str = "gcs.allow-anonymous"; /// Option to skip loading the credential from GCE metadata server. @@ -105,7 +111,9 @@ impl TryFrom<&StorageConfig> for GcsConfig { } // GCS_NO_AUTH enables all anonymous/no-auth options - if props.get(GCS_NO_AUTH).is_some() { + if let Some(no_auth) = props.get(GCS_NO_AUTH) + && is_truthy(no_auth) + { cfg.allow_anonymous = true; cfg.disable_vm_metadata = true; cfg.disable_config_load = true; @@ -176,6 +184,17 @@ mod tests { assert!(gcs_config.disable_config_load); } + #[test] + fn test_gcs_config_no_auth_false() { + let storage_config = StorageConfig::new().with_prop(GCS_NO_AUTH, "false"); + + let gcs_config = GcsConfig::try_from(&storage_config).unwrap(); + + assert!(!gcs_config.allow_anonymous); + assert!(!gcs_config.disable_vm_metadata); + assert!(!gcs_config.disable_config_load); + } + #[test] fn test_gcs_config_allow_anonymous() { let storage_config = StorageConfig::new().with_prop(GCS_ALLOW_ANONYMOUS, "true"); diff --git a/crates/iceberg/src/io/storage/config/mod.rs b/crates/iceberg/src/io/storage/config/mod.rs index 8ea4af080e..bcb267c788 100644 --- a/crates/iceberg/src/io/storage/config/mod.rs +++ b/crates/iceberg/src/io/storage/config/mod.rs @@ -37,7 +37,7 @@ mod hf; mod oss; mod s3; -use std::collections::HashMap; +use std::collections::{BTreeSet, HashMap}; pub use azdls::*; pub use gcs::*; @@ -52,12 +52,22 @@ use serde::{Deserialize, Serialize}; /// This struct contains only configuration properties without specifying /// which storage backend to use. The storage type is determined by the /// explicit factory selection. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Default)] pub struct StorageConfig { /// Configuration properties for the storage backend props: HashMap, } +impl std::fmt::Debug for StorageConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // Property values may hold vended credentials (e.g. `s3.secret-access-key`, + // `s3.session-token`) + f.debug_struct("StorageConfig") + .field("keys", &self.props.keys().collect::>()) + .finish_non_exhaustive() + } +} + impl StorageConfig { /// Create a new empty StorageConfig. pub fn new() -> Self { diff --git a/crates/iceberg/src/io/storage/config/s3.rs b/crates/iceberg/src/io/storage/config/s3.rs index ae3bc4ba3b..87b4654912 100644 --- a/crates/iceberg/src/io/storage/config/s3.rs +++ b/crates/iceberg/src/io/storage/config/s3.rs @@ -36,10 +36,16 @@ pub const S3_ACCESS_KEY_ID: &str = "s3.access-key-id"; pub const S3_SECRET_ACCESS_KEY: &str = "s3.secret-access-key"; /// S3 session token (required when using temporary credentials). pub const S3_SESSION_TOKEN: &str = "s3.session-token"; +/// Epoch-millisecond timestamp at which the vended S3 session token expires. +pub const S3_SESSION_TOKEN_EXPIRES_AT_MS: &str = "s3.session-token-expires-at-ms"; /// S3 region. pub const S3_REGION: &str = "s3.region"; /// Region to use for the S3 client (takes precedence over [`S3_REGION`]). pub const CLIENT_REGION: &str = "client.region"; +/// Table property naming the endpoint a catalog serves to refresh vended AWS credentials. +pub const AWS_REFRESH_CREDENTIALS_ENDPOINT: &str = "client.refresh-credentials-endpoint"; +/// Table property enabling refresh of vended AWS credentials. Defaults to `true`. +pub const AWS_REFRESH_CREDENTIALS_ENABLED: &str = "client.refresh-credentials-enabled"; /// S3 Path Style Access. pub const S3_PATH_STYLE_ACCESS: &str = "s3.path-style-access"; /// S3 Server Side Encryption Type. diff --git a/crates/iceberg/src/io/storage/local_fs.rs b/crates/iceberg/src/io/storage/local_fs.rs index cb780e86e7..f65d8230e0 100644 --- a/crates/iceberg/src/io/storage/local_fs.rs +++ b/crates/iceberg/src/io/storage/local_fs.rs @@ -36,7 +36,7 @@ use serde::{Deserialize, Serialize}; use crate::error::invalid_data; use crate::io::{ FileMetadata, FileRead, FileWrite, InputFile, OutputFile, Storage, StorageConfig, - StorageFactory, + StorageCredentialProvider, StorageFactory, }; use crate::{Error, ErrorKind, Result}; @@ -318,6 +318,15 @@ impl StorageFactory for LocalFsStorageFactory { fn build(&self, _config: &StorageConfig) -> Result> { Ok(Arc::new(LocalFsStorage::new())) } + + /// Local filesystem storage needs no credentials. + fn build_with_credential_provider( + &self, + config: &StorageConfig, + _credential_provider: Option>, + ) -> Result> { + self.build(config) + } } #[cfg(test)] diff --git a/crates/iceberg/src/io/storage/memory.rs b/crates/iceberg/src/io/storage/memory.rs index fefa7973e8..7a151fb3c4 100644 --- a/crates/iceberg/src/io/storage/memory.rs +++ b/crates/iceberg/src/io/storage/memory.rs @@ -35,7 +35,7 @@ use serde::{Deserialize, Serialize}; use crate::error::invalid_data; use crate::io::{ FileMetadata, FileRead, FileWrite, InputFile, OutputFile, Storage, StorageConfig, - StorageFactory, + StorageCredentialProvider, StorageFactory, }; use crate::{Error, ErrorKind, Result}; @@ -242,6 +242,15 @@ impl StorageFactory for MemoryStorageFactory { fn build(&self, _config: &StorageConfig) -> Result> { Ok(Arc::new(MemoryStorage::new())) } + + /// In-memory storage needs no credentials. + fn build_with_credential_provider( + &self, + config: &StorageConfig, + _credential_provider: Option>, + ) -> Result> { + self.build(config) + } } /// File reader for in-memory storage. diff --git a/crates/iceberg/src/io/storage/mod.rs b/crates/iceberg/src/io/storage/mod.rs index 5276c7771f..4ddefc3c7f 100644 --- a/crates/iceberg/src/io/storage/mod.rs +++ b/crates/iceberg/src/io/storage/mod.rs @@ -21,8 +21,9 @@ mod config; mod local_fs; mod memory; +use std::collections::{BTreeSet, HashMap}; use std::fmt::Debug; -use std::sync::Arc; +use std::sync::{Arc, Mutex, PoisonError}; use async_trait::async_trait; use bytes::Bytes; @@ -32,7 +33,7 @@ pub use local_fs::{LocalFsStorage, LocalFsStorageFactory}; pub use memory::{MemoryStorage, MemoryStorageFactory}; use super::{FileMetadata, FileRead, FileWrite, InputFile, OutputFile}; -use crate::Result; +use crate::{Error, ErrorKind, Result}; /// Trait for storage operations in Iceberg. /// @@ -139,4 +140,250 @@ pub trait StorageFactory: Debug + Send + Sync { /// A `Result` containing an `Arc` on success, or an error /// if the storage could not be created. fn build(&self, config: &StorageConfig) -> Result>; + + /// Build a new Storage instance, optionally supplying a credential provider + /// that the backend can call to obtain and refresh short-lived credentials. + /// + /// Backends that cannot use the provider ignore it and use the credentials + /// in `config`, as they would without one. The default does so and logs a + /// warning once per factory type, since the storage's credentials are then + /// not refreshed. Factories that wrap another factory should forward the + /// provider to it, and factories whose storage needs no credentials can + /// ignore it silently. + fn build_with_credential_provider( + &self, + config: &StorageConfig, + credential_provider: Option>, + ) -> Result> { + if credential_provider.is_some() { + // A static in a provided method is shared by every implementor. + static WARNED: Mutex> = Mutex::new(BTreeSet::new()); + let factory = std::any::type_name::(); + if WARNED + .lock() + .unwrap_or_else(PoisonError::into_inner) + .insert(factory) + { + tracing::warn!( + "{factory} ignores storage credential providers; its storage uses the \ + credentials in its configuration, which are not refreshed" + ); + } + } + self.build(config) + } +} + +/// Supplies fresh, backend-specific storage credentials on demand. +/// +/// A catalog that vends temporary credentials implements this trait so that +/// storage backends can re-fetch credentials as they approach expiry instead +/// of failing once the initial token's TTL runs out. +/// +/// # Debug output +/// +/// [`FileIO`](crate::io::FileIO) and storage implementations print the +/// provider in their `Debug` output, so the provider's `Debug` implementation +/// must not expose credentials or other secrets. +/// +/// # Caching +/// +/// [`load_credential`](Self::load_credential) may be called very frequently. +/// Implementations must cache internally and only re-fetch when the current +/// credential is at or near expiry; otherwise every object-store request could +/// trigger a call back to the catalog. Returning the cached [`Arc`] keeps each +/// call from copying the credential. +/// +/// Backends may treat a credential as stale before it expires, and load +/// another on every request until they get a fresher one. The OpenDAL S3 and +/// GCS backends do so within two minutes of expiry, and reject a newly loaded +/// credential that expires within ten seconds. Implementations should +/// therefore refresh early enough that the credential they return has more +/// than two minutes left. +#[async_trait] +pub trait StorageCredentialProvider: Debug + Send + Sync { + /// Return whether this provider supplies credentials for `path`. + /// + /// Backends replace their own credential chain with the provider only for + /// paths it supports, so a provider must return `false` for the storage it + /// does not serve, such as other schemes behind a resolving storage. + fn supports_path(&self, path: &str) -> bool; + + /// Load a fresh credential for the storage location identified by `path`. + /// + /// `path` is an absolute location: usually the file being accessed, such + /// as `s3://bucket/warehouse/db/table/data/file.parquet`, but for a bulk + /// delete the location shared by a batch, which may be a storage root + /// (`s3://bucket/`) or the prefix of a previously returned credential + /// (`s3://bucket/warehouse/db/table`). Providers that vend distinct + /// credentials per location prefix use it to select the most specific + /// match with [`StorageCredential::select`], which must + /// [cover](StorageCredential::covers) `path`. + /// + /// Backends read the credential's expiry from its config, such as + /// `s3.session-token-expires-at-ms`, and load a new one before it expires. + /// A credential without an expiry is used for as long as the backend lives. + /// + /// An error, or a credential that does not cover `path`, fails the request: + /// backends do not fall back to other credentials. Backends log such + /// failures only at debug level, since they recur on every request while a + /// provider is failing, so implementations should log their own, such as + /// once per failed refresh. + async fn load_credential(&self, path: &str) -> Result>; + + /// Return a factory that rebuilds an equivalent provider in another process. + /// + /// [`FileIO::serialize_all`](crate::io::FileIO::serialize_all) serializes this + /// factory in place of the provider. On an error, which the default always + /// returns, it serializes the `FileIO` without the provider and logs a + /// warning. + fn factory(&self) -> Result> { + Err(Error::new( + ErrorKind::FeatureUnsupported, + "storage credential provider cannot be serialized", + )) + } +} + +/// Serializable recipe that rebuilds a [`StorageCredentialProvider`] after +/// [`FileIO`](crate::io::FileIO) deserialization. +/// +/// Factories are serialized through [`typetag`](https://docs.rs/typetag), so +/// implementations must use `#[typetag::serde]`, and the receiving binary must +/// link the concrete implementation. +#[typetag::serde(tag = "type")] +pub trait StorageCredentialProviderFactory: Debug + Send + Sync { + /// Build a provider for a `FileIO` with the given storage configuration. + fn build(&self, config: &StorageConfig) -> Result>; +} + +/// A vended storage credential: the storage properties that apply to +/// locations under a prefix, like Java's `StorageCredential`. +/// +/// `config` holds backend storage properties, such as `s3.access-key-id`, +/// `s3.secret-access-key`, `s3.session-token` and +/// `s3.session-token-expires-at-ms`. Backends read their credential and its +/// expiry from it. +#[derive(Clone, PartialEq, Eq)] +pub struct StorageCredential { + /// Storage-location prefix this credential applies to, such as + /// `s3://bucket/table` or, for a whole scheme, `s3`. + prefix: String, + /// Backend storage properties holding the credential. + config: HashMap, +} + +impl StorageCredential { + /// Create a credential for locations under `prefix`. + /// + /// An empty prefix covers no location; Java rejects one outright. + pub fn new(prefix: impl Into, config: HashMap) -> Self { + Self { + prefix: prefix.into(), + config, + } + } + + /// Return the storage-location prefix this credential applies to. + pub fn prefix(&self) -> &str { + &self.prefix + } + + /// Return the storage properties holding the credential. + pub fn config(&self) -> &HashMap { + &self.config + } + + /// Return whether this credential applies to `location`. + /// + /// As in Java, `location` must start with the non-empty prefix, compared + /// as plain strings: `s3` covers every `s3://`, `s3a://` and `s3n://` + /// location, and `s3://bucket/tab` covers `s3://bucket/table`. + pub fn covers(&self, location: &str) -> bool { + !self.prefix.is_empty() && location.starts_with(&self.prefix) + } + + /// Return the credential with the longest prefix that covers `location`. + pub fn select<'a>( + credentials: impl IntoIterator, + location: &str, + ) -> Option<&'a Self> { + credentials + .into_iter() + .filter(|credential| credential.covers(location)) + .max_by_key(|credential| credential.prefix.len()) + } +} + +impl Debug for StorageCredential { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // Config values are secrets. Keys are sorted for stable output. + let config_keys: BTreeSet<_> = self.config.keys().collect(); + f.debug_struct("StorageCredential") + .field("prefix", &self.prefix) + .field("config_keys", &config_keys) + .finish() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn scoped(prefix: &str) -> StorageCredential { + StorageCredential::new( + prefix, + HashMap::from([("k".to_string(), "secret".to_string())]), + ) + } + + #[test] + fn test_credential_prefix_matches_like_java() { + let credential = scoped("s3://bucket/table"); + assert!(credential.covers("s3://bucket/table")); + assert!(credential.covers("s3://bucket/table/data/file.parquet")); + assert!(credential.covers("s3://bucket/table2/file.parquet")); + assert!(!credential.covers("s3://bucket/tab")); + assert!(!credential.covers("s3a://bucket/table/file.parquet")); + + // A scheme prefix covers every location with that scheme, including + // `s3a` and `s3n`. + assert!(scoped("s3").covers("s3a://bucket/file.parquet")); + assert!(!scoped("s3").covers("gs://bucket/file.parquet")); + assert!(!scoped("").covers("s3://bucket/file.parquet")); + } + + #[test] + fn test_select_prefers_the_longest_covering_prefix() { + let credentials = [ + scoped("s3"), + scoped("s3://bucket/table"), + scoped("s3://bucket"), + scoped("s3://other"), + ]; + let select = |location| { + StorageCredential::select(&credentials, location).map(StorageCredential::prefix) + }; + + assert_eq!(select("s3://bucket/table/file"), Some("s3://bucket/table")); + assert_eq!(select("s3://bucket/other/file"), Some("s3://bucket")); + assert_eq!(select("s3a://bucket/table/file"), Some("s3")); + assert_eq!(select("gs://bucket/table/file"), None); + } + + #[test] + fn test_credential_debug_omits_config_values() { + let debug = format!("{:?}", scoped("s3://bucket")); + assert!(debug.contains("s3://bucket"), "{debug}"); + assert!(!debug.contains("secret"), "{debug}"); + + let credential = StorageCredential::new( + "s3", + HashMap::from([ + ("b".to_string(), String::new()), + ("a".to_string(), String::new()), + ]), + ); + assert!(format!("{credential:?}").contains(r#"{"a", "b"}"#)); + } } diff --git a/crates/storage/opendal/Cargo.toml b/crates/storage/opendal/Cargo.toml index 83541e89c5..0dd5f79fa6 100644 --- a/crates/storage/opendal/Cargo.toml +++ b/crates/storage/opendal/Cargo.toml @@ -39,9 +39,19 @@ opendal-all = [ "opendal-hf", ] -opendal-azdls = ["opendal/services-azdls"] +opendal-azdls = [ + "opendal/services-azdls", + "reqsign-azure-storage", + "reqsign-core", + "dep:tracing", +] opendal-fs = ["opendal/services-fs"] -opendal-gcs = ["opendal/services-gcs"] +opendal-gcs = [ + "opendal/services-gcs", + "reqsign-google", + "reqsign-core", + "dep:tracing", +] opendal-hdfs-native = [ "opendal/services-hdfs-native", "dep:tokio", @@ -50,7 +60,12 @@ opendal-hdfs-native = [ opendal-hf = ["opendal/services-hf"] opendal-memory = ["opendal/services-memory"] opendal-oss = ["opendal/services-oss"] -opendal-s3 = ["opendal/services-s3", "reqsign-aws-v4", "reqsign-core"] +opendal-s3 = [ + "opendal/services-s3", + "reqsign-aws-v4", + "reqsign-core", + "dep:tracing", +] [dependencies] anyhow = { workspace = true } @@ -62,7 +77,9 @@ iceberg = { workspace = true } iceberg-property-macro = { workspace = true } opendal = { workspace = true } reqsign-aws-v4 = { version = "3.0.0", optional = true } -reqsign-core = { version = "3.0.0", optional = true } +reqsign-azure-storage = { version = "3.2.1", optional = true } +reqsign-core = { version = "3.3.1", optional = true } +reqsign-google = { version = "3.0.4", optional = true } serde = { workspace = true } tokio = { workspace = true, optional = true } tracing = { workspace = true, optional = true } @@ -72,6 +89,7 @@ url = { workspace = true } [dev-dependencies] async-trait = { workspace = true } iceberg_test_utils = { path = "../../test_utils", features = ["tests"] } +mockito = { workspace = true } reqwest = { workspace = true } serde_json = { workspace = true } tempfile = { workspace = true } diff --git a/crates/storage/opendal/public-api.txt b/crates/storage/opendal/public-api.txt index 797d90d1e8..e56b8f99d1 100644 --- a/crates/storage/opendal/public-api.txt +++ b/crates/storage/opendal/public-api.txt @@ -1,28 +1,32 @@ pub mod iceberg_storage_opendal pub use iceberg_storage_opendal::AwsCredential pub use iceberg_storage_opendal::ProvideCredential -pub enum iceberg_storage_opendal::OpenDalStorage -pub iceberg_storage_opendal::OpenDalStorage::Azdls +#[non_exhaustive] pub enum iceberg_storage_opendal::OpenDalStorage +#[non_exhaustive] pub iceberg_storage_opendal::OpenDalStorage::Azdls pub iceberg_storage_opendal::OpenDalStorage::Azdls::client_config: iceberg_storage_opendal::OpenDalClientConfig pub iceberg_storage_opendal::OpenDalStorage::Azdls::config: alloc::sync::Arc -pub iceberg_storage_opendal::OpenDalStorage::Gcs +pub iceberg_storage_opendal::OpenDalStorage::Azdls::credential_provider: core::option::Option> +pub iceberg_storage_opendal::OpenDalStorage::Azdls::sas_tokens: alloc::sync::Arc +#[non_exhaustive] pub iceberg_storage_opendal::OpenDalStorage::Gcs pub iceberg_storage_opendal::OpenDalStorage::Gcs::client_config: iceberg_storage_opendal::OpenDalClientConfig pub iceberg_storage_opendal::OpenDalStorage::Gcs::config: alloc::sync::Arc -pub iceberg_storage_opendal::OpenDalStorage::HdfsNative(iceberg_storage_opendal::HdfsNativeStorage) -pub iceberg_storage_opendal::OpenDalStorage::Hf +pub iceberg_storage_opendal::OpenDalStorage::Gcs::credential_provider: core::option::Option> +#[non_exhaustive] pub iceberg_storage_opendal::OpenDalStorage::HdfsNative(iceberg_storage_opendal::HdfsNativeStorage) +#[non_exhaustive] pub iceberg_storage_opendal::OpenDalStorage::Hf pub iceberg_storage_opendal::OpenDalStorage::Hf::client_config: iceberg_storage_opendal::OpenDalClientConfig pub iceberg_storage_opendal::OpenDalStorage::Hf::config: alloc::sync::Arc -pub iceberg_storage_opendal::OpenDalStorage::LocalFs +#[non_exhaustive] pub iceberg_storage_opendal::OpenDalStorage::LocalFs pub iceberg_storage_opendal::OpenDalStorage::LocalFs::client_config: iceberg_storage_opendal::OpenDalClientConfig -pub iceberg_storage_opendal::OpenDalStorage::Memory +#[non_exhaustive] pub iceberg_storage_opendal::OpenDalStorage::Memory pub iceberg_storage_opendal::OpenDalStorage::Memory::client_config: iceberg_storage_opendal::OpenDalClientConfig pub iceberg_storage_opendal::OpenDalStorage::Memory::operator: opendal_core::types::operator::operator::Operator -pub iceberg_storage_opendal::OpenDalStorage::Oss +#[non_exhaustive] pub iceberg_storage_opendal::OpenDalStorage::Oss pub iceberg_storage_opendal::OpenDalStorage::Oss::client_config: iceberg_storage_opendal::OpenDalClientConfig pub iceberg_storage_opendal::OpenDalStorage::Oss::config: alloc::sync::Arc -pub iceberg_storage_opendal::OpenDalStorage::S3 +#[non_exhaustive] pub iceberg_storage_opendal::OpenDalStorage::S3 pub iceberg_storage_opendal::OpenDalStorage::S3::client_config: iceberg_storage_opendal::OpenDalClientConfig pub iceberg_storage_opendal::OpenDalStorage::S3::config: alloc::sync::Arc +pub iceberg_storage_opendal::OpenDalStorage::S3::credential_provider: core::option::Option> pub iceberg_storage_opendal::OpenDalStorage::S3::customized_credential_load: core::option::Option impl core::clone::Clone for iceberg_storage_opendal::OpenDalStorage pub fn iceberg_storage_opendal::OpenDalStorage::clone(&self) -> iceberg_storage_opendal::OpenDalStorage @@ -60,6 +64,7 @@ impl core::fmt::Debug for iceberg_storage_opendal::OpenDalStorageFactory pub fn iceberg_storage_opendal::OpenDalStorageFactory::fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result impl iceberg::io::storage::StorageFactory for iceberg_storage_opendal::OpenDalStorageFactory pub fn iceberg_storage_opendal::OpenDalStorageFactory::build(&self, config: &iceberg::io::storage::config::StorageConfig) -> iceberg::error::Result> +pub fn iceberg_storage_opendal::OpenDalStorageFactory::build_with_credential_provider(&self, config: &iceberg::io::storage::config::StorageConfig, credential_provider: core::option::Option>) -> iceberg::error::Result> impl serde_core::ser::Serialize for iceberg_storage_opendal::OpenDalStorageFactory pub fn iceberg_storage_opendal::OpenDalStorageFactory::serialize<__S>(&self, __serializer: __S) -> core::result::Result<<__S as serde_core::ser::Serializer>::Ok, <__S as serde_core::ser::Serializer>::Error> where __S: serde_core::ser::Serializer impl<'de> serde_core::de::Deserialize<'de> for iceberg_storage_opendal::OpenDalStorageFactory @@ -124,6 +129,7 @@ impl core::fmt::Debug for iceberg_storage_opendal::OpenDalResolvingStorageFactor pub fn iceberg_storage_opendal::OpenDalResolvingStorageFactory::fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result impl iceberg::io::storage::StorageFactory for iceberg_storage_opendal::OpenDalResolvingStorageFactory pub fn iceberg_storage_opendal::OpenDalResolvingStorageFactory::build(&self, config: &iceberg::io::storage::config::StorageConfig) -> iceberg::error::Result> +pub fn iceberg_storage_opendal::OpenDalResolvingStorageFactory::build_with_credential_provider(&self, config: &iceberg::io::storage::config::StorageConfig, credential_provider: core::option::Option>) -> iceberg::error::Result> impl serde_core::ser::Serialize for iceberg_storage_opendal::OpenDalResolvingStorageFactory pub fn iceberg_storage_opendal::OpenDalResolvingStorageFactory::serialize<__S>(&self, __serializer: __S) -> core::result::Result<<__S as serde_core::ser::Serializer>::Ok, <__S as serde_core::ser::Serializer>::Error> where __S: serde_core::ser::Serializer impl<'de> serde_core::de::Deserialize<'de> for iceberg_storage_opendal::OpenDalResolvingStorageFactory diff --git a/crates/storage/opendal/src/azdls.rs b/crates/storage/opendal/src/azdls.rs index 88a197fea8..ed16053f60 100644 --- a/crates/storage/opendal/src/azdls.rs +++ b/crates/storage/opendal/src/azdls.rs @@ -18,18 +18,27 @@ use std::collections::HashMap; use std::fmt::Display; use std::str::FromStr; +use std::sync::Arc; use iceberg::io::{ ADLS_ACCOUNT_KEY, ADLS_ACCOUNT_NAME, ADLS_AUTHORITY_HOST, ADLS_CLIENT_ID, ADLS_CLIENT_SECRET, - ADLS_CONNECTION_STRING, ADLS_SAS_TOKEN, ADLS_TENANT_ID, + ADLS_CONNECTION_STRING, ADLS_SAS_TOKEN, ADLS_SAS_TOKEN_EXPIRES_AT_MS_PREFIX, + ADLS_SAS_TOKEN_PREFIX, ADLS_TENANT_ID, StorageCredentialProvider, }; use iceberg::{Error, ErrorKind, Result}; use opendal::Configurator; use opendal::services::AzdlsConfig; +use reqsign_azure_storage::Credential as AzureCredential; +use reqsign_core::{ + Context, Error as ReqsignError, ProvideCredential, ProvideCredentialChain, + Result as ReqsignResult, +}; use serde::{Deserialize, Serialize}; use url::Url; -use crate::utils::from_opendal_error; +use crate::utils::{ + VendedCredentialSource, credential_expiry, from_opendal_error, required_credential_property, +}; /// Local version of `ensure_data_valid` macro since the iceberg crate's macro /// uses `$crate::error::Error` paths that don't resolve from external crates @@ -84,6 +93,60 @@ pub(crate) fn azdls_config_parse(mut properties: HashMap) -> Res Ok(config) } +/// Account-specific ADLS SAS tokens supplied through Java-compatible storage +/// properties. +/// +/// Public only because [`OpenDalStorage::Azdls`](crate::OpenDalStorage::Azdls) +/// holds it; it is built from the storage configuration. +#[doc(hidden)] +#[derive(Clone, Default, Serialize, Deserialize)] +pub struct AzdlsSasTokens(HashMap); + +impl AzdlsSasTokens { + /// Collect `adls.sas-token.` properties by key suffix. + pub(crate) fn from_properties(properties: &HashMap) -> Self { + Self( + properties + .iter() + .filter_map(|(key, value)| { + let suffix = key.strip_prefix(ADLS_SAS_TOKEN_PREFIX)?; + (!suffix.is_empty() && !value.is_empty()) + .then(|| (suffix.to_string(), value.clone())) + }) + .collect(), + ) + } + + pub(crate) fn is_empty(&self) -> bool { + self.0.is_empty() + } + + /// The token for `path`, selected as by [`sas_token_suffixes`]. + fn for_path(&self, path: &AzureStoragePath) -> Option<&str> { + sas_token_suffixes(path) + .iter() + .find_map(|suffix| self.0.get(suffix)) + .map(String::as_str) + } +} + +/// Suffixes of the `adls.sas-token.` properties that may hold the SAS +/// token for `path`, most specific first: the exact host, as in Java, then the +/// account alone, as sent for older Java versions and PyIceberg. A key that +/// names only the account matches every host of an account with that name, +/// including one in another cloud; a host-keyed token matches only its host. +fn sas_token_suffixes(path: &AzureStoragePath) -> [String; 2] { + [path.host(), path.account_name.clone()] +} + +impl std::fmt::Debug for AzdlsSasTokens { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("AzdlsSasTokens") + .field("token_count", &self.0.len()) + .finish_non_exhaustive() + } +} + /// Builds an OpenDAL operator from the AzdlsConfig and path. /// /// The path is expected to include the scheme in a format like: @@ -91,11 +154,21 @@ pub(crate) fn azdls_config_parse(mut properties: HashMap) -> Res pub(crate) fn azdls_create_operator<'a>( absolute_path: &'a str, config: &AzdlsConfig, + sas_tokens: &AzdlsSasTokens, + credential_provider: &Option>, + credential_location: Option<&str>, ) -> Result<(opendal::Operator, &'a str)> { let path = absolute_path.parse::()?; match_path_with_config(&path, config)?; - let op = azdls_config_build(config, &path)?; + let op = azdls_config_build( + config, + &path, + sas_tokens, + credential_provider, + absolute_path, + credential_location, + )?; // Paths to files in ADLS tend to be written in fully qualified form, // including their filesystem and account name. @@ -109,8 +182,9 @@ pub(crate) fn azdls_create_operator<'a>( /// Note that `abf[s]` and `wasb[s]` variants have different implications: /// - `abfs[s]` is used to refer to files in ADLS Gen2, backed by blob storage; /// paths are expected to contain the `dfs` storage service. -/// - `wasb[s]` is used to refer to files in Blob Storage directly; paths are -/// expected to contain the `blob` storage service. +/// - `wasb[s]` is accepted for compatibility with Blob Storage locations; +/// paths contain the `blob` storage service, but operations still use the +/// ADLS Gen2 `dfs` endpoint, matching Iceberg Java. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum AzureStorageScheme { Abfs, @@ -120,12 +194,9 @@ pub enum AzureStorageScheme { } impl AzureStorageScheme { - // Returns the respective encrypted or plain-text HTTP scheme. - pub fn as_http_scheme(&self) -> &str { - match self { - AzureStorageScheme::Abfs | AzureStorageScheme::Wasb => "http", - AzureStorageScheme::Abfss | AzureStorageScheme::Wasbs => "https", - } + /// Whether an explicitly configured endpoint must use TLS. + fn requires_tls(&self) -> bool { + matches!(self, AzureStorageScheme::Abfss | AzureStorageScheme::Wasbs) } } @@ -169,12 +240,13 @@ pub(crate) fn match_path_with_config(path: &AzureStoragePath, config: &AzdlsConf } if let Some(ref configured_endpoint) = config.endpoint { - let passed_http_scheme = path.scheme.as_http_scheme(); + // An explicit plaintext endpoint, such as a local emulator, remains + // valid for the non-secure schemes. ensure_data_valid!( - configured_endpoint.starts_with(passed_http_scheme), - "Storage::Azdls: Endpoint {} does not use the expected http scheme {}.", + !path.scheme.requires_tls() || configured_endpoint.starts_with("https://"), + "Storage::Azdls: Endpoint {} does not use https, which the {} scheme requires.", configured_endpoint, - passed_http_scheme + path.scheme ); let ends_with_expected_suffix = configured_endpoint @@ -191,7 +263,14 @@ pub(crate) fn match_path_with_config(path: &AzureStoragePath, config: &AzdlsConf Ok(()) } -fn azdls_config_build(config: &AzdlsConfig, path: &AzureStoragePath) -> Result { +fn azdls_config_build( + config: &AzdlsConfig, + path: &AzureStoragePath, + sas_tokens: &AzdlsSasTokens, + credential_provider: &Option>, + absolute_path: &str, + credential_location: Option<&str>, +) -> Result { let mut builder = config.clone().into_builder(); if config.endpoint.is_none() { @@ -200,9 +279,76 @@ fn azdls_config_build(config: &AzdlsConfig, path: &AzureStoragePath) -> Result ReqsignResult> { + let credential = self + .source + .load("ADLS", |config| { + let suffix = self + .sas_token_suffixes + .iter() + .find(|suffix| { + config + .get(&format!("{ADLS_SAS_TOKEN_PREFIX}{suffix}")) + .is_some_and(|token| !token.is_empty()) + }) + .ok_or_else(|| { + ReqsignError::unexpected(format!( + "vended credential is missing {ADLS_SAS_TOKEN_PREFIX}{}", + self.sas_token_suffixes[0] + )) + })?; + let sas_token = required_credential_property( + config, + &format!("{ADLS_SAS_TOKEN_PREFIX}{suffix}"), + )?; + Ok( + match credential_expiry( + config, + &format!("{ADLS_SAS_TOKEN_EXPIRES_AT_MS_PREFIX}{suffix}"), + )? { + Some(expires_at) => { + AzureCredential::with_sas_token_expires_at(sas_token, expires_at) + } + None => AzureCredential::with_sas_token(sas_token), + }, + ) + }) + .await?; + Ok(Some(credential)) + } +} + /// Represents a fully qualified path to blob/ file in Azure Storage. #[derive(Debug, PartialEq)] pub(crate) struct AzureStoragePath { @@ -225,16 +371,24 @@ pub(crate) struct AzureStoragePath { } impl AzureStoragePath { + /// The host of the path, e.g. `account.dfs.core.windows.net`. + fn host(&self) -> String { + let service = match self.scheme { + AzureStorageScheme::Abfs | AzureStorageScheme::Abfss => "dfs", + AzureStorageScheme::Wasb | AzureStorageScheme::Wasbs => "blob", + }; + format!("{}.{service}.{}", self.account_name, self.endpoint_suffix) + } + /// Converts the AzureStoragePath into a full endpoint URL. /// /// This is possible because the path is fully qualified. + /// + /// Like Iceberg Java, the endpoint always uses TLS, also for the + /// non-secure schemes: SAS tokens are query parameters and must not be + /// sent over a plaintext connection unless the user configures one. fn as_endpoint(&self) -> String { - format!( - "{}://{}.dfs.{}", - self.scheme.as_http_scheme(), - self.account_name, - self.endpoint_suffix - ) + format!("https://{}.dfs.{}", self.account_name, self.endpoint_suffix) } /// The part of `absolute_path` below the filesystem, without a leading `/`, @@ -271,6 +425,14 @@ impl FromStr for AzureStoragePath { } } +pub(crate) fn azdls_batch_key(absolute_path: &str) -> Result { + let path = absolute_path.parse::()?; + Ok(format!( + "{}://{}@{}.{}", + path.scheme, path.filesystem, path.account_name, path.endpoint_suffix + )) +} + fn parse_azure_storage_endpoint(url: &Url) -> Result<(&str, &str, &str)> { let host = url.host_str().ok_or(Error::new( ErrorKind::DataInvalid, @@ -324,10 +486,47 @@ fn validate_storage_and_scheme( #[cfg(test)] mod tests { use std::collections::HashMap; + use std::sync::Arc; + use async_trait::async_trait; + use iceberg::Result; + use iceberg::io::{ + ADLS_SAS_TOKEN_EXPIRES_AT_MS_PREFIX, ADLS_SAS_TOKEN_PREFIX, StorageCredential, + StorageCredentialProvider, + }; use opendal::services::AzdlsConfig; + use reqsign_azure_storage::Credential as AzureCredential; + use reqsign_core::{Context, ProvideCredential}; + + use super::{ + AzdlsSasTokens, AzureStoragePath, AzureStorageScheme, VendedAzdlsCredentialProvider, + VendedCredentialSource, azdls_batch_key, azdls_config_parse, azdls_create_operator, + sas_token_suffixes, + }; + + fn adapter(credential: StorageCredential, path: &str) -> VendedAzdlsCredentialProvider { + VendedAzdlsCredentialProvider { + source: VendedCredentialSource::new( + Arc::new(FixedCredentialProvider(credential)), + path.to_string(), + ), + sas_token_suffixes: sas_token_suffixes(&path.parse().unwrap()), + } + } - use super::{AzureStoragePath, AzureStorageScheme, azdls_config_parse, azdls_create_operator}; + #[derive(Debug)] + struct FixedCredentialProvider(StorageCredential); + + #[async_trait] + impl StorageCredentialProvider for FixedCredentialProvider { + fn supports_path(&self, _path: &str) -> bool { + true + } + + async fn load_credential(&self, _path: &str) -> Result> { + Ok(Arc::new(self.0.clone())) + } + } #[test] fn test_azdls_config_parse() { @@ -427,6 +626,18 @@ mod tests { ), None, ), + ( + "plaintext endpoint for a non-secure scheme", + ( + "abfs://myfs@myaccount.dfs.core.windows.net/path/to/file.parquet", + AzdlsConfig { + account_name: Some("myaccount".to_string()), + endpoint: Some("http://myaccount.dfs.core.windows.net".to_string()), + ..Default::default() + }, + ), + Some(("myfs", "path/to/file.parquet")), + ), ( "incompatible scheme for endpoint", ( @@ -482,7 +693,8 @@ mod tests { ]; for (name, input, expected) in test_cases { - let result = azdls_create_operator(input.0, &input.1); + let result = + azdls_create_operator(input.0, &input.1, &AzdlsSasTokens::default(), &None, None); match expected { Some((expected_filesystem, expected_path)) => { assert!(result.is_ok(), "Test case {name} failed: {result:?}"); @@ -498,6 +710,373 @@ mod tests { } } + #[tokio::test] + async fn vended_provider_returns_expiring_sas_credential() { + let path = "abfss://container@account.dfs.core.windows.net/table/data.parquet"; + let host = "account.dfs.core.windows.net"; + let credential = StorageCredential::new( + "abfss://container@account.dfs.core.windows.net/table", + HashMap::from([ + ( + format!("{ADLS_SAS_TOKEN_PREFIX}{host}"), + "sv=2026&sig=host".to_string(), + ), + ( + format!("{ADLS_SAS_TOKEN_EXPIRES_AT_MS_PREFIX}{host}"), + "1500".to_string(), + ), + // The host-keyed token wins over the account-keyed one. + ( + format!("{ADLS_SAS_TOKEN_PREFIX}account"), + "sv=2026&sig=account".to_string(), + ), + ]), + ); + + let credential = adapter(credential, path) + .provide_credential(&Context::new()) + .await + .unwrap() + .unwrap(); + match credential { + AzureCredential::SasToken { token, expires_at } => { + assert_eq!(token, "sv=2026&sig=host"); + assert_eq!( + expires_at, + Some(reqsign_core::time::Timestamp::from_millisecond(1500).unwrap()) + ); + } + other => panic!("expected SAS token, got {other:?}"), + } + } + + #[test] + fn account_specific_sas_tokens_are_selected_by_storage_account() { + let properties = HashMap::from([ + ( + format!("{ADLS_SAS_TOKEN_PREFIX}first"), + "sv=2026&sig=first".to_string(), + ), + ( + format!("{ADLS_SAS_TOKEN_PREFIX}second"), + "sv=2026&sig=second".to_string(), + ), + ]); + let sas_tokens = AzdlsSasTokens::from_properties(&properties); + let path = "abfss://container@second.dfs.core.windows.net/table/data.parquet" + .parse::() + .unwrap(); + + assert_eq!(sas_tokens.for_path(&path), Some("sv=2026&sig=second")); + } + + #[test] + fn host_keyed_sas_tokens_match_java() { + let properties = HashMap::from([ + ( + format!("{ADLS_SAS_TOKEN_PREFIX}account.dfs.core.windows.net"), + "sv=2026&sig=host".to_string(), + ), + ( + format!("{ADLS_SAS_TOKEN_PREFIX}account"), + "sv=2026&sig=account".to_string(), + ), + ]); + let sas_tokens = AzdlsSasTokens::from_properties(&properties); + let token_for = |location: &str| { + sas_tokens + .for_path(&location.parse::().unwrap()) + .map(str::to_owned) + }; + + // The exact host wins over the account. + assert_eq!( + token_for("abfss://container@account.dfs.core.windows.net/table/data.parquet") + .as_deref(), + Some("sv=2026&sig=host") + ); + // Other hosts of the account fall back to the account-keyed token. + assert_eq!( + token_for("wasbs://container@account.blob.core.windows.net/table/data.parquet") + .as_deref(), + Some("sv=2026&sig=account") + ); + + // A host-keyed token is never sent to the same account name in another + // cloud. + let host_only = AzdlsSasTokens::from_properties(&HashMap::from([( + format!("{ADLS_SAS_TOKEN_PREFIX}account.dfs.core.windows.net"), + "sv=2026&sig=host".to_string(), + )])); + let other_cloud = "abfss://container@account.dfs.core.usgovcloudapi.net/data.parquet" + .parse::() + .unwrap(); + assert_eq!(host_only.for_path(&other_cloud), None); + } + + #[tokio::test] + async fn vended_provider_falls_back_to_the_account_token_when_the_host_token_is_empty() { + let path = "abfss://container@account.dfs.core.windows.net/table/data.parquet"; + let credential = StorageCredential::new( + "abfss://container@account.dfs.core.windows.net", + HashMap::from([ + ( + format!("{ADLS_SAS_TOKEN_PREFIX}account.dfs.core.windows.net"), + String::new(), + ), + ( + format!("{ADLS_SAS_TOKEN_PREFIX}account"), + "sv=2026&sig=account".to_string(), + ), + ]), + ); + + match adapter(credential, path) + .provide_credential(&Context::new()) + .await + .unwrap() + .unwrap() + { + AzureCredential::SasToken { token, .. } => assert_eq!(token, "sv=2026&sig=account"), + other => panic!("expected SAS token, got {other:?}"), + } + } + + /// Builds an ADLS operator for `path` that sends its requests to `server`. + fn operator_for( + server: &mockito::Server, + path: &str, + sas_tokens: &AzdlsSasTokens, + credential_provider: Option>, + ) -> opendal::Operator { + let config = AzdlsConfig { + endpoint: Some(server.url()), + ..Default::default() + }; + super::azdls_config_build( + &config, + &path.parse().unwrap(), + sas_tokens, + &credential_provider, + path, + None, + ) + .unwrap() + } + + #[tokio::test] + async fn operator_signs_with_the_vended_sas_token() { + let mut server = mockito::Server::new_async().await; + let mock = server + .mock("HEAD", mockito::Matcher::Any) + .match_query(mockito::Matcher::Regex("sig=vended".to_string())) + .expect_at_least(1) + .with_status(404) + .create_async() + .await; + let path = "abfss://container@account.dfs.core.windows.net/table/data.parquet"; + let credential = StorageCredential::new( + "abfss://container@account.dfs.core.windows.net", + HashMap::from([( + format!("{ADLS_SAS_TOKEN_PREFIX}account.dfs.core.windows.net"), + "sv=2026&sig=vended".to_string(), + )]), + ); + // A static token is not used when a provider supplies credentials. + let static_tokens = AzdlsSasTokens::from_properties(&HashMap::from([( + format!("{ADLS_SAS_TOKEN_PREFIX}account.dfs.core.windows.net"), + "sv=2026&sig=static".to_string(), + )])); + + let operator = operator_for( + &server, + path, + &static_tokens, + Some(Arc::new(FixedCredentialProvider(credential))), + ); + assert!(operator.stat("table/data.parquet").await.is_err()); + mock.assert_async().await; + } + + /// Fails every credential load. + #[derive(Debug)] + struct FailingCredentialProvider; + + #[async_trait] + impl StorageCredentialProvider for FailingCredentialProvider { + fn supports_path(&self, _path: &str) -> bool { + true + } + + async fn load_credential(&self, _path: &str) -> Result> { + Err(iceberg::Error::new( + iceberg::ErrorKind::Unexpected, + "refresh failed", + )) + } + } + + #[tokio::test] + async fn operator_does_not_fall_back_when_the_provider_fails() { + let mut server = mockito::Server::new_async().await; + let mock = server + .mock("HEAD", mockito::Matcher::Any) + .expect(0) + .create_async() + .await; + let path = "abfss://container@account.dfs.core.windows.net/table/data.parquet"; + // An account key and a static SAS token sit next to the provider. + let config = AzdlsConfig { + endpoint: Some(server.url()), + account_name: Some("account".to_string()), + account_key: Some("a2V5".to_string()), + ..Default::default() + }; + let static_tokens = AzdlsSasTokens::from_properties(&HashMap::from([( + format!("{ADLS_SAS_TOKEN_PREFIX}account.dfs.core.windows.net"), + "sv=2026&sig=static".to_string(), + )])); + let provider: Option> = + Some(Arc::new(FailingCredentialProvider)); + let operator = super::azdls_config_build( + &config, + &path.parse().unwrap(), + &static_tokens, + &provider, + path, + None, + ) + .unwrap(); + + assert!(operator.stat("table/data.parquet").await.is_err()); + mock.assert_async().await; + } + + /// Vends `sig=expiring`, which is about to expire, and then `sig=fresh`. + #[derive(Debug, Default)] + struct ExpiringSasProvider { + loads: std::sync::atomic::AtomicUsize, + } + + #[async_trait] + impl StorageCredentialProvider for ExpiringSasProvider { + fn supports_path(&self, _path: &str) -> bool { + true + } + + async fn load_credential(&self, _path: &str) -> Result> { + let (signature, lifetime) = + match self.loads.fetch_add(1, std::sync::atomic::Ordering::SeqCst) { + // Usable for one request, but inside the 20 seconds before + // expiry in which reqsign reloads a cached SAS token. + 0 => ("expiring", std::time::Duration::from_secs(10)), + _ => ("fresh", std::time::Duration::from_secs(3600)), + }; + let expires_at_ms = (std::time::SystemTime::now() + lifetime) + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis(); + let host = "account.dfs.core.windows.net"; + Ok(Arc::new(StorageCredential::new( + "abfss://container@account.dfs.core.windows.net", + HashMap::from([ + ( + format!("{ADLS_SAS_TOKEN_PREFIX}{host}"), + format!("sv=2026&sig={signature}"), + ), + ( + format!("{ADLS_SAS_TOKEN_EXPIRES_AT_MS_PREFIX}{host}"), + expires_at_ms.to_string(), + ), + ]), + ))) + } + } + + #[tokio::test] + async fn operator_reloads_an_expiring_sas_token() { + let mut server = mockito::Server::new_async().await; + let mut stat = |signature: &str| { + server + .mock("HEAD", mockito::Matcher::Any) + .match_query(mockito::Matcher::Regex(format!("sig={signature}"))) + .expect(1) + .with_status(404) + }; + let expiring = stat("expiring").create_async().await; + let fresh = stat("fresh").create_async().await; + let path = "abfss://container@account.dfs.core.windows.net/table/data.parquet"; + + let operator = operator_for( + &server, + path, + &AzdlsSasTokens::default(), + Some(Arc::new(ExpiringSasProvider::default())), + ); + for _ in 0..2 { + assert!(operator.stat("table/data.parquet").await.is_err()); + } + + expiring.assert_async().await; + fresh.assert_async().await; + } + + #[tokio::test] + async fn operator_signs_with_the_static_account_sas_token() { + let mut server = mockito::Server::new_async().await; + let mock = server + .mock("HEAD", mockito::Matcher::Any) + .match_query(mockito::Matcher::Regex("sig=static".to_string())) + .expect_at_least(1) + .with_status(404) + .create_async() + .await; + let static_tokens = AzdlsSasTokens::from_properties(&HashMap::from([( + format!("{ADLS_SAS_TOKEN_PREFIX}account.dfs.core.windows.net"), + "sv=2026&sig=static".to_string(), + )])); + + let operator = operator_for( + &server, + "abfss://container@account.dfs.core.windows.net/table/data.parquet", + &static_tokens, + None, + ); + assert!(operator.stat("table/data.parquet").await.is_err()); + mock.assert_async().await; + } + + #[tokio::test] + async fn vended_provider_rejects_mismatched_prefix() { + let credential = StorageCredential::new( + "abfss://other@account.dfs.core.windows.net/table", + HashMap::from([( + format!("{ADLS_SAS_TOKEN_PREFIX}account.dfs.core.windows.net"), + "sv=2026&sig=secret".to_string(), + )]), + ); + let provider = adapter( + credential, + "abfss://container@account.dfs.core.windows.net/table/data.parquet", + ); + + assert!(provider.provide_credential(&Context::new()).await.is_err()); + } + + #[test] + fn batch_key_distinguishes_azure_filesystems_and_schemes() { + let first = azdls_batch_key("abfss://first@account.dfs.core.windows.net/table/a.parquet"); + let second = azdls_batch_key("abfss://second@account.dfs.core.windows.net/table/b.parquet"); + let blob = azdls_batch_key("wasbs://first@account.blob.core.windows.net/table/c.parquet"); + + assert_ne!(first.unwrap(), second.unwrap()); + assert_ne!( + azdls_batch_key("abfss://first@account.dfs.core.windows.net/table/a.parquet").unwrap(), + blob.unwrap() + ); + assert!(azdls_batch_key("abfss:///no-account.parquet").is_err()); + } + #[test] fn test_azure_storage_path_parse() { let test_cases = vec![ @@ -558,7 +1137,7 @@ mod tests { "https://myaccount.dfs.core.windows.net", ), ( - "abfs uses http", + "abfs uses https for Java compatibility and SAS security", AzureStoragePath { scheme: AzureStorageScheme::Abfs, filesystem: "myfs".to_string(), @@ -566,12 +1145,12 @@ mod tests { endpoint_suffix: "core.windows.net".to_string(), path: "/path/to/file.parquet".to_string(), }, - "http://myaccount.dfs.core.windows.net", + "https://myaccount.dfs.core.windows.net", ), ( "wasbs uses https and dfs", AzureStoragePath { - scheme: AzureStorageScheme::Abfss, + scheme: AzureStorageScheme::Wasbs, filesystem: "myfs".to_string(), account_name: "myaccount".to_string(), endpoint_suffix: "core.windows.net".to_string(), diff --git a/crates/storage/opendal/src/gcs.rs b/crates/storage/opendal/src/gcs.rs index a00282cc22..4703f38dc4 100644 --- a/crates/storage/opendal/src/gcs.rs +++ b/crates/storage/opendal/src/gcs.rs @@ -17,17 +17,23 @@ //! Google Cloud Storage properties use std::collections::HashMap; +use std::sync::Arc; use iceberg::io::{ GCS_ALLOW_ANONYMOUS, GCS_CREDENTIALS_JSON, GCS_DISABLE_CONFIG_LOAD, GCS_DISABLE_VM_METADATA, - GCS_NO_AUTH, GCS_SERVICE_HOST, GCS_TOKEN, + GCS_NO_AUTH, GCS_SERVICE_HOST, GCS_TOKEN, GCS_TOKEN_EXPIRES_AT, StorageCredentialProvider, }; use iceberg::{Error, ErrorKind, Result}; -use opendal::Operator; use opendal::services::GcsConfig; +use opendal::{Configurator, Operator}; +use reqsign_core::{Context, ProvideCredential, Result as ReqsignResult}; +use reqsign_google::{Credential as GoogleCredential, Token as GoogleToken}; use url::Url; -use crate::utils::{from_opendal_error, is_truthy}; +use crate::utils::{ + VendedCredentialSource, credential_expiry, from_opendal_error, is_truthy, + required_credential_property, +}; /// Parse iceberg properties to [`GcsConfig`]. pub(crate) fn gcs_config_parse(mut m: HashMap) -> Result { @@ -45,7 +51,9 @@ pub(crate) fn gcs_config_parse(mut m: HashMap) -> Result) -> Result Result { +pub(crate) fn gcs_config_build( + cfg: &GcsConfig, + credential_provider: &Option>, + path: &str, + credential_location: Option<&str>, +) -> Result { let url = Url::parse(path)?; + if !matches!(url.scheme(), "gs" | "gcs") { + return Err(Error::new( + ErrorKind::DataInvalid, + format!("Invalid gcs url: {path}, expected gs:// or gcs://"), + )); + } let bucket = url.host_str().ok_or_else(|| { Error::new( ErrorKind::DataInvalid, @@ -82,5 +101,155 @@ pub(crate) fn gcs_config_build(cfg: &GcsConfig, path: &str) -> Result let mut cfg = cfg.clone(); cfg.bucket = bucket.to_string(); - Operator::from_config(cfg).map_err(from_opendal_error) + + let credential_provider = credential_provider + .as_ref() + .filter(|provider| provider.supports_path(path)); + if credential_provider.is_some() { + if cfg.skip_signature { + return Err(Error::new( + ErrorKind::DataInvalid, + "Invalid GCS auth settings: anonymous access cannot be combined with refreshable credentials", + )); + } + disable_other_credential_sources(&mut cfg); + } + + let mut builder = cfg.into_builder(); + + // The provider re-fetches the vended OAuth2 token as it nears expiry. + if let Some(provider) = credential_provider { + builder = + builder.credential_provider(VendedGcsCredentialProvider(VendedCredentialSource::new( + Arc::clone(provider), + credential_location.unwrap_or(path).to_string(), + ))); + } + + Operator::new(builder).map_err(from_opendal_error) +} + +/// Disable every configured and ambient credential source but a vended one. +/// +/// `reqsign_google` continues to the next provider even when a provider returns +/// an error, and OpenDAL prepends custom providers to its default chain. With +/// the other sources disabled, the vended provider is effectively the sole +/// source, and refresh failures cannot silently fall back. +fn disable_other_credential_sources(cfg: &mut GcsConfig) { + cfg.token = None; + cfg.credential = None; + cfg.credential_path = None; + cfg.service_account = None; + cfg.disable_vm_metadata = true; + cfg.disable_config_load = true; +} + +/// Adapts a generic [`StorageCredentialProvider`] into a `reqsign` +/// [`ProvideCredential`], so the GCS signer can obtain and refresh vended OAuth2 +/// tokens. +#[derive(Debug)] +struct VendedGcsCredentialProvider(VendedCredentialSource); + +impl ProvideCredential for VendedGcsCredentialProvider { + type Credential = GoogleCredential; + + async fn provide_credential(&self, _ctx: &Context) -> ReqsignResult> { + let token = self + .0 + .load("GCS", |config| { + Ok(GoogleToken { + access_token: required_credential_property(config, GCS_TOKEN)?.to_string(), + expires_at: credential_expiry(config, GCS_TOKEN_EXPIRES_AT)?, + }) + }) + .await?; + Ok(Some(GoogleCredential::with_token(token))) + } +} + +#[cfg(test)] +mod tests { + use async_trait::async_trait; + use iceberg::io::{S3_ACCESS_KEY_ID, StorageCredential}; + use reqsign_core::time::Timestamp; + + use super::*; + + #[derive(Debug)] + struct FixedProvider(StorageCredential); + + #[async_trait] + impl StorageCredentialProvider for FixedProvider { + fn supports_path(&self, _path: &str) -> bool { + true + } + + async fn load_credential(&self, _path: &str) -> Result> { + Ok(Arc::new(self.0.clone())) + } + } + + fn adapter(credential: StorageCredential) -> VendedGcsCredentialProvider { + VendedGcsCredentialProvider(VendedCredentialSource::new( + Arc::new(FixedProvider(credential)), + "gs://bucket/table/file.parquet".to_string(), + )) + } + + fn credential(config: &[(&str, &str)]) -> StorageCredential { + StorageCredential::new( + "gs://bucket/table", + config + .iter() + .map(|(key, value)| (key.to_string(), value.to_string())) + .collect(), + ) + } + + #[tokio::test] + async fn test_vended_adapter_returns_expiring_oauth2_token() { + let credential = credential(&[(GCS_TOKEN, "ya29.token"), (GCS_TOKEN_EXPIRES_AT, "1500")]); + + let google = adapter(credential) + .provide_credential(&Context::new()) + .await + .unwrap() + .unwrap(); + let token = google.token.expect("a token credential"); + assert_eq!(token.access_token, "ya29.token"); + assert_eq!( + token.expires_at, + Some(Timestamp::from_millisecond(1500).unwrap()) + ); + } + + #[tokio::test] + async fn test_vended_adapter_rejects_other_credentials() { + assert!( + adapter(credential(&[(S3_ACCESS_KEY_ID, "AK")])) + .provide_credential(&Context::new()) + .await + .is_err() + ); + } + + #[test] + fn test_vended_credentials_disable_every_other_source() { + let mut cfg = gcs_config_parse(HashMap::from([ + (GCS_TOKEN.to_string(), "static-token".to_string()), + (GCS_CREDENTIALS_JSON.to_string(), "e30=".to_string()), + ])) + .unwrap(); + cfg.credential_path = Some("/path/to/credentials.json".to_string()); + cfg.service_account = Some("account@example.com".to_string()); + + disable_other_credential_sources(&mut cfg); + + assert_eq!(cfg.token, None); + assert_eq!(cfg.credential, None); + assert_eq!(cfg.credential_path, None); + assert_eq!(cfg.service_account, None); + assert!(cfg.disable_vm_metadata); + assert!(cfg.disable_config_load); + } } diff --git a/crates/storage/opendal/src/lib.rs b/crates/storage/opendal/src/lib.rs index 693f4c18b3..cc675159e9 100644 --- a/crates/storage/opendal/src/lib.rs +++ b/crates/storage/opendal/src/lib.rs @@ -37,7 +37,7 @@ use futures::StreamExt; use futures::stream::BoxStream; use iceberg::io::{ FileMetadata, FileRead, FileWrite, InputFile, OutputFile, Storage, StorageConfig, - StorageFactory, + StorageCredentialProvider, StorageFactory, }; use iceberg::{Error, ErrorKind, Result}; use iceberg_property_macro::Properties; @@ -49,6 +49,7 @@ use utils::from_opendal_error; cfg_if! { if #[cfg(feature = "opendal-azdls")] { mod azdls; + pub use azdls::AzdlsSasTokens; use azdls::*; use opendal::services::AzdlsConfig; } @@ -221,10 +222,47 @@ where )) } +/// Fails serialization of a storage holding a credential provider, which would +/// otherwise silently fall back to the configured or ambient credentials. +/// [`FileIO`](iceberg::io::FileIO) serializes its provider separately. +#[cfg(any( + feature = "opendal-s3", + feature = "opendal-gcs", + feature = "opendal-azdls" +))] +pub(crate) fn serialize_credential_provider( + _provider: &Option>, + _serializer: S, +) -> std::result::Result +where + S: serde::Serializer, +{ + Err(serde::ser::Error::custom( + "storage with a credential provider cannot be serialized; serialize its FileIO instead", + )) +} + #[typetag::serde(name = "OpenDalStorageFactory")] impl StorageFactory for OpenDalStorageFactory { - #[allow(unused_variables)] fn build(&self, config: &StorageConfig) -> Result> { + self.build_with_credential_provider(config, None) + } + + #[cfg_attr( + not(any( + feature = "opendal-s3", + feature = "opendal-gcs", + feature = "opendal-azdls" + )), + allow(unused_variables) + )] + fn build_with_credential_provider( + &self, + config: &StorageConfig, + credential_provider: Option>, + ) -> Result> { + // Only S3, GCS and ADLS consume the provider; other backends use the + // credentials in `config`. let client_config = OpenDalClientConfig::from_properties(config.props())?; match self { #[cfg(feature = "opendal-memory")] @@ -240,11 +278,13 @@ impl StorageFactory for OpenDalStorageFactory { } => Ok(Arc::new(OpenDalStorage::S3 { config: s3_config_parse(config.props().clone())?.into(), customized_credential_load: customized_credential_load.clone(), + credential_provider, client_config, })), #[cfg(feature = "opendal-gcs")] OpenDalStorageFactory::Gcs => Ok(Arc::new(OpenDalStorage::Gcs { config: gcs_config_parse(config.props().clone())?.into(), + credential_provider, client_config, })), #[cfg(feature = "opendal-hdfs-native")] @@ -262,6 +302,8 @@ impl StorageFactory for OpenDalStorageFactory { #[cfg(feature = "opendal-azdls")] OpenDalStorageFactory::Azdls => Ok(Arc::new(OpenDalStorage::Azdls { config: azdls_config_parse(config.props().clone())?.into(), + sas_tokens: Arc::new(AzdlsSasTokens::from_properties(config.props())), + credential_provider, client_config, })), #[cfg(feature = "opendal-hf")] @@ -297,8 +339,10 @@ fn default_memory_operator() -> Operator { /// /// The serialized representation is not a stable format and may change between crate versions. #[derive(Clone, Debug, Serialize, Deserialize)] +#[non_exhaustive] pub enum OpenDalStorage { /// Memory storage variant. + #[non_exhaustive] #[cfg(feature = "opendal-memory")] Memory { /// Pre-built memory operator. @@ -309,6 +353,7 @@ pub enum OpenDalStorage { client_config: OpenDalClientConfig, }, /// Local filesystem storage variant. + #[non_exhaustive] #[cfg(feature = "opendal-fs")] LocalFs { /// Backend-independent client settings. @@ -319,6 +364,7 @@ pub enum OpenDalStorage { /// /// Accepts any S3-family URL (`s3://`, `s3a://`, `s3n://`); the scheme is /// derived from the path at call time. + #[non_exhaustive] #[cfg(feature = "opendal-s3")] S3 { /// S3 configuration. @@ -326,23 +372,40 @@ pub enum OpenDalStorage { /// Custom AWS credential loader. #[serde(skip)] customized_credential_load: Option, + /// Provider of refreshable vended credentials, from the `FileIO`. + #[serde( + skip_deserializing, + skip_serializing_if = "Option::is_none", + serialize_with = "serialize_credential_provider" + )] + credential_provider: Option>, /// Backend-independent client settings. #[serde(default)] client_config: OpenDalClientConfig, }, /// GCS storage variant. + #[non_exhaustive] #[cfg(feature = "opendal-gcs")] Gcs { /// GCS configuration. config: Arc, + /// Provider of refreshable vended credentials, from the `FileIO`. + #[serde( + skip_deserializing, + skip_serializing_if = "Option::is_none", + serialize_with = "serialize_credential_provider" + )] + credential_provider: Option>, /// Backend-independent client settings. #[serde(default)] client_config: OpenDalClientConfig, }, /// HDFS storage variant; see [`HdfsNativeStorage`]. + #[non_exhaustive] #[cfg(feature = "opendal-hdfs-native")] HdfsNative(HdfsNativeStorage), /// OSS storage variant. + #[non_exhaustive] #[cfg(feature = "opendal-oss")] Oss { /// OSS configuration. @@ -357,10 +420,21 @@ pub enum OpenDalStorage { /// `abfs[s]://@.dfs./` or /// `wasb[s]://@.blob./`. /// The scheme is derived from the path at call time. + #[non_exhaustive] #[cfg(feature = "opendal-azdls")] Azdls { /// Azure DLS configuration. config: Arc, + /// Account-specific SAS tokens supplied by Java-compatible properties. + #[serde(default, skip_serializing_if = "AzdlsSasTokens::is_empty")] + sas_tokens: Arc, + /// Provider of refreshable vended credentials, from the `FileIO`. + #[serde( + skip_deserializing, + skip_serializing_if = "Option::is_none", + serialize_with = "serialize_credential_provider" + )] + credential_provider: Option>, /// Backend-independent client settings. #[serde(default)] client_config: OpenDalClientConfig, @@ -370,6 +444,7 @@ pub enum OpenDalStorage { /// Accepts paths of the form /// `hf:////[@]/`, /// where `` must be one of `models`, `datasets`, `spaces`, or `buckets`. + #[non_exhaustive] #[cfg(feature = "opendal-hf")] Hf { /// HuggingFace Hub configuration (token + endpoint). @@ -380,6 +455,62 @@ pub enum OpenDalStorage { }, } +/// Groups bulk deletes by operator and credential scope. +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +struct DeleteBatchKey { + storage: String, + credential: BatchCredential, +} + +impl DeleteBatchKey { + /// Open batches to flush before adding a path with this key. + /// + /// A scoped credential inside the scope of an open batch means the provider + /// is replacing that batch's broader credential, such as a scheme-wide one. + /// Such batches are flushed while their credential is still valid: once it + /// expires, nothing may cover their whole scope. + fn superseded_batches<'a>( + &self, + open: impl Iterator, + ) -> Vec { + let BatchCredential::Scoped { prefix } = &self.credential else { + return Vec::new(); + }; + open.filter(|key| { + key.storage == self.storage + && key + .credential + .location() + .is_some_and(|location| location != prefix && prefix.starts_with(location)) + }) + .cloned() + .collect() + } +} + +/// The credential shared by the paths of a bulk-delete batch. +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +enum BatchCredential { + /// Served by the backend's configured credentials. + Static, + /// A vended credential for a whole scheme, such as `s3`, looked up for + /// the storage root. + SchemeWide { root: String }, + /// A vended credential scoped to `prefix`, looked up for the prefix. + Scoped { prefix: String }, +} + +impl BatchCredential { + /// Location the batch operator looks vended credentials up for. + fn location(&self) -> Option<&str> { + match self { + BatchCredential::Static => None, + BatchCredential::SchemeWide { root } => Some(root), + BatchCredential::Scoped { prefix } => Some(prefix), + } + } +} + impl OpenDalStorage { /// Creates operator from path. /// @@ -393,10 +524,23 @@ impl OpenDalStorage { /// /// * An [`opendal::Operator`] instance used to operate on file. /// * Relative path to the root uri of [`opendal::Operator`]. - #[allow(unreachable_code, unused_variables)] pub(crate) fn create_operator<'a>( &self, path: &'a impl AsRef, + ) -> Result<(Operator, &'a str)> { + self.create_operator_with_credential_location(path, None) + } + + /// Creates an operator whose vended credentials are looked up for + /// `credential_location` instead of `path`. + /// + /// A bulk-delete batch passes its scope location, so every credential the + /// operator loads covers all paths in the batch. + #[allow(unreachable_code, unreachable_patterns, unused_variables)] + fn create_operator_with_credential_location<'a>( + &self, + path: &'a impl AsRef, + credential_location: Option<&str>, ) -> Result<(Operator, &'a str)> { let path = path.as_ref(); let (operator, relative_path): (Operator, &str) = match self { @@ -421,9 +565,16 @@ impl OpenDalStorage { OpenDalStorage::S3 { config, customized_credential_load, + credential_provider, .. } => { - let op = s3_config_build(config, customized_credential_load, path)?; + let op = s3_config_build( + config, + customized_credential_load, + credential_provider, + path, + credential_location, + )?; let op_info = op.info(); // Use the URL scheme in the path for prefix matching. This enables @@ -445,9 +596,20 @@ impl OpenDalStorage { } } #[cfg(feature = "opendal-gcs")] - OpenDalStorage::Gcs { config, .. } => { - let operator = gcs_config_build(config, path)?; - let prefix = format!("gs://{}/", operator.info().name()); + OpenDalStorage::Gcs { + config, + credential_provider, + .. + } => { + let operator = + gcs_config_build(config, credential_provider, path, credential_location)?; + let url = url::Url::parse(path).map_err(|e| { + Error::new( + ErrorKind::DataInvalid, + format!("Invalid gcs url: {path}: {e}"), + ) + })?; + let prefix = format!("{}://{}/", url.scheme(), operator.info().name()); if path.starts_with(&prefix) { (operator, &path[prefix.len()..]) } else { @@ -475,7 +637,18 @@ impl OpenDalStorage { } } #[cfg(feature = "opendal-azdls")] - OpenDalStorage::Azdls { config, .. } => azdls_create_operator(path, config)?, + OpenDalStorage::Azdls { + config, + sas_tokens, + credential_provider, + .. + } => azdls_create_operator( + path, + config, + sas_tokens, + credential_provider, + credential_location, + )?, #[cfg(feature = "opendal-hf")] OpenDalStorage::Hf { config, .. } => hf_config_build(config, path)?, #[cfg(all( @@ -547,27 +720,92 @@ impl OpenDalStorage { /// /// For most backends the URL host (bucket name) is sufficient. For HF the host /// encodes the repo type, not the repo identity, so a more specific key is used. - fn batch_key_for_path(&self, path: &str) -> String { + #[allow(unreachable_patterns)] + fn batch_key_for_path(&self, path: &str) -> Result { match self { #[cfg(feature = "opendal-hf")] - OpenDalStorage::Hf { .. } => hf_batch_key(path), + OpenDalStorage::Hf { .. } => Ok(hf_batch_key(path)), + #[cfg(feature = "opendal-azdls")] + OpenDalStorage::Azdls { .. } => azdls_batch_key(path), // The URL host alone would merge distinct NameNodes that differ // only by port; key by the effective NameNode instead. #[cfg(feature = "opendal-hdfs-native")] - OpenDalStorage::HdfsNative(storage) => hdfs_native_batch_key(&storage.config, path), - _ => url::Url::parse(path) + OpenDalStorage::HdfsNative(storage) => Ok(hdfs_native_batch_key(&storage.config, path)), + _ => Ok(url::Url::parse(path) .ok() .and_then(|u| u.host_str().map(|s| s.to_string())) - .unwrap_or_default(), + .unwrap_or_default()), } } + /// Return the credential provider that serves `path`, if any. + fn credential_provider_for_path( + &self, + path: &str, + ) -> Option<&Arc> { + let provider: &Arc = (match self { + #[cfg(feature = "opendal-s3")] + OpenDalStorage::S3 { + customized_credential_load: None, + credential_provider: Some(provider), + .. + } => Some(provider), + #[cfg(feature = "opendal-gcs")] + OpenDalStorage::Gcs { + credential_provider: Some(provider), + .. + } => Some(provider), + #[cfg(feature = "opendal-azdls")] + OpenDalStorage::Azdls { + credential_provider: Some(provider), + .. + } => Some(provider), + _ => None, + })?; + provider.supports_path(path).then_some(provider) + } + + /// Returns a key that keeps bulk deletes within one operator and credential + /// scope. Loading the credential is normally a cache hit and avoids rebuilding + /// an operator for every path while preventing a batch from crossing prefixes. + async fn delete_batch_key_for_path(&self, path: &str) -> Result { + let credential = match self.credential_provider_for_path(path) { + Some(provider) => { + let credential = provider.load_credential(path).await?; + if !credential.covers(path) { + return Err(Error::new( + ErrorKind::DataInvalid, + utils::uncovered_location_message(path, &credential), + )); + } + let prefix = credential.prefix(); + if prefix.contains("://") { + BatchCredential::Scoped { + prefix: prefix.to_string(), + } + } else { + // A scheme-wide prefix such as `s3` is no location to look + // up, so the batch looks its credential up for the root. + BatchCredential::SchemeWide { + root: utils::storage_root(path)?, + } + } + } + None => BatchCredential::Static, + }; + + Ok(DeleteBatchKey { + storage: self.batch_key_for_path(path)?, + credential, + }) + } + /// Extracts the relative path from an absolute path without building an operator. /// /// This is a lightweight alternative to [`create_operator`](Self::create_operator) for cases /// where only the relative path is needed (e.g. bulk deletes where the operator is already /// available). - #[allow(unreachable_code, unused_variables)] + #[allow(unreachable_code, unreachable_patterns, unused_variables)] pub(crate) fn relativize_path<'a>(&self, path: &'a str) -> Result<&'a str> { match self { #[cfg(feature = "opendal-memory")] @@ -598,13 +836,19 @@ impl OpenDalStorage { #[cfg(feature = "opendal-gcs")] OpenDalStorage::Gcs { .. } => { let url = url::Url::parse(path)?; + if !matches!(url.scheme(), "gs" | "gcs") { + return Err(Error::new( + ErrorKind::DataInvalid, + format!("Invalid gcs url: {path}, expected gs:// or gcs://"), + )); + } let bucket = url.host_str().ok_or_else(|| { Error::new( ErrorKind::DataInvalid, format!("Invalid gcs url: {path}, missing bucket"), ) })?; - let prefix = format!("gs://{}/", bucket); + let prefix = format!("{}://{}/", url.scheme(), bucket); if path.starts_with(&prefix) { Ok(&path[prefix.len()..]) } else { @@ -735,17 +979,26 @@ impl Storage for OpenDalStorage { } async fn delete_stream(&self, mut paths: BoxStream<'static, String>) -> Result<()> { - let mut deleters: HashMap = HashMap::new(); + let mut deleters: HashMap = HashMap::new(); while let Some(path) = paths.next().await { - let bucket = self.batch_key_for_path(&path); + let batch_key = self.delete_batch_key_for_path(&path).await?; - let (relative_path, deleter) = match deleters.entry(bucket) { + for key in batch_key.superseded_batches(deleters.keys()) { + if let Some(mut deleter) = deleters.remove(&key) { + deleter.close().await.map_err(from_opendal_error)?; + } + } + + let (relative_path, deleter) = match deleters.entry(batch_key) { Entry::Occupied(entry) => { (self.relativize_path(&path)?.to_string(), entry.into_mut()) } Entry::Vacant(entry) => { - let (op, rel) = self.create_operator(&path)?; + let (op, rel) = self.create_operator_with_credential_location( + &path, + entry.key().credential.location(), + )?; let rel = rel.to_string(); let deleter = op.deleter().await.map_err(from_opendal_error)?; (rel, entry.insert(deleter)) @@ -844,8 +1097,74 @@ impl FileWrite for OpenDalWriter { #[cfg(test)] mod tests { + #[cfg(feature = "opendal-s3")] + use std::sync::atomic::AtomicBool; + #[cfg(any(feature = "opendal-s3", feature = "opendal-gcs"))] + use std::sync::atomic::{AtomicUsize, Ordering}; + #[cfg(any(feature = "opendal-s3", feature = "opendal-gcs"))] + use std::time::{SystemTime, UNIX_EPOCH}; + + #[cfg(feature = "opendal-gcs")] + use iceberg::io::{GCS_SERVICE_HOST, GCS_TOKEN, GCS_TOKEN_EXPIRES_AT}; + #[cfg(any( + feature = "opendal-s3", + feature = "opendal-gcs", + all(feature = "opendal-memory", feature = "opendal-azdls") + ))] + use iceberg::io::{S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY, StorageCredential}; + #[cfg(feature = "opendal-s3")] + use iceberg::io::{ + S3_ENDPOINT, S3_PATH_STYLE_ACCESS, S3_REGION, S3_SESSION_TOKEN_EXPIRES_AT_MS, + }; + + #[allow(unused_imports)] use super::*; + #[cfg(any( + feature = "opendal-s3", + feature = "opendal-gcs", + all(feature = "opendal-memory", feature = "opendal-azdls") + ))] + #[derive(Debug)] + struct AlwaysSupportedCredentialProvider; + + #[cfg(any( + feature = "opendal-s3", + feature = "opendal-gcs", + all(feature = "opendal-memory", feature = "opendal-azdls") + ))] + #[async_trait] + impl StorageCredentialProvider for AlwaysSupportedCredentialProvider { + fn supports_path(&self, _path: &str) -> bool { + true + } + + async fn load_credential(&self, path: &str) -> Result> { + let prefix = if path.contains("/table-a/") { + "s3://bucket/table-a" + } else { + "s3://bucket/table-b" + }; + Ok(Arc::new(s3_credential(prefix, "access-key"))) + } + } + + /// An S3 credential for locations under `prefix`. + #[cfg(any( + feature = "opendal-s3", + feature = "opendal-gcs", + all(feature = "opendal-memory", feature = "opendal-azdls") + ))] + fn s3_credential(prefix: impl Into, access_key: &str) -> StorageCredential { + StorageCredential::new( + prefix, + HashMap::from([ + (S3_ACCESS_KEY_ID.to_string(), access_key.to_string()), + (S3_SECRET_ACCESS_KEY.to_string(), "secret-key".to_string()), + ]), + ) + } + fn client_config(value: &str) -> Result { OpenDalClientConfig::from_properties(&HashMap::from([( OPENDAL_IO_TIMEOUT_MS.to_string(), @@ -907,6 +1226,7 @@ mod tests { let storage = OpenDalStorage::S3 { config: Arc::new(S3Config::default()), customized_credential_load: None, + credential_provider: None, client_config: client_config("45000").unwrap(), }; @@ -1044,6 +1364,26 @@ mod tests { assert_eq!(op.info().scheme().to_string(), "memory"); } + #[cfg(all( + feature = "opendal-memory", + any( + feature = "opendal-s3", + feature = "opendal-gcs", + feature = "opendal-azdls" + ) + ))] + #[test] + fn test_factory_ignores_credentials_for_unsupported_backend() { + let storage = OpenDalStorageFactory::Memory + .build_with_credential_provider( + &StorageConfig::new(), + Some(Arc::new(AlwaysSupportedCredentialProvider)), + ) + .expect("memory must ignore a credential provider"); + + assert!(storage.new_input("memory:/key").is_ok()); + } + #[cfg(feature = "opendal-memory")] #[tokio::test] async fn test_writer_close_returns_stored_size() { @@ -1123,6 +1463,7 @@ mod tests { let storage = OpenDalStorage::S3 { config: Arc::new(S3Config::default()), customized_credential_load: None, + credential_provider: None, client_config: OpenDalClientConfig::default(), }; @@ -1139,27 +1480,620 @@ mod tests { } } + #[cfg(feature = "opendal-azdls")] + #[test] + fn test_azdls_storage_omits_empty_sas_tokens() { + let storage = |sas_tokens: AzdlsSasTokens| OpenDalStorage::Azdls { + config: Arc::new(AzdlsConfig::default()), + sas_tokens: Arc::new(sas_tokens), + credential_provider: None, + client_config: OpenDalClientConfig::default(), + }; + + let json = serde_json::to_value(storage(AzdlsSasTokens::default())).unwrap(); + assert!(json["Azdls"].get("sas_tokens").is_none(), "{json}"); + let deserialized: OpenDalStorage = serde_json::from_value(json).unwrap(); + assert!(matches!(deserialized, OpenDalStorage::Azdls { .. })); + } + + /// Vends a credential for the whole `s3` scheme until it has served + /// `table-c`, then credentials scoped to each table. The scheme-wide + /// credential expires once the `table-c` batch is signed. + #[cfg(feature = "opendal-s3")] + #[derive(Debug, Default)] + struct ChangingScopeProvider { + scoped: AtomicBool, + scheme_wide_expired: AtomicBool, + /// Whether the scheme-wide batch, scoped to the storage root, was signed. + scheme_wide_signed: AtomicBool, + } + + #[cfg(feature = "opendal-s3")] + #[async_trait] + impl StorageCredentialProvider for ChangingScopeProvider { + fn supports_path(&self, _path: &str) -> bool { + true + } + + async fn load_credential(&self, path: &str) -> Result> { + if path == "s3://bucket/" { + self.scheme_wide_signed.store(true, Ordering::SeqCst); + } + if path.starts_with("s3://bucket/table-c") { + self.scoped.store(true, Ordering::SeqCst); + } + // Signing the scoped batch means the scheme-wide credential is gone. + if path == "s3://bucket/table-c" { + self.scheme_wide_expired.store(true, Ordering::SeqCst); + } + match path.strip_prefix("s3://bucket/") { + Some(rest) if self.scoped.load(Ordering::SeqCst) && !rest.is_empty() => { + let table = rest.split('/').next().unwrap_or_default(); + Ok(Arc::new(s3_credential( + format!("s3://bucket/{table}"), + "SCOPED_AK", + ))) + } + _ if self.scheme_wide_expired.load(Ordering::SeqCst) => Err(Error::new( + ErrorKind::Unexpected, + "the scheme-wide credential expired", + )), + _ => Ok(Arc::new(s3_credential("s3", "SCHEME_AK"))), + } + } + } + + #[cfg(feature = "opendal-s3")] + #[tokio::test] + async fn test_delete_stream_signs_each_batch_with_its_vended_credential() { + let mut server = mockito::Server::new_async().await; + let mut delete = |path: &str, access_key: &str| { + server + .mock("DELETE", path) + .match_header( + "authorization", + mockito::Matcher::Regex(format!("Credential={access_key}/")), + ) + .expect(1) + .with_status(204) + }; + // The scheme-wide batch is flushed, with its own credential, before + // the scoped credential that replaces it is used. + let scheme_wide = delete("/bucket/table-b/f.parquet", "SCHEME_AK") + .create_async() + .await; + let scoped = delete("/bucket/table-c/f.parquet", "SCOPED_AK") + .create_async() + .await; + + let mut config = S3Config::default(); + config.endpoint = Some(server.url()); + config.region = Some("us-east-1".to_string()); + config.disable_config_load = true; + config.disable_ec2_metadata = true; + let provider = Arc::new(ChangingScopeProvider::default()); + let storage = OpenDalStorage::S3 { + config: Arc::new(config), + customized_credential_load: None, + credential_provider: Some(provider.clone()), + client_config: OpenDalClientConfig::default(), + }; + // Polled once the `table-c` path is batched, before the stream ends + // and every open batch is closed. + let scheme_wide_flushed_early = futures::stream::once(async move { + assert!(provider.scheme_wide_signed.load(Ordering::SeqCst)); + None + }) + .filter_map(futures::future::ready); + storage + .delete_stream( + futures::stream::iter([ + "s3://bucket/table-b/f.parquet".to_string(), + "s3://bucket/table-c/f.parquet".to_string(), + ]) + .chain(scheme_wide_flushed_early) + .boxed(), + ) + .await + .unwrap(); + + scheme_wide.assert_async().await; + scoped.assert_async().await; + } + + /// A credential lifetime that covers one request, but falls within the two + /// minutes before expiry in which reqsign reloads a cached S3 or GCS + /// credential. + #[cfg(any(feature = "opendal-s3", feature = "opendal-gcs"))] + const EXPIRING_LIFETIME: Duration = Duration::from_secs(60); + + /// The epoch millisecond `lifetime` from now, as vended expiries are given. + #[cfg(any(feature = "opendal-s3", feature = "opendal-gcs"))] + fn epoch_millis_after(lifetime: Duration) -> String { + (SystemTime::now() + lifetime) + .duration_since(UNIX_EPOCH) + .unwrap() + .as_millis() + .to_string() + } + + /// Vends `EXPIRING_AK`, which is about to expire, and then `FRESH_AK`. + #[cfg(feature = "opendal-s3")] + #[derive(Debug, Default)] + struct ExpiringS3Provider { + loads: AtomicUsize, + } + + #[cfg(feature = "opendal-s3")] + #[async_trait] + impl StorageCredentialProvider for ExpiringS3Provider { + fn supports_path(&self, _path: &str) -> bool { + true + } + + async fn load_credential(&self, _path: &str) -> Result> { + let (access_key, lifetime) = match self.loads.fetch_add(1, Ordering::SeqCst) { + 0 => ("EXPIRING_AK", EXPIRING_LIFETIME), + _ => ("FRESH_AK", Duration::from_secs(3600)), + }; + let mut config = s3_credential("s3", access_key).config().clone(); + config.insert( + S3_SESSION_TOKEN_EXPIRES_AT_MS.to_string(), + epoch_millis_after(lifetime), + ); + Ok(Arc::new(StorageCredential::new("s3", config))) + } + } + + #[cfg(feature = "opendal-s3")] + #[tokio::test] + async fn test_s3_operator_reloads_an_expiring_credential() { + let mut server = mockito::Server::new_async().await; + let mut stat = |access_key: &str| { + server + .mock("HEAD", "/bucket/file.parquet") + .match_header( + "authorization", + mockito::Matcher::Regex(format!("Credential={access_key}/")), + ) + .expect(1) + .with_status(200) + .with_header("content-length", "0") + }; + let expiring = stat("EXPIRING_AK").create_async().await; + let fresh = stat("FRESH_AK").create_async().await; + + let mut config = S3Config::default(); + config.endpoint = Some(server.url()); + config.region = Some("us-east-1".to_string()); + config.disable_config_load = true; + config.disable_ec2_metadata = true; + let storage = OpenDalStorage::S3 { + config: Arc::new(config), + customized_credential_load: None, + credential_provider: Some(Arc::new(ExpiringS3Provider::default())), + client_config: OpenDalClientConfig::default(), + }; + let path = "s3://bucket/file.parquet"; + let (operator, relative_path) = storage.create_operator(&path).unwrap(); + for _ in 0..2 { + operator.stat(relative_path).await.unwrap(); + } + + expiring.assert_async().await; + fresh.assert_async().await; + } + + /// Fails every credential load. + #[cfg(any(feature = "opendal-s3", feature = "opendal-gcs"))] + #[derive(Debug)] + struct FailingCredentialProvider; + + #[cfg(any(feature = "opendal-s3", feature = "opendal-gcs"))] + #[async_trait] + impl StorageCredentialProvider for FailingCredentialProvider { + fn supports_path(&self, _path: &str) -> bool { + true + } + + async fn load_credential(&self, _path: &str) -> Result> { + Err(Error::new(ErrorKind::Unexpected, "refresh failed")) + } + } + + #[cfg(feature = "opendal-gcs")] + fn gcs_storage( + server: &mockito::Server, + provider: impl StorageCredentialProvider + 'static, + ) -> OpenDalStorage { + let config = gcs_config_parse(HashMap::from([ + (GCS_SERVICE_HOST.to_string(), server.url()), + (GCS_TOKEN.to_string(), "static-token".to_string()), + ])) + .unwrap(); + OpenDalStorage::Gcs { + config: Arc::new(config), + credential_provider: Some(Arc::new(provider)), + client_config: OpenDalClientConfig::default(), + } + } + + /// Vends `expiring-token`, which is about to expire, and then `fresh-token`. + #[cfg(feature = "opendal-gcs")] + #[derive(Debug, Default)] + struct ExpiringGcsProvider { + loads: AtomicUsize, + } + + #[cfg(feature = "opendal-gcs")] + #[async_trait] + impl StorageCredentialProvider for ExpiringGcsProvider { + fn supports_path(&self, _path: &str) -> bool { + true + } + + async fn load_credential(&self, _path: &str) -> Result> { + let (token, lifetime) = match self.loads.fetch_add(1, Ordering::SeqCst) { + 0 => ("expiring-token", EXPIRING_LIFETIME), + _ => ("fresh-token", Duration::from_secs(3600)), + }; + Ok(Arc::new(StorageCredential::new( + "gs", + HashMap::from([ + (GCS_TOKEN.to_string(), token.to_string()), + ( + GCS_TOKEN_EXPIRES_AT.to_string(), + epoch_millis_after(lifetime), + ), + ]), + ))) + } + } + #[cfg(feature = "opendal-gcs")] + #[tokio::test] + async fn test_gcs_operator_reloads_an_expiring_token() { + let mut server = mockito::Server::new_async().await; + let mut stat = |token: &str| { + server + .mock("GET", mockito::Matcher::Any) + .match_header("authorization", format!("Bearer {token}").as_str()) + .expect(1) + .with_status(404) + }; + let expiring = stat("expiring-token").create_async().await; + let fresh = stat("fresh-token").create_async().await; + + let storage = gcs_storage(&server, ExpiringGcsProvider::default()); + let path = "gs://bucket/file.parquet"; + let (operator, relative_path) = storage.create_operator(&path).unwrap(); + for _ in 0..2 { + assert!(!operator.exists(relative_path).await.unwrap()); + } + + expiring.assert_async().await; + fresh.assert_async().await; + } + + #[cfg(feature = "opendal-gcs")] + #[tokio::test] + async fn test_gcs_does_not_fall_back_when_the_provider_fails() { + let mut server = mockito::Server::new_async().await; + let mock = server + .mock("GET", mockito::Matcher::Any) + .expect(0) + .create_async() + .await; + + let storage = gcs_storage(&server, FailingCredentialProvider); + assert!(storage.exists("gs://bucket/file.parquet").await.is_err()); + mock.assert_async().await; + } + + #[cfg(feature = "opendal-s3")] #[test] - fn test_relativize_path_gcs() { - let storage = OpenDalStorage::Gcs { - config: Arc::new(GcsConfig::default()), + fn test_storage_with_credential_provider_is_not_serializable() { + let storage = + |credential_provider: Option>| OpenDalStorage::S3 { + config: Arc::new(S3Config::default()), + customized_credential_load: None, + credential_provider, + client_config: OpenDalClientConfig::default(), + }; + + assert!(serde_json::to_string(&storage(None)).is_ok()); + let error = + serde_json::to_string(&storage(Some(Arc::new(AlwaysSupportedCredentialProvider)))) + .unwrap_err(); + assert!(error.to_string().contains("credential provider"), "{error}"); + } + + #[cfg(feature = "opendal-s3")] + #[tokio::test] + async fn test_s3_does_not_fall_back_when_the_provider_fails() { + let mut server = mockito::Server::new_async().await; + let mock = server + .mock("HEAD", mockito::Matcher::Any) + .expect(0) + .create_async() + .await; + // REST catalogs often return static keys next to vended credentials. + let config = s3_config_parse(HashMap::from([ + (S3_ENDPOINT.to_string(), server.url()), + (S3_PATH_STYLE_ACCESS.to_string(), "true".to_string()), + (S3_REGION.to_string(), "us-east-1".to_string()), + (S3_ACCESS_KEY_ID.to_string(), "STATIC_AK".to_string()), + ( + S3_SECRET_ACCESS_KEY.to_string(), + "static-secret".to_string(), + ), + ])) + .unwrap(); + let storage = OpenDalStorage::S3 { + config: Arc::new(config), + customized_credential_load: None, + credential_provider: Some(Arc::new(FailingCredentialProvider)), client_config: OpenDalClientConfig::default(), }; + assert!(storage.exists("s3://bucket/file.parquet").await.is_err()); + mock.assert_async().await; + } + + /// Vends one credential scoped to `s3://bucket/table` and counts loads. + #[cfg(feature = "opendal-s3")] + #[derive(Debug, Default)] + struct CountingS3Provider { + loads: AtomicUsize, + } + + #[cfg(feature = "opendal-s3")] + #[async_trait] + impl StorageCredentialProvider for CountingS3Provider { + fn supports_path(&self, _path: &str) -> bool { + true + } + + async fn load_credential(&self, _path: &str) -> Result> { + self.loads.fetch_add(1, Ordering::SeqCst); + Ok(Arc::new(s3_credential("s3://bucket/table", "SCOPED_AK"))) + } + } + + #[cfg(feature = "opendal-s3")] + #[tokio::test] + async fn test_delete_stream_loads_a_credential_per_path_and_batch() { + let mut server = mockito::Server::new_async().await; + let delete = server + .mock("POST", mockito::Matcher::Any) + .match_header( + "authorization", + mockito::Matcher::Regex("Credential=SCOPED_AK/".to_string()), + ) + .expect(1) + .with_status(200) + .with_body(r#""#) + .create_async() + .await; + + let mut config = S3Config::default(); + config.endpoint = Some(server.url()); + config.region = Some("us-east-1".to_string()); + config.disable_config_load = true; + config.disable_ec2_metadata = true; + let provider = Arc::new(CountingS3Provider::default()); + let storage = OpenDalStorage::S3 { + config: Arc::new(config), + customized_credential_load: None, + credential_provider: Some(provider.clone()), + client_config: OpenDalClientConfig::default(), + }; + let paths: Vec = (0..3) + .map(|i| format!("s3://bucket/table/f{i}.parquet")) + .collect(); + storage + .delete_stream(futures::stream::iter(paths.clone()).boxed()) + .await + .unwrap(); + + delete.assert_async().await; + // One load to choose each path's batch, and one to sign the batch. + assert_eq!(provider.loads.load(Ordering::SeqCst), paths.len() + 1); + } + + #[cfg(feature = "opendal-s3")] + #[tokio::test] + async fn test_vended_credentials_batch_by_prefix() { + let storage = OpenDalStorage::S3 { + config: Arc::new(S3Config::default()), + customized_credential_load: None, + credential_provider: Some(Arc::new(AlwaysSupportedCredentialProvider)), + client_config: OpenDalClientConfig::default(), + }; + let first = "s3://bucket/table-a/file.parquet"; + let same_scope = "s3://bucket/table-a/other.parquet"; + let other_scope = "s3://bucket/table-b/file.parquet"; + + let first_key = storage.delete_batch_key_for_path(first).await.unwrap(); + assert_eq!(first_key.credential.location(), Some("s3://bucket/table-a")); assert_eq!( + first_key, + storage.delete_batch_key_for_path(same_scope).await.unwrap() + ); + assert_ne!( + first_key, storage - .relativize_path("gs://my-bucket/path/to/file.parquet") - .unwrap(), - "path/to/file.parquet" + .delete_batch_key_for_path(other_scope) + .await + .unwrap() + ); + } + + #[cfg(feature = "opendal-s3")] + #[tokio::test] + async fn test_scheme_wide_vended_credentials_batch_by_storage_root() { + #[derive(Debug)] + struct SchemeWideProvider; + + #[async_trait] + impl StorageCredentialProvider for SchemeWideProvider { + fn supports_path(&self, _path: &str) -> bool { + true + } + + async fn load_credential(&self, _path: &str) -> Result> { + Ok(Arc::new(s3_credential("s3", "access-key"))) + } + } + + let storage = OpenDalStorage::S3 { + config: Arc::new(S3Config::default()), + customized_credential_load: None, + credential_provider: Some(Arc::new(SchemeWideProvider)), + client_config: OpenDalClientConfig::default(), + }; + + let key = storage + .delete_batch_key_for_path("s3://bucket/table-a/file.parquet") + .await + .unwrap(); + assert_eq!(key.credential, BatchCredential::SchemeWide { + root: "s3://bucket/".to_string() + }); + assert_eq!( + key, + storage + .delete_batch_key_for_path("s3://bucket/table-b/file.parquet") + .await + .unwrap() ); } + #[test] + fn test_scoped_batch_flushes_broader_batches_of_same_storage() { + let key = |storage: &str, credential: BatchCredential| DeleteBatchKey { + storage: storage.to_string(), + credential, + }; + let unscoped = key("bucket", BatchCredential::SchemeWide { + root: "s3://bucket/".to_string(), + }); + let other_storage = key("other", BatchCredential::SchemeWide { + root: "s3://other/".to_string(), + }); + let scoped = key("bucket", BatchCredential::Scoped { + prefix: "s3://bucket/table-a".to_string(), + }); + let open = [unscoped.clone(), other_storage, scoped.clone()]; + + let new_scope = key("bucket", BatchCredential::Scoped { + prefix: "s3://bucket/table-b".to_string(), + }); + assert_eq!(new_scope.superseded_batches(open.iter()), vec![ + unscoped.clone() + ]); + + // A narrower scope also supersedes a broader scoped batch, such as one + // using an account-wide ADLS seed scoped to its container. + let nested = key("bucket", BatchCredential::Scoped { + prefix: "s3://bucket/table-a/data".to_string(), + }); + let superseded = nested.superseded_batches(open.iter()); + assert_eq!(superseded.len(), 2); + assert!(superseded.contains(&unscoped) && superseded.contains(&scoped)); + // A batch never supersedes itself. + assert_eq!(scoped.superseded_batches(open.iter()), vec![ + unscoped.clone() + ]); + // Scheme-wide and static paths leave open batches alone. + assert!(unscoped.superseded_batches(open.iter()).is_empty()); + assert!( + key("bucket", BatchCredential::Static) + .superseded_batches(open.iter()) + .is_empty() + ); + } + + #[cfg(feature = "opendal-s3")] + #[tokio::test] + async fn test_custom_s3_credential_loader_ignores_credential_provider_for_batching() { + let storage = OpenDalStorage::S3 { + config: Arc::new(S3Config::default()), + customized_credential_load: Some(CustomAwsCredentialLoader::new( + reqsign_aws_v4::StaticCredentialProvider::new("access-key", "secret-key"), + )), + credential_provider: Some(Arc::new(AlwaysSupportedCredentialProvider)), + client_config: OpenDalClientConfig::default(), + }; + + let key = storage + .delete_batch_key_for_path("s3://bucket/table-a/file.parquet") + .await + .unwrap(); + assert_eq!(key.credential, BatchCredential::Static); + } + + #[cfg(feature = "opendal-s3")] + #[test] + fn test_s3_rejects_anonymous_vended_credentials() { + let mut config = S3Config::default(); + config.skip_signature = true; + let storage = OpenDalStorage::S3 { + config: Arc::new(config), + customized_credential_load: None, + credential_provider: Some(Arc::new(AlwaysSupportedCredentialProvider)), + client_config: OpenDalClientConfig::default(), + }; + + let error = storage + .create_operator(&"s3://bucket/file.parquet") + .unwrap_err(); + assert_eq!(error.kind(), ErrorKind::DataInvalid); + } + + #[cfg(feature = "opendal-gcs")] + #[test] + fn test_gcs_rejects_anonymous_vended_credentials() { + let mut config = GcsConfig::default(); + config.skip_signature = true; + let storage = OpenDalStorage::Gcs { + config: Arc::new(config), + credential_provider: Some(Arc::new(AlwaysSupportedCredentialProvider)), + client_config: OpenDalClientConfig::default(), + }; + + let error = storage + .create_operator(&"gs://bucket/file.parquet") + .unwrap_err(); + assert_eq!(error.kind(), ErrorKind::DataInvalid); + } + + #[cfg(feature = "opendal-gcs")] + #[test] + fn test_relativize_path_gcs() { + let storage = OpenDalStorage::Gcs { + config: Arc::new(GcsConfig::default()), + credential_provider: None, + client_config: OpenDalClientConfig::default(), + }; + + for scheme in ["gs", "gcs"] { + let path = format!("{scheme}://my-bucket/path/to/file.parquet"); + assert_eq!( + storage.relativize_path(&path).unwrap(), + "path/to/file.parquet" + ); + let (_, relative) = storage.create_operator(&path).unwrap(); + assert_eq!(relative, "path/to/file.parquet"); + } + } + #[cfg(feature = "opendal-gcs")] #[test] fn test_relativize_path_gcs_invalid_scheme() { let storage = OpenDalStorage::Gcs { config: Arc::new(GcsConfig::default()), + credential_provider: None, client_config: OpenDalClientConfig::default(), }; @@ -1168,6 +2102,11 @@ mod tests { .relativize_path("s3://my-bucket/path/to/file.parquet") .is_err() ); + assert!( + storage + .create_operator(&"s3://my-bucket/path/to/file.parquet") + .is_err() + ); } #[cfg(feature = "opendal-oss")] @@ -1210,6 +2149,8 @@ mod tests { endpoint: Some("https://myaccount.dfs.core.windows.net".to_string()), ..Default::default() }), + sas_tokens: Arc::new(AzdlsSasTokens::default()), + credential_provider: None, client_config: OpenDalClientConfig::default(), }; diff --git a/crates/storage/opendal/src/resolving.rs b/crates/storage/opendal/src/resolving.rs index d7a977e7ac..082a16d4ac 100644 --- a/crates/storage/opendal/src/resolving.rs +++ b/crates/storage/opendal/src/resolving.rs @@ -18,7 +18,7 @@ //! Resolving storage that auto-detects the scheme from a path and delegates //! to the appropriate [`OpenDalStorage`] variant. -use std::collections::HashMap; +use std::collections::{BTreeSet, HashMap}; use std::sync::{Arc, RwLock}; use async_trait::async_trait; @@ -27,7 +27,7 @@ use futures::StreamExt; use futures::stream::BoxStream; use iceberg::io::{ FileMetadata, FileRead, FileWrite, InputFile, OutputFile, Storage, StorageConfig, - StorageFactory, + StorageCredentialProvider, StorageFactory, }; use iceberg::{Error, ErrorKind, Result}; use serde::{Deserialize, Serialize}; @@ -83,10 +83,17 @@ fn extract_scheme(path: &str) -> Result<&'static str> { } /// Build an [`OpenDalStorage`] variant for the given scheme and config properties. +#[allow(unused_variables)] fn build_storage_for_scheme( scheme: &'static str, props: &HashMap, #[cfg(feature = "opendal-s3")] customized_credential_load: &Option, + #[cfg(any( + feature = "opendal-s3", + feature = "opendal-gcs", + feature = "opendal-azdls" + ))] + credential_provider: &Option>, ) -> Result { let client_config = OpenDalClientConfig::from_properties(props)?; match scheme { @@ -96,6 +103,7 @@ fn build_storage_for_scheme( Ok(OpenDalStorage::S3 { config: Arc::new(config), customized_credential_load: customized_credential_load.clone(), + credential_provider: credential_provider.clone(), client_config, }) } @@ -104,6 +112,7 @@ fn build_storage_for_scheme( let config = crate::gcs::gcs_config_parse(props.clone())?; Ok(OpenDalStorage::Gcs { config: Arc::new(config), + credential_provider: credential_provider.clone(), client_config, }) } @@ -120,6 +129,8 @@ fn build_storage_for_scheme( let config = crate::azdls::azdls_config_parse(props.clone())?; Ok(OpenDalStorage::Azdls { config: Arc::new(config), + sas_tokens: Arc::new(crate::azdls::AzdlsSasTokens::from_properties(props)), + credential_provider: credential_provider.clone(), client_config, }) } @@ -215,11 +226,35 @@ impl OpenDalResolvingStorageFactory { #[typetag::serde] impl StorageFactory for OpenDalResolvingStorageFactory { fn build(&self, config: &StorageConfig) -> Result> { + self.build_with_credential_provider(config, None) + } + + #[cfg_attr( + not(any( + feature = "opendal-s3", + feature = "opendal-gcs", + feature = "opendal-azdls" + )), + allow(unused_variables) + )] + fn build_with_credential_provider( + &self, + config: &StorageConfig, + credential_provider: Option>, + ) -> Result> { + // Without a compatible backend the provider is ignored, and every + // backend uses the credentials in `config`. Ok(Arc::new(OpenDalResolvingStorage { props: config.props().clone(), storages: RwLock::new(HashMap::new()), #[cfg(feature = "opendal-s3")] customized_credential_load: self.customized_credential_load.clone(), + #[cfg(any( + feature = "opendal-s3", + feature = "opendal-gcs", + feature = "opendal-azdls" + ))] + credential_provider, })) } } @@ -230,7 +265,7 @@ impl StorageFactory for OpenDalResolvingStorageFactory { /// Sub-storages are lazily created on first use for each scheme and cached /// for subsequent operations. Scheme aliases like `s3`/`s3a`/`s3n` map to /// the same canonical scheme, so they share a storage instance. -#[derive(Debug, Serialize, Deserialize)] +#[derive(Serialize, Deserialize)] pub struct OpenDalResolvingStorage { /// Configuration properties shared across all backends. props: HashMap, @@ -241,6 +276,27 @@ pub struct OpenDalResolvingStorage { #[cfg(feature = "opendal-s3")] #[serde(skip)] customized_credential_load: Option, + /// Provider of refreshable vended credentials. + #[cfg(any( + feature = "opendal-s3", + feature = "opendal-gcs", + feature = "opendal-azdls" + ))] + #[serde( + skip_deserializing, + skip_serializing_if = "Option::is_none", + serialize_with = "crate::serialize_credential_provider" + )] + credential_provider: Option>, +} + +impl std::fmt::Debug for OpenDalResolvingStorage { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // `props` can contain storage secrets + f.debug_struct("OpenDalResolvingStorage") + .field("property_keys", &self.props.keys().collect::>()) + .finish_non_exhaustive() + } } impl OpenDalResolvingStorage { @@ -276,6 +332,12 @@ impl OpenDalResolvingStorage { &self.props, #[cfg(feature = "opendal-s3")] &self.customized_credential_load, + #[cfg(any( + feature = "opendal-s3", + feature = "opendal-gcs", + feature = "opendal-azdls" + ))] + &self.credential_provider, )?; let storage = Arc::new(storage); cache.insert(scheme, storage.clone()); @@ -336,6 +398,19 @@ impl Storage for OpenDalResolvingStorage { Ok(()) } + #[cfg_attr( + not(any( + feature = "opendal-memory", + feature = "opendal-fs", + feature = "opendal-s3", + feature = "opendal-gcs", + feature = "opendal-oss", + feature = "opendal-azdls", + feature = "opendal-hf" + )), + // Without a backend, there is no storage to resolve. + allow(unreachable_code) + )] fn new_input(&self, path: &str) -> Result { Ok(InputFile::new( Arc::new(self.resolve(path)?.as_ref().clone()), @@ -343,6 +418,19 @@ impl Storage for OpenDalResolvingStorage { )) } + #[cfg_attr( + not(any( + feature = "opendal-memory", + feature = "opendal-fs", + feature = "opendal-s3", + feature = "opendal-gcs", + feature = "opendal-oss", + feature = "opendal-azdls", + feature = "opendal-hf" + )), + // Without a backend, there is no storage to resolve. + allow(unreachable_code) + )] fn new_output(&self, path: &str) -> Result { Ok(OutputFile::new( Arc::new(self.resolve(path)?.as_ref().clone()), @@ -355,9 +443,43 @@ impl Storage for OpenDalResolvingStorage { mod tests { use std::time::Duration; + use iceberg::io::StorageCredential; + + #[allow(unused_imports)] use super::*; use crate::OPENDAL_IO_TIMEOUT_MS; + #[derive(Debug)] + struct AllPathsCredentialProvider; + + #[async_trait] + impl StorageCredentialProvider for AllPathsCredentialProvider { + fn supports_path(&self, _path: &str) -> bool { + true + } + + async fn load_credential(&self, _path: &str) -> Result> { + unreachable!("resolving a storage never loads credentials") + } + } + + #[cfg(not(any( + feature = "opendal-s3", + feature = "opendal-gcs", + feature = "opendal-azdls" + )))] + #[test] + fn test_factory_ignores_credentials_without_compatible_backend() { + assert!( + OpenDalResolvingStorageFactory::new() + .build_with_credential_provider( + &StorageConfig::new(), + Some(Arc::new(AllPathsCredentialProvider)), + ) + .is_ok() + ); + } + #[cfg(feature = "opendal-s3")] #[derive(Debug)] struct EmptyCredentialLoader; @@ -396,6 +518,12 @@ mod tests { storages: RwLock::new(HashMap::new()), #[cfg(feature = "opendal-s3")] customized_credential_load: None, + #[cfg(any( + feature = "opendal-s3", + feature = "opendal-gcs", + feature = "opendal-azdls" + ))] + credential_provider: None, } } @@ -448,6 +576,22 @@ mod tests { assert!(Arc::ptr_eq(&a, &c), "s3 and s3n should share one instance"); } + #[cfg(all( + feature = "opendal-memory", + any( + feature = "opendal-s3", + feature = "opendal-gcs", + feature = "opendal-azdls" + ) + ))] + #[test] + fn test_resolver_ignores_credentials_for_unsupported_backend() { + let mut storage = empty_resolving_storage(); + storage.credential_provider = Some(Arc::new(AllPathsCredentialProvider)); + + assert!(storage.resolve("memory:/key").is_ok()); + } + #[cfg(feature = "opendal-hdfs-native")] #[test] fn test_resolve_hdfs_native_returns_hdfs_variant() { @@ -475,10 +619,42 @@ mod tests { ); } + #[cfg(any(feature = "opendal-s3", feature = "opendal-gcs"))] + #[test] + #[allow(unreachable_patterns)] + fn test_resolve_passes_the_credential_provider_to_s3_and_gcs() { + let mut storage = empty_resolving_storage(); + storage.credential_provider = Some(Arc::new(AllPathsCredentialProvider)); + + let paths: &[&str] = &[ + #[cfg(feature = "opendal-s3")] + "s3://bucket/key", + #[cfg(feature = "opendal-gcs")] + "gs://bucket/key", + ]; + for path in paths { + let has_provider = match storage.resolve(path).unwrap().as_ref() { + #[cfg(feature = "opendal-s3")] + OpenDalStorage::S3 { + credential_provider, + .. + } => credential_provider.is_some(), + #[cfg(feature = "opendal-gcs")] + OpenDalStorage::Gcs { + credential_provider, + .. + } => credential_provider.is_some(), + _ => false, + }; + assert!(has_provider, "{path}"); + } + } + #[cfg(feature = "opendal-azdls")] #[test] fn test_resolve_azdls_aliases_share_instance() { - let storage = empty_resolving_storage(); + let mut storage = empty_resolving_storage(); + storage.credential_provider = Some(Arc::new(AllPathsCredentialProvider)); let path_for = |scheme: &str| { format!("{scheme}://myfs@myaccount.dfs.core.windows.net/path/to/file.parquet") diff --git a/crates/storage/opendal/src/s3.rs b/crates/storage/opendal/src/s3.rs index 2997fa81d9..cef90535b8 100644 --- a/crates/storage/opendal/src/s3.rs +++ b/crates/storage/opendal/src/s3.rs @@ -22,7 +22,8 @@ use iceberg::io::{ CLIENT_REGION, S3_ACCESS_KEY_ID, S3_ALLOW_ANONYMOUS, S3_ASSUME_ROLE_ARN, S3_ASSUME_ROLE_EXTERNAL_ID, S3_ASSUME_ROLE_SESSION_NAME, S3_DISABLE_CONFIG_LOAD, S3_DISABLE_EC2_METADATA, S3_ENDPOINT, S3_PATH_STYLE_ACCESS, S3_REGION, S3_SECRET_ACCESS_KEY, - S3_SESSION_TOKEN, S3_SSE_KEY, S3_SSE_MD5, S3_SSE_TYPE, + S3_SESSION_TOKEN, S3_SESSION_TOKEN_EXPIRES_AT_MS, S3_SSE_KEY, S3_SSE_MD5, S3_SSE_TYPE, + StorageCredentialProvider, }; use iceberg::{Error, ErrorKind, Result}; use opendal::services::S3Config; @@ -31,10 +32,15 @@ use opendal::{Configurator, Operator}; pub use reqsign_aws_v4::Credential as AwsCredential; /// Trait for types that can asynchronously supply [`AwsCredential`] to a [`CustomAwsCredentialLoader`]. pub use reqsign_core::ProvideCredential; -use reqsign_core::{ProvideCredentialChain, ProvideCredentialDyn}; +use reqsign_core::{ + Context, ProvideCredentialChain, ProvideCredentialDyn, Result as ReqsignResult, +}; use url::Url; -use crate::utils::{from_opendal_error, is_truthy}; +use crate::utils::{ + VendedCredentialSource, credential_expiry, from_opendal_error, is_truthy, + required_credential_property, +}; /// Parse iceberg props to s3 config. pub(crate) fn s3_config_parse(mut m: HashMap) -> Result { @@ -129,7 +135,9 @@ pub(crate) fn s3_config_parse(mut m: HashMap) -> Result, + credential_provider: &Option>, path: &str, + credential_location: Option<&str>, ) -> Result { let url = Url::parse(path)?; let bucket = url.host_str().ok_or_else(|| { @@ -139,6 +147,19 @@ pub(crate) fn s3_config_build( ) })?; + // Preserve the existing custom-loader precedence: an explicitly configured loader + // is the sole source, otherwise install the credential provider as a replacement chain so + // refresh failures cannot fall through to broader ambient AWS credentials. + let credential_provider = credential_provider + .as_ref() + .filter(|provider| provider.supports_path(path)); + if customized_credential_load.is_none() && credential_provider.is_some() && cfg.skip_signature { + return Err(Error::new( + ErrorKind::DataInvalid, + "Invalid S3 auth settings: anonymous access cannot be combined with refreshable credentials", + )); + } + let mut builder = cfg .clone() .into_builder() @@ -148,11 +169,49 @@ pub(crate) fn s3_config_build( if let Some(loader) = customized_credential_load { let chain = ProvideCredentialChain::new().push(Arc::clone(&loader.0)); builder = builder.credential_provider_chain(chain); + } else if let Some(provider) = credential_provider { + let chain = ProvideCredentialChain::new().push(VendedS3CredentialProvider( + VendedCredentialSource::new( + Arc::clone(provider), + credential_location.unwrap_or(path).to_string(), + ), + )); + builder = builder.credential_provider_chain(chain); } Operator::new(builder).map_err(from_opendal_error) } +/// Adapts a generic [`StorageCredentialProvider`] into a reqsign +/// [`ProvideCredential`], so the S3 signer can obtain and refresh vended +/// credentials. +#[derive(Debug)] +struct VendedS3CredentialProvider(VendedCredentialSource); + +impl ProvideCredential for VendedS3CredentialProvider { + type Credential = AwsCredential; + + async fn provide_credential(&self, _ctx: &Context) -> ReqsignResult> { + let credential = self + .0 + .load("S3", |config| { + Ok(AwsCredential { + access_key_id: required_credential_property(config, S3_ACCESS_KEY_ID)? + .to_string(), + secret_access_key: required_credential_property(config, S3_SECRET_ACCESS_KEY)? + .to_string(), + session_token: config + .get(S3_SESSION_TOKEN) + .filter(|token| !token.is_empty()) + .cloned(), + expires_in: credential_expiry(config, S3_SESSION_TOKEN_EXPIRES_AT_MS)?, + }) + }) + .await?; + Ok(Some(credential)) + } +} + /// Custom AWS credential loader. /// /// Wraps any [`ProvideCredential`] implementation for use with the S3 storage backend. @@ -183,10 +242,95 @@ impl CustomAwsCredentialLoader { #[cfg(test)] mod tests { use std::collections::HashMap; + use std::sync::Arc; + + use async_trait::async_trait; + use iceberg::io::{GCS_TOKEN, S3_PATH_STYLE_ACCESS, StorageCredential}; + use reqsign_core::time::Timestamp; + + use super::*; + + #[derive(Debug)] + struct FixedProvider(StorageCredential); - use iceberg::io::S3_PATH_STYLE_ACCESS; + #[async_trait] + impl StorageCredentialProvider for FixedProvider { + fn supports_path(&self, _path: &str) -> bool { + true + } + + async fn load_credential(&self, _path: &str) -> Result> { + Ok(Arc::new(self.0.clone())) + } + } + + fn adapter(credential: StorageCredential) -> VendedS3CredentialProvider { + VendedS3CredentialProvider(VendedCredentialSource::new( + Arc::new(FixedProvider(credential)), + "s3://bucket/table/file.parquet".to_string(), + )) + } + + fn credential(prefix: &str, config: &[(&str, &str)]) -> StorageCredential { + StorageCredential::new( + prefix, + config + .iter() + .map(|(key, value)| (key.to_string(), value.to_string())) + .collect(), + ) + } - use super::s3_config_parse; + #[tokio::test] + async fn test_vended_adapter_returns_expiring_aws_credential() { + let credential = credential("s3://bucket/table", &[ + (S3_ACCESS_KEY_ID, "AK"), + (S3_SECRET_ACCESS_KEY, "SK"), + (S3_SESSION_TOKEN, "TOK"), + (S3_SESSION_TOKEN_EXPIRES_AT_MS, "1500"), + ]); + + let aws = adapter(credential) + .provide_credential(&Context::new()) + .await + .unwrap() + .unwrap(); + assert_eq!(aws.access_key_id, "AK"); + assert_eq!(aws.secret_access_key, "SK"); + assert_eq!(aws.session_token.as_deref(), Some("TOK")); + assert_eq!( + aws.expires_in, + Some(Timestamp::from_millisecond(1500).unwrap()) + ); + } + + #[tokio::test] + async fn test_vended_adapter_rejects_incomplete_or_uncovering_credentials() { + for credential in [ + // A credential for another backend. + credential("s3", &[(GCS_TOKEN, "token")]), + // No secret key. + credential("s3", &[(S3_ACCESS_KEY_ID, "AK")]), + // An unparsable expiry. + credential("s3", &[ + (S3_ACCESS_KEY_ID, "AK"), + (S3_SECRET_ACCESS_KEY, "SK"), + (S3_SESSION_TOKEN_EXPIRES_AT_MS, "soon"), + ]), + // A prefix that does not cover the path. + credential("s3://bucket/other", &[ + (S3_ACCESS_KEY_ID, "AK"), + (S3_SECRET_ACCESS_KEY, "SK"), + ]), + ] { + assert!( + adapter(credential) + .provide_credential(&Context::new()) + .await + .is_err() + ); + } + } fn parse_with(prop: Option<&str>) -> bool { let mut props = HashMap::new(); diff --git a/crates/storage/opendal/src/utils.rs b/crates/storage/opendal/src/utils.rs index 56f8c18059..b9b7998bbd 100644 --- a/crates/storage/opendal/src/utils.rs +++ b/crates/storage/opendal/src/utils.rs @@ -15,6 +15,21 @@ // specific language governing permissions and limitations // under the License. +use cfg_if::cfg_if; +use iceberg::io::StorageCredential; + +cfg_if! { + if #[cfg(any(feature = "opendal-s3", feature = "opendal-gcs", feature = "opendal-azdls"))] { + use std::collections::HashMap; + use std::sync::Arc; + + use iceberg::io::StorageCredentialProvider; + use reqsign_core::time::Timestamp; + use reqsign_core::{Error as ReqsignError, Result as ReqsignResult}; + } +} + +#[cfg(any(feature = "opendal-s3", feature = "opendal-gcs"))] pub(crate) fn is_truthy(value: &str) -> bool { ["true", "t", "1", "on"].contains(&value.to_lowercase().as_str()) } @@ -27,3 +42,318 @@ pub(crate) fn from_opendal_error(e: opendal::Error) -> iceberg::Error { ) .with_source(e) } + +/// The non-empty value of `key` in a vended credential's config. +#[cfg(any( + feature = "opendal-s3", + feature = "opendal-gcs", + feature = "opendal-azdls" +))] +pub(crate) fn required_credential_property<'a>( + config: &'a HashMap, + key: &str, +) -> ReqsignResult<&'a str> { + config + .get(key) + .map(String::as_str) + .filter(|value| !value.is_empty()) + .ok_or_else(|| ReqsignError::unexpected(format!("vended credential is missing {key}"))) +} + +/// The latest epoch millisecond `reqsign` timestamps can represent, +/// `9999-12-30T22:00:00Z`. +#[cfg(any( + feature = "opendal-s3", + feature = "opendal-gcs", + feature = "opendal-azdls" +))] +const MAX_TIMESTAMP_MILLIS: i64 = 253_402_207_200_000; + +/// The epoch-millisecond expiry under `key` in a vended credential's config, +/// if present, as the `reqsign` timestamp backend credentials use. Later +/// expiries, such as `Long.MAX_VALUE` for a credential that never expires, +/// are clamped to the latest representable timestamp. +#[cfg(any( + feature = "opendal-s3", + feature = "opendal-gcs", + feature = "opendal-azdls" +))] +pub(crate) fn credential_expiry( + config: &HashMap, + key: &str, +) -> ReqsignResult> { + config + .get(key) + .filter(|value| !value.is_empty()) + .map(|value| { + value + .parse::() + .ok() + .and_then(|millis| { + Timestamp::from_millisecond(millis.min(MAX_TIMESTAMP_MILLIS)).ok() + }) + .ok_or_else(|| { + ReqsignError::unexpected(format!("vended credential has an invalid {key}")) + }) + }) + .transpose() +} + +/// Validate that a provider's credential covers the location for which the +/// backend requested it. +#[cfg(any( + feature = "opendal-s3", + feature = "opendal-gcs", + feature = "opendal-azdls" +))] +pub(crate) fn validate_credential_prefix( + location: &str, + credential: &StorageCredential, +) -> ReqsignResult<()> { + if credential.covers(location) { + Ok(()) + } else { + Err(ReqsignError::unexpected(uncovered_location_message( + location, credential, + ))) + } +} + +/// The error message for a vended credential that does not cover `location`. +pub(crate) fn uncovered_location_message(location: &str, credential: &StorageCredential) -> String { + format!( + "vended credential prefix {:?} does not cover storage location {location:?}", + credential.prefix() + ) +} + +/// The root of the storage location containing `path`, e.g. `s3://bucket/`. +pub(crate) fn storage_root(path: &str) -> iceberg::Result { + let url = url::Url::parse(path)?; + Ok(format!("{}://{}/", url.scheme(), url.authority())) +} + +/// Loads vended credentials for one storage location on behalf of a backend's +/// `reqsign` credential provider. +#[cfg(any( + feature = "opendal-s3", + feature = "opendal-gcs", + feature = "opendal-azdls" +))] +pub(crate) struct VendedCredentialSource { + provider: Arc, + /// Location handed to the provider: the path an operator serves, or the + /// scope shared by a bulk-delete batch. + location: String, +} + +#[cfg(any( + feature = "opendal-s3", + feature = "opendal-gcs", + feature = "opendal-azdls" +))] +impl VendedCredentialSource { + pub(crate) fn new(provider: Arc, location: String) -> Self { + Self { provider, location } + } + + /// Load a credential covering the location and convert its config with + /// `extract` into the backend's credential. + /// + /// Errors are logged here: reqsign's credential chain replaces them with an + /// error that only says no credential could be loaded, and reports the + /// cause only through the `log` crate. They are logged at debug level, as + /// a failing provider fails every request; providers log their own + /// failures. + pub(crate) async fn load( + &self, + backend: &str, + extract: impl FnOnce(&HashMap) -> ReqsignResult, + ) -> ReqsignResult { + self.try_load(backend, extract).await.inspect_err(|error| { + tracing::debug!( + "cannot use vended {backend} credentials for {}: {error}", + self.location + ) + }) + } + + async fn try_load( + &self, + backend: &str, + extract: impl FnOnce(&HashMap) -> ReqsignResult, + ) -> ReqsignResult { + let credential = self + .provider + .load_credential(&self.location) + .await + .map_err(|e| { + ReqsignError::unexpected(format!( + "failed to load vended {backend} credential for {}: {e}", + self.location + )) + .with_source(e) + })?; + validate_credential_prefix(&self.location, &credential)?; + extract(credential.config()) + } +} + +#[cfg(any( + feature = "opendal-s3", + feature = "opendal-gcs", + feature = "opendal-azdls" +))] +impl std::fmt::Debug for VendedCredentialSource { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("VendedCredentialSource") + .field("location", &self.location) + .finish_non_exhaustive() + } +} + +#[cfg(all( + test, + any( + feature = "opendal-s3", + feature = "opendal-gcs", + feature = "opendal-azdls" + ) +))] +mod tests { + use std::sync::Mutex; + + use async_trait::async_trait; + use iceberg::io::{GCS_TOKEN, GCS_TOKEN_EXPIRES_AT}; + + use super::*; + + /// Returns a credential scoped to `prefix` and records requested locations. + #[derive(Debug)] + struct RecordingProvider { + prefix: &'static str, + requested: Mutex>, + } + + #[async_trait] + impl StorageCredentialProvider for RecordingProvider { + fn supports_path(&self, _path: &str) -> bool { + true + } + + async fn load_credential(&self, path: &str) -> iceberg::Result> { + self.requested.lock().unwrap().push(path.to_string()); + Ok(Arc::new(StorageCredential::new( + self.prefix, + HashMap::from([(GCS_TOKEN.to_string(), "token".to_string())]), + ))) + } + } + + async fn load(prefix: &'static str, location: &str) -> ReqsignResult<()> { + let provider = Arc::new(RecordingProvider { + prefix, + requested: Mutex::new(Vec::new()), + }); + let source = VendedCredentialSource::new(provider.clone(), location.to_string()); + let result = source + .load("GCS", |config| { + required_credential_property(config, GCS_TOKEN).map(|_| ()) + }) + .await; + assert_eq!(*provider.requested.lock().unwrap(), vec![location]); + result + } + + #[tokio::test] + async fn test_vended_source_requires_a_covering_credential() { + let location = "gs://bucket/table/data/file.parquet"; + assert!(load("gs", location).await.is_ok()); + assert!(load("gs://bucket/table", location).await.is_ok()); + assert!(load("gs://bucket/tab", location).await.is_ok()); + assert!( + load("gs://bucket/table/data/other", location) + .await + .is_err() + ); + assert!(load("gcs://bucket", location).await.is_err()); + assert!(load("", location).await.is_err()); + } + + #[test] + fn test_credential_properties_are_parsed() { + let config = HashMap::from([ + (GCS_TOKEN.to_string(), "token".to_string()), + (GCS_TOKEN_EXPIRES_AT.to_string(), "1500".to_string()), + ]); + assert_eq!( + required_credential_property(&config, GCS_TOKEN).unwrap(), + "token" + ); + assert!(required_credential_property(&config, "missing").is_err()); + assert_eq!( + credential_expiry(&config, GCS_TOKEN_EXPIRES_AT).unwrap(), + Some(Timestamp::from_millisecond(1500).unwrap()) + ); + assert_eq!(credential_expiry(&config, "missing").unwrap(), None); + // An expiry beyond year 9999, such as Java's `Long.MAX_VALUE`, is + // clamped rather than rejected. + let never = HashMap::from([(GCS_TOKEN_EXPIRES_AT.to_string(), i64::MAX.to_string())]); + assert_eq!( + credential_expiry(&never, GCS_TOKEN_EXPIRES_AT).unwrap(), + Some(Timestamp::from_millisecond(MAX_TIMESTAMP_MILLIS).unwrap()) + ); + // Pins the constant to the latest timestamp reqsign accepts. + assert!(Timestamp::from_millisecond(MAX_TIMESTAMP_MILLIS + 1).is_err()); + // The value is never quoted in the error. + let invalid = HashMap::from([(GCS_TOKEN_EXPIRES_AT.to_string(), "secret".to_string())]); + let error = credential_expiry(&invalid, GCS_TOKEN_EXPIRES_AT) + .unwrap_err() + .to_string(); + assert!(!error.contains("secret"), "{error}"); + } + + #[test] + fn test_storage_root_keeps_scheme_and_authority() { + assert_eq!( + storage_root("s3a://bucket/table/file.parquet").unwrap(), + "s3a://bucket/" + ); + assert_eq!( + storage_root("abfss://fs@account.dfs.core.windows.net/table/file.parquet").unwrap(), + "abfss://fs@account.dfs.core.windows.net/" + ); + assert!(storage_root("not a url").is_err()); + } + + #[derive(Debug)] + struct FailingProvider; + + #[async_trait] + impl StorageCredentialProvider for FailingProvider { + fn supports_path(&self, _path: &str) -> bool { + true + } + + async fn load_credential(&self, _path: &str) -> iceberg::Result> { + Err(iceberg::Error::new( + iceberg::ErrorKind::Unexpected, + "catalog returned 503", + )) + } + } + + #[tokio::test] + async fn test_vended_source_errors_carry_the_cause() { + let source = VendedCredentialSource::new( + Arc::new(FailingProvider), + "gs://bucket/file.parquet".to_string(), + ); + let error = source + .load("GCS", |_| Ok(())) + .await + .unwrap_err() + .to_string(); + assert!(error.contains("catalog returned 503"), "{error}"); + } +}