OIDC provider part 2: client credentials, revoke, introspect, RP-initiated logout, back-channel logout outbox and worker
Browse files at this commitd2aab2bb2c5d1a5e5544ed746ef73ae60a8bf7f3Parent: 088ace7- feat
- OIDC provider part 2: client credentials, revoke, introspect, RP-initiated logout, back-channel logout outbox and worker
- security headers no longer duplicate route headers
29 changed files +2431 -94
- Cargo.lock +557 -1
- Cargo.toml +1 -0
- crates/im-core/src/jwt.rs +15 -0
- crates/im-core/src/model.rs +14 -0
- crates/im-core/src/store/backchannel.rs +453 -0
- crates/im-core/src/store/clients.rs +14 -0
- crates/im-core/src/store/mod.rs +1 -0
- crates/im-core/src/store/sessions.rs +104 -43
- crates/im-core/src/store/users.rs +43 -0
- crates/im-web/Cargo.toml +2 -1
- crates/im-web/src/auth.rs +10 -6
- crates/im-web/src/backchannel.rs +375 -0
- crates/im-web/src/boot.rs +35 -0
- crates/im-web/src/cli.rs +3 -1
- crates/im-web/src/i18n/oidc.rs +28 -0
- crates/im-web/src/main.rs +1 -0
- crates/im-web/src/oidc/authorize.rs +16 -0
- crates/im-web/src/oidc/discovery.rs +1 -2
- crates/im-web/src/oidc/introspect.rs +120 -0
- crates/im-web/src/oidc/logout.rs +278 -0
- crates/im-web/src/oidc/mod.rs +3 -0
- crates/im-web/src/oidc/revoke.rs +40 -0
- crates/im-web/src/oidc/tests.rs +154 -1
- crates/im-web/src/oidc/token.rs +89 -7
- crates/im-web/src/oidc/userinfo.rs +14 -6
- crates/im-web/src/pages/login.rs +3 -20
- crates/im-web/src/pages/security.rs +6 -1
- crates/im-web/src/pages/sessions.rs +4 -3
- crates/im-web/src/security.rs +47 -2
Cargo.lockmodified+557 -1
| @@ -253,6 +253,29 @@ version = "1.5.1" | |||
| 253 | source = "registry+https://github.com/rust-lang/crates.io-index" | 253 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 254 | checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" | 254 | checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" |
| 255 | 255 | ||
| 256 | +[[package]] | ||
| 257 | +name = "aws-lc-rs" | ||
| 258 | +version = "1.18.2" | ||
| 259 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 260 | +checksum = "faac5829c2b74c28f830747e7818ccfb684261b5f48a1118b1e2a13d36dfab13" | ||
| 261 | +dependencies = [ | ||
| 262 | + "aws-lc-sys", | ||
| 263 | + "zeroize", | ||
| 264 | +] | ||
| 265 | + | ||
| 266 | +[[package]] | ||
| 267 | +name = "aws-lc-sys" | ||
| 268 | +version = "0.46.0" | ||
| 269 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 270 | +checksum = "f1622d8446a2d4b2ce0c7eefc73dd43a99779028d5ee5c2dd8073a658ba8a2bc" | ||
| 271 | +dependencies = [ | ||
| 272 | + "cc", | ||
| 273 | + "cmake", | ||
| 274 | + "dunce", | ||
| 275 | + "fs_extra", | ||
| 276 | + "pkg-config", | ||
| 277 | +] | ||
| 278 | + | ||
| 256 | [[package]] | 279 | [[package]] |
| 257 | name = "base64" | 280 | name = "base64" |
| 258 | version = "0.22.1" | 281 | version = "0.22.1" |
| @@ -584,6 +607,15 @@ version = "1.1.1" | |||
| 584 | source = "registry+https://github.com/rust-lang/crates.io-index" | 607 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 585 | checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" | 608 | checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" |
| 586 | 609 | ||
| 610 | +[[package]] | ||
| 611 | +name = "cmake" | ||
| 612 | +version = "0.1.58" | ||
| 613 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 614 | +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" | ||
| 615 | +dependencies = [ | ||
| 616 | + "cc", | ||
| 617 | +] | ||
| 618 | + | ||
| 587 | [[package]] | 619 | [[package]] |
| 588 | name = "cmov" | 620 | name = "cmov" |
| 589 | version = "0.5.4" | 621 | version = "0.5.4" |
| @@ -608,6 +640,16 @@ version = "1.0.5" | |||
| 608 | source = "registry+https://github.com/rust-lang/crates.io-index" | 640 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 609 | checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" | 641 | checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" |
| 610 | 642 | ||
| 643 | +[[package]] | ||
| 644 | +name = "combine" | ||
| 645 | +version = "4.6.9" | ||
| 646 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 647 | +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" | ||
| 648 | +dependencies = [ | ||
| 649 | + "bytes", | ||
| 650 | + "memchr", | ||
| 651 | +] | ||
| 652 | + | ||
| 611 | [[package]] | 653 | [[package]] |
| 612 | name = "concurrent-queue" | 654 | name = "concurrent-queue" |
| 613 | version = "2.5.0" | 655 | version = "2.5.0" |
| @@ -641,6 +683,16 @@ dependencies = [ | |||
| 641 | "version_check", | 683 | "version_check", |
| 642 | ] | 684 | ] |
| 643 | 685 | ||
| 686 | +[[package]] | ||
| 687 | +name = "core-foundation" | ||
| 688 | +version = "0.10.1" | ||
| 689 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 690 | +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" | ||
| 691 | +dependencies = [ | ||
| 692 | + "core-foundation-sys", | ||
| 693 | + "libc", | ||
| 694 | +] | ||
| 695 | + | ||
| 644 | [[package]] | 696 | [[package]] |
| 645 | name = "core-foundation-sys" | 697 | name = "core-foundation-sys" |
| 646 | version = "0.8.7" | 698 | version = "0.8.7" |
| @@ -923,6 +975,12 @@ version = "2.0.2" | |||
| 923 | source = "registry+https://github.com/rust-lang/crates.io-index" | 975 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 924 | checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc" | 976 | checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc" |
| 925 | 977 | ||
| 978 | +[[package]] | ||
| 979 | +name = "dunce" | ||
| 980 | +version = "1.0.5" | ||
| 981 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 982 | +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" | ||
| 983 | + | ||
| 926 | [[package]] | 984 | [[package]] |
| 927 | name = "ed25519" | 985 | name = "ed25519" |
| 928 | version = "3.0.0" | 986 | version = "3.0.0" |
| @@ -1131,6 +1189,12 @@ dependencies = [ | |||
| 1131 | "windows-sys 0.59.0", | 1189 | "windows-sys 0.59.0", |
| 1132 | ] | 1190 | ] |
| 1133 | 1191 | ||
| 1192 | +[[package]] | ||
| 1193 | +name = "fs_extra" | ||
| 1194 | +version = "1.3.0" | ||
| 1195 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1196 | +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" | ||
| 1197 | + | ||
| 1134 | [[package]] | 1198 | [[package]] |
| 1135 | name = "funty" | 1199 | name = "funty" |
| 1136 | version = "2.0.0" | 1200 | version = "2.0.0" |
| @@ -1511,6 +1575,22 @@ dependencies = [ | |||
| 1511 | "pin-project-lite", | 1575 | "pin-project-lite", |
| 1512 | "smallvec", | 1576 | "smallvec", |
| 1513 | "tokio", | 1577 | "tokio", |
| 1578 | + "want", | ||
| 1579 | +] | ||
| 1580 | + | ||
| 1581 | +[[package]] | ||
| 1582 | +name = "hyper-rustls" | ||
| 1583 | +version = "0.27.10" | ||
| 1584 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1585 | +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" | ||
| 1586 | +dependencies = [ | ||
| 1587 | + "http", | ||
| 1588 | + "hyper", | ||
| 1589 | + "hyper-util", | ||
| 1590 | + "rustls", | ||
| 1591 | + "tokio", | ||
| 1592 | + "tokio-rustls", | ||
| 1593 | + "tower-service", | ||
| 1514 | ] | 1594 | ] |
| 1515 | 1595 | ||
| 1516 | [[package]] | 1596 | [[package]] |
| @@ -1519,12 +1599,22 @@ version = "0.1.21" | |||
| 1519 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1599 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1520 | checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" | 1600 | checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" |
| 1521 | dependencies = [ | 1601 | dependencies = [ |
| 1602 | + "base64 0.23.1", | ||
| 1522 | "bytes", | 1603 | "bytes", |
| 1604 | + "futures-channel", | ||
| 1605 | + "futures-util", | ||
| 1523 | "http", | 1606 | "http", |
| 1524 | "http-body", | 1607 | "http-body", |
| 1608 | + "httparse", | ||
| 1525 | "hyper", | 1609 | "hyper", |
| 1610 | + "ipnet", | ||
| 1611 | + "libc", | ||
| 1612 | + "percent-encoding", | ||
| 1526 | "pin-project-lite", | 1613 | "pin-project-lite", |
| 1614 | + "socket2", | ||
| 1527 | "tokio", | 1615 | "tokio", |
| 1616 | + "tower-service", | ||
| 1617 | + "tracing", | ||
| 1528 | ] | 1618 | ] |
| 1529 | 1619 | ||
| 1530 | [[package]] | 1620 | [[package]] |
| @@ -1773,6 +1863,7 @@ dependencies = [ | |||
| 1773 | "http", | 1863 | "http", |
| 1774 | "im-core", | 1864 | "im-core", |
| 1775 | "qrcode", | 1865 | "qrcode", |
| 1866 | + "reqwest", | ||
| 1776 | "serde", | 1867 | "serde", |
| 1777 | "serde_json", | 1868 | "serde_json", |
| 1778 | "sha2 0.11.1", | 1869 | "sha2 0.11.1", |
| @@ -1948,6 +2039,55 @@ version = "0.1.9" | |||
| 1948 | source = "registry+https://github.com/rust-lang/crates.io-index" | 2039 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1949 | checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" | 2040 | checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" |
| 1950 | 2041 | ||
| 2042 | +[[package]] | ||
| 2043 | +name = "jni" | ||
| 2044 | +version = "0.22.4" | ||
| 2045 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2046 | +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" | ||
| 2047 | +dependencies = [ | ||
| 2048 | + "cfg-if", | ||
| 2049 | + "combine", | ||
| 2050 | + "jni-macros", | ||
| 2051 | + "jni-sys", | ||
| 2052 | + "log", | ||
| 2053 | + "simd_cesu8", | ||
| 2054 | + "thiserror", | ||
| 2055 | + "walkdir", | ||
| 2056 | + "windows-link", | ||
| 2057 | +] | ||
| 2058 | + | ||
| 2059 | +[[package]] | ||
| 2060 | +name = "jni-macros" | ||
| 2061 | +version = "0.22.4" | ||
| 2062 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2063 | +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" | ||
| 2064 | +dependencies = [ | ||
| 2065 | + "proc-macro2", | ||
| 2066 | + "quote", | ||
| 2067 | + "rustc_version", | ||
| 2068 | + "simd_cesu8", | ||
| 2069 | + "syn 2.0.119", | ||
| 2070 | +] | ||
| 2071 | + | ||
| 2072 | +[[package]] | ||
| 2073 | +name = "jni-sys" | ||
| 2074 | +version = "0.4.1" | ||
| 2075 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2076 | +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" | ||
| 2077 | +dependencies = [ | ||
| 2078 | + "jni-sys-macros", | ||
| 2079 | +] | ||
| 2080 | + | ||
| 2081 | +[[package]] | ||
| 2082 | +name = "jni-sys-macros" | ||
| 2083 | +version = "0.4.1" | ||
| 2084 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2085 | +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" | ||
| 2086 | +dependencies = [ | ||
| 2087 | + "quote", | ||
| 2088 | + "syn 2.0.119", | ||
| 2089 | +] | ||
| 2090 | + | ||
| 1951 | [[package]] | 2091 | [[package]] |
| 1952 | name = "jobserver" | 2092 | name = "jobserver" |
| 1953 | version = "0.1.35" | 2093 | version = "0.1.35" |
| @@ -2119,6 +2259,12 @@ dependencies = [ | |||
| 2119 | "hashbrown 0.16.1", | 2259 | "hashbrown 0.16.1", |
| 2120 | ] | 2260 | ] |
| 2121 | 2261 | ||
| 2262 | +[[package]] | ||
| 2263 | +name = "lru-slab" | ||
| 2264 | +version = "0.1.3" | ||
| 2265 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2266 | +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" | ||
| 2267 | + | ||
| 2122 | [[package]] | 2268 | [[package]] |
| 2123 | name = "lz4_flex" | 2269 | name = "lz4_flex" |
| 2124 | version = "0.13.1" | 2270 | version = "0.13.1" |
| @@ -2372,6 +2518,12 @@ version = "0.3.1" | |||
| 2372 | source = "registry+https://github.com/rust-lang/crates.io-index" | 2518 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2373 | checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" | 2519 | checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" |
| 2374 | 2520 | ||
| 2521 | +[[package]] | ||
| 2522 | +name = "openssl-probe" | ||
| 2523 | +version = "0.2.2" | ||
| 2524 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2525 | +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" | ||
| 2526 | + | ||
| 2375 | [[package]] | 2527 | [[package]] |
| 2376 | name = "ordered-float" | 2528 | name = "ordered-float" |
| 2377 | version = "5.5.1" | 2529 | version = "5.5.1" |
| @@ -2684,6 +2836,63 @@ version = "2.0.1" | |||
| 2684 | source = "registry+https://github.com/rust-lang/crates.io-index" | 2836 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2685 | checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" | 2837 | checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" |
| 2686 | 2838 | ||
| 2839 | +[[package]] | ||
| 2840 | +name = "quinn" | ||
| 2841 | +version = "0.11.12" | ||
| 2842 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2843 | +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" | ||
| 2844 | +dependencies = [ | ||
| 2845 | + "bytes", | ||
| 2846 | + "cfg_aliases", | ||
| 2847 | + "pin-project-lite", | ||
| 2848 | + "quinn-proto", | ||
| 2849 | + "quinn-udp", | ||
| 2850 | + "rustc-hash 2.1.3", | ||
| 2851 | + "rustls", | ||
| 2852 | + "socket2", | ||
| 2853 | + "thiserror", | ||
| 2854 | + "tokio", | ||
| 2855 | + "tracing", | ||
| 2856 | + "web-time", | ||
| 2857 | +] | ||
| 2858 | + | ||
| 2859 | +[[package]] | ||
| 2860 | +name = "quinn-proto" | ||
| 2861 | +version = "0.11.19" | ||
| 2862 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2863 | +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" | ||
| 2864 | +dependencies = [ | ||
| 2865 | + "aws-lc-rs", | ||
| 2866 | + "bytes", | ||
| 2867 | + "getrandom 0.4.3", | ||
| 2868 | + "lru-slab", | ||
| 2869 | + "rand 0.10.3", | ||
| 2870 | + "rand_pcg 0.10.2", | ||
| 2871 | + "ring", | ||
| 2872 | + "rustc-hash 2.1.3", | ||
| 2873 | + "rustls", | ||
| 2874 | + "rustls-pki-types", | ||
| 2875 | + "slab", | ||
| 2876 | + "thiserror", | ||
| 2877 | + "tinyvec", | ||
| 2878 | + "tracing", | ||
| 2879 | + "web-time", | ||
| 2880 | +] | ||
| 2881 | + | ||
| 2882 | +[[package]] | ||
| 2883 | +name = "quinn-udp" | ||
| 2884 | +version = "0.5.16" | ||
| 2885 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2886 | +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" | ||
| 2887 | +dependencies = [ | ||
| 2888 | + "cfg_aliases", | ||
| 2889 | + "libc", | ||
| 2890 | + "once_cell", | ||
| 2891 | + "socket2", | ||
| 2892 | + "tracing", | ||
| 2893 | + "windows-sys 0.61.2", | ||
| 2894 | +] | ||
| 2895 | + | ||
| 2687 | [[package]] | 2896 | [[package]] |
| 2688 | name = "quote" | 2897 | name = "quote" |
| 2689 | version = "1.0.47" | 2898 | version = "1.0.47" |
| @@ -2802,6 +3011,15 @@ dependencies = [ | |||
| 2802 | "rand_core 0.6.4", | 3011 | "rand_core 0.6.4", |
| 2803 | ] | 3012 | ] |
| 2804 | 3013 | ||
| 3014 | +[[package]] | ||
| 3015 | +name = "rand_pcg" | ||
| 3016 | +version = "0.10.2" | ||
| 3017 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3018 | +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" | ||
| 3019 | +dependencies = [ | ||
| 3020 | + "rand_core 0.10.1", | ||
| 3021 | +] | ||
| 3022 | + | ||
| 2805 | [[package]] | 3023 | [[package]] |
| 2806 | name = "rapidhash" | 3024 | name = "rapidhash" |
| 2807 | version = "4.5.1" | 3025 | version = "4.5.1" |
| @@ -2889,6 +3107,57 @@ version = "0.8.11" | |||
| 2889 | source = "registry+https://github.com/rust-lang/crates.io-index" | 3107 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2890 | checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" | 3108 | checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" |
| 2891 | 3109 | ||
| 3110 | +[[package]] | ||
| 3111 | +name = "reqwest" | ||
| 3112 | +version = "0.13.5" | ||
| 3113 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3114 | +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" | ||
| 3115 | +dependencies = [ | ||
| 3116 | + "base64 0.23.1", | ||
| 3117 | + "bytes", | ||
| 3118 | + "futures-core", | ||
| 3119 | + "http", | ||
| 3120 | + "http-body", | ||
| 3121 | + "http-body-util", | ||
| 3122 | + "hyper", | ||
| 3123 | + "hyper-rustls", | ||
| 3124 | + "hyper-util", | ||
| 3125 | + "js-sys", | ||
| 3126 | + "log", | ||
| 3127 | + "percent-encoding", | ||
| 3128 | + "pin-project-lite", | ||
| 3129 | + "quinn", | ||
| 3130 | + "rustls", | ||
| 3131 | + "rustls-pki-types", | ||
| 3132 | + "rustls-platform-verifier", | ||
| 3133 | + "serde", | ||
| 3134 | + "serde_urlencoded", | ||
| 3135 | + "sync_wrapper", | ||
| 3136 | + "tokio", | ||
| 3137 | + "tokio-rustls", | ||
| 3138 | + "tower", | ||
| 3139 | + "tower-http", | ||
| 3140 | + "tower-service", | ||
| 3141 | + "url", | ||
| 3142 | + "wasm-bindgen", | ||
| 3143 | + "wasm-bindgen-futures", | ||
| 3144 | + "web-sys", | ||
| 3145 | +] | ||
| 3146 | + | ||
| 3147 | +[[package]] | ||
| 3148 | +name = "ring" | ||
| 3149 | +version = "0.17.14" | ||
| 3150 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3151 | +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" | ||
| 3152 | +dependencies = [ | ||
| 3153 | + "cc", | ||
| 3154 | + "cfg-if", | ||
| 3155 | + "getrandom 0.2.17", | ||
| 3156 | + "libc", | ||
| 3157 | + "untrusted", | ||
| 3158 | + "windows-sys 0.52.0", | ||
| 3159 | +] | ||
| 3160 | + | ||
| 2892 | [[package]] | 3161 | [[package]] |
| 2893 | name = "roaring" | 3162 | name = "roaring" |
| 2894 | version = "0.11.5" | 3163 | version = "0.11.5" |
| @@ -2966,6 +3235,81 @@ dependencies = [ | |||
| 2966 | "windows-sys 0.61.2", | 3235 | "windows-sys 0.61.2", |
| 2967 | ] | 3236 | ] |
| 2968 | 3237 | ||
| 3238 | +[[package]] | ||
| 3239 | +name = "rustls" | ||
| 3240 | +version = "0.23.46" | ||
| 3241 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3242 | +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" | ||
| 3243 | +dependencies = [ | ||
| 3244 | + "aws-lc-rs", | ||
| 3245 | + "once_cell", | ||
| 3246 | + "rustls-pki-types", | ||
| 3247 | + "rustls-webpki", | ||
| 3248 | + "subtle", | ||
| 3249 | + "zeroize", | ||
| 3250 | +] | ||
| 3251 | + | ||
| 3252 | +[[package]] | ||
| 3253 | +name = "rustls-native-certs" | ||
| 3254 | +version = "0.8.5" | ||
| 3255 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3256 | +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" | ||
| 3257 | +dependencies = [ | ||
| 3258 | + "openssl-probe", | ||
| 3259 | + "rustls-pki-types", | ||
| 3260 | + "schannel", | ||
| 3261 | + "security-framework", | ||
| 3262 | +] | ||
| 3263 | + | ||
| 3264 | +[[package]] | ||
| 3265 | +name = "rustls-pki-types" | ||
| 3266 | +version = "1.15.1" | ||
| 3267 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3268 | +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" | ||
| 3269 | +dependencies = [ | ||
| 3270 | + "web-time", | ||
| 3271 | + "zeroize", | ||
| 3272 | +] | ||
| 3273 | + | ||
| 3274 | +[[package]] | ||
| 3275 | +name = "rustls-platform-verifier" | ||
| 3276 | +version = "0.7.1" | ||
| 3277 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3278 | +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" | ||
| 3279 | +dependencies = [ | ||
| 3280 | + "core-foundation", | ||
| 3281 | + "core-foundation-sys", | ||
| 3282 | + "jni", | ||
| 3283 | + "log", | ||
| 3284 | + "once_cell", | ||
| 3285 | + "rustls", | ||
| 3286 | + "rustls-native-certs", | ||
| 3287 | + "rustls-platform-verifier-android", | ||
| 3288 | + "rustls-webpki", | ||
| 3289 | + "security-framework", | ||
| 3290 | + "security-framework-sys", | ||
| 3291 | + "webpki-root-certs", | ||
| 3292 | + "windows-sys 0.61.2", | ||
| 3293 | +] | ||
| 3294 | + | ||
| 3295 | +[[package]] | ||
| 3296 | +name = "rustls-platform-verifier-android" | ||
| 3297 | +version = "0.2.0" | ||
| 3298 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3299 | +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" | ||
| 3300 | + | ||
| 3301 | +[[package]] | ||
| 3302 | +name = "rustls-webpki" | ||
| 3303 | +version = "0.103.16" | ||
| 3304 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3305 | +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" | ||
| 3306 | +dependencies = [ | ||
| 3307 | + "aws-lc-rs", | ||
| 3308 | + "ring", | ||
| 3309 | + "rustls-pki-types", | ||
| 3310 | + "untrusted", | ||
| 3311 | +] | ||
| 3312 | + | ||
| 2969 | [[package]] | 3313 | [[package]] |
| 2970 | name = "rustversion" | 3314 | name = "rustversion" |
| 2971 | version = "1.0.23" | 3315 | version = "1.0.23" |
| @@ -2978,6 +3322,24 @@ version = "1.0.23" | |||
| 2978 | source = "registry+https://github.com/rust-lang/crates.io-index" | 3322 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2979 | checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" | 3323 | checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" |
| 2980 | 3324 | ||
| 3325 | +[[package]] | ||
| 3326 | +name = "same-file" | ||
| 3327 | +version = "1.0.6" | ||
| 3328 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3329 | +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" | ||
| 3330 | +dependencies = [ | ||
| 3331 | + "winapi-util", | ||
| 3332 | +] | ||
| 3333 | + | ||
| 3334 | +[[package]] | ||
| 3335 | +name = "schannel" | ||
| 3336 | +version = "0.1.30" | ||
| 3337 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3338 | +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" | ||
| 3339 | +dependencies = [ | ||
| 3340 | + "windows-sys 0.61.2", | ||
| 3341 | +] | ||
| 3342 | + | ||
| 2981 | [[package]] | 3343 | [[package]] |
| 2982 | name = "scoped-tls" | 3344 | name = "scoped-tls" |
| 2983 | version = "1.0.1" | 3345 | version = "1.0.1" |
| @@ -2990,6 +3352,29 @@ version = "1.2.0" | |||
| 2990 | source = "registry+https://github.com/rust-lang/crates.io-index" | 3352 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2991 | checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" | 3353 | checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" |
| 2992 | 3354 | ||
| 3355 | +[[package]] | ||
| 3356 | +name = "security-framework" | ||
| 3357 | +version = "3.7.0" | ||
| 3358 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3359 | +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" | ||
| 3360 | +dependencies = [ | ||
| 3361 | + "bitflags 2.13.2", | ||
| 3362 | + "core-foundation", | ||
| 3363 | + "core-foundation-sys", | ||
| 3364 | + "libc", | ||
| 3365 | + "security-framework-sys", | ||
| 3366 | +] | ||
| 3367 | + | ||
| 3368 | +[[package]] | ||
| 3369 | +name = "security-framework-sys" | ||
| 3370 | +version = "2.17.0" | ||
| 3371 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3372 | +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" | ||
| 3373 | +dependencies = [ | ||
| 3374 | + "core-foundation-sys", | ||
| 3375 | + "libc", | ||
| 3376 | +] | ||
| 3377 | + | ||
| 2993 | [[package]] | 3378 | [[package]] |
| 2994 | name = "semver" | 3379 | name = "semver" |
| 2995 | version = "1.0.28" | 3380 | version = "1.0.28" |
| @@ -3156,7 +3541,7 @@ dependencies = [ | |||
| 3156 | "owo-colors", | 3541 | "owo-colors", |
| 3157 | "rand 0.8.8", | 3542 | "rand 0.8.8", |
| 3158 | "rand_core 0.6.4", | 3543 | "rand_core 0.6.4", |
| 3159 | - "rand_pcg", | 3544 | + "rand_pcg 0.3.1", |
| 3160 | "scoped-tls", | 3545 | "scoped-tls", |
| 3161 | "smallvec", | 3546 | "smallvec", |
| 3162 | "tracing", | 3547 | "tracing", |
| @@ -3187,6 +3572,16 @@ version = "0.3.10" | |||
| 3187 | source = "registry+https://github.com/rust-lang/crates.io-index" | 3572 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 3188 | checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" | 3573 | checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" |
| 3189 | 3574 | ||
| 3575 | +[[package]] | ||
| 3576 | +name = "simd_cesu8" | ||
| 3577 | +version = "1.2.0" | ||
| 3578 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3579 | +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" | ||
| 3580 | +dependencies = [ | ||
| 3581 | + "rustc_version", | ||
| 3582 | + "simdutf8", | ||
| 3583 | +] | ||
| 3584 | + | ||
| 3190 | [[package]] | 3585 | [[package]] |
| 3191 | name = "simdutf8" | 3586 | name = "simdutf8" |
| 3192 | version = "0.1.5" | 3587 | version = "0.1.5" |
| @@ -3319,6 +3714,15 @@ dependencies = [ | |||
| 3319 | "unicode-ident", | 3714 | "unicode-ident", |
| 3320 | ] | 3715 | ] |
| 3321 | 3716 | ||
| 3717 | +[[package]] | ||
| 3718 | +name = "sync_wrapper" | ||
| 3719 | +version = "1.0.2" | ||
| 3720 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3721 | +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" | ||
| 3722 | +dependencies = [ | ||
| 3723 | + "futures-core", | ||
| 3724 | +] | ||
| 3725 | + | ||
| 3322 | [[package]] | 3726 | [[package]] |
| 3323 | name = "synstructure" | 3727 | name = "synstructure" |
| 3324 | version = "0.14.0" | 3728 | version = "0.14.0" |
| @@ -3567,6 +3971,12 @@ dependencies = [ | |||
| 3567 | "zerovec", | 3971 | "zerovec", |
| 3568 | ] | 3972 | ] |
| 3569 | 3973 | ||
| 3974 | +[[package]] | ||
| 3975 | +name = "tinyvec" | ||
| 3976 | +version = "1.13.3" | ||
| 3977 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3978 | +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" | ||
| 3979 | + | ||
| 3570 | [[package]] | 3980 | [[package]] |
| 3571 | name = "tokio" | 3981 | name = "tokio" |
| 3572 | version = "1.54.1" | 3982 | version = "1.54.1" |
| @@ -3594,6 +4004,16 @@ dependencies = [ | |||
| 3594 | "syn 3.0.9", | 4004 | "syn 3.0.9", |
| 3595 | ] | 4005 | ] |
| 3596 | 4006 | ||
| 4007 | +[[package]] | ||
| 4008 | +name = "tokio-rustls" | ||
| 4009 | +version = "0.26.6" | ||
| 4010 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4011 | +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" | ||
| 4012 | +dependencies = [ | ||
| 4013 | + "rustls", | ||
| 4014 | + "tokio", | ||
| 4015 | +] | ||
| 4016 | + | ||
| 3597 | [[package]] | 4017 | [[package]] |
| 3598 | name = "tokio-tungstenite" | 4018 | name = "tokio-tungstenite" |
| 3599 | version = "0.29.0" | 4019 | version = "0.29.0" |
| @@ -4001,6 +4421,51 @@ dependencies = [ | |||
| 4001 | "topcoat-view-grammar", | 4421 | "topcoat-view-grammar", |
| 4002 | ] | 4422 | ] |
| 4003 | 4423 | ||
| 4424 | +[[package]] | ||
| 4425 | +name = "tower" | ||
| 4426 | +version = "0.5.3" | ||
| 4427 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4428 | +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" | ||
| 4429 | +dependencies = [ | ||
| 4430 | + "futures-core", | ||
| 4431 | + "futures-util", | ||
| 4432 | + "pin-project-lite", | ||
| 4433 | + "sync_wrapper", | ||
| 4434 | + "tokio", | ||
| 4435 | + "tower-layer", | ||
| 4436 | + "tower-service", | ||
| 4437 | +] | ||
| 4438 | + | ||
| 4439 | +[[package]] | ||
| 4440 | +name = "tower-http" | ||
| 4441 | +version = "0.6.11" | ||
| 4442 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4443 | +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" | ||
| 4444 | +dependencies = [ | ||
| 4445 | + "bitflags 2.13.2", | ||
| 4446 | + "bytes", | ||
| 4447 | + "futures-util", | ||
| 4448 | + "http", | ||
| 4449 | + "http-body", | ||
| 4450 | + "pin-project-lite", | ||
| 4451 | + "tower", | ||
| 4452 | + "tower-layer", | ||
| 4453 | + "tower-service", | ||
| 4454 | + "url", | ||
| 4455 | +] | ||
| 4456 | + | ||
| 4457 | +[[package]] | ||
| 4458 | +name = "tower-layer" | ||
| 4459 | +version = "0.3.3" | ||
| 4460 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4461 | +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" | ||
| 4462 | + | ||
| 4463 | +[[package]] | ||
| 4464 | +name = "tower-service" | ||
| 4465 | +version = "0.3.3" | ||
| 4466 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4467 | +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" | ||
| 4468 | + | ||
| 4004 | [[package]] | 4469 | [[package]] |
| 4005 | name = "tracing" | 4470 | name = "tracing" |
| 4006 | version = "0.1.44" | 4471 | version = "0.1.44" |
| @@ -4075,6 +4540,12 @@ dependencies = [ | |||
| 4075 | "tracing-log", | 4540 | "tracing-log", |
| 4076 | ] | 4541 | ] |
| 4077 | 4542 | ||
| 4543 | +[[package]] | ||
| 4544 | +name = "try-lock" | ||
| 4545 | +version = "0.2.5" | ||
| 4546 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4547 | +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" | ||
| 4548 | + | ||
| 4078 | [[package]] | 4549 | [[package]] |
| 4079 | name = "tungstenite" | 4550 | name = "tungstenite" |
| 4080 | version = "0.29.0" | 4551 | version = "0.29.0" |
| @@ -4384,6 +4855,24 @@ dependencies = [ | |||
| 4384 | "ctutils", | 4855 | "ctutils", |
| 4385 | ] | 4856 | ] |
| 4386 | 4857 | ||
| 4858 | +[[package]] | ||
| 4859 | +name = "untrusted" | ||
| 4860 | +version = "0.9.0" | ||
| 4861 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4862 | +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" | ||
| 4863 | + | ||
| 4864 | +[[package]] | ||
| 4865 | +name = "url" | ||
| 4866 | +version = "2.5.8" | ||
| 4867 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4868 | +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" | ||
| 4869 | +dependencies = [ | ||
| 4870 | + "form_urlencoded", | ||
| 4871 | + "idna", | ||
| 4872 | + "percent-encoding", | ||
| 4873 | + "serde", | ||
| 4874 | +] | ||
| 4875 | + | ||
| 4387 | [[package]] | 4876 | [[package]] |
| 4388 | name = "utf16_iter" | 4877 | name = "utf16_iter" |
| 4389 | version = "1.0.5" | 4878 | version = "1.0.5" |
| @@ -4433,6 +4922,25 @@ version = "0.9.5" | |||
| 4433 | source = "registry+https://github.com/rust-lang/crates.io-index" | 4922 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 4434 | checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" | 4923 | checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" |
| 4435 | 4924 | ||
| 4925 | +[[package]] | ||
| 4926 | +name = "walkdir" | ||
| 4927 | +version = "2.5.0" | ||
| 4928 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4929 | +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" | ||
| 4930 | +dependencies = [ | ||
| 4931 | + "same-file", | ||
| 4932 | + "winapi-util", | ||
| 4933 | +] | ||
| 4934 | + | ||
| 4935 | +[[package]] | ||
| 4936 | +name = "want" | ||
| 4937 | +version = "0.3.2" | ||
| 4938 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4939 | +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" | ||
| 4940 | +dependencies = [ | ||
| 4941 | + "try-lock", | ||
| 4942 | +] | ||
| 4943 | + | ||
| 4436 | [[package]] | 4944 | [[package]] |
| 4437 | name = "wasi" | 4945 | name = "wasi" |
| 4438 | version = "0.11.1+wasi-snapshot-preview1" | 4946 | version = "0.11.1+wasi-snapshot-preview1" |
| @@ -4461,6 +4969,17 @@ dependencies = [ | |||
| 4461 | "wasm-bindgen-shared", | 4969 | "wasm-bindgen-shared", |
| 4462 | ] | 4970 | ] |
| 4463 | 4971 | ||
| 4972 | +[[package]] | ||
| 4973 | +name = "wasm-bindgen-futures" | ||
| 4974 | +version = "0.4.79" | ||
| 4975 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4976 | +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" | ||
| 4977 | +dependencies = [ | ||
| 4978 | + "js-sys", | ||
| 4979 | + "tokio", | ||
| 4980 | + "wasm-bindgen", | ||
| 4981 | +] | ||
| 4982 | + | ||
| 4464 | [[package]] | 4983 | [[package]] |
| 4465 | name = "wasm-bindgen-macro" | 4984 | name = "wasm-bindgen-macro" |
| 4466 | version = "0.2.129" | 4985 | version = "0.2.129" |
| @@ -4493,6 +5012,16 @@ dependencies = [ | |||
| 4493 | "unicode-ident", | 5012 | "unicode-ident", |
| 4494 | ] | 5013 | ] |
| 4495 | 5014 | ||
| 5015 | +[[package]] | ||
| 5016 | +name = "web-sys" | ||
| 5017 | +version = "0.3.106" | ||
| 5018 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 5019 | +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" | ||
| 5020 | +dependencies = [ | ||
| 5021 | + "js-sys", | ||
| 5022 | + "wasm-bindgen", | ||
| 5023 | +] | ||
| 5024 | + | ||
| 4496 | [[package]] | 5025 | [[package]] |
| 4497 | name = "web-time" | 5026 | name = "web-time" |
| 4498 | version = "1.1.0" | 5027 | version = "1.1.0" |
| @@ -4503,6 +5032,15 @@ dependencies = [ | |||
| 4503 | "wasm-bindgen", | 5032 | "wasm-bindgen", |
| 4504 | ] | 5033 | ] |
| 4505 | 5034 | ||
| 5035 | +[[package]] | ||
| 5036 | +name = "webpki-root-certs" | ||
| 5037 | +version = "1.0.11" | ||
| 5038 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 5039 | +checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" | ||
| 5040 | +dependencies = [ | ||
| 5041 | + "rustls-pki-types", | ||
| 5042 | +] | ||
| 5043 | + | ||
| 4506 | [[package]] | 5044 | [[package]] |
| 4507 | name = "weezl" | 5045 | name = "weezl" |
| 4508 | version = "0.1.12" | 5046 | version = "0.1.12" |
| @@ -4537,6 +5075,15 @@ version = "0.4.0" | |||
| 4537 | source = "registry+https://github.com/rust-lang/crates.io-index" | 5075 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 4538 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" | 5076 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" |
| 4539 | 5077 | ||
| 5078 | +[[package]] | ||
| 5079 | +name = "winapi-util" | ||
| 5080 | +version = "0.1.11" | ||
| 5081 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 5082 | +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" | ||
| 5083 | +dependencies = [ | ||
| 5084 | + "windows-sys 0.61.2", | ||
| 5085 | +] | ||
| 5086 | + | ||
| 4540 | [[package]] | 5087 | [[package]] |
| 4541 | name = "winapi-x86_64-pc-windows-gnu" | 5088 | name = "winapi-x86_64-pc-windows-gnu" |
| 4542 | version = "0.4.0" | 5089 | version = "0.4.0" |
| @@ -4602,6 +5149,15 @@ dependencies = [ | |||
| 4602 | "windows-link", | 5149 | "windows-link", |
| 4603 | ] | 5150 | ] |
| 4604 | 5151 | ||
| 5152 | +[[package]] | ||
| 5153 | +name = "windows-sys" | ||
| 5154 | +version = "0.52.0" | ||
| 5155 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 5156 | +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" | ||
| 5157 | +dependencies = [ | ||
| 5158 | + "windows-targets", | ||
| 5159 | +] | ||
| 5160 | + | ||
| 4605 | [[package]] | 5161 | [[package]] |
| 4606 | name = "windows-sys" | 5162 | name = "windows-sys" |
| 4607 | version = "0.59.0" | 5163 | version = "0.59.0" |
Cargo.tomlmodified+1 -0
| @@ -23,6 +23,7 @@ image = { version = "0.25.10", default-features = false, features = ["png", "jpe | |||
| 23 | jiff = { version = "0.2.38", default-features = false, features = ["std", "tzdb-bundle-always"] } | 23 | jiff = { version = "0.2.38", default-features = false, features = ["std", "tzdb-bundle-always"] } |
| 24 | http = "1.5.0" | 24 | http = "1.5.0" |
| 25 | ipnet = "2.12.2" | 25 | ipnet = "2.12.2" |
| 26 | +reqwest = { version = "0.13.5", default-features = false, features = ["form", "rustls"] } | ||
| 26 | qrcode = { version = "0.14.1", default-features = false, features = ["svg"] } | 27 | qrcode = { version = "0.14.1", default-features = false, features = ["svg"] } |
| 27 | rand = "0.10.3" | 28 | rand = "0.10.3" |
| 28 | serde = { version = "1.0.229", features = ["derive"] } | 29 | serde = { version = "1.0.229", features = ["derive"] } |
crates/im-core/src/jwt.rsmodified+15 -0
| @@ -136,6 +136,21 @@ pub fn check_claims( | |||
| 136 | Ok(()) | 136 | Ok(()) |
| 137 | } | 137 | } |
| 138 | 138 | ||
| 139 | +/// Checks only the issuer: `iss` equals `issuer` exactly. For a caller that checks its own expiry | ||
| 140 | +/// (an ID token used as a logout hint may be expired) and its own audience. | ||
| 141 | +pub fn check_issuer(claims: &Map<String, Value>, issuer: &str) -> Result<(), JwtError> { | ||
| 142 | + if claims.get("iss").and_then(Value::as_str) == Some(issuer) { | ||
| 143 | + Ok(()) | ||
| 144 | + } else { | ||
| 145 | + Err(JwtError::Claim("iss")) | ||
| 146 | + } | ||
| 147 | +} | ||
| 148 | + | ||
| 149 | +/// The audience of a token when it is a single string. `None` for an array or a missing claim. | ||
| 150 | +pub fn single_audience(claims: &Map<String, Value>) -> Option<&str> { | ||
| 151 | + claims.get("aud").and_then(Value::as_str) | ||
| 152 | +} | ||
| 153 | + | ||
| 139 | fn audience_is(aud: Option<&Value>, expected: &str) -> bool { | 154 | fn audience_is(aud: Option<&Value>, expected: &str) -> bool { |
| 140 | match aud { | 155 | match aud { |
| 141 | Some(Value::String(one)) => one == expected, | 156 | Some(Value::String(one)) => one == expected, |
crates/im-core/src/model.rsmodified+14 -0
| @@ -64,6 +64,20 @@ pub mod amr { | |||
| 64 | pub const PASSWORD_TOTP: &str = "pwd otp"; | 64 | pub const PASSWORD_TOTP: &str = "pwd otp"; |
| 65 | /// Password and a recovery code. | 65 | /// Password and a recovery code. |
| 66 | pub const PASSWORD_RECOVERY: &str = "pwd rc"; | 66 | pub const PASSWORD_RECOVERY: &str = "pwd rc"; |
| 67 | + | ||
| 68 | + /// The RFC 8176 `amr` values of a stored method, for the ID token and the access token. | ||
| 69 | + /// | ||
| 70 | + /// The table keeps the short labels above, because its CHECK constraint names them. The tokens | ||
| 71 | + /// carry the standard values: TOTP is `pwd`, `otp` and `mfa`; a recovery code is `pwd` and `mfa` | ||
| 72 | + /// (a recovery code is a second factor that is not an OTP, so it is not `otp`). Anything else | ||
| 73 | + /// proved only the password. | ||
| 74 | + pub fn rfc8176(stored: &str) -> &'static [&'static str] { | ||
| 75 | + match stored { | ||
| 76 | + PASSWORD_TOTP => &["pwd", "otp", "mfa"], | ||
| 77 | + PASSWORD_RECOVERY => &["pwd", "mfa"], | ||
| 78 | + _ => &["pwd"], | ||
| 79 | + } | ||
| 80 | + } | ||
| 67 | } | 81 | } |
| 68 | 82 | ||
| 69 | /// A browser session. The cookie holds the token; the row holds only its hash. | 83 | /// A browser session. The cookie holds the token; the row holds only its hash. |
crates/im-core/src/store/backchannel.rsadded+453 -0
| @@ -0,0 +1,453 @@ | |||
| 1 | +//! The back-channel logout outbox (contracts.md 2.5): the rows that say which client must be told that | ||
| 2 | +//! an `im` session ended, and the reads and writes the delivery worker makes on them. | ||
| 3 | +//! | ||
| 4 | +//! A row is written in the same transaction as the session end it describes (`sessions.rs`, | ||
| 5 | +//! `users.rs`), so a logout never happens without its rows. Delivery is not here: the worker in | ||
| 6 | +//! `im-web/src/backchannel.rs` signs and posts them. A failed delivery never blocks the logout; it | ||
| 7 | +//! only leaves a row to be retried, and the row is abandoned after its retry window. | ||
| 8 | + | ||
| 9 | +use turso::Connection; | ||
| 10 | + | ||
| 11 | +use crate::error::Result; | ||
| 12 | +use crate::store::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id}; | ||
| 13 | + | ||
| 14 | +/// Why a session, or every session of a person, ended. The stored text is the `reason` column. | ||
| 15 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 16 | +pub enum EndReason { | ||
| 17 | + /// The person signed out (the sign-out button, or RP-initiated logout). | ||
| 18 | + Logout, | ||
| 19 | + /// The person ended a session on the sessions page. | ||
| 20 | + Revoked, | ||
| 21 | + /// The password changed, which ends every other session. | ||
| 22 | + PasswordChanged, | ||
| 23 | + /// The per-person session cap was reached and the oldest session made room. | ||
| 24 | + SessionLimit, | ||
| 25 | + /// A new sign-in in the same browser replaced its previous session. | ||
| 26 | + Replaced, | ||
| 27 | + /// The session reached its expiry and the sweeper removed it. | ||
| 28 | + Expired, | ||
| 29 | + /// The account was disabled. Sent as a `sub`-only logout, which covers every session of the person. | ||
| 30 | + Disabled, | ||
| 31 | +} | ||
| 32 | + | ||
| 33 | +impl EndReason { | ||
| 34 | + /// The stored text of the reason. | ||
| 35 | + pub fn as_str(self) -> &'static str { | ||
| 36 | + match self { | ||
| 37 | + EndReason::Logout => "logout", | ||
| 38 | + EndReason::Revoked => "revoked", | ||
| 39 | + EndReason::PasswordChanged => "password_changed", | ||
| 40 | + EndReason::SessionLimit => "session_limit", | ||
| 41 | + EndReason::Replaced => "replaced", | ||
| 42 | + EndReason::Expired => "expired", | ||
| 43 | + EndReason::Disabled => "disabled", | ||
| 44 | + } | ||
| 45 | + } | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +/// One row of the outbox, as the worker reads it. | ||
| 49 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 50 | +pub struct Delivery { | ||
| 51 | + /// ULID of the row. | ||
| 52 | + pub id: String, | ||
| 53 | + /// The client to tell. Its `backchannel_logout_uri` is read at delivery time. | ||
| 54 | + pub client_id: String, | ||
| 55 | + /// The `im` session that ended, or `None` for a `sub`-only logout. | ||
| 56 | + pub sid: Option<String>, | ||
| 57 | + /// The person. | ||
| 58 | + pub sub: String, | ||
| 59 | + /// Deliveries already tried. | ||
| 60 | + pub attempts: i64, | ||
| 61 | + /// When the row was queued. The retry window counts from here. | ||
| 62 | + pub created_at: String, | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +/// Every column of an outbox row, for inspection and tests. | ||
| 66 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 67 | +pub struct OutboxRow { | ||
| 68 | + /// ULID of the row. | ||
| 69 | + pub id: String, | ||
| 70 | + /// The client the logout is for. | ||
| 71 | + pub client_id: String, | ||
| 72 | + /// The session that ended, when the logout names one. | ||
| 73 | + pub sid: Option<String>, | ||
| 74 | + /// The person. | ||
| 75 | + pub sub: String, | ||
| 76 | + /// The stored [`EndReason::as_str`]. | ||
| 77 | + pub reason: String, | ||
| 78 | + /// `pending`, `sent`, `failed` or `abandoned`. | ||
| 79 | + pub state: String, | ||
| 80 | + /// Deliveries tried so far. | ||
| 81 | + pub attempts: i64, | ||
| 82 | + /// When the row is next due. | ||
| 83 | + pub next_attempt_at: String, | ||
| 84 | + /// The last failure, without secrets. | ||
| 85 | + pub last_error: Option<String>, | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +/// The columns of an outbox row, in the order [`map_row`] reads them. | ||
| 89 | +const ROW_COLS: &str = | ||
| 90 | + "id, client_id, sid, sub, reason, state, attempts, next_attempt_at, last_error"; | ||
| 91 | + | ||
| 92 | +fn map_row(row: &turso::Row) -> Result<OutboxRow> { | ||
| 93 | + Ok(OutboxRow { | ||
| 94 | + id: col_text(row, 0)?, | ||
| 95 | + client_id: col_text(row, 1)?, | ||
| 96 | + sid: col_opt_text(row, 2)?, | ||
| 97 | + sub: col_text(row, 3)?, | ||
| 98 | + reason: col_text(row, 4)?, | ||
| 99 | + state: col_text(row, 5)?, | ||
| 100 | + attempts: col_int(row, 6)?, | ||
| 101 | + next_attempt_at: col_text(row, 7)?, | ||
| 102 | + last_error: col_opt_text(row, 8)?, | ||
| 103 | + }) | ||
| 104 | +} | ||
| 105 | + | ||
| 106 | +/// Inserts one pending row. Runs inside the caller's transaction. | ||
| 107 | +async fn insert_row( | ||
| 108 | + conn: &Connection, | ||
| 109 | + client_id: &str, | ||
| 110 | + sid: Option<&str>, | ||
| 111 | + sub: &str, | ||
| 112 | + reason: EndReason, | ||
| 113 | + now: &str, | ||
| 114 | +) -> Result<()> { | ||
| 115 | + conn.execute( | ||
| 116 | + "INSERT INTO backchannel_outbox (id, client_id, sid, sub, reason, state, attempts, \ | ||
| 117 | + next_attempt_at, created_at) \ | ||
| 118 | + VALUES (?1, ?2, ?3, ?4, ?5, 'pending', 0, ?6, ?6)", | ||
| 119 | + ( | ||
| 120 | + new_id(), | ||
| 121 | + client_id.to_string(), | ||
| 122 | + sid.map(str::to_owned), | ||
| 123 | + sub.to_string(), | ||
| 124 | + reason.as_str().to_string(), | ||
| 125 | + now.to_string(), | ||
| 126 | + ), | ||
| 127 | + ) | ||
| 128 | + .await | ||
| 129 | + .map_err(db_err)?; | ||
| 130 | + Ok(()) | ||
| 131 | +} | ||
| 132 | + | ||
| 133 | +/// Queues a logout for every client the session signed into that has a back-channel URI. Runs inside | ||
| 134 | +/// the caller's transaction, before the session row is deleted (its client links cascade away). | ||
| 135 | +pub(crate) async fn queue_session( | ||
| 136 | + conn: &Connection, | ||
| 137 | + session_id: &str, | ||
| 138 | + user_id: &str, | ||
| 139 | + reason: EndReason, | ||
| 140 | + now: &str, | ||
| 141 | +) -> Result<()> { | ||
| 142 | + let clients = fetch_all( | ||
| 143 | + conn, | ||
| 144 | + "SELECT cs.client_id FROM client_sessions cs \ | ||
| 145 | + JOIN clients c ON c.id = cs.client_id \ | ||
| 146 | + WHERE cs.session_id = ?1 AND c.backchannel_logout_uri IS NOT NULL", | ||
| 147 | + (session_id.to_string(),), | ||
| 148 | + |row| col_text(row, 0), | ||
| 149 | + ) | ||
| 150 | + .await?; | ||
| 151 | + for client_id in clients { | ||
| 152 | + insert_row(conn, &client_id, Some(session_id), user_id, reason, now).await?; | ||
| 153 | + } | ||
| 154 | + Ok(()) | ||
| 155 | +} | ||
| 156 | + | ||
| 157 | +/// Queues a `sub`-only logout (contracts 2.5, "disable") for every client the person ever used: every | ||
| 158 | +/// client of a live session, and every client that holds one of the person's refresh tokens. Runs | ||
| 159 | +/// inside the caller's transaction, before the person's sessions are deleted. | ||
| 160 | +pub(crate) async fn queue_user( | ||
| 161 | + conn: &Connection, | ||
| 162 | + user_id: &str, | ||
| 163 | + reason: EndReason, | ||
| 164 | + now: &str, | ||
| 165 | +) -> Result<()> { | ||
| 166 | + let clients = fetch_all( | ||
| 167 | + conn, | ||
| 168 | + "SELECT id FROM clients WHERE backchannel_logout_uri IS NOT NULL AND id IN ( \ | ||
| 169 | + SELECT cs.client_id FROM client_sessions cs \ | ||
| 170 | + JOIN sessions s ON s.id = cs.session_id WHERE s.user_id = ?1 \ | ||
| 171 | + UNION SELECT client_id FROM refresh_tokens WHERE user_id = ?1)", | ||
| 172 | + (user_id.to_string(),), | ||
| 173 | + |row| col_text(row, 0), | ||
| 174 | + ) | ||
| 175 | + .await?; | ||
| 176 | + for client_id in clients { | ||
| 177 | + insert_row(conn, &client_id, None, user_id, reason, now).await?; | ||
| 178 | + } | ||
| 179 | + Ok(()) | ||
| 180 | +} | ||
| 181 | + | ||
| 182 | +/// The outcome the worker reports for one delivery. | ||
| 183 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 184 | +pub enum Attempt { | ||
| 185 | + /// The client answered 200 or 204. | ||
| 186 | + Delivered, | ||
| 187 | + /// The attempt failed; the row is due again at `next`. | ||
| 188 | + Retry { | ||
| 189 | + /// Total deliveries tried, including this one. | ||
| 190 | + attempts: i64, | ||
| 191 | + /// When to try again (UTC stamp). | ||
| 192 | + next: String, | ||
| 193 | + /// Why it failed, without secrets. | ||
| 194 | + error: String, | ||
| 195 | + }, | ||
| 196 | + /// The row is given up on; it is logged and never tried again. | ||
| 197 | + Abandon { | ||
| 198 | + /// Total deliveries tried, including this one. | ||
| 199 | + attempts: i64, | ||
| 200 | + /// Why it was given up. | ||
| 201 | + error: String, | ||
| 202 | + }, | ||
| 203 | +} | ||
| 204 | + | ||
| 205 | +impl Store { | ||
| 206 | + /// Pending rows that are due at `now`, oldest first, at most `limit`. | ||
| 207 | + pub async fn due_deliveries(&self, now: &str, limit: i64) -> Result<Vec<Delivery>> { | ||
| 208 | + let conn = self.read_conn().await; | ||
| 209 | + fetch_all( | ||
| 210 | + &conn, | ||
| 211 | + "SELECT id, client_id, sid, sub, attempts, created_at FROM backchannel_outbox \ | ||
| 212 | + WHERE state = 'pending' AND next_attempt_at <= ?1 \ | ||
| 213 | + ORDER BY next_attempt_at ASC, id ASC LIMIT ?2", | ||
| 214 | + (now.to_string(), limit), | ||
| 215 | + |row| { | ||
| 216 | + Ok(Delivery { | ||
| 217 | + id: col_text(row, 0)?, | ||
| 218 | + client_id: col_text(row, 1)?, | ||
| 219 | + sid: col_opt_text(row, 2)?, | ||
| 220 | + sub: col_text(row, 3)?, | ||
| 221 | + attempts: col_int(row, 4)?, | ||
| 222 | + created_at: col_text(row, 5)?, | ||
| 223 | + }) | ||
| 224 | + }, | ||
| 225 | + ) | ||
| 226 | + .await | ||
| 227 | + } | ||
| 228 | + | ||
| 229 | + /// Records the outcome of one delivery attempt on a row. | ||
| 230 | + pub async fn record_attempt(&self, id: &str, attempt: &Attempt, now: &str) -> Result<()> { | ||
| 231 | + let conn = self.inner.conn.lock().await; | ||
| 232 | + let changed = match attempt { | ||
| 233 | + Attempt::Delivered => { | ||
| 234 | + conn.execute( | ||
| 235 | + "UPDATE backchannel_outbox SET state = 'sent', done_at = ?2, last_error = NULL \ | ||
| 236 | + WHERE id = ?1 AND state = 'pending'", | ||
| 237 | + (id.to_string(), now.to_string()), | ||
| 238 | + ) | ||
| 239 | + .await | ||
| 240 | + } | ||
| 241 | + Attempt::Retry { | ||
| 242 | + attempts, | ||
| 243 | + next, | ||
| 244 | + error, | ||
| 245 | + } => { | ||
| 246 | + conn.execute( | ||
| 247 | + "UPDATE backchannel_outbox SET attempts = ?2, next_attempt_at = ?3, last_error = ?4 \ | ||
| 248 | + WHERE id = ?1 AND state = 'pending'", | ||
| 249 | + (id.to_string(), *attempts, next.clone(), error.clone()), | ||
| 250 | + ) | ||
| 251 | + .await | ||
| 252 | + } | ||
| 253 | + Attempt::Abandon { attempts, error } => { | ||
| 254 | + conn.execute( | ||
| 255 | + "UPDATE backchannel_outbox SET state = 'abandoned', attempts = ?2, last_error = ?3 \ | ||
| 256 | + WHERE id = ?1 AND state = 'pending'", | ||
| 257 | + (id.to_string(), *attempts, error.clone()), | ||
| 258 | + ) | ||
| 259 | + .await | ||
| 260 | + } | ||
| 261 | + }; | ||
| 262 | + changed.map_err(db_err)?; | ||
| 263 | + Ok(()) | ||
| 264 | + } | ||
| 265 | + | ||
| 266 | + /// Every outbox row, oldest first. For inspection and tests. | ||
| 267 | + pub async fn backchannel_rows(&self) -> Result<Vec<OutboxRow>> { | ||
| 268 | + let conn = self.read_conn().await; | ||
| 269 | + fetch_all( | ||
| 270 | + &conn, | ||
| 271 | + &format!("SELECT {ROW_COLS} FROM backchannel_outbox ORDER BY created_at ASC, id ASC"), | ||
| 272 | + (), | ||
| 273 | + map_row, | ||
| 274 | + ) | ||
| 275 | + .await | ||
| 276 | + } | ||
| 277 | + | ||
| 278 | + /// One outbox row by id, if it exists. | ||
| 279 | + pub async fn backchannel_row(&self, id: &str) -> Result<Option<OutboxRow>> { | ||
| 280 | + let conn = self.read_conn().await; | ||
| 281 | + fetch_opt( | ||
| 282 | + &conn, | ||
| 283 | + &format!("SELECT {ROW_COLS} FROM backchannel_outbox WHERE id = ?1"), | ||
| 284 | + (id.to_string(),), | ||
| 285 | + map_row, | ||
| 286 | + ) | ||
| 287 | + .await | ||
| 288 | + } | ||
| 289 | +} | ||
| 290 | + | ||
| 291 | +#[cfg(test)] | ||
| 292 | +mod tests { | ||
| 293 | + use std::time::Duration; | ||
| 294 | + | ||
| 295 | + use super::*; | ||
| 296 | + use crate::model::amr; | ||
| 297 | + use crate::store::clients::NewClient; | ||
| 298 | + use crate::store::oidc::{NewAuthCode, NewRefreshToken}; | ||
| 299 | + use crate::store::sessions::{NewSession, SESSION_IDLE}; | ||
| 300 | + use crate::time::stamp_after; | ||
| 301 | + use crate::token::hash_token; | ||
| 302 | + | ||
| 303 | + /// A store over a temp file, one person, two clients with back-channel URIs and one live session | ||
| 304 | + /// that both clients signed into. | ||
| 305 | + async fn fixture() -> (tempfile::TempDir, Store, String, String, Vec<String>) { | ||
| 306 | + let dir = tempfile::tempdir().expect("temp dir"); | ||
| 307 | + let store = Store::open(&dir.path().join("im.db")).await.expect("store"); | ||
| 308 | + let user = store | ||
| 309 | + .create_user("ada@example.com", "Ada", "hash", false) | ||
| 310 | + .await | ||
| 311 | + .expect("user"); | ||
| 312 | + let mut clients = Vec::new(); | ||
| 313 | + for key in ["in", "iz"] { | ||
| 314 | + let uri = format!("https://{key}.example.com/auth/backchannel-logout"); | ||
| 315 | + let client = store | ||
| 316 | + .create_client(&NewClient { | ||
| 317 | + name: key, | ||
| 318 | + secret_hash: "secret", | ||
| 319 | + redirect_uris: &[], | ||
| 320 | + post_logout_redirect_uris: &[], | ||
| 321 | + backchannel_logout_uri: Some(&uri), | ||
| 322 | + allowed_scopes: "openid", | ||
| 323 | + service_key: Some(key), | ||
| 324 | + }) | ||
| 325 | + .await | ||
| 326 | + .expect("client"); | ||
| 327 | + clients.push(client.id); | ||
| 328 | + } | ||
| 329 | + let session = store | ||
| 330 | + .create_session( | ||
| 331 | + &NewSession { | ||
| 332 | + user_id: &user.id, | ||
| 333 | + token_hash: "session-token", | ||
| 334 | + csrf_token: "csrf", | ||
| 335 | + amr: amr::PASSWORD, | ||
| 336 | + ip: None, | ||
| 337 | + user_agent: None, | ||
| 338 | + idle: SESSION_IDLE, | ||
| 339 | + max_age: Duration::from_secs(3600), | ||
| 340 | + }, | ||
| 341 | + 10, | ||
| 342 | + ) | ||
| 343 | + .await | ||
| 344 | + .expect("session") | ||
| 345 | + .session; | ||
| 346 | + for client in &clients { | ||
| 347 | + store | ||
| 348 | + .touch_client_session(&session.id, client) | ||
| 349 | + .await | ||
| 350 | + .expect("client session"); | ||
| 351 | + } | ||
| 352 | + (dir, store, user.id, session.id, clients) | ||
| 353 | + } | ||
| 354 | + | ||
| 355 | + #[tokio::test] | ||
| 356 | + async fn a_session_end_queues_one_row_per_client_and_revokes_its_refresh_tokens() { | ||
| 357 | + let (_dir, store, user_id, session_id, clients) = fixture().await; | ||
| 358 | + let expires = stamp_after(Duration::from_secs(60)); | ||
| 359 | + store | ||
| 360 | + .insert_auth_code(&NewAuthCode { | ||
| 361 | + code_hash: "code", | ||
| 362 | + client_id: &clients[0], | ||
| 363 | + user_id: &user_id, | ||
| 364 | + session_id: &session_id, | ||
| 365 | + redirect_uri: "https://in.example.com/auth/callback", | ||
| 366 | + scope: "openid", | ||
| 367 | + nonce: None, | ||
| 368 | + code_challenge: &"c".repeat(43), | ||
| 369 | + expires_at: &expires, | ||
| 370 | + }) | ||
| 371 | + .await | ||
| 372 | + .expect("code"); | ||
| 373 | + let refresh_expires = stamp_after(Duration::from_secs(3600)); | ||
| 374 | + assert!( | ||
| 375 | + store | ||
| 376 | + .redeem_auth_code( | ||
| 377 | + "code", | ||
| 378 | + &NewRefreshToken { | ||
| 379 | + id: "refresh-1", | ||
| 380 | + token_hash: &hash_token("refresh"), | ||
| 381 | + family_id: "refresh-1", | ||
| 382 | + client_id: &clients[0], | ||
| 383 | + user_id: &user_id, | ||
| 384 | + session_id: &session_id, | ||
| 385 | + code_hash: Some("code"), | ||
| 386 | + scope: "openid", | ||
| 387 | + expires_at: &refresh_expires, | ||
| 388 | + }, | ||
| 389 | + ) | ||
| 390 | + .await | ||
| 391 | + .expect("redeem") | ||
| 392 | + ); | ||
| 393 | + | ||
| 394 | + assert!( | ||
| 395 | + store | ||
| 396 | + .end_session(&user_id, &session_id, EndReason::Revoked) | ||
| 397 | + .await | ||
| 398 | + .expect("end") | ||
| 399 | + ); | ||
| 400 | + | ||
| 401 | + let rows = store.backchannel_rows().await.expect("rows"); | ||
| 402 | + assert_eq!(rows.len(), 2, "{rows:?}"); | ||
| 403 | + let mut row_clients: Vec<&str> = rows.iter().map(|r| r.client_id.as_str()).collect(); | ||
| 404 | + row_clients.sort_unstable(); | ||
| 405 | + let mut expected: Vec<&str> = clients.iter().map(String::as_str).collect(); | ||
| 406 | + expected.sort_unstable(); | ||
| 407 | + assert_eq!(row_clients, expected); | ||
| 408 | + for row in &rows { | ||
| 409 | + assert_eq!(row.sid.as_deref(), Some(session_id.as_str())); | ||
| 410 | + assert_eq!(row.sub, user_id); | ||
| 411 | + assert_eq!(row.reason, "revoked"); | ||
| 412 | + assert_eq!(row.state, "pending"); | ||
| 413 | + } | ||
| 414 | + assert!( | ||
| 415 | + store | ||
| 416 | + .refresh_token(&hash_token("refresh")) | ||
| 417 | + .await | ||
| 418 | + .expect("lookup") | ||
| 419 | + .is_none(), | ||
| 420 | + "the refresh token survived its session" | ||
| 421 | + ); | ||
| 422 | + } | ||
| 423 | + | ||
| 424 | + #[tokio::test] | ||
| 425 | + async fn disabling_an_account_queues_one_sub_only_row_per_client_and_ends_its_sessions() { | ||
| 426 | + let (_dir, store, user_id, session_id, _clients) = fixture().await; | ||
| 427 | + assert!(store.disable_user(&user_id).await.expect("disable")); | ||
| 428 | + assert!(!store.disable_user(&user_id).await.expect("again")); | ||
| 429 | + | ||
| 430 | + let rows = store.backchannel_rows().await.expect("rows"); | ||
| 431 | + assert_eq!(rows.len(), 2, "{rows:?}"); | ||
| 432 | + for row in &rows { | ||
| 433 | + assert_eq!(row.sid, None, "a disable is sub-only"); | ||
| 434 | + assert_eq!(row.sub, user_id); | ||
| 435 | + assert_eq!(row.reason, "disabled"); | ||
| 436 | + } | ||
| 437 | + assert!( | ||
| 438 | + store | ||
| 439 | + .backchannel_row(&rows[0].id) | ||
| 440 | + .await | ||
| 441 | + .expect("row") | ||
| 442 | + .is_some() | ||
| 443 | + ); | ||
| 444 | + assert!( | ||
| 445 | + store | ||
| 446 | + .session_by_token_hash("session-token") | ||
| 447 | + .await | ||
| 448 | + .expect("lookup") | ||
| 449 | + .is_none(), | ||
| 450 | + "session {session_id} survived the disable" | ||
| 451 | + ); | ||
| 452 | + } | ||
| 453 | +} | ||
crates/im-core/src/store/clients.rsmodified+14 -0
| @@ -120,6 +120,20 @@ impl Store { | |||
| 120 | .await | 120 | .await |
| 121 | } | 121 | } |
| 122 | 122 | ||
| 123 | + /// True when a registered client carries this family key, so the key names a known service. Machine | ||
| 124 | + /// tokens are issued only for known audiences (contracts.md 2.6). | ||
| 125 | + pub async fn family_key_known(&self, key: &str) -> Result<bool> { | ||
| 126 | + let conn = self.read_conn().await; | ||
| 127 | + let found = fetch_opt( | ||
| 128 | + &conn, | ||
| 129 | + "SELECT 1 FROM clients WHERE service_key = ?1", | ||
| 130 | + (key.to_string(),), | ||
| 131 | + |_row| Ok(()), | ||
| 132 | + ) | ||
| 133 | + .await?; | ||
| 134 | + Ok(found.is_some()) | ||
| 135 | + } | ||
| 136 | + | ||
| 123 | /// Disables a client. Returns false when there was no such client or it was already disabled. | 137 | /// Disables a client. Returns false when there was no such client or it was already disabled. |
| 124 | pub async fn disable_client(&self, id: &str) -> Result<bool> { | 138 | pub async fn disable_client(&self, id: &str) -> Result<bool> { |
| 125 | let conn = self.inner.conn.lock().await; | 139 | let conn = self.inner.conn.lock().await; |
crates/im-core/src/store/mod.rsmodified+1 -0
| @@ -7,6 +7,7 @@ | |||
| 7 | //! in effect are logged at boot. | 7 | //! in effect are logged at boot. |
| 8 | 8 | ||
| 9 | pub mod audit; | 9 | pub mod audit; |
| 10 | +pub mod backchannel; | ||
| 10 | pub mod clients; | 11 | pub mod clients; |
| 11 | pub mod directory; | 12 | pub mod directory; |
| 12 | pub mod keys; | 13 | pub mod keys; |
crates/im-core/src/store/sessions.rsmodified+104 -43
| @@ -15,6 +15,7 @@ use turso::Connection; | |||
| 15 | 15 | ||
| 16 | use crate::error::Result; | 16 | use crate::error::Result; |
| 17 | use crate::model::Session; | 17 | use crate::model::Session; |
| 18 | +use crate::store::backchannel::{self, EndReason}; | ||
| 18 | use crate::store::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id}; | 19 | use crate::store::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id}; |
| 19 | use crate::time::{now_stamp, stamp_after, stamp_before}; | 20 | use crate::time::{now_stamp, stamp_after, stamp_before}; |
| 20 | 21 | ||
| @@ -80,16 +81,15 @@ pub struct CreatedSession { | |||
| 80 | pub ended: Vec<String>, | 81 | pub ended: Vec<String>, |
| 81 | } | 82 | } |
| 82 | 83 | ||
| 83 | -/// Deletes the sessions of `user_id` matching `keep` (none keeps nothing), and returns their ids. | 84 | +/// The ids of the live sessions of `user_id` except `keep` (none keeps nothing), oldest first. |
| 84 | -/// Runs inside the caller's transaction. | 85 | +/// Only sessions that are still live count; expired rows are removed by the sweeper. |
| 85 | -async fn end_sessions( | 86 | +async fn live_session_ids( |
| 86 | conn: &Connection, | 87 | conn: &Connection, |
| 87 | user_id: &str, | 88 | user_id: &str, |
| 88 | keep: Option<&str>, | 89 | keep: Option<&str>, |
| 89 | now: &str, | 90 | now: &str, |
| 90 | ) -> Result<Vec<String>> { | 91 | ) -> Result<Vec<String>> { |
| 91 | - // Only sessions that were still live count as ended. Expired rows are removed by the sweeper. | 92 | + fetch_all( |
| 92 | - let ids = fetch_all( | ||
| 93 | conn, | 93 | conn, |
| 94 | "SELECT id FROM sessions WHERE user_id = ?1 AND expires_at > ?2 AND id IS NOT ?3 \ | 94 | "SELECT id FROM sessions WHERE user_id = ?1 AND expires_at > ?2 AND id IS NOT ?3 \ |
| 95 | ORDER BY created_at ASC, id ASC", | 95 | ORDER BY created_at ASC, id ASC", |
| @@ -100,13 +100,36 @@ async fn end_sessions( | |||
| 100 | ), | 100 | ), |
| 101 | |row| col_text(row, 0), | 101 | |row| col_text(row, 0), |
| 102 | ) | 102 | ) |
| 103 | - .await?; | 103 | + .await |
| 104 | - for id in &ids { | 104 | +} |
| 105 | - conn.execute("DELETE FROM sessions WHERE id = ?1", (id.clone(),)) | 105 | + |
| 106 | - .await | 106 | +/// Ends the given sessions of `user_id` inside the caller's transaction. For each one: the back-channel |
| 107 | - .map_err(db_err)?; | 107 | +/// logout rows of its clients are queued, its refresh tokens are revoked, and the row is deleted (its |
| 108 | +/// client links go with it). Every session end in the store goes through here, so no end skips its | ||
| 109 | +/// back-channel logout (contracts.md 2.5). | ||
| 110 | +pub(crate) async fn end_rows( | ||
| 111 | + conn: &Connection, | ||
| 112 | + user_id: &str, | ||
| 113 | + ids: &[String], | ||
| 114 | + reason: EndReason, | ||
| 115 | + now: &str, | ||
| 116 | +) -> Result<()> { | ||
| 117 | + for id in ids { | ||
| 118 | + backchannel::queue_session(conn, id, user_id, reason, now).await?; | ||
| 119 | + conn.execute( | ||
| 120 | + "UPDATE refresh_tokens SET revoked_at = ?2 WHERE session_id = ?1 AND revoked_at IS NULL", | ||
| 121 | + (id.clone(), now.to_string()), | ||
| 122 | + ) | ||
| 123 | + .await | ||
| 124 | + .map_err(db_err)?; | ||
| 125 | + conn.execute( | ||
| 126 | + "DELETE FROM sessions WHERE id = ?1 AND user_id = ?2", | ||
| 127 | + (id.clone(), user_id.to_string()), | ||
| 128 | + ) | ||
| 129 | + .await | ||
| 130 | + .map_err(db_err)?; | ||
| 108 | } | 131 | } |
| 109 | - Ok(ids) | 132 | + Ok(()) |
| 110 | } | 133 | } |
| 111 | 134 | ||
| 112 | impl Store { | 135 | impl Store { |
| @@ -159,13 +182,8 @@ impl Store { | |||
| 159 | .await?; | 182 | .await?; |
| 160 | // Room for the new one: at most cap - 1 live sessions may remain. | 183 | // Room for the new one: at most cap - 1 live sessions may remain. |
| 161 | let overflow = live.len().saturating_sub(cap - 1); | 184 | let overflow = live.len().saturating_sub(cap - 1); |
| 162 | - let mut ended = Vec::with_capacity(overflow); | 185 | + let ended: Vec<String> = live.into_iter().take(overflow).collect(); |
| 163 | - for id in live.into_iter().take(overflow) { | 186 | + end_rows(&tx, new.user_id, &ended, EndReason::SessionLimit, &now).await?; |
| 164 | - tx.execute("DELETE FROM sessions WHERE id = ?1", (id.clone(),)) | ||
| 165 | - .await | ||
| 166 | - .map_err(db_err)?; | ||
| 167 | - ended.push(id); | ||
| 168 | - } | ||
| 169 | tx.execute( | 187 | tx.execute( |
| 170 | "INSERT INTO sessions (id, user_id, token_hash, csrf_token, created_at, expires_at, \ | 188 | "INSERT INTO sessions (id, user_id, token_hash, csrf_token, created_at, expires_at, \ |
| 171 | last_seen_at, ip, user_agent, auth_time, amr, hard_expires_at) \ | 189 | last_seen_at, ip, user_agent, auth_time, amr, hard_expires_at) \ |
| @@ -286,51 +304,94 @@ impl Store { | |||
| 286 | .await | 304 | .await |
| 287 | } | 305 | } |
| 288 | 306 | ||
| 289 | - /// Ends one session, only if it belongs to `user_id`. Returns false when there was nothing to | 307 | + /// Ends one session, only if it belongs to `user_id`, with its back-channel logout. Returns false |
| 290 | - /// end, which is also the answer for another user's session: the caller cannot tell them apart. | 308 | + /// when there was nothing to end, which is also the answer for another user's session: the caller |
| 291 | - pub async fn end_session(&self, user_id: &str, session_id: &str) -> Result<bool> { | 309 | + /// cannot tell them apart. |
| 310 | + pub async fn end_session( | ||
| 311 | + &self, | ||
| 312 | + user_id: &str, | ||
| 313 | + session_id: &str, | ||
| 314 | + reason: EndReason, | ||
| 315 | + ) -> Result<bool> { | ||
| 292 | let conn = self.inner.conn.lock().await; | 316 | let conn = self.inner.conn.lock().await; |
| 293 | - let changed = conn | 317 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 294 | - .execute( | 318 | + let now = now_stamp(); |
| 295 | - "DELETE FROM sessions WHERE id = ?1 AND user_id = ?2", | 319 | + let outcome: Result<bool> = async { |
| 320 | + let owned = fetch_opt( | ||
| 321 | + &tx, | ||
| 322 | + "SELECT id FROM sessions WHERE id = ?1 AND user_id = ?2", | ||
| 296 | (session_id.to_string(), user_id.to_string()), | 323 | (session_id.to_string(), user_id.to_string()), |
| 324 | + |row| col_text(row, 0), | ||
| 297 | ) | 325 | ) |
| 298 | - .await | 326 | + .await?; |
| 299 | - .map_err(db_err)?; | 327 | + if owned.is_none() { |
| 300 | - Ok(changed == 1) | 328 | + return Ok(false); |
| 329 | + } | ||
| 330 | + end_rows(&tx, user_id, &[session_id.to_owned()], reason, &now).await?; | ||
| 331 | + Ok(true) | ||
| 332 | + } | ||
| 333 | + .await; | ||
| 334 | + finish(tx, outcome).await | ||
| 301 | } | 335 | } |
| 302 | 336 | ||
| 303 | - /// Ends every live session of `user_id` except `keep_session_id`. Returns the ids ended. | 337 | + /// Ends every live session of `user_id` except `keep_session_id`, with their back-channel logouts. |
| 338 | + /// Returns the ids ended. | ||
| 304 | pub async fn end_other_sessions( | 339 | pub async fn end_other_sessions( |
| 305 | &self, | 340 | &self, |
| 306 | user_id: &str, | 341 | user_id: &str, |
| 307 | keep_session_id: &str, | 342 | keep_session_id: &str, |
| 343 | + reason: EndReason, | ||
| 308 | ) -> Result<Vec<String>> { | 344 | ) -> Result<Vec<String>> { |
| 309 | - self.end_matching(user_id, Some(keep_session_id)).await | 345 | + self.end_matching(user_id, Some(keep_session_id), reason) |
| 310 | - } | 346 | + .await |
| 311 | - | ||
| 312 | - /// Ends every live session of `user_id`. Returns the ids ended. | ||
| 313 | - pub async fn end_all_sessions(&self, user_id: &str) -> Result<Vec<String>> { | ||
| 314 | - self.end_matching(user_id, None).await | ||
| 315 | } | 347 | } |
| 316 | 348 | ||
| 317 | - async fn end_matching(&self, user_id: &str, keep: Option<&str>) -> Result<Vec<String>> { | 349 | + async fn end_matching( |
| 350 | + &self, | ||
| 351 | + user_id: &str, | ||
| 352 | + keep: Option<&str>, | ||
| 353 | + reason: EndReason, | ||
| 354 | + ) -> Result<Vec<String>> { | ||
| 318 | let conn = self.inner.conn.lock().await; | 355 | let conn = self.inner.conn.lock().await; |
| 319 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; | 356 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 320 | let now = now_stamp(); | 357 | let now = now_stamp(); |
| 321 | - let outcome: Result<Vec<String>> = end_sessions(&tx, user_id, keep, &now).await; | 358 | + let outcome: Result<Vec<String>> = async { |
| 359 | + let ids = live_session_ids(&tx, user_id, keep, &now).await?; | ||
| 360 | + end_rows(&tx, user_id, &ids, reason, &now).await?; | ||
| 361 | + Ok(ids) | ||
| 362 | + } | ||
| 363 | + .await; | ||
| 322 | finish(tx, outcome).await | 364 | finish(tx, outcome).await |
| 323 | } | 365 | } |
| 324 | 366 | ||
| 325 | - /// Deletes the sessions that have expired. Returns how many were removed. Run by the sweeper. | 367 | + /// Deletes the sessions that have expired, queuing their back-channel logouts first. Returns how |
| 368 | + /// many were removed. Run by the sweeper. | ||
| 326 | pub async fn sweep_expired_sessions(&self) -> Result<u64> { | 369 | pub async fn sweep_expired_sessions(&self) -> Result<u64> { |
| 327 | let conn = self.inner.conn.lock().await; | 370 | let conn = self.inner.conn.lock().await; |
| 328 | - conn.execute( | 371 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 329 | - "DELETE FROM sessions WHERE expires_at <= ?1", | 372 | + let now = now_stamp(); |
| 330 | - (now_stamp(),), | 373 | + let outcome: Result<u64> = async { |
| 331 | - ) | 374 | + let expired = fetch_all( |
| 332 | - .await | 375 | + &tx, |
| 333 | - .map_err(db_err) | 376 | + "SELECT id, user_id FROM sessions WHERE expires_at <= ?1", |
| 377 | + (now.clone(),), | ||
| 378 | + |row| Ok((col_text(row, 0)?, col_text(row, 1)?)), | ||
| 379 | + ) | ||
| 380 | + .await?; | ||
| 381 | + for (id, user_id) in &expired { | ||
| 382 | + end_rows( | ||
| 383 | + &tx, | ||
| 384 | + user_id, | ||
| 385 | + std::slice::from_ref(id), | ||
| 386 | + EndReason::Expired, | ||
| 387 | + &now, | ||
| 388 | + ) | ||
| 389 | + .await?; | ||
| 390 | + } | ||
| 391 | + Ok(expired.len() as u64) | ||
| 392 | + } | ||
| 393 | + .await; | ||
| 394 | + finish(tx, outcome).await | ||
| 334 | } | 395 | } |
| 335 | } | 396 | } |
| 336 | 397 | ||
crates/im-core/src/store/users.rsmodified+43 -0
| @@ -16,6 +16,7 @@ use turso::{Connection, Row}; | |||
| 16 | 16 | ||
| 17 | use crate::error::{Error, Result}; | 17 | use crate::error::{Error, Result}; |
| 18 | use crate::model::User; | 18 | use crate::model::User; |
| 19 | +use crate::store::backchannel::{self, EndReason}; | ||
| 19 | use crate::store::directory::{ChangeKind, record_change}; | 20 | use crate::store::directory::{ChangeKind, record_change}; |
| 20 | use crate::store::{ | 21 | use crate::store::{ |
| 21 | Store, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_opt, finish, new_id, | 22 | Store, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_opt, finish, new_id, |
| @@ -295,6 +296,48 @@ impl Store { | |||
| 295 | Ok(()) | 296 | Ok(()) |
| 296 | } | 297 | } |
| 297 | 298 | ||
| 299 | + /// Disables an account. In one transaction: the account is marked disabled, the directory feed | ||
| 300 | + /// records the change, one `sub`-only back-channel logout is queued for every client the person | ||
| 301 | + /// used (contracts.md 2.5), the refresh tokens are revoked and every session is deleted. Returns | ||
| 302 | + /// false, with nothing changed, when the account is missing or already disabled. | ||
| 303 | + pub async fn disable_user(&self, user_id: &str) -> Result<bool> { | ||
| 304 | + let now = now_stamp(); | ||
| 305 | + let conn = self.inner.conn.lock().await; | ||
| 306 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | ||
| 307 | + let outcome: Result<bool> = async { | ||
| 308 | + let changed = tx | ||
| 309 | + .execute( | ||
| 310 | + "UPDATE users SET disabled_at = ?2, updated_at = ?2 \ | ||
| 311 | + WHERE id = ?1 AND disabled_at IS NULL", | ||
| 312 | + (user_id.to_string(), now.clone()), | ||
| 313 | + ) | ||
| 314 | + .await | ||
| 315 | + .map_err(db_err)?; | ||
| 316 | + if changed != 1 { | ||
| 317 | + return Ok(false); | ||
| 318 | + } | ||
| 319 | + record_change(&tx, user_id, ChangeKind::Member).await?; | ||
| 320 | + // Queued before the sessions go, because the client links are read from them. | ||
| 321 | + backchannel::queue_user(&tx, user_id, EndReason::Disabled, &now).await?; | ||
| 322 | + tx.execute( | ||
| 323 | + "UPDATE refresh_tokens SET revoked_at = ?2 WHERE user_id = ?1 AND revoked_at IS NULL", | ||
| 324 | + (user_id.to_string(), now.clone()), | ||
| 325 | + ) | ||
| 326 | + .await | ||
| 327 | + .map_err(db_err)?; | ||
| 328 | + // No per-session rows here: the sub-only row above covers every session of the person. | ||
| 329 | + tx.execute( | ||
| 330 | + "DELETE FROM sessions WHERE user_id = ?1", | ||
| 331 | + (user_id.to_string(),), | ||
| 332 | + ) | ||
| 333 | + .await | ||
| 334 | + .map_err(db_err)?; | ||
| 335 | + Ok(true) | ||
| 336 | + } | ||
| 337 | + .await; | ||
| 338 | + finish(tx, outcome).await | ||
| 339 | + } | ||
| 340 | + | ||
| 298 | /// Holds a sealed TOTP secret while its enrolment waits for a confirming code. Replaces an | 341 | /// Holds a sealed TOTP secret while its enrolment waits for a confirming code. Replaces an |
| 299 | /// earlier unconfirmed secret of the same user. The user row is not touched. | 342 | /// earlier unconfirmed secret of the same user. The user row is not touched. |
| 300 | pub async fn set_totp_pending(&self, user_id: &str, sealed_secret: &str) -> Result<()> { | 343 | pub async fn set_totp_pending(&self, user_id: &str, sealed_secret: &str) -> Result<()> { |
crates/im-web/Cargo.tomlmodified+2 -1
| @@ -15,10 +15,11 @@ futures-util.workspace = true | |||
| 15 | http.workspace = true | 15 | http.workspace = true |
| 16 | im-core.workspace = true | 16 | im-core.workspace = true |
| 17 | qrcode.workspace = true | 17 | qrcode.workspace = true |
| 18 | +reqwest.workspace = true | ||
| 18 | serde.workspace = true | 19 | serde.workspace = true |
| 19 | serde_json.workspace = true | 20 | serde_json.workspace = true |
| 20 | # `net` and `signal` for the listener and the shutdown signals, `time` for the database probe timeout. | 21 | # `net` and `signal` for the listener and the shutdown signals, `time` for the database probe timeout. |
| 21 | -tokio = { workspace = true, features = ["net", "signal", "time"] } | 22 | +tokio = { workspace = true, features = ["net", "signal", "time", "io-util"] } |
| 22 | topcoat.workspace = true | 23 | topcoat.workspace = true |
| 23 | tracing.workspace = true | 24 | tracing.workspace = true |
| 24 | tracing-subscriber = { workspace = true, features = ["env-filter"] } | 25 | tracing-subscriber = { workspace = true, features = ["env-filter"] } |
crates/im-web/src/auth.rsmodified+10 -6
| @@ -11,6 +11,7 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH}; | |||
| 11 | use im_core::model::{Session, User, amr}; | 11 | use im_core::model::{Session, User, amr}; |
| 12 | use im_core::secret; | 12 | use im_core::secret; |
| 13 | use im_core::store::Store; | 13 | use im_core::store::Store; |
| 14 | +use im_core::store::backchannel::EndReason; | ||
| 14 | use im_core::store::sessions::{NewSession, SESSION_IDLE}; | 15 | use im_core::store::sessions::{NewSession, SESSION_IDLE}; |
| 15 | use im_core::token::{constant_time_eq, generate_token, hash_token}; | 16 | use im_core::token::{constant_time_eq, generate_token, hash_token}; |
| 16 | use im_core::totp; | 17 | use im_core::totp; |
| @@ -150,7 +151,10 @@ pub async fn start_session(cx: &Cx, user: &User, amr: &str) -> Result<Session> { | |||
| 150 | .await? | 151 | .await? |
| 151 | .filter(|old| old.user_id == user.id) | 152 | .filter(|old| old.user_id == user.id) |
| 152 | { | 153 | { |
| 153 | - state.store.end_session(&user.id, &old.id).await?; | 154 | + state |
| 155 | + .store | ||
| 156 | + .end_session(&user.id, &old.id, EndReason::Replaced) | ||
| 157 | + .await?; | ||
| 154 | } | 158 | } |
| 155 | let token = generate_token(); | 159 | let token = generate_token(); |
| 156 | let csrf = generate_token(); | 160 | let csrf = generate_token(); |
| @@ -172,8 +176,7 @@ pub async fn start_session(cx: &Cx, user: &User, amr: &str) -> Result<Session> { | |||
| 172 | state.config.policy.max_sessions, | 176 | state.config.policy.max_sessions, |
| 173 | ) | 177 | ) |
| 174 | .await?; | 178 | .await?; |
| 175 | - // Sessions ended by the cap are not signed out elsewhere yet; their back-channel logout is queued | 179 | + // Sessions ended by the cap were queued for back-channel logout in the store's transaction. |
| 176 | - // once the OpenID provider exists. | ||
| 177 | state.live.bump(&Topic::Account(user.id.clone())); | 180 | state.live.bump(&Topic::Account(user.id.clone())); |
| 178 | // The browser keeps the cookie for the hard cap; the server decides the real expiry. | 181 | // The browser keeps the cookie for the hard cap; the server decides the real expiry. |
| 179 | let cookie_age = time::Duration::seconds(i64::try_from(max_age.as_secs()).unwrap_or(i64::MAX)); | 182 | let cookie_age = time::Duration::seconds(i64::try_from(max_age.as_secs()).unwrap_or(i64::MAX)); |
| @@ -189,12 +192,13 @@ pub async fn start_session(cx: &Cx, user: &User, amr: &str) -> Result<Session> { | |||
| 189 | Ok(created.session) | 192 | Ok(created.session) |
| 190 | } | 193 | } |
| 191 | 194 | ||
| 192 | -/// Ends the session of `viewer` and clears its cookie. Other sessions of the person are untouched. | 195 | +/// Ends the session of `viewer` (with its back-channel logouts) and clears its cookie. Other sessions of |
| 193 | -pub async fn end_current_session(cx: &Cx, viewer: &Viewer) -> Result<()> { | 196 | +/// the person are untouched. |
| 197 | +pub async fn end_current_session(cx: &Cx, viewer: &Viewer, reason: EndReason) -> Result<()> { | ||
| 194 | let state = app_context::<AppState>(cx); | 198 | let state = app_context::<AppState>(cx); |
| 195 | state | 199 | state |
| 196 | .store | 200 | .store |
| 197 | - .end_session(&viewer.user.id, &viewer.session.id) | 201 | + .end_session(&viewer.user.id, &viewer.session.id, reason) |
| 198 | .await?; | 202 | .await?; |
| 199 | state.live.bump(&Topic::Account(viewer.user.id.clone())); | 203 | state.live.bump(&Topic::Account(viewer.user.id.clone())); |
| 200 | jar(cx).remove(Cookie::build((SESSION_COOKIE, "")).path("/")); | 204 | jar(cx).remove(Cookie::build((SESSION_COOKIE, "")).path("/")); |
crates/im-web/src/backchannel.rsadded+375 -0
| @@ -0,0 +1,375 @@ | |||
| 1 | +//! The back-channel logout worker (contracts.md 2.5). It delivers the outbox rows that `im-core` queued | ||
| 2 | +//! when an `im` session ended: it signs a logout token for each row and POSTs it to the client's | ||
| 3 | +//! `backchannel_logout_uri` as the form field `logout_token`. | ||
| 4 | +//! | ||
| 5 | +//! A delivery is done on `200` or `204`. Anything else, or no answer within ten seconds, is a failure and | ||
| 6 | +//! the row is retried after the backoff of contracts.md 2.5 (10 s, 30 s, 1 min, 5 min, then every 15 min) | ||
| 7 | +//! until 24 hours after the row was queued; then it is abandoned and logged. Redirects are never | ||
| 8 | +//! followed. A failure never affects the logout that queued the row: that already committed. | ||
| 9 | +//! | ||
| 10 | +//! The token carries `iss`, `aud` (the client), `iat`, `exp` (two minutes), a fresh `jti`, the logout | ||
| 11 | +//! `events`, `sub` and `sid` (when the row names a session). It carries no `nonce`. | ||
| 12 | + | ||
| 13 | +use std::sync::Arc; | ||
| 14 | +use std::time::Duration; | ||
| 15 | + | ||
| 16 | +use im_core::model::Client; | ||
| 17 | +use im_core::store::Store; | ||
| 18 | +use im_core::store::backchannel::{Attempt, Delivery}; | ||
| 19 | +use im_core::time::{now_stamp, stamp_after, stamp_plus, unix_now}; | ||
| 20 | +use im_core::token::generate_token; | ||
| 21 | +use serde_json::{Value, json}; | ||
| 22 | +use tokio::sync::watch; | ||
| 23 | + | ||
| 24 | +use crate::oidc::signing; | ||
| 25 | + | ||
| 26 | +/// The event name of a logout token (OpenID Back-Channel Logout 1.0). | ||
| 27 | +pub const LOGOUT_EVENT: &str = "http://schemas.openid.net/event/backchannel-logout"; | ||
| 28 | + | ||
| 29 | +/// How long a client has to answer one delivery. | ||
| 30 | +pub const DELIVERY_TIMEOUT: Duration = Duration::from_secs(10); | ||
| 31 | + | ||
| 32 | +/// Lifetime of a logout token, in seconds (contracts.md 2.5: two minutes). | ||
| 33 | +const LOGOUT_TOKEN_TTL: i64 = 2 * 60; | ||
| 34 | + | ||
| 35 | +/// How long a row is retried before it is abandoned (contracts.md 2.5: 24 hours). | ||
| 36 | +pub const RETRY_WINDOW: Duration = Duration::from_secs(24 * 60 * 60); | ||
| 37 | + | ||
| 38 | +/// How often the worker looks for due rows. | ||
| 39 | +const TICK: Duration = Duration::from_secs(5); | ||
| 40 | + | ||
| 41 | +/// The most rows one pass delivers. | ||
| 42 | +const BATCH: i64 = 20; | ||
| 43 | + | ||
| 44 | +/// How long to wait before the next try after `failures` failed tries (contracts.md 2.5). | ||
| 45 | +pub fn backoff(failures: i64) -> Duration { | ||
| 46 | + match failures { | ||
| 47 | + 1 => Duration::from_secs(10), | ||
| 48 | + 2 => Duration::from_secs(30), | ||
| 49 | + 3 => Duration::from_secs(60), | ||
| 50 | + 4 => Duration::from_secs(5 * 60), | ||
| 51 | + _ => Duration::from_secs(15 * 60), | ||
| 52 | + } | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +/// The HTTP client of the worker: ten-second timeouts and no redirects, so a logout is never sent | ||
| 56 | +/// to another host. | ||
| 57 | +pub fn http_client() -> reqwest::Client { | ||
| 58 | + reqwest::Client::builder() | ||
| 59 | + .redirect(reqwest::redirect::Policy::none()) | ||
| 60 | + .timeout(DELIVERY_TIMEOUT) | ||
| 61 | + .connect_timeout(DELIVERY_TIMEOUT) | ||
| 62 | + .build() | ||
| 63 | + .expect("the back-channel HTTP client can be built with fixed settings") | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +/// Runs [`process_due`] every few seconds until `stop` is set. Failures are logged and the next pass | ||
| 67 | +/// tries again. | ||
| 68 | +pub fn spawn( | ||
| 69 | + store: Store, | ||
| 70 | + key: Arc<[u8; 32]>, | ||
| 71 | + issuer: String, | ||
| 72 | + mut stop: watch::Receiver<bool>, | ||
| 73 | +) -> tokio::task::JoinHandle<()> { | ||
| 74 | + tokio::spawn(async move { | ||
| 75 | + let http = http_client(); | ||
| 76 | + loop { | ||
| 77 | + tokio::select! { | ||
| 78 | + () = tokio::time::sleep(TICK) => {} | ||
| 79 | + _ = stop.wait_for(|stopped| *stopped) => break, | ||
| 80 | + } | ||
| 81 | + if let Err(error) = process_due(&store, &key, &issuer, &http, &now_stamp()).await { | ||
| 82 | + tracing::error!(error = %error, "back-channel pass failed"); | ||
| 83 | + } | ||
| 84 | + } | ||
| 85 | + }) | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +/// Delivers every row due at `now`, oldest first, and records each outcome. Returns how many rows were | ||
| 89 | +/// attempted. | ||
| 90 | +pub async fn process_due( | ||
| 91 | + store: &Store, | ||
| 92 | + key: &[u8; 32], | ||
| 93 | + issuer: &str, | ||
| 94 | + http: &reqwest::Client, | ||
| 95 | + now: &str, | ||
| 96 | +) -> im_core::Result<usize> { | ||
| 97 | + let due = store.due_deliveries(now, BATCH).await?; | ||
| 98 | + for job in &due { | ||
| 99 | + let attempt = deliver(store, key, issuer, http, job).await; | ||
| 100 | + match &attempt { | ||
| 101 | + Attempt::Delivered => tracing::info!(row = %job.id, "back-channel logout delivered"), | ||
| 102 | + Attempt::Retry { | ||
| 103 | + attempts, | ||
| 104 | + next, | ||
| 105 | + error, | ||
| 106 | + } => tracing::warn!( | ||
| 107 | + row = %job.id, attempts, next = %next, error = %error, | ||
| 108 | + "back-channel logout failed; retry scheduled" | ||
| 109 | + ), | ||
| 110 | + Attempt::Abandon { attempts, error } => tracing::error!( | ||
| 111 | + row = %job.id, attempts, error = %error, | ||
| 112 | + "back-channel logout abandoned" | ||
| 113 | + ), | ||
| 114 | + } | ||
| 115 | + store | ||
| 116 | + .record_attempt(&job.id, &attempt, &now_stamp()) | ||
| 117 | + .await?; | ||
| 118 | + } | ||
| 119 | + Ok(due.len()) | ||
| 120 | +} | ||
| 121 | + | ||
| 122 | +/// One attempt for one row. Every failure path returns an [`Attempt`]; nothing here is fatal. | ||
| 123 | +async fn deliver( | ||
| 124 | + store: &Store, | ||
| 125 | + key: &[u8; 32], | ||
| 126 | + issuer: &str, | ||
| 127 | + http: &reqwest::Client, | ||
| 128 | + job: &Delivery, | ||
| 129 | +) -> Attempt { | ||
| 130 | + let attempts = job.attempts + 1; | ||
| 131 | + let client = match store.client_by_id(&job.client_id).await { | ||
| 132 | + Ok(Some(client)) => client, | ||
| 133 | + Ok(None) => return abandon(attempts, "the client no longer exists"), | ||
| 134 | + Err(error) => return failure(job, attempts, &error.to_string()), | ||
| 135 | + }; | ||
| 136 | + let Some(uri) = client.backchannel_logout_uri.clone() else { | ||
| 137 | + return abandon(attempts, "the client has no back-channel logout URI"); | ||
| 138 | + }; | ||
| 139 | + let token = match logout_token(store, key, issuer, &client, job).await { | ||
| 140 | + Ok(token) => token, | ||
| 141 | + Err(error) => return failure(job, attempts, &error.to_string()), | ||
| 142 | + }; | ||
| 143 | + match http | ||
| 144 | + .post(&uri) | ||
| 145 | + .form(&[("logout_token", token.as_str())]) | ||
| 146 | + .send() | ||
| 147 | + .await | ||
| 148 | + { | ||
| 149 | + Ok(response) if matches!(response.status().as_u16(), 200 | 204) => Attempt::Delivered, | ||
| 150 | + Ok(response) => failure( | ||
| 151 | + job, | ||
| 152 | + attempts, | ||
| 153 | + &format!("the client answered {}", response.status()), | ||
| 154 | + ), | ||
| 155 | + Err(error) => failure(job, attempts, &describe(&error)), | ||
| 156 | + } | ||
| 157 | +} | ||
| 158 | + | ||
| 159 | +/// A failed attempt: retried after the backoff, or abandoned when the retry window has passed. | ||
| 160 | +fn failure(job: &Delivery, attempts: i64, error: &str) -> Attempt { | ||
| 161 | + let window_over = | ||
| 162 | + stamp_plus(&job.created_at, RETRY_WINDOW).is_none_or(|deadline| now_stamp() >= deadline); | ||
| 163 | + if window_over { | ||
| 164 | + return abandon(attempts, &format!("{error}; given up after 24 hours")); | ||
| 165 | + } | ||
| 166 | + Attempt::Retry { | ||
| 167 | + attempts, | ||
| 168 | + next: stamp_after(backoff(attempts)), | ||
| 169 | + error: error.to_owned(), | ||
| 170 | + } | ||
| 171 | +} | ||
| 172 | + | ||
| 173 | +fn abandon(attempts: i64, error: &str) -> Attempt { | ||
| 174 | + Attempt::Abandon { | ||
| 175 | + attempts, | ||
| 176 | + error: error.to_owned(), | ||
| 177 | + } | ||
| 178 | +} | ||
| 179 | + | ||
| 180 | +/// A short description of a transport error, for the log and the row. Never the token. | ||
| 181 | +fn describe(error: &reqwest::Error) -> String { | ||
| 182 | + if error.is_timeout() { | ||
| 183 | + "the client did not answer within 10 seconds".to_owned() | ||
| 184 | + } else if error.is_connect() { | ||
| 185 | + "the client could not be reached".to_owned() | ||
| 186 | + } else { | ||
| 187 | + "the delivery failed".to_owned() | ||
| 188 | + } | ||
| 189 | +} | ||
| 190 | + | ||
| 191 | +/// Signs the logout token of one row for `client` (contracts.md 2.5). | ||
| 192 | +async fn logout_token( | ||
| 193 | + store: &Store, | ||
| 194 | + key: &[u8; 32], | ||
| 195 | + issuer: &str, | ||
| 196 | + client: &Client, | ||
| 197 | + job: &Delivery, | ||
| 198 | +) -> im_core::Result<String> { | ||
| 199 | + let now = unix_now(); | ||
| 200 | + let mut claims = json!({ | ||
| 201 | + "iss": issuer, | ||
| 202 | + "aud": client.id, | ||
| 203 | + "iat": now, | ||
| 204 | + "exp": now + LOGOUT_TOKEN_TTL, | ||
| 205 | + "jti": generate_token(), | ||
| 206 | + "events": { LOGOUT_EVENT: {} }, | ||
| 207 | + "sub": job.sub, | ||
| 208 | + }); | ||
| 209 | + if let (Some(sid), Some(object)) = (&job.sid, claims.as_object_mut()) { | ||
| 210 | + object.insert("sid".into(), Value::String(sid.clone())); | ||
| 211 | + } | ||
| 212 | + signing::sign(store, key, &claims).await | ||
| 213 | +} | ||
| 214 | + | ||
| 215 | +#[cfg(test)] | ||
| 216 | +mod tests { | ||
| 217 | + use super::*; | ||
| 218 | + use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; | ||
| 219 | + use im_core::model::amr; | ||
| 220 | + use im_core::store::backchannel::EndReason; | ||
| 221 | + use im_core::store::clients::NewClient; | ||
| 222 | + use im_core::store::sessions::{NewSession, SESSION_IDLE}; | ||
| 223 | + use im_core::time::stamp_after; | ||
| 224 | + use tokio::io::{AsyncReadExt, AsyncWriteExt}; | ||
| 225 | + use tokio::net::{TcpListener, TcpStream}; | ||
| 226 | + | ||
| 227 | + /// Reads one HTTP request from `stream` and returns its body. | ||
| 228 | + async fn read_body(stream: &mut TcpStream) -> String { | ||
| 229 | + let mut buf = Vec::new(); | ||
| 230 | + let mut chunk = [0u8; 1024]; | ||
| 231 | + loop { | ||
| 232 | + let n = stream.read(&mut chunk).await.expect("read"); | ||
| 233 | + if n == 0 { | ||
| 234 | + break; | ||
| 235 | + } | ||
| 236 | + buf.extend_from_slice(&chunk[..n]); | ||
| 237 | + if let Some(head_end) = buf.windows(4).position(|w| w == b"\r\n\r\n") { | ||
| 238 | + let head = String::from_utf8_lossy(&buf[..head_end]).to_ascii_lowercase(); | ||
| 239 | + let length = head | ||
| 240 | + .lines() | ||
| 241 | + .find_map(|line| line.strip_prefix("content-length:")) | ||
| 242 | + .and_then(|value| value.trim().parse::<usize>().ok()) | ||
| 243 | + .unwrap_or(0); | ||
| 244 | + if buf.len() >= head_end + 4 + length { | ||
| 245 | + return String::from_utf8_lossy(&buf[head_end + 4..head_end + 4 + length]) | ||
| 246 | + .into_owned(); | ||
| 247 | + } | ||
| 248 | + } | ||
| 249 | + } | ||
| 250 | + String::from_utf8_lossy(&buf).into_owned() | ||
| 251 | + } | ||
| 252 | + | ||
| 253 | + /// A local server that answers successive connections with the given statuses. Returns its URL and | ||
| 254 | + /// a handle that yields the request bodies it received. | ||
| 255 | + async fn server(statuses: Vec<u16>) -> (String, tokio::task::JoinHandle<Vec<String>>) { | ||
| 256 | + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); | ||
| 257 | + let addr = listener.local_addr().expect("address"); | ||
| 258 | + let handle = tokio::spawn(async move { | ||
| 259 | + let mut bodies = Vec::new(); | ||
| 260 | + for status in statuses { | ||
| 261 | + let (mut stream, _) = listener.accept().await.expect("accept"); | ||
| 262 | + bodies.push(read_body(&mut stream).await); | ||
| 263 | + let answer = format!( | ||
| 264 | + "HTTP/1.1 {status} test\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" | ||
| 265 | + ); | ||
| 266 | + stream.write_all(answer.as_bytes()).await.expect("write"); | ||
| 267 | + } | ||
| 268 | + bodies | ||
| 269 | + }); | ||
| 270 | + (format!("http://{addr}/auth/backchannel-logout"), handle) | ||
| 271 | + } | ||
| 272 | + | ||
| 273 | + #[tokio::test] | ||
| 274 | + async fn a_failed_delivery_is_retried_until_the_client_answers() { | ||
| 275 | + let (_dir, state) = crate::boot::test_state().await; | ||
| 276 | + signing::maintain(&state.store, &state.key) | ||
| 277 | + .await | ||
| 278 | + .expect("signing key"); | ||
| 279 | + let (uri, received) = server(vec![500, 200]).await; | ||
| 280 | + let client = state | ||
| 281 | + .store | ||
| 282 | + .create_client(&NewClient { | ||
| 283 | + name: "Board", | ||
| 284 | + secret_hash: "secret", | ||
| 285 | + redirect_uris: &[], | ||
| 286 | + post_logout_redirect_uris: &[], | ||
| 287 | + backchannel_logout_uri: Some(&uri), | ||
| 288 | + allowed_scopes: "openid", | ||
| 289 | + service_key: Some("iz"), | ||
| 290 | + }) | ||
| 291 | + .await | ||
| 292 | + .expect("client"); | ||
| 293 | + let user = state | ||
| 294 | + .store | ||
| 295 | + .create_user("ada@example.com", "Ada", "hash", false) | ||
| 296 | + .await | ||
| 297 | + .expect("user"); | ||
| 298 | + let session = state | ||
| 299 | + .store | ||
| 300 | + .create_session( | ||
| 301 | + &NewSession { | ||
| 302 | + user_id: &user.id, | ||
| 303 | + token_hash: "token", | ||
| 304 | + csrf_token: "csrf", | ||
| 305 | + amr: amr::PASSWORD, | ||
| 306 | + ip: None, | ||
| 307 | + user_agent: None, | ||
| 308 | + idle: SESSION_IDLE, | ||
| 309 | + max_age: std::time::Duration::from_secs(3600), | ||
| 310 | + }, | ||
| 311 | + 10, | ||
| 312 | + ) | ||
| 313 | + .await | ||
| 314 | + .expect("session") | ||
| 315 | + .session; | ||
| 316 | + state | ||
| 317 | + .store | ||
| 318 | + .touch_client_session(&session.id, &client.id) | ||
| 319 | + .await | ||
| 320 | + .expect("client session"); | ||
| 321 | + assert!( | ||
| 322 | + state | ||
| 323 | + .store | ||
| 324 | + .end_session(&user.id, &session.id, EndReason::Logout) | ||
| 325 | + .await | ||
| 326 | + .expect("end") | ||
| 327 | + ); | ||
| 328 | + let http = http_client(); | ||
| 329 | + let issuer = state.config.base_url.clone(); | ||
| 330 | + | ||
| 331 | + // The first pass meets the 500: the row waits for its first backoff. | ||
| 332 | + let first = process_due(&state.store, &state.key, &issuer, &http, &now_stamp()) | ||
| 333 | + .await | ||
| 334 | + .expect("first pass"); | ||
| 335 | + assert_eq!(first, 1); | ||
| 336 | + let row = state.store.backchannel_rows().await.expect("rows")[0].clone(); | ||
| 337 | + assert_eq!(row.state, "pending"); | ||
| 338 | + assert_eq!(row.attempts, 1); | ||
| 339 | + assert!( | ||
| 340 | + row.last_error.as_deref().is_some_and(|e| e.contains("500")), | ||
| 341 | + "{:?}", | ||
| 342 | + row.last_error | ||
| 343 | + ); | ||
| 344 | + | ||
| 345 | + // Once the backoff has passed, the second pass gets the 200. | ||
| 346 | + let later = stamp_after(std::time::Duration::from_secs(60)); | ||
| 347 | + assert_eq!( | ||
| 348 | + process_due(&state.store, &state.key, &issuer, &http, &later) | ||
| 349 | + .await | ||
| 350 | + .expect("second pass"), | ||
| 351 | + 1 | ||
| 352 | + ); | ||
| 353 | + let row = state | ||
| 354 | + .store | ||
| 355 | + .backchannel_row(&row.id) | ||
| 356 | + .await | ||
| 357 | + .expect("row") | ||
| 358 | + .expect("present"); | ||
| 359 | + assert_eq!(row.state, "sent"); | ||
| 360 | + | ||
| 361 | + // Both deliveries carried a logout token for this client and session, without a nonce. | ||
| 362 | + let bodies = received.await.expect("server"); | ||
| 363 | + assert_eq!(bodies.len(), 2); | ||
| 364 | + let token = bodies[1].strip_prefix("logout_token=").expect("form field"); | ||
| 365 | + let payload = token.split('.').nth(1).expect("payload"); | ||
| 366 | + let claims: serde_json::Value = | ||
| 367 | + serde_json::from_slice(&BASE64_URL_SAFE_NO_PAD.decode(payload).expect("base64")) | ||
| 368 | + .expect("json"); | ||
| 369 | + assert_eq!(claims["aud"], client.id.as_str()); | ||
| 370 | + assert_eq!(claims["sid"], session.id.as_str()); | ||
| 371 | + assert_eq!(claims["sub"], user.id.as_str()); | ||
| 372 | + assert!(claims["events"][LOGOUT_EVENT].is_object()); | ||
| 373 | + assert!(claims.get("nonce").is_none()); | ||
| 374 | + } | ||
| 375 | +} | ||
crates/im-web/src/boot.rsmodified+35 -0
| @@ -5,6 +5,7 @@ | |||
| 5 | //! the pragmas and the migrations), build the router, bind the listener, and serve until SIGTERM or | 5 | //! the pragmas and the migrations), build the router, bind the listener, and serve until SIGTERM or |
| 6 | //! Ctrl-C. Stored UI overrides are not layered on the file yet, because no page writes them. | 6 | //! Ctrl-C. Stored UI overrides are not layered on the file yet, because no page writes them. |
| 7 | 7 | ||
| 8 | +use std::fs::{File, OpenOptions, TryLockError}; | ||
| 8 | use std::os::unix::fs::PermissionsExt; | 9 | use std::os::unix::fs::PermissionsExt; |
| 9 | use std::path::Path; | 10 | use std::path::Path; |
| 10 | use std::sync::Arc; | 11 | use std::sync::Arc; |
| @@ -19,6 +20,7 @@ use tokio::sync::watch; | |||
| 19 | use topcoat::cookie::RouterBuilderCookieExt; | 20 | use topcoat::cookie::RouterBuilderCookieExt; |
| 20 | use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService}; | 21 | use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService}; |
| 21 | 22 | ||
| 23 | +use crate::backchannel; | ||
| 22 | use crate::live::LiveHub; | 24 | use crate::live::LiveHub; |
| 23 | use crate::oidc::signing; | 25 | use crate::oidc::signing; |
| 24 | use crate::pages::not_found::NotFoundLayer; | 26 | use crate::pages::not_found::NotFoundLayer; |
| @@ -30,10 +32,36 @@ use crate::throttle::Throttle; | |||
| 30 | /// Name of the instance key file inside the data directory. | 32 | /// Name of the instance key file inside the data directory. |
| 31 | const KEY_FILE: &str = "im.key"; | 33 | const KEY_FILE: &str = "im.key"; |
| 32 | 34 | ||
| 35 | +/// Name of the lock file inside the data directory. The server holds it for its whole life, and so does | ||
| 36 | +/// every operator command, so the two never open the database at once. | ||
| 37 | +const LOCK_FILE: &str = "im.lock"; | ||
| 38 | + | ||
| 39 | +/// Takes the exclusive lock of the data directory, creating the directory (mode 0700) when needed. The | ||
| 40 | +/// returned file keeps the lock; dropping it releases the lock. Fails with a message that tells the | ||
| 41 | +/// operator to stop the server when it is held. | ||
| 42 | +pub fn lock_data_dir(data_dir: &Path) -> im_core::Result<File> { | ||
| 43 | + std::fs::create_dir_all(data_dir)?; | ||
| 44 | + std::fs::set_permissions(data_dir, std::fs::Permissions::from_mode(0o700))?; | ||
| 45 | + let file = OpenOptions::new() | ||
| 46 | + .create(true) | ||
| 47 | + .truncate(false) | ||
| 48 | + .write(true) | ||
| 49 | + .open(data_dir.join(LOCK_FILE))?; | ||
| 50 | + match file.try_lock() { | ||
| 51 | + Ok(()) => Ok(file), | ||
| 52 | + Err(TryLockError::WouldBlock) => Err(im_core::Error::Conflict( | ||
| 53 | + "im is running on this data directory. Stop the server first, then run the command again." | ||
| 54 | + .into(), | ||
| 55 | + )), | ||
| 56 | + Err(TryLockError::Error(error)) => Err(error.into()), | ||
| 57 | + } | ||
| 58 | +} | ||
| 59 | + | ||
| 33 | /// Runs the server until a stop signal arrives. Returns once every connection has finished. | 60 | /// Runs the server until a stop signal arrives. Returns once every connection has finished. |
| 34 | pub async fn serve(config_path: &Path) -> im_core::Result<()> { | 61 | pub async fn serve(config_path: &Path) -> im_core::Result<()> { |
| 35 | let config = Config::load(config_path)?; | 62 | let config = Config::load(config_path)?; |
| 36 | let listen = config.listen; | 63 | let listen = config.listen; |
| 64 | + let _lock = lock_data_dir(&config.data_dir)?; | ||
| 37 | let state = open_state(config).await?; | 65 | let state = open_state(config).await?; |
| 38 | 66 | ||
| 39 | let listener = TcpListener::bind(listen).await.map_err(|error| { | 67 | let listener = TcpListener::bind(listen).await.map_err(|error| { |
| @@ -54,6 +82,12 @@ pub async fn serve(config_path: &Path) -> im_core::Result<()> { | |||
| 54 | stop_tx.send_replace(true); | 82 | stop_tx.send_replace(true); |
| 55 | }); | 83 | }); |
| 56 | let signing_worker = signing::spawn(state.store.clone(), state.key.clone(), stop_rx.clone()); | 84 | let signing_worker = signing::spawn(state.store.clone(), state.key.clone(), stop_rx.clone()); |
| 85 | + let backchannel_worker = backchannel::spawn( | ||
| 86 | + state.store.clone(), | ||
| 87 | + state.key.clone(), | ||
| 88 | + state.config.base_url.clone(), | ||
| 89 | + stop_rx.clone(), | ||
| 90 | + ); | ||
| 57 | 91 | ||
| 58 | topcoat::serve_until( | 92 | topcoat::serve_until( |
| 59 | listener, | 93 | listener, |
| @@ -62,6 +96,7 @@ pub async fn serve(config_path: &Path) -> im_core::Result<()> { | |||
| 62 | ) | 96 | ) |
| 63 | .await?; | 97 | .await?; |
| 64 | let _ = signing_worker.await; | 98 | let _ = signing_worker.await; |
| 99 | + let _ = backchannel_worker.await; | ||
| 65 | tracing::info!("im stopped"); | 100 | tracing::info!("im stopped"); |
| 66 | Ok(()) | 101 | Ok(()) |
| 67 | } | 102 | } |
crates/im-web/src/cli.rsmodified+3 -1
| @@ -17,7 +17,7 @@ use im_core::oauth::{ | |||
| 17 | use im_core::store::clients::NewClient; | 17 | use im_core::store::clients::NewClient; |
| 18 | use im_core::token::{generate_token, hash_token}; | 18 | use im_core::token::{generate_token, hash_token}; |
| 19 | 19 | ||
| 20 | -use crate::boot::open_state; | 20 | +use crate::boot::{lock_data_dir, open_state}; |
| 21 | use crate::state::AppState; | 21 | use crate::state::AppState; |
| 22 | 22 | ||
| 23 | /// Printed with a usage error. | 23 | /// Printed with a usage error. |
| @@ -73,6 +73,8 @@ where | |||
| 73 | { | 73 | { |
| 74 | let outcome = async { | 74 | let outcome = async { |
| 75 | let config = Config::load(config).map_err(|e| e.to_string())?; | 75 | let config = Config::load(config).map_err(|e| e.to_string())?; |
| 76 | + // Held for the whole command: a running server holds the same lock and refuses this one. | ||
| 77 | + let _lock = lock_data_dir(&config.data_dir).map_err(|e| e.to_string())?; | ||
| 76 | let state = open_state(config).await.map_err(|e| e.to_string())?; | 78 | let state = open_state(config).await.map_err(|e| e.to_string())?; |
| 77 | action(state).await | 79 | action(state).await |
| 78 | } | 80 | } |
crates/im-web/src/i18n/oidc.rsmodified+28 -0
| @@ -11,6 +11,16 @@ pub enum OidcText { | |||
| 11 | ErrorTitle, | 11 | ErrorTitle, |
| 12 | /// The sentence under the title. | 12 | /// The sentence under the title. |
| 13 | ErrorBody, | 13 | ErrorBody, |
| 14 | + /// The title of the page after a sign-out. | ||
| 15 | + SignedOutTitle, | ||
| 16 | + /// The sentence under the signed-out title. | ||
| 17 | + SignedOutBody, | ||
| 18 | + /// The title of the sign-out confirmation page. | ||
| 19 | + ConfirmTitle, | ||
| 20 | + /// The sentence under the confirmation title. | ||
| 21 | + ConfirmBody, | ||
| 22 | + /// The button that confirms the sign-out. | ||
| 23 | + ConfirmButton, | ||
| 14 | } | 24 | } |
| 15 | 25 | ||
| 16 | /// The text of `key` in `lang`. | 26 | /// The text of `key` in `lang`. |
| @@ -24,5 +34,23 @@ pub fn text(lang: Lang, key: OidcText) -> &'static str { | |||
| 24 | (OidcText::ErrorBody, Lang::Tr) => { | 34 | (OidcText::ErrorBody, Lang::Tr) => { |
| 25 | "Bu oturum açma isteği geçerli değil. Uygulamaya dönüp yeniden deneyin." | 35 | "Bu oturum açma isteği geçerli değil. Uygulamaya dönüp yeniden deneyin." |
| 26 | } | 36 | } |
| 37 | + (OidcText::SignedOutTitle, Lang::En) => "Signed out", | ||
| 38 | + (OidcText::SignedOutTitle, Lang::Tr) => "Oturum kapatıldı", | ||
| 39 | + (OidcText::SignedOutBody, Lang::En) => { | ||
| 40 | + "You are signed out of im. You can close this window." | ||
| 41 | + } | ||
| 42 | + (OidcText::SignedOutBody, Lang::Tr) => { | ||
| 43 | + "im oturumunuz kapatıldı. Bu pencereyi kapatabilirsiniz." | ||
| 44 | + } | ||
| 45 | + (OidcText::ConfirmTitle, Lang::En) => "Sign out of im?", | ||
| 46 | + (OidcText::ConfirmTitle, Lang::Tr) => "im oturumu kapatılsın mı?", | ||
| 47 | + (OidcText::ConfirmBody, Lang::En) => { | ||
| 48 | + "This ends your im session and your sessions in the family apps you use." | ||
| 49 | + } | ||
| 50 | + (OidcText::ConfirmBody, Lang::Tr) => { | ||
| 51 | + "Bu işlem im oturumunuzu ve kullandığınız aile uygulamalarındaki oturumları kapatır." | ||
| 52 | + } | ||
| 53 | + (OidcText::ConfirmButton, Lang::En) => "Sign out", | ||
| 54 | + (OidcText::ConfirmButton, Lang::Tr) => "Oturumu kapat", | ||
| 27 | } | 55 | } |
| 28 | } | 56 | } |
crates/im-web/src/main.rsmodified+1 -0
| @@ -7,6 +7,7 @@ | |||
| 7 | mod assets; | 7 | mod assets; |
| 8 | mod audit; | 8 | mod audit; |
| 9 | mod auth; | 9 | mod auth; |
| 10 | +mod backchannel; | ||
| 10 | mod boot; | 11 | mod boot; |
| 11 | mod cli; | 12 | mod cli; |
| 12 | mod client_ip; | 13 | mod client_ip; |
crates/im-web/src/oidc/authorize.rsmodified+16 -0
| @@ -193,6 +193,22 @@ async fn authorize(cx: &Cx) -> Result<impl View> { | |||
| 193 | return Err(see_other(format!("/login?next={}", percent_encode(back))).into()); | 193 | return Err(see_other(format!("/login?next={}", percent_encode(back))).into()); |
| 194 | }; | 194 | }; |
| 195 | 195 | ||
| 196 | + // An administrator must have two-factor sign-in first (the policy). The security page enrols it; a | ||
| 197 | + // prompt=none request cannot show a page, so it is refused instead. | ||
| 198 | + if viewer.user.is_admin | ||
| 199 | + && app.config.policy.require_2fa_for_admins | ||
| 200 | + && !viewer.user.totp_enabled() | ||
| 201 | + { | ||
| 202 | + if asked.no_prompt { | ||
| 203 | + let refused = Refused { | ||
| 204 | + code: "interaction_required", | ||
| 205 | + state: asked.state.clone(), | ||
| 206 | + }; | ||
| 207 | + return Err(refusal_redirect(redirect_uri, issuer, &refused).into()); | ||
| 208 | + } | ||
| 209 | + return Err(see_other("/account/security?notice=enrol").into()); | ||
| 210 | + } | ||
| 211 | + | ||
| 196 | let code = generate_token(); | 212 | let code = generate_token(); |
| 197 | let expires_at = stamp_after(CODE_TTL); | 213 | let expires_at = stamp_after(CODE_TTL); |
| 198 | app.store | 214 | app.store |
crates/im-web/src/oidc/discovery.rsmodified+1 -2
| @@ -13,8 +13,7 @@ use super::signing; | |||
| 13 | use super::{PUBLIC_CACHE, issuer, json_response}; | 13 | use super::{PUBLIC_CACHE, issuer, json_response}; |
| 14 | use crate::state::AppState; | 14 | use crate::state::AppState; |
| 15 | 15 | ||
| 16 | -/// The grant types this provider offers. `client_credentials` is listed as the contracts require; it is | 16 | +/// The grant types this provider offers (contracts.md 2.1). |
| 17 | -/// answered once the machine-token part is built. | ||
| 18 | const GRANT_TYPES: [&str; 3] = ["authorization_code", "refresh_token", "client_credentials"]; | 17 | const GRANT_TYPES: [&str; 3] = ["authorization_code", "refresh_token", "client_credentials"]; |
| 19 | 18 | ||
| 20 | /// The client authentication methods of `/token`, `/revoke` and `/introspect`. | 19 | /// The client authentication methods of `/token`, `/revoke` and `/introspect`. |
crates/im-web/src/oidc/introspect.rsadded+120 -0
| @@ -0,0 +1,120 @@ | |||
| 1 | +//! `POST /introspect` (RFC 7662): tells a client whether a token is active. A client sees only its own | ||
| 2 | +//! tokens: a token issued to another client, or one that is expired, revoked or rotated, is | ||
| 3 | +//! `{"active": false}` and nothing more. | ||
| 4 | +//! | ||
| 5 | +//! An access token is checked by its signature, its time and its issuer, and then by what it stands | ||
| 6 | +//! for: a machine token is active while its client is; a person's token is active while its session | ||
| 7 | +//! and account are. A refresh token is active while it is unused, unrevoked and unexpired, and its | ||
| 8 | +//! session is live. The client authenticates like at `/token`. | ||
| 9 | + | ||
| 10 | +use im_core::jwt::{self, PublishedKey}; | ||
| 11 | +use im_core::model::Client; | ||
| 12 | +use im_core::time::{now_stamp, unix_now, unix_seconds}; | ||
| 13 | +use im_core::token::hash_token; | ||
| 14 | +use serde_json::{Value, json}; | ||
| 15 | +use topcoat::Result; | ||
| 16 | +use topcoat::context::{Cx, app_context}; | ||
| 17 | +use topcoat::router::response::Response; | ||
| 18 | +use topcoat::router::{Body, StatusCode, route}; | ||
| 19 | + | ||
| 20 | +use super::signing; | ||
| 21 | +use super::token::client_form; | ||
| 22 | +use super::{issuer, json_response, oauth_error, one}; | ||
| 23 | +use crate::state::AppState; | ||
| 24 | + | ||
| 25 | +/// `POST /introspect`. | ||
| 26 | +#[route(POST "/introspect")] | ||
| 27 | +async fn introspect(cx: &Cx, body: Body) -> Result<Response> { | ||
| 28 | + let app = app_context::<AppState>(cx); | ||
| 29 | + let (client, pairs) = match client_form(cx, body).await? { | ||
| 30 | + Ok(parts) => parts, | ||
| 31 | + Err(response) => return Ok(response), | ||
| 32 | + }; | ||
| 33 | + let Some(token) = one(&pairs, "token") else { | ||
| 34 | + return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request")); | ||
| 35 | + }; | ||
| 36 | + let answer = match access_answer(app, &client, token).await? { | ||
| 37 | + Some(answer) => answer, | ||
| 38 | + None => refresh_answer(app, &client, token).await?, | ||
| 39 | + }; | ||
| 40 | + Ok(json_response(StatusCode::OK, &answer)) | ||
| 41 | +} | ||
| 42 | + | ||
| 43 | +/// The answer for an access token of ours. `None` when the text is not a token of this provider, so the | ||
| 44 | +/// caller tries the refresh tokens. | ||
| 45 | +async fn access_answer(app: &AppState, client: &Client, token: &str) -> Result<Option<Value>> { | ||
| 46 | + let published = signing::published_keys(&app.store).await?; | ||
| 47 | + let keys: Vec<PublishedKey> = published | ||
| 48 | + .iter() | ||
| 49 | + .filter_map(|key| PublishedKey::new(key.kid.clone(), &key.public_raw)) | ||
| 50 | + .collect(); | ||
| 51 | + let Ok(claims) = jwt::verify(&keys, token) else { | ||
| 52 | + return Ok(None); | ||
| 53 | + }; | ||
| 54 | + let now = unix_now(); | ||
| 55 | + let Some(audience) = jwt::single_audience(&claims) else { | ||
| 56 | + return Ok(Some(inactive())); | ||
| 57 | + }; | ||
| 58 | + if jwt::check_claims(&claims, issuer(app), audience, now).is_err() { | ||
| 59 | + return Ok(Some(inactive())); | ||
| 60 | + } | ||
| 61 | + // Only tokens issued to this client are reported, whatever else they are. | ||
| 62 | + if claims.get("azp").and_then(Value::as_str) != Some(client.id.as_str()) { | ||
| 63 | + return Ok(Some(inactive())); | ||
| 64 | + } | ||
| 65 | + let Some(scope) = claims.get("scope").and_then(Value::as_str) else { | ||
| 66 | + return Ok(Some(inactive())); | ||
| 67 | + }; | ||
| 68 | + let Some(sub) = claims.get("sub").and_then(Value::as_str) else { | ||
| 69 | + return Ok(Some(inactive())); | ||
| 70 | + }; | ||
| 71 | + // A person's access token lives only as long as its session and account. | ||
| 72 | + if !sub.starts_with("client:") { | ||
| 73 | + let Some(sid) = claims.get("sid").and_then(Value::as_str) else { | ||
| 74 | + return Ok(Some(inactive())); | ||
| 75 | + }; | ||
| 76 | + if app.store.live_session(sid).await?.is_none() { | ||
| 77 | + return Ok(Some(inactive())); | ||
| 78 | + } | ||
| 79 | + } | ||
| 80 | + Ok(Some(json!({ | ||
| 81 | + "active": true, | ||
| 82 | + "scope": scope, | ||
| 83 | + "client_id": client.id, | ||
| 84 | + "token_type": "Bearer", | ||
| 85 | + "exp": claims.get("exp"), | ||
| 86 | + "iat": claims.get("iat"), | ||
| 87 | + "sub": sub, | ||
| 88 | + "aud": audience, | ||
| 89 | + "iss": issuer(app), | ||
| 90 | + }))) | ||
| 91 | +} | ||
| 92 | + | ||
| 93 | +/// The answer for a refresh token of this client. | ||
| 94 | +async fn refresh_answer(app: &AppState, client: &Client, token: &str) -> Result<Value> { | ||
| 95 | + let Some(row) = app.store.refresh_token(&hash_token(token)).await? else { | ||
| 96 | + return Ok(inactive()); | ||
| 97 | + }; | ||
| 98 | + let usable = row.client_id == client.id | ||
| 99 | + && row.used_at.is_none() | ||
| 100 | + && row.revoked_at.is_none() | ||
| 101 | + && row.expires_at > now_stamp(); | ||
| 102 | + if !usable || app.store.live_session(&row.session_id).await?.is_none() { | ||
| 103 | + return Ok(inactive()); | ||
| 104 | + } | ||
| 105 | + Ok(json!({ | ||
| 106 | + "active": true, | ||
| 107 | + "scope": row.scope, | ||
| 108 | + "client_id": client.id, | ||
| 109 | + "token_type": "refresh_token", | ||
| 110 | + "exp": unix_seconds(&row.expires_at), | ||
| 111 | + "iat": unix_seconds(&row.created_at), | ||
| 112 | + "sub": row.user_id, | ||
| 113 | + "iss": issuer(app), | ||
| 114 | + })) | ||
| 115 | +} | ||
| 116 | + | ||
| 117 | +/// The answer for everything that is not active: no detail, so nothing is learned about other tokens. | ||
| 118 | +fn inactive() -> Value { | ||
| 119 | + json!({ "active": false }) | ||
| 120 | +} | ||
crates/im-web/src/oidc/logout.rsadded+278 -0
| @@ -0,0 +1,278 @@ | |||
| 1 | +//! `GET /logout` and `POST /logout`: OpenID Connect RP-Initiated Logout (contracts.md 2.5), and the | ||
| 2 | +//! sign-out button of the account menu, which posts to the same path with no hint. | ||
| 3 | +//! | ||
| 4 | +//! The rules, in order: | ||
| 5 | +//! - An `id_token_hint` is an ID token of ours: the signature and `iss` are checked, the expiry is not | ||
| 6 | +//! (an expired hint still names a session). A hint that fails is ignored, as if it were absent. | ||
| 7 | +//! - The client is named by the hint's `aud`. A redirect happens only when the client is enabled and | ||
| 8 | +//! `post_logout_redirect_uri` equals one of its registered URIs exactly. Otherwise the answer is the | ||
| 9 | +//! signed-out page, never a redirect. | ||
| 10 | +//! - `state` is echoed on the redirect only when it is usable (bounded, no control characters). | ||
| 11 | +//! - A `GET` ends a session only when the hint's `sid` is the browser's own session: an attacker's | ||
| 12 | +//! link cannot know that. Any other `GET` shows a confirmation form, which carries the session's CSRF | ||
| 13 | +//! token. A `POST` checks that token before anything changes. | ||
| 14 | +//! - Ending the session is `im`'s own: the browser session is deleted (and its clients told by | ||
| 15 | +//! back-channel logout, in the store's transaction). When the hint names another session of the same | ||
| 16 | +//! person, that one ends too. | ||
| 17 | + | ||
| 18 | +use im_core::jwt::{self, PublishedKey}; | ||
| 19 | +use im_core::model::AuditAction; | ||
| 20 | +use im_core::oauth::MAX_ECHO_BYTES; | ||
| 21 | +use im_core::store::Store; | ||
| 22 | +use im_core::store::backchannel::EndReason; | ||
| 23 | +use serde::Deserialize; | ||
| 24 | +use serde_json::Value; | ||
| 25 | +use topcoat::Result; | ||
| 26 | +use topcoat::context::{Cx, app_context}; | ||
| 27 | +use topcoat::router::content::Form; | ||
| 28 | +use topcoat::router::error::{forbidden, see_other}; | ||
| 29 | +use topcoat::router::page; | ||
| 30 | +use topcoat::view::{View, view}; | ||
| 31 | + | ||
| 32 | +use super::signing; | ||
| 33 | +use super::{issuer, with_query}; | ||
| 34 | +use crate::audit::{Actor, record}; | ||
| 35 | +use crate::auth::{Viewer, check_csrf, current_user, end_current_session}; | ||
| 36 | +use crate::i18n::Lang; | ||
| 37 | +use crate::i18n::oidc::{OidcText, text}; | ||
| 38 | +use crate::live::Topic; | ||
| 39 | +use crate::state::AppState; | ||
| 40 | +use crate::views::{page_lang, shell}; | ||
| 41 | + | ||
| 42 | +/// The parameters of a logout request, from the query (GET) or the form (POST). Every field is optional. | ||
| 43 | +#[derive(Debug, Default, Deserialize)] | ||
| 44 | +#[serde(default)] | ||
| 45 | +pub struct LogoutForm { | ||
| 46 | + /// The CSRF token of the browser session. Required by a POST that would end a session. | ||
| 47 | + csrf: String, | ||
| 48 | + /// An ID token previously issued to the client. | ||
| 49 | + id_token_hint: String, | ||
| 50 | + /// Where the client wants the browser to land. | ||
| 51 | + post_logout_redirect_uri: String, | ||
| 52 | + /// The client's opaque value, echoed back on the redirect. | ||
| 53 | + state: String, | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +/// What a valid hint says: the session it names, and the client it was issued to. | ||
| 57 | +struct Hint { | ||
| 58 | + /// The `im` session of the sign-in, when the hint names one. | ||
| 59 | + sid: Option<String>, | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +/// The checked request: the hint (if valid), the redirect to make (if allowed) and the echoed state. | ||
| 63 | +struct Asked { | ||
| 64 | + /// The verified hint, if there was one that checks out. | ||
| 65 | + hint: Option<Hint>, | ||
| 66 | + /// The post-logout URI, when it equals a registered one of the hinted client. | ||
| 67 | + redirect: Option<String>, | ||
| 68 | + /// The state to echo, when it is usable. | ||
| 69 | + state: Option<String>, | ||
| 70 | + /// The hint as given, when it checks out: the confirmation form carries it. | ||
| 71 | + raw_hint: Option<String>, | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +/// Tells a state apart from a value that must not be echoed. | ||
| 75 | +fn usable_state(value: &str) -> bool { | ||
| 76 | + !value.is_empty() && value.len() <= MAX_ECHO_BYTES && !value.chars().any(char::is_control) | ||
| 77 | +} | ||
| 78 | + | ||
| 79 | +/// Verifies an ID token of ours for logout. `None` when it is not an ID token of this provider, or its | ||
| 80 | +/// signature or issuer is wrong. The expiry is not checked. | ||
| 81 | +async fn verify_hint( | ||
| 82 | + store: &Store, | ||
| 83 | + issuer: &str, | ||
| 84 | + token: &str, | ||
| 85 | +) -> im_core::Result<Option<(String, Option<String>)>> { | ||
| 86 | + let published = signing::published_keys(store).await?; | ||
| 87 | + let keys: Vec<PublishedKey> = published | ||
| 88 | + .iter() | ||
| 89 | + .filter_map(|key| PublishedKey::new(key.kid.clone(), &key.public_raw)) | ||
| 90 | + .collect(); | ||
| 91 | + let Ok(claims) = jwt::verify(&keys, token) else { | ||
| 92 | + return Ok(None); | ||
| 93 | + }; | ||
| 94 | + if jwt::check_issuer(&claims, issuer).is_err() { | ||
| 95 | + return Ok(None); | ||
| 96 | + } | ||
| 97 | + // An access token has `azp` and `scope`; an ID token has neither. Only ID tokens are hints. | ||
| 98 | + if claims.contains_key("azp") || claims.contains_key("scope") { | ||
| 99 | + return Ok(None); | ||
| 100 | + } | ||
| 101 | + let Some(client_id) = jwt::single_audience(&claims) else { | ||
| 102 | + return Ok(None); | ||
| 103 | + }; | ||
| 104 | + let sid = claims.get("sid").and_then(Value::as_str).map(str::to_owned); | ||
| 105 | + Ok(Some((client_id.to_owned(), sid))) | ||
| 106 | +} | ||
| 107 | + | ||
| 108 | +/// Checks the request. Nothing here changes state. | ||
| 109 | +async fn read(app: &AppState, form: &LogoutForm) -> Result<Asked> { | ||
| 110 | + let state = Some(form.state.as_str()) | ||
| 111 | + .filter(|value| usable_state(value)) | ||
| 112 | + .map(str::to_owned); | ||
| 113 | + let mut asked = Asked { | ||
| 114 | + hint: None, | ||
| 115 | + redirect: None, | ||
| 116 | + state, | ||
| 117 | + raw_hint: None, | ||
| 118 | + }; | ||
| 119 | + if form.id_token_hint.is_empty() { | ||
| 120 | + return Ok(asked); | ||
| 121 | + } | ||
| 122 | + let Some((client_id, sid)) = verify_hint(&app.store, issuer(app), &form.id_token_hint).await? | ||
| 123 | + else { | ||
| 124 | + return Ok(asked); | ||
| 125 | + }; | ||
| 126 | + asked.raw_hint = Some(form.id_token_hint.clone()); | ||
| 127 | + let client = app.store.client_by_id(&client_id).await?; | ||
| 128 | + if let Some(client) = client.filter(|c| !c.is_disabled()) | ||
| 129 | + && !form.post_logout_redirect_uri.is_empty() | ||
| 130 | + && client | ||
| 131 | + .post_logout_redirect_uris | ||
| 132 | + .iter() | ||
| 133 | + .any(|registered| registered == &form.post_logout_redirect_uri) | ||
| 134 | + { | ||
| 135 | + asked.redirect = Some(form.post_logout_redirect_uri.clone()); | ||
| 136 | + } | ||
| 137 | + asked.hint = Some(Hint { sid }); | ||
| 138 | + Ok(asked) | ||
| 139 | +} | ||
| 140 | + | ||
| 141 | +/// The redirect to the client, with the state when there is one. `None` means the signed-out page. | ||
| 142 | +fn redirect_target(asked: &Asked) -> Option<String> { | ||
| 143 | + let uri = asked.redirect.as_deref()?; | ||
| 144 | + Some(match asked.state.as_deref() { | ||
| 145 | + Some(state) => with_query(uri, &[("state", state)]), | ||
| 146 | + None => uri.to_owned(), | ||
| 147 | + }) | ||
| 148 | +} | ||
| 149 | + | ||
| 150 | +/// Ends the browser's session and, when the hint names another session of the same person, that one | ||
| 151 | +/// too. Audits the sign-out. | ||
| 152 | +async fn sign_out(cx: &Cx, viewer: &Viewer, hint_sid: Option<&str>) -> Result<()> { | ||
| 153 | + let app = app_context::<AppState>(cx); | ||
| 154 | + end_current_session(cx, viewer, EndReason::Logout).await?; | ||
| 155 | + if let Some(other) = hint_sid.filter(|sid| *sid != viewer.session.id) { | ||
| 156 | + // The store checks ownership: another person's session is not ended, and the call says so. | ||
| 157 | + if app | ||
| 158 | + .store | ||
| 159 | + .end_session(&viewer.user.id, other, EndReason::Logout) | ||
| 160 | + .await? | ||
| 161 | + { | ||
| 162 | + app.live.bump(&Topic::Account(viewer.user.id.clone())); | ||
| 163 | + } | ||
| 164 | + } | ||
| 165 | + record( | ||
| 166 | + cx, | ||
| 167 | + Actor::User(&viewer.user.id), | ||
| 168 | + AuditAction::Logout, | ||
| 169 | + Some(("session", &viewer.session.id)), | ||
| 170 | + Value::Null, | ||
| 171 | + ) | ||
| 172 | + .await; | ||
| 173 | + Ok(()) | ||
| 174 | +} | ||
| 175 | + | ||
| 176 | +/// `GET /logout`. | ||
| 177 | +#[page(GET "/logout")] | ||
| 178 | +async fn logout_get(cx: &Cx, Form(form): Form<LogoutForm>) -> Result<impl View> { | ||
| 179 | + let app = app_context::<AppState>(cx); | ||
| 180 | + let asked = read(app, &form).await?; | ||
| 181 | + let viewer = current_user(cx).await?; | ||
| 182 | + let lang = page_lang(cx, viewer.as_ref()); | ||
| 183 | + let own_session = viewer.as_ref().is_some_and(|viewer| { | ||
| 184 | + asked | ||
| 185 | + .hint | ||
| 186 | + .as_ref() | ||
| 187 | + .and_then(|hint| hint.sid.as_deref()) | ||
| 188 | + .is_some_and(|sid| sid == viewer.session.id) | ||
| 189 | + }); | ||
| 190 | + match viewer { | ||
| 191 | + Some(viewer) if own_session => { | ||
| 192 | + sign_out(cx, &viewer, None).await?; | ||
| 193 | + if let Some(target) = redirect_target(&asked) { | ||
| 194 | + return Err(see_other(target).into()); | ||
| 195 | + } | ||
| 196 | + Ok(logout_view(cx, lang, None)) | ||
| 197 | + } | ||
| 198 | + Some(viewer) => { | ||
| 199 | + let confirm = Confirm { | ||
| 200 | + csrf: viewer.session.csrf_token.clone(), | ||
| 201 | + raw_hint: asked.raw_hint.clone(), | ||
| 202 | + redirect: asked.redirect.clone(), | ||
| 203 | + state: asked.state.clone(), | ||
| 204 | + }; | ||
| 205 | + Ok(logout_view(cx, lang, Some(confirm))) | ||
| 206 | + } | ||
| 207 | + // No session to end: only the redirect, if the hint allows one. | ||
| 208 | + None => { | ||
| 209 | + if let Some(target) = redirect_target(&asked) { | ||
| 210 | + return Err(see_other(target).into()); | ||
| 211 | + } | ||
| 212 | + Ok(logout_view(cx, lang, None)) | ||
| 213 | + } | ||
| 214 | + } | ||
| 215 | +} | ||
| 216 | + | ||
| 217 | +/// `POST /logout`. Without a session there is nothing to end, so no CSRF check applies. | ||
| 218 | +#[page(POST "/logout")] | ||
| 219 | +async fn logout_post(cx: &Cx, Form(form): Form<LogoutForm>) -> Result<impl View> { | ||
| 220 | + let app = app_context::<AppState>(cx); | ||
| 221 | + let asked = read(app, &form).await?; | ||
| 222 | + let viewer = current_user(cx).await?; | ||
| 223 | + if let Some(viewer) = &viewer { | ||
| 224 | + if !check_csrf(&viewer.session, &form.csrf) { | ||
| 225 | + return Err(forbidden().into()); | ||
| 226 | + } | ||
| 227 | + let hint_sid = asked.hint.as_ref().and_then(|hint| hint.sid.clone()); | ||
| 228 | + sign_out(cx, viewer, hint_sid.as_deref()).await?; | ||
| 229 | + } | ||
| 230 | + if let Some(target) = redirect_target(&asked) { | ||
| 231 | + return Err(see_other(target).into()); | ||
| 232 | + } | ||
| 233 | + let lang = page_lang(cx, None); | ||
| 234 | + Ok(logout_view(cx, lang, None)) | ||
| 235 | +} | ||
| 236 | + | ||
| 237 | +/// The form that asks for a sign-out (the GET answer when the session is not the hinted one). | ||
| 238 | +struct Confirm { | ||
| 239 | + csrf: String, | ||
| 240 | + raw_hint: Option<String>, | ||
| 241 | + redirect: Option<String>, | ||
| 242 | + state: Option<String>, | ||
| 243 | +} | ||
| 244 | + | ||
| 245 | +/// The confirmation page, or the signed-out page when `confirm` is `None`. The form posts to this same | ||
| 246 | +/// path and carries everything the POST needs to finish the same request. | ||
| 247 | +fn logout_view(cx: &Cx, lang: Lang, confirm: Option<Confirm>) -> impl View { | ||
| 248 | + let title = if confirm.is_some() { | ||
| 249 | + text(lang, OidcText::ConfirmTitle) | ||
| 250 | + } else { | ||
| 251 | + text(lang, OidcText::SignedOutTitle) | ||
| 252 | + }; | ||
| 253 | + view! { cx => | ||
| 254 | + shell(title: title, lang: lang, viewer: None, | ||
| 255 | + <section class="card narrow stack"> | ||
| 256 | + <h1>(title)</h1> | ||
| 257 | + if let Some(confirm) = confirm { | ||
| 258 | + <p class="muted">(text(lang, OidcText::ConfirmBody))</p> | ||
| 259 | + <form method="post" action="/logout" class="stack"> | ||
| 260 | + <input type="hidden" name="csrf" value=(confirm.csrf)> | ||
| 261 | + if let Some(hint) = confirm.raw_hint { | ||
| 262 | + <input type="hidden" name="id_token_hint" value=(hint)> | ||
| 263 | + } | ||
| 264 | + if let Some(uri) = confirm.redirect { | ||
| 265 | + <input type="hidden" name="post_logout_redirect_uri" value=(uri)> | ||
| 266 | + } | ||
| 267 | + if let Some(state) = confirm.state { | ||
| 268 | + <input type="hidden" name="state" value=(state)> | ||
| 269 | + } | ||
| 270 | + <button type="submit" class="button primary">(text(lang, OidcText::ConfirmButton))</button> | ||
| 271 | + </form> | ||
| 272 | + } else { | ||
| 273 | + <p>(text(lang, OidcText::SignedOutBody))</p> | ||
| 274 | + } | ||
| 275 | + </section> | ||
| 276 | + ) | ||
| 277 | + } | ||
| 278 | +} | ||
crates/im-web/src/oidc/mod.rsmodified+3 -0
| @@ -7,6 +7,9 @@ | |||
| 7 | 7 | ||
| 8 | pub mod authorize; | 8 | pub mod authorize; |
| 9 | pub mod discovery; | 9 | pub mod discovery; |
| 10 | +pub mod introspect; | ||
| 11 | +pub mod logout; | ||
| 12 | +pub mod revoke; | ||
| 10 | pub mod signing; | 13 | pub mod signing; |
| 11 | pub mod token; | 14 | pub mod token; |
| 12 | pub mod userinfo; | 15 | pub mod userinfo; |
crates/im-web/src/oidc/revoke.rsadded+40 -0
| @@ -0,0 +1,40 @@ | |||
| 1 | +//! `POST /revoke` (RFC 7009): a client gives back one of its own refresh tokens, and the whole chain of | ||
| 2 | +//! that token is revoked. | ||
| 3 | +//! | ||
| 4 | +//! The client authenticates like at `/token`. The answer is `200` with an empty body for every token: a | ||
| 5 | +//! token that is unknown, belongs to another client, or is already revoked gets the same answer, so the | ||
| 6 | +//! endpoint does not reveal which tokens exist (RFC 7009 section 2.2). Access tokens need no table here: | ||
| 7 | +//! they live ten minutes and are refused at once when their session ends, so revoking the session is the | ||
| 8 | +//! way to end them. | ||
| 9 | + | ||
| 10 | +use im_core::token::hash_token; | ||
| 11 | +use topcoat::Result; | ||
| 12 | +use topcoat::context::Cx; | ||
| 13 | +use topcoat::router::response::Response; | ||
| 14 | +use topcoat::router::{Body, StatusCode, route}; | ||
| 15 | + | ||
| 16 | +use super::token::client_form; | ||
| 17 | +use super::{oauth_error, one}; | ||
| 18 | +use crate::state::AppState; | ||
| 19 | +use topcoat::context::app_context; | ||
| 20 | + | ||
| 21 | +/// `POST /revoke`. | ||
| 22 | +#[route(POST "/revoke")] | ||
| 23 | +async fn revoke(cx: &Cx, body: Body) -> Result<Response> { | ||
| 24 | + let app = app_context::<AppState>(cx); | ||
| 25 | + let (client, pairs) = match client_form(cx, body).await? { | ||
| 26 | + Ok(parts) => parts, | ||
| 27 | + Err(response) => return Ok(response), | ||
| 28 | + }; | ||
| 29 | + let Some(token) = one(&pairs, "token") else { | ||
| 30 | + return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request")); | ||
| 31 | + }; | ||
| 32 | + if let Some(row) = app.store.refresh_token(&hash_token(token)).await? | ||
| 33 | + && row.client_id == client.id | ||
| 34 | + { | ||
| 35 | + app.store.revoke_refresh_family(&row.family_id).await?; | ||
| 36 | + } | ||
| 37 | + let mut response = Response::new(Body::empty()); | ||
| 38 | + *response.status_mut() = StatusCode::OK; | ||
| 39 | + Ok(response) | ||
| 40 | +} | ||
crates/im-web/src/oidc/tests.rsmodified+154 -1
| @@ -23,6 +23,9 @@ use crate::state::AppState; | |||
| 23 | /// The registered redirect URI of the test client. | 23 | /// The registered redirect URI of the test client. |
| 24 | const REDIRECT: &str = "http://127.0.0.1:17651/auth/callback"; | 24 | const REDIRECT: &str = "http://127.0.0.1:17651/auth/callback"; |
| 25 | 25 | ||
| 26 | +/// The registered post-logout URI of the test client. | ||
| 27 | +const POST_LOGOUT: &str = "http://127.0.0.1:17651/signed-out"; | ||
| 28 | + | ||
| 26 | /// The cookie name the browser sends: the `__Host-` prefix is added by the jar. | 29 | /// The cookie name the browser sends: the `__Host-` prefix is added by the jar. |
| 27 | const SESSION_COOKIE: &str = "__Host-im_session"; | 30 | const SESSION_COOKIE: &str = "__Host-im_session"; |
| 28 | 31 | ||
| @@ -43,13 +46,14 @@ async fn fixture() -> Fixture { | |||
| 43 | .expect("signing key"); | 46 | .expect("signing key"); |
| 44 | let secret = generate_token(); | 47 | let secret = generate_token(); |
| 45 | let uris = vec![REDIRECT.to_owned()]; | 48 | let uris = vec![REDIRECT.to_owned()]; |
| 49 | + let post_logout = vec![POST_LOGOUT.to_owned()]; | ||
| 46 | let client = state | 50 | let client = state |
| 47 | .store | 51 | .store |
| 48 | .create_client(&NewClient { | 52 | .create_client(&NewClient { |
| 49 | name: "Files", | 53 | name: "Files", |
| 50 | secret_hash: &hash_token(&secret), | 54 | secret_hash: &hash_token(&secret), |
| 51 | redirect_uris: &uris, | 55 | redirect_uris: &uris, |
| 52 | - post_logout_redirect_uris: &[], | 56 | + post_logout_redirect_uris: &post_logout, |
| 53 | backchannel_logout_uri: None, | 57 | backchannel_logout_uri: None, |
| 54 | allowed_scopes: "openid profile email", | 58 | allowed_scopes: "openid profile email", |
| 55 | service_key: Some("in"), | 59 | service_key: Some("in"), |
| @@ -315,3 +319,152 @@ async fn the_id_token_verifies_against_the_published_key_and_carries_the_nonce() | |||
| 315 | assert_eq!(claims["sub"], f.user_id.as_str()); | 319 | assert_eq!(claims["sub"], f.user_id.as_str()); |
| 316 | assert_eq!(claims["amr"], serde_json::json!(["pwd"])); | 320 | assert_eq!(claims["amr"], serde_json::json!(["pwd"])); |
| 317 | } | 321 | } |
| 322 | + | ||
| 323 | +/// Posts a form to `path` with `client_secret_basic` for `client`. | ||
| 324 | +async fn post_as( | ||
| 325 | + f: &Fixture, | ||
| 326 | + path: &str, | ||
| 327 | + client: &Client, | ||
| 328 | + secret: &str, | ||
| 329 | + body: &str, | ||
| 330 | +) -> (StatusCode, Value) { | ||
| 331 | + let basic = BASE64_STANDARD.encode(format!("{}:{}", client.id, secret)); | ||
| 332 | + let request = http::Request::post(path) | ||
| 333 | + .header(CONTENT_TYPE, "application/x-www-form-urlencoded") | ||
| 334 | + .header(AUTHORIZATION, format!("Basic {basic}")) | ||
| 335 | + .body(Body::from(body.to_owned())) | ||
| 336 | + .expect("request"); | ||
| 337 | + let (status, _, text) = send(&f.state, request).await; | ||
| 338 | + (status, serde_json::from_str(&text).unwrap_or(Value::Null)) | ||
| 339 | +} | ||
| 340 | + | ||
| 341 | +/// A client that is a family service with the given key and allowed scopes. Returns it with its secret. | ||
| 342 | +async fn service(f: &Fixture, key: &str, scopes: &str) -> (Client, String) { | ||
| 343 | + let secret = generate_token(); | ||
| 344 | + let client = f | ||
| 345 | + .state | ||
| 346 | + .store | ||
| 347 | + .create_client(&NewClient { | ||
| 348 | + name: key, | ||
| 349 | + secret_hash: &hash_token(&secret), | ||
| 350 | + redirect_uris: &[], | ||
| 351 | + post_logout_redirect_uris: &[], | ||
| 352 | + backchannel_logout_uri: None, | ||
| 353 | + allowed_scopes: scopes, | ||
| 354 | + service_key: Some(key), | ||
| 355 | + }) | ||
| 356 | + .await | ||
| 357 | + .expect("service client"); | ||
| 358 | + (client, secret) | ||
| 359 | +} | ||
| 360 | + | ||
| 361 | +#[tokio::test] | ||
| 362 | +async fn client_credentials_refuses_a_scope_beyond_the_allowed_ones() { | ||
| 363 | + let f = fixture().await; | ||
| 364 | + let (caller, secret) = service(&f, "iz", "directory.read").await; | ||
| 365 | + let (status, body) = post_as( | ||
| 366 | + &f, | ||
| 367 | + "/token", | ||
| 368 | + &caller, | ||
| 369 | + &secret, | ||
| 370 | + "grant_type=client_credentials&scope=files.service&audience=im", | ||
| 371 | + ) | ||
| 372 | + .await; | ||
| 373 | + assert_eq!(status, StatusCode::BAD_REQUEST, "{body}"); | ||
| 374 | + assert_eq!(body["error"], "invalid_scope"); | ||
| 375 | +} | ||
| 376 | + | ||
| 377 | +#[tokio::test] | ||
| 378 | +async fn client_credentials_refuses_an_unknown_audience() { | ||
| 379 | + let f = fixture().await; | ||
| 380 | + let (caller, secret) = service(&f, "iz", "directory.read").await; | ||
| 381 | + let (status, body) = post_as( | ||
| 382 | + &f, | ||
| 383 | + "/token", | ||
| 384 | + &caller, | ||
| 385 | + &secret, | ||
| 386 | + "grant_type=client_credentials&scope=directory.read&audience=nowhere", | ||
| 387 | + ) | ||
| 388 | + .await; | ||
| 389 | + assert_eq!(status, StatusCode::BAD_REQUEST, "{body}"); | ||
| 390 | + assert_eq!(body["error"], "invalid_target"); | ||
| 391 | +} | ||
| 392 | + | ||
| 393 | +#[tokio::test] | ||
| 394 | +async fn introspection_reports_a_token_inactive_for_any_client_but_its_own() { | ||
| 395 | + let f = fixture().await; | ||
| 396 | + let (caller, caller_secret) = service(&f, "iz", "directory.read").await; | ||
| 397 | + let (other, other_secret) = service(&f, "board", "directory.read").await; | ||
| 398 | + let (status, issued) = post_as( | ||
| 399 | + &f, | ||
| 400 | + "/token", | ||
| 401 | + &caller, | ||
| 402 | + &caller_secret, | ||
| 403 | + "grant_type=client_credentials&scope=directory.read&audience=im", | ||
| 404 | + ) | ||
| 405 | + .await; | ||
| 406 | + assert_eq!(status, StatusCode::OK, "{issued}"); | ||
| 407 | + let token = issued["access_token"].as_str().expect("token"); | ||
| 408 | + let body = format!("token={token}"); | ||
| 409 | + | ||
| 410 | + let (status, own) = post_as(&f, "/introspect", &caller, &caller_secret, &body).await; | ||
| 411 | + assert_eq!(status, StatusCode::OK); | ||
| 412 | + assert_eq!(own["active"], true, "{own}"); | ||
| 413 | + | ||
| 414 | + let (status, foreign) = post_as(&f, "/introspect", &other, &other_secret, &body).await; | ||
| 415 | + assert_eq!(status, StatusCode::OK); | ||
| 416 | + assert_eq!(foreign, serde_json::json!({ "active": false })); | ||
| 417 | +} | ||
| 418 | + | ||
| 419 | +/// The ID token of a fresh sign-in of the fixture's person, and the code exchange's session id. | ||
| 420 | +async fn id_token_of(f: &Fixture) -> String { | ||
| 421 | + let verifier = generate_token(); | ||
| 422 | + let code = code_for(f, &f.client, &verifier).await; | ||
| 423 | + let (status, tokens) = token_with(f, &f.client, &f.secret, &code_body(&code, &verifier)).await; | ||
| 424 | + assert_eq!(status, StatusCode::OK, "{tokens}"); | ||
| 425 | + tokens["id_token"].as_str().expect("id_token").to_owned() | ||
| 426 | +} | ||
| 427 | + | ||
| 428 | +#[tokio::test] | ||
| 429 | +async fn logout_redirects_only_to_the_registered_post_logout_uri() { | ||
| 430 | + let f = fixture().await; | ||
| 431 | + let hint = encode_value(&id_token_of(&f).await); | ||
| 432 | + let unregistered = encode_value("http://127.0.0.1:17651/elsewhere"); | ||
| 433 | + let path = | ||
| 434 | + format!("/logout?id_token_hint={hint}&post_logout_redirect_uri={unregistered}&state=abc"); | ||
| 435 | + let request = http::Request::get(path) | ||
| 436 | + .header(COOKIE, format!("{SESSION_COOKIE}={}", f.cookie)) | ||
| 437 | + .body(Body::empty()) | ||
| 438 | + .expect("request"); | ||
| 439 | + let (status, headers, body) = send(&f.state, request).await; | ||
| 440 | + assert_eq!(status, StatusCode::OK, "{body}"); | ||
| 441 | + assert!( | ||
| 442 | + headers.get(LOCATION).is_none(), | ||
| 443 | + "redirected to an unregistered URI" | ||
| 444 | + ); | ||
| 445 | + // The hint names the browser's own session, so it ends even though nothing is redirected. | ||
| 446 | + let live = f | ||
| 447 | + .state | ||
| 448 | + .store | ||
| 449 | + .session_by_token_hash(&hash_token(&f.cookie)) | ||
| 450 | + .await | ||
| 451 | + .expect("lookup"); | ||
| 452 | + assert!(live.is_none(), "the session did not end"); | ||
| 453 | +} | ||
| 454 | + | ||
| 455 | +#[tokio::test] | ||
| 456 | +async fn logout_with_the_registered_uri_redirects_and_carries_the_state() { | ||
| 457 | + let f = fixture().await; | ||
| 458 | + let hint = encode_value(&id_token_of(&f).await); | ||
| 459 | + let registered = encode_value(POST_LOGOUT); | ||
| 460 | + let path = | ||
| 461 | + format!("/logout?id_token_hint={hint}&post_logout_redirect_uri={registered}&state=abc"); | ||
| 462 | + let request = http::Request::get(path) | ||
| 463 | + .header(COOKIE, format!("{SESSION_COOKIE}={}", f.cookie)) | ||
| 464 | + .body(Body::empty()) | ||
| 465 | + .expect("request"); | ||
| 466 | + let (status, headers, _) = send(&f.state, request).await; | ||
| 467 | + assert_eq!(status, StatusCode::SEE_OTHER); | ||
| 468 | + let location = headers[LOCATION].to_str().expect("location"); | ||
| 469 | + assert_eq!(location, format!("{POST_LOGOUT}?state=abc")); | ||
| 470 | +} | ||
crates/im-web/src/oidc/token.rsmodified+89 -7
| @@ -4,16 +4,18 @@ | |||
| 4 | //! Client authentication is `client_secret_basic` or `client_secret_post`, never both. The | 4 | //! Client authentication is `client_secret_basic` or `client_secret_post`, never both. The |
| 5 | //! authorization-code grant consumes the code in one statement and refuses a reuse by revoking every | 5 | //! authorization-code grant consumes the code in one statement and refuses a reuse by revoking every |
| 6 | //! refresh token made from that code. The refresh grant rotates the token; presenting a rotated one | 6 | //! refresh token made from that code. The refresh grant rotates the token; presenting a rotated one |
| 7 | -//! revokes its whole family. Client credentials (machine tokens) is answered `unsupported_grant_type` | 7 | +//! revokes its whole family. The client-credentials grant issues the machine tokens of contracts.md 2.6. |
| 8 | -//! until its part of the provider is built. | 8 | +//! A disabled client fails client authentication, so no grant runs for it: its refresh tokens and its |
| 9 | +//! machine tokens are refused at once. | ||
| 9 | 10 | ||
| 10 | use base64::prelude::{BASE64_STANDARD, Engine as _}; | 11 | use base64::prelude::{BASE64_STANDARD, Engine as _}; |
| 11 | use http::header::AUTHORIZATION; | 12 | use http::header::AUTHORIZATION; |
| 12 | -use im_core::model::{Client, Session, User}; | 13 | +use im_core::model::{Client, Session, User, amr}; |
| 14 | +use im_core::oauth::{is_supported_scope, is_user_scope, is_valid_family_key}; | ||
| 13 | use im_core::oauth::{is_valid_verifier, pkce_s256}; | 15 | use im_core::oauth::{is_valid_verifier, pkce_s256}; |
| 14 | use im_core::store::new_id; | 16 | use im_core::store::new_id; |
| 15 | use im_core::store::oidc::NewRefreshToken; | 17 | use im_core::store::oidc::NewRefreshToken; |
| 16 | -use im_core::time::{now_stamp, stamp_after, unix_seconds}; | 18 | +use im_core::time::{now_stamp, stamp_after, unix_now, unix_seconds}; |
| 17 | use im_core::token::{constant_time_eq, generate_token, hash_token}; | 19 | use im_core::token::{constant_time_eq, generate_token, hash_token}; |
| 18 | use serde_json::{Map, Value, json}; | 20 | use serde_json::{Map, Value, json}; |
| 19 | use topcoat::Result; | 21 | use topcoat::Result; |
| @@ -56,6 +58,7 @@ async fn token_endpoint(cx: &Cx, body: Body) -> Result<Response> { | |||
| 56 | match one(&pairs, "grant_type") { | 58 | match one(&pairs, "grant_type") { |
| 57 | Some("authorization_code") => grant_code(app, &client, &pairs).await, | 59 | Some("authorization_code") => grant_code(app, &client, &pairs).await, |
| 58 | Some("refresh_token") => grant_refresh(app, &client, &pairs).await, | 60 | Some("refresh_token") => grant_refresh(app, &client, &pairs).await, |
| 61 | + Some("client_credentials") => grant_client(app, &client, &pairs).await, | ||
| 59 | Some(_) => Ok(oauth_error( | 62 | Some(_) => Ok(oauth_error( |
| 60 | StatusCode::BAD_REQUEST, | 63 | StatusCode::BAD_REQUEST, |
| 61 | "unsupported_grant_type", | 64 | "unsupported_grant_type", |
| @@ -64,6 +67,35 @@ async fn token_endpoint(cx: &Cx, body: Body) -> Result<Response> { | |||
| 64 | } | 67 | } |
| 65 | } | 68 | } |
| 66 | 69 | ||
| 70 | +/// Reads a client-authenticated form for `/revoke` and `/introspect`: the same content type, size and | ||
| 71 | +/// client authentication as `/token`. The inner `Err` is the refusal to send. | ||
| 72 | +pub(super) async fn client_form( | ||
| 73 | + cx: &Cx, | ||
| 74 | + body: Body, | ||
| 75 | +) -> Result<std::result::Result<(Client, Pairs), Response>> { | ||
| 76 | + let app = app_context::<AppState>(cx); | ||
| 77 | + if !is_form(content_type(cx)) { | ||
| 78 | + return Ok(Err(oauth_error(StatusCode::BAD_REQUEST, "invalid_request"))); | ||
| 79 | + } | ||
| 80 | + let Ok(bytes) = to_bytes(body, TOKEN_BODY_LIMIT).await else { | ||
| 81 | + return Ok(Err(oauth_error( | ||
| 82 | + StatusCode::PAYLOAD_TOO_LARGE, | ||
| 83 | + "invalid_request", | ||
| 84 | + ))); | ||
| 85 | + }; | ||
| 86 | + let Some(pairs) = parse_pairs(&bytes) else { | ||
| 87 | + return Ok(Err(oauth_error(StatusCode::BAD_REQUEST, "invalid_request"))); | ||
| 88 | + }; | ||
| 89 | + let authorization = headers(cx) | ||
| 90 | + .get(AUTHORIZATION) | ||
| 91 | + .and_then(|value| value.to_str().ok()) | ||
| 92 | + .map(str::to_owned); | ||
| 93 | + match authenticate(app, authorization.as_deref(), &pairs).await? { | ||
| 94 | + Ok(client) => Ok(Ok((client, pairs))), | ||
| 95 | + Err(response) => Ok(Err(response)), | ||
| 96 | + } | ||
| 97 | +} | ||
| 98 | + | ||
| 67 | /// True for a form body, with or without parameters after the media type. | 99 | /// True for a form body, with or without parameters after the media type. |
| 68 | fn is_form(content_type: Option<&str>) -> bool { | 100 | fn is_form(content_type: Option<&str>) -> bool { |
| 69 | content_type.is_some_and(|value| { | 101 | content_type.is_some_and(|value| { |
| @@ -96,7 +128,7 @@ fn basic_credentials(header: &str) -> Option<std::result::Result<(String, String | |||
| 96 | 128 | ||
| 97 | /// Authenticates the client. The outer `Result` is a server failure; the inner one is either the client | 129 | /// Authenticates the client. The outer `Result` is a server failure; the inner one is either the client |
| 98 | /// or the response that refuses the request. | 130 | /// or the response that refuses the request. |
| 99 | -async fn authenticate( | 131 | +pub(super) async fn authenticate( |
| 100 | app: &AppState, | 132 | app: &AppState, |
| 101 | authorization: Option<&str>, | 133 | authorization: Option<&str>, |
| 102 | pairs: &Pairs, | 134 | pairs: &Pairs, |
| @@ -280,6 +312,53 @@ async fn grant_refresh(app: &AppState, client: &Client, pairs: &Pairs) -> Result | |||
| 280 | )) | 312 | )) |
| 281 | } | 313 | } |
| 282 | 314 | ||
| 315 | +/// The client-credentials grant (contracts.md 2.6): a machine token that a family service presents to | ||
| 316 | +/// another family service. The caller must be a family service (its key is `svc`), every requested scope | ||
| 317 | +/// must be a machine scope the client is allowed, and the audience must be a known family key. The token | ||
| 318 | +/// is addressed to that key, so it cannot be presented to any other service. | ||
| 319 | +async fn grant_client(app: &AppState, client: &Client, pairs: &Pairs) -> Result<Response> { | ||
| 320 | + let Some(caller) = client.service_key.as_deref() else { | ||
| 321 | + return Ok(oauth_error(StatusCode::BAD_REQUEST, "unauthorized_client")); | ||
| 322 | + }; | ||
| 323 | + let (Some(requested), Some(audience)) = (one(pairs, "scope"), one(pairs, "audience")) else { | ||
| 324 | + return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_request")); | ||
| 325 | + }; | ||
| 326 | + let mut granted: Vec<&str> = Vec::new(); | ||
| 327 | + for word in requested.split_whitespace() { | ||
| 328 | + // A person's scopes never come from this grant, so a user scope is refused like an unknown one. | ||
| 329 | + if !is_supported_scope(word) || is_user_scope(word) || !client.allows_scope(word) { | ||
| 330 | + return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_scope")); | ||
| 331 | + } | ||
| 332 | + if !granted.contains(&word) { | ||
| 333 | + granted.push(word); | ||
| 334 | + } | ||
| 335 | + } | ||
| 336 | + if granted.is_empty() { | ||
| 337 | + return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_scope")); | ||
| 338 | + } | ||
| 339 | + // `im` itself is always a known audience; any other one needs a registered family client. | ||
| 340 | + let known = audience == USERINFO_AUDIENCE | ||
| 341 | + || (is_valid_family_key(audience) && app.store.family_key_known(audience).await?); | ||
| 342 | + if !known { | ||
| 343 | + return Ok(oauth_error(StatusCode::BAD_REQUEST, "invalid_target")); | ||
| 344 | + } | ||
| 345 | + let scope = granted.join(" "); | ||
| 346 | + let now = unix_now(); | ||
| 347 | + let claims = json!({ | ||
| 348 | + "iss": issuer(app), | ||
| 349 | + "sub": format!("client:{}", client.id), | ||
| 350 | + "azp": client.id, | ||
| 351 | + "aud": audience, | ||
| 352 | + "scope": scope, | ||
| 353 | + "svc": caller, | ||
| 354 | + "iat": now, | ||
| 355 | + "exp": now + i64::try_from(ACCESS_TTL.as_secs()).unwrap_or(0), | ||
| 356 | + "jti": generate_token(), | ||
| 357 | + }); | ||
| 358 | + let token = signing::sign(&app.store, &app.key, &claims).await?; | ||
| 359 | + Ok(token_response(token, &scope, None, None)) | ||
| 360 | +} | ||
| 361 | + | ||
| 283 | /// The JSON answer of a successful exchange, with the no-store headers that RFC 6749 requires. | 362 | /// The JSON answer of a successful exchange, with the no-store headers that RFC 6749 requires. |
| 284 | fn token_response( | 363 | fn token_response( |
| 285 | access_token: String, | 364 | access_token: String, |
| @@ -315,7 +394,10 @@ pub fn person_claims(user: &User, scope: &str) -> Map<String, Value> { | |||
| 315 | if granted("profile") { | 394 | if granted("profile") { |
| 316 | claims.insert("name".into(), json!(user.name)); | 395 | claims.insert("name".into(), json!(user.name)); |
| 317 | claims.insert("admin".into(), json!(user.is_admin)); | 396 | claims.insert("admin".into(), json!(user.is_admin)); |
| 318 | - claims.insert("locale".into(), json!(user.locale)); | 397 | + // An account that follows the browser's language has no stored locale to share. |
| 398 | + if !user.locale_auto { | ||
| 399 | + claims.insert("locale".into(), json!(user.locale)); | ||
| 400 | + } | ||
| 319 | claims.insert("zoneinfo".into(), json!(user.zoneinfo)); | 401 | claims.insert("zoneinfo".into(), json!(user.zoneinfo)); |
| 320 | claims.insert("picture_version".into(), json!(user.picture_version)); | 402 | claims.insert("picture_version".into(), json!(user.picture_version)); |
| 321 | } | 403 | } |
| @@ -364,7 +446,7 @@ async fn id_token( | |||
| 364 | "exp": now + i64::try_from(ID_TOKEN_TTL.as_secs()).unwrap_or(0), | 446 | "exp": now + i64::try_from(ID_TOKEN_TTL.as_secs()).unwrap_or(0), |
| 365 | "auth_time": unix_seconds(&session.auth_time).unwrap_or(now), | 447 | "auth_time": unix_seconds(&session.auth_time).unwrap_or(now), |
| 366 | "sid": session.id, | 448 | "sid": session.id, |
| 367 | - "amr": session.amr.split(' ').collect::<Vec<_>>(), | 449 | + "amr": amr::rfc8176(&session.amr), |
| 368 | }); | 450 | }); |
| 369 | if let Some(object) = claims.as_object_mut() { | 451 | if let Some(object) = claims.as_object_mut() { |
| 370 | if let Some(nonce) = nonce { | 452 | if let Some(nonce) = nonce { |
crates/im-web/src/oidc/userinfo.rsmodified+14 -6
| @@ -5,7 +5,7 @@ | |||
| 5 | //! provider), `exp` and `iat`, and the `openid` scope. The token is then checked against the session it | 5 | //! provider), `exp` and `iat`, and the `openid` scope. The token is then checked against the session it |
| 6 | //! names: a session that ended, or a disabled account, refuses the token at once, even before it expires. | 6 | //! names: a session that ended, or a disabled account, refuses the token at once, even before it expires. |
| 7 | 7 | ||
| 8 | -use http::header::{AUTHORIZATION, CACHE_CONTROL, HeaderValue, WWW_AUTHENTICATE}; | 8 | +use http::header::{AUTHORIZATION, HeaderValue, WWW_AUTHENTICATE}; |
| 9 | use im_core::jwt::{self, PublishedKey}; | 9 | use im_core::jwt::{self, PublishedKey}; |
| 10 | use im_core::time::unix_now; | 10 | use im_core::time::unix_now; |
| 11 | use serde_json::{Value, json}; | 11 | use serde_json::{Value, json}; |
| @@ -66,14 +66,22 @@ async fn userinfo(cx: &Cx) -> Result<Response> { | |||
| 66 | if session.user_id != user.id { | 66 | if session.user_id != user.id { |
| 67 | return Ok(unauthorized()); | 67 | return Ok(unauthorized()); |
| 68 | } | 68 | } |
| 69 | + // A token outlives nothing that its client loses: a disabled client's tokens are refused at once. | ||
| 70 | + let Some(client_id) = claims.get("azp").and_then(Value::as_str) else { | ||
| 71 | + return Ok(unauthorized()); | ||
| 72 | + }; | ||
| 73 | + if !app | ||
| 74 | + .store | ||
| 75 | + .client_by_id(client_id) | ||
| 76 | + .await? | ||
| 77 | + .is_some_and(|client| !client.is_disabled()) | ||
| 78 | + { | ||
| 79 | + return Ok(unauthorized()); | ||
| 80 | + } | ||
| 69 | 81 | ||
| 70 | let mut body = person_claims(&user, scope); | 82 | let mut body = person_claims(&user, scope); |
| 71 | body.insert("sub".into(), json!(user.id)); | 83 | body.insert("sub".into(), json!(user.id)); |
| 72 | - let mut response = json_response(StatusCode::OK, &Value::Object(body)); | 84 | + Ok(json_response(StatusCode::OK, &Value::Object(body))) |
| 73 | - response | ||
| 74 | - .headers_mut() | ||
| 75 | - .insert(CACHE_CONTROL, HeaderValue::from_static("no-store")); | ||
| 76 | - Ok(response) | ||
| 77 | } | 85 | } |
| 78 | 86 | ||
| 79 | /// The token of a `Bearer` authorization header, or `None`. | 87 | /// The token of a `Bearer` authorization header, or `None`. |
crates/im-web/src/pages/login.rsmodified+3 -20
| @@ -16,16 +16,15 @@ use serde_json::{Value, json}; | |||
| 16 | use topcoat::Result; | 16 | use topcoat::Result; |
| 17 | use topcoat::context::{Cx, app_context}; | 17 | use topcoat::context::{Cx, app_context}; |
| 18 | use topcoat::router::content::Form; | 18 | use topcoat::router::content::Form; |
| 19 | -use topcoat::router::error::{SeeOther, forbidden, see_other}; | 19 | +use topcoat::router::error::{forbidden, see_other}; |
| 20 | use topcoat::router::response::response_headers; | 20 | use topcoat::router::response::response_headers; |
| 21 | -use topcoat::router::{HeaderValue, StatusCode, header, page, route}; | 21 | +use topcoat::router::{HeaderValue, StatusCode, header, page}; |
| 22 | use topcoat::view::{View, view}; | 22 | use topcoat::view::{View, view}; |
| 23 | 23 | ||
| 24 | use crate::audit::{Actor, record}; | 24 | use crate::audit::{Actor, record}; |
| 25 | use crate::auth::{ | 25 | use crate::auth::{ |
| 26 | after_sign_in, check_pre_csrf, check_second_factor, clear_pending_login, clear_pre_csrf, | 26 | after_sign_in, check_pre_csrf, check_second_factor, clear_pending_login, clear_pre_csrf, |
| 27 | - end_current_session, pending_login, pre_csrf_token, require_csrf, safe_next, set_pending_login, | 27 | + pending_login, pre_csrf_token, safe_next, set_pending_login, start_session, |
| 28 | - start_session, | ||
| 29 | }; | 28 | }; |
| 30 | use crate::client_ip::client_ip; | 29 | use crate::client_ip::client_ip; |
| 31 | use crate::i18n::Lang; | 30 | use crate::i18n::Lang; |
| @@ -232,22 +231,6 @@ async fn two_factor_submit(cx: &Cx, Form(form): Form<TwoFactorForm>) -> Result<i | |||
| 232 | } | 231 | } |
| 233 | } | 232 | } |
| 234 | 233 | ||
| 235 | -/// `POST /logout`. Ends the current session only; other sessions of the person stay. | ||
| 236 | -#[route(POST "/logout")] | ||
| 237 | -async fn logout(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> { | ||
| 238 | - let viewer = require_csrf(cx, &form.csrf).await?; | ||
| 239 | - end_current_session(cx, &viewer).await?; | ||
| 240 | - record( | ||
| 241 | - cx, | ||
| 242 | - Actor::User(&viewer.user.id), | ||
| 243 | - AuditAction::Logout, | ||
| 244 | - Some(("session", &viewer.session.id)), | ||
| 245 | - Value::Null, | ||
| 246 | - ) | ||
| 247 | - .await; | ||
| 248 | - Ok(see_other("/login")) | ||
| 249 | -} | ||
| 250 | - | ||
| 251 | /// Starts the session, clears the pre-session token, audits the sign-in and sends the person on. | 234 | /// Starts the session, clears the pre-session token, audits the sign-in and sends the person on. |
| 252 | async fn finish_sign_in(cx: &Cx, user: &User, method: &str, next: &str) -> Result<topcoat::Error> { | 235 | async fn finish_sign_in(cx: &Cx, user: &User, method: &str, next: &str) -> Result<topcoat::Error> { |
| 253 | let state = app_context::<AppState>(cx); | 236 | let state = app_context::<AppState>(cx); |
crates/im-web/src/pages/security.rsmodified+6 -1
| @@ -9,6 +9,7 @@ use base64::engine::general_purpose::STANDARD as BASE64; | |||
| 9 | use im_core::model::AuditAction; | 9 | use im_core::model::AuditAction; |
| 10 | use im_core::password::{check_policy, hash_password_async, verify_password_async}; | 10 | use im_core::password::{check_policy, hash_password_async, verify_password_async}; |
| 11 | use im_core::secret; | 11 | use im_core::secret; |
| 12 | +use im_core::store::backchannel::EndReason; | ||
| 12 | use im_core::totp; | 13 | use im_core::totp; |
| 13 | use serde::Deserialize; | 14 | use serde::Deserialize; |
| 14 | use serde_json::json; | 15 | use serde_json::json; |
| @@ -175,7 +176,11 @@ async fn change_password(cx: &Cx, Form(form): Form<PasswordForm>) -> Result<impl | |||
| 175 | // Every other session of the person ends with the old password. This one stays signed in. | 176 | // Every other session of the person ends with the old password. This one stays signed in. |
| 176 | let ended = state | 177 | let ended = state |
| 177 | .store | 178 | .store |
| 178 | - .end_other_sessions(&viewer.user.id, &viewer.session.id) | 179 | + .end_other_sessions( |
| 180 | + &viewer.user.id, | ||
| 181 | + &viewer.session.id, | ||
| 182 | + EndReason::PasswordChanged, | ||
| 183 | + ) | ||
| 179 | .await?; | 184 | .await?; |
| 180 | changed(state, &viewer); | 185 | changed(state, &viewer); |
| 181 | record( | 186 | record( |
crates/im-web/src/pages/sessions.rsmodified+4 -3
| @@ -2,6 +2,7 @@ | |||
| 2 | //! one session or every other one. Ending the current session signs the browser out. | 2 | //! one session or every other one. Ending the current session signs the browser out. |
| 3 | 3 | ||
| 4 | use im_core::model::{AuditAction, Session}; | 4 | use im_core::model::{AuditAction, Session}; |
| 5 | +use im_core::store::backchannel::EndReason; | ||
| 5 | use serde::Deserialize; | 6 | use serde::Deserialize; |
| 6 | use serde_json::json; | 7 | use serde_json::json; |
| 7 | use topcoat::Result; | 8 | use topcoat::Result; |
| @@ -130,7 +131,7 @@ async fn revoke_session(cx: &Cx, Form(form): Form<RevokeForm>) -> Result<SeeOthe | |||
| 130 | let viewer = require_csrf(cx, &form.csrf).await?; | 131 | let viewer = require_csrf(cx, &form.csrf).await?; |
| 131 | let state = app_context::<AppState>(cx); | 132 | let state = app_context::<AppState>(cx); |
| 132 | if form.session_id == viewer.session.id { | 133 | if form.session_id == viewer.session.id { |
| 133 | - end_current_session(cx, &viewer).await?; | 134 | + end_current_session(cx, &viewer, EndReason::Revoked).await?; |
| 134 | record( | 135 | record( |
| 135 | cx, | 136 | cx, |
| 136 | Actor::User(&viewer.user.id), | 137 | Actor::User(&viewer.user.id), |
| @@ -143,7 +144,7 @@ async fn revoke_session(cx: &Cx, Form(form): Form<RevokeForm>) -> Result<SeeOthe | |||
| 143 | } | 144 | } |
| 144 | if state | 145 | if state |
| 145 | .store | 146 | .store |
| 146 | - .end_session(&viewer.user.id, &form.session_id) | 147 | + .end_session(&viewer.user.id, &form.session_id, EndReason::Revoked) |
| 147 | .await? | 148 | .await? |
| 148 | { | 149 | { |
| 149 | state.live.bump(&Topic::Account(viewer.user.id.clone())); | 150 | state.live.bump(&Topic::Account(viewer.user.id.clone())); |
| @@ -166,7 +167,7 @@ async fn revoke_others(cx: &Cx, Form(form): Form<CsrfOnly>) -> Result<SeeOther> | |||
| 166 | let state = app_context::<AppState>(cx); | 167 | let state = app_context::<AppState>(cx); |
| 167 | let ended = state | 168 | let ended = state |
| 168 | .store | 169 | .store |
| 169 | - .end_other_sessions(&viewer.user.id, &viewer.session.id) | 170 | + .end_other_sessions(&viewer.user.id, &viewer.session.id, EndReason::Revoked) |
| 170 | .await?; | 171 | .await?; |
| 171 | if !ended.is_empty() { | 172 | if !ended.is_empty() { |
| 172 | state.live.bump(&Topic::Account(viewer.user.id.clone())); | 173 | state.live.bump(&Topic::Account(viewer.user.id.clone())); |
crates/im-web/src/security.rsmodified+47 -2
| @@ -115,8 +115,25 @@ impl Layer for SecurityHeaders { | |||
| 115 | if answer == Answer::Page { | 115 | if answer == Answer::Page { |
| 116 | headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(NO_STORE)); | 116 | headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(NO_STORE)); |
| 117 | } | 117 | } |
| 118 | - response_headers(cx).extend(headers); | 118 | + match next.run(cx, body).await { |
| 119 | - next.run(cx, body).await | 119 | + // A header the route set itself wins: a token answer that is already `no-store`, or a |
| 120 | + // photo with its own stricter policy, must not get a second copy of the same header. | ||
| 121 | + Ok(mut response) => { | ||
| 122 | + let response_map = response.headers_mut(); | ||
| 123 | + for (name, value) in &headers { | ||
| 124 | + if !response_map.contains_key(name) { | ||
| 125 | + response_map.insert(name.clone(), value.clone()); | ||
| 126 | + } | ||
| 127 | + } | ||
| 128 | + Ok(response) | ||
| 129 | + } | ||
| 130 | + // Errors become responses after the layers have run; the per-request slot gives | ||
| 131 | + // them the headers too. | ||
| 132 | + Err(error) => { | ||
| 133 | + response_headers(cx).extend(headers); | ||
| 134 | + Err(error) | ||
| 135 | + } | ||
| 136 | + } | ||
| 120 | }) | 137 | }) |
| 121 | } | 138 | } |
| 122 | } | 139 | } |
| @@ -137,6 +154,34 @@ mod tests { | |||
| 137 | assert_eq!(answer_for("/photographs"), Answer::Page); | 154 | assert_eq!(answer_for("/photographs"), Answer::Page); |
| 138 | } | 155 | } |
| 139 | 156 | ||
| 157 | + #[tokio::test] | ||
| 158 | + async fn a_route_header_is_not_repeated_by_the_layer() { | ||
| 159 | + let (_dir, state) = crate::boot::test_state().await; | ||
| 160 | + for (method, path) in [("POST", "/token"), ("GET", "/photo/01HZ")] { | ||
| 161 | + let request = http::Request::builder() | ||
| 162 | + .method(method) | ||
| 163 | + .uri(path) | ||
| 164 | + .body(topcoat::router::Body::empty()) | ||
| 165 | + .expect("request"); | ||
| 166 | + let response = crate::boot::router(state.clone()).handle(request).await; | ||
| 167 | + let headers = response.headers(); | ||
| 168 | + // A missing photo answers without Cache-Control; a repeat is the bug under test. | ||
| 169 | + let cache_control = headers.get_all(header::CACHE_CONTROL).iter().count(); | ||
| 170 | + assert!(cache_control <= 1, "Cache-Control repeated on {path}"); | ||
| 171 | + if path == "/token" { | ||
| 172 | + assert_eq!(cache_control, 1, "Cache-Control on {path}"); | ||
| 173 | + } | ||
| 174 | + let csp = headers | ||
| 175 | + .get_all(header::CONTENT_SECURITY_POLICY) | ||
| 176 | + .iter() | ||
| 177 | + .count(); | ||
| 178 | + assert!(csp <= 1, "CSP repeated on {path}"); | ||
| 179 | + if path == "/token" { | ||
| 180 | + assert_eq!(csp, 1, "CSP on {path}"); | ||
| 181 | + } | ||
| 182 | + } | ||
| 183 | + } | ||
| 184 | + | ||
| 140 | #[test] | 185 | #[test] |
| 141 | fn hsts_only_for_https_origins() { | 186 | fn hsts_only_for_https_origins() { |
| 142 | assert!( | 187 | assert!( |