From d2aab2bb2c5d1a5e5544ed746ef73ae60a8bf7f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 28 Oct 2026 10:22:38 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20OIDC=20provider=20part=202:?= =?UTF-8?q?=20client=20credentials,=20revoke,=20introspect,=20RP-initiated?= =?UTF-8?q?=20logout,=20back-channel=20logout=20outbox=20and=20worker;=20s?= =?UTF-8?q?ecurity=20headers=20no=20longer=20duplicate=20route=20headers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.lock | 558 +++++++++++++++++++++++- Cargo.toml | 1 + crates/im-core/src/jwt.rs | 15 + crates/im-core/src/model.rs | 14 + crates/im-core/src/store/backchannel.rs | 453 +++++++++++++++++++ crates/im-core/src/store/clients.rs | 14 + crates/im-core/src/store/mod.rs | 1 + crates/im-core/src/store/sessions.rs | 147 +++++-- crates/im-core/src/store/users.rs | 43 ++ crates/im-web/Cargo.toml | 3 +- crates/im-web/src/auth.rs | 16 +- crates/im-web/src/backchannel.rs | 375 ++++++++++++++++ crates/im-web/src/boot.rs | 35 ++ crates/im-web/src/cli.rs | 4 +- crates/im-web/src/i18n/oidc.rs | 28 ++ crates/im-web/src/main.rs | 1 + crates/im-web/src/oidc/authorize.rs | 16 + crates/im-web/src/oidc/discovery.rs | 3 +- crates/im-web/src/oidc/introspect.rs | 120 +++++ crates/im-web/src/oidc/logout.rs | 278 ++++++++++++ crates/im-web/src/oidc/mod.rs | 3 + crates/im-web/src/oidc/revoke.rs | 40 ++ crates/im-web/src/oidc/tests.rs | 155 ++++++- crates/im-web/src/oidc/token.rs | 96 +++- crates/im-web/src/oidc/userinfo.rs | 20 +- crates/im-web/src/pages/login.rs | 23 +- crates/im-web/src/pages/security.rs | 7 +- crates/im-web/src/pages/sessions.rs | 7 +- crates/im-web/src/security.rs | 49 ++- 29 files changed, 2431 insertions(+), 94 deletions(-) create mode 100644 crates/im-core/src/store/backchannel.rs create mode 100644 crates/im-web/src/backchannel.rs create mode 100644 crates/im-web/src/oidc/introspect.rs create mode 100644 crates/im-web/src/oidc/logout.rs create mode 100644 crates/im-web/src/oidc/revoke.rs diff --git a/Cargo.lock b/Cargo.lock index aede45d..947bcf2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -253,6 +253,29 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "aws-lc-rs" +version = "1.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faac5829c2b74c28f830747e7818ccfb684261b5f48a1118b1e2a13d36dfab13" +dependencies = [ + "aws-lc-sys", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1622d8446a2d4b2ce0c7eefc73dd43a99779028d5ee5c2dd8073a658ba8a2bc" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + [[package]] name = "base64" version = "0.22.1" @@ -584,6 +607,15 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + [[package]] name = "cmov" version = "0.5.4" @@ -608,6 +640,16 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + [[package]] name = "concurrent-queue" version = "2.5.0" @@ -641,6 +683,16 @@ dependencies = [ "version_check", ] +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation-sys" version = "0.8.7" @@ -923,6 +975,12 @@ version = "2.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc" +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + [[package]] name = "ed25519" version = "3.0.0" @@ -1131,6 +1189,12 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + [[package]] name = "funty" version = "2.0.0" @@ -1511,6 +1575,22 @@ dependencies = [ "pin-project-lite", "smallvec", "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", ] [[package]] @@ -1519,12 +1599,22 @@ version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" dependencies = [ + "base64 0.23.1", "bytes", + "futures-channel", + "futures-util", "http", "http-body", + "httparse", "hyper", + "ipnet", + "libc", + "percent-encoding", "pin-project-lite", + "socket2", "tokio", + "tower-service", + "tracing", ] [[package]] @@ -1773,6 +1863,7 @@ dependencies = [ "http", "im-core", "qrcode", + "reqwest", "serde", "serde_json", "sha2 0.11.1", @@ -1948,6 +2039,55 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + [[package]] name = "jobserver" version = "0.1.35" @@ -2119,6 +2259,12 @@ dependencies = [ "hashbrown 0.16.1", ] +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + [[package]] name = "lz4_flex" version = "0.13.1" @@ -2372,6 +2518,12 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + [[package]] name = "ordered-float" version = "5.5.1" @@ -2684,6 +2836,63 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash 2.1.3", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "aws-lc-rs", + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.3", + "rand_pcg 0.10.2", + "ring", + "rustc-hash 2.1.3", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + [[package]] name = "quote" version = "1.0.47" @@ -2802,6 +3011,15 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core 0.10.1", +] + [[package]] name = "rapidhash" version = "4.5.1" @@ -2889,6 +3107,57 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "serde", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "roaring" version = "0.11.5" @@ -2966,6 +3235,81 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "aws-lc-rs", + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "aws-lc-rs", + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -2978,6 +3322,24 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "scoped-tls" version = "1.0.1" @@ -2990,6 +3352,29 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.2", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "semver" version = "1.0.28" @@ -3156,7 +3541,7 @@ dependencies = [ "owo-colors", "rand 0.8.8", "rand_core 0.6.4", - "rand_pcg", + "rand_pcg 0.3.1", "scoped-tls", "smallvec", "tracing", @@ -3187,6 +3572,16 @@ version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + [[package]] name = "simdutf8" version = "0.1.5" @@ -3319,6 +3714,15 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + [[package]] name = "synstructure" version = "0.14.0" @@ -3567,6 +3971,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + [[package]] name = "tokio" version = "1.54.1" @@ -3594,6 +4004,16 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + [[package]] name = "tokio-tungstenite" version = "0.29.0" @@ -4001,6 +4421,51 @@ dependencies = [ "topcoat-view-grammar", ] +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags 2.13.2", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + [[package]] name = "tracing" version = "0.1.44" @@ -4075,6 +4540,12 @@ dependencies = [ "tracing-log", ] +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + [[package]] name = "tungstenite" version = "0.29.0" @@ -4384,6 +4855,24 @@ dependencies = [ "ctutils", ] +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + [[package]] name = "utf16_iter" version = "1.0.5" @@ -4433,6 +4922,25 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -4461,6 +4969,17 @@ dependencies = [ "wasm-bindgen-shared", ] +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + [[package]] name = "wasm-bindgen-macro" version = "0.2.129" @@ -4493,6 +5012,16 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "web-time" version = "1.1.0" @@ -4503,6 +5032,15 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webpki-root-certs" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "weezl" version = "0.1.12" @@ -4537,6 +5075,15 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" @@ -4602,6 +5149,15 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + [[package]] name = "windows-sys" version = "0.59.0" diff --git a/Cargo.toml b/Cargo.toml index 39379a1..ce6691f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,6 +23,7 @@ image = { version = "0.25.10", default-features = false, features = ["png", "jpe jiff = { version = "0.2.38", default-features = false, features = ["std", "tzdb-bundle-always"] } http = "1.5.0" ipnet = "2.12.2" +reqwest = { version = "0.13.5", default-features = false, features = ["form", "rustls"] } qrcode = { version = "0.14.1", default-features = false, features = ["svg"] } rand = "0.10.3" serde = { version = "1.0.229", features = ["derive"] } diff --git a/crates/im-core/src/jwt.rs b/crates/im-core/src/jwt.rs index 6fc4465..6aabb4b 100644 --- a/crates/im-core/src/jwt.rs +++ b/crates/im-core/src/jwt.rs @@ -136,6 +136,21 @@ pub fn check_claims( Ok(()) } +/// Checks only the issuer: `iss` equals `issuer` exactly. For a caller that checks its own expiry +/// (an ID token used as a logout hint may be expired) and its own audience. +pub fn check_issuer(claims: &Map, issuer: &str) -> Result<(), JwtError> { + if claims.get("iss").and_then(Value::as_str) == Some(issuer) { + Ok(()) + } else { + Err(JwtError::Claim("iss")) + } +} + +/// The audience of a token when it is a single string. `None` for an array or a missing claim. +pub fn single_audience(claims: &Map) -> Option<&str> { + claims.get("aud").and_then(Value::as_str) +} + fn audience_is(aud: Option<&Value>, expected: &str) -> bool { match aud { Some(Value::String(one)) => one == expected, diff --git a/crates/im-core/src/model.rs b/crates/im-core/src/model.rs index c36d146..92d0da9 100644 --- a/crates/im-core/src/model.rs +++ b/crates/im-core/src/model.rs @@ -64,6 +64,20 @@ pub mod amr { pub const PASSWORD_TOTP: &str = "pwd otp"; /// Password and a recovery code. pub const PASSWORD_RECOVERY: &str = "pwd rc"; + + /// The RFC 8176 `amr` values of a stored method, for the ID token and the access token. + /// + /// The table keeps the short labels above, because its CHECK constraint names them. The tokens + /// carry the standard values: TOTP is `pwd`, `otp` and `mfa`; a recovery code is `pwd` and `mfa` + /// (a recovery code is a second factor that is not an OTP, so it is not `otp`). Anything else + /// proved only the password. + pub fn rfc8176(stored: &str) -> &'static [&'static str] { + match stored { + PASSWORD_TOTP => &["pwd", "otp", "mfa"], + PASSWORD_RECOVERY => &["pwd", "mfa"], + _ => &["pwd"], + } + } } /// A browser session. The cookie holds the token; the row holds only its hash. diff --git a/crates/im-core/src/store/backchannel.rs b/crates/im-core/src/store/backchannel.rs new file mode 100644 index 0000000..f53eaa7 --- /dev/null +++ b/crates/im-core/src/store/backchannel.rs @@ -0,0 +1,453 @@ +//! The back-channel logout outbox (contracts.md 2.5): the rows that say which client must be told that +//! an `im` session ended, and the reads and writes the delivery worker makes on them. +//! +//! A row is written in the same transaction as the session end it describes (`sessions.rs`, +//! `users.rs`), so a logout never happens without its rows. Delivery is not here: the worker in +//! `im-web/src/backchannel.rs` signs and posts them. A failed delivery never blocks the logout; it +//! only leaves a row to be retried, and the row is abandoned after its retry window. + +use turso::Connection; + +use crate::error::Result; +use crate::store::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id}; + +/// Why a session, or every session of a person, ended. The stored text is the `reason` column. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum EndReason { + /// The person signed out (the sign-out button, or RP-initiated logout). + Logout, + /// The person ended a session on the sessions page. + Revoked, + /// The password changed, which ends every other session. + PasswordChanged, + /// The per-person session cap was reached and the oldest session made room. + SessionLimit, + /// A new sign-in in the same browser replaced its previous session. + Replaced, + /// The session reached its expiry and the sweeper removed it. + Expired, + /// The account was disabled. Sent as a `sub`-only logout, which covers every session of the person. + Disabled, +} + +impl EndReason { + /// The stored text of the reason. + pub fn as_str(self) -> &'static str { + match self { + EndReason::Logout => "logout", + EndReason::Revoked => "revoked", + EndReason::PasswordChanged => "password_changed", + EndReason::SessionLimit => "session_limit", + EndReason::Replaced => "replaced", + EndReason::Expired => "expired", + EndReason::Disabled => "disabled", + } + } +} + +/// One row of the outbox, as the worker reads it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Delivery { + /// ULID of the row. + pub id: String, + /// The client to tell. Its `backchannel_logout_uri` is read at delivery time. + pub client_id: String, + /// The `im` session that ended, or `None` for a `sub`-only logout. + pub sid: Option, + /// The person. + pub sub: String, + /// Deliveries already tried. + pub attempts: i64, + /// When the row was queued. The retry window counts from here. + pub created_at: String, +} + +/// Every column of an outbox row, for inspection and tests. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OutboxRow { + /// ULID of the row. + pub id: String, + /// The client the logout is for. + pub client_id: String, + /// The session that ended, when the logout names one. + pub sid: Option, + /// The person. + pub sub: String, + /// The stored [`EndReason::as_str`]. + pub reason: String, + /// `pending`, `sent`, `failed` or `abandoned`. + pub state: String, + /// Deliveries tried so far. + pub attempts: i64, + /// When the row is next due. + pub next_attempt_at: String, + /// The last failure, without secrets. + pub last_error: Option, +} + +/// The columns of an outbox row, in the order [`map_row`] reads them. +const ROW_COLS: &str = + "id, client_id, sid, sub, reason, state, attempts, next_attempt_at, last_error"; + +fn map_row(row: &turso::Row) -> Result { + Ok(OutboxRow { + id: col_text(row, 0)?, + client_id: col_text(row, 1)?, + sid: col_opt_text(row, 2)?, + sub: col_text(row, 3)?, + reason: col_text(row, 4)?, + state: col_text(row, 5)?, + attempts: col_int(row, 6)?, + next_attempt_at: col_text(row, 7)?, + last_error: col_opt_text(row, 8)?, + }) +} + +/// Inserts one pending row. Runs inside the caller's transaction. +async fn insert_row( + conn: &Connection, + client_id: &str, + sid: Option<&str>, + sub: &str, + reason: EndReason, + now: &str, +) -> Result<()> { + conn.execute( + "INSERT INTO backchannel_outbox (id, client_id, sid, sub, reason, state, attempts, \ + next_attempt_at, created_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, 'pending', 0, ?6, ?6)", + ( + new_id(), + client_id.to_string(), + sid.map(str::to_owned), + sub.to_string(), + reason.as_str().to_string(), + now.to_string(), + ), + ) + .await + .map_err(db_err)?; + Ok(()) +} + +/// Queues a logout for every client the session signed into that has a back-channel URI. Runs inside +/// the caller's transaction, before the session row is deleted (its client links cascade away). +pub(crate) async fn queue_session( + conn: &Connection, + session_id: &str, + user_id: &str, + reason: EndReason, + now: &str, +) -> Result<()> { + let clients = fetch_all( + conn, + "SELECT cs.client_id FROM client_sessions cs \ + JOIN clients c ON c.id = cs.client_id \ + WHERE cs.session_id = ?1 AND c.backchannel_logout_uri IS NOT NULL", + (session_id.to_string(),), + |row| col_text(row, 0), + ) + .await?; + for client_id in clients { + insert_row(conn, &client_id, Some(session_id), user_id, reason, now).await?; + } + Ok(()) +} + +/// Queues a `sub`-only logout (contracts 2.5, "disable") for every client the person ever used: every +/// client of a live session, and every client that holds one of the person's refresh tokens. Runs +/// inside the caller's transaction, before the person's sessions are deleted. +pub(crate) async fn queue_user( + conn: &Connection, + user_id: &str, + reason: EndReason, + now: &str, +) -> Result<()> { + let clients = fetch_all( + conn, + "SELECT id FROM clients WHERE backchannel_logout_uri IS NOT NULL AND id IN ( \ + SELECT cs.client_id FROM client_sessions cs \ + JOIN sessions s ON s.id = cs.session_id WHERE s.user_id = ?1 \ + UNION SELECT client_id FROM refresh_tokens WHERE user_id = ?1)", + (user_id.to_string(),), + |row| col_text(row, 0), + ) + .await?; + for client_id in clients { + insert_row(conn, &client_id, None, user_id, reason, now).await?; + } + Ok(()) +} + +/// The outcome the worker reports for one delivery. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Attempt { + /// The client answered 200 or 204. + Delivered, + /// The attempt failed; the row is due again at `next`. + Retry { + /// Total deliveries tried, including this one. + attempts: i64, + /// When to try again (UTC stamp). + next: String, + /// Why it failed, without secrets. + error: String, + }, + /// The row is given up on; it is logged and never tried again. + Abandon { + /// Total deliveries tried, including this one. + attempts: i64, + /// Why it was given up. + error: String, + }, +} + +impl Store { + /// Pending rows that are due at `now`, oldest first, at most `limit`. + pub async fn due_deliveries(&self, now: &str, limit: i64) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + "SELECT id, client_id, sid, sub, attempts, created_at FROM backchannel_outbox \ + WHERE state = 'pending' AND next_attempt_at <= ?1 \ + ORDER BY next_attempt_at ASC, id ASC LIMIT ?2", + (now.to_string(), limit), + |row| { + Ok(Delivery { + id: col_text(row, 0)?, + client_id: col_text(row, 1)?, + sid: col_opt_text(row, 2)?, + sub: col_text(row, 3)?, + attempts: col_int(row, 4)?, + created_at: col_text(row, 5)?, + }) + }, + ) + .await + } + + /// Records the outcome of one delivery attempt on a row. + pub async fn record_attempt(&self, id: &str, attempt: &Attempt, now: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + let changed = match attempt { + Attempt::Delivered => { + conn.execute( + "UPDATE backchannel_outbox SET state = 'sent', done_at = ?2, last_error = NULL \ + WHERE id = ?1 AND state = 'pending'", + (id.to_string(), now.to_string()), + ) + .await + } + Attempt::Retry { + attempts, + next, + error, + } => { + conn.execute( + "UPDATE backchannel_outbox SET attempts = ?2, next_attempt_at = ?3, last_error = ?4 \ + WHERE id = ?1 AND state = 'pending'", + (id.to_string(), *attempts, next.clone(), error.clone()), + ) + .await + } + Attempt::Abandon { attempts, error } => { + conn.execute( + "UPDATE backchannel_outbox SET state = 'abandoned', attempts = ?2, last_error = ?3 \ + WHERE id = ?1 AND state = 'pending'", + (id.to_string(), *attempts, error.clone()), + ) + .await + } + }; + changed.map_err(db_err)?; + Ok(()) + } + + /// Every outbox row, oldest first. For inspection and tests. + pub async fn backchannel_rows(&self) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + &format!("SELECT {ROW_COLS} FROM backchannel_outbox ORDER BY created_at ASC, id ASC"), + (), + map_row, + ) + .await + } + + /// One outbox row by id, if it exists. + pub async fn backchannel_row(&self, id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + &format!("SELECT {ROW_COLS} FROM backchannel_outbox WHERE id = ?1"), + (id.to_string(),), + map_row, + ) + .await + } +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use super::*; + use crate::model::amr; + use crate::store::clients::NewClient; + use crate::store::oidc::{NewAuthCode, NewRefreshToken}; + use crate::store::sessions::{NewSession, SESSION_IDLE}; + use crate::time::stamp_after; + use crate::token::hash_token; + + /// A store over a temp file, one person, two clients with back-channel URIs and one live session + /// that both clients signed into. + async fn fixture() -> (tempfile::TempDir, Store, String, String, Vec) { + let dir = tempfile::tempdir().expect("temp dir"); + let store = Store::open(&dir.path().join("im.db")).await.expect("store"); + let user = store + .create_user("ada@example.com", "Ada", "hash", false) + .await + .expect("user"); + let mut clients = Vec::new(); + for key in ["in", "iz"] { + let uri = format!("https://{key}.example.com/auth/backchannel-logout"); + let client = store + .create_client(&NewClient { + name: key, + secret_hash: "secret", + redirect_uris: &[], + post_logout_redirect_uris: &[], + backchannel_logout_uri: Some(&uri), + allowed_scopes: "openid", + service_key: Some(key), + }) + .await + .expect("client"); + clients.push(client.id); + } + let session = store + .create_session( + &NewSession { + user_id: &user.id, + token_hash: "session-token", + csrf_token: "csrf", + amr: amr::PASSWORD, + ip: None, + user_agent: None, + idle: SESSION_IDLE, + max_age: Duration::from_secs(3600), + }, + 10, + ) + .await + .expect("session") + .session; + for client in &clients { + store + .touch_client_session(&session.id, client) + .await + .expect("client session"); + } + (dir, store, user.id, session.id, clients) + } + + #[tokio::test] + async fn a_session_end_queues_one_row_per_client_and_revokes_its_refresh_tokens() { + let (_dir, store, user_id, session_id, clients) = fixture().await; + let expires = stamp_after(Duration::from_secs(60)); + store + .insert_auth_code(&NewAuthCode { + code_hash: "code", + client_id: &clients[0], + user_id: &user_id, + session_id: &session_id, + redirect_uri: "https://in.example.com/auth/callback", + scope: "openid", + nonce: None, + code_challenge: &"c".repeat(43), + expires_at: &expires, + }) + .await + .expect("code"); + let refresh_expires = stamp_after(Duration::from_secs(3600)); + assert!( + store + .redeem_auth_code( + "code", + &NewRefreshToken { + id: "refresh-1", + token_hash: &hash_token("refresh"), + family_id: "refresh-1", + client_id: &clients[0], + user_id: &user_id, + session_id: &session_id, + code_hash: Some("code"), + scope: "openid", + expires_at: &refresh_expires, + }, + ) + .await + .expect("redeem") + ); + + assert!( + store + .end_session(&user_id, &session_id, EndReason::Revoked) + .await + .expect("end") + ); + + let rows = store.backchannel_rows().await.expect("rows"); + assert_eq!(rows.len(), 2, "{rows:?}"); + let mut row_clients: Vec<&str> = rows.iter().map(|r| r.client_id.as_str()).collect(); + row_clients.sort_unstable(); + let mut expected: Vec<&str> = clients.iter().map(String::as_str).collect(); + expected.sort_unstable(); + assert_eq!(row_clients, expected); + for row in &rows { + assert_eq!(row.sid.as_deref(), Some(session_id.as_str())); + assert_eq!(row.sub, user_id); + assert_eq!(row.reason, "revoked"); + assert_eq!(row.state, "pending"); + } + assert!( + store + .refresh_token(&hash_token("refresh")) + .await + .expect("lookup") + .is_none(), + "the refresh token survived its session" + ); + } + + #[tokio::test] + async fn disabling_an_account_queues_one_sub_only_row_per_client_and_ends_its_sessions() { + let (_dir, store, user_id, session_id, _clients) = fixture().await; + assert!(store.disable_user(&user_id).await.expect("disable")); + assert!(!store.disable_user(&user_id).await.expect("again")); + + let rows = store.backchannel_rows().await.expect("rows"); + assert_eq!(rows.len(), 2, "{rows:?}"); + for row in &rows { + assert_eq!(row.sid, None, "a disable is sub-only"); + assert_eq!(row.sub, user_id); + assert_eq!(row.reason, "disabled"); + } + assert!( + store + .backchannel_row(&rows[0].id) + .await + .expect("row") + .is_some() + ); + assert!( + store + .session_by_token_hash("session-token") + .await + .expect("lookup") + .is_none(), + "session {session_id} survived the disable" + ); + } +} diff --git a/crates/im-core/src/store/clients.rs b/crates/im-core/src/store/clients.rs index 39e4230..33d487c 100644 --- a/crates/im-core/src/store/clients.rs +++ b/crates/im-core/src/store/clients.rs @@ -120,6 +120,20 @@ impl Store { .await } + /// True when a registered client carries this family key, so the key names a known service. Machine + /// tokens are issued only for known audiences (contracts.md 2.6). + pub async fn family_key_known(&self, key: &str) -> Result { + let conn = self.read_conn().await; + let found = fetch_opt( + &conn, + "SELECT 1 FROM clients WHERE service_key = ?1", + (key.to_string(),), + |_row| Ok(()), + ) + .await?; + Ok(found.is_some()) + } + /// Disables a client. Returns false when there was no such client or it was already disabled. pub async fn disable_client(&self, id: &str) -> Result { let conn = self.inner.conn.lock().await; diff --git a/crates/im-core/src/store/mod.rs b/crates/im-core/src/store/mod.rs index ab76590..57497f8 100644 --- a/crates/im-core/src/store/mod.rs +++ b/crates/im-core/src/store/mod.rs @@ -7,6 +7,7 @@ //! in effect are logged at boot. pub mod audit; +pub mod backchannel; pub mod clients; pub mod directory; pub mod keys; diff --git a/crates/im-core/src/store/sessions.rs b/crates/im-core/src/store/sessions.rs index fc057fa..a8284a5 100644 --- a/crates/im-core/src/store/sessions.rs +++ b/crates/im-core/src/store/sessions.rs @@ -15,6 +15,7 @@ use turso::Connection; use crate::error::Result; use crate::model::Session; +use crate::store::backchannel::{self, EndReason}; use crate::store::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id}; use crate::time::{now_stamp, stamp_after, stamp_before}; @@ -80,16 +81,15 @@ pub struct CreatedSession { pub ended: Vec, } -/// Deletes the sessions of `user_id` matching `keep` (none keeps nothing), and returns their ids. -/// Runs inside the caller's transaction. -async fn end_sessions( +/// The ids of the live sessions of `user_id` except `keep` (none keeps nothing), oldest first. +/// Only sessions that are still live count; expired rows are removed by the sweeper. +async fn live_session_ids( conn: &Connection, user_id: &str, keep: Option<&str>, now: &str, ) -> Result> { - // Only sessions that were still live count as ended. Expired rows are removed by the sweeper. - let ids = fetch_all( + fetch_all( conn, "SELECT id FROM sessions WHERE user_id = ?1 AND expires_at > ?2 AND id IS NOT ?3 \ ORDER BY created_at ASC, id ASC", @@ -100,13 +100,36 @@ async fn end_sessions( ), |row| col_text(row, 0), ) - .await?; - for id in &ids { - conn.execute("DELETE FROM sessions WHERE id = ?1", (id.clone(),)) - .await - .map_err(db_err)?; + .await +} + +/// Ends the given sessions of `user_id` inside the caller's transaction. For each one: the back-channel +/// logout rows of its clients are queued, its refresh tokens are revoked, and the row is deleted (its +/// client links go with it). Every session end in the store goes through here, so no end skips its +/// back-channel logout (contracts.md 2.5). +pub(crate) async fn end_rows( + conn: &Connection, + user_id: &str, + ids: &[String], + reason: EndReason, + now: &str, +) -> Result<()> { + for id in ids { + backchannel::queue_session(conn, id, user_id, reason, now).await?; + conn.execute( + "UPDATE refresh_tokens SET revoked_at = ?2 WHERE session_id = ?1 AND revoked_at IS NULL", + (id.clone(), now.to_string()), + ) + .await + .map_err(db_err)?; + conn.execute( + "DELETE FROM sessions WHERE id = ?1 AND user_id = ?2", + (id.clone(), user_id.to_string()), + ) + .await + .map_err(db_err)?; } - Ok(ids) + Ok(()) } impl Store { @@ -159,13 +182,8 @@ impl Store { .await?; // Room for the new one: at most cap - 1 live sessions may remain. let overflow = live.len().saturating_sub(cap - 1); - let mut ended = Vec::with_capacity(overflow); - for id in live.into_iter().take(overflow) { - tx.execute("DELETE FROM sessions WHERE id = ?1", (id.clone(),)) - .await - .map_err(db_err)?; - ended.push(id); - } + let ended: Vec = live.into_iter().take(overflow).collect(); + end_rows(&tx, new.user_id, &ended, EndReason::SessionLimit, &now).await?; tx.execute( "INSERT INTO sessions (id, user_id, token_hash, csrf_token, created_at, expires_at, \ last_seen_at, ip, user_agent, auth_time, amr, hard_expires_at) \ @@ -286,51 +304,94 @@ impl Store { .await } - /// Ends one session, only if it belongs to `user_id`. Returns false when there was nothing to - /// end, which is also the answer for another user's session: the caller cannot tell them apart. - pub async fn end_session(&self, user_id: &str, session_id: &str) -> Result { + /// Ends one session, only if it belongs to `user_id`, with its back-channel logout. Returns false + /// when there was nothing to end, which is also the answer for another user's session: the caller + /// cannot tell them apart. + pub async fn end_session( + &self, + user_id: &str, + session_id: &str, + reason: EndReason, + ) -> Result { let conn = self.inner.conn.lock().await; - let changed = conn - .execute( - "DELETE FROM sessions WHERE id = ?1 AND user_id = ?2", + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let now = now_stamp(); + let outcome: Result = async { + let owned = fetch_opt( + &tx, + "SELECT id FROM sessions WHERE id = ?1 AND user_id = ?2", (session_id.to_string(), user_id.to_string()), + |row| col_text(row, 0), ) - .await - .map_err(db_err)?; - Ok(changed == 1) + .await?; + if owned.is_none() { + return Ok(false); + } + end_rows(&tx, user_id, &[session_id.to_owned()], reason, &now).await?; + Ok(true) + } + .await; + finish(tx, outcome).await } - /// Ends every live session of `user_id` except `keep_session_id`. Returns the ids ended. + /// Ends every live session of `user_id` except `keep_session_id`, with their back-channel logouts. + /// Returns the ids ended. pub async fn end_other_sessions( &self, user_id: &str, keep_session_id: &str, + reason: EndReason, ) -> Result> { - self.end_matching(user_id, Some(keep_session_id)).await - } - - /// Ends every live session of `user_id`. Returns the ids ended. - pub async fn end_all_sessions(&self, user_id: &str) -> Result> { - self.end_matching(user_id, None).await + self.end_matching(user_id, Some(keep_session_id), reason) + .await } - async fn end_matching(&self, user_id: &str, keep: Option<&str>) -> Result> { + async fn end_matching( + &self, + user_id: &str, + keep: Option<&str>, + reason: EndReason, + ) -> Result> { let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; let now = now_stamp(); - let outcome: Result> = end_sessions(&tx, user_id, keep, &now).await; + let outcome: Result> = async { + let ids = live_session_ids(&tx, user_id, keep, &now).await?; + end_rows(&tx, user_id, &ids, reason, &now).await?; + Ok(ids) + } + .await; finish(tx, outcome).await } - /// Deletes the sessions that have expired. Returns how many were removed. Run by the sweeper. + /// Deletes the sessions that have expired, queuing their back-channel logouts first. Returns how + /// many were removed. Run by the sweeper. pub async fn sweep_expired_sessions(&self) -> Result { let conn = self.inner.conn.lock().await; - conn.execute( - "DELETE FROM sessions WHERE expires_at <= ?1", - (now_stamp(),), - ) - .await - .map_err(db_err) + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let now = now_stamp(); + let outcome: Result = async { + let expired = fetch_all( + &tx, + "SELECT id, user_id FROM sessions WHERE expires_at <= ?1", + (now.clone(),), + |row| Ok((col_text(row, 0)?, col_text(row, 1)?)), + ) + .await?; + for (id, user_id) in &expired { + end_rows( + &tx, + user_id, + std::slice::from_ref(id), + EndReason::Expired, + &now, + ) + .await?; + } + Ok(expired.len() as u64) + } + .await; + finish(tx, outcome).await } } diff --git a/crates/im-core/src/store/users.rs b/crates/im-core/src/store/users.rs index 2ece347..59089de 100644 --- a/crates/im-core/src/store/users.rs +++ b/crates/im-core/src/store/users.rs @@ -16,6 +16,7 @@ use turso::{Connection, Row}; use crate::error::{Error, Result}; use crate::model::User; +use crate::store::backchannel::{self, EndReason}; use crate::store::directory::{ChangeKind, record_change}; use crate::store::{ Store, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_opt, finish, new_id, @@ -295,6 +296,48 @@ impl Store { Ok(()) } + /// Disables an account. In one transaction: the account is marked disabled, the directory feed + /// records the change, one `sub`-only back-channel logout is queued for every client the person + /// used (contracts.md 2.5), the refresh tokens are revoked and every session is deleted. Returns + /// false, with nothing changed, when the account is missing or already disabled. + pub async fn disable_user(&self, user_id: &str) -> Result { + let now = now_stamp(); + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + let changed = tx + .execute( + "UPDATE users SET disabled_at = ?2, updated_at = ?2 \ + WHERE id = ?1 AND disabled_at IS NULL", + (user_id.to_string(), now.clone()), + ) + .await + .map_err(db_err)?; + if changed != 1 { + return Ok(false); + } + record_change(&tx, user_id, ChangeKind::Member).await?; + // Queued before the sessions go, because the client links are read from them. + backchannel::queue_user(&tx, user_id, EndReason::Disabled, &now).await?; + tx.execute( + "UPDATE refresh_tokens SET revoked_at = ?2 WHERE user_id = ?1 AND revoked_at IS NULL", + (user_id.to_string(), now.clone()), + ) + .await + .map_err(db_err)?; + // No per-session rows here: the sub-only row above covers every session of the person. + tx.execute( + "DELETE FROM sessions WHERE user_id = ?1", + (user_id.to_string(),), + ) + .await + .map_err(db_err)?; + Ok(true) + } + .await; + finish(tx, outcome).await + } + /// Holds a sealed TOTP secret while its enrolment waits for a confirming code. Replaces an /// earlier unconfirmed secret of the same user. The user row is not touched. pub async fn set_totp_pending(&self, user_id: &str, sealed_secret: &str) -> Result<()> { diff --git a/crates/im-web/Cargo.toml b/crates/im-web/Cargo.toml index 28800f6..cc1af9d 100644 --- a/crates/im-web/Cargo.toml +++ b/crates/im-web/Cargo.toml @@ -15,10 +15,11 @@ futures-util.workspace = true http.workspace = true im-core.workspace = true qrcode.workspace = true +reqwest.workspace = true serde.workspace = true serde_json.workspace = true # `net` and `signal` for the listener and the shutdown signals, `time` for the database probe timeout. -tokio = { workspace = true, features = ["net", "signal", "time"] } +tokio = { workspace = true, features = ["net", "signal", "time", "io-util"] } topcoat.workspace = true tracing.workspace = true tracing-subscriber = { workspace = true, features = ["env-filter"] } diff --git a/crates/im-web/src/auth.rs b/crates/im-web/src/auth.rs index 9aef097..a21bb4b 100644 --- a/crates/im-web/src/auth.rs +++ b/crates/im-web/src/auth.rs @@ -11,6 +11,7 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH}; use im_core::model::{Session, User, amr}; use im_core::secret; use im_core::store::Store; +use im_core::store::backchannel::EndReason; use im_core::store::sessions::{NewSession, SESSION_IDLE}; use im_core::token::{constant_time_eq, generate_token, hash_token}; use im_core::totp; @@ -150,7 +151,10 @@ pub async fn start_session(cx: &Cx, user: &User, amr: &str) -> Result { .await? .filter(|old| old.user_id == user.id) { - state.store.end_session(&user.id, &old.id).await?; + state + .store + .end_session(&user.id, &old.id, EndReason::Replaced) + .await?; } let token = generate_token(); let csrf = generate_token(); @@ -172,8 +176,7 @@ pub async fn start_session(cx: &Cx, user: &User, amr: &str) -> Result { state.config.policy.max_sessions, ) .await?; - // Sessions ended by the cap are not signed out elsewhere yet; their back-channel logout is queued - // once the OpenID provider exists. + // Sessions ended by the cap were queued for back-channel logout in the store's transaction. state.live.bump(&Topic::Account(user.id.clone())); // The browser keeps the cookie for the hard cap; the server decides the real expiry. let cookie_age = time::Duration::seconds(i64::try_from(max_age.as_secs()).unwrap_or(i64::MAX)); @@ -189,12 +192,13 @@ pub async fn start_session(cx: &Cx, user: &User, amr: &str) -> Result { Ok(created.session) } -/// Ends the session of `viewer` and clears its cookie. Other sessions of the person are untouched. -pub async fn end_current_session(cx: &Cx, viewer: &Viewer) -> Result<()> { +/// Ends the session of `viewer` (with its back-channel logouts) and clears its cookie. Other sessions of +/// the person are untouched. +pub async fn end_current_session(cx: &Cx, viewer: &Viewer, reason: EndReason) -> Result<()> { let state = app_context::(cx); state .store - .end_session(&viewer.user.id, &viewer.session.id) + .end_session(&viewer.user.id, &viewer.session.id, reason) .await?; state.live.bump(&Topic::Account(viewer.user.id.clone())); jar(cx).remove(Cookie::build((SESSION_COOKIE, "")).path("/")); diff --git a/crates/im-web/src/backchannel.rs b/crates/im-web/src/backchannel.rs new file mode 100644 index 0000000..db5a3ce --- /dev/null +++ b/crates/im-web/src/backchannel.rs @@ -0,0 +1,375 @@ +//! The back-channel logout worker (contracts.md 2.5). It delivers the outbox rows that `im-core` queued +//! when an `im` session ended: it signs a logout token for each row and POSTs it to the client's +//! `backchannel_logout_uri` as the form field `logout_token`. +//! +//! A delivery is done on `200` or `204`. Anything else, or no answer within ten seconds, is a failure and +//! the row is retried after the backoff of contracts.md 2.5 (10 s, 30 s, 1 min, 5 min, then every 15 min) +//! until 24 hours after the row was queued; then it is abandoned and logged. Redirects are never +//! followed. A failure never affects the logout that queued the row: that already committed. +//! +//! The token carries `iss`, `aud` (the client), `iat`, `exp` (two minutes), a fresh `jti`, the logout +//! `events`, `sub` and `sid` (when the row names a session). It carries no `nonce`. + +use std::sync::Arc; +use std::time::Duration; + +use im_core::model::Client; +use im_core::store::Store; +use im_core::store::backchannel::{Attempt, Delivery}; +use im_core::time::{now_stamp, stamp_after, stamp_plus, unix_now}; +use im_core::token::generate_token; +use serde_json::{Value, json}; +use tokio::sync::watch; + +use crate::oidc::signing; + +/// The event name of a logout token (OpenID Back-Channel Logout 1.0). +pub const LOGOUT_EVENT: &str = "http://schemas.openid.net/event/backchannel-logout"; + +/// How long a client has to answer one delivery. +pub const DELIVERY_TIMEOUT: Duration = Duration::from_secs(10); + +/// Lifetime of a logout token, in seconds (contracts.md 2.5: two minutes). +const LOGOUT_TOKEN_TTL: i64 = 2 * 60; + +/// How long a row is retried before it is abandoned (contracts.md 2.5: 24 hours). +pub const RETRY_WINDOW: Duration = Duration::from_secs(24 * 60 * 60); + +/// How often the worker looks for due rows. +const TICK: Duration = Duration::from_secs(5); + +/// The most rows one pass delivers. +const BATCH: i64 = 20; + +/// How long to wait before the next try after `failures` failed tries (contracts.md 2.5). +pub fn backoff(failures: i64) -> Duration { + match failures { + 1 => Duration::from_secs(10), + 2 => Duration::from_secs(30), + 3 => Duration::from_secs(60), + 4 => Duration::from_secs(5 * 60), + _ => Duration::from_secs(15 * 60), + } +} + +/// The HTTP client of the worker: ten-second timeouts and no redirects, so a logout is never sent +/// to another host. +pub fn http_client() -> reqwest::Client { + reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .timeout(DELIVERY_TIMEOUT) + .connect_timeout(DELIVERY_TIMEOUT) + .build() + .expect("the back-channel HTTP client can be built with fixed settings") +} + +/// Runs [`process_due`] every few seconds until `stop` is set. Failures are logged and the next pass +/// tries again. +pub fn spawn( + store: Store, + key: Arc<[u8; 32]>, + issuer: String, + mut stop: watch::Receiver, +) -> tokio::task::JoinHandle<()> { + tokio::spawn(async move { + let http = http_client(); + loop { + tokio::select! { + () = tokio::time::sleep(TICK) => {} + _ = stop.wait_for(|stopped| *stopped) => break, + } + if let Err(error) = process_due(&store, &key, &issuer, &http, &now_stamp()).await { + tracing::error!(error = %error, "back-channel pass failed"); + } + } + }) +} + +/// Delivers every row due at `now`, oldest first, and records each outcome. Returns how many rows were +/// attempted. +pub async fn process_due( + store: &Store, + key: &[u8; 32], + issuer: &str, + http: &reqwest::Client, + now: &str, +) -> im_core::Result { + let due = store.due_deliveries(now, BATCH).await?; + for job in &due { + let attempt = deliver(store, key, issuer, http, job).await; + match &attempt { + Attempt::Delivered => tracing::info!(row = %job.id, "back-channel logout delivered"), + Attempt::Retry { + attempts, + next, + error, + } => tracing::warn!( + row = %job.id, attempts, next = %next, error = %error, + "back-channel logout failed; retry scheduled" + ), + Attempt::Abandon { attempts, error } => tracing::error!( + row = %job.id, attempts, error = %error, + "back-channel logout abandoned" + ), + } + store + .record_attempt(&job.id, &attempt, &now_stamp()) + .await?; + } + Ok(due.len()) +} + +/// One attempt for one row. Every failure path returns an [`Attempt`]; nothing here is fatal. +async fn deliver( + store: &Store, + key: &[u8; 32], + issuer: &str, + http: &reqwest::Client, + job: &Delivery, +) -> Attempt { + let attempts = job.attempts + 1; + let client = match store.client_by_id(&job.client_id).await { + Ok(Some(client)) => client, + Ok(None) => return abandon(attempts, "the client no longer exists"), + Err(error) => return failure(job, attempts, &error.to_string()), + }; + let Some(uri) = client.backchannel_logout_uri.clone() else { + return abandon(attempts, "the client has no back-channel logout URI"); + }; + let token = match logout_token(store, key, issuer, &client, job).await { + Ok(token) => token, + Err(error) => return failure(job, attempts, &error.to_string()), + }; + match http + .post(&uri) + .form(&[("logout_token", token.as_str())]) + .send() + .await + { + Ok(response) if matches!(response.status().as_u16(), 200 | 204) => Attempt::Delivered, + Ok(response) => failure( + job, + attempts, + &format!("the client answered {}", response.status()), + ), + Err(error) => failure(job, attempts, &describe(&error)), + } +} + +/// A failed attempt: retried after the backoff, or abandoned when the retry window has passed. +fn failure(job: &Delivery, attempts: i64, error: &str) -> Attempt { + let window_over = + stamp_plus(&job.created_at, RETRY_WINDOW).is_none_or(|deadline| now_stamp() >= deadline); + if window_over { + return abandon(attempts, &format!("{error}; given up after 24 hours")); + } + Attempt::Retry { + attempts, + next: stamp_after(backoff(attempts)), + error: error.to_owned(), + } +} + +fn abandon(attempts: i64, error: &str) -> Attempt { + Attempt::Abandon { + attempts, + error: error.to_owned(), + } +} + +/// A short description of a transport error, for the log and the row. Never the token. +fn describe(error: &reqwest::Error) -> String { + if error.is_timeout() { + "the client did not answer within 10 seconds".to_owned() + } else if error.is_connect() { + "the client could not be reached".to_owned() + } else { + "the delivery failed".to_owned() + } +} + +/// Signs the logout token of one row for `client` (contracts.md 2.5). +async fn logout_token( + store: &Store, + key: &[u8; 32], + issuer: &str, + client: &Client, + job: &Delivery, +) -> im_core::Result { + let now = unix_now(); + let mut claims = json!({ + "iss": issuer, + "aud": client.id, + "iat": now, + "exp": now + LOGOUT_TOKEN_TTL, + "jti": generate_token(), + "events": { LOGOUT_EVENT: {} }, + "sub": job.sub, + }); + if let (Some(sid), Some(object)) = (&job.sid, claims.as_object_mut()) { + object.insert("sid".into(), Value::String(sid.clone())); + } + signing::sign(store, key, &claims).await +} + +#[cfg(test)] +mod tests { + use super::*; + use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; + use im_core::model::amr; + use im_core::store::backchannel::EndReason; + use im_core::store::clients::NewClient; + use im_core::store::sessions::{NewSession, SESSION_IDLE}; + use im_core::time::stamp_after; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + use tokio::net::{TcpListener, TcpStream}; + + /// Reads one HTTP request from `stream` and returns its body. + async fn read_body(stream: &mut TcpStream) -> String { + let mut buf = Vec::new(); + let mut chunk = [0u8; 1024]; + loop { + let n = stream.read(&mut chunk).await.expect("read"); + if n == 0 { + break; + } + buf.extend_from_slice(&chunk[..n]); + if let Some(head_end) = buf.windows(4).position(|w| w == b"\r\n\r\n") { + let head = String::from_utf8_lossy(&buf[..head_end]).to_ascii_lowercase(); + let length = head + .lines() + .find_map(|line| line.strip_prefix("content-length:")) + .and_then(|value| value.trim().parse::().ok()) + .unwrap_or(0); + if buf.len() >= head_end + 4 + length { + return String::from_utf8_lossy(&buf[head_end + 4..head_end + 4 + length]) + .into_owned(); + } + } + } + String::from_utf8_lossy(&buf).into_owned() + } + + /// A local server that answers successive connections with the given statuses. Returns its URL and + /// a handle that yields the request bodies it received. + async fn server(statuses: Vec) -> (String, tokio::task::JoinHandle>) { + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let addr = listener.local_addr().expect("address"); + let handle = tokio::spawn(async move { + let mut bodies = Vec::new(); + for status in statuses { + let (mut stream, _) = listener.accept().await.expect("accept"); + bodies.push(read_body(&mut stream).await); + let answer = format!( + "HTTP/1.1 {status} test\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + ); + stream.write_all(answer.as_bytes()).await.expect("write"); + } + bodies + }); + (format!("http://{addr}/auth/backchannel-logout"), handle) + } + + #[tokio::test] + async fn a_failed_delivery_is_retried_until_the_client_answers() { + let (_dir, state) = crate::boot::test_state().await; + signing::maintain(&state.store, &state.key) + .await + .expect("signing key"); + let (uri, received) = server(vec![500, 200]).await; + let client = state + .store + .create_client(&NewClient { + name: "Board", + secret_hash: "secret", + redirect_uris: &[], + post_logout_redirect_uris: &[], + backchannel_logout_uri: Some(&uri), + allowed_scopes: "openid", + service_key: Some("iz"), + }) + .await + .expect("client"); + let user = state + .store + .create_user("ada@example.com", "Ada", "hash", false) + .await + .expect("user"); + let session = state + .store + .create_session( + &NewSession { + user_id: &user.id, + token_hash: "token", + csrf_token: "csrf", + amr: amr::PASSWORD, + ip: None, + user_agent: None, + idle: SESSION_IDLE, + max_age: std::time::Duration::from_secs(3600), + }, + 10, + ) + .await + .expect("session") + .session; + state + .store + .touch_client_session(&session.id, &client.id) + .await + .expect("client session"); + assert!( + state + .store + .end_session(&user.id, &session.id, EndReason::Logout) + .await + .expect("end") + ); + let http = http_client(); + let issuer = state.config.base_url.clone(); + + // The first pass meets the 500: the row waits for its first backoff. + let first = process_due(&state.store, &state.key, &issuer, &http, &now_stamp()) + .await + .expect("first pass"); + assert_eq!(first, 1); + let row = state.store.backchannel_rows().await.expect("rows")[0].clone(); + assert_eq!(row.state, "pending"); + assert_eq!(row.attempts, 1); + assert!( + row.last_error.as_deref().is_some_and(|e| e.contains("500")), + "{:?}", + row.last_error + ); + + // Once the backoff has passed, the second pass gets the 200. + let later = stamp_after(std::time::Duration::from_secs(60)); + assert_eq!( + process_due(&state.store, &state.key, &issuer, &http, &later) + .await + .expect("second pass"), + 1 + ); + let row = state + .store + .backchannel_row(&row.id) + .await + .expect("row") + .expect("present"); + assert_eq!(row.state, "sent"); + + // Both deliveries carried a logout token for this client and session, without a nonce. + let bodies = received.await.expect("server"); + assert_eq!(bodies.len(), 2); + let token = bodies[1].strip_prefix("logout_token=").expect("form field"); + let payload = token.split('.').nth(1).expect("payload"); + let claims: serde_json::Value = + serde_json::from_slice(&BASE64_URL_SAFE_NO_PAD.decode(payload).expect("base64")) + .expect("json"); + assert_eq!(claims["aud"], client.id.as_str()); + assert_eq!(claims["sid"], session.id.as_str()); + assert_eq!(claims["sub"], user.id.as_str()); + assert!(claims["events"][LOGOUT_EVENT].is_object()); + assert!(claims.get("nonce").is_none()); + } +} diff --git a/crates/im-web/src/boot.rs b/crates/im-web/src/boot.rs index ba9b3a0..fadcc46 100644 --- a/crates/im-web/src/boot.rs +++ b/crates/im-web/src/boot.rs @@ -5,6 +5,7 @@ //! the pragmas and the migrations), build the router, bind the listener, and serve until SIGTERM or //! Ctrl-C. Stored UI overrides are not layered on the file yet, because no page writes them. +use std::fs::{File, OpenOptions, TryLockError}; use std::os::unix::fs::PermissionsExt; use std::path::Path; use std::sync::Arc; @@ -19,6 +20,7 @@ use tokio::sync::watch; use topcoat::cookie::RouterBuilderCookieExt; use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService}; +use crate::backchannel; use crate::live::LiveHub; use crate::oidc::signing; use crate::pages::not_found::NotFoundLayer; @@ -30,10 +32,36 @@ use crate::throttle::Throttle; /// Name of the instance key file inside the data directory. const KEY_FILE: &str = "im.key"; +/// Name of the lock file inside the data directory. The server holds it for its whole life, and so does +/// every operator command, so the two never open the database at once. +const LOCK_FILE: &str = "im.lock"; + +/// Takes the exclusive lock of the data directory, creating the directory (mode 0700) when needed. The +/// returned file keeps the lock; dropping it releases the lock. Fails with a message that tells the +/// operator to stop the server when it is held. +pub fn lock_data_dir(data_dir: &Path) -> im_core::Result { + std::fs::create_dir_all(data_dir)?; + std::fs::set_permissions(data_dir, std::fs::Permissions::from_mode(0o700))?; + let file = OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(data_dir.join(LOCK_FILE))?; + match file.try_lock() { + Ok(()) => Ok(file), + Err(TryLockError::WouldBlock) => Err(im_core::Error::Conflict( + "im is running on this data directory. Stop the server first, then run the command again." + .into(), + )), + Err(TryLockError::Error(error)) => Err(error.into()), + } +} + /// Runs the server until a stop signal arrives. Returns once every connection has finished. pub async fn serve(config_path: &Path) -> im_core::Result<()> { let config = Config::load(config_path)?; let listen = config.listen; + let _lock = lock_data_dir(&config.data_dir)?; let state = open_state(config).await?; let listener = TcpListener::bind(listen).await.map_err(|error| { @@ -54,6 +82,12 @@ pub async fn serve(config_path: &Path) -> im_core::Result<()> { stop_tx.send_replace(true); }); let signing_worker = signing::spawn(state.store.clone(), state.key.clone(), stop_rx.clone()); + let backchannel_worker = backchannel::spawn( + state.store.clone(), + state.key.clone(), + state.config.base_url.clone(), + stop_rx.clone(), + ); topcoat::serve_until( listener, @@ -62,6 +96,7 @@ pub async fn serve(config_path: &Path) -> im_core::Result<()> { ) .await?; let _ = signing_worker.await; + let _ = backchannel_worker.await; tracing::info!("im stopped"); Ok(()) } diff --git a/crates/im-web/src/cli.rs b/crates/im-web/src/cli.rs index d32ee34..99e56d0 100644 --- a/crates/im-web/src/cli.rs +++ b/crates/im-web/src/cli.rs @@ -17,7 +17,7 @@ use im_core::oauth::{ use im_core::store::clients::NewClient; use im_core::token::{generate_token, hash_token}; -use crate::boot::open_state; +use crate::boot::{lock_data_dir, open_state}; use crate::state::AppState; /// Printed with a usage error. @@ -73,6 +73,8 @@ where { let outcome = async { let config = Config::load(config).map_err(|e| e.to_string())?; + // Held for the whole command: a running server holds the same lock and refuses this one. + let _lock = lock_data_dir(&config.data_dir).map_err(|e| e.to_string())?; let state = open_state(config).await.map_err(|e| e.to_string())?; action(state).await } diff --git a/crates/im-web/src/i18n/oidc.rs b/crates/im-web/src/i18n/oidc.rs index 4b41da0..8e44fd3 100644 --- a/crates/im-web/src/i18n/oidc.rs +++ b/crates/im-web/src/i18n/oidc.rs @@ -11,6 +11,16 @@ pub enum OidcText { ErrorTitle, /// The sentence under the title. ErrorBody, + /// The title of the page after a sign-out. + SignedOutTitle, + /// The sentence under the signed-out title. + SignedOutBody, + /// The title of the sign-out confirmation page. + ConfirmTitle, + /// The sentence under the confirmation title. + ConfirmBody, + /// The button that confirms the sign-out. + ConfirmButton, } /// The text of `key` in `lang`. @@ -24,5 +34,23 @@ pub fn text(lang: Lang, key: OidcText) -> &'static str { (OidcText::ErrorBody, Lang::Tr) => { "Bu oturum açma isteği geçerli değil. Uygulamaya dönüp yeniden deneyin." } + (OidcText::SignedOutTitle, Lang::En) => "Signed out", + (OidcText::SignedOutTitle, Lang::Tr) => "Oturum kapatıldı", + (OidcText::SignedOutBody, Lang::En) => { + "You are signed out of im. You can close this window." + } + (OidcText::SignedOutBody, Lang::Tr) => { + "im oturumunuz kapatıldı. Bu pencereyi kapatabilirsiniz." + } + (OidcText::ConfirmTitle, Lang::En) => "Sign out of im?", + (OidcText::ConfirmTitle, Lang::Tr) => "im oturumu kapatılsın mı?", + (OidcText::ConfirmBody, Lang::En) => { + "This ends your im session and your sessions in the family apps you use." + } + (OidcText::ConfirmBody, Lang::Tr) => { + "Bu işlem im oturumunuzu ve kullandığınız aile uygulamalarındaki oturumları kapatır." + } + (OidcText::ConfirmButton, Lang::En) => "Sign out", + (OidcText::ConfirmButton, Lang::Tr) => "Oturumu kapat", } } diff --git a/crates/im-web/src/main.rs b/crates/im-web/src/main.rs index 9aa8b38..3c20f6f 100644 --- a/crates/im-web/src/main.rs +++ b/crates/im-web/src/main.rs @@ -7,6 +7,7 @@ mod assets; mod audit; mod auth; +mod backchannel; mod boot; mod cli; mod client_ip; diff --git a/crates/im-web/src/oidc/authorize.rs b/crates/im-web/src/oidc/authorize.rs index a2d3355..1accef7 100644 --- a/crates/im-web/src/oidc/authorize.rs +++ b/crates/im-web/src/oidc/authorize.rs @@ -193,6 +193,22 @@ async fn authorize(cx: &Cx) -> Result { return Err(see_other(format!("/login?next={}", percent_encode(back))).into()); }; + // An administrator must have two-factor sign-in first (the policy). The security page enrols it; a + // prompt=none request cannot show a page, so it is refused instead. + if viewer.user.is_admin + && app.config.policy.require_2fa_for_admins + && !viewer.user.totp_enabled() + { + if asked.no_prompt { + let refused = Refused { + code: "interaction_required", + state: asked.state.clone(), + }; + return Err(refusal_redirect(redirect_uri, issuer, &refused).into()); + } + return Err(see_other("/account/security?notice=enrol").into()); + } + let code = generate_token(); let expires_at = stamp_after(CODE_TTL); app.store diff --git a/crates/im-web/src/oidc/discovery.rs b/crates/im-web/src/oidc/discovery.rs index 18c3b1f..e3bed51 100644 --- a/crates/im-web/src/oidc/discovery.rs +++ b/crates/im-web/src/oidc/discovery.rs @@ -13,8 +13,7 @@ use super::signing; use super::{PUBLIC_CACHE, issuer, json_response}; use crate::state::AppState; -/// The grant types this provider offers. `client_credentials` is listed as the contracts require; it is -/// answered once the machine-token part is built. +/// The grant types this provider offers (contracts.md 2.1). const GRANT_TYPES: [&str; 3] = ["authorization_code", "refresh_token", "client_credentials"]; /// The client authentication methods of `/token`, `/revoke` and `/introspect`. diff --git a/crates/im-web/src/oidc/introspect.rs b/crates/im-web/src/oidc/introspect.rs new file mode 100644 index 0000000..2464702 --- /dev/null +++ b/crates/im-web/src/oidc/introspect.rs @@ -0,0 +1,120 @@ +//! `POST /introspect` (RFC 7662): tells a client whether a token is active. A client sees only its own +//! tokens: a token issued to another client, or one that is expired, revoked or rotated, is +//! `{"active": false}` and nothing more. +//! +//! An access token is checked by its signature, its time and its issuer, and then by what it stands +//! for: a machine token is active while its client is; a person's token is active while its session +//! and account are. A refresh token is active while it is unused, unrevoked and unexpired, and its +//! session is live. The client authenticates like at `/token`. + +use im_core::jwt::{self, PublishedKey}; +use im_core::model::Client; +use im_core::time::{now_stamp, unix_now, unix_seconds}; +use im_core::token::hash_token; +use serde_json::{Value, json}; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::response::Response; +use topcoat::router::{Body, StatusCode, route}; + +use super::signing; +use super::token::client_form; +use super::{issuer, json_response, oauth_error, one}; +use crate::state::AppState; + +/// `POST /introspect`. +#[route(POST "/introspect")] +async fn introspect(cx: &Cx, body: Body) -> Result { + let app = app_context::(cx); + let (client, pairs) = match client_form(cx, body).await? { + Ok(parts) => parts, + Err(response) => return Ok(response), + }; + let Some(token) = one(&pairs, "token") else { + return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request")); + }; + let answer = match access_answer(app, &client, token).await? { + Some(answer) => answer, + None => refresh_answer(app, &client, token).await?, + }; + Ok(json_response(StatusCode::OK, &answer)) +} + +/// The answer for an access token of ours. `None` when the text is not a token of this provider, so the +/// caller tries the refresh tokens. +async fn access_answer(app: &AppState, client: &Client, token: &str) -> Result> { + let published = signing::published_keys(&app.store).await?; + let keys: Vec = published + .iter() + .filter_map(|key| PublishedKey::new(key.kid.clone(), &key.public_raw)) + .collect(); + let Ok(claims) = jwt::verify(&keys, token) else { + return Ok(None); + }; + let now = unix_now(); + let Some(audience) = jwt::single_audience(&claims) else { + return Ok(Some(inactive())); + }; + if jwt::check_claims(&claims, issuer(app), audience, now).is_err() { + return Ok(Some(inactive())); + } + // Only tokens issued to this client are reported, whatever else they are. + if claims.get("azp").and_then(Value::as_str) != Some(client.id.as_str()) { + return Ok(Some(inactive())); + } + let Some(scope) = claims.get("scope").and_then(Value::as_str) else { + return Ok(Some(inactive())); + }; + let Some(sub) = claims.get("sub").and_then(Value::as_str) else { + return Ok(Some(inactive())); + }; + // A person's access token lives only as long as its session and account. + if !sub.starts_with("client:") { + let Some(sid) = claims.get("sid").and_then(Value::as_str) else { + return Ok(Some(inactive())); + }; + if app.store.live_session(sid).await?.is_none() { + return Ok(Some(inactive())); + } + } + Ok(Some(json!({ + "active": true, + "scope": scope, + "client_id": client.id, + "token_type": "Bearer", + "exp": claims.get("exp"), + "iat": claims.get("iat"), + "sub": sub, + "aud": audience, + "iss": issuer(app), + }))) +} + +/// The answer for a refresh token of this client. +async fn refresh_answer(app: &AppState, client: &Client, token: &str) -> Result { + let Some(row) = app.store.refresh_token(&hash_token(token)).await? else { + return Ok(inactive()); + }; + let usable = row.client_id == client.id + && row.used_at.is_none() + && row.revoked_at.is_none() + && row.expires_at > now_stamp(); + if !usable || app.store.live_session(&row.session_id).await?.is_none() { + return Ok(inactive()); + } + Ok(json!({ + "active": true, + "scope": row.scope, + "client_id": client.id, + "token_type": "refresh_token", + "exp": unix_seconds(&row.expires_at), + "iat": unix_seconds(&row.created_at), + "sub": row.user_id, + "iss": issuer(app), + })) +} + +/// The answer for everything that is not active: no detail, so nothing is learned about other tokens. +fn inactive() -> Value { + json!({ "active": false }) +} diff --git a/crates/im-web/src/oidc/logout.rs b/crates/im-web/src/oidc/logout.rs new file mode 100644 index 0000000..8a33ca9 --- /dev/null +++ b/crates/im-web/src/oidc/logout.rs @@ -0,0 +1,278 @@ +//! `GET /logout` and `POST /logout`: OpenID Connect RP-Initiated Logout (contracts.md 2.5), and the +//! sign-out button of the account menu, which posts to the same path with no hint. +//! +//! The rules, in order: +//! - An `id_token_hint` is an ID token of ours: the signature and `iss` are checked, the expiry is not +//! (an expired hint still names a session). A hint that fails is ignored, as if it were absent. +//! - The client is named by the hint's `aud`. A redirect happens only when the client is enabled and +//! `post_logout_redirect_uri` equals one of its registered URIs exactly. Otherwise the answer is the +//! signed-out page, never a redirect. +//! - `state` is echoed on the redirect only when it is usable (bounded, no control characters). +//! - A `GET` ends a session only when the hint's `sid` is the browser's own session: an attacker's +//! link cannot know that. Any other `GET` shows a confirmation form, which carries the session's CSRF +//! token. A `POST` checks that token before anything changes. +//! - Ending the session is `im`'s own: the browser session is deleted (and its clients told by +//! back-channel logout, in the store's transaction). When the hint names another session of the same +//! person, that one ends too. + +use im_core::jwt::{self, PublishedKey}; +use im_core::model::AuditAction; +use im_core::oauth::MAX_ECHO_BYTES; +use im_core::store::Store; +use im_core::store::backchannel::EndReason; +use serde::Deserialize; +use serde_json::Value; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::content::Form; +use topcoat::router::error::{forbidden, see_other}; +use topcoat::router::page; +use topcoat::view::{View, view}; + +use super::signing; +use super::{issuer, with_query}; +use crate::audit::{Actor, record}; +use crate::auth::{Viewer, check_csrf, current_user, end_current_session}; +use crate::i18n::Lang; +use crate::i18n::oidc::{OidcText, text}; +use crate::live::Topic; +use crate::state::AppState; +use crate::views::{page_lang, shell}; + +/// The parameters of a logout request, from the query (GET) or the form (POST). Every field is optional. +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +pub struct LogoutForm { + /// The CSRF token of the browser session. Required by a POST that would end a session. + csrf: String, + /// An ID token previously issued to the client. + id_token_hint: String, + /// Where the client wants the browser to land. + post_logout_redirect_uri: String, + /// The client's opaque value, echoed back on the redirect. + state: String, +} + +/// What a valid hint says: the session it names, and the client it was issued to. +struct Hint { + /// The `im` session of the sign-in, when the hint names one. + sid: Option, +} + +/// The checked request: the hint (if valid), the redirect to make (if allowed) and the echoed state. +struct Asked { + /// The verified hint, if there was one that checks out. + hint: Option, + /// The post-logout URI, when it equals a registered one of the hinted client. + redirect: Option, + /// The state to echo, when it is usable. + state: Option, + /// The hint as given, when it checks out: the confirmation form carries it. + raw_hint: Option, +} + +/// Tells a state apart from a value that must not be echoed. +fn usable_state(value: &str) -> bool { + !value.is_empty() && value.len() <= MAX_ECHO_BYTES && !value.chars().any(char::is_control) +} + +/// Verifies an ID token of ours for logout. `None` when it is not an ID token of this provider, or its +/// signature or issuer is wrong. The expiry is not checked. +async fn verify_hint( + store: &Store, + issuer: &str, + token: &str, +) -> im_core::Result)>> { + let published = signing::published_keys(store).await?; + let keys: Vec = published + .iter() + .filter_map(|key| PublishedKey::new(key.kid.clone(), &key.public_raw)) + .collect(); + let Ok(claims) = jwt::verify(&keys, token) else { + return Ok(None); + }; + if jwt::check_issuer(&claims, issuer).is_err() { + return Ok(None); + } + // An access token has `azp` and `scope`; an ID token has neither. Only ID tokens are hints. + if claims.contains_key("azp") || claims.contains_key("scope") { + return Ok(None); + } + let Some(client_id) = jwt::single_audience(&claims) else { + return Ok(None); + }; + let sid = claims.get("sid").and_then(Value::as_str).map(str::to_owned); + Ok(Some((client_id.to_owned(), sid))) +} + +/// Checks the request. Nothing here changes state. +async fn read(app: &AppState, form: &LogoutForm) -> Result { + let state = Some(form.state.as_str()) + .filter(|value| usable_state(value)) + .map(str::to_owned); + let mut asked = Asked { + hint: None, + redirect: None, + state, + raw_hint: None, + }; + if form.id_token_hint.is_empty() { + return Ok(asked); + } + let Some((client_id, sid)) = verify_hint(&app.store, issuer(app), &form.id_token_hint).await? + else { + return Ok(asked); + }; + asked.raw_hint = Some(form.id_token_hint.clone()); + let client = app.store.client_by_id(&client_id).await?; + if let Some(client) = client.filter(|c| !c.is_disabled()) + && !form.post_logout_redirect_uri.is_empty() + && client + .post_logout_redirect_uris + .iter() + .any(|registered| registered == &form.post_logout_redirect_uri) + { + asked.redirect = Some(form.post_logout_redirect_uri.clone()); + } + asked.hint = Some(Hint { sid }); + Ok(asked) +} + +/// The redirect to the client, with the state when there is one. `None` means the signed-out page. +fn redirect_target(asked: &Asked) -> Option { + let uri = asked.redirect.as_deref()?; + Some(match asked.state.as_deref() { + Some(state) => with_query(uri, &[("state", state)]), + None => uri.to_owned(), + }) +} + +/// Ends the browser's session and, when the hint names another session of the same person, that one +/// too. Audits the sign-out. +async fn sign_out(cx: &Cx, viewer: &Viewer, hint_sid: Option<&str>) -> Result<()> { + let app = app_context::(cx); + end_current_session(cx, viewer, EndReason::Logout).await?; + if let Some(other) = hint_sid.filter(|sid| *sid != viewer.session.id) { + // The store checks ownership: another person's session is not ended, and the call says so. + if app + .store + .end_session(&viewer.user.id, other, EndReason::Logout) + .await? + { + app.live.bump(&Topic::Account(viewer.user.id.clone())); + } + } + record( + cx, + Actor::User(&viewer.user.id), + AuditAction::Logout, + Some(("session", &viewer.session.id)), + Value::Null, + ) + .await; + Ok(()) +} + +/// `GET /logout`. +#[page(GET "/logout")] +async fn logout_get(cx: &Cx, Form(form): Form) -> Result { + let app = app_context::(cx); + let asked = read(app, &form).await?; + let viewer = current_user(cx).await?; + let lang = page_lang(cx, viewer.as_ref()); + let own_session = viewer.as_ref().is_some_and(|viewer| { + asked + .hint + .as_ref() + .and_then(|hint| hint.sid.as_deref()) + .is_some_and(|sid| sid == viewer.session.id) + }); + match viewer { + Some(viewer) if own_session => { + sign_out(cx, &viewer, None).await?; + if let Some(target) = redirect_target(&asked) { + return Err(see_other(target).into()); + } + Ok(logout_view(cx, lang, None)) + } + Some(viewer) => { + let confirm = Confirm { + csrf: viewer.session.csrf_token.clone(), + raw_hint: asked.raw_hint.clone(), + redirect: asked.redirect.clone(), + state: asked.state.clone(), + }; + Ok(logout_view(cx, lang, Some(confirm))) + } + // No session to end: only the redirect, if the hint allows one. + None => { + if let Some(target) = redirect_target(&asked) { + return Err(see_other(target).into()); + } + Ok(logout_view(cx, lang, None)) + } + } +} + +/// `POST /logout`. Without a session there is nothing to end, so no CSRF check applies. +#[page(POST "/logout")] +async fn logout_post(cx: &Cx, Form(form): Form) -> Result { + let app = app_context::(cx); + let asked = read(app, &form).await?; + let viewer = current_user(cx).await?; + if let Some(viewer) = &viewer { + if !check_csrf(&viewer.session, &form.csrf) { + return Err(forbidden().into()); + } + let hint_sid = asked.hint.as_ref().and_then(|hint| hint.sid.clone()); + sign_out(cx, viewer, hint_sid.as_deref()).await?; + } + if let Some(target) = redirect_target(&asked) { + return Err(see_other(target).into()); + } + let lang = page_lang(cx, None); + Ok(logout_view(cx, lang, None)) +} + +/// The form that asks for a sign-out (the GET answer when the session is not the hinted one). +struct Confirm { + csrf: String, + raw_hint: Option, + redirect: Option, + state: Option, +} + +/// The confirmation page, or the signed-out page when `confirm` is `None`. The form posts to this same +/// path and carries everything the POST needs to finish the same request. +fn logout_view(cx: &Cx, lang: Lang, confirm: Option) -> impl View { + let title = if confirm.is_some() { + text(lang, OidcText::ConfirmTitle) + } else { + text(lang, OidcText::SignedOutTitle) + }; + view! { cx => + shell(title: title, lang: lang, viewer: None, +
+

(title)

+ if let Some(confirm) = confirm { +

(text(lang, OidcText::ConfirmBody))

+
+ + if let Some(hint) = confirm.raw_hint { + + } + if let Some(uri) = confirm.redirect { + + } + if let Some(state) = confirm.state { + + } + +
+ } else { +

(text(lang, OidcText::SignedOutBody))

+ } +
+ ) + } +} diff --git a/crates/im-web/src/oidc/mod.rs b/crates/im-web/src/oidc/mod.rs index 4585645..3b5dfdb 100644 --- a/crates/im-web/src/oidc/mod.rs +++ b/crates/im-web/src/oidc/mod.rs @@ -7,6 +7,9 @@ pub mod authorize; pub mod discovery; +pub mod introspect; +pub mod logout; +pub mod revoke; pub mod signing; pub mod token; pub mod userinfo; diff --git a/crates/im-web/src/oidc/revoke.rs b/crates/im-web/src/oidc/revoke.rs new file mode 100644 index 0000000..944a96b --- /dev/null +++ b/crates/im-web/src/oidc/revoke.rs @@ -0,0 +1,40 @@ +//! `POST /revoke` (RFC 7009): a client gives back one of its own refresh tokens, and the whole chain of +//! that token is revoked. +//! +//! The client authenticates like at `/token`. The answer is `200` with an empty body for every token: a +//! token that is unknown, belongs to another client, or is already revoked gets the same answer, so the +//! endpoint does not reveal which tokens exist (RFC 7009 section 2.2). Access tokens need no table here: +//! they live ten minutes and are refused at once when their session ends, so revoking the session is the +//! way to end them. + +use im_core::token::hash_token; +use topcoat::Result; +use topcoat::context::Cx; +use topcoat::router::response::Response; +use topcoat::router::{Body, StatusCode, route}; + +use super::token::client_form; +use super::{oauth_error, one}; +use crate::state::AppState; +use topcoat::context::app_context; + +/// `POST /revoke`. +#[route(POST "/revoke")] +async fn revoke(cx: &Cx, body: Body) -> Result { + let app = app_context::(cx); + let (client, pairs) = match client_form(cx, body).await? { + Ok(parts) => parts, + Err(response) => return Ok(response), + }; + let Some(token) = one(&pairs, "token") else { + return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request")); + }; + if let Some(row) = app.store.refresh_token(&hash_token(token)).await? + && row.client_id == client.id + { + app.store.revoke_refresh_family(&row.family_id).await?; + } + let mut response = Response::new(Body::empty()); + *response.status_mut() = StatusCode::OK; + Ok(response) +} diff --git a/crates/im-web/src/oidc/tests.rs b/crates/im-web/src/oidc/tests.rs index 6f4649c..36e58fc 100644 --- a/crates/im-web/src/oidc/tests.rs +++ b/crates/im-web/src/oidc/tests.rs @@ -23,6 +23,9 @@ use crate::state::AppState; /// The registered redirect URI of the test client. const REDIRECT: &str = "http://127.0.0.1:17651/auth/callback"; +/// The registered post-logout URI of the test client. +const POST_LOGOUT: &str = "http://127.0.0.1:17651/signed-out"; + /// The cookie name the browser sends: the `__Host-` prefix is added by the jar. const SESSION_COOKIE: &str = "__Host-im_session"; @@ -43,13 +46,14 @@ async fn fixture() -> Fixture { .expect("signing key"); let secret = generate_token(); let uris = vec![REDIRECT.to_owned()]; + let post_logout = vec![POST_LOGOUT.to_owned()]; let client = state .store .create_client(&NewClient { name: "Files", secret_hash: &hash_token(&secret), redirect_uris: &uris, - post_logout_redirect_uris: &[], + post_logout_redirect_uris: &post_logout, backchannel_logout_uri: None, allowed_scopes: "openid profile email", service_key: Some("in"), @@ -315,3 +319,152 @@ async fn the_id_token_verifies_against_the_published_key_and_carries_the_nonce() assert_eq!(claims["sub"], f.user_id.as_str()); assert_eq!(claims["amr"], serde_json::json!(["pwd"])); } + +/// Posts a form to `path` with `client_secret_basic` for `client`. +async fn post_as( + f: &Fixture, + path: &str, + client: &Client, + secret: &str, + body: &str, +) -> (StatusCode, Value) { + let basic = BASE64_STANDARD.encode(format!("{}:{}", client.id, secret)); + let request = http::Request::post(path) + .header(CONTENT_TYPE, "application/x-www-form-urlencoded") + .header(AUTHORIZATION, format!("Basic {basic}")) + .body(Body::from(body.to_owned())) + .expect("request"); + let (status, _, text) = send(&f.state, request).await; + (status, serde_json::from_str(&text).unwrap_or(Value::Null)) +} + +/// A client that is a family service with the given key and allowed scopes. Returns it with its secret. +async fn service(f: &Fixture, key: &str, scopes: &str) -> (Client, String) { + let secret = generate_token(); + let client = f + .state + .store + .create_client(&NewClient { + name: key, + secret_hash: &hash_token(&secret), + redirect_uris: &[], + post_logout_redirect_uris: &[], + backchannel_logout_uri: None, + allowed_scopes: scopes, + service_key: Some(key), + }) + .await + .expect("service client"); + (client, secret) +} + +#[tokio::test] +async fn client_credentials_refuses_a_scope_beyond_the_allowed_ones() { + let f = fixture().await; + let (caller, secret) = service(&f, "iz", "directory.read").await; + let (status, body) = post_as( + &f, + "/token", + &caller, + &secret, + "grant_type=client_credentials&scope=files.service&audience=im", + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{body}"); + assert_eq!(body["error"], "invalid_scope"); +} + +#[tokio::test] +async fn client_credentials_refuses_an_unknown_audience() { + let f = fixture().await; + let (caller, secret) = service(&f, "iz", "directory.read").await; + let (status, body) = post_as( + &f, + "/token", + &caller, + &secret, + "grant_type=client_credentials&scope=directory.read&audience=nowhere", + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{body}"); + assert_eq!(body["error"], "invalid_target"); +} + +#[tokio::test] +async fn introspection_reports_a_token_inactive_for_any_client_but_its_own() { + let f = fixture().await; + let (caller, caller_secret) = service(&f, "iz", "directory.read").await; + let (other, other_secret) = service(&f, "board", "directory.read").await; + let (status, issued) = post_as( + &f, + "/token", + &caller, + &caller_secret, + "grant_type=client_credentials&scope=directory.read&audience=im", + ) + .await; + assert_eq!(status, StatusCode::OK, "{issued}"); + let token = issued["access_token"].as_str().expect("token"); + let body = format!("token={token}"); + + let (status, own) = post_as(&f, "/introspect", &caller, &caller_secret, &body).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(own["active"], true, "{own}"); + + let (status, foreign) = post_as(&f, "/introspect", &other, &other_secret, &body).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(foreign, serde_json::json!({ "active": false })); +} + +/// The ID token of a fresh sign-in of the fixture's person, and the code exchange's session id. +async fn id_token_of(f: &Fixture) -> String { + let verifier = generate_token(); + let code = code_for(f, &f.client, &verifier).await; + let (status, tokens) = token_with(f, &f.client, &f.secret, &code_body(&code, &verifier)).await; + assert_eq!(status, StatusCode::OK, "{tokens}"); + tokens["id_token"].as_str().expect("id_token").to_owned() +} + +#[tokio::test] +async fn logout_redirects_only_to_the_registered_post_logout_uri() { + let f = fixture().await; + let hint = encode_value(&id_token_of(&f).await); + let unregistered = encode_value("http://127.0.0.1:17651/elsewhere"); + let path = + format!("/logout?id_token_hint={hint}&post_logout_redirect_uri={unregistered}&state=abc"); + let request = http::Request::get(path) + .header(COOKIE, format!("{SESSION_COOKIE}={}", f.cookie)) + .body(Body::empty()) + .expect("request"); + let (status, headers, body) = send(&f.state, request).await; + assert_eq!(status, StatusCode::OK, "{body}"); + assert!( + headers.get(LOCATION).is_none(), + "redirected to an unregistered URI" + ); + // The hint names the browser's own session, so it ends even though nothing is redirected. + let live = f + .state + .store + .session_by_token_hash(&hash_token(&f.cookie)) + .await + .expect("lookup"); + assert!(live.is_none(), "the session did not end"); +} + +#[tokio::test] +async fn logout_with_the_registered_uri_redirects_and_carries_the_state() { + let f = fixture().await; + let hint = encode_value(&id_token_of(&f).await); + let registered = encode_value(POST_LOGOUT); + let path = + format!("/logout?id_token_hint={hint}&post_logout_redirect_uri={registered}&state=abc"); + let request = http::Request::get(path) + .header(COOKIE, format!("{SESSION_COOKIE}={}", f.cookie)) + .body(Body::empty()) + .expect("request"); + let (status, headers, _) = send(&f.state, request).await; + assert_eq!(status, StatusCode::SEE_OTHER); + let location = headers[LOCATION].to_str().expect("location"); + assert_eq!(location, format!("{POST_LOGOUT}?state=abc")); +} diff --git a/crates/im-web/src/oidc/token.rs b/crates/im-web/src/oidc/token.rs index 80ba329..6ebd6c3 100644 --- a/crates/im-web/src/oidc/token.rs +++ b/crates/im-web/src/oidc/token.rs @@ -4,16 +4,18 @@ //! Client authentication is `client_secret_basic` or `client_secret_post`, never both. The //! authorization-code grant consumes the code in one statement and refuses a reuse by revoking every //! refresh token made from that code. The refresh grant rotates the token; presenting a rotated one -//! revokes its whole family. Client credentials (machine tokens) is answered `unsupported_grant_type` -//! until its part of the provider is built. +//! revokes its whole family. The client-credentials grant issues the machine tokens of contracts.md 2.6. +//! A disabled client fails client authentication, so no grant runs for it: its refresh tokens and its +//! machine tokens are refused at once. use base64::prelude::{BASE64_STANDARD, Engine as _}; use http::header::AUTHORIZATION; -use im_core::model::{Client, Session, User}; +use im_core::model::{Client, Session, User, amr}; +use im_core::oauth::{is_supported_scope, is_user_scope, is_valid_family_key}; use im_core::oauth::{is_valid_verifier, pkce_s256}; use im_core::store::new_id; use im_core::store::oidc::NewRefreshToken; -use im_core::time::{now_stamp, stamp_after, unix_seconds}; +use im_core::time::{now_stamp, stamp_after, unix_now, unix_seconds}; use im_core::token::{constant_time_eq, generate_token, hash_token}; use serde_json::{Map, Value, json}; use topcoat::Result; @@ -56,6 +58,7 @@ async fn token_endpoint(cx: &Cx, body: Body) -> Result { match one(&pairs, "grant_type") { Some("authorization_code") => grant_code(app, &client, &pairs).await, Some("refresh_token") => grant_refresh(app, &client, &pairs).await, + Some("client_credentials") => grant_client(app, &client, &pairs).await, Some(_) => Ok(oauth_error( StatusCode::BAD_REQUEST, "unsupported_grant_type", @@ -64,6 +67,35 @@ async fn token_endpoint(cx: &Cx, body: Body) -> Result { } } +/// Reads a client-authenticated form for `/revoke` and `/introspect`: the same content type, size and +/// client authentication as `/token`. The inner `Err` is the refusal to send. +pub(super) async fn client_form( + cx: &Cx, + body: Body, +) -> Result> { + let app = app_context::(cx); + if !is_form(content_type(cx)) { + return Ok(Err(oauth_error(StatusCode::BAD_REQUEST, "invalid_request"))); + } + let Ok(bytes) = to_bytes(body, TOKEN_BODY_LIMIT).await else { + return Ok(Err(oauth_error( + StatusCode::PAYLOAD_TOO_LARGE, + "invalid_request", + ))); + }; + let Some(pairs) = parse_pairs(&bytes) else { + return Ok(Err(oauth_error(StatusCode::BAD_REQUEST, "invalid_request"))); + }; + let authorization = headers(cx) + .get(AUTHORIZATION) + .and_then(|value| value.to_str().ok()) + .map(str::to_owned); + match authenticate(app, authorization.as_deref(), &pairs).await? { + Ok(client) => Ok(Ok((client, pairs))), + Err(response) => Ok(Err(response)), + } +} + /// True for a form body, with or without parameters after the media type. fn is_form(content_type: Option<&str>) -> bool { content_type.is_some_and(|value| { @@ -96,7 +128,7 @@ fn basic_credentials(header: &str) -> Option, pairs: &Pairs, @@ -280,6 +312,53 @@ async fn grant_refresh(app: &AppState, client: &Client, pairs: &Pairs) -> Result )) } +/// The client-credentials grant (contracts.md 2.6): a machine token that a family service presents to +/// another family service. The caller must be a family service (its key is `svc`), every requested scope +/// must be a machine scope the client is allowed, and the audience must be a known family key. The token +/// is addressed to that key, so it cannot be presented to any other service. +async fn grant_client(app: &AppState, client: &Client, pairs: &Pairs) -> Result { + let Some(caller) = client.service_key.as_deref() else { + return Ok(oauth_error(StatusCode::BAD_REQUEST, "unauthorized_client")); + }; + let (Some(requested), Some(audience)) = (one(pairs, "scope"), one(pairs, "audience")) else { + return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request")); + }; + let mut granted: Vec<&str> = Vec::new(); + for word in requested.split_whitespace() { + // A person's scopes never come from this grant, so a user scope is refused like an unknown one. + if !is_supported_scope(word) || is_user_scope(word) || !client.allows_scope(word) { + return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_scope")); + } + if !granted.contains(&word) { + granted.push(word); + } + } + if granted.is_empty() { + return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_scope")); + } + // `im` itself is always a known audience; any other one needs a registered family client. + let known = audience == USERINFO_AUDIENCE + || (is_valid_family_key(audience) && app.store.family_key_known(audience).await?); + if !known { + return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_target")); + } + let scope = granted.join(" "); + let now = unix_now(); + let claims = json!({ + "iss": issuer(app), + "sub": format!("client:{}", client.id), + "azp": client.id, + "aud": audience, + "scope": scope, + "svc": caller, + "iat": now, + "exp": now + i64::try_from(ACCESS_TTL.as_secs()).unwrap_or(0), + "jti": generate_token(), + }); + let token = signing::sign(&app.store, &app.key, &claims).await?; + Ok(token_response(token, &scope, None, None)) +} + /// The JSON answer of a successful exchange, with the no-store headers that RFC 6749 requires. fn token_response( access_token: String, @@ -315,7 +394,10 @@ pub fn person_claims(user: &User, scope: &str) -> Map { if granted("profile") { claims.insert("name".into(), json!(user.name)); claims.insert("admin".into(), json!(user.is_admin)); - claims.insert("locale".into(), json!(user.locale)); + // An account that follows the browser's language has no stored locale to share. + if !user.locale_auto { + claims.insert("locale".into(), json!(user.locale)); + } claims.insert("zoneinfo".into(), json!(user.zoneinfo)); claims.insert("picture_version".into(), json!(user.picture_version)); } @@ -364,7 +446,7 @@ async fn id_token( "exp": now + i64::try_from(ID_TOKEN_TTL.as_secs()).unwrap_or(0), "auth_time": unix_seconds(&session.auth_time).unwrap_or(now), "sid": session.id, - "amr": session.amr.split(' ').collect::>(), + "amr": amr::rfc8176(&session.amr), }); if let Some(object) = claims.as_object_mut() { if let Some(nonce) = nonce { diff --git a/crates/im-web/src/oidc/userinfo.rs b/crates/im-web/src/oidc/userinfo.rs index c1b2de7..dc7b818 100644 --- a/crates/im-web/src/oidc/userinfo.rs +++ b/crates/im-web/src/oidc/userinfo.rs @@ -5,7 +5,7 @@ //! provider), `exp` and `iat`, and the `openid` scope. The token is then checked against the session it //! names: a session that ended, or a disabled account, refuses the token at once, even before it expires. -use http::header::{AUTHORIZATION, CACHE_CONTROL, HeaderValue, WWW_AUTHENTICATE}; +use http::header::{AUTHORIZATION, HeaderValue, WWW_AUTHENTICATE}; use im_core::jwt::{self, PublishedKey}; use im_core::time::unix_now; use serde_json::{Value, json}; @@ -66,14 +66,22 @@ async fn userinfo(cx: &Cx) -> Result { if session.user_id != user.id { return Ok(unauthorized()); } + // A token outlives nothing that its client loses: a disabled client's tokens are refused at once. + let Some(client_id) = claims.get("azp").and_then(Value::as_str) else { + return Ok(unauthorized()); + }; + if !app + .store + .client_by_id(client_id) + .await? + .is_some_and(|client| !client.is_disabled()) + { + return Ok(unauthorized()); + } let mut body = person_claims(&user, scope); body.insert("sub".into(), json!(user.id)); - let mut response = json_response(StatusCode::OK, &Value::Object(body)); - response - .headers_mut() - .insert(CACHE_CONTROL, HeaderValue::from_static("no-store")); - Ok(response) + Ok(json_response(StatusCode::OK, &Value::Object(body))) } /// The token of a `Bearer` authorization header, or `None`. diff --git a/crates/im-web/src/pages/login.rs b/crates/im-web/src/pages/login.rs index 6fd61ac..72ea1f1 100644 --- a/crates/im-web/src/pages/login.rs +++ b/crates/im-web/src/pages/login.rs @@ -16,16 +16,15 @@ use serde_json::{Value, json}; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::content::Form; -use topcoat::router::error::{SeeOther, forbidden, see_other}; +use topcoat::router::error::{forbidden, see_other}; use topcoat::router::response::response_headers; -use topcoat::router::{HeaderValue, StatusCode, header, page, route}; +use topcoat::router::{HeaderValue, StatusCode, header, page}; use topcoat::view::{View, view}; use crate::audit::{Actor, record}; use crate::auth::{ after_sign_in, check_pre_csrf, check_second_factor, clear_pending_login, clear_pre_csrf, - end_current_session, pending_login, pre_csrf_token, require_csrf, safe_next, set_pending_login, - start_session, + pending_login, pre_csrf_token, safe_next, set_pending_login, start_session, }; use crate::client_ip::client_ip; use crate::i18n::Lang; @@ -232,22 +231,6 @@ async fn two_factor_submit(cx: &Cx, Form(form): Form) -> Result) -> Result { - let viewer = require_csrf(cx, &form.csrf).await?; - end_current_session(cx, &viewer).await?; - record( - cx, - Actor::User(&viewer.user.id), - AuditAction::Logout, - Some(("session", &viewer.session.id)), - Value::Null, - ) - .await; - Ok(see_other("/login")) -} - /// Starts the session, clears the pre-session token, audits the sign-in and sends the person on. async fn finish_sign_in(cx: &Cx, user: &User, method: &str, next: &str) -> Result { let state = app_context::(cx); diff --git a/crates/im-web/src/pages/security.rs b/crates/im-web/src/pages/security.rs index 47f383d..bad3256 100644 --- a/crates/im-web/src/pages/security.rs +++ b/crates/im-web/src/pages/security.rs @@ -9,6 +9,7 @@ use base64::engine::general_purpose::STANDARD as BASE64; use im_core::model::AuditAction; use im_core::password::{check_policy, hash_password_async, verify_password_async}; use im_core::secret; +use im_core::store::backchannel::EndReason; use im_core::totp; use serde::Deserialize; use serde_json::json; @@ -175,7 +176,11 @@ async fn change_password(cx: &Cx, Form(form): Form) -> Result) -> Result(cx); if form.session_id == viewer.session.id { - end_current_session(cx, &viewer).await?; + end_current_session(cx, &viewer, EndReason::Revoked).await?; record( cx, Actor::User(&viewer.user.id), @@ -143,7 +144,7 @@ async fn revoke_session(cx: &Cx, Form(form): Form) -> Result) -> Result let state = app_context::(cx); let ended = state .store - .end_other_sessions(&viewer.user.id, &viewer.session.id) + .end_other_sessions(&viewer.user.id, &viewer.session.id, EndReason::Revoked) .await?; if !ended.is_empty() { state.live.bump(&Topic::Account(viewer.user.id.clone())); diff --git a/crates/im-web/src/security.rs b/crates/im-web/src/security.rs index 1f05632..5a2b4bc 100644 --- a/crates/im-web/src/security.rs +++ b/crates/im-web/src/security.rs @@ -115,8 +115,25 @@ impl Layer for SecurityHeaders { if answer == Answer::Page { headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(NO_STORE)); } - response_headers(cx).extend(headers); - next.run(cx, body).await + match next.run(cx, body).await { + // A header the route set itself wins: a token answer that is already `no-store`, or a + // photo with its own stricter policy, must not get a second copy of the same header. + Ok(mut response) => { + let response_map = response.headers_mut(); + for (name, value) in &headers { + if !response_map.contains_key(name) { + response_map.insert(name.clone(), value.clone()); + } + } + Ok(response) + } + // Errors become responses after the layers have run; the per-request slot gives + // them the headers too. + Err(error) => { + response_headers(cx).extend(headers); + Err(error) + } + } }) } } @@ -137,6 +154,34 @@ mod tests { assert_eq!(answer_for("/photographs"), Answer::Page); } + #[tokio::test] + async fn a_route_header_is_not_repeated_by_the_layer() { + let (_dir, state) = crate::boot::test_state().await; + for (method, path) in [("POST", "/token"), ("GET", "/photo/01HZ")] { + let request = http::Request::builder() + .method(method) + .uri(path) + .body(topcoat::router::Body::empty()) + .expect("request"); + let response = crate::boot::router(state.clone()).handle(request).await; + let headers = response.headers(); + // A missing photo answers without Cache-Control; a repeat is the bug under test. + let cache_control = headers.get_all(header::CACHE_CONTROL).iter().count(); + assert!(cache_control <= 1, "Cache-Control repeated on {path}"); + if path == "/token" { + assert_eq!(cache_control, 1, "Cache-Control on {path}"); + } + let csp = headers + .get_all(header::CONTENT_SECURITY_POLICY) + .iter() + .count(); + assert!(csp <= 1, "CSP repeated on {path}"); + if path == "/token" { + assert_eq!(csp, 1, "CSP on {path}"); + } + } + } + #[test] fn hsts_only_for_https_origins() { assert!(