diff --git a/Cargo.lock b/Cargo.lock index 8cb1260..d230fcc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -235,6 +235,30 @@ 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", + "untrusted 0.7.1", + "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" @@ -545,6 +569,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" @@ -563,6 +596,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" @@ -596,6 +639,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" @@ -849,6 +902,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 = "either" version = "1.19.0" @@ -1007,6 +1066,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" @@ -1028,6 +1093,12 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + [[package]] name = "futures-macro" version = "0.3.34" @@ -1058,9 +1129,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-core", + "futures-io", "futures-macro", "futures-sink", "futures-task", + "memchr", "pin-project-lite", "slab", ] @@ -1368,6 +1441,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]] @@ -1376,12 +1465,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]] @@ -1711,13 +1810,22 @@ dependencies = [ name = "iz-web" version = "0.1.0" dependencies = [ + "aws-lc-rs", + "base64 0.23.1", "futures-util", "grass", "hex", "http", "iz-core", + "jsonwebtoken", + "rand 0.10.3", + "reqwest", + "serde", + "serde_json", "sha2 0.11.1", + "subtle", "tempfile", + "thiserror", "tokio", "topcoat", "tracing", @@ -1768,6 +1876,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" @@ -1789,6 +1946,22 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "jsonwebtoken" +version = "11.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e75fe14a82d81e5f5af639997db37d8b96045938a7ac6ab18cdbe1c7467e05e1" +dependencies = [ + "aws-lc-rs", + "base64 0.22.1", + "getrandom 0.2.17", + "js-sys", + "serde", + "serde_json", + "signature", + "zeroize", +] + [[package]] name = "lasso" version = "0.7.3" @@ -1939,6 +2112,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" @@ -2162,6 +2341,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" @@ -2422,6 +2607,63 @@ dependencies = [ "syn 2.0.119", ] +[[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" @@ -2540,6 +2782,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" @@ -2627,6 +2878,61 @@ 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", + "futures-util", + "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_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "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 0.9.0", + "windows-sys 0.52.0", +] + [[package]] name = "roaring" version = "0.11.5" @@ -2704,6 +3010,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 0.9.0", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -2716,6 +3097,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" @@ -2728,6 +3127,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" @@ -2883,7 +3305,7 @@ dependencies = [ "owo-colors", "rand 0.8.8", "rand_core 0.6.4", - "rand_pcg", + "rand_pcg 0.3.1", "scoped-tls", "smallvec", "tracing", @@ -2899,6 +3321,25 @@ dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "rand_core 0.6.4", +] + +[[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" @@ -3031,6 +3472,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" @@ -3279,6 +3729,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" @@ -3306,6 +3762,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" @@ -3713,6 +4179,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" @@ -3787,6 +4298,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" @@ -4096,6 +4613,30 @@ dependencies = [ "ctutils", ] +[[package]] +name = "untrusted" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" + +[[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" @@ -4145,6 +4686,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" @@ -4173,6 +4733,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" @@ -4205,6 +4776,29 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "wasm-streams" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[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" @@ -4215,6 +4809,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 = "which" version = "4.4.2" @@ -4243,6 +4846,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" @@ -4308,6 +4920,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" @@ -4490,6 +5111,26 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "zerotrie" version = "0.2.5" diff --git a/Cargo.toml b/Cargo.toml index f7d2fe2..7b7ea5e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,7 @@ license = "AGPL-3.0-or-later" [workspace.dependencies] # external crates (versions are the latest releases when added) +aws-lc-rs = "1.18.2" base64 = "0.23.1" futures-util = "0.3.34" grass = "0.13.4" @@ -19,8 +20,10 @@ http = "1.5.0" chacha20poly1305 = "0.11.0" hex = "0.4.3" ipnet = "2.12.2" +jsonwebtoken = { version = "11.1.0", default-features = false, features = ["aws_lc_rs"] } jiff = { version = "0.2.38", default-features = false, features = ["std", "tzdb-bundle-always"] } rand = "0.10.3" +reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "form", "json", "stream"] } serde = "1.0.229" serde_json = "1.0.154" sha2 = "0.11.1" diff --git a/config/iz.example.toml b/config/iz.example.toml index b1bc69d..203f89b 100644 --- a/config/iz.example.toml +++ b/config/iz.example.toml @@ -13,9 +13,11 @@ base_url = "http://127.0.0.1:7654" trusted_proxies = [] # Identity provider (OpenID Connect). Uncomment to enable sign-in. +# The client secret is read from client_secret_file at boot. That file must be mode 0600 or 0400. # [oidc] # issuer = "https://im.example.com" # client_id = "iz" +# client_secret_file = "data/oidc_client_secret" # Attachments in the external Files service instead of local disk. [in_store] diff --git a/crates/iz-core/migrations/0002_session_id_token.sql b/crates/iz-core/migrations/0002_session_id_token.sql new file mode 100644 index 0000000..4820694 --- /dev/null +++ b/crates/iz-core/migrations/0002_session_id_token.sql @@ -0,0 +1,4 @@ +-- 0002: the sealed ID token of each local session. It is the id_token_hint of the RP-initiated logout +-- (docs/contracts.md 2.5). It is sealed with the instance key (secret::seal), so a leaked row does not +-- hold a usable token. NULL for sessions that were created without one. +ALTER TABLE sessions ADD COLUMN id_token_sealed TEXT; diff --git a/crates/iz-core/src/config.rs b/crates/iz-core/src/config.rs index dd48a3c..4aac41b 100644 --- a/crates/iz-core/src/config.rs +++ b/crates/iz-core/src/config.rs @@ -51,6 +51,9 @@ pub struct OidcConfig { pub issuer: String, /// Client id registered with the provider. pub client_id: String, + /// File holding the client secret, read at boot. It must not be readable by group or others, + /// and it is never stored in the database or in this file. + pub client_secret_file: PathBuf, } /// Switch for storing attachments in the external Files service. @@ -173,6 +176,11 @@ impl Config { "oidc.client_id must be 1 to 200 characters".into(), )); } + if oidc.client_secret_file.as_os_str().is_empty() { + return Err(Error::Config( + "oidc.client_secret_file must not be empty".into(), + )); + } } if let Some(backup) = &self.backup { if backup.dir.as_os_str().is_empty() { @@ -201,6 +209,10 @@ impl Config { /// An issuer must be https. Plain http is allowed only for loopback, which is how a local /// identity provider is reached in development. fn validate_issuer(issuer: &str) -> Result<()> { + // The issuer is compared exactly with the `iss` claim, so a trailing slash would never match. + if issuer.ends_with('/') { + return Err(Error::Config("oidc.issuer must not end with /".into())); + } let loopback = issuer.starts_with("http://127.0.0.1") || issuer.starts_with("http://localhost"); if issuer.starts_with("https://") || loopback { Ok(()) @@ -242,7 +254,11 @@ mod tests { assert!(Config::parse("base_url = \"ftp://x\"\n").is_err()); assert!(Config::parse("base_url = \"https://x/\"\n").is_err()); assert!( - Config::parse("[oidc]\nissuer = \"http://im.example.com\"\nclient_id = \"iz\"\n") + Config::parse("[oidc]\nissuer = \"http://im.example.com\"\nclient_id = \"iz\"\nclient_secret_file = \"s\"\n") + .is_err() + ); + assert!( + Config::parse("[oidc]\nissuer = \"https://im.example.com/\"\nclient_id = \"iz\"\nclient_secret_file = \"s\"\n") .is_err() ); assert!(Config::parse("[backup]\ndir = \"/srv/b\"\ninterval_hours = 0\n").is_err()); diff --git a/crates/iz-core/src/store/migrate.rs b/crates/iz-core/src/store/migrate.rs index f048d67..45f74be 100644 --- a/crates/iz-core/src/store/migrate.rs +++ b/crates/iz-core/src/store/migrate.rs @@ -8,7 +8,10 @@ use crate::error::{Error, Result}; use crate::time::now_stamp; /// `(version, sql)` in ascending order. -pub const MIGRATIONS: &[(u32, &str)] = &[(1, include_str!("../../migrations/0001_init.sql"))]; +pub const MIGRATIONS: &[(u32, &str)] = &[ + (1, include_str!("../../migrations/0001_init.sql")), + (2, include_str!("../../migrations/0002_session_id_token.sql")), +]; fn migration_err(e: turso::Error) -> Error { Error::Migration(e.to_string()) diff --git a/crates/iz-core/src/store/mod.rs b/crates/iz-core/src/store/mod.rs index 011449f..25be9b0 100644 --- a/crates/iz-core/src/store/mod.rs +++ b/crates/iz-core/src/store/mod.rs @@ -379,7 +379,7 @@ mod tests { }) .await .unwrap(); - assert_eq!(versions, vec![1]); + assert_eq!(versions, vec![1, 2]); } #[tokio::test] diff --git a/crates/iz-core/src/store/sessions.rs b/crates/iz-core/src/store/sessions.rs index 4b04988..2304511 100644 --- a/crates/iz-core/src/store/sessions.rs +++ b/crates/iz-core/src/store/sessions.rs @@ -24,6 +24,8 @@ pub struct SessionRecord { pub csrf_token: String, /// The im browser session id, used by back-channel logout. pub sid: Option, + /// The sealed ID token that was issued with this session, for the logout `id_token_hint`. + pub id_token_sealed: Option, /// UTC stamp after which the session is refused. pub expires_at: String, /// UTC stamp of the last request that used the session. @@ -41,7 +43,8 @@ pub struct IssuedSession { pub csrf_token: String, } -const SESSION_COLS: &str = "s.id, s.sub, s.csrf_token, s.sid, s.expires_at, s.last_seen"; +const SESSION_COLS: &str = + "s.id, s.sub, s.csrf_token, s.sid, s.expires_at, s.last_seen, s.id_token_sealed"; fn map_session(row: &turso::Row) -> Result { Ok(SessionRecord { @@ -51,16 +54,19 @@ fn map_session(row: &turso::Row) -> Result { sid: col_opt_text(row, 3)?, expires_at: col_text(row, 4)?, last_seen: col_text(row, 5)?, + id_token_sealed: col_opt_text(row, 6)?, }) } impl Store { - /// Creates a session for `sub` that lasts `lifetime`. The member must be enabled and have a role - /// other than `none`; otherwise nothing is written and the result is `Forbidden`. + /// Creates a session for `sub` that lasts `lifetime`. `id_token_sealed` is the sealed ID token of + /// the sign-in, kept for the logout hint. The member must be enabled and have a role other than + /// `none`; otherwise nothing is written and the result is `Forbidden`. pub async fn create_session( &self, sub: &str, sid: Option<&str>, + id_token_sealed: Option<&str>, lifetime: Duration, user_agent: Option<&str>, ip: Option<&str>, @@ -73,8 +79,8 @@ impl Store { let changed = conn .execute( "INSERT INTO sessions (id, sub, token_hash, csrf_token, sid, created_at, expires_at, \ - last_seen, user_agent, ip) \ - SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?6, ?8, ?9 FROM members \ + last_seen, user_agent, ip, id_token_sealed) \ + SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?6, ?8, ?9, ?10 FROM members \ WHERE sub = ?2 AND disabled = 0 AND role <> 'none'", ( id.clone(), @@ -86,6 +92,7 @@ impl Store { stamp_after(lifetime), user_agent.map(str::to_owned), ip.map(str::to_owned), + id_token_sealed.map(str::to_owned), ), ) .await @@ -201,7 +208,14 @@ mod tests { async fn sessions_follow_member_state_and_jti_is_single_use() { let (_dir, store, _board) = seeded().await; let issued = store - .create_session("bo", Some("sid-1"), Duration::from_secs(3600), None, None) + .create_session( + "bo", + Some("sid-1"), + Some("sealed"), + Duration::from_secs(3600), + None, + None, + ) .await .unwrap(); let found = store @@ -211,6 +225,7 @@ mod tests { .unwrap(); assert_eq!(found.sub, "bo"); assert_eq!(found.csrf_token, issued.csrf_token); + assert_eq!(found.id_token_sealed.as_deref(), Some("sealed")); // Back-channel logout by sid removes the session. assert_eq!(store.delete_sessions_by_sid("sid-1").await.unwrap(), 1); assert!( @@ -224,7 +239,7 @@ mod tests { store.mark_deleted("bo").await.unwrap(); assert!(matches!( store - .create_session("bo", None, Duration::from_secs(60), None, None) + .create_session("bo", None, None, Duration::from_secs(60), None, None) .await, Err(Error::Forbidden(_)) )); diff --git a/crates/iz-web/Cargo.toml b/crates/iz-web/Cargo.toml index 0b0a145..54bef2d 100644 --- a/crates/iz-web/Cargo.toml +++ b/crates/iz-web/Cargo.toml @@ -11,16 +11,29 @@ name = "iz" path = "src/main.rs" [dependencies] +base64.workspace = true futures-util.workspace = true +hex.workspace = true http.workspace = true iz-core.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"] } +jsonwebtoken.workspace = true +rand.workspace = true +reqwest.workspace = true +serde = { workspace = true, features = ["derive"] } +serde_json.workspace = true +sha2.workspace = true +subtle.workspace = true +# `net` and `signal` for the listener and the shutdown signals, `time` for the database probe timeout +# and the reconnect backoff, `fs` for the photo cache. +tokio = { workspace = true, features = ["fs", "net", "signal", "time"] } topcoat.workspace = true tracing.workspace = true +thiserror.workspace = true tracing-subscriber = { workspace = true, features = ["env-filter"] } [dev-dependencies] +# Makes Ed25519 keys for the token tests. Never used by the server. +aws-lc-rs.workspace = true tempfile.workspace = true [build-dependencies] diff --git a/crates/iz-web/src/auth.rs b/crates/iz-web/src/auth.rs new file mode 100644 index 0000000..a11a3e2 --- /dev/null +++ b/crates/iz-web/src/auth.rs @@ -0,0 +1,322 @@ +//! Sessions and access checks for the web layer: the cookies, the current member, the role and CSRF +//! checks that every handler calls first, and the `next` guard for redirects. +//! +//! The browser holds the raw session token in `__Host-iz_session`. The store keeps only its SHA-256 +//! (`iz_core::store::sessions`). The sign-in flight (state, nonce, PKCE verifier, `next`) lives in +//! `__Host-iz_flight`, sealed with the instance key, so the browser cannot change it. + +use std::time::Duration; + +use iz_core::authz::{Action, Actor, Denied, authorize}; +use iz_core::secret; +use iz_core::store::members::Member; +use iz_core::store::sessions::SessionRecord; +use iz_core::token::constant_time_eq; +use reqwest::Url; +use serde::{Deserialize, Serialize}; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time}; +use topcoat::router::error::{forbidden, not_found, see_other}; +use topcoat::router::request::{headers, uri}; + +use crate::oidc::unix_now; +use crate::state::AppState; + +/// Logical name of the session cookie. `override_prefix_host()` stores it as `__Host-iz_session`. +pub const SESSION_COOKIE: &str = "iz_session"; +/// Logical name of the sign-in flight cookie. Stored as `__Host-iz_flight`. +pub const STATE_COOKIE: &str = "iz_flight"; +/// Lifetime of a local session, in seconds of absolute age (contracts.md 2.4: at most 12 hours). +pub const SESSION_LIFETIME: Duration = Duration::from_secs(12 * 60 * 60); +/// How long a sign-in may take from the start to the callback (contracts.md 2.3 and this task). +pub const STATE_LIFETIME: Duration = Duration::from_secs(10 * 60); +/// Longest `next` target accepted, in bytes. Reason: a return path is a path, not a document. +const MAX_NEXT_LEN: usize = 2048; +/// Longest user agent stored with a session, in bytes. Reason: the value is only shown to admins. +const MAX_USER_AGENT_LEN: usize = 256; + +/// The level a page or a write needs. Maps to one authorization action. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Need { + /// Reading the board. + Viewer, + /// Creating and changing tasks, comments and files. + Member, + /// Settings, roles, tags, columns and rules. + Admin, +} + +/// A signed-in member and the session that carries them. +pub struct CurrentMember { + /// The session row (its CSRF token, its sid and the sealed ID token). + pub session: SessionRecord, + /// The member row, read in the same request. + pub member: Member, +} + +impl CurrentMember { + /// The actor for [`authorize`], built from the stored member. + pub fn actor(&self) -> Actor { + Actor::Member { + sub: self.member.sub.clone(), + role: self.member.role, + im_admin: self.member.im_admin, + disabled: self.member.disabled, + } + } + + /// Whether `submitted` is this session's CSRF token, compared in constant time. An empty value + /// never matches. + pub fn csrf_matches(&self, submitted: &str) -> bool { + !submitted.is_empty() + && !self.session.csrf_token.is_empty() + && constant_time_eq(self.session.csrf_token.as_bytes(), submitted.as_bytes()) + } +} + +/// The state of one sign-in, sealed into the flight cookie. +#[derive(Debug, Serialize, Deserialize)] +pub struct SignInState { + /// The `state` parameter sent to `im`. Compared with the one that comes back. + pub state: String, + /// The `nonce` sent to `im`. Must equal the nonce of the ID token. + pub nonce: String, + /// The PKCE verifier. Only its challenge went to `im`. + pub verifier: String, + /// The return path, already checked by [`safe_next`] when it was stored. + pub next: String, + /// Unix time after which the flight is refused. + pub expires: u64, +} + +/// The cookie jar with the `__Host-` prefix, so the browser enforces `Secure`, `Path=/` and no domain. +fn jar(cx: &Cx) -> impl Cookies + '_ { + cookies(cx).override_prefix_host() +} + +/// The signed-in member, or `None` when there is no session, the session has expired, or its member +/// is disabled or has no role. The store answers all of these the same way. +pub async fn current_member(cx: &Cx) -> Result> { + let Some(cookie) = jar(cx).get(SESSION_COOKIE) else { + return Ok(None); + }; + let store = &app_context::(cx).store; + let Some(session) = store.session_by_token(cookie.value()).await? else { + return Ok(None); + }; + let Some(member) = store.member(&session.sub).await? else { + return Ok(None); + }; + Ok(Some(CurrentMember { session, member })) +} + +/// The signed-in member. Without a session, redirects to `/login?next=`. +pub async fn require_member(cx: &Cx) -> Result { + match current_member(cx).await? { + Some(me) => Ok(me), + None => { + let path = uri(cx).path_and_query().map_or("/", |p| p.as_str()); + let target = format!("/auth/login?next={}", percent_encode(path)); + Err(see_other(target).into()) + } + } +} + +/// The signed-in member with the level `need`. A shortfall is `404` for admin pages, which must not +/// reveal that they exist, and `403` for a write that a viewer tried. +pub async fn require_role(cx: &Cx, need: Need) -> Result { + let me = require_member(cx).await?; + let action = match need { + Need::Viewer => Action::ReadBoard, + Need::Member => Action::WriteTask, + Need::Admin => Action::Administer, + }; + match authorize(&me.actor(), &action) { + Ok(()) => Ok(me), + Err(Denied::Forbidden) if need == Need::Member => Err(forbidden().into()), + Err(_) => Err(not_found().into()), + } +} + +/// The signed-in member, after the CSRF check. A missing or wrong `csrf` is `403`, and the check runs +/// before any side effect of the handler. +pub async fn require_csrf(cx: &Cx, submitted: &str) -> Result { + let me = require_member(cx).await?; + if me.csrf_matches(submitted) { + Ok(me) + } else { + Err(forbidden().into()) + } +} + +/// Stores a new session cookie. `token` is the value from [`store::sessions::IssuedSession`]. +pub fn set_session_cookie(cx: &Cx, token: String) { + jar(cx).add( + Cookie::build((SESSION_COOKIE, token)) + .path("/") + .secure(true) + .http_only(true) + .same_site(SameSite::Lax) + .max_age(time::Duration::seconds( + i64::try_from(SESSION_LIFETIME.as_secs()).unwrap_or(i64::MAX), + )) + .build(), + ); +} + +/// Removes the session cookie. +pub fn clear_session_cookie(cx: &Cx) { + jar(cx).remove(Cookie::build((SESSION_COOKIE, "")).path("/")); +} + +/// Stores the sealed sign-in flight. `SameSite=Lax` is needed: the callback is a top-level +/// navigation that comes back from `im`. +pub fn set_state_cookie(cx: &Cx, sealed: String) { + jar(cx).add( + Cookie::build((STATE_COOKIE, sealed)) + .path("/") + .secure(true) + .http_only(true) + .same_site(SameSite::Lax) + .max_age(time::Duration::seconds( + i64::try_from(STATE_LIFETIME.as_secs()).unwrap_or(i64::MAX), + )) + .build(), + ); +} + +/// The sealed sign-in flight cookie, if the browser sent one. +pub fn state_cookie(cx: &Cx) -> Option { + jar(cx).get(STATE_COOKIE).map(|c| c.value().to_owned()) +} + +/// Removes the sign-in flight cookie. Called on every callback, whatever the outcome, so a flight +/// can be used only once. +pub fn clear_state_cookie(cx: &Cx) { + jar(cx).remove(Cookie::build((STATE_COOKIE, "")).path("/")); +} + +/// Seals a sign-in flight for the cookie. +pub fn seal_sign_in_state(key: &[u8; 32], state: &SignInState) -> iz_core::Result { + let json = serde_json::to_vec(state) + .map_err(|e| iz_core::Error::Crypto(format!("encoding the sign-in state: {e}")))?; + secret::seal(key, &json) +} + +/// Opens a sealed sign-in flight. `None` when it is malformed, tampered with, or past its expiry. +pub fn open_sign_in_state(key: &[u8; 32], sealed: &str) -> Option { + let plain = secret::open(key, sealed).ok()?; + let state: SignInState = serde_json::from_slice(&plain).ok()?; + (unix_now() < state.expires).then_some(state) +} + +/// The User-Agent of the request, shortened, for the session row. +pub fn user_agent(cx: &Cx) -> Option { + headers(cx) + .get(http::header::USER_AGENT) + .and_then(|value| value.to_str().ok()) + .map(|value| value.chars().take(MAX_USER_AGENT_LEN).collect()) +} + +/// One query parameter of the request, decoded. `None` when it is absent. +pub fn query_param(cx: &Cx, name: &str) -> Option { + let mut url = Url::parse("http://iz.invalid/").ok()?; + url.set_query(uri(cx).query()); + url.query_pairs() + .find(|(key, _)| key == name) + .map(|(_, value)| value.into_owned()) +} + +/// The return path, if it is safe to redirect to; otherwise `/`. A safe path starts with one `/`, +/// is ASCII without control characters, and is at most 2048 bytes. Anything that could name another +/// host (`//`, `/\`, a scheme) is refused. +pub fn safe_next(next: Option<&str>) -> &str { + match next { + Some(path) if is_local_path(path) => path, + _ => "/", + } +} + +fn is_local_path(path: &str) -> bool { + path.len() <= MAX_NEXT_LEN + && path.starts_with('/') + && !path.starts_with("//") + && !path.starts_with("/\\") + && path.bytes().all(|b| b.is_ascii() && !b.is_ascii_control()) +} + +/// Percent-encodes everything except unreserved characters and `/`, for a `next` value in a URL. +fn percent_encode(input: &str) -> String { + let mut out = String::with_capacity(input.len()); + for b in input.bytes() { + match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => { + out.push(char::from(b)); + } + _ => out.push_str(&format!("%{b:02X}")), + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn safe_next_accepts_local_paths() { + assert_eq!(safe_next(Some("/")), "/"); + assert_eq!(safe_next(Some("/tasks/IZ-4?file=2")), "/tasks/IZ-4?file=2"); + } + + /// Every string here is a classic open-redirect or header-injection attempt. None may come back. + #[test] + fn safe_next_refuses_the_attack_strings() { + let attacks = [ + "//evil.example", + "/\\evil.example", + "\\\\evil.example", + "https://evil.example", + "HTTPS://evil.example", + "%2f%2fevil.example", + "%5c%5cevil.example", + "javascript:alert(1)", + "/\r\nSet-Cookie: x=y", + "/ok\nLocation: https://evil.example", + "/\t/evil.example", + " //evil.example", + "evil.example", + "", + ]; + for attack in attacks { + assert_eq!(safe_next(Some(attack)), "/", "accepted {attack:?}"); + } + assert_eq!(safe_next(None), "/"); + let too_long = format!("/{}", "a".repeat(MAX_NEXT_LEN)); + assert_eq!(safe_next(Some(&too_long)), "/"); + } + + #[test] + fn sign_in_state_round_trips_and_expires() { + let key = [9u8; 32]; + let state = SignInState { + state: "s".into(), + nonce: "n".into(), + verifier: "v".into(), + next: "/".into(), + expires: unix_now() + 600, + }; + let sealed = seal_sign_in_state(&key, &state).unwrap(); + let opened = open_sign_in_state(&key, &sealed).unwrap(); + assert_eq!(opened.nonce, "n"); + assert!(open_sign_in_state(&[8u8; 32], &sealed).is_none()); + + let stale = SignInState { + expires: unix_now() - 1, + ..state + }; + let sealed = seal_sign_in_state(&key, &stale).unwrap(); + assert!(open_sign_in_state(&key, &sealed).is_none()); + } +} diff --git a/crates/iz-web/src/boot.rs b/crates/iz-web/src/boot.rs index 9758b88..24b8c1b 100644 --- a/crates/iz-web/src/boot.rs +++ b/crates/iz-web/src/boot.rs @@ -18,7 +18,9 @@ use tokio::sync::watch; use topcoat::cookie::RouterBuilderCookieExt; use topcoat::router::{Router, RouterBuilderDiscoverExt, RouterService}; +use crate::directory; use crate::live::LiveHub; +use crate::oidc; use crate::pages::not_found::NotFoundLayer; use crate::security::{self, SecurityHeaders}; use crate::state::AppState; @@ -42,8 +44,9 @@ pub async fn serve(config_path: &Path) -> iz_core::Result<()> { "iz starting" ); - // One stop flag. The signal task sets it; the server watches it and then drains. + // One stop flag. The signal task sets it; the mirror worker and the server both watch it. let (stop_tx, stop_rx) = watch::channel(false); + directory::spawn(state.clone(), stop_rx.clone()); tokio::spawn(async move { shutdown_signal().await; tracing::info!("shutdown signal received"); @@ -76,11 +79,23 @@ async fn open_state(config: Config) -> iz_core::Result { } let key = secret::load_or_create_key(&data_dir.join(KEY_FILE))?; let store = Store::open(&config.database).await?; + let oidc = match &config.oidc { + Some(oidc_config) => { + let secret = oidc::read_client_secret(&oidc_config.client_secret_file)?; + Some(Arc::new(oidc::OidcClient::new( + oidc_config, + &config.base_url, + secret, + )?)) + } + None => None, + }; Ok(AppState { config: Arc::new(config), store, key: Arc::new(key), live: Arc::new(LiveHub::default()), + oidc, }) } @@ -155,6 +170,7 @@ mod tests { store, key: Arc::new(key), live: Arc::new(LiveHub::default()), + oidc: None, }; (dir, state) } diff --git a/crates/iz-web/src/directory.rs b/crates/iz-web/src/directory.rs new file mode 100644 index 0000000..3fe107b --- /dev/null +++ b/crates/iz-web/src/directory.rs @@ -0,0 +1,473 @@ +//! The members mirror (docs/contracts.md section 3): a full read of `im`'s people directory at boot, +//! then its change stream, applied to the local `members` table. The worker keeps running until the +//! stop flag is set. +//! +//! Pages never call `im` to show a name or an avatar; they read this mirror. A member who is disabled +//! or deleted loses their local sessions here, and the same check also runs at every request in the +//! store, so either path alone is enough (contracts.md 2.5). +//! +//! The stream cursor is kept in `settings`. A `resync` event, or a cursor that `im` no longer knows, +//! starts a full read again. A broken connection is retried with exponential backoff from one second +//! to one minute, with jitter, so a restart of `im` does not bring every client back in the same +//! instant. + +use std::collections::HashSet; +use std::time::Duration; + +use futures_util::StreamExt; +use iz_core::authz::Role; +use iz_core::store::members::DirectoryMember; +use iz_core::store::Store; +use serde_json::Value; +use tokio::sync::watch; + +use crate::oidc::{ImError, ImResult, OidcClient, read_limited}; +use crate::state::AppState; + +/// The setting that holds the stream cursor. +pub const CURSOR_SETTING: &str = "directory_cursor"; +/// The setting that holds the role of a member the directory adds (`member` by default). +pub const DEFAULT_ROLE_SETTING: &str = "default_role"; +/// The shortest wait before a reconnect. Reason: contracts.md 2.2 style backoff, first step. +const BACKOFF_MIN: Duration = Duration::from_secs(1); +/// The longest wait before a reconnect. Reason: a family board can wait a minute for `im`. +const BACKOFF_MAX: Duration = Duration::from_secs(60); +/// Silence after which the stream is considered dead. `im` sends a keep-alive every 30 seconds. +const IDLE_LIMIT: Duration = Duration::from_secs(90); +/// Largest directory listing read at once, in bytes. Reason: a family has a few dozen members, so +/// this is far above a real listing and still bounds memory. +const ROSTER_MAX_BYTES: usize = 8 * 1024 * 1024; +/// Largest stream event accepted, in bytes. Reason: a member record is a few hundred bytes. +const MAX_EVENT_BYTES: usize = 64 * 1024; +/// Largest photo fetched from `im`, in bytes. Reason: avatars are small; this bounds the cache. +pub const PHOTO_MAX_BYTES: usize = 5 * 1024 * 1024; +/// The image types a photo may be served as. Anything else from `im` is not shown. +pub const PHOTO_TYPES: [&str; 4] = ["image/png", "image/jpeg", "image/gif", "image/webp"]; + +/// What can stop the mirror: the directory or the local store. +#[derive(Debug, thiserror::Error)] +pub enum MirrorError { + /// `im` failed to answer. The worker retries. + #[error(transparent)] + Im(#[from] ImError), + /// The local database failed. The worker retries. + #[error(transparent)] + Store(#[from] iz_core::Error), +} + +/// A member record as `im` sends it (contracts.md 3.1). Unknown fields are ignored. +#[derive(serde::Deserialize)] +struct WireMember { + sub: String, + email: String, + name: String, + #[serde(default)] + admin: bool, + #[serde(default)] + disabled: bool, + #[serde(default)] + locale: Option, + #[serde(default = "utc")] + zoneinfo: String, + #[serde(default)] + picture_version: i64, +} + +fn utc() -> String { + "UTC".to_owned() +} + +/// The listing of `im`'s directory (contracts.md 3.2). Members are kept as raw values so that one +/// bad record does not stop the rest. +#[derive(serde::Deserialize)] +struct Roster { + members: Vec, + cursor: String, +} + +/// How one connection of the stream ended. +enum Ended { + /// The stop flag was set. + Stopped, + /// `im` asked for a full read again. + Resync, + /// The stream closed, went idle, or `im` closed it after 50 minutes. Reconnect with the cursor. + Closed, +} + +/// Starts the mirror. Does nothing when OIDC is not configured. +pub fn spawn(state: AppState, stop: watch::Receiver) { + let Some(oidc) = state.oidc.clone() else { + return; + }; + tokio::spawn(run(state, oidc, stop)); +} + +async fn run(state: AppState, oidc: std::sync::Arc, mut stop: watch::Receiver) { + let mut backoff = BACKOFF_MIN; + loop { + match mirror_once(&state, &oidc, &mut stop).await { + Ok(Ended::Stopped) => return, + Ok(Ended::Resync) => { + tracing::info!("directory: the stream asked for a full read"); + backoff = BACKOFF_MIN; + } + Ok(Ended::Closed) => { + tracing::info!("directory: the stream closed; reconnecting"); + backoff = BACKOFF_MIN; + } + Err(error) => { + tracing::warn!(error = %error, retry_in = ?backoff, "directory: the mirror failed"); + } + } + if wait_or_stop(jittered(backoff), &mut stop).await { + return; + } + backoff = (backoff * 2).min(BACKOFF_MAX); + } +} + +/// One full read and then one stream connection. +async fn mirror_once( + state: &AppState, + oidc: &OidcClient, + stop: &mut watch::Receiver, +) -> std::result::Result { + full_read(state, oidc).await?; + stream(state, oidc, stop).await +} + +/// Reads the whole directory and applies it. Members that the listing no longer has were deleted in +/// `im`, so they are marked deleted here too. +async fn full_read(state: &AppState, oidc: &OidcClient) -> std::result::Result<(), MirrorError> { + let token = oidc.service_token().await?; + let url = format!("{}/api/v1/directory", oidc.issuer()); + let response = oidc.http().get(url).bearer_auth(token).send().await.map_err(|e| { + ImError::Unavailable(e.to_string()) + })?; + if !response.status().is_success() { + return Err(ImError::BadResponse(format!( + "the directory answered {}", + response.status().as_u16() + )) + .into()); + } + let roster: Roster = decode_json_limited(response, ROSTER_MAX_BYTES).await?; + let default_role = default_role(&state.store).await?; + let mut listed = HashSet::new(); + for raw in roster.members { + let Some(member) = parse_member(raw) else { + tracing::warn!("directory: skipping a member record that does not parse"); + continue; + }; + listed.insert(member.sub.clone()); + apply(state, &member, default_role).await?; + } + for local in state.store.list_members().await? { + if !listed.contains(&local.sub) && !local.disabled { + tracing::info!(sub = %local.sub, "directory: member is gone from the listing; marking deleted"); + state.store.mark_deleted(&local.sub).await?; + state.store.delete_sessions_by_sub(&local.sub).await?; + } + } + state.store.set_setting(CURSOR_SETTING, &roster.cursor).await?; + Ok(()) +} + +/// Decodes a listing, with the same size limit as the other reads. +async fn decode_json_limited( + response: reqwest::Response, + limit: usize, +) -> ImResult { + let body = read_limited(response, limit).await?; + serde_json::from_slice(&body) + .map_err(|e| ImError::BadResponse(format!("the directory listing: {e}"))) +} + +/// Opens the change stream from the stored cursor and applies events until the stream ends. +async fn stream( + state: &AppState, + oidc: &OidcClient, + stop: &mut watch::Receiver, +) -> std::result::Result { + let token = oidc.service_token().await?; + let url = format!("{}/api/v1/directory/stream", oidc.issuer()); + let mut request = oidc + .stream_http() + .get(url) + .bearer_auth(token) + .header(reqwest::header::ACCEPT, "text/event-stream"); + if let Some(cursor) = state.store.get_setting(CURSOR_SETTING).await? { + request = request.header("Last-Event-ID", cursor); + } + let response = request + .send() + .await + .map_err(|e| ImError::Unavailable(e.to_string()))?; + if !response.status().is_success() { + return Err(ImError::BadResponse(format!( + "the stream answered {}", + response.status().as_u16() + )) + .into()); + } + let mut chunks = response.bytes_stream(); + let mut parser = SseParser::default(); + loop { + let next = tokio::select! { + _ = stop.wait_for(|stopped| *stopped) => return Ok(Ended::Stopped), + next = tokio::time::timeout(IDLE_LIMIT, chunks.next()) => next, + }; + let chunk = match next { + // Silence for longer than the limit: reconnect. + Err(_elapsed) => return Ok(Ended::Closed), + Ok(None) => return Ok(Ended::Closed), + Ok(Some(Err(error))) => return Err(ImError::Unavailable(error.to_string()).into()), + Ok(Some(Ok(bytes))) => bytes, + }; + for event in parser.feed(&chunk).map_err(ImError::BadResponse)? { + match event.name.as_str() { + "member" => match serde_json::from_str::(&event.data).ok().and_then(parse_member) { + Some(member) => { + let default_role = default_role(&state.store).await?; + apply(state, &member, default_role).await?; + } + None => tracing::warn!("directory: skipping a member event that does not parse"), + }, + "deleted" => match serde_json::from_str::(&event.data) + .ok() + .and_then(|v| v.get("sub").and_then(Value::as_str).map(str::to_owned)) + { + Some(sub) => { + remove(state, &sub).await?; + } + None => tracing::warn!("directory: skipping a deleted event without a sub"), + }, + "resync" => return Ok(Ended::Resync), + _ => {} + } + if let Some(id) = &event.id { + state.store.set_setting(CURSOR_SETTING, id).await?; + } + } + } +} + +/// Applies one member record. A disabled member loses their sessions. A record the store refuses +/// (for example a time zone it does not know) is logged and skipped, so one bad record never stops +/// the mirror. +async fn apply( + state: &AppState, + member: &DirectoryMember, + default_role: Role, +) -> std::result::Result<(), MirrorError> { + match state.store.apply_directory_member(member, default_role).await { + Ok(stored) => { + if stored.disabled { + state.store.delete_sessions_by_sub(&stored.sub).await?; + } + Ok(()) + } + Err(iz_core::Error::Invalid(reason)) => { + tracing::warn!(sub = %member.sub, reason, "directory: skipping a member the store refuses"); + Ok(()) + } + Err(error) => Err(error.into()), + } +} + +/// Marks a deleted member and ends their sessions. +async fn remove(state: &AppState, sub: &str) -> std::result::Result<(), MirrorError> { + match state.store.mark_deleted(sub).await { + Ok(()) | Err(iz_core::Error::NotFound) => {} + Err(error) => return Err(error.into()), + } + state.store.delete_sessions_by_sub(sub).await?; + Ok(()) +} + +/// The role for a member the directory adds: the `default_role` setting, else `member`. +pub async fn default_role(store: &Store) -> iz_core::Result { + Ok(store + .get_setting(DEFAULT_ROLE_SETTING) + .await? + .as_deref() + .and_then(Role::parse) + .unwrap_or(Role::Member)) +} + +/// Converts a raw member record into the store's form, or `None` when it does not parse. +fn parse_member(raw: Value) -> Option { + let wire: WireMember = serde_json::from_value(raw).ok()?; + Some(DirectoryMember { + sub: wire.sub, + email: wire.email, + name: wire.name, + im_admin: wire.admin, + disabled: wire.disabled, + locale: wire.locale, + zoneinfo: wire.zoneinfo, + picture_version: wire.picture_version, + }) +} + +/// Waits for `wait`, or returns `true` early when the stop flag is set. +async fn wait_or_stop(wait: Duration, stop: &mut watch::Receiver) -> bool { + tokio::select! { + _ = stop.wait_for(|stopped| *stopped) => true, + () = tokio::time::sleep(wait) => false, + } +} + +/// A wait between half and all of `backoff`. The jitter spreads the reconnects of several clients. +fn jittered(backoff: Duration) -> Duration { + let mut bytes = [0u8; 8]; + rand::fill(&mut bytes); + let fraction = (u64::from_le_bytes(bytes) % 1000) as f64 / 1000.0; + backoff.mul_f64(0.5 + fraction * 0.5) +} + +/// One event of a server-sent event stream. +#[derive(Debug, PartialEq, Eq)] +pub struct SseEvent { + /// The `event:` name, `message` when none was sent. + pub name: String, + /// The `data:` lines joined with newlines. + pub data: String, + /// The `id:` of the event, which is the cursor to resume from. + pub id: Option, +} + +/// Reads a server-sent event stream (the HTML living standard, event stream section) from raw +/// chunks. A line may be split across chunks; a blank line ends an event. +#[derive(Default)] +pub struct SseParser { + pending: Vec, + name: Option, + data: Option, + id: Option, +} + +impl SseParser { + /// Feeds one chunk and returns the events it completes. An over-long line is an error, so a + /// hostile stream cannot grow the buffer without bound. + pub fn feed(&mut self, chunk: &[u8]) -> std::result::Result, String> { + self.pending.extend_from_slice(chunk); + let mut events = Vec::new(); + while let Some(end) = self.pending.iter().position(|&b| b == b'\n') { + let line: Vec = self.pending.drain(..=end).collect(); + let line = String::from_utf8_lossy(&line[..line.len() - 1]).into_owned(); + let line = line.strip_suffix('\r').unwrap_or(&line).to_owned(); + if line.is_empty() { + if let Some(event) = self.dispatch() { + events.push(event); + } + continue; + } + if line.starts_with(':') { + continue; + } + let (field, value) = match line.split_once(':') { + Some((field, value)) => (field, value.strip_prefix(' ').unwrap_or(value)), + None => (line.as_str(), ""), + }; + match field { + "event" => self.name = Some(value.to_owned()), + "id" if !value.contains('\0') => self.id = Some(value.to_owned()), + "data" => { + let data = self.data.get_or_insert_with(String::new); + if !data.is_empty() { + data.push('\n'); + } + data.push_str(value); + if data.len() > MAX_EVENT_BYTES { + return Err("a stream event is too large".into()); + } + } + _ => {} + } + } + if self.pending.len() > MAX_EVENT_BYTES { + return Err("a stream line is too large".into()); + } + Ok(events) + } + + /// Ends the current event. An event with no data is dropped, as the standard says. + fn dispatch(&mut self) -> Option { + let name = self.name.take(); + let id = self.id.clone(); + let data = self.data.take()?; + Some(SseEvent { + name: name.unwrap_or_else(|| "message".to_owned()), + data, + id, + }) + } +} + +/// Fetches a member's photo from `im` with the service token. `None` when `im` has no photo, or the +/// photo has a type iz does not serve. +pub async fn fetch_photo(oidc: &OidcClient, sub: &str) -> ImResult)>> { + let token = oidc.service_token().await?; + let url = format!("{}/api/v1/people/{sub}/photo", oidc.issuer()); + let response = oidc + .http() + .get(url) + .bearer_auth(token) + .send() + .await + .map_err(|e| ImError::Unavailable(e.to_string()))?; + match response.status() { + status if status == reqwest::StatusCode::NOT_FOUND => return Ok(None), + status if !status.is_success() => { + return Err(ImError::BadResponse(format!( + "the photo answered {}", + status.as_u16() + ))); + } + _ => {} + } + let mime = response + .headers() + .get(reqwest::header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .map(|value| value.split(';').next().unwrap_or_default().trim().to_ascii_lowercase()) + .unwrap_or_default(); + if !PHOTO_TYPES.contains(&mime.as_str()) { + return Ok(None); + } + let bytes = read_limited(response, PHOTO_MAX_BYTES).await?; + Ok(Some((mime, bytes))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sse_events_split_across_chunks_and_resume_ids() { + let mut parser = SseParser::default(); + assert!(parser.feed(b": keep-alive\n\nevent: mem").unwrap().is_empty()); + let events = parser + .feed(b"ber\nid: 01CURSOR\ndata: {\"sub\":\"a\"}\ndata: more\r\n\r\n") + .unwrap(); + assert_eq!( + events, + vec![SseEvent { + name: "member".into(), + data: "{\"sub\":\"a\"}\nmore".into(), + id: Some("01CURSOR".into()), + }] + ); + // An event with no data is dropped. + assert!(parser.feed(b"event: resync\n\n").unwrap().is_empty()); + } + + #[test] + fn sse_refuses_an_unbounded_line() { + let mut parser = SseParser::default(); + let long = vec![b'x'; MAX_EVENT_BYTES + 1]; + assert!(parser.feed(&long).is_err()); + } +} diff --git a/crates/iz-web/src/i18n/shell.rs b/crates/iz-web/src/i18n/shell.rs index 6a6f807..c2525e2 100644 --- a/crates/iz-web/src/i18n/shell.rs +++ b/crates/iz-web/src/i18n/shell.rs @@ -12,6 +12,24 @@ pub enum K { BackHome, /// The sentence under the 404 title. NotFoundBody, + /// The sentence on the start page for a signed-in member, before the board exists. + BoardComesNext, + /// The title of the page that says a sign-in did not finish. + SignInFailedTitle, + /// The sentence under that title. + SignInFailedBody, + /// The button that starts a sign-in. + SignIn, + /// The title of the page for a member who has no access to the board. + NoAccessTitle, + /// The sentence under that title. + NoAccessBody, + /// The button in the user menu that ends the session. + SignOut, + /// The title of the page that says sign-in is not possible right now. + SignInUnavailableTitle, + /// The sentence under that title. + SignInUnavailableBody, /// The title of the 404 page. NotFoundTitle, /// The sentence on the signed-out start page. @@ -32,15 +50,43 @@ pub fn t(lang: Lang, key: K) -> &'static str { (K::Admin, Lang::En) => "Admin", (K::Admin, Lang::Tr) => "Yönetici", (K::BackHome, Lang::En) => "Back to the start", + (K::BoardComesNext, Lang::En) => "The board comes next. There is nothing to show yet.", + (K::BoardComesNext, Lang::Tr) => "Pano sırada. Henüz gösterilecek bir şey yok.", + (K::SignIn, Lang::En) => "Sign in", + (K::SignIn, Lang::Tr) => "Oturum aç", + (K::SignOut, Lang::En) => "Sign out", + (K::SignOut, Lang::Tr) => "Çıkış yap", + (K::SignInFailedTitle, Lang::En) => "Sign-in did not finish", + (K::SignInFailedTitle, Lang::Tr) => "Oturum açma tamamlanamadı", + (K::SignInFailedBody, Lang::En) => { + "Start again from the sign-in button. If it keeps failing, ask an administrator." + } + (K::SignInFailedBody, Lang::Tr) => { + "Oturum aç düğmesinden yeniden başlayın. Sürerse bir yöneticiye sorun." + } + (K::SignInUnavailableTitle, Lang::En) => "Sign-in is unavailable", + (K::SignInUnavailableTitle, Lang::Tr) => "Oturum açma şu an kullanılamıyor", + (K::SignInUnavailableBody, Lang::En) => { + "The account service cannot be reached right now. Try again in a few minutes." + } + (K::SignInUnavailableBody, Lang::Tr) => { + "Hesap servisine şu anda ulaşılamıyor. Birkaç dakika sonra tekrar deneyin." + } + (K::NoAccessTitle, Lang::En) => "No access to this board", + (K::NoAccessTitle, Lang::Tr) => "Bu panoya erişiminiz yok", + (K::NoAccessBody, Lang::En) => { + "Your account is known, but no administrator has given it access. Ask one to add you." + } + (K::NoAccessBody, Lang::Tr) => { + "Hesabınız tanınıyor, ama bir yönetici erişim vermemiş. Eklenmeniz için bir yöneticiye sorun." + } (K::BackHome, Lang::Tr) => "Başlangıca dön", (K::NotFoundBody, Lang::En) => "The page does not exist, or you do not have access to it.", (K::NotFoundBody, Lang::Tr) => "Sayfa yok ya da bu sayfayı görme izniniz yok.", (K::NotFoundTitle, Lang::En) => "Page not found", (K::NotFoundTitle, Lang::Tr) => "Sayfa bulunamadı", - (K::SignedOutBody, Lang::En) => { - "You are signed out. Sign-in is not part of this build yet." - } - (K::SignedOutBody, Lang::Tr) => "Oturumunuz kapalı. Oturum açma bu sürümde henüz yok.", + (K::SignedOutBody, Lang::En) => "Sign in with your family account to use the board.", + (K::SignedOutBody, Lang::Tr) => "Pano için aile hesabınızla oturum açın.", (K::SignedOutTitle, Lang::En) => "iz", (K::SignedOutTitle, Lang::Tr) => "iz", (K::ServerRestarting, Lang::En) => "The server is restarting. Reconnecting…", @@ -51,3 +97,11 @@ pub fn t(lang: Lang, key: K) -> &'static str { (K::SkipToContent, Lang::Tr) => "İçeriğe geç", } } + +/// The greeting of a signed-in member, with their name. +pub fn greeting(lang: Lang, name: &str) -> String { + match lang { + Lang::En => format!("Hello, {name}"), + Lang::Tr => format!("Merhaba, {name}"), + } +} diff --git a/crates/iz-web/src/main.rs b/crates/iz-web/src/main.rs index d533966..d2318f8 100644 --- a/crates/iz-web/src/main.rs +++ b/crates/iz-web/src/main.rs @@ -5,10 +5,15 @@ //! then `IZ_CONFIG`, then `config/iz.toml`. Exit status 0 is success, 1 a failure, 2 a usage error. mod assets; +// The board pages that come next call these helpers; until then they have no caller. +#[allow(dead_code)] +mod auth; mod boot; +mod directory; mod health; mod i18n; mod live; +mod oidc; mod pages; mod security; mod state; diff --git a/crates/iz-web/src/oidc.rs b/crates/iz-web/src/oidc.rs new file mode 100644 index 0000000..8941ec9 --- /dev/null +++ b/crates/iz-web/src/oidc.rs @@ -0,0 +1,832 @@ +//! The OpenID Connect relying party for `im` (docs/contracts.md section 2), and the client +//! credentials token that iz uses to read the people directory (section 2.6). +//! +//! It finds `im`'s endpoints through discovery and keeps them for an hour. It keeps `im`'s signing +//! keys (JWKS) for an hour, and refetches them at most once a minute when a token names a key that +//! is not known. It exchanges authorization codes, and it verifies ID tokens and logout tokens. +//! +//! It decides nothing about who may sign in: that is `pages/sign_in.rs` and the store. It keeps no +//! session state: that is `iz_core::store::sessions`. +//! +//! Verification accepts EdDSA only. The algorithm is checked before a key is looked up, so `none` +//! and every other algorithm are refused. The checks are: the signature, `iss` equal to the +//! configured issuer, `aud` equal to the client id, `exp` with 60 seconds of leeway, `iat` not more +//! than five minutes ahead, and the claims each token kind needs. The pure functions below take the +//! key set and the clock as arguments, so the tests can run without a network. + +use std::collections::HashMap; +use std::path::Path; +use std::sync::Arc; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; +use futures_util::StreamExt; +use iz_core::config::OidcConfig; +use iz_core::token::constant_time_eq; +use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header}; +use serde::Deserialize; +use serde_json::{Map, Value}; +use sha2::{Digest, Sha256}; +use tokio::sync::Mutex; + +/// The scope that reads the people directory and its photos at `im`. +pub const DIRECTORY_SCOPE: &str = "directory.read"; +/// The audience of every directory call: the family key of `im`. +pub const IM_AUDIENCE: &str = "im"; +/// The scopes asked for at sign-in. `openid` is required; `profile` and `email` carry the claims iz uses. +pub const SIGN_IN_SCOPE: &str = "openid profile email"; +/// The event name a back-channel logout token must carry (OIDC Back-Channel Logout 1.0). +pub const BACKCHANNEL_EVENT: &str = "http://schemas.openid.net/event/backchannel-logout"; + +/// Longest wait for one call to `im`, in seconds. Reason: a slow identity provider must not hold a +/// request, and the directory worker retries with backoff anyway. +pub const IM_TIMEOUT: Duration = Duration::from_secs(10); +/// Clock skew tolerated on `exp`, in seconds. Reason: the task policy for every token check. +pub const LEEWAY_SECS: u64 = 60; +/// How far ahead of the local clock an `iat` may be, in seconds. Reason: contracts.md 2.3, five minutes. +pub const MAX_IAT_AHEAD_SECS: u64 = 300; +/// Largest discovery, JWKS or token response read from `im`, in bytes. Reason: those documents are +/// a few kilobytes; a larger answer is not what `im` sends. +pub const MAX_RESPONSE_BYTES: usize = 256 * 1024; +/// How long discovery is cached, before it is fetched again. +const DISCOVERY_TTL: Duration = Duration::from_secs(3600); +/// How long the JWKS is cached, before it is fetched again (contracts.md 2.2). +const KEYS_TTL: Duration = Duration::from_secs(3600); +/// The shortest gap between two JWKS fetches caused by unknown key ids (contracts.md 2.2). +const UNKNOWN_KEY_REFETCH: Duration = Duration::from_secs(60); +/// A service token is replaced this long before it expires (contracts.md 2.6). +const SERVICE_TOKEN_MARGIN: Duration = Duration::from_secs(60); + +/// Every failure of a call to `im` or of a token check. +#[derive(Debug, thiserror::Error)] +pub enum ImError { + /// The token is signed with a key id that is not in the key set. The caller may refetch the + /// keys once and check again. + #[error("the token names a key that is not published")] + UnknownKey, + /// The token failed a check. The text names the check; it is for logs only. + #[error("the token was rejected: {0}")] + Rejected(String), + /// `im` could not be reached, or it did not answer in time. + #[error("the account service cannot be reached: {0}")] + Unavailable(String), + /// `im` answered, but not in a form iz accepts. + #[error("the account service answered in an unexpected way: {0}")] + BadResponse(String), +} + +/// The result of a call to `im` or of a token check. +pub type ImResult = std::result::Result; + +/// The part of the discovery document that iz uses (contracts.md 2.1). +#[derive(Debug, Deserialize)] +pub struct Discovery { + /// Must equal the configured issuer exactly. + pub issuer: String, + /// Where the browser is sent to sign in. + pub authorization_endpoint: String, + /// Where codes and client credentials are exchanged for tokens. + pub token_endpoint: String, + /// Where the signing keys are published. + pub jwks_uri: String, + /// Where the browser is sent to end its `im` session. + #[serde(default)] + pub end_session_endpoint: Option, +} + +/// The answer of the token endpoint. The refresh token is not read: iz discards it (contracts.md 2.4). +#[derive(Debug, Deserialize)] +pub struct TokenResponse { + /// The ID token, for an authorization-code exchange. + #[serde(default)] + pub id_token: Option, + /// The access token, for a client-credentials grant. + #[serde(default)] + pub access_token: Option, + /// The lifetime of the access token, in seconds. + #[serde(default)] + pub expires_in: Option, +} + +/// The claims of an ID token that iz uses. `sid` is the `im` browser session. +#[derive(Debug, Clone, Deserialize, PartialEq, Eq)] +pub struct IdClaims { + /// The user's id (a ULID, stable forever). + pub sub: String, + /// The `im` browser session id, kept with the local session for back-channel logout. + #[serde(default)] + pub sid: Option, + /// The address. `im` only stores confirmed addresses. + #[serde(default)] + pub email: Option, + /// The display name. + #[serde(default)] + pub name: Option, + /// Whether `im` marks the user as an instance administrator. + #[serde(default)] + pub admin: bool, + /// The language the user chose in `im`, `en` or `tr`. + #[serde(default)] + pub locale: Option, + /// The user's IANA time zone, for example `Europe/Istanbul`. + #[serde(default)] + pub zoneinfo: Option, + /// Bumps when the photo changes. Used as the avatar cache key. + #[serde(default)] + pub picture_version: i64, +} + +/// The claims of a back-channel logout token that iz uses. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LogoutClaims { + /// The token id, refused when it is seen again. + pub jti: String, + /// The `im` browser session that ended, when the token names one. + pub sid: Option, + /// The user whose sessions end, when the token names one. + pub sub: Option, +} + +#[derive(Deserialize)] +struct JwksDocument { + keys: Vec, +} + +#[derive(Deserialize)] +struct Jwk { + kty: String, + #[serde(default)] + crv: Option, + #[serde(default)] + x: Option, + #[serde(default)] + kid: Option, + #[serde(default)] + alg: Option, +} + +/// The verification keys of `im`, by key id. Only Ed25519 keys are kept; others are skipped. +#[derive(Default)] +pub struct KeySet { + keys: HashMap, +} + +impl KeySet { + /// Reads a JWKS document. Keys that are not Ed25519 or have no `kid` are skipped, not fatal. + pub fn from_jwks(bytes: &[u8]) -> ImResult { + let document: JwksDocument = serde_json::from_slice(bytes) + .map_err(|e| ImError::BadResponse(format!("the key set is not JSON: {e}")))?; + let mut keys = HashMap::new(); + for jwk in document.keys { + let (Some(kid), Some(x)) = (jwk.kid.as_deref(), jwk.x.as_deref()) else { + continue; + }; + let is_ed25519 = jwk.kty == "OKP" && jwk.crv.as_deref() == Some("Ed25519"); + if !is_ed25519 || jwk.alg.as_deref().is_some_and(|alg| alg != "EdDSA") { + continue; + } + match DecodingKey::from_ed_components(x) { + Ok(key) => { + keys.insert(kid.to_owned(), key); + } + Err(e) => tracing::warn!(kid, error = %e, "skipping an unreadable signing key"), + } + } + Ok(KeySet { keys }) + } + + fn get(&self, kid: &str) -> Option<&DecodingKey> { + self.keys.get(kid) + } +} + +/// The client of `im`: discovery, keys, token calls and token checks. One per process. +pub struct OidcClient { + issuer: String, + client_id: String, + client_secret: String, + redirect_uri: String, + post_logout_uri: String, + /// Short calls: discovery, keys, tokens, photos. The timeout applies to the whole call. + http: reqwest::Client, + /// Long-lived event stream. Only the connect is bounded here; the reader has its own idle limit. + stream_http: reqwest::Client, + discovery: Mutex)>>, + keys: Mutex, + service: Mutex>, +} + +#[derive(Default)] +struct KeyCache { + current: Option<(Instant, Arc)>, + last_fetch: Option, +} + +impl OidcClient { + /// Builds the client. `base_url` is the public origin of iz, from which the callback and the + /// post-logout URIs are derived; `im` has these registered for the client. + pub fn new(config: &OidcConfig, base_url: &str, client_secret: String) -> iz_core::Result { + // Redirects are never followed: a token call that is redirected would send the client + // secret to another host. + let http = reqwest::Client::builder() + .timeout(IM_TIMEOUT) + .connect_timeout(IM_TIMEOUT) + .redirect(reqwest::redirect::Policy::none()) + .user_agent(concat!("iz/", env!("CARGO_PKG_VERSION"))) + .build() + .map_err(|e| iz_core::Error::Config(format!("cannot build the HTTP client: {e}")))?; + let stream_http = reqwest::Client::builder() + .connect_timeout(IM_TIMEOUT) + .redirect(reqwest::redirect::Policy::none()) + .user_agent(concat!("iz/", env!("CARGO_PKG_VERSION"))) + .build() + .map_err(|e| iz_core::Error::Config(format!("cannot build the HTTP client: {e}")))?; + Ok(OidcClient { + issuer: config.issuer.clone(), + client_id: config.client_id.clone(), + client_secret, + redirect_uri: format!("{base_url}/auth/callback"), + post_logout_uri: format!("{base_url}/"), + http, + stream_http, + discovery: Mutex::new(None), + keys: Mutex::new(KeyCache::default()), + service: Mutex::new(None), + }) + } + + /// The configured issuer, exactly as it is compared with `iss`. + pub fn issuer(&self) -> &str { + &self.issuer + } + + /// The short-call HTTP client. + pub fn http(&self) -> &reqwest::Client { + &self.http + } + + /// The event-stream HTTP client. + pub fn stream_http(&self) -> &reqwest::Client { + &self.stream_http + } + + /// The discovery document, fetched once and kept for an hour. + pub async fn discovery(&self) -> ImResult> { + let mut slot = self.discovery.lock().await; + if let Some((at, doc)) = slot.as_ref() + && at.elapsed() < DISCOVERY_TTL + { + return Ok(doc.clone()); + } + let url = format!("{}/.well-known/openid-configuration", self.issuer); + let response = self.http.get(url).send().await.map_err(unavailable)?; + if !response.status().is_success() { + return Err(ImError::Unavailable(format!( + "discovery answered {}", + response.status().as_u16() + ))); + } + let body = read_limited(response, MAX_RESPONSE_BYTES).await?; + let doc: Discovery = serde_json::from_slice(&body) + .map_err(|e| ImError::BadResponse(format!("discovery: {e}")))?; + if doc.issuer != self.issuer { + return Err(ImError::BadResponse( + "discovery names another issuer".into(), + )); + } + let doc = Arc::new(doc); + *slot = Some((Instant::now(), doc.clone())); + Ok(doc) + } + + /// The key set, from the cache when it is fresh. With `refetch_unknown` set, it is fetched again + /// unless the last fetch was less than a minute ago. + async fn key_set(&self, refetch_unknown: bool) -> ImResult> { + let mut cache = self.keys.lock().await; + if let Some((at, keys)) = cache.current.as_ref() { + if at.elapsed() < KEYS_TTL && !refetch_unknown { + return Ok(keys.clone()); + } + let recently_fetched = cache + .last_fetch + .is_some_and(|at| at.elapsed() < UNKNOWN_KEY_REFETCH); + if refetch_unknown && recently_fetched { + return Ok(keys.clone()); + } + } + let discovery = self.discovery().await?; + let response = self + .http + .get(&discovery.jwks_uri) + .send() + .await + .map_err(unavailable)?; + if !response.status().is_success() { + return Err(ImError::Unavailable(format!( + "the key set answered {}", + response.status().as_u16() + ))); + } + let body = read_limited(response, MAX_RESPONSE_BYTES).await?; + let keys = Arc::new(KeySet::from_jwks(&body)?); + let now = Instant::now(); + cache.last_fetch = Some(now); + cache.current = Some((now, keys.clone())); + Ok(keys) + } + + /// Runs a check against the cached keys. A token that names an unknown key gets one more try + /// against a fresh key set, which the rate bound may refuse. + async fn with_keys(&self, check: impl Fn(&KeySet) -> ImResult) -> ImResult { + let keys = self.key_set(false).await?; + match check(&keys) { + Err(ImError::UnknownKey) => { + let keys = self.key_set(true).await?; + match check(&keys) { + Err(ImError::UnknownKey) => Err(ImError::Rejected( + "the signing key is not published".into(), + )), + other => other, + } + } + other => other, + } + } + + /// The authorization URL for a sign-in, with PKCE (S256) and the state and nonce of this flight. + pub async fn authorize_url(&self, state: &str, nonce: &str, challenge: &str) -> ImResult { + let discovery = self.discovery().await?; + let mut url = reqwest::Url::parse(&discovery.authorization_endpoint) + .map_err(|e| ImError::BadResponse(format!("authorization endpoint: {e}")))?; + url.query_pairs_mut() + .append_pair("response_type", "code") + .append_pair("client_id", &self.client_id) + .append_pair("redirect_uri", &self.redirect_uri) + .append_pair("scope", SIGN_IN_SCOPE) + .append_pair("state", state) + .append_pair("nonce", nonce) + .append_pair("code_challenge", challenge) + .append_pair("code_challenge_method", "S256"); + Ok(url.into()) + } + + /// The end-session URL of RP-initiated logout (contracts.md 2.5). `id_token_hint` is omitted when + /// the session has no stored ID token. + pub async fn end_session_url(&self, id_token_hint: Option<&str>, state: &str) -> ImResult { + let discovery = self.discovery().await?; + let endpoint = discovery + .end_session_endpoint + .as_deref() + .ok_or_else(|| ImError::BadResponse("no end_session_endpoint".into()))?; + let mut url = reqwest::Url::parse(endpoint) + .map_err(|e| ImError::BadResponse(format!("end_session endpoint: {e}")))?; + { + let mut query = url.query_pairs_mut(); + if let Some(hint) = id_token_hint { + query.append_pair("id_token_hint", hint); + } + query + .append_pair("post_logout_redirect_uri", &self.post_logout_uri) + .append_pair("state", state); + } + Ok(url.into()) + } + + /// Exchanges an authorization code for tokens (contracts.md 2.3, step 3). + pub async fn exchange_code(&self, code: &str, verifier: &str) -> ImResult { + let discovery = self.discovery().await?; + let form = [ + ("grant_type", "authorization_code"), + ("code", code), + ("redirect_uri", self.redirect_uri.as_str()), + ("code_verifier", verifier), + ]; + self.post_token(&discovery.token_endpoint, &form).await + } + + /// A client-credentials token for `scope` and `audience`, cached until 60 seconds before it + /// expires (contracts.md 2.6). + pub async fn service_token(&self) -> ImResult { + let mut slot = self.service.lock().await; + if let Some((until, token)) = slot.as_ref() + && Instant::now() < *until + { + return Ok(token.clone()); + } + let discovery = self.discovery().await?; + let form = [ + ("grant_type", "client_credentials"), + ("scope", DIRECTORY_SCOPE), + ("audience", IM_AUDIENCE), + ]; + let response = self.post_token(&discovery.token_endpoint, &form).await?; + let token = response + .access_token + .filter(|token| !token.is_empty()) + .ok_or_else(|| ImError::BadResponse("the token answer has no access token".into()))?; + let lifetime = Duration::from_secs(response.expires_in.unwrap_or(0)); + let until = Instant::now() + lifetime.saturating_sub(SERVICE_TOKEN_MARGIN); + *slot = Some((until, token.clone())); + Ok(token) + } + + /// Posts a form to the token endpoint with `client_secret_basic` and no redirect following. + async fn post_token(&self, url: &str, form: &[(&str, &str)]) -> ImResult { + let response = self + .http + .post(url) + .basic_auth(&self.client_id, Some(&self.client_secret)) + .form(form) + .send() + .await + .map_err(unavailable)?; + let status = response.status(); + let body = read_limited(response, MAX_RESPONSE_BYTES).await?; + if !status.is_success() { + // The body of an error answer is not logged: it can echo request values. + return Err(ImError::Rejected(format!( + "the token endpoint answered {}", + status.as_u16() + ))); + } + serde_json::from_slice(&body) + .map_err(|e| ImError::BadResponse(format!("the token answer: {e}"))) + } + + /// Verifies an ID token against the current keys, and the nonce of the flight. + pub async fn verify_id_token(&self, token: &str, nonce: &str) -> ImResult { + let now = unix_now(); + self.with_keys(|keys| verify_id_token(keys, &self.issuer, &self.client_id, token, nonce, now)) + .await + } + + /// Verifies a back-channel logout token against the current keys. + pub async fn verify_logout_token(&self, token: &str) -> ImResult { + let now = unix_now(); + self.with_keys(|keys| verify_logout_token(keys, &self.issuer, &self.client_id, token, now)) + .await + } +} + +/// The PKCE code challenge of a verifier: base64url of the SHA-256 of the verifier (RFC 7636, S256). +pub fn pkce_challenge(verifier: &str) -> String { + BASE64_URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())) +} + +/// The current time as seconds since the Unix epoch. Zero if the clock is before it. +pub fn unix_now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_secs()) +} + +/// Verifies an ID token (contracts.md 2.3, step 4). `nonce` must equal the nonce of this flight. +pub fn verify_id_token( + keys: &KeySet, + issuer: &str, + client_id: &str, + token: &str, + nonce: &str, + now: u64, +) -> ImResult { + let claims = verify_signature(keys, issuer, client_id, token)?; + check_iat(&claims, now)?; + let sent = str_claim(&claims, "nonce") + .ok_or_else(|| ImError::Rejected("the nonce claim is missing".into()))?; + if !constant_time_eq(sent.as_bytes(), nonce.as_bytes()) { + return Err(ImError::Rejected("the nonce does not match this sign-in".into())); + } + let id: IdClaims = serde_json::from_value(Value::Object(claims)) + .map_err(|e| ImError::Rejected(format!("the claims are malformed: {e}")))?; + if id.sub.is_empty() || id.sub.len() > 64 { + return Err(ImError::Rejected("the subject is not a member id".into())); + } + Ok(id) +} + +/// Verifies a back-channel logout token (OIDC Back-Channel Logout 1.0, contracts.md 2.5). It must +/// carry the back-channel event, must not carry a nonce, must carry a `jti`, and must name a `sid` or +/// a `sub`. +pub fn verify_logout_token( + keys: &KeySet, + issuer: &str, + client_id: &str, + token: &str, + now: u64, +) -> ImResult { + let claims = verify_signature(keys, issuer, client_id, token)?; + check_iat(&claims, now)?; + if claims.contains_key("nonce") { + return Err(ImError::Rejected("a logout token must not carry a nonce".into())); + } + let events = claims + .get("events") + .and_then(Value::as_object) + .ok_or_else(|| ImError::Rejected("the events claim is missing".into()))?; + if !events.contains_key(BACKCHANNEL_EVENT) { + return Err(ImError::Rejected("the event is not back-channel logout".into())); + } + let jti = str_claim(&claims, "jti") + .ok_or_else(|| ImError::Rejected("the jti claim is missing".into()))?; + let sid = str_claim(&claims, "sid"); + let sub = str_claim(&claims, "sub"); + if sid.is_none() && sub.is_none() { + return Err(ImError::Rejected("the token names neither sid nor sub".into())); + } + Ok(LogoutClaims { jti, sid, sub }) +} + +/// Checks the header, finds the key, and verifies the signature and the registered claims. Returns +/// the claims as a map, for the token-specific checks. +fn verify_signature( + keys: &KeySet, + issuer: &str, + client_id: &str, + token: &str, +) -> ImResult> { + // The algorithm is read from the header and refused unless it is EdDSA, before any key is used. + let header = decode_header(token) + .map_err(|e| ImError::Rejected(format!("the header is malformed: {e}")))?; + if header.alg != Algorithm::EdDSA { + return Err(ImError::Rejected(format!( + "the algorithm {:?} is not accepted", + header.alg + ))); + } + let kid = header + .kid + .as_deref() + .ok_or_else(|| ImError::Rejected("the header has no kid".into()))?; + let key = keys.get(kid).ok_or(ImError::UnknownKey)?; + let mut validation = Validation::new(Algorithm::EdDSA); + validation.leeway = LEEWAY_SECS; + validation.set_issuer(&[issuer]); + validation.set_audience(&[client_id]); + validation.set_required_spec_claims(&["exp", "iss", "aud"]); + let data = decode::>(token, key, &validation) + .map_err(|e| ImError::Rejected(e.to_string()))?; + Ok(data.claims) +} + +/// `iat` must be present and not more than [`MAX_IAT_AHEAD_SECS`] ahead of `now`. +fn check_iat(claims: &Map, now: u64) -> ImResult<()> { + let iat = claims + .get("iat") + .and_then(Value::as_u64) + .ok_or_else(|| ImError::Rejected("the iat claim is missing".into()))?; + if iat > now.saturating_add(MAX_IAT_AHEAD_SECS) { + return Err(ImError::Rejected("the iat claim is in the future".into())); + } + Ok(()) +} + +/// A string claim that is present and not empty. +fn str_claim(claims: &Map, name: &str) -> Option { + claims + .get(name) + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + .map(str::to_owned) +} + +fn unavailable(error: reqwest::Error) -> ImError { + ImError::Unavailable(error.to_string()) +} + +/// Reads a response body, refusing one larger than `limit` bytes. The check runs while the body is +/// read, so a server that lies about its length cannot make iz hold more than `limit`. +pub async fn read_limited(response: reqwest::Response, limit: usize) -> ImResult> { + let too_large = || ImError::BadResponse("the answer is too large".into()); + if response + .content_length() + .is_some_and(|len| len > u64::try_from(limit).unwrap_or(u64::MAX)) + { + return Err(too_large()); + } + let mut body = Vec::new(); + let mut chunks = response.bytes_stream(); + while let Some(chunk) = chunks.next().await { + let chunk = chunk.map_err(unavailable)?; + if body.len() + chunk.len() > limit { + return Err(too_large()); + } + body.extend_from_slice(&chunk); + } + Ok(body) +} + +/// Reads the client secret from `path`. The file must not be readable by group or others, the same +/// rule as the instance key. The value is trimmed and must not be empty. +pub fn read_client_secret(path: &Path) -> iz_core::Result { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(path)?.permissions().mode(); + if mode & 0o077 != 0 { + return Err(iz_core::Error::Config(format!( + "client secret {} is group or world accessible (mode {:o}); expected 0600", + path.display(), + mode & 0o777 + ))); + } + } + let text = std::fs::read_to_string(path)?; + let secret = text.trim().to_owned(); + if secret.is_empty() { + return Err(iz_core::Error::Config(format!( + "client secret {} is empty", + path.display() + ))); + } + Ok(secret) +} + +#[cfg(test)] +pub(crate) mod test_support { + //! Ed25519 keys and signed tokens for the tests. The keys are generated for each test, so no key + //! material lives in the repository. + + use aws_lc_rs::rand::SystemRandom; + use aws_lc_rs::signature::{Ed25519KeyPair, KeyPair}; + use jsonwebtoken::{EncodingKey, Header, encode}; + use serde_json::{Value, json}; + + use super::KeySet; + + /// The issuer used by the tests. + pub const ISSUER: &str = "https://im.example.com"; + /// The client id used by the tests. + pub const CLIENT_ID: &str = "iz"; + + /// A signing key with the key set that verifies it, under the key id `k1`. + pub struct Signer { + pub keys: KeySet, + encoding: EncodingKey, + } + + impl Signer { + pub fn generate() -> Signer { + let pkcs8 = Ed25519KeyPair::generate_pkcs8(&SystemRandom::new()).expect("keygen"); + let pair = Ed25519KeyPair::from_pkcs8(pkcs8.as_ref()).expect("pkcs8"); + let x = base64::Engine::encode( + &base64::prelude::BASE64_URL_SAFE_NO_PAD, + pair.public_key().as_ref(), + ); + let jwks = json!({"keys": [{"kty": "OKP", "crv": "Ed25519", "x": x, "kid": "k1", "use": "sig", "alg": "EdDSA"}]}); + Signer { + keys: KeySet::from_jwks(jwks.to_string().as_bytes()).expect("jwks"), + encoding: EncodingKey::from_ed_der(pkcs8.as_ref()), + } + } + + /// Signs `claims` as an EdDSA token with kid `k1`. + pub fn sign(&self, claims: &Value) -> String { + self.sign_with_kid("k1", claims) + } + + /// Signs `claims` as an EdDSA token with the given kid. + pub fn sign_with_kid(&self, kid: &str, claims: &Value) -> String { + let mut header = Header::new(jsonwebtoken::Algorithm::EdDSA); + header.kid = Some(kid.into()); + encode(&header, claims, &self.encoding).expect("sign") + } + } + + /// Claims of an ID token that passes every check at time `now`, with `nonce`. + pub fn id_claims(now: u64, nonce: &str) -> Value { + json!({ + "iss": ISSUER, "aud": CLIENT_ID, "sub": "01JMEMBER0000000000000000A", + "exp": now + 600, "iat": now, "auth_time": now, "nonce": nonce, + "sid": "sid-1", "email": "ada@example.com", "email_verified": true, + "name": "Ada", "admin": false, "locale": "en", "zoneinfo": "Europe/Istanbul", + "picture_version": 1 + }) + } + + /// Claims of a back-channel logout token that passes every check at time `now`. + pub fn logout_claims(now: u64, jti: &str) -> Value { + json!({ + "iss": ISSUER, "aud": CLIENT_ID, "iat": now, "exp": now + 120, "jti": jti, + "sid": "sid-1", "sub": "01JMEMBER0000000000000000A", + "events": {"http://schemas.openid.net/event/backchannel-logout": {}} + }) + } +} + +#[cfg(test)] +mod tests { + use super::test_support::{CLIENT_ID, ISSUER, Signer, id_claims, logout_claims}; + use super::*; + use serde_json::json; + + const NOW: u64 = 1_800_000_000; + + fn unsigned(header: &str, payload: &Value) -> String { + let h = BASE64_URL_SAFE_NO_PAD.encode(header); + let p = BASE64_URL_SAFE_NO_PAD.encode(payload.to_string()); + format!("{h}.{p}.") + } + + #[test] + fn pkce_challenge_matches_the_rfc_7636_example() { + assert_eq!( + pkce_challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"), + "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" + ); + } + + #[test] + fn a_well_formed_id_token_is_accepted() { + let signer = Signer::generate(); + let token = signer.sign(&id_claims(NOW, "n-1")); + let id = verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-1", NOW).unwrap(); + assert_eq!(id.sub, "01JMEMBER0000000000000000A"); + assert_eq!(id.sid.as_deref(), Some("sid-1")); + assert_eq!(id.picture_version, 1); + } + + #[test] + fn an_unsigned_alg_none_token_is_refused() { + let signer = Signer::generate(); + let token = unsigned(r#"{"alg":"none","kid":"k1"}"#, &id_claims(NOW, "n-1")); + assert!(matches!( + verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-1", NOW), + Err(ImError::Rejected(_)) + )); + } + + #[test] + fn a_token_for_another_audience_is_refused() { + let signer = Signer::generate(); + let mut claims = id_claims(NOW, "n-1"); + claims["aud"] = json!("in"); + let token = signer.sign(&claims); + assert!(matches!( + verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-1", NOW), + Err(ImError::Rejected(_)) + )); + } + + #[test] + fn an_expired_token_is_refused_but_leeway_is_allowed() { + // `exp` is checked against the system clock, so this test uses the real current time. + let now = unix_now(); + let signer = Signer::generate(); + let mut claims = id_claims(now, "n-1"); + claims["exp"] = json!(now - 3600); + let token = signer.sign(&claims); + assert!(verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-1", now).is_err()); + let mut claims = id_claims(now, "n-1"); + claims["exp"] = json!(now - 30); + let token = signer.sign(&claims); + assert!(verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-1", now).is_ok()); + } + + #[test] + fn a_wrong_nonce_is_refused() { + let signer = Signer::generate(); + let token = signer.sign(&id_claims(NOW, "n-1")); + assert!(matches!( + verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-2", NOW), + Err(ImError::Rejected(_)) + )); + } + + #[test] + fn an_unknown_key_id_asks_for_a_refetch() { + let signer = Signer::generate(); + let token = signer.sign_with_kid("k2", &id_claims(NOW, "n-1")); + assert!(matches!( + verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-1", NOW), + Err(ImError::UnknownKey) + )); + } + + #[test] + fn a_logout_token_needs_the_event_and_no_nonce() { + let signer = Signer::generate(); + let good = signer.sign(&logout_claims(NOW, "j-1")); + let claims = verify_logout_token(&signer.keys, ISSUER, CLIENT_ID, &good, NOW).unwrap(); + assert_eq!(claims.jti, "j-1"); + assert_eq!(claims.sid.as_deref(), Some("sid-1")); + + let mut with_nonce = logout_claims(NOW, "j-2"); + with_nonce["nonce"] = json!("n"); + let token = signer.sign(&with_nonce); + assert!(verify_logout_token(&signer.keys, ISSUER, CLIENT_ID, &token, NOW).is_err()); + + let mut no_event = logout_claims(NOW, "j-3"); + no_event["events"] = json!({}); + let token = signer.sign(&no_event); + assert!(verify_logout_token(&signer.keys, ISSUER, CLIENT_ID, &token, NOW).is_err()); + } + + #[test] + fn the_key_set_keeps_only_ed25519_keys_with_a_kid() { + let set = KeySet::from_jwks( + br#"{"keys":[{"kty":"RSA","kid":"r1","n":"x","e":"AQAB"},{"kty":"OKP","crv":"Ed25519","kid":"no-x"}]}"#, + ) + .unwrap(); + assert!(set.keys.is_empty()); + } +} diff --git a/crates/iz-web/src/pages/backchannel.rs b/crates/iz-web/src/pages/backchannel.rs new file mode 100644 index 0000000..9b4a7f7 --- /dev/null +++ b/crates/iz-web/src/pages/backchannel.rs @@ -0,0 +1,202 @@ +//! `POST /auth/backchannel-logout`: the back-channel logout of `im` (OIDC Back-Channel Logout 1.0, +//! docs/contracts.md 2.5). `im` posts `logout_token=` here when a session ends, and iz ends the +//! matching local sessions. +//! +//! The route is the one contracts.md 2.5 names as the URI `im` registers for each client. It is a +//! machine endpoint: no CSRF token, no cookie, and a body capped at 16 KiB. Success is `200` with an +//! empty body. Every other answer is a JSON error (`docs/contracts.md` section 7): `413` for a body +//! over 16 KiB, `503` when `im`'s keys cannot be fetched, `400` for anything else the request gets +//! wrong (a token iz refuses, a replayed token included), and `500` when the database fails. + +use std::time::Duration; + +use iz_core::store::Store; +use serde::Deserialize; +use serde_json::json; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::content::Form; +use topcoat::router::{Body, HeaderMap, HeaderValue, StatusCode, header, route, to_bytes}; + +use crate::oidc::{ImError, LogoutClaims}; +use crate::state::AppState; + +/// Largest back-channel body accepted, in bytes. Reason: the form holds one token of a few kilobytes. +const MAX_BODY_BYTES: usize = 16 * 1024; +/// How long a logout token id is remembered, so a replay is refused. Reason: contracts.md 2.5, ten +/// minutes, which is five times the token's own two-minute life. +const JTI_LIFETIME: Duration = Duration::from_secs(10 * 60); + +/// Why a logout token did not end any session. +#[derive(Debug, thiserror::Error)] +pub enum BackchannelError { + /// The token id was already used. Refused, so the same token cannot be replayed. + #[error("the logout token was already used")] + Replay, + /// The database failed while the logout was recorded. + #[error(transparent)] + Store(#[from] iz_core::Error), +} + +/// The form body of the back-channel request. +#[derive(Deserialize)] +struct BackchannelForm { + #[serde(default)] + logout_token: String, +} + +/// Ends the sessions that a verified logout token names, and records its id so it cannot be used +/// again. A `sid` ends that browser session; a token with only a `sub` ends every session of the +/// user (a disabled or deleted member). Returns how many sessions ended. +/// +/// The id is recorded first and atomically (`seen_jti` inserts and reports a repeat), so two copies +/// of one token cannot both succeed. +pub async fn end_sessions(store: &Store, claims: &LogoutClaims) -> std::result::Result { + if store.seen_jti(&claims.jti, JTI_LIFETIME).await? { + return Err(BackchannelError::Replay); + } + let ended = match (&claims.sid, &claims.sub) { + (Some(sid), _) => store.delete_sessions_by_sid(sid).await?, + (None, Some(sub)) => store.delete_sessions_by_sub(sub).await?, + // The verifier requires one of the two, so this arm is unreachable in practice. + (None, None) => 0, + }; + Ok(ended) +} + +/// `POST /auth/backchannel-logout`. +#[route(POST "/auth/backchannel-logout")] +async fn backchannel_logout(cx: &Cx, body: Body) -> Result<(StatusCode, HeaderMap, String)> { + let state = app_context::(cx); + let Some(client) = state.oidc.clone() else { + return Ok(json_error( + StatusCode::SERVICE_UNAVAILABLE, + "unavailable", + "sign-in is not configured", + )); + }; + let Ok(bytes) = to_bytes(body, MAX_BODY_BYTES).await else { + return Ok(json_error( + StatusCode::PAYLOAD_TOO_LARGE, + "invalid_request", + "the body is missing or larger than 16 KiB", + )); + }; + let Ok(Form(form)) = Form::::from_bytes(&bytes) else { + return Ok(json_error( + StatusCode::BAD_REQUEST, + "invalid_request", + "the body is not a form", + )); + }; + if form.logout_token.is_empty() { + return Ok(json_error( + StatusCode::BAD_REQUEST, + "invalid_request", + "logout_token is missing", + )); + } + let claims = match client.verify_logout_token(&form.logout_token).await { + Ok(claims) => claims, + Err(ImError::Unavailable(reason) | ImError::BadResponse(reason)) => { + tracing::warn!(reason, "back-channel logout: the key set cannot be read"); + return Ok(json_error( + StatusCode::SERVICE_UNAVAILABLE, + "unavailable", + "the keys of the account service cannot be read", + )); + } + Err(error) => { + tracing::warn!(error = %error, "back-channel logout: the token was refused"); + return Ok(json_error( + StatusCode::BAD_REQUEST, + "invalid_request", + "the logout token was refused", + )); + } + }; + match end_sessions(&state.store, &claims).await { + Ok(ended) => { + tracing::info!(ended, "back-channel logout"); + Ok((StatusCode::OK, HeaderMap::new(), String::new())) + } + Err(BackchannelError::Replay) => { + tracing::warn!("back-channel logout: a token was replayed"); + Ok(json_error( + StatusCode::BAD_REQUEST, + "invalid_request", + "the logout token was already used", + )) + } + Err(BackchannelError::Store(error)) => { + tracing::error!(error = %error, "back-channel logout: the database failed"); + Ok(json_error( + StatusCode::INTERNAL_SERVER_ERROR, + "internal", + "the logout could not be recorded", + )) + } + } +} + +/// A JSON error answer: `{"error": , "message": }`. +fn json_error(status: StatusCode, error: &str, message: &str) -> (StatusCode, HeaderMap, String) { + let mut headers = HeaderMap::new(); + headers.insert( + header::CONTENT_TYPE, + HeaderValue::from_static("application/json"), + ); + ( + status, + headers, + json!({"error": error, "message": message}).to_string(), + ) +} + +#[cfg(test)] +mod tests { + use iz_core::authz::Role; + use iz_core::store::Store; + use iz_core::store::members::DirectoryMember; + + use super::*; + use crate::oidc::test_support::{CLIENT_ID, ISSUER, Signer, logout_claims}; + use crate::oidc::{unix_now, verify_logout_token}; + + /// A replayed logout token is refused, and it ends a session only the first time. + #[tokio::test] + async fn a_replayed_back_channel_jti_is_refused() { + let dir = tempfile::tempdir().expect("temp dir"); + let store = Store::open(&dir.path().join("iz.db")).await.expect("store"); + let member = DirectoryMember { + sub: "01MEMBERAAAAAAAAAAAAAAAAAA".into(), + email: "ada@example.com".into(), + name: "Ada".into(), + im_admin: false, + disabled: false, + locale: None, + zoneinfo: "UTC".into(), + picture_version: 0, + }; + store + .apply_directory_member(&member, Role::Member) + .await + .expect("member"); + store + .create_session(&member.sub, Some("sid-1"), None, Duration::from_secs(3600), None, None) + .await + .expect("session"); + + let now = unix_now(); + let signer = Signer::generate(); + let token = signer.sign(&logout_claims(now, "jti-1")); + let claims = verify_logout_token(&signer.keys, ISSUER, CLIENT_ID, &token, now) + .expect("the token verifies"); + + assert_eq!(end_sessions(&store, &claims).await.expect("first use"), 1); + assert!(matches!( + end_sessions(&store, &claims).await, + Err(BackchannelError::Replay) + )); + } +} diff --git a/crates/iz-web/src/pages/home.rs b/crates/iz-web/src/pages/home.rs index 03bd548..fe22c78 100644 --- a/crates/iz-web/src/pages/home.rs +++ b/crates/iz-web/src/pages/home.rs @@ -1,25 +1,44 @@ -//! The start page. Until sign-in exists every visitor is signed out, so it shows the app name and -//! that the viewer is not signed in. +//! The start page. A signed-out visitor sees the app name and a sign-in button. A signed-in member +//! sees a greeting; the board itself comes later, so the page says that. use topcoat::Result; use topcoat::context::Cx; use topcoat::router::page; use topcoat::view::{View, view}; +use crate::auth::current_member; +use crate::i18n::shell::{K, greeting, t}; use crate::i18n::lang; -use crate::i18n::shell::{K, t}; -use crate::views::shell; +use crate::views::{ViewerInfo, shell}; +use iz_core::authz::Role; /// `GET /`. #[page("/")] async fn home(cx: &Cx) -> Result { - let lang = lang(cx, None); + let me = current_member(cx).await?; + let lang = lang( + cx, + me.as_ref() + .and_then(|me| me.member.locale_override.as_deref()), + ); + let viewer = me.as_ref().map(|me| ViewerInfo { + name: me.member.name.clone(), + is_admin: me.member.im_admin || me.member.role == Role::Admin, + csrf: me.session.csrf_token.clone(), + }); + let name = me.as_ref().map(|me| me.member.name.clone()); Ok(view! { - shell(title: t(lang, K::SignedOutTitle), lang: lang, viewer: None, + shell(title: t(lang, K::SignedOutTitle), lang: lang, viewer: viewer.as_ref(),

"iz"

-

(t(lang, K::SignedOutTitle))

-

(t(lang, K::SignedOutBody))

+ if let Some(name) = name { +

(greeting(lang, &name))

+

(t(lang, K::BoardComesNext))

+ } else { +

(t(lang, K::SignedOutTitle))

+

(t(lang, K::SignedOutBody))

+ (t(lang, K::SignIn)) + }
) }) diff --git a/crates/iz-web/src/pages/mod.rs b/crates/iz-web/src/pages/mod.rs index 2f18c8a..af6582e 100644 --- a/crates/iz-web/src/pages/mod.rs +++ b/crates/iz-web/src/pages/mod.rs @@ -1,4 +1,7 @@ //! The pages and the page-level layers. One file per page. +pub mod backchannel; pub mod home; pub mod not_found; +pub mod photo; +pub mod sign_in; diff --git a/crates/iz-web/src/pages/photo.rs b/crates/iz-web/src/pages/photo.rs new file mode 100644 index 0000000..8babbbe --- /dev/null +++ b/crates/iz-web/src/pages/photo.rs @@ -0,0 +1,158 @@ +//! `GET /avatar/{sub}`: a member's photo, proxied from `im` and cached on disk +//! (docs/contracts.md 3.2 and `architecture.md` section 4). +//! +//! Only a signed-in member may fetch a photo. A browser never talks to `im` for one, and an `im` +//! failure with no cached copy is a plain `404`, so the page falls back to initials. The cache key is +//! `(sub, picture_version)`; a changed photo gets a new version and the old files are removed. +//! The ETag is `"p"`. A `?v=` that matches the current version may be cached for a +//! year; any other request is revalidated. + +use std::path::{Path, PathBuf}; + +use http::header::{ + CACHE_CONTROL, CONTENT_TYPE, ETAG, IF_NONE_MATCH, X_CONTENT_TYPE_OPTIONS, +}; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::error::not_found; +use topcoat::router::request::{headers, uri}; +use topcoat::router::{HeaderMap, HeaderValue, StatusCode, path_param_segment, route}; + +use crate::auth::current_member; +use crate::directory::{PHOTO_TYPES, fetch_photo}; +use crate::state::AppState; + +/// Longest member id accepted in the path. Reason: ids are ULIDs (26 characters); this leaves room. +const MAX_SUB_LEN: usize = 64; + +/// `GET /avatar/{sub}`. +#[route(GET "/avatar/{sub}")] +async fn photo(cx: &Cx) -> Result<(StatusCode, HeaderMap, Vec)> { + let state = app_context::(cx); + // Anonymous and unknown requests get the same 404: a photo URL reveals nothing without a session. + if current_member(cx).await?.is_none() { + return Err(not_found().into()); + } + let sub = path_param_segment(cx, "sub").to_owned(); + if !valid_sub(&sub) { + return Err(not_found().into()); + } + let Some(member) = state.store.member(&sub).await? else { + return Err(not_found().into()); + }; + if member.disabled { + return Err(not_found().into()); + } + + let etag = format!("\"p{}\"", member.picture_version); + let current = requested_version(cx) == Some(member.picture_version); + let mut out = HeaderMap::new(); + out.insert(ETAG, HeaderValue::from_str(&etag)?); + out.insert( + CACHE_CONTROL, + HeaderValue::from_static(if current { + "private, max-age=31536000, immutable" + } else { + "private, no-cache" + }), + ); + out.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")); + if if_none_match_has(cx, &etag) { + return Ok((StatusCode::NOT_MODIFIED, out, Vec::new())); + } + + let Some((mime, bytes)) = load(state, &sub, member.picture_version).await else { + return Err(not_found().into()); + }; + out.insert(CONTENT_TYPE, HeaderValue::from_str(&mime)?); + Ok((StatusCode::OK, out, bytes)) +} + +/// A member id that is safe as a directory name and in a URL: letters, digits, `-` and `_`. +fn valid_sub(sub: &str) -> bool { + !sub.is_empty() + && sub.len() <= MAX_SUB_LEN + && sub + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') +} + +/// The `v` of the query string, if it is a number. +fn requested_version(cx: &Cx) -> Option { + uri(cx) + .query()? + .split('&') + .find_map(|pair| pair.strip_prefix("v=")) + .and_then(|value| value.parse().ok()) +} + +/// Whether `If-None-Match` names `etag` (or `*`). +fn if_none_match_has(cx: &Cx, etag: &str) -> bool { + headers(cx) + .get(IF_NONE_MATCH) + .and_then(|value| value.to_str().ok()) + .is_some_and(|value| { + value + .split(',') + .map(str::trim) + .any(|candidate| candidate == etag || candidate == "*") + }) +} + +/// The photo for `(sub, version)`: from the disk cache, else from `im`, which is then cached. `None` +/// when there is no photo, `im` is unreachable and nothing is cached, or the type is not allowed. +async fn load(state: &AppState, sub: &str, version: i64) -> Option<(String, Vec)> { + let dir = state.config.data_dir.join("photos").join(sub); + if let Some(cached) = read_cache(&dir.join(format!("{version}.img"))).await { + return Some(cached); + } + let oidc = state.oidc.as_ref()?; + match fetch_photo(oidc, sub).await { + Ok(Some((mime, bytes))) => { + if let Err(error) = write_cache(&dir, version, &mime, &bytes).await { + tracing::warn!(error = %error, "photo: could not write the cache"); + } + Some((mime, bytes)) + } + Ok(None) => None, + Err(error) => { + tracing::warn!(error = %error, "photo: the account service did not answer"); + None + } + } +} + +/// Reads a cached photo: the first line is the type, the rest is the image. A cached type that is no +/// longer allowed is treated as a miss. +async fn read_cache(path: &Path) -> Option<(String, Vec)> { + let data = tokio::fs::read(path).await.ok()?; + let newline = data.iter().position(|&b| b == b'\n')?; + let mime = std::str::from_utf8(&data[..newline]).ok()?.to_owned(); + if !PHOTO_TYPES.contains(&mime.as_str()) { + return None; + } + Some((mime, data[newline + 1..].to_vec())) +} + +/// Writes a photo under its version, through a temporary file so a reader never sees half of it, and +/// removes the files of other versions of the same member. +async fn write_cache(dir: &Path, version: i64, mime: &str, bytes: &[u8]) -> std::io::Result<()> { + tokio::fs::create_dir_all(dir).await?; + let name = format!("{version}.img"); + let tmp = dir.join(format!("{version}.tmp")); + let mut data = Vec::with_capacity(mime.len() + 1 + bytes.len()); + data.extend_from_slice(mime.as_bytes()); + data.push(b'\n'); + data.extend_from_slice(bytes); + tokio::fs::write(&tmp, &data).await?; + tokio::fs::rename(&tmp, dir.join(&name)).await?; + let mut entries = tokio::fs::read_dir(dir).await?; + while let Some(entry) = entries.next_entry().await? { + let path: PathBuf = entry.path(); + let is_image = path.extension().is_some_and(|ext| ext == "img"); + if is_image && entry.file_name().to_str() != Some(name.as_str()) { + tokio::fs::remove_file(&path).await?; + } + } + Ok(()) +} diff --git a/crates/iz-web/src/pages/sign_in.rs b/crates/iz-web/src/pages/sign_in.rs new file mode 100644 index 0000000..3469b98 --- /dev/null +++ b/crates/iz-web/src/pages/sign_in.rs @@ -0,0 +1,397 @@ +//! Sign-in and sign-out (docs/contracts.md 2.3 and 2.5): `GET /auth/login` starts the flight, `GET +//! /auth/callback` finishes it, and `POST /auth/logout` ends the local session and the `im` session. +//! +//! The order in the callback is fixed: the flight cookie is cleared first, so it is used only once; +//! the state is compared in constant time; the code is exchanged; the ID token is verified with the +//! nonce of this flight; the member is upserted from the claims; a member with no role, or who is +//! disabled, gets the no-access page and no session; only then is the local session created. + +use iz_core::authz::Role; +use iz_core::secret; +use iz_core::store::members::DirectoryMember; +use iz_core::token::{constant_time_eq, generate_token}; +use iz_core::zones::parse_zone; +use serde::Deserialize; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::content::Form; +use topcoat::router::error::{forbidden, see_other}; +use topcoat::router::{StatusCode, page, route}; +use topcoat::view::{View, view}; + +use crate::auth::{ + SESSION_LIFETIME, STATE_LIFETIME, SignInState, clear_session_cookie, clear_state_cookie, + current_member, open_sign_in_state, query_param, safe_next, seal_sign_in_state, + set_session_cookie, set_state_cookie, state_cookie, user_agent, +}; +use crate::directory; +use crate::i18n::shell::{K, t}; +use crate::i18n::{Lang, lang}; +use crate::oidc::{ImError, pkce_challenge, unix_now}; +use crate::state::AppState; +use crate::views::{message_page, shell}; + +/// The page of a failed sign-in or a refused one. `detail` is shown escaped, in a code element. +async fn message( + cx: &Cx, + status: StatusCode, + title: K, + body: K, + detail: Option, +) -> Result { + let lang: Lang = lang(cx, None); + Ok(view! { + cx => + shell(title: t(lang, title), lang: lang, viewer: None, + (status) + message_page(lang: lang, title: title, body: body, detail: detail) + ) + }) +} + +/// The page and status for an `im` failure: the account service is down or answered badly, or the +/// token was refused. +fn failure_for(error: &ImError) -> (StatusCode, K, K) { + match error { + ImError::Unavailable(_) | ImError::BadResponse(_) => ( + StatusCode::SERVICE_UNAVAILABLE, + K::SignInUnavailableTitle, + K::SignInUnavailableBody, + ), + ImError::UnknownKey | ImError::Rejected(_) => ( + StatusCode::BAD_REQUEST, + K::SignInFailedTitle, + K::SignInFailedBody, + ), + } +} + +/// `GET /login?next=`: starts a sign-in. Stores the flight in a sealed cookie and sends the +/// browser to `im`'s authorization endpoint with PKCE, the state and the nonce. +#[page("/auth/login")] +async fn login(cx: &Cx) -> Result { + let state = app_context::(cx); + let Some(client) = state.oidc.clone() else { + return message( + cx, + StatusCode::SERVICE_UNAVAILABLE, + K::SignInUnavailableTitle, + K::SignInUnavailableBody, + None, + ) + .await; + }; + let flight = SignInState { + state: generate_token(), + nonce: generate_token(), + verifier: generate_token(), + next: safe_next(query_param(cx, "next").as_deref()).to_owned(), + expires: unix_now() + STATE_LIFETIME.as_secs(), + }; + let url = match client + .authorize_url(&flight.state, &flight.nonce, &pkce_challenge(&flight.verifier)) + .await + { + Ok(url) => url, + Err(error) => { + tracing::warn!(error = %error, "sign-in: cannot start the flight"); + let (status, title, body) = failure_for(&error); + return message(cx, status, title, body, None).await; + } + }; + let sealed = seal_sign_in_state(&state.key, &flight)?; + set_state_cookie(cx, sealed); + Err(see_other(url).into()) +} + +/// `GET /auth/callback`: finishes a sign-in that `im` sent back. +#[page("/auth/callback")] +async fn callback(cx: &Cx) -> Result { + let state = app_context::(cx); + let sealed = state_cookie(cx); + // Cleared before anything else, so the flight can be used only once, whatever happens next. + clear_state_cookie(cx); + let Some(client) = state.oidc.clone() else { + return message( + cx, + StatusCode::SERVICE_UNAVAILABLE, + K::SignInUnavailableTitle, + K::SignInUnavailableBody, + None, + ) + .await; + }; + let Some(flight) = sealed.and_then(|s| open_sign_in_state(&state.key, &s)) else { + tracing::warn!("sign-in: no valid flight cookie"); + return message( + cx, + StatusCode::BAD_REQUEST, + K::SignInFailedTitle, + K::SignInFailedBody, + None, + ) + .await; + }; + let returned = query_param(cx, "state").unwrap_or_default(); + if !constant_time_eq(returned.as_bytes(), flight.state.as_bytes()) { + tracing::warn!("sign-in: the state does not match the flight"); + return message( + cx, + StatusCode::BAD_REQUEST, + K::SignInFailedTitle, + K::SignInFailedBody, + None, + ) + .await; + } + if let Some(error) = query_param(cx, "error") { + // The value comes from `im`. It is cut short and shown escaped, and never used for anything else. + let shown: String = error.chars().take(64).collect(); + tracing::warn!(error = %shown, "sign-in: the identity provider refused the sign-in"); + return message( + cx, + StatusCode::BAD_REQUEST, + K::SignInFailedTitle, + K::SignInFailedBody, + Some(shown), + ) + .await; + } + let Some(code) = query_param(cx, "code").filter(|code| !code.is_empty()) else { + return message( + cx, + StatusCode::BAD_REQUEST, + K::SignInFailedTitle, + K::SignInFailedBody, + None, + ) + .await; + }; + + let tokens = match client.exchange_code(&code, &flight.verifier).await { + Ok(tokens) => tokens, + Err(error) => { + tracing::warn!(error = %error, "sign-in: the code exchange failed"); + let (status, title, body) = failure_for(&error); + return message(cx, status, title, body, None).await; + } + }; + let Some(id_token) = tokens.id_token.filter(|token| !token.is_empty()) else { + tracing::warn!("sign-in: the token answer has no ID token"); + return message( + cx, + StatusCode::BAD_REQUEST, + K::SignInFailedTitle, + K::SignInFailedBody, + None, + ) + .await; + }; + let claims = match client.verify_id_token(&id_token, &flight.nonce).await { + Ok(claims) => claims, + Err(error) => { + tracing::warn!(error = %error, "sign-in: the ID token was refused"); + let (status, title, body) = failure_for(&error); + return message(cx, status, title, body, None).await; + } + }; + + let Some(email) = claims + .email + .clone() + .map(|email| email.trim().to_owned()) + .filter(|email| !email.is_empty()) + else { + tracing::warn!("sign-in: the ID token has no email"); + return message( + cx, + StatusCode::BAD_REQUEST, + K::SignInFailedTitle, + K::SignInFailedBody, + None, + ) + .await; + }; + let name = claims + .name + .clone() + .map(|name| name.trim().to_owned()) + .filter(|name| !name.is_empty()) + .unwrap_or_else(|| email.clone()); + // A time zone the store does not know must not block the sign-in; it falls back to UTC. + let zoneinfo = claims + .zoneinfo + .clone() + .filter(|zone| parse_zone(zone).is_ok()) + .unwrap_or_else(|| "UTC".to_owned()); + let member_input = DirectoryMember { + sub: claims.sub.clone(), + email, + name, + im_admin: claims.admin, + disabled: false, + locale: claims.locale.clone(), + zoneinfo, + picture_version: claims.picture_version, + }; + let default_role = directory::default_role(&state.store).await?; + let stored = match state + .store + .upsert_from_claims(&member_input, default_role) + .await + { + Ok(stored) => stored, + Err(iz_core::Error::Invalid(reason)) => { + tracing::warn!(reason, "sign-in: the member record is refused"); + return message( + cx, + StatusCode::BAD_REQUEST, + K::SignInFailedTitle, + K::SignInFailedBody, + None, + ) + .await; + } + Err(error) => return Err(error.into()), + }; + if stored.disabled || stored.role == Role::NoAccess { + tracing::info!(sub = %stored.sub, "sign-in: no access for this member"); + return message( + cx, + StatusCode::FORBIDDEN, + K::NoAccessTitle, + K::NoAccessBody, + None, + ) + .await; + } + + // The ID token is kept, sealed, as the hint of a later logout. + let sealed_id_token = secret::seal(&state.key, id_token.as_bytes())?; + let issued = match state + .store + .create_session( + &stored.sub, + claims.sid.as_deref(), + Some(&sealed_id_token), + SESSION_LIFETIME, + user_agent(cx).as_deref(), + None, + ) + .await + { + Ok(issued) => issued, + Err(iz_core::Error::Forbidden(_)) => { + return message( + cx, + StatusCode::FORBIDDEN, + K::NoAccessTitle, + K::NoAccessBody, + None, + ) + .await; + } + Err(error) => return Err(error.into()), + }; + set_session_cookie(cx, issued.token); + tracing::info!(sub = %stored.sub, "signed in"); + Err(see_other(safe_next(Some(&flight.next))).into()) +} + +/// The form of `POST /auth/logout`. The CSRF token is read as text; a missing one is refused. +#[derive(Deserialize)] +struct LogoutForm { + #[serde(default)] + csrf: String, +} + +/// `POST /auth/logout`: ends the local session, then sends the browser to `im`'s end-session endpoint with +/// the stored ID token as the hint (contracts.md 2.5). The CSRF check runs before any side effect. +#[route(POST "/auth/logout")] +async fn logout(cx: &Cx, form: Option>) -> Result { + let state = app_context::(cx); + let Some(me) = current_member(cx).await? else { + // Nothing to end: the session is already gone. + clear_session_cookie(cx); + return Ok(see_other("/")); + }; + let submitted = form.map(|Form(form)| form.csrf).unwrap_or_default(); + if !me.csrf_matches(&submitted) { + return Err(forbidden().into()); + } + state.store.delete_session(&me.session.id).await?; + clear_session_cookie(cx); + + let id_token = me + .session + .id_token_sealed + .as_deref() + .and_then(|sealed| secret::open(&state.key, sealed).ok()) + .and_then(|plain| String::from_utf8(plain).ok()); + let target = match &state.oidc { + Some(client) => match client + .end_session_url(id_token.as_deref(), &generate_token()) + .await + { + Ok(url) => url, + Err(error) => { + tracing::warn!(error = %error, "logout: no end-session URL; returning to the start"); + "/".to_owned() + } + }, + None => "/".to_owned(), + }; + Ok(see_other(target)) +} + +#[cfg(test)] +mod tests { + use http::header::{CONTENT_TYPE, COOKIE}; + use iz_core::authz::Role; + use iz_core::store::members::DirectoryMember; + use topcoat::router::Body; + + use crate::auth::SESSION_LIFETIME; + use crate::boot::{router, test_state}; + + /// A sign-out without the CSRF token is refused, and the session survives it. + #[tokio::test] + async fn logout_without_csrf_is_forbidden_and_keeps_the_session() { + let (_dir, state) = test_state().await; + let member = DirectoryMember { + sub: "01MEMBERAAAAAAAAAAAAAAAAAA".into(), + email: "ada@example.com".into(), + name: "Ada".into(), + im_admin: false, + disabled: false, + locale: None, + zoneinfo: "UTC".into(), + picture_version: 0, + }; + state + .store + .apply_directory_member(&member, Role::Member) + .await + .unwrap(); + let issued = state + .store + .create_session(&member.sub, Some("sid-1"), None, SESSION_LIFETIME, None, None) + .await + .unwrap(); + let request = http::Request::post("/auth/logout") + .header(CONTENT_TYPE, "application/x-www-form-urlencoded") + .header(COOKIE, format!("__Host-iz_session={}", issued.token)) + .body(Body::from("csrf=not-the-token")) + .expect("request"); + let response = router(state.clone()).handle(request).await; + assert_eq!(response.status(), 403); + assert!( + state + .store + .session_by_token(&issued.token) + .await + .unwrap() + .is_some() + ); + } +} diff --git a/crates/iz-web/src/state.rs b/crates/iz-web/src/state.rs index 0778d0b..966e55f 100644 --- a/crates/iz-web/src/state.rs +++ b/crates/iz-web/src/state.rs @@ -6,9 +6,10 @@ use iz_core::config::Config; use iz_core::store::Store; use crate::live::LiveHub; +use crate::oidc::OidcClient; /// Everything a request handler reaches through the app context. Every field is cheap to clone. -#[allow(dead_code)] // The key and the hub are read by the sign-in and live pages that come next. +#[allow(dead_code)] // The hub is read by the live pages that come next. #[derive(Clone)] pub struct AppState { /// The configuration the process booted with. @@ -19,4 +20,6 @@ pub struct AppState { pub key: Arc<[u8; 32]>, /// The change counters of the live pages. pub live: Arc, + /// The `im` client. `None` when no `[oidc]` section is configured, so sign-in is off. + pub oidc: Option>, } diff --git a/crates/iz-web/src/views/mod.rs b/crates/iz-web/src/views/mod.rs index 9f16ef9..8684ab6 100644 --- a/crates/iz-web/src/views/mod.rs +++ b/crates/iz-web/src/views/mod.rs @@ -10,14 +10,15 @@ use crate::assets::{MAIN_CSS_HREF, NAV_JS_HREF, PAGES_JS_HREF}; use crate::i18n::Lang; use crate::i18n::shell::{K, t}; -/// What the shell shows about the signed-in person. Nothing signs a person in yet, so every page -/// is built for an anonymous viewer. -#[allow(dead_code)] // Built by the sign-in code, which comes next. +/// What the shell shows about the signed-in person: the name in the user menu, the administrator +/// badge, and the CSRF token of the sign-out form in that menu. pub struct ViewerInfo { - /// The name shown in the topbar. + /// The name shown in the user menu. pub name: String, /// Whether the topbar shows the administrator badge. pub is_admin: bool, + /// The session's CSRF token. The sign-out form carries it. + pub csrf: String, } /// The HTML document around a page. `title` is the page's own title; the document title adds the @@ -51,7 +52,13 @@ pub async fn shell(
if let Some(viewer) = viewer { - (viewer.name.as_str()) +
+ (viewer.name.as_str()) +
+ + +
+
if viewer.is_admin { (t(lang, K::Admin)) } @@ -64,6 +71,27 @@ pub async fn shell( }) } +/// The body of a message page: a title, one sentence, an optional detail (escaped, in a code +/// element) and a way back to the start. +#[component] +pub async fn message_page( + lang: Lang, + title: K, + body: K, + detail: Option, +) -> Result { + Ok(view! { +
+

(t(lang, title))

+

(t(lang, body))

+ if let Some(detail) = detail { +

(detail.as_str())

+ } + (t(lang, K::BackHome)) +
+ }) +} + /// An error message for a failed action. Forms show it above their fields. #[allow(dead_code)] // The first form that can fail a check uses it. #[component] diff --git a/style/_layout.scss b/style/_layout.scss index a4b2827..3b94fb1 100644 --- a/style/_layout.scss +++ b/style/_layout.scss @@ -67,6 +67,28 @@ font-size: var(--text-sm); } +// The user menu: the name opens a small panel with the sign-out button. The panel is plain HTML +// (a details element), so it works without script. +.user-menu { + position: relative; +} + +.user-menu > summary { + cursor: pointer; + list-style: none; +} + +.user-menu-form { + position: absolute; + right: 0; + top: 100%; + margin-top: var(--space-2); + padding: var(--space-3); + background: var(--surface-2); + border-radius: var(--radius, 8px); + z-index: 10; +} + .page { width: 100%; max-width: var(--content-width);