diff --git a/Cargo.lock b/Cargo.lock index eee54d5e..a165edea 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -203,7 +203,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" dependencies = [ "axum-core", - "axum-macros", "bytes", "form_urlencoded", "futures-util", @@ -249,58 +248,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "axum-extra" -version = "0.12.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be44683b41ccb9ab2d23a5230015c9c3c55be97a25e4428366de8873103f7970" -dependencies = [ - "axum", - "axum-core", - "bytes", - "cookie", - "futures-core", - "futures-util", - "headers", - "http", - "http-body", - "http-body-util", - "mime", - "pin-project-lite", - "tower-layer", - "tower-service", - "tracing", -] - -[[package]] -name = "axum-jwt-auth" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26502f886f3cda7cf02edfe0a5d34ea6a4a6db56850b7ae075d224ccbed08c61" -dependencies = [ - "axum", - "axum-extra", - "dashmap", - "jsonwebtoken", - "reqwest 0.12.28", - "serde", - "thiserror 2.0.18", - "tokio", - "tokio-util", - "tracing", -] - -[[package]] -name = "axum-macros" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7aa268c23bfbbd2c4363b9cd302a4f504fb2a9dfe7e3451d66f35dd392e20aca" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - [[package]] name = "axum-server" version = "0.8.0" @@ -366,6 +313,12 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" +[[package]] +name = "base64" +version = "0.21.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" + [[package]] name = "base64" version = "0.22.1" @@ -378,22 +331,6 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" -[[package]] -name = "biscuit" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e28fc7c56c61743a01d0d1b73e4fed68b8a4f032ea3a2d4bb8c6520a33fc05a" -dependencies = [ - "chrono", - "data-encoding", - "num-bigint", - "num-traits", - "once_cell", - "ring", - "serde", - "serde_json", -] - [[package]] name = "bitflags" version = "2.11.1" @@ -439,6 +376,15 @@ dependencies = [ "alloc-stdlib", ] +[[package]] +name = "bs58" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" +dependencies = [ + "tinyvec", +] + [[package]] name = "bumpalo" version = "3.20.2" @@ -645,7 +591,7 @@ dependencies = [ name = "contextforge-gateway-rs-apis" version = "0.1.0" dependencies = [ - "schemars", + "schemars 1.2.1", "serde", "serde_json", "url", @@ -658,7 +604,6 @@ dependencies = [ "anyhow", "async-trait", "axum", - "axum-jwt-auth", "axum-server", "axum-test", "bytes", @@ -671,11 +616,11 @@ dependencies = [ "http-body-util", "hyper", "hyper-util", - "itertools", + "itertools 0.14.0", "jsonwebtoken", "lru_time_cache", "mockito", - "openid", + "openidconnect", "openport", "redis", "reqwest 0.13.3", @@ -871,38 +816,14 @@ dependencies = [ "syn 2.0.117", ] -[[package]] -name = "darling" -version = "0.20.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" -dependencies = [ - "darling_core 0.20.11", - "darling_macro 0.20.11", -] - [[package]] name = "darling" version = "0.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d" dependencies = [ - "darling_core 0.23.0", - "darling_macro 0.23.0", -] - -[[package]] -name = "darling_core" -version = "0.20.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" -dependencies = [ - "fnv", - "ident_case", - "proc-macro2", - "quote", - "strsim", - "syn 2.0.117", + "darling_core", + "darling_macro", ] [[package]] @@ -918,42 +839,17 @@ dependencies = [ "syn 2.0.117", ] -[[package]] -name = "darling_macro" -version = "0.20.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" -dependencies = [ - "darling_core 0.20.11", - "quote", - "syn 2.0.117", -] - [[package]] name = "darling_macro" version = "0.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d" dependencies = [ - "darling_core 0.23.0", + "darling_core", "quote", "syn 2.0.117", ] -[[package]] -name = "dashmap" -version = "6.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5041cc499144891f3790297212f32a74fb938e5136a14943f338ef9e0ae276cf" -dependencies = [ - "cfg-if", - "crossbeam-utils", - "hashbrown 0.14.5", - "lock_api", - "once_cell", - "parking_lot_core", -] - [[package]] name = "data-encoding" version = "2.11.0" @@ -978,6 +874,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" dependencies = [ "powerfmt", + "serde_core", ] [[package]] @@ -1294,21 +1191,6 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" -[[package]] -name = "foreign-types" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" -dependencies = [ - "foreign-types-shared", -] - -[[package]] -name = "foreign-types-shared" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" - [[package]] name = "form_urlencoded" version = "1.2.2" @@ -1487,7 +1369,7 @@ dependencies = [ "futures", "gumdrop", "http", - "itertools", + "itertools 0.14.0", "lazy_static", "log", "num-format", @@ -1547,7 +1429,7 @@ dependencies = [ "futures-core", "futures-sink", "http", - "indexmap", + "indexmap 2.14.0", "slab", "tokio", "tokio-util", @@ -1556,9 +1438,9 @@ dependencies = [ [[package]] name = "hashbrown" -version = "0.14.5" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" [[package]] name = "hashbrown" @@ -1575,30 +1457,6 @@ version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" -[[package]] -name = "headers" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3314d5adb5d94bcdf56771f2e50dbbc80bb4bdf88967526706205ac9eff24eb" -dependencies = [ - "base64", - "bytes", - "headers-core", - "http", - "httpdate", - "mime", - "sha1", -] - -[[package]] -name = "headers-core" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54b4a22553d4242c49fddb9ba998a99962b5cc6f22cb5a3482bec22522403ce4" -dependencies = [ - "http", -] - [[package]] name = "heck" version = "0.5.0" @@ -1611,6 +1469,12 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + [[package]] name = "hkdf" version = "0.12.4" @@ -1629,12 +1493,6 @@ dependencies = [ "digest", ] -[[package]] -name = "hmac-sha256" -version = "1.1.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec9d92d097f4749b64e8cc33d924d9f40a2d4eb91402b458014b781f5733d60f" - [[package]] name = "http" version = "1.4.0" @@ -1737,29 +1595,13 @@ dependencies = [ "tower-service", ] -[[package]] -name = "hyper-tls" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" -dependencies = [ - "bytes", - "http-body-util", - "hyper", - "hyper-util", - "native-tls", - "tokio", - "tokio-native-tls", - "tower-service", -] - [[package]] name = "hyper-util" version = "0.1.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" dependencies = [ - "base64", + "base64 0.22.1", "bytes", "futures-channel", "futures-util", @@ -1917,6 +1759,17 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", + "serde", +] + [[package]] name = "indexmap" version = "2.14.0" @@ -1950,6 +1803,15 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" +[[package]] +name = "itertools" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" +dependencies = [ + "either", +] + [[package]] name = "itertools" version = "0.14.0" @@ -2042,7 +1904,7 @@ version = "10.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eba32bfb4ffdeaca3e34431072faf01745c9b26d25504aa7a6cf5684334fc4fc" dependencies = [ - "base64", + "base64 0.22.1", "ed25519-dalek", "getrandom 0.2.17", "hmac", @@ -2087,12 +1949,6 @@ version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" -[[package]] -name = "linux-raw-sys" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" - [[package]] name = "litemap" version = "0.8.2" @@ -2215,23 +2071,6 @@ dependencies = [ "tokio", ] -[[package]] -name = "native-tls" -version = "0.2.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2" -dependencies = [ - "libc", - "log", - "openssl", - "openssl-probe", - "openssl-sys", - "schannel", - "security-framework", - "security-framework-sys", - "tempfile", -] - [[package]] name = "nix" version = "0.31.3" @@ -2384,11 +2223,12 @@ version = "5.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51e219e79014df21a225b1860a479e2dcd7cbd9130f4defd4bd0e191ea31d67d" dependencies = [ - "base64", + "base64 0.22.1", "chrono", "getrandom 0.2.17", "http", "rand 0.8.6", + "reqwest 0.12.28", "serde", "serde_json", "serde_path_to_error", @@ -2425,23 +2265,34 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" [[package]] -name = "openid" -version = "0.23.0" +name = "openidconnect" +version = "4.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bac643ad786105ff8a3469ec4afcef267f62159b7c0e8a5399dbd97c26f7efcf" +checksum = "0d8c6709ba2ea764bbed26bce1adf3c10517113ddea6f2d4196e4851757ef2b2" dependencies = [ - "base64", - "biscuit", + "base64 0.21.7", "chrono", - "getrandom 0.4.2", - "hmac-sha256", - "mime", - "reqwest 0.13.3", + "dyn-clone", + "ed25519-dalek", + "hmac", + "http", + "itertools 0.10.5", + "log", + "oauth2", + "p256", + "p384", + "rand 0.8.6", + "rsa", "serde", + "serde-value", "serde_json", - "thiserror 2.0.18", + "serde_path_to_error", + "serde_plain", + "serde_with", + "sha2", + "subtle", + "thiserror 1.0.69", "url", - "validator", ] [[package]] @@ -2453,49 +2304,12 @@ dependencies = [ "rand 0.8.6", ] -[[package]] -name = "openssl" -version = "0.10.79" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf0b434746ee2832f4f0baf10137e1cabb18cbe6912c69e2e33263c45250f542" -dependencies = [ - "bitflags", - "cfg-if", - "foreign-types", - "libc", - "openssl-macros", - "openssl-sys", -] - -[[package]] -name = "openssl-macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - [[package]] name = "openssl-probe" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" -[[package]] -name = "openssl-sys" -version = "0.9.115" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "158fe5b292746440aa6e7a7e690e55aeb72d41505e2804c23c6973ad0e9c9781" -dependencies = [ - "cc", - "libc", - "pkg-config", - "vcpkg", -] - [[package]] name = "opentelemetry" version = "0.31.0" @@ -2572,6 +2386,15 @@ dependencies = [ "tokio-stream", ] +[[package]] +name = "ordered-float" +version = "2.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c" +dependencies = [ + "num-traits", +] + [[package]] name = "p256" version = "0.13.2" @@ -2637,7 +2460,7 @@ version = "3.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" dependencies = [ - "base64", + "base64 0.22.1", "serde_core", ] @@ -2762,28 +2585,6 @@ dependencies = [ "elliptic-curve", ] -[[package]] -name = "proc-macro-error-attr2" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5" -dependencies = [ - "proc-macro2", - "quote", -] - -[[package]] -name = "proc-macro-error2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802" -dependencies = [ - "proc-macro-error-attr2", - "proc-macro2", - "quote", - "syn 2.0.117", -] - [[package]] name = "proc-macro2" version = "1.0.106" @@ -2810,7 +2611,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "27c6023962132f4b30eb4c172c91ce92d933da334c59c23cddee82358ddafb0b" dependencies = [ "anyhow", - "itertools", + "itertools 0.14.0", "proc-macro2", "quote", "syn 2.0.117", @@ -3080,7 +2881,7 @@ version = "0.12.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" dependencies = [ - "base64", + "base64 0.22.1", "bytes", "futures-channel", "futures-core", @@ -3120,7 +2921,7 @@ version = "0.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "62e0021ea2c22aed41653bc7e1419abb2c97e038ff2c33d0e1309e49a97deec0" dependencies = [ - "base64", + "base64 0.22.1", "bytes", "cookie", "cookie_store", @@ -3133,12 +2934,10 @@ dependencies = [ "http-body-util", "hyper", "hyper-rustls", - "hyper-tls", "hyper-util", "js-sys", "log", "mime", - "native-tls", "percent-encoding", "pin-project-lite", "quinn", @@ -3150,7 +2949,6 @@ dependencies = [ "serde_urlencoded", "sync_wrapper", "tokio", - "tokio-native-tls", "tokio-rustls", "tokio-util", "tower", @@ -3202,7 +3000,7 @@ version = "1.6.0" source = "git+https://github.com/contextforge-gateway-rs/mcp-rust-sdk?branch=enabling_propagation_of_new_session_id_2#d07fa4f8d7978cd0829a09fab181437b99a81878" dependencies = [ "async-trait", - "base64", + "base64 0.22.1", "bytes", "chrono", "futures", @@ -3215,7 +3013,7 @@ dependencies = [ "rand 0.10.1", "reqwest 0.13.3", "rmcp-macros", - "schemars", + "schemars 1.2.1", "serde", "serde_json", "sse-stream", @@ -3234,7 +3032,7 @@ name = "rmcp-macros" version = "1.6.0" source = "git+https://github.com/contextforge-gateway-rs/mcp-rust-sdk?branch=enabling_propagation_of_new_session_id_2#d07fa4f8d7978cd0829a09fab181437b99a81878" dependencies = [ - "darling 0.23.0", + "darling", "proc-macro2", "quote", "serde_json", @@ -3310,19 +3108,6 @@ dependencies = [ "semver", ] -[[package]] -name = "rustix" -version = "1.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" -dependencies = [ - "bitflags", - "errno", - "libc", - "linux-raw-sys", - "windows-sys 0.61.2", -] - [[package]] name = "rustls" version = "0.23.40" @@ -3430,6 +3215,18 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "schemars" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + [[package]] name = "schemars" version = "1.2.1" @@ -3516,6 +3313,16 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "serde-value" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c" +dependencies = [ + "ordered-float", + "serde", +] + [[package]] name = "serde_core" version = "1.0.228" @@ -3553,7 +3360,7 @@ version = "1.0.149" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" dependencies = [ - "indexmap", + "indexmap 2.14.0", "itoa", "memchr", "serde", @@ -3572,6 +3379,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "serde_plain" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce1fc6db65a611022b23a0dec6975d63fb80a302cb3388835ff02c097258d50" +dependencies = [ + "serde", +] + [[package]] name = "serde_urlencoded" version = "0.7.1" @@ -3584,6 +3400,38 @@ dependencies = [ "serde", ] +[[package]] +name = "serde_with" +version = "3.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e72c1c2cb7b223fafb600a619537a871c2818583d619401b785e7c0b746ccde2" +dependencies = [ + "base64 0.22.1", + "bs58", + "chrono", + "hex", + "indexmap 1.9.3", + "indexmap 2.14.0", + "schemars 0.9.0", + "schemars 1.2.1", + "serde_core", + "serde_json", + "serde_with_macros", + "time", +] + +[[package]] +name = "serde_with_macros" +version = "3.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b90c488738ecb4fb0262f41f43bc40efc5868d9fb744319ddf5f5317f417bfac" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "sha1" version = "0.10.6" @@ -3857,19 +3705,6 @@ dependencies = [ "libc", ] -[[package]] -name = "tempfile" -version = "3.27.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" -dependencies = [ - "fastrand", - "getrandom 0.4.2", - "once_cell", - "rustix", - "windows-sys 0.61.2", -] - [[package]] name = "termcolor" version = "1.4.1" @@ -4066,16 +3901,6 @@ dependencies = [ "syn 2.0.117", ] -[[package]] -name = "tokio-native-tls" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" -dependencies = [ - "native-tls", - "tokio", -] - [[package]] name = "tokio-rustls" version = "0.26.4" @@ -4129,7 +3954,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef" dependencies = [ "async-trait", - "base64", + "base64 0.22.1", "bytes", "http", "http-body", @@ -4167,7 +3992,7 @@ checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" dependencies = [ "futures-core", "futures-util", - "indexmap", + "indexmap 2.14.0", "pin-project-lite", "slab", "sync_wrapper", @@ -4185,7 +4010,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68d6fdd9f81c2819c9a8b0e0cd91660e7746a8e6ea2ba7c6b2b057985f6bcb51" dependencies = [ "async-compression", - "base64", + "base64 0.22.1", "bitflags", "bytes", "futures-core", @@ -4457,48 +4282,12 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "validator" -version = "0.20.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43fb22e1a008ece370ce08a3e9e4447a910e92621bb49b85d6e48a45397e7cfa" -dependencies = [ - "idna", - "once_cell", - "regex", - "serde", - "serde_derive", - "serde_json", - "url", - "validator_derive", -] - -[[package]] -name = "validator_derive" -version = "0.20.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7df16e474ef958526d1205f6dda359fdfab79d9aa6d54bafcb92dcd07673dca" -dependencies = [ - "darling 0.20.11", - "once_cell", - "proc-macro-error2", - "proc-macro2", - "quote", - "syn 2.0.117", -] - [[package]] name = "valuable" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" -[[package]] -name = "vcpkg" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" - [[package]] name = "version_check" version = "0.9.5" @@ -4620,7 +4409,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" dependencies = [ "anyhow", - "indexmap", + "indexmap 2.14.0", "wasm-encoder", "wasmparser", ] @@ -4646,7 +4435,7 @@ checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" dependencies = [ "bitflags", "hashbrown 0.15.5", - "indexmap", + "indexmap 2.14.0", "semver", ] @@ -4957,7 +4746,7 @@ checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" dependencies = [ "anyhow", "heck", - "indexmap", + "indexmap 2.14.0", "prettyplease", "syn 2.0.117", "wasm-metadata", @@ -4988,7 +4777,7 @@ checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" dependencies = [ "anyhow", "bitflags", - "indexmap", + "indexmap 2.14.0", "log", "serde", "serde_derive", @@ -5007,7 +4796,7 @@ checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" dependencies = [ "anyhow", "id-arena", - "indexmap", + "indexmap 2.14.0", "log", "semver", "serde", diff --git a/Cargo.toml b/Cargo.toml index fd260270..4723bd8e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -47,9 +47,8 @@ tower-http = { version = "0.6.8", features = ["full"] } tower-layer = "0.3.3" tower = "0.5.3" http = "1.4.0" -axum-jwt-auth = "0.6.3" futures = { version = "0.3", features = ["std", "alloc"] } -jsonwebtoken = "10.3.0" +jsonwebtoken = {version= "10.3.0", features=["rust_crypto"]} chrono = "0.4.44" redis = { version = "1.2.1", features = [ "default", @@ -59,7 +58,6 @@ redis = { version = "1.2.1", features = [ ] } clap = { version = "4.5.60", features = ["derive", "env"] } thiserror = "2.0.18" -openid = "0.23.0" url = "2.5.8" rmp-serde = "1.3.1" async-trait = "0.1.89" diff --git a/crates/contextforge-gateway-rs-apis/src/main.rs b/crates/contextforge-gateway-rs-apis/src/main.rs index b7b8d3e7..97eba7e1 100644 --- a/crates/contextforge-gateway-rs-apis/src/main.rs +++ b/crates/contextforge-gateway-rs-apis/src/main.rs @@ -1,7 +1,6 @@ use std::fs; use contextforge_gateway_rs_apis::{User, user_store}; - use schemars::SchemaGenerator; use user_store::UserConfig; #[allow(clippy::print_stdout)] diff --git a/crates/contextforge-gateway-rs-lib/Cargo.toml b/crates/contextforge-gateway-rs-lib/Cargo.toml index 5c931826..b9e103e3 100644 --- a/crates/contextforge-gateway-rs-lib/Cargo.toml +++ b/crates/contextforge-gateway-rs-lib/Cargo.toml @@ -25,14 +25,13 @@ tower-http.workspace = true tower-layer.workspace = true tower.workspace = true http.workspace = true -axum-jwt-auth.workspace = true futures.workspace = true jsonwebtoken.workspace = true chrono.workspace = true redis.workspace = true clap.workspace = true thiserror.workspace = true -openid.workspace = true +openidconnect = "4.0.1" url.workspace = true rmp-serde.workspace = true async-trait.workspace = true @@ -47,7 +46,6 @@ hyper-util = "0.1.20" hyper = { version = "1.4.0" } rustls.workspace = true rustls-pki-types = { version = "1.14.1", features = ["std","alloc"] } - tokio-rustls = "0.26.4" typed-builder.workspace = true diff --git a/crates/contextforge-gateway-rs-lib/src/common.rs b/crates/contextforge-gateway-rs-lib/src/common.rs index 4b408da0..0ec055da 100644 --- a/crates/contextforge-gateway-rs-lib/src/common.rs +++ b/crates/contextforge-gateway-rs-lib/src/common.rs @@ -6,41 +6,94 @@ use std::{ sync::Arc, }; -use axum_jwt_auth::JwtDecoder; -use chrono::{Duration, Utc}; +use chrono::Duration; use clap::{Parser, ValueEnum}; use http::uri::Authority; -use openid::{CompactJson, CustomClaims, StandardClaims}; +use jsonwebtoken::DecodingKey; use redis::{ConnectionAddr, IntoConnectionInfo, RedisError}; - use rustls_pki_types::{CertificateDer, PrivatePkcs8KeyDer, pem::PemObject}; use serde::{Deserialize, Serialize}; use thiserror::Error; -use url::Url; +use typed_builder::TypedBuilder; +use uuid::Uuid; + +use crate::{ + const_values::{CONTEXT_FORGE_GATEWAY_AUDIENCE, CONTEXT_FORGE_GATEWAY_ISSUER}, + user_config_store::UserConfigStore, +}; -use crate::{const_values::CONEXT_FORGE_GATEWAY_AUDIENCE, user_config_store::UserConfigStore}; +#[derive(Clone)] +pub struct JwtTokenDecoders { + pub rs: Option, + pub hmac_sha: Option, +} #[derive(Clone)] pub struct ContextForgeGatewayAppState { - pub(crate) jwt_token_decoder: Arc + Send + Sync>, + pub(crate) jwt_token_decoding_keys: JwtTokenDecoders, pub(crate) config_store: Arc, pub(crate) config: Config, } -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct ContextForgeGatewayClaims { - pub additional_claim: Option, - #[serde(flatten)] - pub standard_claims: StandardClaims, +#[derive(Clone, Debug, Serialize, Deserialize, TypedBuilder)] +pub struct User { + email: String, + full_name: String, + is_admin: bool, + auth_provider: String, } -impl CustomClaims for ContextForgeGatewayClaims { - fn standard_claims(&self) -> &StandardClaims { - &self.standard_claims - } +#[derive(Clone, Debug, Serialize, Deserialize, TypedBuilder)] +pub struct Scopes { + server_id: Option, + permissions: Vec, + ip_restrictions: Vec, + time_restrictions: Option, } -impl CompactJson for ContextForgeGatewayClaims {} +#[derive(Clone, Debug, Serialize, Deserialize, TypedBuilder)] +pub struct ContextForgeClaims { + pub sub: String, + pub jti: String, + pub token_use: String, + pub iat: Option, + pub iss: String, + pub aud: String, + pub exp: u64, + pub teams: Option>, + pub user: User, + pub scopes: Scopes, +} + +impl ContextForgeClaims { + pub fn new(user_id: &str) -> Self { + let audience = CONTEXT_FORGE_GATEWAY_AUDIENCE.to_owned(); + let start = std::time::SystemTime::now(); + let now = start.duration_since(std::time::UNIX_EPOCH).expect("Time went backwards").as_secs(); + Self { + iss: CONTEXT_FORGE_GATEWAY_ISSUER.to_owned(), + sub: user_id.to_owned(), + aud: audience, + exp: now + Duration::hours(1).num_seconds().cast_unsigned(), + iat: Some(now), + jti: Uuid::new_v4().to_string(), + token_use: "api".to_owned(), + teams: Some(vec!["team_awesome".to_owned()]), + user: User::builder() + .email(user_id.to_owned()) + .auth_provider("api_token".to_owned()) + .full_name("API Token User".to_owned()) + .is_admin(true) + .build(), + scopes: Scopes::builder() + .server_id(Some("my_id".to_owned())) + .ip_restrictions(vec!["192.169.1.0/24".to_owned()]) + .permissions(vec!["tools.read".to_owned(), "servers.use".to_owned()]) + .time_restrictions(None) + .build(), + } + } +} pub type RedisClient = redis::Client; @@ -110,12 +163,15 @@ pub struct Config { pub address: Option, #[arg(long, env = "CONTEXTFORGE_GATEWAY_RS_TOKEN_VERIFICATION_PUBLIC_KEY")] - pub token_verification_public_key: PathBuf, + pub token_verification_public_key: Option, #[cfg(feature = "with_tools")] #[arg(long, env = "CONTEXTFORGE_GATEWAY_RS_TOKEN_VERIFICATION_PRIVATE_KEY")] pub token_verification_private_key: PathBuf, + #[arg(long, env = "CONTEXTFORGE_GATEWAY_RS_TOKEN_SECRET")] + pub token_verification_secret: Option, + #[arg(long, env = "CONTEXTFORGE_GATEWAY_RS_ENABLE_OPEN_TELEMETRY")] pub enable_open_telemetry: Option, @@ -301,38 +357,12 @@ impl TryFrom<&Config> for reqwest::Client { fn extract_identity(config: &Config) -> crate::Result { match (config.upstream_private_key.as_ref(), config.upstream_certificate.as_ref()) { (Some(private_key), Some(certificate)) => { - let cert = fs::read(certificate)?; + let mut cert = fs::read(certificate)?; let key = fs::read(private_key)?; - Ok(reqwest::Identity::from_pkcs8_pem(&cert, &key)?) + cert.extend(key); + Ok(reqwest::Identity::from_pem(&cert)?) }, _ => Err("Invalid/missing configuration".into()), } } - -#[derive(Deserialize, Serialize)] -pub struct DefaultClaims { - iss: Url, - sub: String, - aud: String, - exp: i64, - iat: Option, - userinfo: openid::Userinfo, -} - -impl DefaultClaims { - pub fn new(user_id: String) -> Self { - let url = "http://contextforge-gateway-rs".parse().expect("Expecting this to work"); - let audience = CONEXT_FORGE_GATEWAY_AUDIENCE.to_owned(); - let user_info = openid::Userinfo { sub: user_id.clone(), ..Default::default() }; - Self { - iss: url, - sub: user_id, - aud: audience, - exp: (Utc::now() + Duration::hours(1)).timestamp(), - iat: Some(Utc::now().timestamp()), - - userinfo: user_info, - } - } -} diff --git a/crates/contextforge-gateway-rs-lib/src/const_values.rs b/crates/contextforge-gateway-rs-lib/src/const_values.rs index 545771ef..892c3d50 100644 --- a/crates/contextforge-gateway-rs-lib/src/const_values.rs +++ b/crates/contextforge-gateway-rs-lib/src/const_values.rs @@ -2,5 +2,7 @@ use std::time::Duration; pub const LRU_CACHE_ENTRIES: usize = 50_000; pub const LRU_CACHE_EXPIRY_DURATION: Duration = Duration::from_hours(1); -pub const CONEXT_FORGE_GATEWAY_AUDIENCE: &str = "mcp-audience"; +pub const CONTEXT_FORGE_GATEWAY_AUDIENCE: &str = "mcpgateway-api"; +pub const CONTEXT_FORGE_GATEWAY_ISSUER: &str = "mcpgateway"; pub const MCP_SESSION_ID: &str = "mcp-session-id"; +pub const REDIS_RETRIES: usize = 1000; // keep re-trying forver diff --git a/crates/contextforge-gateway-rs-lib/src/gateway/session_store/redis_session_store.rs b/crates/contextforge-gateway-rs-lib/src/gateway/session_store/redis_session_store.rs index a6572763..71de4ab9 100644 --- a/crates/contextforge-gateway-rs-lib/src/gateway/session_store/redis_session_store.rs +++ b/crates/contextforge-gateway-rs-lib/src/gateway/session_store/redis_session_store.rs @@ -12,7 +12,7 @@ use tokio::sync::Mutex; use super::{SessionMapping, SessionStoreError, UserSession, UserSessionStore}; use crate::{ common::RedisClient, - const_values::{LRU_CACHE_ENTRIES, LRU_CACHE_EXPIRY_DURATION}, + const_values::{LRU_CACHE_ENTRIES, LRU_CACHE_EXPIRY_DURATION, REDIS_RETRIES}, }; #[derive(Clone)] @@ -30,7 +30,9 @@ impl RedisUserSessionStore { LRU_CACHE_ENTRIES, ))), connection: redis_client - .get_connection_manager_with_config(ConnectionManagerConfig::default()) + .get_connection_manager_with_config( + ConnectionManagerConfig::default().set_number_of_retries(REDIS_RETRIES), + ) .await .map_err(|_| SessionStoreError::InvalidConnection)?, }) diff --git a/crates/contextforge-gateway-rs-lib/src/layers/claims_id.rs b/crates/contextforge-gateway-rs-lib/src/layers/claims_id.rs index bb101273..4535330f 100644 --- a/crates/contextforge-gateway-rs-lib/src/layers/claims_id.rs +++ b/crates/contextforge-gateway-rs-lib/src/layers/claims_id.rs @@ -1,115 +1,190 @@ -// use std::{ -// pin::Pin, -// sync::Arc, -// task::{Context, Poll}, -// }; - -// use axum::{ -// body::Body, -// extract::{FromRequest, FromRequestParts, State}, -// http::Request, -// middleware::Next, -// response::{IntoResponse, Response}, -// }; -// use axum_jwt_auth::{Claims, Decoder, JwtDecoder}; -// use futures::{FutureExt, future::BoxFuture}; -// use http::{StatusCode, header, request::Parts}; -// use serde::{Deserialize, Serialize, de::DeserializeOwned}; -// use tower::Service; - -// use tower_layer::Layer; -// use tracing::{info, warn}; - use axum::{ body::Body, - extract::{FromRequestParts, Request, State}, + extract::{Request, State}, middleware::Next, response::Response, }; -use axum_jwt_auth::Claims; use http::{StatusCode, header}; -use tracing::warn; - -use crate::common::{ContextForgeGatewayAppState, ContextForgeGatewayClaims}; - -// #[derive(Clone)] -// pub struct ClaimsLayer { -// pub decoder: Arc + Send + Sync + 'static>, -// } - -// impl Layer for ClaimsLayer { -// type Service = ClaimsService; - -// fn layer(&self, service: S) -> Self::Service { -// ClaimsService { -// service, -// decoder: Arc::clone(&self.decoder), -// } -// } -// } - -// #[derive(Clone)] -// pub struct ClaimsService { -// service: S, -// decoder: Arc + Send + Sync>, -// } - -// impl Service> for ClaimsService -// where -// S: Service> + Send + Sync + 'static + Clone, -// B: Send + Sync + 'static, -// { -// type Response = S::Response; -// type Error = S::Error; -// type Future = -// Pin> + Send + Sync + 'static>>; -// //type Future = Box>>::Future> + 'static> - -// //Result<>>::Response, >>::Error>, - -// fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { -// self.service.poll_ready(cx) -// } - -// fn call(&mut self, request: Request) -> Self::Future { -// let (mut parts, body) = request.into_parts(); -// let mut new_parts = parts.clone(); -// let mut new_self = self.clone(); -// let future = async { -// // if let Ok(claims) = -// // Claims::::from_request_parts(&mut new_parts, &new_self.decoder).await -// // { -// // parts.extensions.insert(claims.claims); -// // }; -// let request = Request::from_parts(parts, body); -// let response = new_self.service.call(request).await; -// response -// }; - -// Box::pin(future) -// } -// } +use jsonwebtoken::Validation; + +use crate::{ + common::{ContextForgeClaims, ContextForgeGatewayAppState}, + const_values::{CONTEXT_FORGE_GATEWAY_AUDIENCE, CONTEXT_FORGE_GATEWAY_ISSUER}, +}; + +fn unauthorized_response() -> Response { + Response::builder() + .status(StatusCode::UNAUTHORIZED) + .header(header::CONTENT_TYPE, "text/plain") + .body(Body::empty()) + .expect("Expecting this to work") +} pub async fn claims_layer( State(state): State, request: http::Request, next: Next, ) -> Response { + let decoding_keys = state.jwt_token_decoding_keys; let (mut parts, body) = request.into_parts(); - let mut new_parts = parts.clone(); - let decoder = state.jwt_token_decoder; - let maybe_claims = Claims::::from_request_parts(&mut new_parts, &decoder).await; - if let Ok(claims) = maybe_claims { - parts.extensions.insert(claims.claims); - let request = Request::from_parts(parts, body); - next.run(request).await - } else { - let err = maybe_claims.err(); - warn!("No claims {:?}", err); - Response::builder() - .status(StatusCode::BAD_REQUEST) - .header(header::CONTENT_TYPE, "text/plain") - .body(Body::from(format!("Invalid authorization token {err:?}"))) - .expect("Expecting this to work") + + let Some(authorization) = parts.headers.get("Authorization") else { return unauthorized_response() }; + + let Some(token) = authorization.as_bytes().strip_prefix(b"Bearer ") else { return unauthorized_response() }; + + let Ok(raw_token) = str::from_utf8(token) else { return unauthorized_response() }; + + let Ok(header) = jsonwebtoken::decode_header(raw_token) else { return unauthorized_response() }; + + let mut validation = Validation::new(header.alg); + validation.set_audience(&[CONTEXT_FORGE_GATEWAY_AUDIENCE]); + validation.set_issuer(&[CONTEXT_FORGE_GATEWAY_ISSUER]); + validation.validate_exp = true; + + let claims = match header.alg { + jsonwebtoken::Algorithm::RS256 | jsonwebtoken::Algorithm::RS384 | jsonwebtoken::Algorithm::RS512 => { + let Some(decoding_key) = decoding_keys.rs.as_ref() else { + return Response::builder() + .status(StatusCode::UNAUTHORIZED) + .header(header::CONTENT_TYPE, "text/plain") + .body(Body::empty()) + .expect("Expecting this to work"); + }; + let maybe_valid = jsonwebtoken::decode::(raw_token, decoding_key, &validation); + let Ok(claims) = maybe_valid else { return unauthorized_response() }; + claims + }, + jsonwebtoken::Algorithm::HS256 | jsonwebtoken::Algorithm::HS384 | jsonwebtoken::Algorithm::HS512 => { + let Some(decoding_key) = decoding_keys.hmac_sha.as_ref() else { return unauthorized_response() }; + let maybe_valid = jsonwebtoken::decode::(raw_token, decoding_key, &validation); + let Ok(claims) = maybe_valid else { return unauthorized_response() }; + + claims + }, + + _ => return unauthorized_response(), + }; + + let claims: ContextForgeClaims = claims.claims; + parts.extensions.insert(claims.clone()); + let request = Request::from_parts(parts, body); + next.run(request).await +} + +#[cfg(test)] +mod test { + + use std::sync::{Arc, Once}; + + use async_trait::async_trait; + use axum::{Router, body::Body, middleware, response::Response, routing::get}; + use contextforge_gateway_rs_apis::{User, user_store::UserConfig}; + use http::{HeaderMap, Request, StatusCode}; + use jsonwebtoken::{DecodingKey, Validation}; + use tower::ServiceExt; + + use crate::{ + Config, + common::{ContextForgeClaims, ContextForgeGatewayAppState, JwtTokenDecoders}, + const_values::{CONTEXT_FORGE_GATEWAY_AUDIENCE, CONTEXT_FORGE_GATEWAY_ISSUER}, + layers::claims_id::claims_layer, + tests, + user_config_store::{ConfigStoreError, UserConfigStore}, + }; + + static CRYPTO: Once = Once::new(); + + struct MockedUserConfigStore; + #[async_trait] + impl UserConfigStore for MockedUserConfigStore { + async fn get_config<'a>(&self, _: &'a User) -> Result { + Err(ConfigStoreError::InvalidConnection) + } + + async fn set_config<'a>(&self, _: &'a User, _: &'a UserConfig) -> Result<(), ConfigStoreError> { + Err(ConfigStoreError::InvalidConnection) + } + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 1)] + #[allow(clippy::items_after_statements)] + async fn claim_test_valid_hmac() { + CRYPTO.call_once(|| { + rustls::crypto::ring::default_provider() + .install_default() + .expect("Failed to install rustls crypto provider"); + }); + + async fn handle(_: HeaderMap) -> Response { + Response::builder().status(StatusCode::OK).body(Body::empty()).expect("Expecting this to work") + } + + let token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhZG1pbkBleGFtcGxlLmNvbSIsImp0aSI6Ijc1ZWYwZTZjLTZkZWMtNGExNy1hNzU3LWFlYmYzZjk1N2Q1NSIsInRva2VuX3VzZSI6ImFwaSIsImlhdCI6MTc3ODg2NTE2OCwiaXNzIjoibWNwZ2F0ZXdheSIsImF1ZCI6Im1jcGdhdGV3YXktYXBpIiwidXNlciI6eyJlbWFpbCI6ImFkbWluQGV4YW1wbGUuY29tIiwiZnVsbF9uYW1lIjoiQVBJIFRva2VuIFVzZXIiLCJpc19hZG1pbiI6dHJ1ZSwiYXV0aF9wcm92aWRlciI6ImFwaV90b2tlbiJ9LCJ0ZWFtcyI6bnVsbCwic2NvcGVzIjp7InNlcnZlcl9pZCI6bnVsbCwicGVybWlzc2lvbnMiOltdLCJpcF9yZXN0cmljdGlvbnMiOltdLCJ0aW1lX3Jlc3RyaWN0aW9ucyI6e319LCJleHAiOjE3ODE0NTcxNjh9.9d2-iLOHL2dJRFTSbOxHzuD6zLxupqK0ZkCG-3GZABU"; + + let mut validation = Validation::new(jsonwebtoken::Algorithm::HS256); + validation.set_audience(&[CONTEXT_FORGE_GATEWAY_AUDIENCE]); + validation.set_issuer(&[CONTEXT_FORGE_GATEWAY_ISSUER]); + validation.validate_exp = false; + + let decoding_key = DecodingKey::from_secret("my-test-key-but-now-longer-than-32-bytes".as_bytes()); + + let state = ContextForgeGatewayAppState { + jwt_token_decoding_keys: JwtTokenDecoders { rs: None, hmac_sha: Some(decoding_key) }, + config_store: Arc::new(MockedUserConfigStore {}), + config: Config::default(), + }; + let http_requst = Request::builder() + .header("Authorization", format!("Bearer {token}")) + .method("GET") + .body(Body::empty()) + .expect("This should work"); + + let app = + Router::new().route("/", get(handle)).layer(middleware::from_fn_with_state(state.clone(), claims_layer)); + + let res = app.oneshot(http_requst).await.unwrap(); + assert_eq!(res.status(), StatusCode::OK); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 1)] + #[allow(clippy::items_after_statements)] + async fn claim_test_expired_token() { + CRYPTO.call_once(|| { + rustls::crypto::ring::default_provider() + .install_default() + .expect("Failed to install rustls crypto provider"); + }); + + async fn handle(_: HeaderMap) -> Response { + Response::builder().status(StatusCode::OK).body(Body::empty()).expect("Expecting this to work") + } + + let mut claims = ContextForgeClaims::new("blah@blah.com"); + claims.exp = 0; + let token = tests::gateway_end_to_end::get_token_for_claims(&claims); + + let mut validation = Validation::new(jsonwebtoken::Algorithm::RS256); + validation.set_audience(&[CONTEXT_FORGE_GATEWAY_AUDIENCE]); + validation.set_issuer(&[CONTEXT_FORGE_GATEWAY_ISSUER]); + validation.validate_exp = true; + + let decoding_key = DecodingKey::from_secret("my-test-key-but-now-longer-than-32-bytes".as_bytes()); + + let state = ContextForgeGatewayAppState { + jwt_token_decoding_keys: JwtTokenDecoders { rs: None, hmac_sha: Some(decoding_key) }, + config_store: Arc::new(MockedUserConfigStore {}), + config: Config::default(), + }; + let http_requst = Request::builder() + .header("Authorization", format!("Bearer {token}")) + .method("GET") + .body(Body::empty()) + .expect("This should work"); + + let app = + Router::new().route("/", get(handle)).layer(middleware::from_fn_with_state(state.clone(), claims_layer)); + + let res = app.oneshot(http_requst).await.unwrap(); + assert_eq!(res.status(), StatusCode::UNAUTHORIZED); } } diff --git a/crates/contextforge-gateway-rs-lib/src/layers/user_config_store.rs b/crates/contextforge-gateway-rs-lib/src/layers/user_config_store.rs index 7cadeaab..81371f1c 100644 --- a/crates/contextforge-gateway-rs-lib/src/layers/user_config_store.rs +++ b/crates/contextforge-gateway-rs-lib/src/layers/user_config_store.rs @@ -1,11 +1,11 @@ use axum::{body::Body, extract::State, middleware::Next, response::Response}; use contextforge_gateway_rs_apis::User; use http::{StatusCode, header}; -use openid::Claims; +//use openid::Claims; use tracing::{debug, info, warn}; use crate::{ - common::{ContextForgeGatewayAppState, ContextForgeGatewayClaims}, + common::{ContextForgeClaims, ContextForgeGatewayAppState}, user_config_store::ConfigStoreError, }; @@ -14,11 +14,11 @@ pub async fn user_config_store_layer( mut request: http::Request, next: Next, ) -> Response { - let maybe_claims = request.extensions().get::(); + let maybe_claims = request.extensions().get::(); if let Some(claims) = maybe_claims { - let subject = claims.standard_claims.sub(); - debug!("Getting user config for {subject}"); - match state.config_store.get_config(&User::new(subject)).await { + let subject = claims.sub.clone(); + debug!("Getting user config for {subject:?}"); + match state.config_store.get_config(&User::new(&subject)).await { Ok(user_config) => { info!("Got config for user {subject} {user_config:?}"); request.extensions_mut().insert(user_config); diff --git a/crates/contextforge-gateway-rs-lib/src/lib.rs b/crates/contextforge-gateway-rs-lib/src/lib.rs index c8cde43e..27e4a96a 100644 --- a/crates/contextforge-gateway-rs-lib/src/lib.rs +++ b/crates/contextforge-gateway-rs-lib/src/lib.rs @@ -1,9 +1,8 @@ use std::{fs, sync::Arc}; use axum::middleware; -use axum_jwt_auth::LocalDecoder; use futures::FutureExt; -use jsonwebtoken::{Algorithm, DecodingKey, Validation}; +use jsonwebtoken::DecodingKey; use rmcp::transport::{ StreamableHttpServerConfig, streamable_http_server::{session::local::LocalSessionManager, tower::StreamableHttpService}, @@ -34,8 +33,7 @@ pub type Error = Box; pub type Result = std::result::Result; use crate::{ - common::ContextForgeGatewayAppState, - const_values::CONEXT_FORGE_GATEWAY_AUDIENCE, + common::{ContextForgeGatewayAppState, JwtTokenDecoders}, gateway::LocalUserSessionStore, layers::{ claims_id::claims_layer, session_id::SessionIdLayer, user_config_store::user_config_store_layer, @@ -90,29 +88,28 @@ impl Gateway { let cors_layer = CorsLayer::new().allow_origin(Any).allow_methods(Any).allow_headers(Any).expose_headers(Any); - let mut validation = Validation::new(Algorithm::RS256); - validation.set_audience(&[CONEXT_FORGE_GATEWAY_AUDIENCE]); - - let local_docoder = LocalDecoder::builder() - .keys(vec![ - DecodingKey::from_rsa_pem(&fs::read(&config.token_verification_public_key).map_err(|e| { - format!( - "Error when creating local decoder {e:?} {}", - config.token_verification_public_key.display() - ) - })?) - .map_err(|e| { - format!( - "Error when creating local decoder {e:?} {}", - config.token_verification_public_key.display() - ) - })?, - ]) - .validation(validation) - .build() - .map_err(|e| format!("Error when creating local decoder {e:?}"))?; + let rs_decoding_key = config.token_verification_public_key.as_ref().map(|path| { + let Ok(key) = + fs::read(path).map_err(|e| format!("Error when creating local decoder {e:?} {}", path.display())) + else { + return Err(format!("Error when creating local decoder. Can't read path {}", path.display())); + }; + + let Ok(key) = DecodingKey::from_rsa_pem(&key) else { + return Err(format!("Error when creating local decoder. Can't read the key {}", path.display())); + }; + Ok(key) + }); + let mcp_add_state: ContextForgeGatewayAppState = ContextForgeGatewayAppState { - jwt_token_decoder: Arc::new(local_docoder), + jwt_token_decoding_keys: JwtTokenDecoders { + rs: rs_decoding_key.transpose()?, + hmac_sha: config + .token_verification_secret + .as_ref() + .map(|token| DecodingKey::from_secret(token.as_bytes())), + }, + config_store: Arc::clone(&user_config_store), config: config.clone(), }; diff --git a/crates/contextforge-gateway-rs-lib/src/tests/gateway_end_to_end.rs b/crates/contextforge-gateway-rs-lib/src/tests/gateway_end_to_end.rs index 63db44db..fe7a281e 100644 --- a/crates/contextforge-gateway-rs-lib/src/tests/gateway_end_to_end.rs +++ b/crates/contextforge-gateway-rs-lib/src/tests/gateway_end_to_end.rs @@ -28,7 +28,7 @@ use tracing::{info, warn}; use crate::{ Config, Gateway, - common::DefaultClaims, + common::ContextForgeClaims, tests::{mock_counter, mocked_user_config_store::MockedUserConfigStore}, user_config_store::UserConfigStore, }; @@ -104,15 +104,17 @@ async fn create_axum_tls_servers(ports: &[u16], router: axum::Router) -> Vec String { +pub fn get_token_for_claims(claims: &ContextForgeClaims) -> String { let key = EncodingKey::from_rsa_pem(&fs::read("../../assets/jwt.key").expect("Expecting this to work")) .expect("Expecting this to work"); let mut header = Header::new(Algorithm::RS256); header.kid = Some("test".to_owned()); - let claims = DefaultClaims::new(user_id); + encode::(&header, claims, &key).expect("Expecting this to work") +} - encode::(&header, &claims, &key).expect("Expecting this to work") +pub fn get_token(user_id: &str) -> String { + get_token_for_claims(&ContextForgeClaims::new(user_id)) } struct TestSettings { @@ -161,7 +163,6 @@ async fn create_gateway_with_four_counters(user: &str, config: Config) -> crate: let gateway = Gateway::builder() .with_config(config.clone()) - //.with_user_config_store(Arc::new(mocked_user_config_store)) .with_session_manager(Arc::new(LocalSessionManager::default())) .with_user_config_store_type(crate::UserConfigStoreType::Test(Arc::new(mocked_user_config_store))) .build(); @@ -262,7 +263,7 @@ async fn plaintext_list_tools_end_to_end_test() -> crate::Result<()> { let config = Config { address: Some(format!("127.0.0.1:{gateway_port}").parse().expect("This should work")), - token_verification_public_key: "../../assets/jwt.key.pub".into(), + token_verification_public_key: Some("../../assets/jwt.key.pub".into()), upstream_connection_mode: Some(crate::common::UpstreamConnectionMode::PlainTextOrTls), ..Default::default() }; @@ -278,7 +279,7 @@ async fn plaintext_list_tools_end_to_end_test() -> crate::Result<()> { let test_future: BoxFuture<'_, crate::Result<()>> = async { tokio::time::sleep(Duration::from_millis(100)).await; let mut default_headers = HeaderMap::new(); - let token = get_token(user.to_owned()); + let token = get_token(user); default_headers.insert( http::header::AUTHORIZATION, HeaderValue::from_str(format!("Bearer {token}").as_str()).expect("This should work"), @@ -340,7 +341,7 @@ async fn tls_list_tools_end_to_end_test() -> crate::Result<()> { format!("127.0.0.1:{gateway_port}").parse().expect("This should work"); let config = Config { - token_verification_public_key: "../../assets/jwt.key.pub".into(), + token_verification_public_key: Some("../../assets/jwt.key.pub".into()), upstream_connection_mode: Some(crate::common::UpstreamConnectionMode::PlainTextOrTls), tls_address: Some(server_socket_addr), server_private_key: Some("../../assets/contextforgeCA/contextforge-server.key.pem".into()), @@ -364,7 +365,7 @@ async fn tls_list_tools_end_to_end_test() -> crate::Result<()> { tokio::time::sleep(Duration::from_millis(100)).await; let mut default_headers = HeaderMap::new(); - let token = get_token(user.to_owned()); + let token = get_token(user); default_headers.insert( http::header::AUTHORIZATION, HeaderValue::from_str(format!("Bearer {token}").as_str()).expect("This should work"), diff --git a/crates/contextforge-gateway-rs-lib/src/tests/mod.rs b/crates/contextforge-gateway-rs-lib/src/tests/mod.rs index bde29179..d3efceb8 100644 --- a/crates/contextforge-gateway-rs-lib/src/tests/mod.rs +++ b/crates/contextforge-gateway-rs-lib/src/tests/mod.rs @@ -1,3 +1,3 @@ -mod gateway_end_to_end; +pub mod gateway_end_to_end; mod mock_counter; mod mocked_user_config_store; diff --git a/crates/contextforge-gateway-rs-lib/src/tools.rs b/crates/contextforge-gateway-rs-lib/src/tools.rs index 3de8c0f7..412b4c31 100644 --- a/crates/contextforge-gateway-rs-lib/src/tools.rs +++ b/crates/contextforge-gateway-rs-lib/src/tools.rs @@ -7,12 +7,11 @@ use axum::{ response::{IntoResponse, Response}, routing::{Router, get, post}, }; -use contextforge_gateway_rs_apis::{User, user_store::UserConfig}; +use contextforge_gateway_rs_apis::{User as CFUser, user_store::UserConfig}; use http::{StatusCode, header}; -use jsonwebtoken::{Algorithm, EncodingKey, Header, encode}; //use tracing::debug; -use crate::common::{ContextForgeGatewayAppState, DefaultClaims}; +use crate::common::{ContextForgeClaims, ContextForgeGatewayAppState}; pub fn add_tools(router: Router) -> Router { router @@ -30,16 +29,15 @@ pub async fn health() -> Response { } pub async fn get_token(State(state): State, Path(user_id): Path) -> Response { - let key = EncodingKey::from_rsa_pem( + let key = jsonwebtoken::EncodingKey::from_rsa_pem( &fs::read(&state.config.token_verification_private_key).expect("Expecting this to work"), ) .expect("Expecting this to work"); - let mut header = Header::new(Algorithm::RS256); - header.kid = Some("test".to_owned()); - - let claims = DefaultClaims::new(user_id); - let token = encode::(&header, &claims, &key).expect("Expecting this to work"); + let claims = ContextForgeClaims::new(&user_id); + let mut header = jsonwebtoken::Header::new(jsonwebtoken::Algorithm::RS256); + header.kid = Some("test".to_owned()); + let token = jsonwebtoken::encode::(&header, &claims, &key).expect("Expecting this to work"); token.into_response() } @@ -50,7 +48,7 @@ pub async fn configure_user( State(state): State, Json(user_config): Json, ) -> Response { - if state.config_store.set_config(&User::new(&user_id), &user_config).await.is_ok() { + if state.config_store.set_config(&CFUser::new(&user_id), &user_config).await.is_ok() { Response::builder() .status(StatusCode::ACCEPTED) .header(header::CONTENT_TYPE, "text/plain") diff --git a/crates/contextforge-gateway-rs-lib/src/user_config_store/mod.rs b/crates/contextforge-gateway-rs-lib/src/user_config_store/mod.rs index 1cc33776..b7d5bc4d 100644 --- a/crates/contextforge-gateway-rs-lib/src/user_config_store/mod.rs +++ b/crates/contextforge-gateway-rs-lib/src/user_config_store/mod.rs @@ -1,7 +1,6 @@ mod redis_config_store; use async_trait::async_trait; use contextforge_gateway_rs_apis::{User, user_store::UserConfig}; - pub use redis_config_store::RedisUserConfigStore; use serde::{Deserialize, Serialize}; diff --git a/crates/contextforge-gateway-rs-lib/src/user_config_store/redis_config_store.rs b/crates/contextforge-gateway-rs-lib/src/user_config_store/redis_config_store.rs index fb8cf273..8db36f07 100644 --- a/crates/contextforge-gateway-rs-lib/src/user_config_store/redis_config_store.rs +++ b/crates/contextforge-gateway-rs-lib/src/user_config_store/redis_config_store.rs @@ -8,13 +8,12 @@ use redis::{ aio::{ConnectionManager, ConnectionManagerConfig}, cmd, }; - use tokio::sync::Mutex; use super::{ConfigStoreError, UserConfigStore}; use crate::{ common::RedisClient, - const_values::{LRU_CACHE_ENTRIES, LRU_CACHE_EXPIRY_DURATION}, + const_values::{LRU_CACHE_ENTRIES, LRU_CACHE_EXPIRY_DURATION, REDIS_RETRIES}, }; #[derive(Clone)] @@ -22,11 +21,14 @@ pub struct RedisUserConfigStore { connection: ConnectionManager, cache: Arc>>, } + impl RedisUserConfigStore { pub async fn new(redis_client: &RedisClient) -> crate::Result { Ok(Self { connection: redis_client - .get_connection_manager_with_config(ConnectionManagerConfig::default()) + .get_connection_manager_with_config( + ConnectionManagerConfig::default().set_number_of_retries(REDIS_RETRIES), + ) .await .map_err(|_| ConfigStoreError::InvalidConnection)?, cache: Arc::new(Mutex::new(LruCache::with_expiry_duration_and_capacity(