Sign in through im: OIDC client, local sessions, back-channel logout, directory mirror, avatar proxy
Browse files at this commitb06a190ef80958dda1e555108c8de8463f2db577Parent: 832b437- feat
- sign in through im: OIDC client, local sessions, back-channel logout, directory mirror, avatar proxy
23 changed files +3263 -32
- Cargo.lock +642 -1
- Cargo.toml +3 -0
- config/iz.example.toml +2 -0
- crates/iz-core/migrations/0002_session_id_token.sql +4 -0
- crates/iz-core/src/config.rs +17 -1
- crates/iz-core/src/store/migrate.rs +4 -1
- crates/iz-core/src/store/mod.rs +1 -1
- crates/iz-core/src/store/sessions.rs +22 -7
- crates/iz-web/Cargo.toml +15 -2
- crates/iz-web/src/auth.rs +322 -0
- crates/iz-web/src/boot.rs +17 -1
- crates/iz-web/src/directory.rs +473 -0
- crates/iz-web/src/i18n/shell.rs +58 -4
- crates/iz-web/src/main.rs +5 -0
- crates/iz-web/src/oidc.rs +832 -0
- crates/iz-web/src/pages/backchannel.rs +202 -0
- crates/iz-web/src/pages/home.rs +27 -8
- crates/iz-web/src/pages/mod.rs +3 -0
- crates/iz-web/src/pages/photo.rs +158 -0
- crates/iz-web/src/pages/sign_in.rs +397 -0
- crates/iz-web/src/state.rs +4 -1
- crates/iz-web/src/views/mod.rs +33 -5
- style/_layout.scss +22 -0
Cargo.lockmodified+642 -1
| @@ -235,6 +235,30 @@ version = "1.5.1" | |||
| 235 | source = "registry+https://github.com/rust-lang/crates.io-index" | 235 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 236 | checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" | 236 | checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" |
| 237 | 237 | ||
| 238 | +[[package]] | ||
| 239 | +name = "aws-lc-rs" | ||
| 240 | +version = "1.18.2" | ||
| 241 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 242 | +checksum = "faac5829c2b74c28f830747e7818ccfb684261b5f48a1118b1e2a13d36dfab13" | ||
| 243 | +dependencies = [ | ||
| 244 | + "aws-lc-sys", | ||
| 245 | + "untrusted 0.7.1", | ||
| 246 | + "zeroize", | ||
| 247 | +] | ||
| 248 | + | ||
| 249 | +[[package]] | ||
| 250 | +name = "aws-lc-sys" | ||
| 251 | +version = "0.46.0" | ||
| 252 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 253 | +checksum = "f1622d8446a2d4b2ce0c7eefc73dd43a99779028d5ee5c2dd8073a658ba8a2bc" | ||
| 254 | +dependencies = [ | ||
| 255 | + "cc", | ||
| 256 | + "cmake", | ||
| 257 | + "dunce", | ||
| 258 | + "fs_extra", | ||
| 259 | + "pkg-config", | ||
| 260 | +] | ||
| 261 | + | ||
| 238 | [[package]] | 262 | [[package]] |
| 239 | name = "base64" | 263 | name = "base64" |
| 240 | version = "0.22.1" | 264 | version = "0.22.1" |
| @@ -545,6 +569,15 @@ version = "1.1.1" | |||
| 545 | source = "registry+https://github.com/rust-lang/crates.io-index" | 569 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 546 | checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" | 570 | checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" |
| 547 | 571 | ||
| 572 | +[[package]] | ||
| 573 | +name = "cmake" | ||
| 574 | +version = "0.1.58" | ||
| 575 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 576 | +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" | ||
| 577 | +dependencies = [ | ||
| 578 | + "cc", | ||
| 579 | +] | ||
| 580 | + | ||
| 548 | [[package]] | 581 | [[package]] |
| 549 | name = "cmov" | 582 | name = "cmov" |
| 550 | version = "0.5.4" | 583 | version = "0.5.4" |
| @@ -563,6 +596,16 @@ version = "1.0.5" | |||
| 563 | source = "registry+https://github.com/rust-lang/crates.io-index" | 596 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 564 | checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" | 597 | checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" |
| 565 | 598 | ||
| 599 | +[[package]] | ||
| 600 | +name = "combine" | ||
| 601 | +version = "4.6.9" | ||
| 602 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 603 | +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" | ||
| 604 | +dependencies = [ | ||
| 605 | + "bytes", | ||
| 606 | + "memchr", | ||
| 607 | +] | ||
| 608 | + | ||
| 566 | [[package]] | 609 | [[package]] |
| 567 | name = "concurrent-queue" | 610 | name = "concurrent-queue" |
| 568 | version = "2.5.0" | 611 | version = "2.5.0" |
| @@ -596,6 +639,16 @@ dependencies = [ | |||
| 596 | "version_check", | 639 | "version_check", |
| 597 | ] | 640 | ] |
| 598 | 641 | ||
| 642 | +[[package]] | ||
| 643 | +name = "core-foundation" | ||
| 644 | +version = "0.10.1" | ||
| 645 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 646 | +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" | ||
| 647 | +dependencies = [ | ||
| 648 | + "core-foundation-sys", | ||
| 649 | + "libc", | ||
| 650 | +] | ||
| 651 | + | ||
| 599 | [[package]] | 652 | [[package]] |
| 600 | name = "core-foundation-sys" | 653 | name = "core-foundation-sys" |
| 601 | version = "0.8.7" | 654 | version = "0.8.7" |
| @@ -849,6 +902,12 @@ version = "2.0.2" | |||
| 849 | source = "registry+https://github.com/rust-lang/crates.io-index" | 902 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 850 | checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc" | 903 | checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc" |
| 851 | 904 | ||
| 905 | +[[package]] | ||
| 906 | +name = "dunce" | ||
| 907 | +version = "1.0.5" | ||
| 908 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 909 | +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" | ||
| 910 | + | ||
| 852 | [[package]] | 911 | [[package]] |
| 853 | name = "either" | 912 | name = "either" |
| 854 | version = "1.19.0" | 913 | version = "1.19.0" |
| @@ -1007,6 +1066,12 @@ dependencies = [ | |||
| 1007 | "windows-sys 0.59.0", | 1066 | "windows-sys 0.59.0", |
| 1008 | ] | 1067 | ] |
| 1009 | 1068 | ||
| 1069 | +[[package]] | ||
| 1070 | +name = "fs_extra" | ||
| 1071 | +version = "1.3.0" | ||
| 1072 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1073 | +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" | ||
| 1074 | + | ||
| 1010 | [[package]] | 1075 | [[package]] |
| 1011 | name = "funty" | 1076 | name = "funty" |
| 1012 | version = "2.0.0" | 1077 | version = "2.0.0" |
| @@ -1028,6 +1093,12 @@ version = "0.3.34" | |||
| 1028 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1093 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1029 | checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" | 1094 | checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" |
| 1030 | 1095 | ||
| 1096 | +[[package]] | ||
| 1097 | +name = "futures-io" | ||
| 1098 | +version = "0.3.34" | ||
| 1099 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1100 | +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" | ||
| 1101 | + | ||
| 1031 | [[package]] | 1102 | [[package]] |
| 1032 | name = "futures-macro" | 1103 | name = "futures-macro" |
| 1033 | version = "0.3.34" | 1104 | version = "0.3.34" |
| @@ -1058,9 +1129,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" | |||
| 1058 | checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" | 1129 | checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" |
| 1059 | dependencies = [ | 1130 | dependencies = [ |
| 1060 | "futures-core", | 1131 | "futures-core", |
| 1132 | + "futures-io", | ||
| 1061 | "futures-macro", | 1133 | "futures-macro", |
| 1062 | "futures-sink", | 1134 | "futures-sink", |
| 1063 | "futures-task", | 1135 | "futures-task", |
| 1136 | + "memchr", | ||
| 1064 | "pin-project-lite", | 1137 | "pin-project-lite", |
| 1065 | "slab", | 1138 | "slab", |
| 1066 | ] | 1139 | ] |
| @@ -1368,6 +1441,22 @@ dependencies = [ | |||
| 1368 | "pin-project-lite", | 1441 | "pin-project-lite", |
| 1369 | "smallvec", | 1442 | "smallvec", |
| 1370 | "tokio", | 1443 | "tokio", |
| 1444 | + "want", | ||
| 1445 | +] | ||
| 1446 | + | ||
| 1447 | +[[package]] | ||
| 1448 | +name = "hyper-rustls" | ||
| 1449 | +version = "0.27.10" | ||
| 1450 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1451 | +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" | ||
| 1452 | +dependencies = [ | ||
| 1453 | + "http", | ||
| 1454 | + "hyper", | ||
| 1455 | + "hyper-util", | ||
| 1456 | + "rustls", | ||
| 1457 | + "tokio", | ||
| 1458 | + "tokio-rustls", | ||
| 1459 | + "tower-service", | ||
| 1371 | ] | 1460 | ] |
| 1372 | 1461 | ||
| 1373 | [[package]] | 1462 | [[package]] |
| @@ -1376,12 +1465,22 @@ version = "0.1.21" | |||
| 1376 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1465 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1377 | checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" | 1466 | checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" |
| 1378 | dependencies = [ | 1467 | dependencies = [ |
| 1468 | + "base64 0.23.1", | ||
| 1379 | "bytes", | 1469 | "bytes", |
| 1470 | + "futures-channel", | ||
| 1471 | + "futures-util", | ||
| 1380 | "http", | 1472 | "http", |
| 1381 | "http-body", | 1473 | "http-body", |
| 1474 | + "httparse", | ||
| 1382 | "hyper", | 1475 | "hyper", |
| 1476 | + "ipnet", | ||
| 1477 | + "libc", | ||
| 1478 | + "percent-encoding", | ||
| 1383 | "pin-project-lite", | 1479 | "pin-project-lite", |
| 1480 | + "socket2", | ||
| 1384 | "tokio", | 1481 | "tokio", |
| 1482 | + "tower-service", | ||
| 1483 | + "tracing", | ||
| 1385 | ] | 1484 | ] |
| 1386 | 1485 | ||
| 1387 | [[package]] | 1486 | [[package]] |
| @@ -1711,13 +1810,22 @@ dependencies = [ | |||
| 1711 | name = "iz-web" | 1810 | name = "iz-web" |
| 1712 | version = "0.1.0" | 1811 | version = "0.1.0" |
| 1713 | dependencies = [ | 1812 | dependencies = [ |
| 1813 | + "aws-lc-rs", | ||
| 1814 | + "base64 0.23.1", | ||
| 1714 | "futures-util", | 1815 | "futures-util", |
| 1715 | "grass", | 1816 | "grass", |
| 1716 | "hex", | 1817 | "hex", |
| 1717 | "http", | 1818 | "http", |
| 1718 | "iz-core", | 1819 | "iz-core", |
| 1820 | + "jsonwebtoken", | ||
| 1821 | + "rand 0.10.3", | ||
| 1822 | + "reqwest", | ||
| 1823 | + "serde", | ||
| 1824 | + "serde_json", | ||
| 1719 | "sha2 0.11.1", | 1825 | "sha2 0.11.1", |
| 1826 | + "subtle", | ||
| 1720 | "tempfile", | 1827 | "tempfile", |
| 1828 | + "thiserror", | ||
| 1721 | "tokio", | 1829 | "tokio", |
| 1722 | "topcoat", | 1830 | "topcoat", |
| 1723 | "tracing", | 1831 | "tracing", |
| @@ -1768,6 +1876,55 @@ version = "0.1.9" | |||
| 1768 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1876 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1769 | checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" | 1877 | checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" |
| 1770 | 1878 | ||
| 1879 | +[[package]] | ||
| 1880 | +name = "jni" | ||
| 1881 | +version = "0.22.4" | ||
| 1882 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1883 | +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" | ||
| 1884 | +dependencies = [ | ||
| 1885 | + "cfg-if", | ||
| 1886 | + "combine", | ||
| 1887 | + "jni-macros", | ||
| 1888 | + "jni-sys", | ||
| 1889 | + "log", | ||
| 1890 | + "simd_cesu8", | ||
| 1891 | + "thiserror", | ||
| 1892 | + "walkdir", | ||
| 1893 | + "windows-link", | ||
| 1894 | +] | ||
| 1895 | + | ||
| 1896 | +[[package]] | ||
| 1897 | +name = "jni-macros" | ||
| 1898 | +version = "0.22.4" | ||
| 1899 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1900 | +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" | ||
| 1901 | +dependencies = [ | ||
| 1902 | + "proc-macro2", | ||
| 1903 | + "quote", | ||
| 1904 | + "rustc_version", | ||
| 1905 | + "simd_cesu8", | ||
| 1906 | + "syn 2.0.119", | ||
| 1907 | +] | ||
| 1908 | + | ||
| 1909 | +[[package]] | ||
| 1910 | +name = "jni-sys" | ||
| 1911 | +version = "0.4.1" | ||
| 1912 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1913 | +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" | ||
| 1914 | +dependencies = [ | ||
| 1915 | + "jni-sys-macros", | ||
| 1916 | +] | ||
| 1917 | + | ||
| 1918 | +[[package]] | ||
| 1919 | +name = "jni-sys-macros" | ||
| 1920 | +version = "0.4.1" | ||
| 1921 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1922 | +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" | ||
| 1923 | +dependencies = [ | ||
| 1924 | + "quote", | ||
| 1925 | + "syn 2.0.119", | ||
| 1926 | +] | ||
| 1927 | + | ||
| 1771 | [[package]] | 1928 | [[package]] |
| 1772 | name = "jobserver" | 1929 | name = "jobserver" |
| 1773 | version = "0.1.35" | 1930 | version = "0.1.35" |
| @@ -1789,6 +1946,22 @@ dependencies = [ | |||
| 1789 | "wasm-bindgen", | 1946 | "wasm-bindgen", |
| 1790 | ] | 1947 | ] |
| 1791 | 1948 | ||
| 1949 | +[[package]] | ||
| 1950 | +name = "jsonwebtoken" | ||
| 1951 | +version = "11.1.0" | ||
| 1952 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1953 | +checksum = "e75fe14a82d81e5f5af639997db37d8b96045938a7ac6ab18cdbe1c7467e05e1" | ||
| 1954 | +dependencies = [ | ||
| 1955 | + "aws-lc-rs", | ||
| 1956 | + "base64 0.22.1", | ||
| 1957 | + "getrandom 0.2.17", | ||
| 1958 | + "js-sys", | ||
| 1959 | + "serde", | ||
| 1960 | + "serde_json", | ||
| 1961 | + "signature", | ||
| 1962 | + "zeroize", | ||
| 1963 | +] | ||
| 1964 | + | ||
| 1792 | [[package]] | 1965 | [[package]] |
| 1793 | name = "lasso" | 1966 | name = "lasso" |
| 1794 | version = "0.7.3" | 1967 | version = "0.7.3" |
| @@ -1939,6 +2112,12 @@ dependencies = [ | |||
| 1939 | "hashbrown 0.16.1", | 2112 | "hashbrown 0.16.1", |
| 1940 | ] | 2113 | ] |
| 1941 | 2114 | ||
| 2115 | +[[package]] | ||
| 2116 | +name = "lru-slab" | ||
| 2117 | +version = "0.1.3" | ||
| 2118 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2119 | +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" | ||
| 2120 | + | ||
| 1942 | [[package]] | 2121 | [[package]] |
| 1943 | name = "lz4_flex" | 2122 | name = "lz4_flex" |
| 1944 | version = "0.13.1" | 2123 | version = "0.13.1" |
| @@ -2162,6 +2341,12 @@ version = "0.3.1" | |||
| 2162 | source = "registry+https://github.com/rust-lang/crates.io-index" | 2341 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2163 | checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" | 2342 | checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" |
| 2164 | 2343 | ||
| 2344 | +[[package]] | ||
| 2345 | +name = "openssl-probe" | ||
| 2346 | +version = "0.2.2" | ||
| 2347 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2348 | +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" | ||
| 2349 | + | ||
| 2165 | [[package]] | 2350 | [[package]] |
| 2166 | name = "ordered-float" | 2351 | name = "ordered-float" |
| 2167 | version = "5.5.1" | 2352 | version = "5.5.1" |
| @@ -2422,6 +2607,63 @@ dependencies = [ | |||
| 2422 | "syn 2.0.119", | 2607 | "syn 2.0.119", |
| 2423 | ] | 2608 | ] |
| 2424 | 2609 | ||
| 2610 | +[[package]] | ||
| 2611 | +name = "quinn" | ||
| 2612 | +version = "0.11.12" | ||
| 2613 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2614 | +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" | ||
| 2615 | +dependencies = [ | ||
| 2616 | + "bytes", | ||
| 2617 | + "cfg_aliases", | ||
| 2618 | + "pin-project-lite", | ||
| 2619 | + "quinn-proto", | ||
| 2620 | + "quinn-udp", | ||
| 2621 | + "rustc-hash 2.1.3", | ||
| 2622 | + "rustls", | ||
| 2623 | + "socket2", | ||
| 2624 | + "thiserror", | ||
| 2625 | + "tokio", | ||
| 2626 | + "tracing", | ||
| 2627 | + "web-time", | ||
| 2628 | +] | ||
| 2629 | + | ||
| 2630 | +[[package]] | ||
| 2631 | +name = "quinn-proto" | ||
| 2632 | +version = "0.11.19" | ||
| 2633 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2634 | +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" | ||
| 2635 | +dependencies = [ | ||
| 2636 | + "aws-lc-rs", | ||
| 2637 | + "bytes", | ||
| 2638 | + "getrandom 0.4.3", | ||
| 2639 | + "lru-slab", | ||
| 2640 | + "rand 0.10.3", | ||
| 2641 | + "rand_pcg 0.10.2", | ||
| 2642 | + "ring", | ||
| 2643 | + "rustc-hash 2.1.3", | ||
| 2644 | + "rustls", | ||
| 2645 | + "rustls-pki-types", | ||
| 2646 | + "slab", | ||
| 2647 | + "thiserror", | ||
| 2648 | + "tinyvec", | ||
| 2649 | + "tracing", | ||
| 2650 | + "web-time", | ||
| 2651 | +] | ||
| 2652 | + | ||
| 2653 | +[[package]] | ||
| 2654 | +name = "quinn-udp" | ||
| 2655 | +version = "0.5.16" | ||
| 2656 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2657 | +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" | ||
| 2658 | +dependencies = [ | ||
| 2659 | + "cfg_aliases", | ||
| 2660 | + "libc", | ||
| 2661 | + "once_cell", | ||
| 2662 | + "socket2", | ||
| 2663 | + "tracing", | ||
| 2664 | + "windows-sys 0.61.2", | ||
| 2665 | +] | ||
| 2666 | + | ||
| 2425 | [[package]] | 2667 | [[package]] |
| 2426 | name = "quote" | 2668 | name = "quote" |
| 2427 | version = "1.0.47" | 2669 | version = "1.0.47" |
| @@ -2540,6 +2782,15 @@ dependencies = [ | |||
| 2540 | "rand_core 0.6.4", | 2782 | "rand_core 0.6.4", |
| 2541 | ] | 2783 | ] |
| 2542 | 2784 | ||
| 2785 | +[[package]] | ||
| 2786 | +name = "rand_pcg" | ||
| 2787 | +version = "0.10.2" | ||
| 2788 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2789 | +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" | ||
| 2790 | +dependencies = [ | ||
| 2791 | + "rand_core 0.10.1", | ||
| 2792 | +] | ||
| 2793 | + | ||
| 2543 | [[package]] | 2794 | [[package]] |
| 2544 | name = "rapidhash" | 2795 | name = "rapidhash" |
| 2545 | version = "4.5.1" | 2796 | version = "4.5.1" |
| @@ -2627,6 +2878,61 @@ version = "0.8.11" | |||
| 2627 | source = "registry+https://github.com/rust-lang/crates.io-index" | 2878 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2628 | checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" | 2879 | checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" |
| 2629 | 2880 | ||
| 2881 | +[[package]] | ||
| 2882 | +name = "reqwest" | ||
| 2883 | +version = "0.13.5" | ||
| 2884 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2885 | +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" | ||
| 2886 | +dependencies = [ | ||
| 2887 | + "base64 0.23.1", | ||
| 2888 | + "bytes", | ||
| 2889 | + "futures-core", | ||
| 2890 | + "futures-util", | ||
| 2891 | + "http", | ||
| 2892 | + "http-body", | ||
| 2893 | + "http-body-util", | ||
| 2894 | + "hyper", | ||
| 2895 | + "hyper-rustls", | ||
| 2896 | + "hyper-util", | ||
| 2897 | + "js-sys", | ||
| 2898 | + "log", | ||
| 2899 | + "percent-encoding", | ||
| 2900 | + "pin-project-lite", | ||
| 2901 | + "quinn", | ||
| 2902 | + "rustls", | ||
| 2903 | + "rustls-pki-types", | ||
| 2904 | + "rustls-platform-verifier", | ||
| 2905 | + "serde", | ||
| 2906 | + "serde_json", | ||
| 2907 | + "serde_urlencoded", | ||
| 2908 | + "sync_wrapper", | ||
| 2909 | + "tokio", | ||
| 2910 | + "tokio-rustls", | ||
| 2911 | + "tokio-util", | ||
| 2912 | + "tower", | ||
| 2913 | + "tower-http", | ||
| 2914 | + "tower-service", | ||
| 2915 | + "url", | ||
| 2916 | + "wasm-bindgen", | ||
| 2917 | + "wasm-bindgen-futures", | ||
| 2918 | + "wasm-streams", | ||
| 2919 | + "web-sys", | ||
| 2920 | +] | ||
| 2921 | + | ||
| 2922 | +[[package]] | ||
| 2923 | +name = "ring" | ||
| 2924 | +version = "0.17.14" | ||
| 2925 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2926 | +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" | ||
| 2927 | +dependencies = [ | ||
| 2928 | + "cc", | ||
| 2929 | + "cfg-if", | ||
| 2930 | + "getrandom 0.2.17", | ||
| 2931 | + "libc", | ||
| 2932 | + "untrusted 0.9.0", | ||
| 2933 | + "windows-sys 0.52.0", | ||
| 2934 | +] | ||
| 2935 | + | ||
| 2630 | [[package]] | 2936 | [[package]] |
| 2631 | name = "roaring" | 2937 | name = "roaring" |
| 2632 | version = "0.11.5" | 2938 | version = "0.11.5" |
| @@ -2704,6 +3010,81 @@ dependencies = [ | |||
| 2704 | "windows-sys 0.61.2", | 3010 | "windows-sys 0.61.2", |
| 2705 | ] | 3011 | ] |
| 2706 | 3012 | ||
| 3013 | +[[package]] | ||
| 3014 | +name = "rustls" | ||
| 3015 | +version = "0.23.46" | ||
| 3016 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3017 | +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" | ||
| 3018 | +dependencies = [ | ||
| 3019 | + "aws-lc-rs", | ||
| 3020 | + "once_cell", | ||
| 3021 | + "rustls-pki-types", | ||
| 3022 | + "rustls-webpki", | ||
| 3023 | + "subtle", | ||
| 3024 | + "zeroize", | ||
| 3025 | +] | ||
| 3026 | + | ||
| 3027 | +[[package]] | ||
| 3028 | +name = "rustls-native-certs" | ||
| 3029 | +version = "0.8.5" | ||
| 3030 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3031 | +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" | ||
| 3032 | +dependencies = [ | ||
| 3033 | + "openssl-probe", | ||
| 3034 | + "rustls-pki-types", | ||
| 3035 | + "schannel", | ||
| 3036 | + "security-framework", | ||
| 3037 | +] | ||
| 3038 | + | ||
| 3039 | +[[package]] | ||
| 3040 | +name = "rustls-pki-types" | ||
| 3041 | +version = "1.15.1" | ||
| 3042 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3043 | +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" | ||
| 3044 | +dependencies = [ | ||
| 3045 | + "web-time", | ||
| 3046 | + "zeroize", | ||
| 3047 | +] | ||
| 3048 | + | ||
| 3049 | +[[package]] | ||
| 3050 | +name = "rustls-platform-verifier" | ||
| 3051 | +version = "0.7.1" | ||
| 3052 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3053 | +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" | ||
| 3054 | +dependencies = [ | ||
| 3055 | + "core-foundation", | ||
| 3056 | + "core-foundation-sys", | ||
| 3057 | + "jni", | ||
| 3058 | + "log", | ||
| 3059 | + "once_cell", | ||
| 3060 | + "rustls", | ||
| 3061 | + "rustls-native-certs", | ||
| 3062 | + "rustls-platform-verifier-android", | ||
| 3063 | + "rustls-webpki", | ||
| 3064 | + "security-framework", | ||
| 3065 | + "security-framework-sys", | ||
| 3066 | + "webpki-root-certs", | ||
| 3067 | + "windows-sys 0.61.2", | ||
| 3068 | +] | ||
| 3069 | + | ||
| 3070 | +[[package]] | ||
| 3071 | +name = "rustls-platform-verifier-android" | ||
| 3072 | +version = "0.2.0" | ||
| 3073 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3074 | +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" | ||
| 3075 | + | ||
| 3076 | +[[package]] | ||
| 3077 | +name = "rustls-webpki" | ||
| 3078 | +version = "0.103.16" | ||
| 3079 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3080 | +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" | ||
| 3081 | +dependencies = [ | ||
| 3082 | + "aws-lc-rs", | ||
| 3083 | + "ring", | ||
| 3084 | + "rustls-pki-types", | ||
| 3085 | + "untrusted 0.9.0", | ||
| 3086 | +] | ||
| 3087 | + | ||
| 2707 | [[package]] | 3088 | [[package]] |
| 2708 | name = "rustversion" | 3089 | name = "rustversion" |
| 2709 | version = "1.0.23" | 3090 | version = "1.0.23" |
| @@ -2716,6 +3097,24 @@ version = "1.0.23" | |||
| 2716 | source = "registry+https://github.com/rust-lang/crates.io-index" | 3097 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2717 | checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" | 3098 | checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" |
| 2718 | 3099 | ||
| 3100 | +[[package]] | ||
| 3101 | +name = "same-file" | ||
| 3102 | +version = "1.0.6" | ||
| 3103 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3104 | +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" | ||
| 3105 | +dependencies = [ | ||
| 3106 | + "winapi-util", | ||
| 3107 | +] | ||
| 3108 | + | ||
| 3109 | +[[package]] | ||
| 3110 | +name = "schannel" | ||
| 3111 | +version = "0.1.30" | ||
| 3112 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3113 | +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" | ||
| 3114 | +dependencies = [ | ||
| 3115 | + "windows-sys 0.61.2", | ||
| 3116 | +] | ||
| 3117 | + | ||
| 2719 | [[package]] | 3118 | [[package]] |
| 2720 | name = "scoped-tls" | 3119 | name = "scoped-tls" |
| 2721 | version = "1.0.1" | 3120 | version = "1.0.1" |
| @@ -2728,6 +3127,29 @@ version = "1.2.0" | |||
| 2728 | source = "registry+https://github.com/rust-lang/crates.io-index" | 3127 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2729 | checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" | 3128 | checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" |
| 2730 | 3129 | ||
| 3130 | +[[package]] | ||
| 3131 | +name = "security-framework" | ||
| 3132 | +version = "3.7.0" | ||
| 3133 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3134 | +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" | ||
| 3135 | +dependencies = [ | ||
| 3136 | + "bitflags 2.13.2", | ||
| 3137 | + "core-foundation", | ||
| 3138 | + "core-foundation-sys", | ||
| 3139 | + "libc", | ||
| 3140 | + "security-framework-sys", | ||
| 3141 | +] | ||
| 3142 | + | ||
| 3143 | +[[package]] | ||
| 3144 | +name = "security-framework-sys" | ||
| 3145 | +version = "2.17.0" | ||
| 3146 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3147 | +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" | ||
| 3148 | +dependencies = [ | ||
| 3149 | + "core-foundation-sys", | ||
| 3150 | + "libc", | ||
| 3151 | +] | ||
| 3152 | + | ||
| 2731 | [[package]] | 3153 | [[package]] |
| 2732 | name = "semver" | 3154 | name = "semver" |
| 2733 | version = "1.0.28" | 3155 | version = "1.0.28" |
| @@ -2883,7 +3305,7 @@ dependencies = [ | |||
| 2883 | "owo-colors", | 3305 | "owo-colors", |
| 2884 | "rand 0.8.8", | 3306 | "rand 0.8.8", |
| 2885 | "rand_core 0.6.4", | 3307 | "rand_core 0.6.4", |
| 2886 | - "rand_pcg", | 3308 | + "rand_pcg 0.3.1", |
| 2887 | "scoped-tls", | 3309 | "scoped-tls", |
| 2888 | "smallvec", | 3310 | "smallvec", |
| 2889 | "tracing", | 3311 | "tracing", |
| @@ -2899,6 +3321,25 @@ dependencies = [ | |||
| 2899 | "libc", | 3321 | "libc", |
| 2900 | ] | 3322 | ] |
| 2901 | 3323 | ||
| 3324 | +[[package]] | ||
| 3325 | +name = "signature" | ||
| 3326 | +version = "2.2.0" | ||
| 3327 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3328 | +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" | ||
| 3329 | +dependencies = [ | ||
| 3330 | + "rand_core 0.6.4", | ||
| 3331 | +] | ||
| 3332 | + | ||
| 3333 | +[[package]] | ||
| 3334 | +name = "simd_cesu8" | ||
| 3335 | +version = "1.2.0" | ||
| 3336 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3337 | +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" | ||
| 3338 | +dependencies = [ | ||
| 3339 | + "rustc_version", | ||
| 3340 | + "simdutf8", | ||
| 3341 | +] | ||
| 3342 | + | ||
| 2902 | [[package]] | 3343 | [[package]] |
| 2903 | name = "simdutf8" | 3344 | name = "simdutf8" |
| 2904 | version = "0.1.5" | 3345 | version = "0.1.5" |
| @@ -3031,6 +3472,15 @@ dependencies = [ | |||
| 3031 | "unicode-ident", | 3472 | "unicode-ident", |
| 3032 | ] | 3473 | ] |
| 3033 | 3474 | ||
| 3475 | +[[package]] | ||
| 3476 | +name = "sync_wrapper" | ||
| 3477 | +version = "1.0.2" | ||
| 3478 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3479 | +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" | ||
| 3480 | +dependencies = [ | ||
| 3481 | + "futures-core", | ||
| 3482 | +] | ||
| 3483 | + | ||
| 3034 | [[package]] | 3484 | [[package]] |
| 3035 | name = "synstructure" | 3485 | name = "synstructure" |
| 3036 | version = "0.14.0" | 3486 | version = "0.14.0" |
| @@ -3279,6 +3729,12 @@ dependencies = [ | |||
| 3279 | "zerovec", | 3729 | "zerovec", |
| 3280 | ] | 3730 | ] |
| 3281 | 3731 | ||
| 3732 | +[[package]] | ||
| 3733 | +name = "tinyvec" | ||
| 3734 | +version = "1.13.3" | ||
| 3735 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3736 | +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" | ||
| 3737 | + | ||
| 3282 | [[package]] | 3738 | [[package]] |
| 3283 | name = "tokio" | 3739 | name = "tokio" |
| 3284 | version = "1.54.1" | 3740 | version = "1.54.1" |
| @@ -3306,6 +3762,16 @@ dependencies = [ | |||
| 3306 | "syn 3.0.9", | 3762 | "syn 3.0.9", |
| 3307 | ] | 3763 | ] |
| 3308 | 3764 | ||
| 3765 | +[[package]] | ||
| 3766 | +name = "tokio-rustls" | ||
| 3767 | +version = "0.26.6" | ||
| 3768 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3769 | +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" | ||
| 3770 | +dependencies = [ | ||
| 3771 | + "rustls", | ||
| 3772 | + "tokio", | ||
| 3773 | +] | ||
| 3774 | + | ||
| 3309 | [[package]] | 3775 | [[package]] |
| 3310 | name = "tokio-tungstenite" | 3776 | name = "tokio-tungstenite" |
| 3311 | version = "0.29.0" | 3777 | version = "0.29.0" |
| @@ -3713,6 +4179,51 @@ dependencies = [ | |||
| 3713 | "topcoat-view-grammar", | 4179 | "topcoat-view-grammar", |
| 3714 | ] | 4180 | ] |
| 3715 | 4181 | ||
| 4182 | +[[package]] | ||
| 4183 | +name = "tower" | ||
| 4184 | +version = "0.5.3" | ||
| 4185 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4186 | +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" | ||
| 4187 | +dependencies = [ | ||
| 4188 | + "futures-core", | ||
| 4189 | + "futures-util", | ||
| 4190 | + "pin-project-lite", | ||
| 4191 | + "sync_wrapper", | ||
| 4192 | + "tokio", | ||
| 4193 | + "tower-layer", | ||
| 4194 | + "tower-service", | ||
| 4195 | +] | ||
| 4196 | + | ||
| 4197 | +[[package]] | ||
| 4198 | +name = "tower-http" | ||
| 4199 | +version = "0.6.11" | ||
| 4200 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4201 | +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" | ||
| 4202 | +dependencies = [ | ||
| 4203 | + "bitflags 2.13.2", | ||
| 4204 | + "bytes", | ||
| 4205 | + "futures-util", | ||
| 4206 | + "http", | ||
| 4207 | + "http-body", | ||
| 4208 | + "pin-project-lite", | ||
| 4209 | + "tower", | ||
| 4210 | + "tower-layer", | ||
| 4211 | + "tower-service", | ||
| 4212 | + "url", | ||
| 4213 | +] | ||
| 4214 | + | ||
| 4215 | +[[package]] | ||
| 4216 | +name = "tower-layer" | ||
| 4217 | +version = "0.3.3" | ||
| 4218 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4219 | +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" | ||
| 4220 | + | ||
| 4221 | +[[package]] | ||
| 4222 | +name = "tower-service" | ||
| 4223 | +version = "0.3.3" | ||
| 4224 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4225 | +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" | ||
| 4226 | + | ||
| 3716 | [[package]] | 4227 | [[package]] |
| 3717 | name = "tracing" | 4228 | name = "tracing" |
| 3718 | version = "0.1.44" | 4229 | version = "0.1.44" |
| @@ -3787,6 +4298,12 @@ dependencies = [ | |||
| 3787 | "tracing-log", | 4298 | "tracing-log", |
| 3788 | ] | 4299 | ] |
| 3789 | 4300 | ||
| 4301 | +[[package]] | ||
| 4302 | +name = "try-lock" | ||
| 4303 | +version = "0.2.5" | ||
| 4304 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4305 | +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" | ||
| 4306 | + | ||
| 3790 | [[package]] | 4307 | [[package]] |
| 3791 | name = "tungstenite" | 4308 | name = "tungstenite" |
| 3792 | version = "0.29.0" | 4309 | version = "0.29.0" |
| @@ -4096,6 +4613,30 @@ dependencies = [ | |||
| 4096 | "ctutils", | 4613 | "ctutils", |
| 4097 | ] | 4614 | ] |
| 4098 | 4615 | ||
| 4616 | +[[package]] | ||
| 4617 | +name = "untrusted" | ||
| 4618 | +version = "0.7.1" | ||
| 4619 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4620 | +checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" | ||
| 4621 | + | ||
| 4622 | +[[package]] | ||
| 4623 | +name = "untrusted" | ||
| 4624 | +version = "0.9.0" | ||
| 4625 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4626 | +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" | ||
| 4627 | + | ||
| 4628 | +[[package]] | ||
| 4629 | +name = "url" | ||
| 4630 | +version = "2.5.8" | ||
| 4631 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4632 | +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" | ||
| 4633 | +dependencies = [ | ||
| 4634 | + "form_urlencoded", | ||
| 4635 | + "idna", | ||
| 4636 | + "percent-encoding", | ||
| 4637 | + "serde", | ||
| 4638 | +] | ||
| 4639 | + | ||
| 4099 | [[package]] | 4640 | [[package]] |
| 4100 | name = "utf16_iter" | 4641 | name = "utf16_iter" |
| 4101 | version = "1.0.5" | 4642 | version = "1.0.5" |
| @@ -4145,6 +4686,25 @@ version = "0.9.5" | |||
| 4145 | source = "registry+https://github.com/rust-lang/crates.io-index" | 4686 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 4146 | checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" | 4687 | checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" |
| 4147 | 4688 | ||
| 4689 | +[[package]] | ||
| 4690 | +name = "walkdir" | ||
| 4691 | +version = "2.5.0" | ||
| 4692 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4693 | +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" | ||
| 4694 | +dependencies = [ | ||
| 4695 | + "same-file", | ||
| 4696 | + "winapi-util", | ||
| 4697 | +] | ||
| 4698 | + | ||
| 4699 | +[[package]] | ||
| 4700 | +name = "want" | ||
| 4701 | +version = "0.3.2" | ||
| 4702 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4703 | +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" | ||
| 4704 | +dependencies = [ | ||
| 4705 | + "try-lock", | ||
| 4706 | +] | ||
| 4707 | + | ||
| 4148 | [[package]] | 4708 | [[package]] |
| 4149 | name = "wasi" | 4709 | name = "wasi" |
| 4150 | version = "0.11.1+wasi-snapshot-preview1" | 4710 | version = "0.11.1+wasi-snapshot-preview1" |
| @@ -4173,6 +4733,17 @@ dependencies = [ | |||
| 4173 | "wasm-bindgen-shared", | 4733 | "wasm-bindgen-shared", |
| 4174 | ] | 4734 | ] |
| 4175 | 4735 | ||
| 4736 | +[[package]] | ||
| 4737 | +name = "wasm-bindgen-futures" | ||
| 4738 | +version = "0.4.79" | ||
| 4739 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4740 | +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" | ||
| 4741 | +dependencies = [ | ||
| 4742 | + "js-sys", | ||
| 4743 | + "tokio", | ||
| 4744 | + "wasm-bindgen", | ||
| 4745 | +] | ||
| 4746 | + | ||
| 4176 | [[package]] | 4747 | [[package]] |
| 4177 | name = "wasm-bindgen-macro" | 4748 | name = "wasm-bindgen-macro" |
| 4178 | version = "0.2.129" | 4749 | version = "0.2.129" |
| @@ -4205,6 +4776,29 @@ dependencies = [ | |||
| 4205 | "unicode-ident", | 4776 | "unicode-ident", |
| 4206 | ] | 4777 | ] |
| 4207 | 4778 | ||
| 4779 | +[[package]] | ||
| 4780 | +name = "wasm-streams" | ||
| 4781 | +version = "0.5.0" | ||
| 4782 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4783 | +checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" | ||
| 4784 | +dependencies = [ | ||
| 4785 | + "futures-util", | ||
| 4786 | + "js-sys", | ||
| 4787 | + "wasm-bindgen", | ||
| 4788 | + "wasm-bindgen-futures", | ||
| 4789 | + "web-sys", | ||
| 4790 | +] | ||
| 4791 | + | ||
| 4792 | +[[package]] | ||
| 4793 | +name = "web-sys" | ||
| 4794 | +version = "0.3.106" | ||
| 4795 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4796 | +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" | ||
| 4797 | +dependencies = [ | ||
| 4798 | + "js-sys", | ||
| 4799 | + "wasm-bindgen", | ||
| 4800 | +] | ||
| 4801 | + | ||
| 4208 | [[package]] | 4802 | [[package]] |
| 4209 | name = "web-time" | 4803 | name = "web-time" |
| 4210 | version = "1.1.0" | 4804 | version = "1.1.0" |
| @@ -4215,6 +4809,15 @@ dependencies = [ | |||
| 4215 | "wasm-bindgen", | 4809 | "wasm-bindgen", |
| 4216 | ] | 4810 | ] |
| 4217 | 4811 | ||
| 4812 | +[[package]] | ||
| 4813 | +name = "webpki-root-certs" | ||
| 4814 | +version = "1.0.11" | ||
| 4815 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4816 | +checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" | ||
| 4817 | +dependencies = [ | ||
| 4818 | + "rustls-pki-types", | ||
| 4819 | +] | ||
| 4820 | + | ||
| 4218 | [[package]] | 4821 | [[package]] |
| 4219 | name = "which" | 4822 | name = "which" |
| 4220 | version = "4.4.2" | 4823 | version = "4.4.2" |
| @@ -4243,6 +4846,15 @@ version = "0.4.0" | |||
| 4243 | source = "registry+https://github.com/rust-lang/crates.io-index" | 4846 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 4244 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" | 4847 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" |
| 4245 | 4848 | ||
| 4849 | +[[package]] | ||
| 4850 | +name = "winapi-util" | ||
| 4851 | +version = "0.1.11" | ||
| 4852 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4853 | +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" | ||
| 4854 | +dependencies = [ | ||
| 4855 | + "windows-sys 0.61.2", | ||
| 4856 | +] | ||
| 4857 | + | ||
| 4246 | [[package]] | 4858 | [[package]] |
| 4247 | name = "winapi-x86_64-pc-windows-gnu" | 4859 | name = "winapi-x86_64-pc-windows-gnu" |
| 4248 | version = "0.4.0" | 4860 | version = "0.4.0" |
| @@ -4308,6 +4920,15 @@ dependencies = [ | |||
| 4308 | "windows-link", | 4920 | "windows-link", |
| 4309 | ] | 4921 | ] |
| 4310 | 4922 | ||
| 4923 | +[[package]] | ||
| 4924 | +name = "windows-sys" | ||
| 4925 | +version = "0.52.0" | ||
| 4926 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4927 | +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" | ||
| 4928 | +dependencies = [ | ||
| 4929 | + "windows-targets", | ||
| 4930 | +] | ||
| 4931 | + | ||
| 4311 | [[package]] | 4932 | [[package]] |
| 4312 | name = "windows-sys" | 4933 | name = "windows-sys" |
| 4313 | version = "0.59.0" | 4934 | version = "0.59.0" |
| @@ -4490,6 +5111,26 @@ dependencies = [ | |||
| 4490 | "synstructure", | 5111 | "synstructure", |
| 4491 | ] | 5112 | ] |
| 4492 | 5113 | ||
| 5114 | +[[package]] | ||
| 5115 | +name = "zeroize" | ||
| 5116 | +version = "1.9.1" | ||
| 5117 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 5118 | +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" | ||
| 5119 | +dependencies = [ | ||
| 5120 | + "zeroize_derive", | ||
| 5121 | +] | ||
| 5122 | + | ||
| 5123 | +[[package]] | ||
| 5124 | +name = "zeroize_derive" | ||
| 5125 | +version = "1.5.0" | ||
| 5126 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 5127 | +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" | ||
| 5128 | +dependencies = [ | ||
| 5129 | + "proc-macro2", | ||
| 5130 | + "quote", | ||
| 5131 | + "syn 2.0.119", | ||
| 5132 | +] | ||
| 5133 | + | ||
| 4493 | [[package]] | 5134 | [[package]] |
| 4494 | name = "zerotrie" | 5135 | name = "zerotrie" |
| 4495 | version = "0.2.5" | 5136 | version = "0.2.5" |
Cargo.tomlmodified+3 -0
| @@ -12,6 +12,7 @@ license = "AGPL-3.0-or-later" | |||
| 12 | 12 | ||
| 13 | [workspace.dependencies] | 13 | [workspace.dependencies] |
| 14 | # external crates (versions are the latest releases when added) | 14 | # external crates (versions are the latest releases when added) |
| 15 | +aws-lc-rs = "1.18.2" | ||
| 15 | base64 = "0.23.1" | 16 | base64 = "0.23.1" |
| 16 | futures-util = "0.3.34" | 17 | futures-util = "0.3.34" |
| 17 | grass = "0.13.4" | 18 | grass = "0.13.4" |
| @@ -19,8 +20,10 @@ http = "1.5.0" | |||
| 19 | chacha20poly1305 = "0.11.0" | 20 | chacha20poly1305 = "0.11.0" |
| 20 | hex = "0.4.3" | 21 | hex = "0.4.3" |
| 21 | ipnet = "2.12.2" | 22 | ipnet = "2.12.2" |
| 23 | +jsonwebtoken = { version = "11.1.0", default-features = false, features = ["aws_lc_rs"] } | ||
| 22 | jiff = { version = "0.2.38", default-features = false, features = ["std", "tzdb-bundle-always"] } | 24 | jiff = { version = "0.2.38", default-features = false, features = ["std", "tzdb-bundle-always"] } |
| 23 | rand = "0.10.3" | 25 | rand = "0.10.3" |
| 26 | +reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "form", "json", "stream"] } | ||
| 24 | serde = "1.0.229" | 27 | serde = "1.0.229" |
| 25 | serde_json = "1.0.154" | 28 | serde_json = "1.0.154" |
| 26 | sha2 = "0.11.1" | 29 | sha2 = "0.11.1" |
config/iz.example.tomlmodified+2 -0
| @@ -13,9 +13,11 @@ base_url = "http://127.0.0.1:7654" | |||
| 13 | trusted_proxies = [] | 13 | trusted_proxies = [] |
| 14 | 14 | ||
| 15 | # Identity provider (OpenID Connect). Uncomment to enable sign-in. | 15 | # Identity provider (OpenID Connect). Uncomment to enable sign-in. |
| 16 | +# The client secret is read from client_secret_file at boot. That file must be mode 0600 or 0400. | ||
| 16 | # [oidc] | 17 | # [oidc] |
| 17 | # issuer = "https://im.example.com" | 18 | # issuer = "https://im.example.com" |
| 18 | # client_id = "iz" | 19 | # client_id = "iz" |
| 20 | +# client_secret_file = "data/oidc_client_secret" | ||
| 19 | 21 | ||
| 20 | # Attachments in the external Files service instead of local disk. | 22 | # Attachments in the external Files service instead of local disk. |
| 21 | [in_store] | 23 | [in_store] |
crates/iz-core/migrations/0002_session_id_token.sqladded+4 -0
| @@ -0,0 +1,4 @@ | |||
| 1 | +-- 0002: the sealed ID token of each local session. It is the id_token_hint of the RP-initiated logout | ||
| 2 | +-- (docs/contracts.md 2.5). It is sealed with the instance key (secret::seal), so a leaked row does not | ||
| 3 | +-- hold a usable token. NULL for sessions that were created without one. | ||
| 4 | +ALTER TABLE sessions ADD COLUMN id_token_sealed TEXT; | ||
crates/iz-core/src/config.rsmodified+17 -1
| @@ -51,6 +51,9 @@ pub struct OidcConfig { | |||
| 51 | pub issuer: String, | 51 | pub issuer: String, |
| 52 | /// Client id registered with the provider. | 52 | /// Client id registered with the provider. |
| 53 | pub client_id: String, | 53 | pub client_id: String, |
| 54 | + /// File holding the client secret, read at boot. It must not be readable by group or others, | ||
| 55 | + /// and it is never stored in the database or in this file. | ||
| 56 | + pub client_secret_file: PathBuf, | ||
| 54 | } | 57 | } |
| 55 | 58 | ||
| 56 | /// Switch for storing attachments in the external Files service. | 59 | /// Switch for storing attachments in the external Files service. |
| @@ -173,6 +176,11 @@ impl Config { | |||
| 173 | "oidc.client_id must be 1 to 200 characters".into(), | 176 | "oidc.client_id must be 1 to 200 characters".into(), |
| 174 | )); | 177 | )); |
| 175 | } | 178 | } |
| 179 | + if oidc.client_secret_file.as_os_str().is_empty() { | ||
| 180 | + return Err(Error::Config( | ||
| 181 | + "oidc.client_secret_file must not be empty".into(), | ||
| 182 | + )); | ||
| 183 | + } | ||
| 176 | } | 184 | } |
| 177 | if let Some(backup) = &self.backup { | 185 | if let Some(backup) = &self.backup { |
| 178 | if backup.dir.as_os_str().is_empty() { | 186 | if backup.dir.as_os_str().is_empty() { |
| @@ -201,6 +209,10 @@ impl Config { | |||
| 201 | /// An issuer must be https. Plain http is allowed only for loopback, which is how a local | 209 | /// An issuer must be https. Plain http is allowed only for loopback, which is how a local |
| 202 | /// identity provider is reached in development. | 210 | /// identity provider is reached in development. |
| 203 | fn validate_issuer(issuer: &str) -> Result<()> { | 211 | fn validate_issuer(issuer: &str) -> Result<()> { |
| 212 | + // The issuer is compared exactly with the `iss` claim, so a trailing slash would never match. | ||
| 213 | + if issuer.ends_with('/') { | ||
| 214 | + return Err(Error::Config("oidc.issuer must not end with /".into())); | ||
| 215 | + } | ||
| 204 | let loopback = issuer.starts_with("http://127.0.0.1") || issuer.starts_with("http://localhost"); | 216 | let loopback = issuer.starts_with("http://127.0.0.1") || issuer.starts_with("http://localhost"); |
| 205 | if issuer.starts_with("https://") || loopback { | 217 | if issuer.starts_with("https://") || loopback { |
| 206 | Ok(()) | 218 | Ok(()) |
| @@ -242,7 +254,11 @@ mod tests { | |||
| 242 | assert!(Config::parse("base_url = \"ftp://x\"\n").is_err()); | 254 | assert!(Config::parse("base_url = \"ftp://x\"\n").is_err()); |
| 243 | assert!(Config::parse("base_url = \"https://x/\"\n").is_err()); | 255 | assert!(Config::parse("base_url = \"https://x/\"\n").is_err()); |
| 244 | assert!( | 256 | assert!( |
| 245 | - Config::parse("[oidc]\nissuer = \"http://im.example.com\"\nclient_id = \"iz\"\n") | 257 | + Config::parse("[oidc]\nissuer = \"http://im.example.com\"\nclient_id = \"iz\"\nclient_secret_file = \"s\"\n") |
| 258 | + .is_err() | ||
| 259 | + ); | ||
| 260 | + assert!( | ||
| 261 | + Config::parse("[oidc]\nissuer = \"https://im.example.com/\"\nclient_id = \"iz\"\nclient_secret_file = \"s\"\n") | ||
| 246 | .is_err() | 262 | .is_err() |
| 247 | ); | 263 | ); |
| 248 | assert!(Config::parse("[backup]\ndir = \"/srv/b\"\ninterval_hours = 0\n").is_err()); | 264 | assert!(Config::parse("[backup]\ndir = \"/srv/b\"\ninterval_hours = 0\n").is_err()); |
crates/iz-core/src/store/migrate.rsmodified+4 -1
| @@ -8,7 +8,10 @@ use crate::error::{Error, Result}; | |||
| 8 | use crate::time::now_stamp; | 8 | use crate::time::now_stamp; |
| 9 | 9 | ||
| 10 | /// `(version, sql)` in ascending order. | 10 | /// `(version, sql)` in ascending order. |
| 11 | -pub const MIGRATIONS: &[(u32, &str)] = &[(1, include_str!("../../migrations/0001_init.sql"))]; | 11 | +pub const MIGRATIONS: &[(u32, &str)] = &[ |
| 12 | + (1, include_str!("../../migrations/0001_init.sql")), | ||
| 13 | + (2, include_str!("../../migrations/0002_session_id_token.sql")), | ||
| 14 | +]; | ||
| 12 | 15 | ||
| 13 | fn migration_err(e: turso::Error) -> Error { | 16 | fn migration_err(e: turso::Error) -> Error { |
| 14 | Error::Migration(e.to_string()) | 17 | Error::Migration(e.to_string()) |
crates/iz-core/src/store/mod.rsmodified+1 -1
| @@ -379,7 +379,7 @@ mod tests { | |||
| 379 | }) | 379 | }) |
| 380 | .await | 380 | .await |
| 381 | .unwrap(); | 381 | .unwrap(); |
| 382 | - assert_eq!(versions, vec![1]); | 382 | + assert_eq!(versions, vec![1, 2]); |
| 383 | } | 383 | } |
| 384 | 384 | ||
| 385 | #[tokio::test] | 385 | #[tokio::test] |
crates/iz-core/src/store/sessions.rsmodified+22 -7
| @@ -24,6 +24,8 @@ pub struct SessionRecord { | |||
| 24 | pub csrf_token: String, | 24 | pub csrf_token: String, |
| 25 | /// The im browser session id, used by back-channel logout. | 25 | /// The im browser session id, used by back-channel logout. |
| 26 | pub sid: Option<String>, | 26 | pub sid: Option<String>, |
| 27 | + /// The sealed ID token that was issued with this session, for the logout `id_token_hint`. | ||
| 28 | + pub id_token_sealed: Option<String>, | ||
| 27 | /// UTC stamp after which the session is refused. | 29 | /// UTC stamp after which the session is refused. |
| 28 | pub expires_at: String, | 30 | pub expires_at: String, |
| 29 | /// UTC stamp of the last request that used the session. | 31 | /// UTC stamp of the last request that used the session. |
| @@ -41,7 +43,8 @@ pub struct IssuedSession { | |||
| 41 | pub csrf_token: String, | 43 | pub csrf_token: String, |
| 42 | } | 44 | } |
| 43 | 45 | ||
| 44 | -const SESSION_COLS: &str = "s.id, s.sub, s.csrf_token, s.sid, s.expires_at, s.last_seen"; | 46 | +const SESSION_COLS: &str = |
| 47 | + "s.id, s.sub, s.csrf_token, s.sid, s.expires_at, s.last_seen, s.id_token_sealed"; | ||
| 45 | 48 | ||
| 46 | fn map_session(row: &turso::Row) -> Result<SessionRecord> { | 49 | fn map_session(row: &turso::Row) -> Result<SessionRecord> { |
| 47 | Ok(SessionRecord { | 50 | Ok(SessionRecord { |
| @@ -51,16 +54,19 @@ fn map_session(row: &turso::Row) -> Result<SessionRecord> { | |||
| 51 | sid: col_opt_text(row, 3)?, | 54 | sid: col_opt_text(row, 3)?, |
| 52 | expires_at: col_text(row, 4)?, | 55 | expires_at: col_text(row, 4)?, |
| 53 | last_seen: col_text(row, 5)?, | 56 | last_seen: col_text(row, 5)?, |
| 57 | + id_token_sealed: col_opt_text(row, 6)?, | ||
| 54 | }) | 58 | }) |
| 55 | } | 59 | } |
| 56 | 60 | ||
| 57 | impl Store { | 61 | impl Store { |
| 58 | - /// Creates a session for `sub` that lasts `lifetime`. The member must be enabled and have a role | 62 | + /// Creates a session for `sub` that lasts `lifetime`. `id_token_sealed` is the sealed ID token of |
| 59 | - /// other than `none`; otherwise nothing is written and the result is `Forbidden`. | 63 | + /// the sign-in, kept for the logout hint. The member must be enabled and have a role other than |
| 64 | + /// `none`; otherwise nothing is written and the result is `Forbidden`. | ||
| 60 | pub async fn create_session( | 65 | pub async fn create_session( |
| 61 | &self, | 66 | &self, |
| 62 | sub: &str, | 67 | sub: &str, |
| 63 | sid: Option<&str>, | 68 | sid: Option<&str>, |
| 69 | + id_token_sealed: Option<&str>, | ||
| 64 | lifetime: Duration, | 70 | lifetime: Duration, |
| 65 | user_agent: Option<&str>, | 71 | user_agent: Option<&str>, |
| 66 | ip: Option<&str>, | 72 | ip: Option<&str>, |
| @@ -73,8 +79,8 @@ impl Store { | |||
| 73 | let changed = conn | 79 | let changed = conn |
| 74 | .execute( | 80 | .execute( |
| 75 | "INSERT INTO sessions (id, sub, token_hash, csrf_token, sid, created_at, expires_at, \ | 81 | "INSERT INTO sessions (id, sub, token_hash, csrf_token, sid, created_at, expires_at, \ |
| 76 | - last_seen, user_agent, ip) \ | 82 | + last_seen, user_agent, ip, id_token_sealed) \ |
| 77 | - SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?6, ?8, ?9 FROM members \ | 83 | + SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?6, ?8, ?9, ?10 FROM members \ |
| 78 | WHERE sub = ?2 AND disabled = 0 AND role <> 'none'", | 84 | WHERE sub = ?2 AND disabled = 0 AND role <> 'none'", |
| 79 | ( | 85 | ( |
| 80 | id.clone(), | 86 | id.clone(), |
| @@ -86,6 +92,7 @@ impl Store { | |||
| 86 | stamp_after(lifetime), | 92 | stamp_after(lifetime), |
| 87 | user_agent.map(str::to_owned), | 93 | user_agent.map(str::to_owned), |
| 88 | ip.map(str::to_owned), | 94 | ip.map(str::to_owned), |
| 95 | + id_token_sealed.map(str::to_owned), | ||
| 89 | ), | 96 | ), |
| 90 | ) | 97 | ) |
| 91 | .await | 98 | .await |
| @@ -201,7 +208,14 @@ mod tests { | |||
| 201 | async fn sessions_follow_member_state_and_jti_is_single_use() { | 208 | async fn sessions_follow_member_state_and_jti_is_single_use() { |
| 202 | let (_dir, store, _board) = seeded().await; | 209 | let (_dir, store, _board) = seeded().await; |
| 203 | let issued = store | 210 | let issued = store |
| 204 | - .create_session("bo", Some("sid-1"), Duration::from_secs(3600), None, None) | 211 | + .create_session( |
| 212 | + "bo", | ||
| 213 | + Some("sid-1"), | ||
| 214 | + Some("sealed"), | ||
| 215 | + Duration::from_secs(3600), | ||
| 216 | + None, | ||
| 217 | + None, | ||
| 218 | + ) | ||
| 205 | .await | 219 | .await |
| 206 | .unwrap(); | 220 | .unwrap(); |
| 207 | let found = store | 221 | let found = store |
| @@ -211,6 +225,7 @@ mod tests { | |||
| 211 | .unwrap(); | 225 | .unwrap(); |
| 212 | assert_eq!(found.sub, "bo"); | 226 | assert_eq!(found.sub, "bo"); |
| 213 | assert_eq!(found.csrf_token, issued.csrf_token); | 227 | assert_eq!(found.csrf_token, issued.csrf_token); |
| 228 | + assert_eq!(found.id_token_sealed.as_deref(), Some("sealed")); | ||
| 214 | // Back-channel logout by sid removes the session. | 229 | // Back-channel logout by sid removes the session. |
| 215 | assert_eq!(store.delete_sessions_by_sid("sid-1").await.unwrap(), 1); | 230 | assert_eq!(store.delete_sessions_by_sid("sid-1").await.unwrap(), 1); |
| 216 | assert!( | 231 | assert!( |
| @@ -224,7 +239,7 @@ mod tests { | |||
| 224 | store.mark_deleted("bo").await.unwrap(); | 239 | store.mark_deleted("bo").await.unwrap(); |
| 225 | assert!(matches!( | 240 | assert!(matches!( |
| 226 | store | 241 | store |
| 227 | - .create_session("bo", None, Duration::from_secs(60), None, None) | 242 | + .create_session("bo", None, None, Duration::from_secs(60), None, None) |
| 228 | .await, | 243 | .await, |
| 229 | Err(Error::Forbidden(_)) | 244 | Err(Error::Forbidden(_)) |
| 230 | )); | 245 | )); |
crates/iz-web/Cargo.tomlmodified+15 -2
| @@ -11,16 +11,29 @@ name = "iz" | |||
| 11 | path = "src/main.rs" | 11 | path = "src/main.rs" |
| 12 | 12 | ||
| 13 | [dependencies] | 13 | [dependencies] |
| 14 | +base64.workspace = true | ||
| 14 | futures-util.workspace = true | 15 | futures-util.workspace = true |
| 16 | +hex.workspace = true | ||
| 15 | http.workspace = true | 17 | http.workspace = true |
| 16 | iz-core.workspace = true | 18 | iz-core.workspace = true |
| 17 | -# `net` and `signal` for the listener and the shutdown signals, `time` for the database probe timeout. | 19 | +jsonwebtoken.workspace = true |
| 18 | -tokio = { workspace = true, features = ["net", "signal", "time"] } | 20 | +rand.workspace = true |
| 21 | +reqwest.workspace = true | ||
| 22 | +serde = { workspace = true, features = ["derive"] } | ||
| 23 | +serde_json.workspace = true | ||
| 24 | +sha2.workspace = true | ||
| 25 | +subtle.workspace = true | ||
| 26 | +# `net` and `signal` for the listener and the shutdown signals, `time` for the database probe timeout | ||
| 27 | +# and the reconnect backoff, `fs` for the photo cache. | ||
| 28 | +tokio = { workspace = true, features = ["fs", "net", "signal", "time"] } | ||
| 19 | topcoat.workspace = true | 29 | topcoat.workspace = true |
| 20 | tracing.workspace = true | 30 | tracing.workspace = true |
| 31 | +thiserror.workspace = true | ||
| 21 | tracing-subscriber = { workspace = true, features = ["env-filter"] } | 32 | tracing-subscriber = { workspace = true, features = ["env-filter"] } |
| 22 | 33 | ||
| 23 | [dev-dependencies] | 34 | [dev-dependencies] |
| 35 | +# Makes Ed25519 keys for the token tests. Never used by the server. | ||
| 36 | +aws-lc-rs.workspace = true | ||
| 24 | tempfile.workspace = true | 37 | tempfile.workspace = true |
| 25 | 38 | ||
| 26 | [build-dependencies] | 39 | [build-dependencies] |
crates/iz-web/src/auth.rsadded+322 -0
| @@ -0,0 +1,322 @@ | |||
| 1 | +//! Sessions and access checks for the web layer: the cookies, the current member, the role and CSRF | ||
| 2 | +//! checks that every handler calls first, and the `next` guard for redirects. | ||
| 3 | +//! | ||
| 4 | +//! The browser holds the raw session token in `__Host-iz_session`. The store keeps only its SHA-256 | ||
| 5 | +//! (`iz_core::store::sessions`). The sign-in flight (state, nonce, PKCE verifier, `next`) lives in | ||
| 6 | +//! `__Host-iz_flight`, sealed with the instance key, so the browser cannot change it. | ||
| 7 | + | ||
| 8 | +use std::time::Duration; | ||
| 9 | + | ||
| 10 | +use iz_core::authz::{Action, Actor, Denied, authorize}; | ||
| 11 | +use iz_core::secret; | ||
| 12 | +use iz_core::store::members::Member; | ||
| 13 | +use iz_core::store::sessions::SessionRecord; | ||
| 14 | +use iz_core::token::constant_time_eq; | ||
| 15 | +use reqwest::Url; | ||
| 16 | +use serde::{Deserialize, Serialize}; | ||
| 17 | +use topcoat::Result; | ||
| 18 | +use topcoat::context::{Cx, app_context}; | ||
| 19 | +use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time}; | ||
| 20 | +use topcoat::router::error::{forbidden, not_found, see_other}; | ||
| 21 | +use topcoat::router::request::{headers, uri}; | ||
| 22 | + | ||
| 23 | +use crate::oidc::unix_now; | ||
| 24 | +use crate::state::AppState; | ||
| 25 | + | ||
| 26 | +/// Logical name of the session cookie. `override_prefix_host()` stores it as `__Host-iz_session`. | ||
| 27 | +pub const SESSION_COOKIE: &str = "iz_session"; | ||
| 28 | +/// Logical name of the sign-in flight cookie. Stored as `__Host-iz_flight`. | ||
| 29 | +pub const STATE_COOKIE: &str = "iz_flight"; | ||
| 30 | +/// Lifetime of a local session, in seconds of absolute age (contracts.md 2.4: at most 12 hours). | ||
| 31 | +pub const SESSION_LIFETIME: Duration = Duration::from_secs(12 * 60 * 60); | ||
| 32 | +/// How long a sign-in may take from the start to the callback (contracts.md 2.3 and this task). | ||
| 33 | +pub const STATE_LIFETIME: Duration = Duration::from_secs(10 * 60); | ||
| 34 | +/// Longest `next` target accepted, in bytes. Reason: a return path is a path, not a document. | ||
| 35 | +const MAX_NEXT_LEN: usize = 2048; | ||
| 36 | +/// Longest user agent stored with a session, in bytes. Reason: the value is only shown to admins. | ||
| 37 | +const MAX_USER_AGENT_LEN: usize = 256; | ||
| 38 | + | ||
| 39 | +/// The level a page or a write needs. Maps to one authorization action. | ||
| 40 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
| 41 | +pub enum Need { | ||
| 42 | + /// Reading the board. | ||
| 43 | + Viewer, | ||
| 44 | + /// Creating and changing tasks, comments and files. | ||
| 45 | + Member, | ||
| 46 | + /// Settings, roles, tags, columns and rules. | ||
| 47 | + Admin, | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +/// A signed-in member and the session that carries them. | ||
| 51 | +pub struct CurrentMember { | ||
| 52 | + /// The session row (its CSRF token, its sid and the sealed ID token). | ||
| 53 | + pub session: SessionRecord, | ||
| 54 | + /// The member row, read in the same request. | ||
| 55 | + pub member: Member, | ||
| 56 | +} | ||
| 57 | + | ||
| 58 | +impl CurrentMember { | ||
| 59 | + /// The actor for [`authorize`], built from the stored member. | ||
| 60 | + pub fn actor(&self) -> Actor { | ||
| 61 | + Actor::Member { | ||
| 62 | + sub: self.member.sub.clone(), | ||
| 63 | + role: self.member.role, | ||
| 64 | + im_admin: self.member.im_admin, | ||
| 65 | + disabled: self.member.disabled, | ||
| 66 | + } | ||
| 67 | + } | ||
| 68 | + | ||
| 69 | + /// Whether `submitted` is this session's CSRF token, compared in constant time. An empty value | ||
| 70 | + /// never matches. | ||
| 71 | + pub fn csrf_matches(&self, submitted: &str) -> bool { | ||
| 72 | + !submitted.is_empty() | ||
| 73 | + && !self.session.csrf_token.is_empty() | ||
| 74 | + && constant_time_eq(self.session.csrf_token.as_bytes(), submitted.as_bytes()) | ||
| 75 | + } | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +/// The state of one sign-in, sealed into the flight cookie. | ||
| 79 | +#[derive(Debug, Serialize, Deserialize)] | ||
| 80 | +pub struct SignInState { | ||
| 81 | + /// The `state` parameter sent to `im`. Compared with the one that comes back. | ||
| 82 | + pub state: String, | ||
| 83 | + /// The `nonce` sent to `im`. Must equal the nonce of the ID token. | ||
| 84 | + pub nonce: String, | ||
| 85 | + /// The PKCE verifier. Only its challenge went to `im`. | ||
| 86 | + pub verifier: String, | ||
| 87 | + /// The return path, already checked by [`safe_next`] when it was stored. | ||
| 88 | + pub next: String, | ||
| 89 | + /// Unix time after which the flight is refused. | ||
| 90 | + pub expires: u64, | ||
| 91 | +} | ||
| 92 | + | ||
| 93 | +/// The cookie jar with the `__Host-` prefix, so the browser enforces `Secure`, `Path=/` and no domain. | ||
| 94 | +fn jar(cx: &Cx) -> impl Cookies + '_ { | ||
| 95 | + cookies(cx).override_prefix_host() | ||
| 96 | +} | ||
| 97 | + | ||
| 98 | +/// The signed-in member, or `None` when there is no session, the session has expired, or its member | ||
| 99 | +/// is disabled or has no role. The store answers all of these the same way. | ||
| 100 | +pub async fn current_member(cx: &Cx) -> Result<Option<CurrentMember>> { | ||
| 101 | + let Some(cookie) = jar(cx).get(SESSION_COOKIE) else { | ||
| 102 | + return Ok(None); | ||
| 103 | + }; | ||
| 104 | + let store = &app_context::<AppState>(cx).store; | ||
| 105 | + let Some(session) = store.session_by_token(cookie.value()).await? else { | ||
| 106 | + return Ok(None); | ||
| 107 | + }; | ||
| 108 | + let Some(member) = store.member(&session.sub).await? else { | ||
| 109 | + return Ok(None); | ||
| 110 | + }; | ||
| 111 | + Ok(Some(CurrentMember { session, member })) | ||
| 112 | +} | ||
| 113 | + | ||
| 114 | +/// The signed-in member. Without a session, redirects to `/login?next=<this page>`. | ||
| 115 | +pub async fn require_member(cx: &Cx) -> Result<CurrentMember> { | ||
| 116 | + match current_member(cx).await? { | ||
| 117 | + Some(me) => Ok(me), | ||
| 118 | + None => { | ||
| 119 | + let path = uri(cx).path_and_query().map_or("/", |p| p.as_str()); | ||
| 120 | + let target = format!("/auth/login?next={}", percent_encode(path)); | ||
| 121 | + Err(see_other(target).into()) | ||
| 122 | + } | ||
| 123 | + } | ||
| 124 | +} | ||
| 125 | + | ||
| 126 | +/// The signed-in member with the level `need`. A shortfall is `404` for admin pages, which must not | ||
| 127 | +/// reveal that they exist, and `403` for a write that a viewer tried. | ||
| 128 | +pub async fn require_role(cx: &Cx, need: Need) -> Result<CurrentMember> { | ||
| 129 | + let me = require_member(cx).await?; | ||
| 130 | + let action = match need { | ||
| 131 | + Need::Viewer => Action::ReadBoard, | ||
| 132 | + Need::Member => Action::WriteTask, | ||
| 133 | + Need::Admin => Action::Administer, | ||
| 134 | + }; | ||
| 135 | + match authorize(&me.actor(), &action) { | ||
| 136 | + Ok(()) => Ok(me), | ||
| 137 | + Err(Denied::Forbidden) if need == Need::Member => Err(forbidden().into()), | ||
| 138 | + Err(_) => Err(not_found().into()), | ||
| 139 | + } | ||
| 140 | +} | ||
| 141 | + | ||
| 142 | +/// The signed-in member, after the CSRF check. A missing or wrong `csrf` is `403`, and the check runs | ||
| 143 | +/// before any side effect of the handler. | ||
| 144 | +pub async fn require_csrf(cx: &Cx, submitted: &str) -> Result<CurrentMember> { | ||
| 145 | + let me = require_member(cx).await?; | ||
| 146 | + if me.csrf_matches(submitted) { | ||
| 147 | + Ok(me) | ||
| 148 | + } else { | ||
| 149 | + Err(forbidden().into()) | ||
| 150 | + } | ||
| 151 | +} | ||
| 152 | + | ||
| 153 | +/// Stores a new session cookie. `token` is the value from [`store::sessions::IssuedSession`]. | ||
| 154 | +pub fn set_session_cookie(cx: &Cx, token: String) { | ||
| 155 | + jar(cx).add( | ||
| 156 | + Cookie::build((SESSION_COOKIE, token)) | ||
| 157 | + .path("/") | ||
| 158 | + .secure(true) | ||
| 159 | + .http_only(true) | ||
| 160 | + .same_site(SameSite::Lax) | ||
| 161 | + .max_age(time::Duration::seconds( | ||
| 162 | + i64::try_from(SESSION_LIFETIME.as_secs()).unwrap_or(i64::MAX), | ||
| 163 | + )) | ||
| 164 | + .build(), | ||
| 165 | + ); | ||
| 166 | +} | ||
| 167 | + | ||
| 168 | +/// Removes the session cookie. | ||
| 169 | +pub fn clear_session_cookie(cx: &Cx) { | ||
| 170 | + jar(cx).remove(Cookie::build((SESSION_COOKIE, "")).path("/")); | ||
| 171 | +} | ||
| 172 | + | ||
| 173 | +/// Stores the sealed sign-in flight. `SameSite=Lax` is needed: the callback is a top-level | ||
| 174 | +/// navigation that comes back from `im`. | ||
| 175 | +pub fn set_state_cookie(cx: &Cx, sealed: String) { | ||
| 176 | + jar(cx).add( | ||
| 177 | + Cookie::build((STATE_COOKIE, sealed)) | ||
| 178 | + .path("/") | ||
| 179 | + .secure(true) | ||
| 180 | + .http_only(true) | ||
| 181 | + .same_site(SameSite::Lax) | ||
| 182 | + .max_age(time::Duration::seconds( | ||
| 183 | + i64::try_from(STATE_LIFETIME.as_secs()).unwrap_or(i64::MAX), | ||
| 184 | + )) | ||
| 185 | + .build(), | ||
| 186 | + ); | ||
| 187 | +} | ||
| 188 | + | ||
| 189 | +/// The sealed sign-in flight cookie, if the browser sent one. | ||
| 190 | +pub fn state_cookie(cx: &Cx) -> Option<String> { | ||
| 191 | + jar(cx).get(STATE_COOKIE).map(|c| c.value().to_owned()) | ||
| 192 | +} | ||
| 193 | + | ||
| 194 | +/// Removes the sign-in flight cookie. Called on every callback, whatever the outcome, so a flight | ||
| 195 | +/// can be used only once. | ||
| 196 | +pub fn clear_state_cookie(cx: &Cx) { | ||
| 197 | + jar(cx).remove(Cookie::build((STATE_COOKIE, "")).path("/")); | ||
| 198 | +} | ||
| 199 | + | ||
| 200 | +/// Seals a sign-in flight for the cookie. | ||
| 201 | +pub fn seal_sign_in_state(key: &[u8; 32], state: &SignInState) -> iz_core::Result<String> { | ||
| 202 | + let json = serde_json::to_vec(state) | ||
| 203 | + .map_err(|e| iz_core::Error::Crypto(format!("encoding the sign-in state: {e}")))?; | ||
| 204 | + secret::seal(key, &json) | ||
| 205 | +} | ||
| 206 | + | ||
| 207 | +/// Opens a sealed sign-in flight. `None` when it is malformed, tampered with, or past its expiry. | ||
| 208 | +pub fn open_sign_in_state(key: &[u8; 32], sealed: &str) -> Option<SignInState> { | ||
| 209 | + let plain = secret::open(key, sealed).ok()?; | ||
| 210 | + let state: SignInState = serde_json::from_slice(&plain).ok()?; | ||
| 211 | + (unix_now() < state.expires).then_some(state) | ||
| 212 | +} | ||
| 213 | + | ||
| 214 | +/// The User-Agent of the request, shortened, for the session row. | ||
| 215 | +pub fn user_agent(cx: &Cx) -> Option<String> { | ||
| 216 | + headers(cx) | ||
| 217 | + .get(http::header::USER_AGENT) | ||
| 218 | + .and_then(|value| value.to_str().ok()) | ||
| 219 | + .map(|value| value.chars().take(MAX_USER_AGENT_LEN).collect()) | ||
| 220 | +} | ||
| 221 | + | ||
| 222 | +/// One query parameter of the request, decoded. `None` when it is absent. | ||
| 223 | +pub fn query_param(cx: &Cx, name: &str) -> Option<String> { | ||
| 224 | + let mut url = Url::parse("http://iz.invalid/").ok()?; | ||
| 225 | + url.set_query(uri(cx).query()); | ||
| 226 | + url.query_pairs() | ||
| 227 | + .find(|(key, _)| key == name) | ||
| 228 | + .map(|(_, value)| value.into_owned()) | ||
| 229 | +} | ||
| 230 | + | ||
| 231 | +/// The return path, if it is safe to redirect to; otherwise `/`. A safe path starts with one `/`, | ||
| 232 | +/// is ASCII without control characters, and is at most 2048 bytes. Anything that could name another | ||
| 233 | +/// host (`//`, `/\`, a scheme) is refused. | ||
| 234 | +pub fn safe_next(next: Option<&str>) -> &str { | ||
| 235 | + match next { | ||
| 236 | + Some(path) if is_local_path(path) => path, | ||
| 237 | + _ => "/", | ||
| 238 | + } | ||
| 239 | +} | ||
| 240 | + | ||
| 241 | +fn is_local_path(path: &str) -> bool { | ||
| 242 | + path.len() <= MAX_NEXT_LEN | ||
| 243 | + && path.starts_with('/') | ||
| 244 | + && !path.starts_with("//") | ||
| 245 | + && !path.starts_with("/\\") | ||
| 246 | + && path.bytes().all(|b| b.is_ascii() && !b.is_ascii_control()) | ||
| 247 | +} | ||
| 248 | + | ||
| 249 | +/// Percent-encodes everything except unreserved characters and `/`, for a `next` value in a URL. | ||
| 250 | +fn percent_encode(input: &str) -> String { | ||
| 251 | + let mut out = String::with_capacity(input.len()); | ||
| 252 | + for b in input.bytes() { | ||
| 253 | + match b { | ||
| 254 | + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => { | ||
| 255 | + out.push(char::from(b)); | ||
| 256 | + } | ||
| 257 | + _ => out.push_str(&format!("%{b:02X}")), | ||
| 258 | + } | ||
| 259 | + } | ||
| 260 | + out | ||
| 261 | +} | ||
| 262 | + | ||
| 263 | +#[cfg(test)] | ||
| 264 | +mod tests { | ||
| 265 | + use super::*; | ||
| 266 | + | ||
| 267 | + #[test] | ||
| 268 | + fn safe_next_accepts_local_paths() { | ||
| 269 | + assert_eq!(safe_next(Some("/")), "/"); | ||
| 270 | + assert_eq!(safe_next(Some("/tasks/IZ-4?file=2")), "/tasks/IZ-4?file=2"); | ||
| 271 | + } | ||
| 272 | + | ||
| 273 | + /// Every string here is a classic open-redirect or header-injection attempt. None may come back. | ||
| 274 | + #[test] | ||
| 275 | + fn safe_next_refuses_the_attack_strings() { | ||
| 276 | + let attacks = [ | ||
| 277 | + "//evil.example", | ||
| 278 | + "/\\evil.example", | ||
| 279 | + "\\\\evil.example", | ||
| 280 | + "https://evil.example", | ||
| 281 | + "HTTPS://evil.example", | ||
| 282 | + "%2f%2fevil.example", | ||
| 283 | + "%5c%5cevil.example", | ||
| 284 | + "javascript:alert(1)", | ||
| 285 | + "/\r\nSet-Cookie: x=y", | ||
| 286 | + "/ok\nLocation: https://evil.example", | ||
| 287 | + "/\t/evil.example", | ||
| 288 | + " //evil.example", | ||
| 289 | + "evil.example", | ||
| 290 | + "", | ||
| 291 | + ]; | ||
| 292 | + for attack in attacks { | ||
| 293 | + assert_eq!(safe_next(Some(attack)), "/", "accepted {attack:?}"); | ||
| 294 | + } | ||
| 295 | + assert_eq!(safe_next(None), "/"); | ||
| 296 | + let too_long = format!("/{}", "a".repeat(MAX_NEXT_LEN)); | ||
| 297 | + assert_eq!(safe_next(Some(&too_long)), "/"); | ||
| 298 | + } | ||
| 299 | + | ||
| 300 | + #[test] | ||
| 301 | + fn sign_in_state_round_trips_and_expires() { | ||
| 302 | + let key = [9u8; 32]; | ||
| 303 | + let state = SignInState { | ||
| 304 | + state: "s".into(), | ||
| 305 | + nonce: "n".into(), | ||
| 306 | + verifier: "v".into(), | ||
| 307 | + next: "/".into(), | ||
| 308 | + expires: unix_now() + 600, | ||
| 309 | + }; | ||
| 310 | + let sealed = seal_sign_in_state(&key, &state).unwrap(); | ||
| 311 | + let opened = open_sign_in_state(&key, &sealed).unwrap(); | ||
| 312 | + assert_eq!(opened.nonce, "n"); | ||
| 313 | + assert!(open_sign_in_state(&[8u8; 32], &sealed).is_none()); | ||
| 314 | + | ||
| 315 | + let stale = SignInState { | ||
| 316 | + expires: unix_now() - 1, | ||
| 317 | + ..state | ||
| 318 | + }; | ||
| 319 | + let sealed = seal_sign_in_state(&key, &stale).unwrap(); | ||
| 320 | + assert!(open_sign_in_state(&key, &sealed).is_none()); | ||
| 321 | + } | ||
| 322 | +} | ||
crates/iz-web/src/boot.rsmodified+17 -1
| @@ -18,7 +18,9 @@ use tokio::sync::watch; | |||
| 18 | use topcoat::cookie::RouterBuilderCookieExt; | 18 | use topcoat::cookie::RouterBuilderCookieExt; |
| 19 | use topcoat::router::{Router, RouterBuilderDiscoverExt, RouterService}; | 19 | use topcoat::router::{Router, RouterBuilderDiscoverExt, RouterService}; |
| 20 | 20 | ||
| 21 | +use crate::directory; | ||
| 21 | use crate::live::LiveHub; | 22 | use crate::live::LiveHub; |
| 23 | +use crate::oidc; | ||
| 22 | use crate::pages::not_found::NotFoundLayer; | 24 | use crate::pages::not_found::NotFoundLayer; |
| 23 | use crate::security::{self, SecurityHeaders}; | 25 | use crate::security::{self, SecurityHeaders}; |
| 24 | use crate::state::AppState; | 26 | use crate::state::AppState; |
| @@ -42,8 +44,9 @@ pub async fn serve(config_path: &Path) -> iz_core::Result<()> { | |||
| 42 | "iz starting" | 44 | "iz starting" |
| 43 | ); | 45 | ); |
| 44 | 46 | ||
| 45 | - // One stop flag. The signal task sets it; the server watches it and then drains. | 47 | + // One stop flag. The signal task sets it; the mirror worker and the server both watch it. |
| 46 | let (stop_tx, stop_rx) = watch::channel(false); | 48 | let (stop_tx, stop_rx) = watch::channel(false); |
| 49 | + directory::spawn(state.clone(), stop_rx.clone()); | ||
| 47 | tokio::spawn(async move { | 50 | tokio::spawn(async move { |
| 48 | shutdown_signal().await; | 51 | shutdown_signal().await; |
| 49 | tracing::info!("shutdown signal received"); | 52 | tracing::info!("shutdown signal received"); |
| @@ -76,11 +79,23 @@ async fn open_state(config: Config) -> iz_core::Result<AppState> { | |||
| 76 | } | 79 | } |
| 77 | let key = secret::load_or_create_key(&data_dir.join(KEY_FILE))?; | 80 | let key = secret::load_or_create_key(&data_dir.join(KEY_FILE))?; |
| 78 | let store = Store::open(&config.database).await?; | 81 | let store = Store::open(&config.database).await?; |
| 82 | + let oidc = match &config.oidc { | ||
| 83 | + Some(oidc_config) => { | ||
| 84 | + let secret = oidc::read_client_secret(&oidc_config.client_secret_file)?; | ||
| 85 | + Some(Arc::new(oidc::OidcClient::new( | ||
| 86 | + oidc_config, | ||
| 87 | + &config.base_url, | ||
| 88 | + secret, | ||
| 89 | + )?)) | ||
| 90 | + } | ||
| 91 | + None => None, | ||
| 92 | + }; | ||
| 79 | Ok(AppState { | 93 | Ok(AppState { |
| 80 | config: Arc::new(config), | 94 | config: Arc::new(config), |
| 81 | store, | 95 | store, |
| 82 | key: Arc::new(key), | 96 | key: Arc::new(key), |
| 83 | live: Arc::new(LiveHub::default()), | 97 | live: Arc::new(LiveHub::default()), |
| 98 | + oidc, | ||
| 84 | }) | 99 | }) |
| 85 | } | 100 | } |
| 86 | 101 | ||
| @@ -155,6 +170,7 @@ mod tests { | |||
| 155 | store, | 170 | store, |
| 156 | key: Arc::new(key), | 171 | key: Arc::new(key), |
| 157 | live: Arc::new(LiveHub::default()), | 172 | live: Arc::new(LiveHub::default()), |
| 173 | + oidc: None, | ||
| 158 | }; | 174 | }; |
| 159 | (dir, state) | 175 | (dir, state) |
| 160 | } | 176 | } |
crates/iz-web/src/directory.rsadded+473 -0
| @@ -0,0 +1,473 @@ | |||
| 1 | +//! The members mirror (docs/contracts.md section 3): a full read of `im`'s people directory at boot, | ||
| 2 | +//! then its change stream, applied to the local `members` table. The worker keeps running until the | ||
| 3 | +//! stop flag is set. | ||
| 4 | +//! | ||
| 5 | +//! Pages never call `im` to show a name or an avatar; they read this mirror. A member who is disabled | ||
| 6 | +//! or deleted loses their local sessions here, and the same check also runs at every request in the | ||
| 7 | +//! store, so either path alone is enough (contracts.md 2.5). | ||
| 8 | +//! | ||
| 9 | +//! The stream cursor is kept in `settings`. A `resync` event, or a cursor that `im` no longer knows, | ||
| 10 | +//! starts a full read again. A broken connection is retried with exponential backoff from one second | ||
| 11 | +//! to one minute, with jitter, so a restart of `im` does not bring every client back in the same | ||
| 12 | +//! instant. | ||
| 13 | + | ||
| 14 | +use std::collections::HashSet; | ||
| 15 | +use std::time::Duration; | ||
| 16 | + | ||
| 17 | +use futures_util::StreamExt; | ||
| 18 | +use iz_core::authz::Role; | ||
| 19 | +use iz_core::store::members::DirectoryMember; | ||
| 20 | +use iz_core::store::Store; | ||
| 21 | +use serde_json::Value; | ||
| 22 | +use tokio::sync::watch; | ||
| 23 | + | ||
| 24 | +use crate::oidc::{ImError, ImResult, OidcClient, read_limited}; | ||
| 25 | +use crate::state::AppState; | ||
| 26 | + | ||
| 27 | +/// The setting that holds the stream cursor. | ||
| 28 | +pub const CURSOR_SETTING: &str = "directory_cursor"; | ||
| 29 | +/// The setting that holds the role of a member the directory adds (`member` by default). | ||
| 30 | +pub const DEFAULT_ROLE_SETTING: &str = "default_role"; | ||
| 31 | +/// The shortest wait before a reconnect. Reason: contracts.md 2.2 style backoff, first step. | ||
| 32 | +const BACKOFF_MIN: Duration = Duration::from_secs(1); | ||
| 33 | +/// The longest wait before a reconnect. Reason: a family board can wait a minute for `im`. | ||
| 34 | +const BACKOFF_MAX: Duration = Duration::from_secs(60); | ||
| 35 | +/// Silence after which the stream is considered dead. `im` sends a keep-alive every 30 seconds. | ||
| 36 | +const IDLE_LIMIT: Duration = Duration::from_secs(90); | ||
| 37 | +/// Largest directory listing read at once, in bytes. Reason: a family has a few dozen members, so | ||
| 38 | +/// this is far above a real listing and still bounds memory. | ||
| 39 | +const ROSTER_MAX_BYTES: usize = 8 * 1024 * 1024; | ||
| 40 | +/// Largest stream event accepted, in bytes. Reason: a member record is a few hundred bytes. | ||
| 41 | +const MAX_EVENT_BYTES: usize = 64 * 1024; | ||
| 42 | +/// Largest photo fetched from `im`, in bytes. Reason: avatars are small; this bounds the cache. | ||
| 43 | +pub const PHOTO_MAX_BYTES: usize = 5 * 1024 * 1024; | ||
| 44 | +/// The image types a photo may be served as. Anything else from `im` is not shown. | ||
| 45 | +pub const PHOTO_TYPES: [&str; 4] = ["image/png", "image/jpeg", "image/gif", "image/webp"]; | ||
| 46 | + | ||
| 47 | +/// What can stop the mirror: the directory or the local store. | ||
| 48 | +#[derive(Debug, thiserror::Error)] | ||
| 49 | +pub enum MirrorError { | ||
| 50 | + /// `im` failed to answer. The worker retries. | ||
| 51 | + #[error(transparent)] | ||
| 52 | + Im(#[from] ImError), | ||
| 53 | + /// The local database failed. The worker retries. | ||
| 54 | + #[error(transparent)] | ||
| 55 | + Store(#[from] iz_core::Error), | ||
| 56 | +} | ||
| 57 | + | ||
| 58 | +/// A member record as `im` sends it (contracts.md 3.1). Unknown fields are ignored. | ||
| 59 | +#[derive(serde::Deserialize)] | ||
| 60 | +struct WireMember { | ||
| 61 | + sub: String, | ||
| 62 | + email: String, | ||
| 63 | + name: String, | ||
| 64 | + #[serde(default)] | ||
| 65 | + admin: bool, | ||
| 66 | + #[serde(default)] | ||
| 67 | + disabled: bool, | ||
| 68 | + #[serde(default)] | ||
| 69 | + locale: Option<String>, | ||
| 70 | + #[serde(default = "utc")] | ||
| 71 | + zoneinfo: String, | ||
| 72 | + #[serde(default)] | ||
| 73 | + picture_version: i64, | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +fn utc() -> String { | ||
| 77 | + "UTC".to_owned() | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +/// The listing of `im`'s directory (contracts.md 3.2). Members are kept as raw values so that one | ||
| 81 | +/// bad record does not stop the rest. | ||
| 82 | +#[derive(serde::Deserialize)] | ||
| 83 | +struct Roster { | ||
| 84 | + members: Vec<Value>, | ||
| 85 | + cursor: String, | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +/// How one connection of the stream ended. | ||
| 89 | +enum Ended { | ||
| 90 | + /// The stop flag was set. | ||
| 91 | + Stopped, | ||
| 92 | + /// `im` asked for a full read again. | ||
| 93 | + Resync, | ||
| 94 | + /// The stream closed, went idle, or `im` closed it after 50 minutes. Reconnect with the cursor. | ||
| 95 | + Closed, | ||
| 96 | +} | ||
| 97 | + | ||
| 98 | +/// Starts the mirror. Does nothing when OIDC is not configured. | ||
| 99 | +pub fn spawn(state: AppState, stop: watch::Receiver<bool>) { | ||
| 100 | + let Some(oidc) = state.oidc.clone() else { | ||
| 101 | + return; | ||
| 102 | + }; | ||
| 103 | + tokio::spawn(run(state, oidc, stop)); | ||
| 104 | +} | ||
| 105 | + | ||
| 106 | +async fn run(state: AppState, oidc: std::sync::Arc<OidcClient>, mut stop: watch::Receiver<bool>) { | ||
| 107 | + let mut backoff = BACKOFF_MIN; | ||
| 108 | + loop { | ||
| 109 | + match mirror_once(&state, &oidc, &mut stop).await { | ||
| 110 | + Ok(Ended::Stopped) => return, | ||
| 111 | + Ok(Ended::Resync) => { | ||
| 112 | + tracing::info!("directory: the stream asked for a full read"); | ||
| 113 | + backoff = BACKOFF_MIN; | ||
| 114 | + } | ||
| 115 | + Ok(Ended::Closed) => { | ||
| 116 | + tracing::info!("directory: the stream closed; reconnecting"); | ||
| 117 | + backoff = BACKOFF_MIN; | ||
| 118 | + } | ||
| 119 | + Err(error) => { | ||
| 120 | + tracing::warn!(error = %error, retry_in = ?backoff, "directory: the mirror failed"); | ||
| 121 | + } | ||
| 122 | + } | ||
| 123 | + if wait_or_stop(jittered(backoff), &mut stop).await { | ||
| 124 | + return; | ||
| 125 | + } | ||
| 126 | + backoff = (backoff * 2).min(BACKOFF_MAX); | ||
| 127 | + } | ||
| 128 | +} | ||
| 129 | + | ||
| 130 | +/// One full read and then one stream connection. | ||
| 131 | +async fn mirror_once( | ||
| 132 | + state: &AppState, | ||
| 133 | + oidc: &OidcClient, | ||
| 134 | + stop: &mut watch::Receiver<bool>, | ||
| 135 | +) -> std::result::Result<Ended, MirrorError> { | ||
| 136 | + full_read(state, oidc).await?; | ||
| 137 | + stream(state, oidc, stop).await | ||
| 138 | +} | ||
| 139 | + | ||
| 140 | +/// Reads the whole directory and applies it. Members that the listing no longer has were deleted in | ||
| 141 | +/// `im`, so they are marked deleted here too. | ||
| 142 | +async fn full_read(state: &AppState, oidc: &OidcClient) -> std::result::Result<(), MirrorError> { | ||
| 143 | + let token = oidc.service_token().await?; | ||
| 144 | + let url = format!("{}/api/v1/directory", oidc.issuer()); | ||
| 145 | + let response = oidc.http().get(url).bearer_auth(token).send().await.map_err(|e| { | ||
| 146 | + ImError::Unavailable(e.to_string()) | ||
| 147 | + })?; | ||
| 148 | + if !response.status().is_success() { | ||
| 149 | + return Err(ImError::BadResponse(format!( | ||
| 150 | + "the directory answered {}", | ||
| 151 | + response.status().as_u16() | ||
| 152 | + )) | ||
| 153 | + .into()); | ||
| 154 | + } | ||
| 155 | + let roster: Roster = decode_json_limited(response, ROSTER_MAX_BYTES).await?; | ||
| 156 | + let default_role = default_role(&state.store).await?; | ||
| 157 | + let mut listed = HashSet::new(); | ||
| 158 | + for raw in roster.members { | ||
| 159 | + let Some(member) = parse_member(raw) else { | ||
| 160 | + tracing::warn!("directory: skipping a member record that does not parse"); | ||
| 161 | + continue; | ||
| 162 | + }; | ||
| 163 | + listed.insert(member.sub.clone()); | ||
| 164 | + apply(state, &member, default_role).await?; | ||
| 165 | + } | ||
| 166 | + for local in state.store.list_members().await? { | ||
| 167 | + if !listed.contains(&local.sub) && !local.disabled { | ||
| 168 | + tracing::info!(sub = %local.sub, "directory: member is gone from the listing; marking deleted"); | ||
| 169 | + state.store.mark_deleted(&local.sub).await?; | ||
| 170 | + state.store.delete_sessions_by_sub(&local.sub).await?; | ||
| 171 | + } | ||
| 172 | + } | ||
| 173 | + state.store.set_setting(CURSOR_SETTING, &roster.cursor).await?; | ||
| 174 | + Ok(()) | ||
| 175 | +} | ||
| 176 | + | ||
| 177 | +/// Decodes a listing, with the same size limit as the other reads. | ||
| 178 | +async fn decode_json_limited<T: serde::de::DeserializeOwned>( | ||
| 179 | + response: reqwest::Response, | ||
| 180 | + limit: usize, | ||
| 181 | +) -> ImResult<T> { | ||
| 182 | + let body = read_limited(response, limit).await?; | ||
| 183 | + serde_json::from_slice(&body) | ||
| 184 | + .map_err(|e| ImError::BadResponse(format!("the directory listing: {e}"))) | ||
| 185 | +} | ||
| 186 | + | ||
| 187 | +/// Opens the change stream from the stored cursor and applies events until the stream ends. | ||
| 188 | +async fn stream( | ||
| 189 | + state: &AppState, | ||
| 190 | + oidc: &OidcClient, | ||
| 191 | + stop: &mut watch::Receiver<bool>, | ||
| 192 | +) -> std::result::Result<Ended, MirrorError> { | ||
| 193 | + let token = oidc.service_token().await?; | ||
| 194 | + let url = format!("{}/api/v1/directory/stream", oidc.issuer()); | ||
| 195 | + let mut request = oidc | ||
| 196 | + .stream_http() | ||
| 197 | + .get(url) | ||
| 198 | + .bearer_auth(token) | ||
| 199 | + .header(reqwest::header::ACCEPT, "text/event-stream"); | ||
| 200 | + if let Some(cursor) = state.store.get_setting(CURSOR_SETTING).await? { | ||
| 201 | + request = request.header("Last-Event-ID", cursor); | ||
| 202 | + } | ||
| 203 | + let response = request | ||
| 204 | + .send() | ||
| 205 | + .await | ||
| 206 | + .map_err(|e| ImError::Unavailable(e.to_string()))?; | ||
| 207 | + if !response.status().is_success() { | ||
| 208 | + return Err(ImError::BadResponse(format!( | ||
| 209 | + "the stream answered {}", | ||
| 210 | + response.status().as_u16() | ||
| 211 | + )) | ||
| 212 | + .into()); | ||
| 213 | + } | ||
| 214 | + let mut chunks = response.bytes_stream(); | ||
| 215 | + let mut parser = SseParser::default(); | ||
| 216 | + loop { | ||
| 217 | + let next = tokio::select! { | ||
| 218 | + _ = stop.wait_for(|stopped| *stopped) => return Ok(Ended::Stopped), | ||
| 219 | + next = tokio::time::timeout(IDLE_LIMIT, chunks.next()) => next, | ||
| 220 | + }; | ||
| 221 | + let chunk = match next { | ||
| 222 | + // Silence for longer than the limit: reconnect. | ||
| 223 | + Err(_elapsed) => return Ok(Ended::Closed), | ||
| 224 | + Ok(None) => return Ok(Ended::Closed), | ||
| 225 | + Ok(Some(Err(error))) => return Err(ImError::Unavailable(error.to_string()).into()), | ||
| 226 | + Ok(Some(Ok(bytes))) => bytes, | ||
| 227 | + }; | ||
| 228 | + for event in parser.feed(&chunk).map_err(ImError::BadResponse)? { | ||
| 229 | + match event.name.as_str() { | ||
| 230 | + "member" => match serde_json::from_str::<Value>(&event.data).ok().and_then(parse_member) { | ||
| 231 | + Some(member) => { | ||
| 232 | + let default_role = default_role(&state.store).await?; | ||
| 233 | + apply(state, &member, default_role).await?; | ||
| 234 | + } | ||
| 235 | + None => tracing::warn!("directory: skipping a member event that does not parse"), | ||
| 236 | + }, | ||
| 237 | + "deleted" => match serde_json::from_str::<Value>(&event.data) | ||
| 238 | + .ok() | ||
| 239 | + .and_then(|v| v.get("sub").and_then(Value::as_str).map(str::to_owned)) | ||
| 240 | + { | ||
| 241 | + Some(sub) => { | ||
| 242 | + remove(state, &sub).await?; | ||
| 243 | + } | ||
| 244 | + None => tracing::warn!("directory: skipping a deleted event without a sub"), | ||
| 245 | + }, | ||
| 246 | + "resync" => return Ok(Ended::Resync), | ||
| 247 | + _ => {} | ||
| 248 | + } | ||
| 249 | + if let Some(id) = &event.id { | ||
| 250 | + state.store.set_setting(CURSOR_SETTING, id).await?; | ||
| 251 | + } | ||
| 252 | + } | ||
| 253 | + } | ||
| 254 | +} | ||
| 255 | + | ||
| 256 | +/// Applies one member record. A disabled member loses their sessions. A record the store refuses | ||
| 257 | +/// (for example a time zone it does not know) is logged and skipped, so one bad record never stops | ||
| 258 | +/// the mirror. | ||
| 259 | +async fn apply( | ||
| 260 | + state: &AppState, | ||
| 261 | + member: &DirectoryMember, | ||
| 262 | + default_role: Role, | ||
| 263 | +) -> std::result::Result<(), MirrorError> { | ||
| 264 | + match state.store.apply_directory_member(member, default_role).await { | ||
| 265 | + Ok(stored) => { | ||
| 266 | + if stored.disabled { | ||
| 267 | + state.store.delete_sessions_by_sub(&stored.sub).await?; | ||
| 268 | + } | ||
| 269 | + Ok(()) | ||
| 270 | + } | ||
| 271 | + Err(iz_core::Error::Invalid(reason)) => { | ||
| 272 | + tracing::warn!(sub = %member.sub, reason, "directory: skipping a member the store refuses"); | ||
| 273 | + Ok(()) | ||
| 274 | + } | ||
| 275 | + Err(error) => Err(error.into()), | ||
| 276 | + } | ||
| 277 | +} | ||
| 278 | + | ||
| 279 | +/// Marks a deleted member and ends their sessions. | ||
| 280 | +async fn remove(state: &AppState, sub: &str) -> std::result::Result<(), MirrorError> { | ||
| 281 | + match state.store.mark_deleted(sub).await { | ||
| 282 | + Ok(()) | Err(iz_core::Error::NotFound) => {} | ||
| 283 | + Err(error) => return Err(error.into()), | ||
| 284 | + } | ||
| 285 | + state.store.delete_sessions_by_sub(sub).await?; | ||
| 286 | + Ok(()) | ||
| 287 | +} | ||
| 288 | + | ||
| 289 | +/// The role for a member the directory adds: the `default_role` setting, else `member`. | ||
| 290 | +pub async fn default_role(store: &Store) -> iz_core::Result<Role> { | ||
| 291 | + Ok(store | ||
| 292 | + .get_setting(DEFAULT_ROLE_SETTING) | ||
| 293 | + .await? | ||
| 294 | + .as_deref() | ||
| 295 | + .and_then(Role::parse) | ||
| 296 | + .unwrap_or(Role::Member)) | ||
| 297 | +} | ||
| 298 | + | ||
| 299 | +/// Converts a raw member record into the store's form, or `None` when it does not parse. | ||
| 300 | +fn parse_member(raw: Value) -> Option<DirectoryMember> { | ||
| 301 | + let wire: WireMember = serde_json::from_value(raw).ok()?; | ||
| 302 | + Some(DirectoryMember { | ||
| 303 | + sub: wire.sub, | ||
| 304 | + email: wire.email, | ||
| 305 | + name: wire.name, | ||
| 306 | + im_admin: wire.admin, | ||
| 307 | + disabled: wire.disabled, | ||
| 308 | + locale: wire.locale, | ||
| 309 | + zoneinfo: wire.zoneinfo, | ||
| 310 | + picture_version: wire.picture_version, | ||
| 311 | + }) | ||
| 312 | +} | ||
| 313 | + | ||
| 314 | +/// Waits for `wait`, or returns `true` early when the stop flag is set. | ||
| 315 | +async fn wait_or_stop(wait: Duration, stop: &mut watch::Receiver<bool>) -> bool { | ||
| 316 | + tokio::select! { | ||
| 317 | + _ = stop.wait_for(|stopped| *stopped) => true, | ||
| 318 | + () = tokio::time::sleep(wait) => false, | ||
| 319 | + } | ||
| 320 | +} | ||
| 321 | + | ||
| 322 | +/// A wait between half and all of `backoff`. The jitter spreads the reconnects of several clients. | ||
| 323 | +fn jittered(backoff: Duration) -> Duration { | ||
| 324 | + let mut bytes = [0u8; 8]; | ||
| 325 | + rand::fill(&mut bytes); | ||
| 326 | + let fraction = (u64::from_le_bytes(bytes) % 1000) as f64 / 1000.0; | ||
| 327 | + backoff.mul_f64(0.5 + fraction * 0.5) | ||
| 328 | +} | ||
| 329 | + | ||
| 330 | +/// One event of a server-sent event stream. | ||
| 331 | +#[derive(Debug, PartialEq, Eq)] | ||
| 332 | +pub struct SseEvent { | ||
| 333 | + /// The `event:` name, `message` when none was sent. | ||
| 334 | + pub name: String, | ||
| 335 | + /// The `data:` lines joined with newlines. | ||
| 336 | + pub data: String, | ||
| 337 | + /// The `id:` of the event, which is the cursor to resume from. | ||
| 338 | + pub id: Option<String>, | ||
| 339 | +} | ||
| 340 | + | ||
| 341 | +/// Reads a server-sent event stream (the HTML living standard, event stream section) from raw | ||
| 342 | +/// chunks. A line may be split across chunks; a blank line ends an event. | ||
| 343 | +#[derive(Default)] | ||
| 344 | +pub struct SseParser { | ||
| 345 | + pending: Vec<u8>, | ||
| 346 | + name: Option<String>, | ||
| 347 | + data: Option<String>, | ||
| 348 | + id: Option<String>, | ||
| 349 | +} | ||
| 350 | + | ||
| 351 | +impl SseParser { | ||
| 352 | + /// Feeds one chunk and returns the events it completes. An over-long line is an error, so a | ||
| 353 | + /// hostile stream cannot grow the buffer without bound. | ||
| 354 | + pub fn feed(&mut self, chunk: &[u8]) -> std::result::Result<Vec<SseEvent>, String> { | ||
| 355 | + self.pending.extend_from_slice(chunk); | ||
| 356 | + let mut events = Vec::new(); | ||
| 357 | + while let Some(end) = self.pending.iter().position(|&b| b == b'\n') { | ||
| 358 | + let line: Vec<u8> = self.pending.drain(..=end).collect(); | ||
| 359 | + let line = String::from_utf8_lossy(&line[..line.len() - 1]).into_owned(); | ||
| 360 | + let line = line.strip_suffix('\r').unwrap_or(&line).to_owned(); | ||
| 361 | + if line.is_empty() { | ||
| 362 | + if let Some(event) = self.dispatch() { | ||
| 363 | + events.push(event); | ||
| 364 | + } | ||
| 365 | + continue; | ||
| 366 | + } | ||
| 367 | + if line.starts_with(':') { | ||
| 368 | + continue; | ||
| 369 | + } | ||
| 370 | + let (field, value) = match line.split_once(':') { | ||
| 371 | + Some((field, value)) => (field, value.strip_prefix(' ').unwrap_or(value)), | ||
| 372 | + None => (line.as_str(), ""), | ||
| 373 | + }; | ||
| 374 | + match field { | ||
| 375 | + "event" => self.name = Some(value.to_owned()), | ||
| 376 | + "id" if !value.contains('\0') => self.id = Some(value.to_owned()), | ||
| 377 | + "data" => { | ||
| 378 | + let data = self.data.get_or_insert_with(String::new); | ||
| 379 | + if !data.is_empty() { | ||
| 380 | + data.push('\n'); | ||
| 381 | + } | ||
| 382 | + data.push_str(value); | ||
| 383 | + if data.len() > MAX_EVENT_BYTES { | ||
| 384 | + return Err("a stream event is too large".into()); | ||
| 385 | + } | ||
| 386 | + } | ||
| 387 | + _ => {} | ||
| 388 | + } | ||
| 389 | + } | ||
| 390 | + if self.pending.len() > MAX_EVENT_BYTES { | ||
| 391 | + return Err("a stream line is too large".into()); | ||
| 392 | + } | ||
| 393 | + Ok(events) | ||
| 394 | + } | ||
| 395 | + | ||
| 396 | + /// Ends the current event. An event with no data is dropped, as the standard says. | ||
| 397 | + fn dispatch(&mut self) -> Option<SseEvent> { | ||
| 398 | + let name = self.name.take(); | ||
| 399 | + let id = self.id.clone(); | ||
| 400 | + let data = self.data.take()?; | ||
| 401 | + Some(SseEvent { | ||
| 402 | + name: name.unwrap_or_else(|| "message".to_owned()), | ||
| 403 | + data, | ||
| 404 | + id, | ||
| 405 | + }) | ||
| 406 | + } | ||
| 407 | +} | ||
| 408 | + | ||
| 409 | +/// Fetches a member's photo from `im` with the service token. `None` when `im` has no photo, or the | ||
| 410 | +/// photo has a type iz does not serve. | ||
| 411 | +pub async fn fetch_photo(oidc: &OidcClient, sub: &str) -> ImResult<Option<(String, Vec<u8>)>> { | ||
| 412 | + let token = oidc.service_token().await?; | ||
| 413 | + let url = format!("{}/api/v1/people/{sub}/photo", oidc.issuer()); | ||
| 414 | + let response = oidc | ||
| 415 | + .http() | ||
| 416 | + .get(url) | ||
| 417 | + .bearer_auth(token) | ||
| 418 | + .send() | ||
| 419 | + .await | ||
| 420 | + .map_err(|e| ImError::Unavailable(e.to_string()))?; | ||
| 421 | + match response.status() { | ||
| 422 | + status if status == reqwest::StatusCode::NOT_FOUND => return Ok(None), | ||
| 423 | + status if !status.is_success() => { | ||
| 424 | + return Err(ImError::BadResponse(format!( | ||
| 425 | + "the photo answered {}", | ||
| 426 | + status.as_u16() | ||
| 427 | + ))); | ||
| 428 | + } | ||
| 429 | + _ => {} | ||
| 430 | + } | ||
| 431 | + let mime = response | ||
| 432 | + .headers() | ||
| 433 | + .get(reqwest::header::CONTENT_TYPE) | ||
| 434 | + .and_then(|value| value.to_str().ok()) | ||
| 435 | + .map(|value| value.split(';').next().unwrap_or_default().trim().to_ascii_lowercase()) | ||
| 436 | + .unwrap_or_default(); | ||
| 437 | + if !PHOTO_TYPES.contains(&mime.as_str()) { | ||
| 438 | + return Ok(None); | ||
| 439 | + } | ||
| 440 | + let bytes = read_limited(response, PHOTO_MAX_BYTES).await?; | ||
| 441 | + Ok(Some((mime, bytes))) | ||
| 442 | +} | ||
| 443 | + | ||
| 444 | +#[cfg(test)] | ||
| 445 | +mod tests { | ||
| 446 | + use super::*; | ||
| 447 | + | ||
| 448 | + #[test] | ||
| 449 | + fn sse_events_split_across_chunks_and_resume_ids() { | ||
| 450 | + let mut parser = SseParser::default(); | ||
| 451 | + assert!(parser.feed(b": keep-alive\n\nevent: mem").unwrap().is_empty()); | ||
| 452 | + let events = parser | ||
| 453 | + .feed(b"ber\nid: 01CURSOR\ndata: {\"sub\":\"a\"}\ndata: more\r\n\r\n") | ||
| 454 | + .unwrap(); | ||
| 455 | + assert_eq!( | ||
| 456 | + events, | ||
| 457 | + vec![SseEvent { | ||
| 458 | + name: "member".into(), | ||
| 459 | + data: "{\"sub\":\"a\"}\nmore".into(), | ||
| 460 | + id: Some("01CURSOR".into()), | ||
| 461 | + }] | ||
| 462 | + ); | ||
| 463 | + // An event with no data is dropped. | ||
| 464 | + assert!(parser.feed(b"event: resync\n\n").unwrap().is_empty()); | ||
| 465 | + } | ||
| 466 | + | ||
| 467 | + #[test] | ||
| 468 | + fn sse_refuses_an_unbounded_line() { | ||
| 469 | + let mut parser = SseParser::default(); | ||
| 470 | + let long = vec![b'x'; MAX_EVENT_BYTES + 1]; | ||
| 471 | + assert!(parser.feed(&long).is_err()); | ||
| 472 | + } | ||
| 473 | +} | ||
crates/iz-web/src/i18n/shell.rsmodified+58 -4
| @@ -12,6 +12,24 @@ pub enum K { | |||
| 12 | BackHome, | 12 | BackHome, |
| 13 | /// The sentence under the 404 title. | 13 | /// The sentence under the 404 title. |
| 14 | NotFoundBody, | 14 | NotFoundBody, |
| 15 | + /// The sentence on the start page for a signed-in member, before the board exists. | ||
| 16 | + BoardComesNext, | ||
| 17 | + /// The title of the page that says a sign-in did not finish. | ||
| 18 | + SignInFailedTitle, | ||
| 19 | + /// The sentence under that title. | ||
| 20 | + SignInFailedBody, | ||
| 21 | + /// The button that starts a sign-in. | ||
| 22 | + SignIn, | ||
| 23 | + /// The title of the page for a member who has no access to the board. | ||
| 24 | + NoAccessTitle, | ||
| 25 | + /// The sentence under that title. | ||
| 26 | + NoAccessBody, | ||
| 27 | + /// The button in the user menu that ends the session. | ||
| 28 | + SignOut, | ||
| 29 | + /// The title of the page that says sign-in is not possible right now. | ||
| 30 | + SignInUnavailableTitle, | ||
| 31 | + /// The sentence under that title. | ||
| 32 | + SignInUnavailableBody, | ||
| 15 | /// The title of the 404 page. | 33 | /// The title of the 404 page. |
| 16 | NotFoundTitle, | 34 | NotFoundTitle, |
| 17 | /// The sentence on the signed-out start page. | 35 | /// The sentence on the signed-out start page. |
| @@ -32,15 +50,43 @@ pub fn t(lang: Lang, key: K) -> &'static str { | |||
| 32 | (K::Admin, Lang::En) => "Admin", | 50 | (K::Admin, Lang::En) => "Admin", |
| 33 | (K::Admin, Lang::Tr) => "Yönetici", | 51 | (K::Admin, Lang::Tr) => "Yönetici", |
| 34 | (K::BackHome, Lang::En) => "Back to the start", | 52 | (K::BackHome, Lang::En) => "Back to the start", |
| 53 | + (K::BoardComesNext, Lang::En) => "The board comes next. There is nothing to show yet.", | ||
| 54 | + (K::BoardComesNext, Lang::Tr) => "Pano sırada. Henüz gösterilecek bir şey yok.", | ||
| 55 | + (K::SignIn, Lang::En) => "Sign in", | ||
| 56 | + (K::SignIn, Lang::Tr) => "Oturum aç", | ||
| 57 | + (K::SignOut, Lang::En) => "Sign out", | ||
| 58 | + (K::SignOut, Lang::Tr) => "Çıkış yap", | ||
| 59 | + (K::SignInFailedTitle, Lang::En) => "Sign-in did not finish", | ||
| 60 | + (K::SignInFailedTitle, Lang::Tr) => "Oturum açma tamamlanamadı", | ||
| 61 | + (K::SignInFailedBody, Lang::En) => { | ||
| 62 | + "Start again from the sign-in button. If it keeps failing, ask an administrator." | ||
| 63 | + } | ||
| 64 | + (K::SignInFailedBody, Lang::Tr) => { | ||
| 65 | + "Oturum aç düğmesinden yeniden başlayın. Sürerse bir yöneticiye sorun." | ||
| 66 | + } | ||
| 67 | + (K::SignInUnavailableTitle, Lang::En) => "Sign-in is unavailable", | ||
| 68 | + (K::SignInUnavailableTitle, Lang::Tr) => "Oturum açma şu an kullanılamıyor", | ||
| 69 | + (K::SignInUnavailableBody, Lang::En) => { | ||
| 70 | + "The account service cannot be reached right now. Try again in a few minutes." | ||
| 71 | + } | ||
| 72 | + (K::SignInUnavailableBody, Lang::Tr) => { | ||
| 73 | + "Hesap servisine şu anda ulaşılamıyor. Birkaç dakika sonra tekrar deneyin." | ||
| 74 | + } | ||
| 75 | + (K::NoAccessTitle, Lang::En) => "No access to this board", | ||
| 76 | + (K::NoAccessTitle, Lang::Tr) => "Bu panoya erişiminiz yok", | ||
| 77 | + (K::NoAccessBody, Lang::En) => { | ||
| 78 | + "Your account is known, but no administrator has given it access. Ask one to add you." | ||
| 79 | + } | ||
| 80 | + (K::NoAccessBody, Lang::Tr) => { | ||
| 81 | + "Hesabınız tanınıyor, ama bir yönetici erişim vermemiş. Eklenmeniz için bir yöneticiye sorun." | ||
| 82 | + } | ||
| 35 | (K::BackHome, Lang::Tr) => "Başlangıca dön", | 83 | (K::BackHome, Lang::Tr) => "Başlangıca dön", |
| 36 | (K::NotFoundBody, Lang::En) => "The page does not exist, or you do not have access to it.", | 84 | (K::NotFoundBody, Lang::En) => "The page does not exist, or you do not have access to it.", |
| 37 | (K::NotFoundBody, Lang::Tr) => "Sayfa yok ya da bu sayfayı görme izniniz yok.", | 85 | (K::NotFoundBody, Lang::Tr) => "Sayfa yok ya da bu sayfayı görme izniniz yok.", |
| 38 | (K::NotFoundTitle, Lang::En) => "Page not found", | 86 | (K::NotFoundTitle, Lang::En) => "Page not found", |
| 39 | (K::NotFoundTitle, Lang::Tr) => "Sayfa bulunamadı", | 87 | (K::NotFoundTitle, Lang::Tr) => "Sayfa bulunamadı", |
| 40 | - (K::SignedOutBody, Lang::En) => { | 88 | + (K::SignedOutBody, Lang::En) => "Sign in with your family account to use the board.", |
| 41 | - "You are signed out. Sign-in is not part of this build yet." | 89 | + (K::SignedOutBody, Lang::Tr) => "Pano için aile hesabınızla oturum açın.", |
| 42 | - } | ||
| 43 | - (K::SignedOutBody, Lang::Tr) => "Oturumunuz kapalı. Oturum açma bu sürümde henüz yok.", | ||
| 44 | (K::SignedOutTitle, Lang::En) => "iz", | 90 | (K::SignedOutTitle, Lang::En) => "iz", |
| 45 | (K::SignedOutTitle, Lang::Tr) => "iz", | 91 | (K::SignedOutTitle, Lang::Tr) => "iz", |
| 46 | (K::ServerRestarting, Lang::En) => "The server is restarting. Reconnecting…", | 92 | (K::ServerRestarting, Lang::En) => "The server is restarting. Reconnecting…", |
| @@ -51,3 +97,11 @@ pub fn t(lang: Lang, key: K) -> &'static str { | |||
| 51 | (K::SkipToContent, Lang::Tr) => "İçeriğe geç", | 97 | (K::SkipToContent, Lang::Tr) => "İçeriğe geç", |
| 52 | } | 98 | } |
| 53 | } | 99 | } |
| 100 | + | ||
| 101 | +/// The greeting of a signed-in member, with their name. | ||
| 102 | +pub fn greeting(lang: Lang, name: &str) -> String { | ||
| 103 | + match lang { | ||
| 104 | + Lang::En => format!("Hello, {name}"), | ||
| 105 | + Lang::Tr => format!("Merhaba, {name}"), | ||
| 106 | + } | ||
| 107 | +} | ||
crates/iz-web/src/main.rsmodified+5 -0
| @@ -5,10 +5,15 @@ | |||
| 5 | //! then `IZ_CONFIG`, then `config/iz.toml`. Exit status 0 is success, 1 a failure, 2 a usage error. | 5 | //! then `IZ_CONFIG`, then `config/iz.toml`. Exit status 0 is success, 1 a failure, 2 a usage error. |
| 6 | 6 | ||
| 7 | mod assets; | 7 | mod assets; |
| 8 | +// The board pages that come next call these helpers; until then they have no caller. | ||
| 9 | +#[allow(dead_code)] | ||
| 10 | +mod auth; | ||
| 8 | mod boot; | 11 | mod boot; |
| 12 | +mod directory; | ||
| 9 | mod health; | 13 | mod health; |
| 10 | mod i18n; | 14 | mod i18n; |
| 11 | mod live; | 15 | mod live; |
| 16 | +mod oidc; | ||
| 12 | mod pages; | 17 | mod pages; |
| 13 | mod security; | 18 | mod security; |
| 14 | mod state; | 19 | mod state; |
crates/iz-web/src/oidc.rsadded+832 -0
| @@ -0,0 +1,832 @@ | |||
| 1 | +//! The OpenID Connect relying party for `im` (docs/contracts.md section 2), and the client | ||
| 2 | +//! credentials token that iz uses to read the people directory (section 2.6). | ||
| 3 | +//! | ||
| 4 | +//! It finds `im`'s endpoints through discovery and keeps them for an hour. It keeps `im`'s signing | ||
| 5 | +//! keys (JWKS) for an hour, and refetches them at most once a minute when a token names a key that | ||
| 6 | +//! is not known. It exchanges authorization codes, and it verifies ID tokens and logout tokens. | ||
| 7 | +//! | ||
| 8 | +//! It decides nothing about who may sign in: that is `pages/sign_in.rs` and the store. It keeps no | ||
| 9 | +//! session state: that is `iz_core::store::sessions`. | ||
| 10 | +//! | ||
| 11 | +//! Verification accepts EdDSA only. The algorithm is checked before a key is looked up, so `none` | ||
| 12 | +//! and every other algorithm are refused. The checks are: the signature, `iss` equal to the | ||
| 13 | +//! configured issuer, `aud` equal to the client id, `exp` with 60 seconds of leeway, `iat` not more | ||
| 14 | +//! than five minutes ahead, and the claims each token kind needs. The pure functions below take the | ||
| 15 | +//! key set and the clock as arguments, so the tests can run without a network. | ||
| 16 | + | ||
| 17 | +use std::collections::HashMap; | ||
| 18 | +use std::path::Path; | ||
| 19 | +use std::sync::Arc; | ||
| 20 | +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; | ||
| 21 | + | ||
| 22 | +use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; | ||
| 23 | +use futures_util::StreamExt; | ||
| 24 | +use iz_core::config::OidcConfig; | ||
| 25 | +use iz_core::token::constant_time_eq; | ||
| 26 | +use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header}; | ||
| 27 | +use serde::Deserialize; | ||
| 28 | +use serde_json::{Map, Value}; | ||
| 29 | +use sha2::{Digest, Sha256}; | ||
| 30 | +use tokio::sync::Mutex; | ||
| 31 | + | ||
| 32 | +/// The scope that reads the people directory and its photos at `im`. | ||
| 33 | +pub const DIRECTORY_SCOPE: &str = "directory.read"; | ||
| 34 | +/// The audience of every directory call: the family key of `im`. | ||
| 35 | +pub const IM_AUDIENCE: &str = "im"; | ||
| 36 | +/// The scopes asked for at sign-in. `openid` is required; `profile` and `email` carry the claims iz uses. | ||
| 37 | +pub const SIGN_IN_SCOPE: &str = "openid profile email"; | ||
| 38 | +/// The event name a back-channel logout token must carry (OIDC Back-Channel Logout 1.0). | ||
| 39 | +pub const BACKCHANNEL_EVENT: &str = "http://schemas.openid.net/event/backchannel-logout"; | ||
| 40 | + | ||
| 41 | +/// Longest wait for one call to `im`, in seconds. Reason: a slow identity provider must not hold a | ||
| 42 | +/// request, and the directory worker retries with backoff anyway. | ||
| 43 | +pub const IM_TIMEOUT: Duration = Duration::from_secs(10); | ||
| 44 | +/// Clock skew tolerated on `exp`, in seconds. Reason: the task policy for every token check. | ||
| 45 | +pub const LEEWAY_SECS: u64 = 60; | ||
| 46 | +/// How far ahead of the local clock an `iat` may be, in seconds. Reason: contracts.md 2.3, five minutes. | ||
| 47 | +pub const MAX_IAT_AHEAD_SECS: u64 = 300; | ||
| 48 | +/// Largest discovery, JWKS or token response read from `im`, in bytes. Reason: those documents are | ||
| 49 | +/// a few kilobytes; a larger answer is not what `im` sends. | ||
| 50 | +pub const MAX_RESPONSE_BYTES: usize = 256 * 1024; | ||
| 51 | +/// How long discovery is cached, before it is fetched again. | ||
| 52 | +const DISCOVERY_TTL: Duration = Duration::from_secs(3600); | ||
| 53 | +/// How long the JWKS is cached, before it is fetched again (contracts.md 2.2). | ||
| 54 | +const KEYS_TTL: Duration = Duration::from_secs(3600); | ||
| 55 | +/// The shortest gap between two JWKS fetches caused by unknown key ids (contracts.md 2.2). | ||
| 56 | +const UNKNOWN_KEY_REFETCH: Duration = Duration::from_secs(60); | ||
| 57 | +/// A service token is replaced this long before it expires (contracts.md 2.6). | ||
| 58 | +const SERVICE_TOKEN_MARGIN: Duration = Duration::from_secs(60); | ||
| 59 | + | ||
| 60 | +/// Every failure of a call to `im` or of a token check. | ||
| 61 | +#[derive(Debug, thiserror::Error)] | ||
| 62 | +pub enum ImError { | ||
| 63 | + /// The token is signed with a key id that is not in the key set. The caller may refetch the | ||
| 64 | + /// keys once and check again. | ||
| 65 | + #[error("the token names a key that is not published")] | ||
| 66 | + UnknownKey, | ||
| 67 | + /// The token failed a check. The text names the check; it is for logs only. | ||
| 68 | + #[error("the token was rejected: {0}")] | ||
| 69 | + Rejected(String), | ||
| 70 | + /// `im` could not be reached, or it did not answer in time. | ||
| 71 | + #[error("the account service cannot be reached: {0}")] | ||
| 72 | + Unavailable(String), | ||
| 73 | + /// `im` answered, but not in a form iz accepts. | ||
| 74 | + #[error("the account service answered in an unexpected way: {0}")] | ||
| 75 | + BadResponse(String), | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +/// The result of a call to `im` or of a token check. | ||
| 79 | +pub type ImResult<T> = std::result::Result<T, ImError>; | ||
| 80 | + | ||
| 81 | +/// The part of the discovery document that iz uses (contracts.md 2.1). | ||
| 82 | +#[derive(Debug, Deserialize)] | ||
| 83 | +pub struct Discovery { | ||
| 84 | + /// Must equal the configured issuer exactly. | ||
| 85 | + pub issuer: String, | ||
| 86 | + /// Where the browser is sent to sign in. | ||
| 87 | + pub authorization_endpoint: String, | ||
| 88 | + /// Where codes and client credentials are exchanged for tokens. | ||
| 89 | + pub token_endpoint: String, | ||
| 90 | + /// Where the signing keys are published. | ||
| 91 | + pub jwks_uri: String, | ||
| 92 | + /// Where the browser is sent to end its `im` session. | ||
| 93 | + #[serde(default)] | ||
| 94 | + pub end_session_endpoint: Option<String>, | ||
| 95 | +} | ||
| 96 | + | ||
| 97 | +/// The answer of the token endpoint. The refresh token is not read: iz discards it (contracts.md 2.4). | ||
| 98 | +#[derive(Debug, Deserialize)] | ||
| 99 | +pub struct TokenResponse { | ||
| 100 | + /// The ID token, for an authorization-code exchange. | ||
| 101 | + #[serde(default)] | ||
| 102 | + pub id_token: Option<String>, | ||
| 103 | + /// The access token, for a client-credentials grant. | ||
| 104 | + #[serde(default)] | ||
| 105 | + pub access_token: Option<String>, | ||
| 106 | + /// The lifetime of the access token, in seconds. | ||
| 107 | + #[serde(default)] | ||
| 108 | + pub expires_in: Option<u64>, | ||
| 109 | +} | ||
| 110 | + | ||
| 111 | +/// The claims of an ID token that iz uses. `sid` is the `im` browser session. | ||
| 112 | +#[derive(Debug, Clone, Deserialize, PartialEq, Eq)] | ||
| 113 | +pub struct IdClaims { | ||
| 114 | + /// The user's id (a ULID, stable forever). | ||
| 115 | + pub sub: String, | ||
| 116 | + /// The `im` browser session id, kept with the local session for back-channel logout. | ||
| 117 | + #[serde(default)] | ||
| 118 | + pub sid: Option<String>, | ||
| 119 | + /// The address. `im` only stores confirmed addresses. | ||
| 120 | + #[serde(default)] | ||
| 121 | + pub email: Option<String>, | ||
| 122 | + /// The display name. | ||
| 123 | + #[serde(default)] | ||
| 124 | + pub name: Option<String>, | ||
| 125 | + /// Whether `im` marks the user as an instance administrator. | ||
| 126 | + #[serde(default)] | ||
| 127 | + pub admin: bool, | ||
| 128 | + /// The language the user chose in `im`, `en` or `tr`. | ||
| 129 | + #[serde(default)] | ||
| 130 | + pub locale: Option<String>, | ||
| 131 | + /// The user's IANA time zone, for example `Europe/Istanbul`. | ||
| 132 | + #[serde(default)] | ||
| 133 | + pub zoneinfo: Option<String>, | ||
| 134 | + /// Bumps when the photo changes. Used as the avatar cache key. | ||
| 135 | + #[serde(default)] | ||
| 136 | + pub picture_version: i64, | ||
| 137 | +} | ||
| 138 | + | ||
| 139 | +/// The claims of a back-channel logout token that iz uses. | ||
| 140 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 141 | +pub struct LogoutClaims { | ||
| 142 | + /// The token id, refused when it is seen again. | ||
| 143 | + pub jti: String, | ||
| 144 | + /// The `im` browser session that ended, when the token names one. | ||
| 145 | + pub sid: Option<String>, | ||
| 146 | + /// The user whose sessions end, when the token names one. | ||
| 147 | + pub sub: Option<String>, | ||
| 148 | +} | ||
| 149 | + | ||
| 150 | +#[derive(Deserialize)] | ||
| 151 | +struct JwksDocument { | ||
| 152 | + keys: Vec<Jwk>, | ||
| 153 | +} | ||
| 154 | + | ||
| 155 | +#[derive(Deserialize)] | ||
| 156 | +struct Jwk { | ||
| 157 | + kty: String, | ||
| 158 | + #[serde(default)] | ||
| 159 | + crv: Option<String>, | ||
| 160 | + #[serde(default)] | ||
| 161 | + x: Option<String>, | ||
| 162 | + #[serde(default)] | ||
| 163 | + kid: Option<String>, | ||
| 164 | + #[serde(default)] | ||
| 165 | + alg: Option<String>, | ||
| 166 | +} | ||
| 167 | + | ||
| 168 | +/// The verification keys of `im`, by key id. Only Ed25519 keys are kept; others are skipped. | ||
| 169 | +#[derive(Default)] | ||
| 170 | +pub struct KeySet { | ||
| 171 | + keys: HashMap<String, DecodingKey>, | ||
| 172 | +} | ||
| 173 | + | ||
| 174 | +impl KeySet { | ||
| 175 | + /// Reads a JWKS document. Keys that are not Ed25519 or have no `kid` are skipped, not fatal. | ||
| 176 | + pub fn from_jwks(bytes: &[u8]) -> ImResult<KeySet> { | ||
| 177 | + let document: JwksDocument = serde_json::from_slice(bytes) | ||
| 178 | + .map_err(|e| ImError::BadResponse(format!("the key set is not JSON: {e}")))?; | ||
| 179 | + let mut keys = HashMap::new(); | ||
| 180 | + for jwk in document.keys { | ||
| 181 | + let (Some(kid), Some(x)) = (jwk.kid.as_deref(), jwk.x.as_deref()) else { | ||
| 182 | + continue; | ||
| 183 | + }; | ||
| 184 | + let is_ed25519 = jwk.kty == "OKP" && jwk.crv.as_deref() == Some("Ed25519"); | ||
| 185 | + if !is_ed25519 || jwk.alg.as_deref().is_some_and(|alg| alg != "EdDSA") { | ||
| 186 | + continue; | ||
| 187 | + } | ||
| 188 | + match DecodingKey::from_ed_components(x) { | ||
| 189 | + Ok(key) => { | ||
| 190 | + keys.insert(kid.to_owned(), key); | ||
| 191 | + } | ||
| 192 | + Err(e) => tracing::warn!(kid, error = %e, "skipping an unreadable signing key"), | ||
| 193 | + } | ||
| 194 | + } | ||
| 195 | + Ok(KeySet { keys }) | ||
| 196 | + } | ||
| 197 | + | ||
| 198 | + fn get(&self, kid: &str) -> Option<&DecodingKey> { | ||
| 199 | + self.keys.get(kid) | ||
| 200 | + } | ||
| 201 | +} | ||
| 202 | + | ||
| 203 | +/// The client of `im`: discovery, keys, token calls and token checks. One per process. | ||
| 204 | +pub struct OidcClient { | ||
| 205 | + issuer: String, | ||
| 206 | + client_id: String, | ||
| 207 | + client_secret: String, | ||
| 208 | + redirect_uri: String, | ||
| 209 | + post_logout_uri: String, | ||
| 210 | + /// Short calls: discovery, keys, tokens, photos. The timeout applies to the whole call. | ||
| 211 | + http: reqwest::Client, | ||
| 212 | + /// Long-lived event stream. Only the connect is bounded here; the reader has its own idle limit. | ||
| 213 | + stream_http: reqwest::Client, | ||
| 214 | + discovery: Mutex<Option<(Instant, Arc<Discovery>)>>, | ||
| 215 | + keys: Mutex<KeyCache>, | ||
| 216 | + service: Mutex<Option<(Instant, String)>>, | ||
| 217 | +} | ||
| 218 | + | ||
| 219 | +#[derive(Default)] | ||
| 220 | +struct KeyCache { | ||
| 221 | + current: Option<(Instant, Arc<KeySet>)>, | ||
| 222 | + last_fetch: Option<Instant>, | ||
| 223 | +} | ||
| 224 | + | ||
| 225 | +impl OidcClient { | ||
| 226 | + /// Builds the client. `base_url` is the public origin of iz, from which the callback and the | ||
| 227 | + /// post-logout URIs are derived; `im` has these registered for the client. | ||
| 228 | + pub fn new(config: &OidcConfig, base_url: &str, client_secret: String) -> iz_core::Result<Self> { | ||
| 229 | + // Redirects are never followed: a token call that is redirected would send the client | ||
| 230 | + // secret to another host. | ||
| 231 | + let http = reqwest::Client::builder() | ||
| 232 | + .timeout(IM_TIMEOUT) | ||
| 233 | + .connect_timeout(IM_TIMEOUT) | ||
| 234 | + .redirect(reqwest::redirect::Policy::none()) | ||
| 235 | + .user_agent(concat!("iz/", env!("CARGO_PKG_VERSION"))) | ||
| 236 | + .build() | ||
| 237 | + .map_err(|e| iz_core::Error::Config(format!("cannot build the HTTP client: {e}")))?; | ||
| 238 | + let stream_http = reqwest::Client::builder() | ||
| 239 | + .connect_timeout(IM_TIMEOUT) | ||
| 240 | + .redirect(reqwest::redirect::Policy::none()) | ||
| 241 | + .user_agent(concat!("iz/", env!("CARGO_PKG_VERSION"))) | ||
| 242 | + .build() | ||
| 243 | + .map_err(|e| iz_core::Error::Config(format!("cannot build the HTTP client: {e}")))?; | ||
| 244 | + Ok(OidcClient { | ||
| 245 | + issuer: config.issuer.clone(), | ||
| 246 | + client_id: config.client_id.clone(), | ||
| 247 | + client_secret, | ||
| 248 | + redirect_uri: format!("{base_url}/auth/callback"), | ||
| 249 | + post_logout_uri: format!("{base_url}/"), | ||
| 250 | + http, | ||
| 251 | + stream_http, | ||
| 252 | + discovery: Mutex::new(None), | ||
| 253 | + keys: Mutex::new(KeyCache::default()), | ||
| 254 | + service: Mutex::new(None), | ||
| 255 | + }) | ||
| 256 | + } | ||
| 257 | + | ||
| 258 | + /// The configured issuer, exactly as it is compared with `iss`. | ||
| 259 | + pub fn issuer(&self) -> &str { | ||
| 260 | + &self.issuer | ||
| 261 | + } | ||
| 262 | + | ||
| 263 | + /// The short-call HTTP client. | ||
| 264 | + pub fn http(&self) -> &reqwest::Client { | ||
| 265 | + &self.http | ||
| 266 | + } | ||
| 267 | + | ||
| 268 | + /// The event-stream HTTP client. | ||
| 269 | + pub fn stream_http(&self) -> &reqwest::Client { | ||
| 270 | + &self.stream_http | ||
| 271 | + } | ||
| 272 | + | ||
| 273 | + /// The discovery document, fetched once and kept for an hour. | ||
| 274 | + pub async fn discovery(&self) -> ImResult<Arc<Discovery>> { | ||
| 275 | + let mut slot = self.discovery.lock().await; | ||
| 276 | + if let Some((at, doc)) = slot.as_ref() | ||
| 277 | + && at.elapsed() < DISCOVERY_TTL | ||
| 278 | + { | ||
| 279 | + return Ok(doc.clone()); | ||
| 280 | + } | ||
| 281 | + let url = format!("{}/.well-known/openid-configuration", self.issuer); | ||
| 282 | + let response = self.http.get(url).send().await.map_err(unavailable)?; | ||
| 283 | + if !response.status().is_success() { | ||
| 284 | + return Err(ImError::Unavailable(format!( | ||
| 285 | + "discovery answered {}", | ||
| 286 | + response.status().as_u16() | ||
| 287 | + ))); | ||
| 288 | + } | ||
| 289 | + let body = read_limited(response, MAX_RESPONSE_BYTES).await?; | ||
| 290 | + let doc: Discovery = serde_json::from_slice(&body) | ||
| 291 | + .map_err(|e| ImError::BadResponse(format!("discovery: {e}")))?; | ||
| 292 | + if doc.issuer != self.issuer { | ||
| 293 | + return Err(ImError::BadResponse( | ||
| 294 | + "discovery names another issuer".into(), | ||
| 295 | + )); | ||
| 296 | + } | ||
| 297 | + let doc = Arc::new(doc); | ||
| 298 | + *slot = Some((Instant::now(), doc.clone())); | ||
| 299 | + Ok(doc) | ||
| 300 | + } | ||
| 301 | + | ||
| 302 | + /// The key set, from the cache when it is fresh. With `refetch_unknown` set, it is fetched again | ||
| 303 | + /// unless the last fetch was less than a minute ago. | ||
| 304 | + async fn key_set(&self, refetch_unknown: bool) -> ImResult<Arc<KeySet>> { | ||
| 305 | + let mut cache = self.keys.lock().await; | ||
| 306 | + if let Some((at, keys)) = cache.current.as_ref() { | ||
| 307 | + if at.elapsed() < KEYS_TTL && !refetch_unknown { | ||
| 308 | + return Ok(keys.clone()); | ||
| 309 | + } | ||
| 310 | + let recently_fetched = cache | ||
| 311 | + .last_fetch | ||
| 312 | + .is_some_and(|at| at.elapsed() < UNKNOWN_KEY_REFETCH); | ||
| 313 | + if refetch_unknown && recently_fetched { | ||
| 314 | + return Ok(keys.clone()); | ||
| 315 | + } | ||
| 316 | + } | ||
| 317 | + let discovery = self.discovery().await?; | ||
| 318 | + let response = self | ||
| 319 | + .http | ||
| 320 | + .get(&discovery.jwks_uri) | ||
| 321 | + .send() | ||
| 322 | + .await | ||
| 323 | + .map_err(unavailable)?; | ||
| 324 | + if !response.status().is_success() { | ||
| 325 | + return Err(ImError::Unavailable(format!( | ||
| 326 | + "the key set answered {}", | ||
| 327 | + response.status().as_u16() | ||
| 328 | + ))); | ||
| 329 | + } | ||
| 330 | + let body = read_limited(response, MAX_RESPONSE_BYTES).await?; | ||
| 331 | + let keys = Arc::new(KeySet::from_jwks(&body)?); | ||
| 332 | + let now = Instant::now(); | ||
| 333 | + cache.last_fetch = Some(now); | ||
| 334 | + cache.current = Some((now, keys.clone())); | ||
| 335 | + Ok(keys) | ||
| 336 | + } | ||
| 337 | + | ||
| 338 | + /// Runs a check against the cached keys. A token that names an unknown key gets one more try | ||
| 339 | + /// against a fresh key set, which the rate bound may refuse. | ||
| 340 | + async fn with_keys<T>(&self, check: impl Fn(&KeySet) -> ImResult<T>) -> ImResult<T> { | ||
| 341 | + let keys = self.key_set(false).await?; | ||
| 342 | + match check(&keys) { | ||
| 343 | + Err(ImError::UnknownKey) => { | ||
| 344 | + let keys = self.key_set(true).await?; | ||
| 345 | + match check(&keys) { | ||
| 346 | + Err(ImError::UnknownKey) => Err(ImError::Rejected( | ||
| 347 | + "the signing key is not published".into(), | ||
| 348 | + )), | ||
| 349 | + other => other, | ||
| 350 | + } | ||
| 351 | + } | ||
| 352 | + other => other, | ||
| 353 | + } | ||
| 354 | + } | ||
| 355 | + | ||
| 356 | + /// The authorization URL for a sign-in, with PKCE (S256) and the state and nonce of this flight. | ||
| 357 | + pub async fn authorize_url(&self, state: &str, nonce: &str, challenge: &str) -> ImResult<String> { | ||
| 358 | + let discovery = self.discovery().await?; | ||
| 359 | + let mut url = reqwest::Url::parse(&discovery.authorization_endpoint) | ||
| 360 | + .map_err(|e| ImError::BadResponse(format!("authorization endpoint: {e}")))?; | ||
| 361 | + url.query_pairs_mut() | ||
| 362 | + .append_pair("response_type", "code") | ||
| 363 | + .append_pair("client_id", &self.client_id) | ||
| 364 | + .append_pair("redirect_uri", &self.redirect_uri) | ||
| 365 | + .append_pair("scope", SIGN_IN_SCOPE) | ||
| 366 | + .append_pair("state", state) | ||
| 367 | + .append_pair("nonce", nonce) | ||
| 368 | + .append_pair("code_challenge", challenge) | ||
| 369 | + .append_pair("code_challenge_method", "S256"); | ||
| 370 | + Ok(url.into()) | ||
| 371 | + } | ||
| 372 | + | ||
| 373 | + /// The end-session URL of RP-initiated logout (contracts.md 2.5). `id_token_hint` is omitted when | ||
| 374 | + /// the session has no stored ID token. | ||
| 375 | + pub async fn end_session_url(&self, id_token_hint: Option<&str>, state: &str) -> ImResult<String> { | ||
| 376 | + let discovery = self.discovery().await?; | ||
| 377 | + let endpoint = discovery | ||
| 378 | + .end_session_endpoint | ||
| 379 | + .as_deref() | ||
| 380 | + .ok_or_else(|| ImError::BadResponse("no end_session_endpoint".into()))?; | ||
| 381 | + let mut url = reqwest::Url::parse(endpoint) | ||
| 382 | + .map_err(|e| ImError::BadResponse(format!("end_session endpoint: {e}")))?; | ||
| 383 | + { | ||
| 384 | + let mut query = url.query_pairs_mut(); | ||
| 385 | + if let Some(hint) = id_token_hint { | ||
| 386 | + query.append_pair("id_token_hint", hint); | ||
| 387 | + } | ||
| 388 | + query | ||
| 389 | + .append_pair("post_logout_redirect_uri", &self.post_logout_uri) | ||
| 390 | + .append_pair("state", state); | ||
| 391 | + } | ||
| 392 | + Ok(url.into()) | ||
| 393 | + } | ||
| 394 | + | ||
| 395 | + /// Exchanges an authorization code for tokens (contracts.md 2.3, step 3). | ||
| 396 | + pub async fn exchange_code(&self, code: &str, verifier: &str) -> ImResult<TokenResponse> { | ||
| 397 | + let discovery = self.discovery().await?; | ||
| 398 | + let form = [ | ||
| 399 | + ("grant_type", "authorization_code"), | ||
| 400 | + ("code", code), | ||
| 401 | + ("redirect_uri", self.redirect_uri.as_str()), | ||
| 402 | + ("code_verifier", verifier), | ||
| 403 | + ]; | ||
| 404 | + self.post_token(&discovery.token_endpoint, &form).await | ||
| 405 | + } | ||
| 406 | + | ||
| 407 | + /// A client-credentials token for `scope` and `audience`, cached until 60 seconds before it | ||
| 408 | + /// expires (contracts.md 2.6). | ||
| 409 | + pub async fn service_token(&self) -> ImResult<String> { | ||
| 410 | + let mut slot = self.service.lock().await; | ||
| 411 | + if let Some((until, token)) = slot.as_ref() | ||
| 412 | + && Instant::now() < *until | ||
| 413 | + { | ||
| 414 | + return Ok(token.clone()); | ||
| 415 | + } | ||
| 416 | + let discovery = self.discovery().await?; | ||
| 417 | + let form = [ | ||
| 418 | + ("grant_type", "client_credentials"), | ||
| 419 | + ("scope", DIRECTORY_SCOPE), | ||
| 420 | + ("audience", IM_AUDIENCE), | ||
| 421 | + ]; | ||
| 422 | + let response = self.post_token(&discovery.token_endpoint, &form).await?; | ||
| 423 | + let token = response | ||
| 424 | + .access_token | ||
| 425 | + .filter(|token| !token.is_empty()) | ||
| 426 | + .ok_or_else(|| ImError::BadResponse("the token answer has no access token".into()))?; | ||
| 427 | + let lifetime = Duration::from_secs(response.expires_in.unwrap_or(0)); | ||
| 428 | + let until = Instant::now() + lifetime.saturating_sub(SERVICE_TOKEN_MARGIN); | ||
| 429 | + *slot = Some((until, token.clone())); | ||
| 430 | + Ok(token) | ||
| 431 | + } | ||
| 432 | + | ||
| 433 | + /// Posts a form to the token endpoint with `client_secret_basic` and no redirect following. | ||
| 434 | + async fn post_token(&self, url: &str, form: &[(&str, &str)]) -> ImResult<TokenResponse> { | ||
| 435 | + let response = self | ||
| 436 | + .http | ||
| 437 | + .post(url) | ||
| 438 | + .basic_auth(&self.client_id, Some(&self.client_secret)) | ||
| 439 | + .form(form) | ||
| 440 | + .send() | ||
| 441 | + .await | ||
| 442 | + .map_err(unavailable)?; | ||
| 443 | + let status = response.status(); | ||
| 444 | + let body = read_limited(response, MAX_RESPONSE_BYTES).await?; | ||
| 445 | + if !status.is_success() { | ||
| 446 | + // The body of an error answer is not logged: it can echo request values. | ||
| 447 | + return Err(ImError::Rejected(format!( | ||
| 448 | + "the token endpoint answered {}", | ||
| 449 | + status.as_u16() | ||
| 450 | + ))); | ||
| 451 | + } | ||
| 452 | + serde_json::from_slice(&body) | ||
| 453 | + .map_err(|e| ImError::BadResponse(format!("the token answer: {e}"))) | ||
| 454 | + } | ||
| 455 | + | ||
| 456 | + /// Verifies an ID token against the current keys, and the nonce of the flight. | ||
| 457 | + pub async fn verify_id_token(&self, token: &str, nonce: &str) -> ImResult<IdClaims> { | ||
| 458 | + let now = unix_now(); | ||
| 459 | + self.with_keys(|keys| verify_id_token(keys, &self.issuer, &self.client_id, token, nonce, now)) | ||
| 460 | + .await | ||
| 461 | + } | ||
| 462 | + | ||
| 463 | + /// Verifies a back-channel logout token against the current keys. | ||
| 464 | + pub async fn verify_logout_token(&self, token: &str) -> ImResult<LogoutClaims> { | ||
| 465 | + let now = unix_now(); | ||
| 466 | + self.with_keys(|keys| verify_logout_token(keys, &self.issuer, &self.client_id, token, now)) | ||
| 467 | + .await | ||
| 468 | + } | ||
| 469 | +} | ||
| 470 | + | ||
| 471 | +/// The PKCE code challenge of a verifier: base64url of the SHA-256 of the verifier (RFC 7636, S256). | ||
| 472 | +pub fn pkce_challenge(verifier: &str) -> String { | ||
| 473 | + BASE64_URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())) | ||
| 474 | +} | ||
| 475 | + | ||
| 476 | +/// The current time as seconds since the Unix epoch. Zero if the clock is before it. | ||
| 477 | +pub fn unix_now() -> u64 { | ||
| 478 | + SystemTime::now() | ||
| 479 | + .duration_since(UNIX_EPOCH) | ||
| 480 | + .map_or(0, |d| d.as_secs()) | ||
| 481 | +} | ||
| 482 | + | ||
| 483 | +/// Verifies an ID token (contracts.md 2.3, step 4). `nonce` must equal the nonce of this flight. | ||
| 484 | +pub fn verify_id_token( | ||
| 485 | + keys: &KeySet, | ||
| 486 | + issuer: &str, | ||
| 487 | + client_id: &str, | ||
| 488 | + token: &str, | ||
| 489 | + nonce: &str, | ||
| 490 | + now: u64, | ||
| 491 | +) -> ImResult<IdClaims> { | ||
| 492 | + let claims = verify_signature(keys, issuer, client_id, token)?; | ||
| 493 | + check_iat(&claims, now)?; | ||
| 494 | + let sent = str_claim(&claims, "nonce") | ||
| 495 | + .ok_or_else(|| ImError::Rejected("the nonce claim is missing".into()))?; | ||
| 496 | + if !constant_time_eq(sent.as_bytes(), nonce.as_bytes()) { | ||
| 497 | + return Err(ImError::Rejected("the nonce does not match this sign-in".into())); | ||
| 498 | + } | ||
| 499 | + let id: IdClaims = serde_json::from_value(Value::Object(claims)) | ||
| 500 | + .map_err(|e| ImError::Rejected(format!("the claims are malformed: {e}")))?; | ||
| 501 | + if id.sub.is_empty() || id.sub.len() > 64 { | ||
| 502 | + return Err(ImError::Rejected("the subject is not a member id".into())); | ||
| 503 | + } | ||
| 504 | + Ok(id) | ||
| 505 | +} | ||
| 506 | + | ||
| 507 | +/// Verifies a back-channel logout token (OIDC Back-Channel Logout 1.0, contracts.md 2.5). It must | ||
| 508 | +/// carry the back-channel event, must not carry a nonce, must carry a `jti`, and must name a `sid` or | ||
| 509 | +/// a `sub`. | ||
| 510 | +pub fn verify_logout_token( | ||
| 511 | + keys: &KeySet, | ||
| 512 | + issuer: &str, | ||
| 513 | + client_id: &str, | ||
| 514 | + token: &str, | ||
| 515 | + now: u64, | ||
| 516 | +) -> ImResult<LogoutClaims> { | ||
| 517 | + let claims = verify_signature(keys, issuer, client_id, token)?; | ||
| 518 | + check_iat(&claims, now)?; | ||
| 519 | + if claims.contains_key("nonce") { | ||
| 520 | + return Err(ImError::Rejected("a logout token must not carry a nonce".into())); | ||
| 521 | + } | ||
| 522 | + let events = claims | ||
| 523 | + .get("events") | ||
| 524 | + .and_then(Value::as_object) | ||
| 525 | + .ok_or_else(|| ImError::Rejected("the events claim is missing".into()))?; | ||
| 526 | + if !events.contains_key(BACKCHANNEL_EVENT) { | ||
| 527 | + return Err(ImError::Rejected("the event is not back-channel logout".into())); | ||
| 528 | + } | ||
| 529 | + let jti = str_claim(&claims, "jti") | ||
| 530 | + .ok_or_else(|| ImError::Rejected("the jti claim is missing".into()))?; | ||
| 531 | + let sid = str_claim(&claims, "sid"); | ||
| 532 | + let sub = str_claim(&claims, "sub"); | ||
| 533 | + if sid.is_none() && sub.is_none() { | ||
| 534 | + return Err(ImError::Rejected("the token names neither sid nor sub".into())); | ||
| 535 | + } | ||
| 536 | + Ok(LogoutClaims { jti, sid, sub }) | ||
| 537 | +} | ||
| 538 | + | ||
| 539 | +/// Checks the header, finds the key, and verifies the signature and the registered claims. Returns | ||
| 540 | +/// the claims as a map, for the token-specific checks. | ||
| 541 | +fn verify_signature( | ||
| 542 | + keys: &KeySet, | ||
| 543 | + issuer: &str, | ||
| 544 | + client_id: &str, | ||
| 545 | + token: &str, | ||
| 546 | +) -> ImResult<Map<String, Value>> { | ||
| 547 | + // The algorithm is read from the header and refused unless it is EdDSA, before any key is used. | ||
| 548 | + let header = decode_header(token) | ||
| 549 | + .map_err(|e| ImError::Rejected(format!("the header is malformed: {e}")))?; | ||
| 550 | + if header.alg != Algorithm::EdDSA { | ||
| 551 | + return Err(ImError::Rejected(format!( | ||
| 552 | + "the algorithm {:?} is not accepted", | ||
| 553 | + header.alg | ||
| 554 | + ))); | ||
| 555 | + } | ||
| 556 | + let kid = header | ||
| 557 | + .kid | ||
| 558 | + .as_deref() | ||
| 559 | + .ok_or_else(|| ImError::Rejected("the header has no kid".into()))?; | ||
| 560 | + let key = keys.get(kid).ok_or(ImError::UnknownKey)?; | ||
| 561 | + let mut validation = Validation::new(Algorithm::EdDSA); | ||
| 562 | + validation.leeway = LEEWAY_SECS; | ||
| 563 | + validation.set_issuer(&[issuer]); | ||
| 564 | + validation.set_audience(&[client_id]); | ||
| 565 | + validation.set_required_spec_claims(&["exp", "iss", "aud"]); | ||
| 566 | + let data = decode::<Map<String, Value>>(token, key, &validation) | ||
| 567 | + .map_err(|e| ImError::Rejected(e.to_string()))?; | ||
| 568 | + Ok(data.claims) | ||
| 569 | +} | ||
| 570 | + | ||
| 571 | +/// `iat` must be present and not more than [`MAX_IAT_AHEAD_SECS`] ahead of `now`. | ||
| 572 | +fn check_iat(claims: &Map<String, Value>, now: u64) -> ImResult<()> { | ||
| 573 | + let iat = claims | ||
| 574 | + .get("iat") | ||
| 575 | + .and_then(Value::as_u64) | ||
| 576 | + .ok_or_else(|| ImError::Rejected("the iat claim is missing".into()))?; | ||
| 577 | + if iat > now.saturating_add(MAX_IAT_AHEAD_SECS) { | ||
| 578 | + return Err(ImError::Rejected("the iat claim is in the future".into())); | ||
| 579 | + } | ||
| 580 | + Ok(()) | ||
| 581 | +} | ||
| 582 | + | ||
| 583 | +/// A string claim that is present and not empty. | ||
| 584 | +fn str_claim(claims: &Map<String, Value>, name: &str) -> Option<String> { | ||
| 585 | + claims | ||
| 586 | + .get(name) | ||
| 587 | + .and_then(Value::as_str) | ||
| 588 | + .filter(|s| !s.is_empty()) | ||
| 589 | + .map(str::to_owned) | ||
| 590 | +} | ||
| 591 | + | ||
| 592 | +fn unavailable(error: reqwest::Error) -> ImError { | ||
| 593 | + ImError::Unavailable(error.to_string()) | ||
| 594 | +} | ||
| 595 | + | ||
| 596 | +/// Reads a response body, refusing one larger than `limit` bytes. The check runs while the body is | ||
| 597 | +/// read, so a server that lies about its length cannot make iz hold more than `limit`. | ||
| 598 | +pub async fn read_limited(response: reqwest::Response, limit: usize) -> ImResult<Vec<u8>> { | ||
| 599 | + let too_large = || ImError::BadResponse("the answer is too large".into()); | ||
| 600 | + if response | ||
| 601 | + .content_length() | ||
| 602 | + .is_some_and(|len| len > u64::try_from(limit).unwrap_or(u64::MAX)) | ||
| 603 | + { | ||
| 604 | + return Err(too_large()); | ||
| 605 | + } | ||
| 606 | + let mut body = Vec::new(); | ||
| 607 | + let mut chunks = response.bytes_stream(); | ||
| 608 | + while let Some(chunk) = chunks.next().await { | ||
| 609 | + let chunk = chunk.map_err(unavailable)?; | ||
| 610 | + if body.len() + chunk.len() > limit { | ||
| 611 | + return Err(too_large()); | ||
| 612 | + } | ||
| 613 | + body.extend_from_slice(&chunk); | ||
| 614 | + } | ||
| 615 | + Ok(body) | ||
| 616 | +} | ||
| 617 | + | ||
| 618 | +/// Reads the client secret from `path`. The file must not be readable by group or others, the same | ||
| 619 | +/// rule as the instance key. The value is trimmed and must not be empty. | ||
| 620 | +pub fn read_client_secret(path: &Path) -> iz_core::Result<String> { | ||
| 621 | + #[cfg(unix)] | ||
| 622 | + { | ||
| 623 | + use std::os::unix::fs::PermissionsExt; | ||
| 624 | + let mode = std::fs::metadata(path)?.permissions().mode(); | ||
| 625 | + if mode & 0o077 != 0 { | ||
| 626 | + return Err(iz_core::Error::Config(format!( | ||
| 627 | + "client secret {} is group or world accessible (mode {:o}); expected 0600", | ||
| 628 | + path.display(), | ||
| 629 | + mode & 0o777 | ||
| 630 | + ))); | ||
| 631 | + } | ||
| 632 | + } | ||
| 633 | + let text = std::fs::read_to_string(path)?; | ||
| 634 | + let secret = text.trim().to_owned(); | ||
| 635 | + if secret.is_empty() { | ||
| 636 | + return Err(iz_core::Error::Config(format!( | ||
| 637 | + "client secret {} is empty", | ||
| 638 | + path.display() | ||
| 639 | + ))); | ||
| 640 | + } | ||
| 641 | + Ok(secret) | ||
| 642 | +} | ||
| 643 | + | ||
| 644 | +#[cfg(test)] | ||
| 645 | +pub(crate) mod test_support { | ||
| 646 | + //! Ed25519 keys and signed tokens for the tests. The keys are generated for each test, so no key | ||
| 647 | + //! material lives in the repository. | ||
| 648 | + | ||
| 649 | + use aws_lc_rs::rand::SystemRandom; | ||
| 650 | + use aws_lc_rs::signature::{Ed25519KeyPair, KeyPair}; | ||
| 651 | + use jsonwebtoken::{EncodingKey, Header, encode}; | ||
| 652 | + use serde_json::{Value, json}; | ||
| 653 | + | ||
| 654 | + use super::KeySet; | ||
| 655 | + | ||
| 656 | + /// The issuer used by the tests. | ||
| 657 | + pub const ISSUER: &str = "https://im.example.com"; | ||
| 658 | + /// The client id used by the tests. | ||
| 659 | + pub const CLIENT_ID: &str = "iz"; | ||
| 660 | + | ||
| 661 | + /// A signing key with the key set that verifies it, under the key id `k1`. | ||
| 662 | + pub struct Signer { | ||
| 663 | + pub keys: KeySet, | ||
| 664 | + encoding: EncodingKey, | ||
| 665 | + } | ||
| 666 | + | ||
| 667 | + impl Signer { | ||
| 668 | + pub fn generate() -> Signer { | ||
| 669 | + let pkcs8 = Ed25519KeyPair::generate_pkcs8(&SystemRandom::new()).expect("keygen"); | ||
| 670 | + let pair = Ed25519KeyPair::from_pkcs8(pkcs8.as_ref()).expect("pkcs8"); | ||
| 671 | + let x = base64::Engine::encode( | ||
| 672 | + &base64::prelude::BASE64_URL_SAFE_NO_PAD, | ||
| 673 | + pair.public_key().as_ref(), | ||
| 674 | + ); | ||
| 675 | + let jwks = json!({"keys": [{"kty": "OKP", "crv": "Ed25519", "x": x, "kid": "k1", "use": "sig", "alg": "EdDSA"}]}); | ||
| 676 | + Signer { | ||
| 677 | + keys: KeySet::from_jwks(jwks.to_string().as_bytes()).expect("jwks"), | ||
| 678 | + encoding: EncodingKey::from_ed_der(pkcs8.as_ref()), | ||
| 679 | + } | ||
| 680 | + } | ||
| 681 | + | ||
| 682 | + /// Signs `claims` as an EdDSA token with kid `k1`. | ||
| 683 | + pub fn sign(&self, claims: &Value) -> String { | ||
| 684 | + self.sign_with_kid("k1", claims) | ||
| 685 | + } | ||
| 686 | + | ||
| 687 | + /// Signs `claims` as an EdDSA token with the given kid. | ||
| 688 | + pub fn sign_with_kid(&self, kid: &str, claims: &Value) -> String { | ||
| 689 | + let mut header = Header::new(jsonwebtoken::Algorithm::EdDSA); | ||
| 690 | + header.kid = Some(kid.into()); | ||
| 691 | + encode(&header, claims, &self.encoding).expect("sign") | ||
| 692 | + } | ||
| 693 | + } | ||
| 694 | + | ||
| 695 | + /// Claims of an ID token that passes every check at time `now`, with `nonce`. | ||
| 696 | + pub fn id_claims(now: u64, nonce: &str) -> Value { | ||
| 697 | + json!({ | ||
| 698 | + "iss": ISSUER, "aud": CLIENT_ID, "sub": "01JMEMBER0000000000000000A", | ||
| 699 | + "exp": now + 600, "iat": now, "auth_time": now, "nonce": nonce, | ||
| 700 | + "sid": "sid-1", "email": "ada@example.com", "email_verified": true, | ||
| 701 | + "name": "Ada", "admin": false, "locale": "en", "zoneinfo": "Europe/Istanbul", | ||
| 702 | + "picture_version": 1 | ||
| 703 | + }) | ||
| 704 | + } | ||
| 705 | + | ||
| 706 | + /// Claims of a back-channel logout token that passes every check at time `now`. | ||
| 707 | + pub fn logout_claims(now: u64, jti: &str) -> Value { | ||
| 708 | + json!({ | ||
| 709 | + "iss": ISSUER, "aud": CLIENT_ID, "iat": now, "exp": now + 120, "jti": jti, | ||
| 710 | + "sid": "sid-1", "sub": "01JMEMBER0000000000000000A", | ||
| 711 | + "events": {"http://schemas.openid.net/event/backchannel-logout": {}} | ||
| 712 | + }) | ||
| 713 | + } | ||
| 714 | +} | ||
| 715 | + | ||
| 716 | +#[cfg(test)] | ||
| 717 | +mod tests { | ||
| 718 | + use super::test_support::{CLIENT_ID, ISSUER, Signer, id_claims, logout_claims}; | ||
| 719 | + use super::*; | ||
| 720 | + use serde_json::json; | ||
| 721 | + | ||
| 722 | + const NOW: u64 = 1_800_000_000; | ||
| 723 | + | ||
| 724 | + fn unsigned(header: &str, payload: &Value) -> String { | ||
| 725 | + let h = BASE64_URL_SAFE_NO_PAD.encode(header); | ||
| 726 | + let p = BASE64_URL_SAFE_NO_PAD.encode(payload.to_string()); | ||
| 727 | + format!("{h}.{p}.") | ||
| 728 | + } | ||
| 729 | + | ||
| 730 | + #[test] | ||
| 731 | + fn pkce_challenge_matches_the_rfc_7636_example() { | ||
| 732 | + assert_eq!( | ||
| 733 | + pkce_challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"), | ||
| 734 | + "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" | ||
| 735 | + ); | ||
| 736 | + } | ||
| 737 | + | ||
| 738 | + #[test] | ||
| 739 | + fn a_well_formed_id_token_is_accepted() { | ||
| 740 | + let signer = Signer::generate(); | ||
| 741 | + let token = signer.sign(&id_claims(NOW, "n-1")); | ||
| 742 | + let id = verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-1", NOW).unwrap(); | ||
| 743 | + assert_eq!(id.sub, "01JMEMBER0000000000000000A"); | ||
| 744 | + assert_eq!(id.sid.as_deref(), Some("sid-1")); | ||
| 745 | + assert_eq!(id.picture_version, 1); | ||
| 746 | + } | ||
| 747 | + | ||
| 748 | + #[test] | ||
| 749 | + fn an_unsigned_alg_none_token_is_refused() { | ||
| 750 | + let signer = Signer::generate(); | ||
| 751 | + let token = unsigned(r#"{"alg":"none","kid":"k1"}"#, &id_claims(NOW, "n-1")); | ||
| 752 | + assert!(matches!( | ||
| 753 | + verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-1", NOW), | ||
| 754 | + Err(ImError::Rejected(_)) | ||
| 755 | + )); | ||
| 756 | + } | ||
| 757 | + | ||
| 758 | + #[test] | ||
| 759 | + fn a_token_for_another_audience_is_refused() { | ||
| 760 | + let signer = Signer::generate(); | ||
| 761 | + let mut claims = id_claims(NOW, "n-1"); | ||
| 762 | + claims["aud"] = json!("in"); | ||
| 763 | + let token = signer.sign(&claims); | ||
| 764 | + assert!(matches!( | ||
| 765 | + verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-1", NOW), | ||
| 766 | + Err(ImError::Rejected(_)) | ||
| 767 | + )); | ||
| 768 | + } | ||
| 769 | + | ||
| 770 | + #[test] | ||
| 771 | + fn an_expired_token_is_refused_but_leeway_is_allowed() { | ||
| 772 | + // `exp` is checked against the system clock, so this test uses the real current time. | ||
| 773 | + let now = unix_now(); | ||
| 774 | + let signer = Signer::generate(); | ||
| 775 | + let mut claims = id_claims(now, "n-1"); | ||
| 776 | + claims["exp"] = json!(now - 3600); | ||
| 777 | + let token = signer.sign(&claims); | ||
| 778 | + assert!(verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-1", now).is_err()); | ||
| 779 | + let mut claims = id_claims(now, "n-1"); | ||
| 780 | + claims["exp"] = json!(now - 30); | ||
| 781 | + let token = signer.sign(&claims); | ||
| 782 | + assert!(verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-1", now).is_ok()); | ||
| 783 | + } | ||
| 784 | + | ||
| 785 | + #[test] | ||
| 786 | + fn a_wrong_nonce_is_refused() { | ||
| 787 | + let signer = Signer::generate(); | ||
| 788 | + let token = signer.sign(&id_claims(NOW, "n-1")); | ||
| 789 | + assert!(matches!( | ||
| 790 | + verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-2", NOW), | ||
| 791 | + Err(ImError::Rejected(_)) | ||
| 792 | + )); | ||
| 793 | + } | ||
| 794 | + | ||
| 795 | + #[test] | ||
| 796 | + fn an_unknown_key_id_asks_for_a_refetch() { | ||
| 797 | + let signer = Signer::generate(); | ||
| 798 | + let token = signer.sign_with_kid("k2", &id_claims(NOW, "n-1")); | ||
| 799 | + assert!(matches!( | ||
| 800 | + verify_id_token(&signer.keys, ISSUER, CLIENT_ID, &token, "n-1", NOW), | ||
| 801 | + Err(ImError::UnknownKey) | ||
| 802 | + )); | ||
| 803 | + } | ||
| 804 | + | ||
| 805 | + #[test] | ||
| 806 | + fn a_logout_token_needs_the_event_and_no_nonce() { | ||
| 807 | + let signer = Signer::generate(); | ||
| 808 | + let good = signer.sign(&logout_claims(NOW, "j-1")); | ||
| 809 | + let claims = verify_logout_token(&signer.keys, ISSUER, CLIENT_ID, &good, NOW).unwrap(); | ||
| 810 | + assert_eq!(claims.jti, "j-1"); | ||
| 811 | + assert_eq!(claims.sid.as_deref(), Some("sid-1")); | ||
| 812 | + | ||
| 813 | + let mut with_nonce = logout_claims(NOW, "j-2"); | ||
| 814 | + with_nonce["nonce"] = json!("n"); | ||
| 815 | + let token = signer.sign(&with_nonce); | ||
| 816 | + assert!(verify_logout_token(&signer.keys, ISSUER, CLIENT_ID, &token, NOW).is_err()); | ||
| 817 | + | ||
| 818 | + let mut no_event = logout_claims(NOW, "j-3"); | ||
| 819 | + no_event["events"] = json!({}); | ||
| 820 | + let token = signer.sign(&no_event); | ||
| 821 | + assert!(verify_logout_token(&signer.keys, ISSUER, CLIENT_ID, &token, NOW).is_err()); | ||
| 822 | + } | ||
| 823 | + | ||
| 824 | + #[test] | ||
| 825 | + fn the_key_set_keeps_only_ed25519_keys_with_a_kid() { | ||
| 826 | + let set = KeySet::from_jwks( | ||
| 827 | + br#"{"keys":[{"kty":"RSA","kid":"r1","n":"x","e":"AQAB"},{"kty":"OKP","crv":"Ed25519","kid":"no-x"}]}"#, | ||
| 828 | + ) | ||
| 829 | + .unwrap(); | ||
| 830 | + assert!(set.keys.is_empty()); | ||
| 831 | + } | ||
| 832 | +} | ||
crates/iz-web/src/pages/backchannel.rsadded+202 -0
| @@ -0,0 +1,202 @@ | |||
| 1 | +//! `POST /auth/backchannel-logout`: the back-channel logout of `im` (OIDC Back-Channel Logout 1.0, | ||
| 2 | +//! docs/contracts.md 2.5). `im` posts `logout_token=<JWT>` here when a session ends, and iz ends the | ||
| 3 | +//! matching local sessions. | ||
| 4 | +//! | ||
| 5 | +//! The route is the one contracts.md 2.5 names as the URI `im` registers for each client. It is a | ||
| 6 | +//! machine endpoint: no CSRF token, no cookie, and a body capped at 16 KiB. Success is `200` with an | ||
| 7 | +//! empty body. Every other answer is a JSON error (`docs/contracts.md` section 7): `413` for a body | ||
| 8 | +//! over 16 KiB, `503` when `im`'s keys cannot be fetched, `400` for anything else the request gets | ||
| 9 | +//! wrong (a token iz refuses, a replayed token included), and `500` when the database fails. | ||
| 10 | + | ||
| 11 | +use std::time::Duration; | ||
| 12 | + | ||
| 13 | +use iz_core::store::Store; | ||
| 14 | +use serde::Deserialize; | ||
| 15 | +use serde_json::json; | ||
| 16 | +use topcoat::Result; | ||
| 17 | +use topcoat::context::{Cx, app_context}; | ||
| 18 | +use topcoat::router::content::Form; | ||
| 19 | +use topcoat::router::{Body, HeaderMap, HeaderValue, StatusCode, header, route, to_bytes}; | ||
| 20 | + | ||
| 21 | +use crate::oidc::{ImError, LogoutClaims}; | ||
| 22 | +use crate::state::AppState; | ||
| 23 | + | ||
| 24 | +/// Largest back-channel body accepted, in bytes. Reason: the form holds one token of a few kilobytes. | ||
| 25 | +const MAX_BODY_BYTES: usize = 16 * 1024; | ||
| 26 | +/// How long a logout token id is remembered, so a replay is refused. Reason: contracts.md 2.5, ten | ||
| 27 | +/// minutes, which is five times the token's own two-minute life. | ||
| 28 | +const JTI_LIFETIME: Duration = Duration::from_secs(10 * 60); | ||
| 29 | + | ||
| 30 | +/// Why a logout token did not end any session. | ||
| 31 | +#[derive(Debug, thiserror::Error)] | ||
| 32 | +pub enum BackchannelError { | ||
| 33 | + /// The token id was already used. Refused, so the same token cannot be replayed. | ||
| 34 | + #[error("the logout token was already used")] | ||
| 35 | + Replay, | ||
| 36 | + /// The database failed while the logout was recorded. | ||
| 37 | + #[error(transparent)] | ||
| 38 | + Store(#[from] iz_core::Error), | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +/// The form body of the back-channel request. | ||
| 42 | +#[derive(Deserialize)] | ||
| 43 | +struct BackchannelForm { | ||
| 44 | + #[serde(default)] | ||
| 45 | + logout_token: String, | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +/// Ends the sessions that a verified logout token names, and records its id so it cannot be used | ||
| 49 | +/// again. A `sid` ends that browser session; a token with only a `sub` ends every session of the | ||
| 50 | +/// user (a disabled or deleted member). Returns how many sessions ended. | ||
| 51 | +/// | ||
| 52 | +/// The id is recorded first and atomically (`seen_jti` inserts and reports a repeat), so two copies | ||
| 53 | +/// of one token cannot both succeed. | ||
| 54 | +pub async fn end_sessions(store: &Store, claims: &LogoutClaims) -> std::result::Result<u64, BackchannelError> { | ||
| 55 | + if store.seen_jti(&claims.jti, JTI_LIFETIME).await? { | ||
| 56 | + return Err(BackchannelError::Replay); | ||
| 57 | + } | ||
| 58 | + let ended = match (&claims.sid, &claims.sub) { | ||
| 59 | + (Some(sid), _) => store.delete_sessions_by_sid(sid).await?, | ||
| 60 | + (None, Some(sub)) => store.delete_sessions_by_sub(sub).await?, | ||
| 61 | + // The verifier requires one of the two, so this arm is unreachable in practice. | ||
| 62 | + (None, None) => 0, | ||
| 63 | + }; | ||
| 64 | + Ok(ended) | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +/// `POST /auth/backchannel-logout`. | ||
| 68 | +#[route(POST "/auth/backchannel-logout")] | ||
| 69 | +async fn backchannel_logout(cx: &Cx, body: Body) -> Result<(StatusCode, HeaderMap, String)> { | ||
| 70 | + let state = app_context::<AppState>(cx); | ||
| 71 | + let Some(client) = state.oidc.clone() else { | ||
| 72 | + return Ok(json_error( | ||
| 73 | + StatusCode::SERVICE_UNAVAILABLE, | ||
| 74 | + "unavailable", | ||
| 75 | + "sign-in is not configured", | ||
| 76 | + )); | ||
| 77 | + }; | ||
| 78 | + let Ok(bytes) = to_bytes(body, MAX_BODY_BYTES).await else { | ||
| 79 | + return Ok(json_error( | ||
| 80 | + StatusCode::PAYLOAD_TOO_LARGE, | ||
| 81 | + "invalid_request", | ||
| 82 | + "the body is missing or larger than 16 KiB", | ||
| 83 | + )); | ||
| 84 | + }; | ||
| 85 | + let Ok(Form(form)) = Form::<BackchannelForm>::from_bytes(&bytes) else { | ||
| 86 | + return Ok(json_error( | ||
| 87 | + StatusCode::BAD_REQUEST, | ||
| 88 | + "invalid_request", | ||
| 89 | + "the body is not a form", | ||
| 90 | + )); | ||
| 91 | + }; | ||
| 92 | + if form.logout_token.is_empty() { | ||
| 93 | + return Ok(json_error( | ||
| 94 | + StatusCode::BAD_REQUEST, | ||
| 95 | + "invalid_request", | ||
| 96 | + "logout_token is missing", | ||
| 97 | + )); | ||
| 98 | + } | ||
| 99 | + let claims = match client.verify_logout_token(&form.logout_token).await { | ||
| 100 | + Ok(claims) => claims, | ||
| 101 | + Err(ImError::Unavailable(reason) | ImError::BadResponse(reason)) => { | ||
| 102 | + tracing::warn!(reason, "back-channel logout: the key set cannot be read"); | ||
| 103 | + return Ok(json_error( | ||
| 104 | + StatusCode::SERVICE_UNAVAILABLE, | ||
| 105 | + "unavailable", | ||
| 106 | + "the keys of the account service cannot be read", | ||
| 107 | + )); | ||
| 108 | + } | ||
| 109 | + Err(error) => { | ||
| 110 | + tracing::warn!(error = %error, "back-channel logout: the token was refused"); | ||
| 111 | + return Ok(json_error( | ||
| 112 | + StatusCode::BAD_REQUEST, | ||
| 113 | + "invalid_request", | ||
| 114 | + "the logout token was refused", | ||
| 115 | + )); | ||
| 116 | + } | ||
| 117 | + }; | ||
| 118 | + match end_sessions(&state.store, &claims).await { | ||
| 119 | + Ok(ended) => { | ||
| 120 | + tracing::info!(ended, "back-channel logout"); | ||
| 121 | + Ok((StatusCode::OK, HeaderMap::new(), String::new())) | ||
| 122 | + } | ||
| 123 | + Err(BackchannelError::Replay) => { | ||
| 124 | + tracing::warn!("back-channel logout: a token was replayed"); | ||
| 125 | + Ok(json_error( | ||
| 126 | + StatusCode::BAD_REQUEST, | ||
| 127 | + "invalid_request", | ||
| 128 | + "the logout token was already used", | ||
| 129 | + )) | ||
| 130 | + } | ||
| 131 | + Err(BackchannelError::Store(error)) => { | ||
| 132 | + tracing::error!(error = %error, "back-channel logout: the database failed"); | ||
| 133 | + Ok(json_error( | ||
| 134 | + StatusCode::INTERNAL_SERVER_ERROR, | ||
| 135 | + "internal", | ||
| 136 | + "the logout could not be recorded", | ||
| 137 | + )) | ||
| 138 | + } | ||
| 139 | + } | ||
| 140 | +} | ||
| 141 | + | ||
| 142 | +/// A JSON error answer: `{"error": <stable word>, "message": <English text>}`. | ||
| 143 | +fn json_error(status: StatusCode, error: &str, message: &str) -> (StatusCode, HeaderMap, String) { | ||
| 144 | + let mut headers = HeaderMap::new(); | ||
| 145 | + headers.insert( | ||
| 146 | + header::CONTENT_TYPE, | ||
| 147 | + HeaderValue::from_static("application/json"), | ||
| 148 | + ); | ||
| 149 | + ( | ||
| 150 | + status, | ||
| 151 | + headers, | ||
| 152 | + json!({"error": error, "message": message}).to_string(), | ||
| 153 | + ) | ||
| 154 | +} | ||
| 155 | + | ||
| 156 | +#[cfg(test)] | ||
| 157 | +mod tests { | ||
| 158 | + use iz_core::authz::Role; | ||
| 159 | + use iz_core::store::Store; | ||
| 160 | + use iz_core::store::members::DirectoryMember; | ||
| 161 | + | ||
| 162 | + use super::*; | ||
| 163 | + use crate::oidc::test_support::{CLIENT_ID, ISSUER, Signer, logout_claims}; | ||
| 164 | + use crate::oidc::{unix_now, verify_logout_token}; | ||
| 165 | + | ||
| 166 | + /// A replayed logout token is refused, and it ends a session only the first time. | ||
| 167 | + #[tokio::test] | ||
| 168 | + async fn a_replayed_back_channel_jti_is_refused() { | ||
| 169 | + let dir = tempfile::tempdir().expect("temp dir"); | ||
| 170 | + let store = Store::open(&dir.path().join("iz.db")).await.expect("store"); | ||
| 171 | + let member = DirectoryMember { | ||
| 172 | + sub: "01MEMBERAAAAAAAAAAAAAAAAAA".into(), | ||
| 173 | + email: "ada@example.com".into(), | ||
| 174 | + name: "Ada".into(), | ||
| 175 | + im_admin: false, | ||
| 176 | + disabled: false, | ||
| 177 | + locale: None, | ||
| 178 | + zoneinfo: "UTC".into(), | ||
| 179 | + picture_version: 0, | ||
| 180 | + }; | ||
| 181 | + store | ||
| 182 | + .apply_directory_member(&member, Role::Member) | ||
| 183 | + .await | ||
| 184 | + .expect("member"); | ||
| 185 | + store | ||
| 186 | + .create_session(&member.sub, Some("sid-1"), None, Duration::from_secs(3600), None, None) | ||
| 187 | + .await | ||
| 188 | + .expect("session"); | ||
| 189 | + | ||
| 190 | + let now = unix_now(); | ||
| 191 | + let signer = Signer::generate(); | ||
| 192 | + let token = signer.sign(&logout_claims(now, "jti-1")); | ||
| 193 | + let claims = verify_logout_token(&signer.keys, ISSUER, CLIENT_ID, &token, now) | ||
| 194 | + .expect("the token verifies"); | ||
| 195 | + | ||
| 196 | + assert_eq!(end_sessions(&store, &claims).await.expect("first use"), 1); | ||
| 197 | + assert!(matches!( | ||
| 198 | + end_sessions(&store, &claims).await, | ||
| 199 | + Err(BackchannelError::Replay) | ||
| 200 | + )); | ||
| 201 | + } | ||
| 202 | +} | ||
crates/iz-web/src/pages/home.rsmodified+27 -8
| @@ -1,25 +1,44 @@ | |||
| 1 | -//! The start page. Until sign-in exists every visitor is signed out, so it shows the app name and | 1 | +//! The start page. A signed-out visitor sees the app name and a sign-in button. A signed-in member |
| 2 | -//! that the viewer is not signed in. | 2 | +//! sees a greeting; the board itself comes later, so the page says that. |
| 3 | 3 | ||
| 4 | use topcoat::Result; | 4 | use topcoat::Result; |
| 5 | use topcoat::context::Cx; | 5 | use topcoat::context::Cx; |
| 6 | use topcoat::router::page; | 6 | use topcoat::router::page; |
| 7 | use topcoat::view::{View, view}; | 7 | use topcoat::view::{View, view}; |
| 8 | 8 | ||
| 9 | +use crate::auth::current_member; | ||
| 10 | +use crate::i18n::shell::{K, greeting, t}; | ||
| 9 | use crate::i18n::lang; | 11 | use crate::i18n::lang; |
| 10 | -use crate::i18n::shell::{K, t}; | 12 | +use crate::views::{ViewerInfo, shell}; |
| 11 | -use crate::views::shell; | 13 | +use iz_core::authz::Role; |
| 12 | 14 | ||
| 13 | /// `GET /`. | 15 | /// `GET /`. |
| 14 | #[page("/")] | 16 | #[page("/")] |
| 15 | async fn home(cx: &Cx) -> Result<impl View> { | 17 | async fn home(cx: &Cx) -> Result<impl View> { |
| 16 | - let lang = lang(cx, None); | 18 | + let me = current_member(cx).await?; |
| 19 | + let lang = lang( | ||
| 20 | + cx, | ||
| 21 | + me.as_ref() | ||
| 22 | + .and_then(|me| me.member.locale_override.as_deref()), | ||
| 23 | + ); | ||
| 24 | + let viewer = me.as_ref().map(|me| ViewerInfo { | ||
| 25 | + name: me.member.name.clone(), | ||
| 26 | + is_admin: me.member.im_admin || me.member.role == Role::Admin, | ||
| 27 | + csrf: me.session.csrf_token.clone(), | ||
| 28 | + }); | ||
| 29 | + let name = me.as_ref().map(|me| me.member.name.clone()); | ||
| 17 | Ok(view! { | 30 | Ok(view! { |
| 18 | - shell(title: t(lang, K::SignedOutTitle), lang: lang, viewer: None, | 31 | + shell(title: t(lang, K::SignedOutTitle), lang: lang, viewer: viewer.as_ref(), |
| 19 | <section class="card"> | 32 | <section class="card"> |
| 20 | <p class="kicker">"iz"</p> | 33 | <p class="kicker">"iz"</p> |
| 21 | - <h1>(t(lang, K::SignedOutTitle))</h1> | 34 | + if let Some(name) = name { |
| 22 | - <p>(t(lang, K::SignedOutBody))</p> | 35 | + <h1>(greeting(lang, &name))</h1> |
| 36 | + <p>(t(lang, K::BoardComesNext))</p> | ||
| 37 | + } else { | ||
| 38 | + <h1>(t(lang, K::SignedOutTitle))</h1> | ||
| 39 | + <p>(t(lang, K::SignedOutBody))</p> | ||
| 40 | + <a class="button primary" href="/auth/login">(t(lang, K::SignIn))</a> | ||
| 41 | + } | ||
| 23 | </section> | 42 | </section> |
| 24 | ) | 43 | ) |
| 25 | }) | 44 | }) |
crates/iz-web/src/pages/mod.rsmodified+3 -0
| @@ -1,4 +1,7 @@ | |||
| 1 | //! The pages and the page-level layers. One file per page. | 1 | //! The pages and the page-level layers. One file per page. |
| 2 | 2 | ||
| 3 | +pub mod backchannel; | ||
| 3 | pub mod home; | 4 | pub mod home; |
| 4 | pub mod not_found; | 5 | pub mod not_found; |
| 6 | +pub mod photo; | ||
| 7 | +pub mod sign_in; | ||
crates/iz-web/src/pages/photo.rsadded+158 -0
| @@ -0,0 +1,158 @@ | |||
| 1 | +//! `GET /avatar/{sub}`: a member's photo, proxied from `im` and cached on disk | ||
| 2 | +//! (docs/contracts.md 3.2 and `architecture.md` section 4). | ||
| 3 | +//! | ||
| 4 | +//! Only a signed-in member may fetch a photo. A browser never talks to `im` for one, and an `im` | ||
| 5 | +//! failure with no cached copy is a plain `404`, so the page falls back to initials. The cache key is | ||
| 6 | +//! `(sub, picture_version)`; a changed photo gets a new version and the old files are removed. | ||
| 7 | +//! The ETag is `"p<picture_version>"`. A `?v=` that matches the current version may be cached for a | ||
| 8 | +//! year; any other request is revalidated. | ||
| 9 | + | ||
| 10 | +use std::path::{Path, PathBuf}; | ||
| 11 | + | ||
| 12 | +use http::header::{ | ||
| 13 | + CACHE_CONTROL, CONTENT_TYPE, ETAG, IF_NONE_MATCH, X_CONTENT_TYPE_OPTIONS, | ||
| 14 | +}; | ||
| 15 | +use topcoat::Result; | ||
| 16 | +use topcoat::context::{Cx, app_context}; | ||
| 17 | +use topcoat::router::error::not_found; | ||
| 18 | +use topcoat::router::request::{headers, uri}; | ||
| 19 | +use topcoat::router::{HeaderMap, HeaderValue, StatusCode, path_param_segment, route}; | ||
| 20 | + | ||
| 21 | +use crate::auth::current_member; | ||
| 22 | +use crate::directory::{PHOTO_TYPES, fetch_photo}; | ||
| 23 | +use crate::state::AppState; | ||
| 24 | + | ||
| 25 | +/// Longest member id accepted in the path. Reason: ids are ULIDs (26 characters); this leaves room. | ||
| 26 | +const MAX_SUB_LEN: usize = 64; | ||
| 27 | + | ||
| 28 | +/// `GET /avatar/{sub}`. | ||
| 29 | +#[route(GET "/avatar/{sub}")] | ||
| 30 | +async fn photo(cx: &Cx) -> Result<(StatusCode, HeaderMap, Vec<u8>)> { | ||
| 31 | + let state = app_context::<AppState>(cx); | ||
| 32 | + // Anonymous and unknown requests get the same 404: a photo URL reveals nothing without a session. | ||
| 33 | + if current_member(cx).await?.is_none() { | ||
| 34 | + return Err(not_found().into()); | ||
| 35 | + } | ||
| 36 | + let sub = path_param_segment(cx, "sub").to_owned(); | ||
| 37 | + if !valid_sub(&sub) { | ||
| 38 | + return Err(not_found().into()); | ||
| 39 | + } | ||
| 40 | + let Some(member) = state.store.member(&sub).await? else { | ||
| 41 | + return Err(not_found().into()); | ||
| 42 | + }; | ||
| 43 | + if member.disabled { | ||
| 44 | + return Err(not_found().into()); | ||
| 45 | + } | ||
| 46 | + | ||
| 47 | + let etag = format!("\"p{}\"", member.picture_version); | ||
| 48 | + let current = requested_version(cx) == Some(member.picture_version); | ||
| 49 | + let mut out = HeaderMap::new(); | ||
| 50 | + out.insert(ETAG, HeaderValue::from_str(&etag)?); | ||
| 51 | + out.insert( | ||
| 52 | + CACHE_CONTROL, | ||
| 53 | + HeaderValue::from_static(if current { | ||
| 54 | + "private, max-age=31536000, immutable" | ||
| 55 | + } else { | ||
| 56 | + "private, no-cache" | ||
| 57 | + }), | ||
| 58 | + ); | ||
| 59 | + out.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")); | ||
| 60 | + if if_none_match_has(cx, &etag) { | ||
| 61 | + return Ok((StatusCode::NOT_MODIFIED, out, Vec::new())); | ||
| 62 | + } | ||
| 63 | + | ||
| 64 | + let Some((mime, bytes)) = load(state, &sub, member.picture_version).await else { | ||
| 65 | + return Err(not_found().into()); | ||
| 66 | + }; | ||
| 67 | + out.insert(CONTENT_TYPE, HeaderValue::from_str(&mime)?); | ||
| 68 | + Ok((StatusCode::OK, out, bytes)) | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +/// A member id that is safe as a directory name and in a URL: letters, digits, `-` and `_`. | ||
| 72 | +fn valid_sub(sub: &str) -> bool { | ||
| 73 | + !sub.is_empty() | ||
| 74 | + && sub.len() <= MAX_SUB_LEN | ||
| 75 | + && sub | ||
| 76 | + .bytes() | ||
| 77 | + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +/// The `v` of the query string, if it is a number. | ||
| 81 | +fn requested_version(cx: &Cx) -> Option<i64> { | ||
| 82 | + uri(cx) | ||
| 83 | + .query()? | ||
| 84 | + .split('&') | ||
| 85 | + .find_map(|pair| pair.strip_prefix("v=")) | ||
| 86 | + .and_then(|value| value.parse().ok()) | ||
| 87 | +} | ||
| 88 | + | ||
| 89 | +/// Whether `If-None-Match` names `etag` (or `*`). | ||
| 90 | +fn if_none_match_has(cx: &Cx, etag: &str) -> bool { | ||
| 91 | + headers(cx) | ||
| 92 | + .get(IF_NONE_MATCH) | ||
| 93 | + .and_then(|value| value.to_str().ok()) | ||
| 94 | + .is_some_and(|value| { | ||
| 95 | + value | ||
| 96 | + .split(',') | ||
| 97 | + .map(str::trim) | ||
| 98 | + .any(|candidate| candidate == etag || candidate == "*") | ||
| 99 | + }) | ||
| 100 | +} | ||
| 101 | + | ||
| 102 | +/// The photo for `(sub, version)`: from the disk cache, else from `im`, which is then cached. `None` | ||
| 103 | +/// when there is no photo, `im` is unreachable and nothing is cached, or the type is not allowed. | ||
| 104 | +async fn load(state: &AppState, sub: &str, version: i64) -> Option<(String, Vec<u8>)> { | ||
| 105 | + let dir = state.config.data_dir.join("photos").join(sub); | ||
| 106 | + if let Some(cached) = read_cache(&dir.join(format!("{version}.img"))).await { | ||
| 107 | + return Some(cached); | ||
| 108 | + } | ||
| 109 | + let oidc = state.oidc.as_ref()?; | ||
| 110 | + match fetch_photo(oidc, sub).await { | ||
| 111 | + Ok(Some((mime, bytes))) => { | ||
| 112 | + if let Err(error) = write_cache(&dir, version, &mime, &bytes).await { | ||
| 113 | + tracing::warn!(error = %error, "photo: could not write the cache"); | ||
| 114 | + } | ||
| 115 | + Some((mime, bytes)) | ||
| 116 | + } | ||
| 117 | + Ok(None) => None, | ||
| 118 | + Err(error) => { | ||
| 119 | + tracing::warn!(error = %error, "photo: the account service did not answer"); | ||
| 120 | + None | ||
| 121 | + } | ||
| 122 | + } | ||
| 123 | +} | ||
| 124 | + | ||
| 125 | +/// Reads a cached photo: the first line is the type, the rest is the image. A cached type that is no | ||
| 126 | +/// longer allowed is treated as a miss. | ||
| 127 | +async fn read_cache(path: &Path) -> Option<(String, Vec<u8>)> { | ||
| 128 | + let data = tokio::fs::read(path).await.ok()?; | ||
| 129 | + let newline = data.iter().position(|&b| b == b'\n')?; | ||
| 130 | + let mime = std::str::from_utf8(&data[..newline]).ok()?.to_owned(); | ||
| 131 | + if !PHOTO_TYPES.contains(&mime.as_str()) { | ||
| 132 | + return None; | ||
| 133 | + } | ||
| 134 | + Some((mime, data[newline + 1..].to_vec())) | ||
| 135 | +} | ||
| 136 | + | ||
| 137 | +/// Writes a photo under its version, through a temporary file so a reader never sees half of it, and | ||
| 138 | +/// removes the files of other versions of the same member. | ||
| 139 | +async fn write_cache(dir: &Path, version: i64, mime: &str, bytes: &[u8]) -> std::io::Result<()> { | ||
| 140 | + tokio::fs::create_dir_all(dir).await?; | ||
| 141 | + let name = format!("{version}.img"); | ||
| 142 | + let tmp = dir.join(format!("{version}.tmp")); | ||
| 143 | + let mut data = Vec::with_capacity(mime.len() + 1 + bytes.len()); | ||
| 144 | + data.extend_from_slice(mime.as_bytes()); | ||
| 145 | + data.push(b'\n'); | ||
| 146 | + data.extend_from_slice(bytes); | ||
| 147 | + tokio::fs::write(&tmp, &data).await?; | ||
| 148 | + tokio::fs::rename(&tmp, dir.join(&name)).await?; | ||
| 149 | + let mut entries = tokio::fs::read_dir(dir).await?; | ||
| 150 | + while let Some(entry) = entries.next_entry().await? { | ||
| 151 | + let path: PathBuf = entry.path(); | ||
| 152 | + let is_image = path.extension().is_some_and(|ext| ext == "img"); | ||
| 153 | + if is_image && entry.file_name().to_str() != Some(name.as_str()) { | ||
| 154 | + tokio::fs::remove_file(&path).await?; | ||
| 155 | + } | ||
| 156 | + } | ||
| 157 | + Ok(()) | ||
| 158 | +} | ||
crates/iz-web/src/pages/sign_in.rsadded+397 -0
| @@ -0,0 +1,397 @@ | |||
| 1 | +//! Sign-in and sign-out (docs/contracts.md 2.3 and 2.5): `GET /auth/login` starts the flight, `GET | ||
| 2 | +//! /auth/callback` finishes it, and `POST /auth/logout` ends the local session and the `im` session. | ||
| 3 | +//! | ||
| 4 | +//! The order in the callback is fixed: the flight cookie is cleared first, so it is used only once; | ||
| 5 | +//! the state is compared in constant time; the code is exchanged; the ID token is verified with the | ||
| 6 | +//! nonce of this flight; the member is upserted from the claims; a member with no role, or who is | ||
| 7 | +//! disabled, gets the no-access page and no session; only then is the local session created. | ||
| 8 | + | ||
| 9 | +use iz_core::authz::Role; | ||
| 10 | +use iz_core::secret; | ||
| 11 | +use iz_core::store::members::DirectoryMember; | ||
| 12 | +use iz_core::token::{constant_time_eq, generate_token}; | ||
| 13 | +use iz_core::zones::parse_zone; | ||
| 14 | +use serde::Deserialize; | ||
| 15 | +use topcoat::Result; | ||
| 16 | +use topcoat::context::{Cx, app_context}; | ||
| 17 | +use topcoat::router::content::Form; | ||
| 18 | +use topcoat::router::error::{forbidden, see_other}; | ||
| 19 | +use topcoat::router::{StatusCode, page, route}; | ||
| 20 | +use topcoat::view::{View, view}; | ||
| 21 | + | ||
| 22 | +use crate::auth::{ | ||
| 23 | + SESSION_LIFETIME, STATE_LIFETIME, SignInState, clear_session_cookie, clear_state_cookie, | ||
| 24 | + current_member, open_sign_in_state, query_param, safe_next, seal_sign_in_state, | ||
| 25 | + set_session_cookie, set_state_cookie, state_cookie, user_agent, | ||
| 26 | +}; | ||
| 27 | +use crate::directory; | ||
| 28 | +use crate::i18n::shell::{K, t}; | ||
| 29 | +use crate::i18n::{Lang, lang}; | ||
| 30 | +use crate::oidc::{ImError, pkce_challenge, unix_now}; | ||
| 31 | +use crate::state::AppState; | ||
| 32 | +use crate::views::{message_page, shell}; | ||
| 33 | + | ||
| 34 | +/// The page of a failed sign-in or a refused one. `detail` is shown escaped, in a code element. | ||
| 35 | +async fn message( | ||
| 36 | + cx: &Cx, | ||
| 37 | + status: StatusCode, | ||
| 38 | + title: K, | ||
| 39 | + body: K, | ||
| 40 | + detail: Option<String>, | ||
| 41 | +) -> Result<impl View> { | ||
| 42 | + let lang: Lang = lang(cx, None); | ||
| 43 | + Ok(view! { | ||
| 44 | + cx => | ||
| 45 | + shell(title: t(lang, title), lang: lang, viewer: None, | ||
| 46 | + (status) | ||
| 47 | + message_page(lang: lang, title: title, body: body, detail: detail) | ||
| 48 | + ) | ||
| 49 | + }) | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +/// The page and status for an `im` failure: the account service is down or answered badly, or the | ||
| 53 | +/// token was refused. | ||
| 54 | +fn failure_for(error: &ImError) -> (StatusCode, K, K) { | ||
| 55 | + match error { | ||
| 56 | + ImError::Unavailable(_) | ImError::BadResponse(_) => ( | ||
| 57 | + StatusCode::SERVICE_UNAVAILABLE, | ||
| 58 | + K::SignInUnavailableTitle, | ||
| 59 | + K::SignInUnavailableBody, | ||
| 60 | + ), | ||
| 61 | + ImError::UnknownKey | ImError::Rejected(_) => ( | ||
| 62 | + StatusCode::BAD_REQUEST, | ||
| 63 | + K::SignInFailedTitle, | ||
| 64 | + K::SignInFailedBody, | ||
| 65 | + ), | ||
| 66 | + } | ||
| 67 | +} | ||
| 68 | + | ||
| 69 | +/// `GET /login?next=<path>`: starts a sign-in. Stores the flight in a sealed cookie and sends the | ||
| 70 | +/// browser to `im`'s authorization endpoint with PKCE, the state and the nonce. | ||
| 71 | +#[page("/auth/login")] | ||
| 72 | +async fn login(cx: &Cx) -> Result<impl View> { | ||
| 73 | + let state = app_context::<AppState>(cx); | ||
| 74 | + let Some(client) = state.oidc.clone() else { | ||
| 75 | + return message( | ||
| 76 | + cx, | ||
| 77 | + StatusCode::SERVICE_UNAVAILABLE, | ||
| 78 | + K::SignInUnavailableTitle, | ||
| 79 | + K::SignInUnavailableBody, | ||
| 80 | + None, | ||
| 81 | + ) | ||
| 82 | + .await; | ||
| 83 | + }; | ||
| 84 | + let flight = SignInState { | ||
| 85 | + state: generate_token(), | ||
| 86 | + nonce: generate_token(), | ||
| 87 | + verifier: generate_token(), | ||
| 88 | + next: safe_next(query_param(cx, "next").as_deref()).to_owned(), | ||
| 89 | + expires: unix_now() + STATE_LIFETIME.as_secs(), | ||
| 90 | + }; | ||
| 91 | + let url = match client | ||
| 92 | + .authorize_url(&flight.state, &flight.nonce, &pkce_challenge(&flight.verifier)) | ||
| 93 | + .await | ||
| 94 | + { | ||
| 95 | + Ok(url) => url, | ||
| 96 | + Err(error) => { | ||
| 97 | + tracing::warn!(error = %error, "sign-in: cannot start the flight"); | ||
| 98 | + let (status, title, body) = failure_for(&error); | ||
| 99 | + return message(cx, status, title, body, None).await; | ||
| 100 | + } | ||
| 101 | + }; | ||
| 102 | + let sealed = seal_sign_in_state(&state.key, &flight)?; | ||
| 103 | + set_state_cookie(cx, sealed); | ||
| 104 | + Err(see_other(url).into()) | ||
| 105 | +} | ||
| 106 | + | ||
| 107 | +/// `GET /auth/callback`: finishes a sign-in that `im` sent back. | ||
| 108 | +#[page("/auth/callback")] | ||
| 109 | +async fn callback(cx: &Cx) -> Result<impl View> { | ||
| 110 | + let state = app_context::<AppState>(cx); | ||
| 111 | + let sealed = state_cookie(cx); | ||
| 112 | + // Cleared before anything else, so the flight can be used only once, whatever happens next. | ||
| 113 | + clear_state_cookie(cx); | ||
| 114 | + let Some(client) = state.oidc.clone() else { | ||
| 115 | + return message( | ||
| 116 | + cx, | ||
| 117 | + StatusCode::SERVICE_UNAVAILABLE, | ||
| 118 | + K::SignInUnavailableTitle, | ||
| 119 | + K::SignInUnavailableBody, | ||
| 120 | + None, | ||
| 121 | + ) | ||
| 122 | + .await; | ||
| 123 | + }; | ||
| 124 | + let Some(flight) = sealed.and_then(|s| open_sign_in_state(&state.key, &s)) else { | ||
| 125 | + tracing::warn!("sign-in: no valid flight cookie"); | ||
| 126 | + return message( | ||
| 127 | + cx, | ||
| 128 | + StatusCode::BAD_REQUEST, | ||
| 129 | + K::SignInFailedTitle, | ||
| 130 | + K::SignInFailedBody, | ||
| 131 | + None, | ||
| 132 | + ) | ||
| 133 | + .await; | ||
| 134 | + }; | ||
| 135 | + let returned = query_param(cx, "state").unwrap_or_default(); | ||
| 136 | + if !constant_time_eq(returned.as_bytes(), flight.state.as_bytes()) { | ||
| 137 | + tracing::warn!("sign-in: the state does not match the flight"); | ||
| 138 | + return message( | ||
| 139 | + cx, | ||
| 140 | + StatusCode::BAD_REQUEST, | ||
| 141 | + K::SignInFailedTitle, | ||
| 142 | + K::SignInFailedBody, | ||
| 143 | + None, | ||
| 144 | + ) | ||
| 145 | + .await; | ||
| 146 | + } | ||
| 147 | + if let Some(error) = query_param(cx, "error") { | ||
| 148 | + // The value comes from `im`. It is cut short and shown escaped, and never used for anything else. | ||
| 149 | + let shown: String = error.chars().take(64).collect(); | ||
| 150 | + tracing::warn!(error = %shown, "sign-in: the identity provider refused the sign-in"); | ||
| 151 | + return message( | ||
| 152 | + cx, | ||
| 153 | + StatusCode::BAD_REQUEST, | ||
| 154 | + K::SignInFailedTitle, | ||
| 155 | + K::SignInFailedBody, | ||
| 156 | + Some(shown), | ||
| 157 | + ) | ||
| 158 | + .await; | ||
| 159 | + } | ||
| 160 | + let Some(code) = query_param(cx, "code").filter(|code| !code.is_empty()) else { | ||
| 161 | + return message( | ||
| 162 | + cx, | ||
| 163 | + StatusCode::BAD_REQUEST, | ||
| 164 | + K::SignInFailedTitle, | ||
| 165 | + K::SignInFailedBody, | ||
| 166 | + None, | ||
| 167 | + ) | ||
| 168 | + .await; | ||
| 169 | + }; | ||
| 170 | + | ||
| 171 | + let tokens = match client.exchange_code(&code, &flight.verifier).await { | ||
| 172 | + Ok(tokens) => tokens, | ||
| 173 | + Err(error) => { | ||
| 174 | + tracing::warn!(error = %error, "sign-in: the code exchange failed"); | ||
| 175 | + let (status, title, body) = failure_for(&error); | ||
| 176 | + return message(cx, status, title, body, None).await; | ||
| 177 | + } | ||
| 178 | + }; | ||
| 179 | + let Some(id_token) = tokens.id_token.filter(|token| !token.is_empty()) else { | ||
| 180 | + tracing::warn!("sign-in: the token answer has no ID token"); | ||
| 181 | + return message( | ||
| 182 | + cx, | ||
| 183 | + StatusCode::BAD_REQUEST, | ||
| 184 | + K::SignInFailedTitle, | ||
| 185 | + K::SignInFailedBody, | ||
| 186 | + None, | ||
| 187 | + ) | ||
| 188 | + .await; | ||
| 189 | + }; | ||
| 190 | + let claims = match client.verify_id_token(&id_token, &flight.nonce).await { | ||
| 191 | + Ok(claims) => claims, | ||
| 192 | + Err(error) => { | ||
| 193 | + tracing::warn!(error = %error, "sign-in: the ID token was refused"); | ||
| 194 | + let (status, title, body) = failure_for(&error); | ||
| 195 | + return message(cx, status, title, body, None).await; | ||
| 196 | + } | ||
| 197 | + }; | ||
| 198 | + | ||
| 199 | + let Some(email) = claims | ||
| 200 | |||
| 201 | + .clone() | ||
| 202 | + .map(|email| email.trim().to_owned()) | ||
| 203 | + .filter(|email| !email.is_empty()) | ||
| 204 | + else { | ||
| 205 | + tracing::warn!("sign-in: the ID token has no email"); | ||
| 206 | + return message( | ||
| 207 | + cx, | ||
| 208 | + StatusCode::BAD_REQUEST, | ||
| 209 | + K::SignInFailedTitle, | ||
| 210 | + K::SignInFailedBody, | ||
| 211 | + None, | ||
| 212 | + ) | ||
| 213 | + .await; | ||
| 214 | + }; | ||
| 215 | + let name = claims | ||
| 216 | + .name | ||
| 217 | + .clone() | ||
| 218 | + .map(|name| name.trim().to_owned()) | ||
| 219 | + .filter(|name| !name.is_empty()) | ||
| 220 | + .unwrap_or_else(|| email.clone()); | ||
| 221 | + // A time zone the store does not know must not block the sign-in; it falls back to UTC. | ||
| 222 | + let zoneinfo = claims | ||
| 223 | + .zoneinfo | ||
| 224 | + .clone() | ||
| 225 | + .filter(|zone| parse_zone(zone).is_ok()) | ||
| 226 | + .unwrap_or_else(|| "UTC".to_owned()); | ||
| 227 | + let member_input = DirectoryMember { | ||
| 228 | + sub: claims.sub.clone(), | ||
| 229 | + email, | ||
| 230 | + name, | ||
| 231 | + im_admin: claims.admin, | ||
| 232 | + disabled: false, | ||
| 233 | + locale: claims.locale.clone(), | ||
| 234 | + zoneinfo, | ||
| 235 | + picture_version: claims.picture_version, | ||
| 236 | + }; | ||
| 237 | + let default_role = directory::default_role(&state.store).await?; | ||
| 238 | + let stored = match state | ||
| 239 | + .store | ||
| 240 | + .upsert_from_claims(&member_input, default_role) | ||
| 241 | + .await | ||
| 242 | + { | ||
| 243 | + Ok(stored) => stored, | ||
| 244 | + Err(iz_core::Error::Invalid(reason)) => { | ||
| 245 | + tracing::warn!(reason, "sign-in: the member record is refused"); | ||
| 246 | + return message( | ||
| 247 | + cx, | ||
| 248 | + StatusCode::BAD_REQUEST, | ||
| 249 | + K::SignInFailedTitle, | ||
| 250 | + K::SignInFailedBody, | ||
| 251 | + None, | ||
| 252 | + ) | ||
| 253 | + .await; | ||
| 254 | + } | ||
| 255 | + Err(error) => return Err(error.into()), | ||
| 256 | + }; | ||
| 257 | + if stored.disabled || stored.role == Role::NoAccess { | ||
| 258 | + tracing::info!(sub = %stored.sub, "sign-in: no access for this member"); | ||
| 259 | + return message( | ||
| 260 | + cx, | ||
| 261 | + StatusCode::FORBIDDEN, | ||
| 262 | + K::NoAccessTitle, | ||
| 263 | + K::NoAccessBody, | ||
| 264 | + None, | ||
| 265 | + ) | ||
| 266 | + .await; | ||
| 267 | + } | ||
| 268 | + | ||
| 269 | + // The ID token is kept, sealed, as the hint of a later logout. | ||
| 270 | + let sealed_id_token = secret::seal(&state.key, id_token.as_bytes())?; | ||
| 271 | + let issued = match state | ||
| 272 | + .store | ||
| 273 | + .create_session( | ||
| 274 | + &stored.sub, | ||
| 275 | + claims.sid.as_deref(), | ||
| 276 | + Some(&sealed_id_token), | ||
| 277 | + SESSION_LIFETIME, | ||
| 278 | + user_agent(cx).as_deref(), | ||
| 279 | + None, | ||
| 280 | + ) | ||
| 281 | + .await | ||
| 282 | + { | ||
| 283 | + Ok(issued) => issued, | ||
| 284 | + Err(iz_core::Error::Forbidden(_)) => { | ||
| 285 | + return message( | ||
| 286 | + cx, | ||
| 287 | + StatusCode::FORBIDDEN, | ||
| 288 | + K::NoAccessTitle, | ||
| 289 | + K::NoAccessBody, | ||
| 290 | + None, | ||
| 291 | + ) | ||
| 292 | + .await; | ||
| 293 | + } | ||
| 294 | + Err(error) => return Err(error.into()), | ||
| 295 | + }; | ||
| 296 | + set_session_cookie(cx, issued.token); | ||
| 297 | + tracing::info!(sub = %stored.sub, "signed in"); | ||
| 298 | + Err(see_other(safe_next(Some(&flight.next))).into()) | ||
| 299 | +} | ||
| 300 | + | ||
| 301 | +/// The form of `POST /auth/logout`. The CSRF token is read as text; a missing one is refused. | ||
| 302 | +#[derive(Deserialize)] | ||
| 303 | +struct LogoutForm { | ||
| 304 | + #[serde(default)] | ||
| 305 | + csrf: String, | ||
| 306 | +} | ||
| 307 | + | ||
| 308 | +/// `POST /auth/logout`: ends the local session, then sends the browser to `im`'s end-session endpoint with | ||
| 309 | +/// the stored ID token as the hint (contracts.md 2.5). The CSRF check runs before any side effect. | ||
| 310 | +#[route(POST "/auth/logout")] | ||
| 311 | +async fn logout(cx: &Cx, form: Option<Form<LogoutForm>>) -> Result<topcoat::router::error::SeeOther> { | ||
| 312 | + let state = app_context::<AppState>(cx); | ||
| 313 | + let Some(me) = current_member(cx).await? else { | ||
| 314 | + // Nothing to end: the session is already gone. | ||
| 315 | + clear_session_cookie(cx); | ||
| 316 | + return Ok(see_other("/")); | ||
| 317 | + }; | ||
| 318 | + let submitted = form.map(|Form(form)| form.csrf).unwrap_or_default(); | ||
| 319 | + if !me.csrf_matches(&submitted) { | ||
| 320 | + return Err(forbidden().into()); | ||
| 321 | + } | ||
| 322 | + state.store.delete_session(&me.session.id).await?; | ||
| 323 | + clear_session_cookie(cx); | ||
| 324 | + | ||
| 325 | + let id_token = me | ||
| 326 | + .session | ||
| 327 | + .id_token_sealed | ||
| 328 | + .as_deref() | ||
| 329 | + .and_then(|sealed| secret::open(&state.key, sealed).ok()) | ||
| 330 | + .and_then(|plain| String::from_utf8(plain).ok()); | ||
| 331 | + let target = match &state.oidc { | ||
| 332 | + Some(client) => match client | ||
| 333 | + .end_session_url(id_token.as_deref(), &generate_token()) | ||
| 334 | + .await | ||
| 335 | + { | ||
| 336 | + Ok(url) => url, | ||
| 337 | + Err(error) => { | ||
| 338 | + tracing::warn!(error = %error, "logout: no end-session URL; returning to the start"); | ||
| 339 | + "/".to_owned() | ||
| 340 | + } | ||
| 341 | + }, | ||
| 342 | + None => "/".to_owned(), | ||
| 343 | + }; | ||
| 344 | + Ok(see_other(target)) | ||
| 345 | +} | ||
| 346 | + | ||
| 347 | +#[cfg(test)] | ||
| 348 | +mod tests { | ||
| 349 | + use http::header::{CONTENT_TYPE, COOKIE}; | ||
| 350 | + use iz_core::authz::Role; | ||
| 351 | + use iz_core::store::members::DirectoryMember; | ||
| 352 | + use topcoat::router::Body; | ||
| 353 | + | ||
| 354 | + use crate::auth::SESSION_LIFETIME; | ||
| 355 | + use crate::boot::{router, test_state}; | ||
| 356 | + | ||
| 357 | + /// A sign-out without the CSRF token is refused, and the session survives it. | ||
| 358 | + #[tokio::test] | ||
| 359 | + async fn logout_without_csrf_is_forbidden_and_keeps_the_session() { | ||
| 360 | + let (_dir, state) = test_state().await; | ||
| 361 | + let member = DirectoryMember { | ||
| 362 | + sub: "01MEMBERAAAAAAAAAAAAAAAAAA".into(), | ||
| 363 | + email: "ada@example.com".into(), | ||
| 364 | + name: "Ada".into(), | ||
| 365 | + im_admin: false, | ||
| 366 | + disabled: false, | ||
| 367 | + locale: None, | ||
| 368 | + zoneinfo: "UTC".into(), | ||
| 369 | + picture_version: 0, | ||
| 370 | + }; | ||
| 371 | + state | ||
| 372 | + .store | ||
| 373 | + .apply_directory_member(&member, Role::Member) | ||
| 374 | + .await | ||
| 375 | + .unwrap(); | ||
| 376 | + let issued = state | ||
| 377 | + .store | ||
| 378 | + .create_session(&member.sub, Some("sid-1"), None, SESSION_LIFETIME, None, None) | ||
| 379 | + .await | ||
| 380 | + .unwrap(); | ||
| 381 | + let request = http::Request::post("/auth/logout") | ||
| 382 | + .header(CONTENT_TYPE, "application/x-www-form-urlencoded") | ||
| 383 | + .header(COOKIE, format!("__Host-iz_session={}", issued.token)) | ||
| 384 | + .body(Body::from("csrf=not-the-token")) | ||
| 385 | + .expect("request"); | ||
| 386 | + let response = router(state.clone()).handle(request).await; | ||
| 387 | + assert_eq!(response.status(), 403); | ||
| 388 | + assert!( | ||
| 389 | + state | ||
| 390 | + .store | ||
| 391 | + .session_by_token(&issued.token) | ||
| 392 | + .await | ||
| 393 | + .unwrap() | ||
| 394 | + .is_some() | ||
| 395 | + ); | ||
| 396 | + } | ||
| 397 | +} | ||
crates/iz-web/src/state.rsmodified+4 -1
| @@ -6,9 +6,10 @@ use iz_core::config::Config; | |||
| 6 | use iz_core::store::Store; | 6 | use iz_core::store::Store; |
| 7 | 7 | ||
| 8 | use crate::live::LiveHub; | 8 | use crate::live::LiveHub; |
| 9 | +use crate::oidc::OidcClient; | ||
| 9 | 10 | ||
| 10 | /// Everything a request handler reaches through the app context. Every field is cheap to clone. | 11 | /// Everything a request handler reaches through the app context. Every field is cheap to clone. |
| 11 | -#[allow(dead_code)] // The key and the hub are read by the sign-in and live pages that come next. | 12 | +#[allow(dead_code)] // The hub is read by the live pages that come next. |
| 12 | #[derive(Clone)] | 13 | #[derive(Clone)] |
| 13 | pub struct AppState { | 14 | pub struct AppState { |
| 14 | /// The configuration the process booted with. | 15 | /// The configuration the process booted with. |
| @@ -19,4 +20,6 @@ pub struct AppState { | |||
| 19 | pub key: Arc<[u8; 32]>, | 20 | pub key: Arc<[u8; 32]>, |
| 20 | /// The change counters of the live pages. | 21 | /// The change counters of the live pages. |
| 21 | pub live: Arc<LiveHub>, | 22 | pub live: Arc<LiveHub>, |
| 23 | + /// The `im` client. `None` when no `[oidc]` section is configured, so sign-in is off. | ||
| 24 | + pub oidc: Option<Arc<OidcClient>>, | ||
| 22 | } | 25 | } |
crates/iz-web/src/views/mod.rsmodified+33 -5
| @@ -10,14 +10,15 @@ use crate::assets::{MAIN_CSS_HREF, NAV_JS_HREF, PAGES_JS_HREF}; | |||
| 10 | use crate::i18n::Lang; | 10 | use crate::i18n::Lang; |
| 11 | use crate::i18n::shell::{K, t}; | 11 | use crate::i18n::shell::{K, t}; |
| 12 | 12 | ||
| 13 | -/// What the shell shows about the signed-in person. Nothing signs a person in yet, so every page | 13 | +/// What the shell shows about the signed-in person: the name in the user menu, the administrator |
| 14 | -/// is built for an anonymous viewer. | 14 | +/// badge, and the CSRF token of the sign-out form in that menu. |
| 15 | -#[allow(dead_code)] // Built by the sign-in code, which comes next. | ||
| 16 | pub struct ViewerInfo { | 15 | pub struct ViewerInfo { |
| 17 | - /// The name shown in the topbar. | 16 | + /// The name shown in the user menu. |
| 18 | pub name: String, | 17 | pub name: String, |
| 19 | /// Whether the topbar shows the administrator badge. | 18 | /// Whether the topbar shows the administrator badge. |
| 20 | pub is_admin: bool, | 19 | pub is_admin: bool, |
| 20 | + /// The session's CSRF token. The sign-out form carries it. | ||
| 21 | + pub csrf: String, | ||
| 21 | } | 22 | } |
| 22 | 23 | ||
| 23 | /// The HTML document around a page. `title` is the page's own title; the document title adds the | 24 | /// The HTML document around a page. `title` is the page's own title; the document title adds the |
| @@ -51,7 +52,13 @@ pub async fn shell( | |||
| 51 | <nav class="switcher" aria-label=(t(lang, K::Services))></nav> | 52 | <nav class="switcher" aria-label=(t(lang, K::Services))></nav> |
| 52 | <div class="topbar-end"> | 53 | <div class="topbar-end"> |
| 53 | if let Some(viewer) = viewer { | 54 | if let Some(viewer) = viewer { |
| 54 | - <span>(viewer.name.as_str())</span> | 55 | + <details class="user-menu"> |
| 56 | + <summary>(viewer.name.as_str())</summary> | ||
| 57 | + <form method="post" action="/auth/logout" class="user-menu-form"> | ||
| 58 | + <input type="hidden" name="csrf" value=(viewer.csrf.as_str())> | ||
| 59 | + <button type="submit" class="button">(t(lang, K::SignOut))</button> | ||
| 60 | + </form> | ||
| 61 | + </details> | ||
| 55 | if viewer.is_admin { | 62 | if viewer.is_admin { |
| 56 | <span class="badge accent">(t(lang, K::Admin))</span> | 63 | <span class="badge accent">(t(lang, K::Admin))</span> |
| 57 | } | 64 | } |
| @@ -64,6 +71,27 @@ pub async fn shell( | |||
| 64 | }) | 71 | }) |
| 65 | } | 72 | } |
| 66 | 73 | ||
| 74 | +/// The body of a message page: a title, one sentence, an optional detail (escaped, in a code | ||
| 75 | +/// element) and a way back to the start. | ||
| 76 | +#[component] | ||
| 77 | +pub async fn message_page( | ||
| 78 | + lang: Lang, | ||
| 79 | + title: K, | ||
| 80 | + body: K, | ||
| 81 | + detail: Option<String>, | ||
| 82 | +) -> Result<impl View> { | ||
| 83 | + Ok(view! { | ||
| 84 | + <section class="card narrow"> | ||
| 85 | + <h1>(t(lang, title))</h1> | ||
| 86 | + <p>(t(lang, body))</p> | ||
| 87 | + if let Some(detail) = detail { | ||
| 88 | + <p><code>(detail.as_str())</code></p> | ||
| 89 | + } | ||
| 90 | + <a class="button primary" href="/">(t(lang, K::BackHome))</a> | ||
| 91 | + </section> | ||
| 92 | + }) | ||
| 93 | +} | ||
| 94 | + | ||
| 67 | /// An error message for a failed action. Forms show it above their fields. | 95 | /// An error message for a failed action. Forms show it above their fields. |
| 68 | #[allow(dead_code)] // The first form that can fail a check uses it. | 96 | #[allow(dead_code)] // The first form that can fail a check uses it. |
| 69 | #[component] | 97 | #[component] |
style/_layout.scssmodified+22 -0
| @@ -67,6 +67,28 @@ | |||
| 67 | font-size: var(--text-sm); | 67 | font-size: var(--text-sm); |
| 68 | } | 68 | } |
| 69 | 69 | ||
| 70 | +// The user menu: the name opens a small panel with the sign-out button. The panel is plain HTML | ||
| 71 | +// (a details element), so it works without script. | ||
| 72 | +.user-menu { | ||
| 73 | + position: relative; | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +.user-menu > summary { | ||
| 77 | + cursor: pointer; | ||
| 78 | + list-style: none; | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +.user-menu-form { | ||
| 82 | + position: absolute; | ||
| 83 | + right: 0; | ||
| 84 | + top: 100%; | ||
| 85 | + margin-top: var(--space-2); | ||
| 86 | + padding: var(--space-3); | ||
| 87 | + background: var(--surface-2); | ||
| 88 | + border-radius: var(--radius, 8px); | ||
| 89 | + z-index: 10; | ||
| 90 | +} | ||
| 91 | + | ||
| 70 | .page { | 92 | .page { |
| 71 | width: 100%; | 93 | width: 100%; |
| 72 | max-width: var(--content-width); | 94 | max-width: var(--content-width); |