Sign in through im: OIDC client, local sessions, back-channel logout, directory mirror, avatar proxy
Browse files at this commitbf41400348c723965b1c6a6880c038f1cdcbc647Parent: 490130e- feat
- sign in through im: OIDC client, local sessions, back-channel logout, directory mirror, avatar proxy
22 changed files +2954 -29
- Cargo.lock +354 -1
- Cargo.toml +3 -0
- config/in.example.toml +4 -2
- crates/in-core/migrations/0002_session_id_token.sql +5 -0
- crates/in-core/src/config.rs +5 -0
- crates/in-core/src/quota.rs +4 -0
- crates/in-core/src/store/migrate.rs +7 -1
- crates/in-core/src/store/sessions.rs +12 -2
- crates/in-web/Cargo.toml +14 -3
- crates/in-web/src/auth.rs +229 -0
- crates/in-web/src/boot.rs +21 -3
- crates/in-web/src/directory.rs +418 -0
- crates/in-web/src/i18n/shell.rs +58 -2
- crates/in-web/src/main.rs +3 -0
- crates/in-web/src/oidc.rs +905 -0
- crates/in-web/src/pages/backchannel.rs +223 -0
- crates/in-web/src/pages/home.rs +34 -8
- crates/in-web/src/pages/mod.rs +4 -1
- crates/in-web/src/pages/photo.rs +248 -0
- crates/in-web/src/pages/sign_in.rs +385 -0
- crates/in-web/src/state.rs +5 -1
- crates/in-web/src/views/mod.rs +13 -5
Cargo.lockmodified+354 -1
| @@ -270,6 +270,12 @@ dependencies = [ | |||
| 270 | "pkg-config", | 270 | "pkg-config", |
| 271 | ] | 271 | ] |
| 272 | 272 | ||
| 273 | +[[package]] | ||
| 274 | +name = "base16ct" | ||
| 275 | +version = "0.2.0" | ||
| 276 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 277 | +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" | ||
| 278 | + | ||
| 273 | [[package]] | 279 | [[package]] |
| 274 | name = "base64" | 280 | name = "base64" |
| 275 | version = "0.22.1" | 281 | version = "0.22.1" |
| @@ -636,6 +642,12 @@ dependencies = [ | |||
| 636 | "crossbeam-utils", | 642 | "crossbeam-utils", |
| 637 | ] | 643 | ] |
| 638 | 644 | ||
| 645 | +[[package]] | ||
| 646 | +name = "const-oid" | ||
| 647 | +version = "0.9.6" | ||
| 648 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 649 | +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" | ||
| 650 | + | ||
| 639 | [[package]] | 651 | [[package]] |
| 640 | name = "const-oid" | 652 | name = "const-oid" |
| 641 | version = "0.10.2" | 653 | version = "0.10.2" |
| @@ -768,6 +780,18 @@ version = "0.2.4" | |||
| 768 | source = "registry+https://github.com/rust-lang/crates.io-index" | 780 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 769 | checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" | 781 | checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" |
| 770 | 782 | ||
| 783 | +[[package]] | ||
| 784 | +name = "crypto-bigint" | ||
| 785 | +version = "0.5.5" | ||
| 786 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 787 | +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" | ||
| 788 | +dependencies = [ | ||
| 789 | + "generic-array", | ||
| 790 | + "rand_core 0.6.4", | ||
| 791 | + "subtle", | ||
| 792 | + "zeroize", | ||
| 793 | +] | ||
| 794 | + | ||
| 771 | [[package]] | 795 | [[package]] |
| 772 | name = "crypto-common" | 796 | name = "crypto-common" |
| 773 | version = "0.1.7" | 797 | version = "0.1.7" |
| @@ -808,6 +832,33 @@ dependencies = [ | |||
| 808 | "cmov", | 832 | "cmov", |
| 809 | ] | 833 | ] |
| 810 | 834 | ||
| 835 | +[[package]] | ||
| 836 | +name = "curve25519-dalek" | ||
| 837 | +version = "4.1.3" | ||
| 838 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 839 | +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" | ||
| 840 | +dependencies = [ | ||
| 841 | + "cfg-if", | ||
| 842 | + "cpufeatures 0.2.17", | ||
| 843 | + "curve25519-dalek-derive", | ||
| 844 | + "digest 0.10.7", | ||
| 845 | + "fiat-crypto", | ||
| 846 | + "rustc_version", | ||
| 847 | + "subtle", | ||
| 848 | + "zeroize", | ||
| 849 | +] | ||
| 850 | + | ||
| 851 | +[[package]] | ||
| 852 | +name = "curve25519-dalek-derive" | ||
| 853 | +version = "0.1.1" | ||
| 854 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 855 | +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" | ||
| 856 | +dependencies = [ | ||
| 857 | + "proc-macro2", | ||
| 858 | + "quote", | ||
| 859 | + "syn 2.0.119", | ||
| 860 | +] | ||
| 861 | + | ||
| 811 | [[package]] | 862 | [[package]] |
| 812 | name = "darling" | 863 | name = "darling" |
| 813 | version = "0.24.1" | 864 | version = "0.24.1" |
| @@ -854,6 +905,17 @@ version = "0.2.0" | |||
| 854 | source = "registry+https://github.com/rust-lang/crates.io-index" | 905 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 855 | checksum = "c286de4e81ea2590afc24d754e0f83810c566f50a1388fa75ebd57928c0d9745" | 906 | checksum = "c286de4e81ea2590afc24d754e0f83810c566f50a1388fa75ebd57928c0d9745" |
| 856 | 907 | ||
| 908 | +[[package]] | ||
| 909 | +name = "der" | ||
| 910 | +version = "0.7.10" | ||
| 911 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 912 | +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" | ||
| 913 | +dependencies = [ | ||
| 914 | + "const-oid 0.9.6", | ||
| 915 | + "pem-rfc7468", | ||
| 916 | + "zeroize", | ||
| 917 | +] | ||
| 918 | + | ||
| 857 | [[package]] | 919 | [[package]] |
| 858 | name = "deranged" | 920 | name = "deranged" |
| 859 | version = "0.5.9" | 921 | version = "0.5.9" |
| @@ -870,6 +932,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" | |||
| 870 | checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" | 932 | checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" |
| 871 | dependencies = [ | 933 | dependencies = [ |
| 872 | "block-buffer 0.10.4", | 934 | "block-buffer 0.10.4", |
| 935 | + "const-oid 0.9.6", | ||
| 873 | "crypto-common 0.1.7", | 936 | "crypto-common 0.1.7", |
| 874 | "subtle", | 937 | "subtle", |
| 875 | ] | 938 | ] |
| @@ -881,7 +944,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" | |||
| 881 | checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" | 944 | checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" |
| 882 | dependencies = [ | 945 | dependencies = [ |
| 883 | "block-buffer 0.12.1", | 946 | "block-buffer 0.12.1", |
| 884 | - "const-oid", | 947 | + "const-oid 0.10.2", |
| 885 | "crypto-common 0.2.2", | 948 | "crypto-common 0.2.2", |
| 886 | "ctutils", | 949 | "ctutils", |
| 887 | ] | 950 | ] |
| @@ -909,12 +972,71 @@ version = "1.0.5" | |||
| 909 | source = "registry+https://github.com/rust-lang/crates.io-index" | 972 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 910 | checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" | 973 | checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" |
| 911 | 974 | ||
| 975 | +[[package]] | ||
| 976 | +name = "ecdsa" | ||
| 977 | +version = "0.16.9" | ||
| 978 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 979 | +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" | ||
| 980 | +dependencies = [ | ||
| 981 | + "der", | ||
| 982 | + "digest 0.10.7", | ||
| 983 | + "elliptic-curve", | ||
| 984 | + "rfc6979", | ||
| 985 | + "signature", | ||
| 986 | + "spki", | ||
| 987 | +] | ||
| 988 | + | ||
| 989 | +[[package]] | ||
| 990 | +name = "ed25519" | ||
| 991 | +version = "2.2.3" | ||
| 992 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 993 | +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" | ||
| 994 | +dependencies = [ | ||
| 995 | + "pkcs8", | ||
| 996 | + "signature", | ||
| 997 | +] | ||
| 998 | + | ||
| 999 | +[[package]] | ||
| 1000 | +name = "ed25519-dalek" | ||
| 1001 | +version = "2.2.0" | ||
| 1002 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1003 | +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" | ||
| 1004 | +dependencies = [ | ||
| 1005 | + "curve25519-dalek", | ||
| 1006 | + "ed25519", | ||
| 1007 | + "serde", | ||
| 1008 | + "sha2 0.10.9", | ||
| 1009 | + "subtle", | ||
| 1010 | + "zeroize", | ||
| 1011 | +] | ||
| 1012 | + | ||
| 912 | [[package]] | 1013 | [[package]] |
| 913 | name = "either" | 1014 | name = "either" |
| 914 | version = "1.19.0" | 1015 | version = "1.19.0" |
| 915 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1016 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 916 | checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" | 1017 | checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" |
| 917 | 1018 | ||
| 1019 | +[[package]] | ||
| 1020 | +name = "elliptic-curve" | ||
| 1021 | +version = "0.13.8" | ||
| 1022 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1023 | +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" | ||
| 1024 | +dependencies = [ | ||
| 1025 | + "base16ct", | ||
| 1026 | + "crypto-bigint", | ||
| 1027 | + "digest 0.10.7", | ||
| 1028 | + "ff", | ||
| 1029 | + "generic-array", | ||
| 1030 | + "group", | ||
| 1031 | + "hkdf", | ||
| 1032 | + "pem-rfc7468", | ||
| 1033 | + "pkcs8", | ||
| 1034 | + "rand_core 0.6.4", | ||
| 1035 | + "sec1", | ||
| 1036 | + "subtle", | ||
| 1037 | + "zeroize", | ||
| 1038 | +] | ||
| 1039 | + | ||
| 918 | [[package]] | 1040 | [[package]] |
| 919 | name = "elsa" | 1041 | name = "elsa" |
| 920 | version = "1.11.2" | 1042 | version = "1.11.2" |
| @@ -1030,6 +1152,22 @@ version = "2.5.0" | |||
| 1030 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1152 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1031 | checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" | 1153 | checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" |
| 1032 | 1154 | ||
| 1155 | +[[package]] | ||
| 1156 | +name = "ff" | ||
| 1157 | +version = "0.13.1" | ||
| 1158 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1159 | +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" | ||
| 1160 | +dependencies = [ | ||
| 1161 | + "rand_core 0.6.4", | ||
| 1162 | + "subtle", | ||
| 1163 | +] | ||
| 1164 | + | ||
| 1165 | +[[package]] | ||
| 1166 | +name = "fiat-crypto" | ||
| 1167 | +version = "0.2.9" | ||
| 1168 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1169 | +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" | ||
| 1170 | + | ||
| 1033 | [[package]] | 1171 | [[package]] |
| 1034 | name = "find-msvc-tools" | 1172 | name = "find-msvc-tools" |
| 1035 | version = "0.1.15" | 1173 | version = "0.1.15" |
| @@ -1178,6 +1316,7 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" | |||
| 1178 | dependencies = [ | 1316 | dependencies = [ |
| 1179 | "typenum", | 1317 | "typenum", |
| 1180 | "version_check", | 1318 | "version_check", |
| 1319 | + "zeroize", | ||
| 1181 | ] | 1320 | ] |
| 1182 | 1321 | ||
| 1183 | [[package]] | 1322 | [[package]] |
| @@ -1262,6 +1401,17 @@ dependencies = [ | |||
| 1262 | "rand 0.8.8", | 1401 | "rand 0.8.8", |
| 1263 | ] | 1402 | ] |
| 1264 | 1403 | ||
| 1404 | +[[package]] | ||
| 1405 | +name = "group" | ||
| 1406 | +version = "0.13.0" | ||
| 1407 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1408 | +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" | ||
| 1409 | +dependencies = [ | ||
| 1410 | + "ff", | ||
| 1411 | + "rand_core 0.6.4", | ||
| 1412 | + "subtle", | ||
| 1413 | +] | ||
| 1414 | + | ||
| 1265 | [[package]] | 1415 | [[package]] |
| 1266 | name = "h2" | 1416 | name = "h2" |
| 1267 | version = "0.4.20" | 1417 | version = "0.4.20" |
| @@ -1739,13 +1889,21 @@ dependencies = [ | |||
| 1739 | name = "in-web" | 1889 | name = "in-web" |
| 1740 | version = "0.1.0" | 1890 | version = "0.1.0" |
| 1741 | dependencies = [ | 1891 | dependencies = [ |
| 1892 | + "base64 0.23.1", | ||
| 1893 | + "ed25519-dalek", | ||
| 1742 | "futures-util", | 1894 | "futures-util", |
| 1743 | "grass", | 1895 | "grass", |
| 1744 | "hex", | 1896 | "hex", |
| 1745 | "http", | 1897 | "http", |
| 1746 | "in-core", | 1898 | "in-core", |
| 1899 | + "jsonwebtoken", | ||
| 1900 | + "rand 0.10.3", | ||
| 1901 | + "reqwest", | ||
| 1902 | + "serde", | ||
| 1903 | + "serde_json", | ||
| 1747 | "sha2 0.11.1", | 1904 | "sha2 0.11.1", |
| 1748 | "tempfile", | 1905 | "tempfile", |
| 1906 | + "thiserror", | ||
| 1749 | "tokio", | 1907 | "tokio", |
| 1750 | "topcoat", | 1908 | "topcoat", |
| 1751 | "tracing", | 1909 | "tracing", |
| @@ -1924,6 +2082,28 @@ dependencies = [ | |||
| 1924 | "wasm-bindgen", | 2082 | "wasm-bindgen", |
| 1925 | ] | 2083 | ] |
| 1926 | 2084 | ||
| 2085 | +[[package]] | ||
| 2086 | +name = "jsonwebtoken" | ||
| 2087 | +version = "11.1.0" | ||
| 2088 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2089 | +checksum = "e75fe14a82d81e5f5af639997db37d8b96045938a7ac6ab18cdbe1c7467e05e1" | ||
| 2090 | +dependencies = [ | ||
| 2091 | + "base64 0.22.1", | ||
| 2092 | + "ed25519-dalek", | ||
| 2093 | + "getrandom 0.2.17", | ||
| 2094 | + "hmac 0.12.1", | ||
| 2095 | + "js-sys", | ||
| 2096 | + "p256", | ||
| 2097 | + "p384", | ||
| 2098 | + "rand 0.8.8", | ||
| 2099 | + "rsa", | ||
| 2100 | + "serde", | ||
| 2101 | + "serde_json", | ||
| 2102 | + "sha2 0.10.9", | ||
| 2103 | + "signature", | ||
| 2104 | + "zeroize", | ||
| 2105 | +] | ||
| 2106 | + | ||
| 1927 | [[package]] | 2107 | [[package]] |
| 1928 | name = "lasso" | 2108 | name = "lasso" |
| 1929 | version = "0.7.3" | 2109 | version = "0.7.3" |
| @@ -1938,6 +2118,9 @@ name = "lazy_static" | |||
| 1938 | version = "1.5.1" | 2118 | version = "1.5.1" |
| 1939 | source = "registry+https://github.com/rust-lang/crates.io-index" | 2119 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1940 | checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" | 2120 | checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" |
| 2121 | +dependencies = [ | ||
| 2122 | + "spin 0.9.9", | ||
| 2123 | +] | ||
| 1941 | 2124 | ||
| 1942 | [[package]] | 2125 | [[package]] |
| 1943 | name = "lazycell" | 2126 | name = "lazycell" |
| @@ -2277,6 +2460,22 @@ dependencies = [ | |||
| 2277 | "num-traits", | 2460 | "num-traits", |
| 2278 | ] | 2461 | ] |
| 2279 | 2462 | ||
| 2463 | +[[package]] | ||
| 2464 | +name = "num-bigint-dig" | ||
| 2465 | +version = "0.8.6" | ||
| 2466 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2467 | +checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" | ||
| 2468 | +dependencies = [ | ||
| 2469 | + "lazy_static", | ||
| 2470 | + "libm", | ||
| 2471 | + "num-integer", | ||
| 2472 | + "num-iter", | ||
| 2473 | + "num-traits", | ||
| 2474 | + "rand 0.8.8", | ||
| 2475 | + "smallvec", | ||
| 2476 | + "zeroize", | ||
| 2477 | +] | ||
| 2478 | + | ||
| 2280 | [[package]] | 2479 | [[package]] |
| 2281 | name = "num-conv" | 2480 | name = "num-conv" |
| 2282 | version = "0.2.2" | 2481 | version = "0.2.2" |
| @@ -2292,6 +2491,16 @@ dependencies = [ | |||
| 2292 | "num-traits", | 2491 | "num-traits", |
| 2293 | ] | 2492 | ] |
| 2294 | 2493 | ||
| 2494 | +[[package]] | ||
| 2495 | +name = "num-iter" | ||
| 2496 | +version = "0.1.46" | ||
| 2497 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2498 | +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" | ||
| 2499 | +dependencies = [ | ||
| 2500 | + "num-integer", | ||
| 2501 | + "num-traits", | ||
| 2502 | +] | ||
| 2503 | + | ||
| 2295 | [[package]] | 2504 | [[package]] |
| 2296 | name = "num-traits" | 2505 | name = "num-traits" |
| 2297 | version = "0.2.19" | 2506 | version = "0.2.19" |
| @@ -2299,6 +2508,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" | |||
| 2299 | checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" | 2508 | checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" |
| 2300 | dependencies = [ | 2509 | dependencies = [ |
| 2301 | "autocfg", | 2510 | "autocfg", |
| 2511 | + "libm", | ||
| 2302 | ] | 2512 | ] |
| 2303 | 2513 | ||
| 2304 | [[package]] | 2514 | [[package]] |
| @@ -2397,6 +2607,30 @@ version = "3.5.0" | |||
| 2397 | source = "registry+https://github.com/rust-lang/crates.io-index" | 2607 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2398 | checksum = "c1b04fb49957986fdce4d6ee7a65027d55d4b6d2265e5848bbb507b58ccfdb6f" | 2608 | checksum = "c1b04fb49957986fdce4d6ee7a65027d55d4b6d2265e5848bbb507b58ccfdb6f" |
| 2399 | 2609 | ||
| 2610 | +[[package]] | ||
| 2611 | +name = "p256" | ||
| 2612 | +version = "0.13.2" | ||
| 2613 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2614 | +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" | ||
| 2615 | +dependencies = [ | ||
| 2616 | + "ecdsa", | ||
| 2617 | + "elliptic-curve", | ||
| 2618 | + "primeorder", | ||
| 2619 | + "sha2 0.10.9", | ||
| 2620 | +] | ||
| 2621 | + | ||
| 2622 | +[[package]] | ||
| 2623 | +name = "p384" | ||
| 2624 | +version = "0.13.1" | ||
| 2625 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2626 | +checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6" | ||
| 2627 | +dependencies = [ | ||
| 2628 | + "ecdsa", | ||
| 2629 | + "elliptic-curve", | ||
| 2630 | + "primeorder", | ||
| 2631 | + "sha2 0.10.9", | ||
| 2632 | +] | ||
| 2633 | + | ||
| 2400 | [[package]] | 2634 | [[package]] |
| 2401 | name = "pack1" | 2635 | name = "pack1" |
| 2402 | version = "1.1.0" | 2636 | version = "1.1.0" |
| @@ -2445,6 +2679,15 @@ version = "0.2.3" | |||
| 2445 | source = "registry+https://github.com/rust-lang/crates.io-index" | 2679 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2446 | checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" | 2680 | checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" |
| 2447 | 2681 | ||
| 2682 | +[[package]] | ||
| 2683 | +name = "pem-rfc7468" | ||
| 2684 | +version = "0.7.0" | ||
| 2685 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2686 | +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" | ||
| 2687 | +dependencies = [ | ||
| 2688 | + "base64ct", | ||
| 2689 | +] | ||
| 2690 | + | ||
| 2448 | [[package]] | 2691 | [[package]] |
| 2449 | name = "percent-encoding" | 2692 | name = "percent-encoding" |
| 2450 | version = "2.3.2" | 2693 | version = "2.3.2" |
| @@ -2510,6 +2753,27 @@ version = "0.2.17" | |||
| 2510 | source = "registry+https://github.com/rust-lang/crates.io-index" | 2753 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2511 | checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" | 2754 | checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" |
| 2512 | 2755 | ||
| 2756 | +[[package]] | ||
| 2757 | +name = "pkcs1" | ||
| 2758 | +version = "0.7.5" | ||
| 2759 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2760 | +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" | ||
| 2761 | +dependencies = [ | ||
| 2762 | + "der", | ||
| 2763 | + "pkcs8", | ||
| 2764 | + "spki", | ||
| 2765 | +] | ||
| 2766 | + | ||
| 2767 | +[[package]] | ||
| 2768 | +name = "pkcs8" | ||
| 2769 | +version = "0.10.2" | ||
| 2770 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2771 | +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" | ||
| 2772 | +dependencies = [ | ||
| 2773 | + "der", | ||
| 2774 | + "spki", | ||
| 2775 | +] | ||
| 2776 | + | ||
| 2513 | [[package]] | 2777 | [[package]] |
| 2514 | name = "pkg-config" | 2778 | name = "pkg-config" |
| 2515 | version = "0.3.34" | 2779 | version = "0.3.34" |
| @@ -2598,6 +2862,15 @@ dependencies = [ | |||
| 2598 | "syn 3.0.9", | 2862 | "syn 3.0.9", |
| 2599 | ] | 2863 | ] |
| 2600 | 2864 | ||
| 2865 | +[[package]] | ||
| 2866 | +name = "primeorder" | ||
| 2867 | +version = "0.13.6" | ||
| 2868 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2869 | +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" | ||
| 2870 | +dependencies = [ | ||
| 2871 | + "elliptic-curve", | ||
| 2872 | +] | ||
| 2873 | + | ||
| 2601 | [[package]] | 2874 | [[package]] |
| 2602 | name = "proc-macro-crate" | 2875 | name = "proc-macro-crate" |
| 2603 | version = "3.5.0" | 2876 | version = "3.5.0" |
| @@ -2945,6 +3218,8 @@ dependencies = [ | |||
| 2945 | "rustls", | 3218 | "rustls", |
| 2946 | "rustls-pki-types", | 3219 | "rustls-pki-types", |
| 2947 | "rustls-platform-verifier", | 3220 | "rustls-platform-verifier", |
| 3221 | + "serde", | ||
| 3222 | + "serde_urlencoded", | ||
| 2948 | "sync_wrapper", | 3223 | "sync_wrapper", |
| 2949 | "tokio", | 3224 | "tokio", |
| 2950 | "tokio-rustls", | 3225 | "tokio-rustls", |
| @@ -2959,6 +3234,16 @@ dependencies = [ | |||
| 2959 | "web-sys", | 3234 | "web-sys", |
| 2960 | ] | 3235 | ] |
| 2961 | 3236 | ||
| 3237 | +[[package]] | ||
| 3238 | +name = "rfc6979" | ||
| 3239 | +version = "0.4.0" | ||
| 3240 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3241 | +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" | ||
| 3242 | +dependencies = [ | ||
| 3243 | + "hmac 0.12.1", | ||
| 3244 | + "subtle", | ||
| 3245 | +] | ||
| 3246 | + | ||
| 2962 | [[package]] | 3247 | [[package]] |
| 2963 | name = "ring" | 3248 | name = "ring" |
| 2964 | version = "0.17.14" | 3249 | version = "0.17.14" |
| @@ -2983,6 +3268,26 @@ dependencies = [ | |||
| 2983 | "byteorder", | 3268 | "byteorder", |
| 2984 | ] | 3269 | ] |
| 2985 | 3270 | ||
| 3271 | +[[package]] | ||
| 3272 | +name = "rsa" | ||
| 3273 | +version = "0.9.10" | ||
| 3274 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3275 | +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" | ||
| 3276 | +dependencies = [ | ||
| 3277 | + "const-oid 0.9.6", | ||
| 3278 | + "digest 0.10.7", | ||
| 3279 | + "num-bigint-dig", | ||
| 3280 | + "num-integer", | ||
| 3281 | + "num-traits", | ||
| 3282 | + "pkcs1", | ||
| 3283 | + "pkcs8", | ||
| 3284 | + "rand_core 0.6.4", | ||
| 3285 | + "signature", | ||
| 3286 | + "spki", | ||
| 3287 | + "subtle", | ||
| 3288 | + "zeroize", | ||
| 3289 | +] | ||
| 3290 | + | ||
| 2986 | [[package]] | 3291 | [[package]] |
| 2987 | name = "rust-stemmers" | 3292 | name = "rust-stemmers" |
| 2988 | version = "1.2.0" | 3293 | version = "1.2.0" |
| @@ -3167,6 +3472,20 @@ version = "1.2.0" | |||
| 3167 | source = "registry+https://github.com/rust-lang/crates.io-index" | 3472 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 3168 | checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" | 3473 | checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" |
| 3169 | 3474 | ||
| 3475 | +[[package]] | ||
| 3476 | +name = "sec1" | ||
| 3477 | +version = "0.7.3" | ||
| 3478 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3479 | +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" | ||
| 3480 | +dependencies = [ | ||
| 3481 | + "base16ct", | ||
| 3482 | + "der", | ||
| 3483 | + "generic-array", | ||
| 3484 | + "pkcs8", | ||
| 3485 | + "subtle", | ||
| 3486 | + "zeroize", | ||
| 3487 | +] | ||
| 3488 | + | ||
| 3170 | [[package]] | 3489 | [[package]] |
| 3171 | name = "security-framework" | 3490 | name = "security-framework" |
| 3172 | version = "3.7.0" | 3491 | version = "3.7.0" |
| @@ -3361,6 +3680,16 @@ dependencies = [ | |||
| 3361 | "libc", | 3680 | "libc", |
| 3362 | ] | 3681 | ] |
| 3363 | 3682 | ||
| 3683 | +[[package]] | ||
| 3684 | +name = "signature" | ||
| 3685 | +version = "2.2.0" | ||
| 3686 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3687 | +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" | ||
| 3688 | +dependencies = [ | ||
| 3689 | + "digest 0.10.7", | ||
| 3690 | + "rand_core 0.6.4", | ||
| 3691 | +] | ||
| 3692 | + | ||
| 3364 | [[package]] | 3693 | [[package]] |
| 3365 | name = "simd_cesu8" | 3694 | name = "simd_cesu8" |
| 3366 | version = "1.2.0" | 3695 | version = "1.2.0" |
| @@ -3441,6 +3770,16 @@ version = "0.10.1" | |||
| 3441 | source = "registry+https://github.com/rust-lang/crates.io-index" | 3770 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 3442 | checksum = "023a211cb3138dbc438680b32560ad89f699977624c9f8dbb95a47d5b4c07dd3" | 3771 | checksum = "023a211cb3138dbc438680b32560ad89f699977624c9f8dbb95a47d5b4c07dd3" |
| 3443 | 3772 | ||
| 3773 | +[[package]] | ||
| 3774 | +name = "spki" | ||
| 3775 | +version = "0.7.3" | ||
| 3776 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3777 | +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" | ||
| 3778 | +dependencies = [ | ||
| 3779 | + "base64ct", | ||
| 3780 | + "der", | ||
| 3781 | +] | ||
| 3782 | + | ||
| 3444 | [[package]] | 3783 | [[package]] |
| 3445 | name = "stable_deref_trait" | 3784 | name = "stable_deref_trait" |
| 3446 | version = "1.2.1" | 3785 | version = "1.2.1" |
| @@ -5147,6 +5486,20 @@ name = "zeroize" | |||
| 5147 | version = "1.9.1" | 5486 | version = "1.9.1" |
| 5148 | source = "registry+https://github.com/rust-lang/crates.io-index" | 5487 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 5149 | checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" | 5488 | checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" |
| 5489 | +dependencies = [ | ||
| 5490 | + "zeroize_derive", | ||
| 5491 | +] | ||
| 5492 | + | ||
| 5493 | +[[package]] | ||
| 5494 | +name = "zeroize_derive" | ||
| 5495 | +version = "1.5.0" | ||
| 5496 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 5497 | +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" | ||
| 5498 | +dependencies = [ | ||
| 5499 | + "proc-macro2", | ||
| 5500 | + "quote", | ||
| 5501 | + "syn 2.0.119", | ||
| 5502 | +] | ||
| 5150 | 5503 | ||
| 5151 | [[package]] | 5504 | [[package]] |
| 5152 | name = "zerotrie" | 5505 | name = "zerotrie" |
Cargo.tomlmodified+3 -0
| @@ -45,6 +45,7 @@ async-trait = "0.1.92" | |||
| 45 | base64 = "0.23.1" | 45 | base64 = "0.23.1" |
| 46 | bytes = "1.12.1" | 46 | bytes = "1.12.1" |
| 47 | chacha20poly1305 = "0.11.0" | 47 | chacha20poly1305 = "0.11.0" |
| 48 | +ed25519-dalek = "2.1.1" | ||
| 48 | futures-util = "0.3.34" | 49 | futures-util = "0.3.34" |
| 49 | grass = "0.13.4" | 50 | grass = "0.13.4" |
| 50 | hex = "0.4.3" | 51 | hex = "0.4.3" |
| @@ -52,8 +53,10 @@ hmac = "0.13.0" | |||
| 52 | http = "1.5.0" | 53 | http = "1.5.0" |
| 53 | in-core = { path = "crates/in-core" } | 54 | in-core = { path = "crates/in-core" } |
| 54 | ipnet = "2.12.2" | 55 | ipnet = "2.12.2" |
| 56 | +jsonwebtoken = { version = "11.1.0", default-features = false, features = ["rust_crypto"] } | ||
| 55 | object_store = { version = "0.14.2", features = ["aws"] } | 57 | object_store = { version = "0.14.2", features = ["aws"] } |
| 56 | rand = "0.10.3" | 58 | rand = "0.10.3" |
| 59 | +reqwest = { version = "0.13.5", default-features = false, features = ["form", "rustls", "stream"] } | ||
| 57 | serde = "1.0.229" | 60 | serde = "1.0.229" |
| 58 | serde_json = "1.0.154" | 61 | serde_json = "1.0.154" |
| 59 | sha2 = "0.11.1" | 62 | sha2 = "0.11.1" |
config/in.example.tomlmodified+4 -2
| @@ -13,10 +13,12 @@ base_url = "http://127.0.0.1:7655" | |||
| 13 | # Proxies whose X-Forwarded-For header is believed for client addresses. CIDR ranges or bare addresses. | 13 | # Proxies whose X-Forwarded-For header is believed for client addresses. CIDR ranges or bare addresses. |
| 14 | trusted_proxies = [] | 14 | trusted_proxies = [] |
| 15 | 15 | ||
| 16 | -# Sign-in through im. Placeholder for development: point issuer at the im instance you run. | 16 | +# Sign-in through im (OpenID Connect). Point issuer at the im instance you run (its origin, no |
| 17 | +# trailing slash). The client secret is read from client_secret_file at boot; it is never in this file. | ||
| 17 | [oidc] | 18 | [oidc] |
| 18 | -issuer = "http://127.0.0.1:7600" | 19 | +issuer = "http://127.0.0.1:7650" |
| 19 | client_id = "in" | 20 | client_id = "in" |
| 21 | +client_secret_file = "data/oidc_client_secret" | ||
| 20 | 22 | ||
| 21 | [storage] | 23 | [storage] |
| 22 | backend = "local" | 24 | backend = "local" |
crates/in-core/migrations/0002_session_id_token.sqladded+5 -0
| @@ -0,0 +1,5 @@ | |||
| 1 | +-- 0002: keeps the sealed ID token of each sign-in session. RP-initiated logout needs it as the | ||
| 2 | +-- `id_token_hint`. It is sealed with the instance key (secret.rs), and it is NULL for sessions made | ||
| 3 | +-- before this migration, which then sign out without a hint. | ||
| 4 | + | ||
| 5 | +ALTER TABLE sessions ADD COLUMN id_token_sealed TEXT; | ||
crates/in-core/src/config.rsmodified+5 -0
| @@ -60,6 +60,8 @@ pub struct Oidc { | |||
| 60 | pub issuer: String, | 60 | pub issuer: String, |
| 61 | /// The OAuth client id registered for `in` in `im`. | 61 | /// The OAuth client id registered for `in` in `im`. |
| 62 | pub client_id: String, | 62 | pub client_id: String, |
| 63 | + /// File holding the client secret, readable only by the service user. Read at boot. | ||
| 64 | + pub client_secret_file: PathBuf, | ||
| 63 | } | 65 | } |
| 64 | 66 | ||
| 65 | /// The `[storage]` table. | 67 | /// The `[storage]` table. |
| @@ -163,6 +165,9 @@ impl Config { | |||
| 163 | "oidc.client_id must be a non-empty plain string", | 165 | "oidc.client_id must be a non-empty plain string", |
| 164 | )); | 166 | )); |
| 165 | } | 167 | } |
| 168 | + if oidc.client_secret_file.as_os_str().is_empty() { | ||
| 169 | + return Err(config_err("oidc.client_secret_file must not be empty")); | ||
| 170 | + } | ||
| 166 | } | 171 | } |
| 167 | self.storage.validate()?; | 172 | self.storage.validate()?; |
| 168 | if let Some(backup) = &self.backup { | 173 | if let Some(backup) = &self.backup { |
crates/in-core/src/quota.rsmodified+4 -0
| @@ -5,6 +5,10 @@ | |||
| 5 | //! those bytes are promised to be written, so a new upload cannot take them. Everything saturates, so | 5 | //! those bytes are promised to be written, so a new upload cannot take them. Everything saturates, so |
| 6 | //! an over-full account has zero headroom instead of a negative one. | 6 | //! an over-full account has zero headroom instead of a negative one. |
| 7 | 7 | ||
| 8 | +/// Quota of a person who has none set yet: 10 GiB. Used when a person first appears, from a sign-in or | ||
| 9 | +/// from the directory. The admin page changes it per person later. | ||
| 10 | +pub const DEFAULT_MEMBER_QUOTA: i64 = 10 * 1024 * 1024 * 1024; | ||
| 11 | + | ||
| 8 | /// Bytes a new upload may still use: the quota less what is stored and what is promised to uploads | 12 | /// Bytes a new upload may still use: the quota less what is stored and what is promised to uploads |
| 9 | /// in progress. Never negative. | 13 | /// in progress. Never negative. |
| 10 | pub fn headroom(quota: i64, used: i64, staged_claims: i64) -> i64 { | 14 | pub fn headroom(quota: i64, used: i64, staged_claims: i64) -> i64 { |
crates/in-core/src/store/migrate.rsmodified+7 -1
| @@ -9,7 +9,13 @@ use crate::store::fetch_all; | |||
| 9 | use crate::time::now_stamp; | 9 | use crate::time::now_stamp; |
| 10 | 10 | ||
| 11 | /// `(version, sql)` in ascending order. Never edit a migration that has been applied; add a new one. | 11 | /// `(version, sql)` in ascending order. Never edit a migration that has been applied; add a new one. |
| 12 | -pub const MIGRATIONS: &[(u32, &str)] = &[(1, include_str!("../../migrations/0001_init.sql"))]; | 12 | +pub const MIGRATIONS: &[(u32, &str)] = &[ |
| 13 | + (1, include_str!("../../migrations/0001_init.sql")), | ||
| 14 | + ( | ||
| 15 | + 2, | ||
| 16 | + include_str!("../../migrations/0002_session_id_token.sql"), | ||
| 17 | + ), | ||
| 18 | +]; | ||
| 13 | 19 | ||
| 14 | fn migration_err(e: turso::Error) -> Error { | 20 | fn migration_err(e: turso::Error) -> Error { |
| 15 | Error::Migration(e.to_string()) | 21 | Error::Migration(e.to_string()) |
crates/in-core/src/store/sessions.rsmodified+12 -2
| @@ -10,7 +10,7 @@ use crate::time::now_stamp; | |||
| 10 | 10 | ||
| 11 | /// Column list for [`map_session`]. Keep the two in step. | 11 | /// Column list for [`map_session`]. Keep the two in step. |
| 12 | pub const SESSION_COLS: &str = "id, sub, token_hash, csrf_token, im_sid, created_at, expires_at, \ | 12 | pub const SESSION_COLS: &str = "id, sub, token_hash, csrf_token, im_sid, created_at, expires_at, \ |
| 13 | - last_seen_at, ip, user_agent"; | 13 | + last_seen_at, ip, user_agent, id_token_sealed"; |
| 14 | 14 | ||
| 15 | /// One row of the `sessions` table. The token itself is not in here. | 15 | /// One row of the `sessions` table. The token itself is not in here. |
| 16 | #[derive(Debug, Clone, PartialEq, Eq)] | 16 | #[derive(Debug, Clone, PartialEq, Eq)] |
| @@ -35,6 +35,9 @@ pub struct Session { | |||
| 35 | pub ip: Option<String>, | 35 | pub ip: Option<String>, |
| 36 | /// User agent at sign-in, when sent. | 36 | /// User agent at sign-in, when sent. |
| 37 | pub user_agent: Option<String>, | 37 | pub user_agent: Option<String>, |
| 38 | + /// The sealed ID token of the sign-in, used as the `id_token_hint` of logout. Absent for sessions | ||
| 39 | + /// made before migration 2. | ||
| 40 | + pub id_token_sealed: Option<String>, | ||
| 38 | } | 41 | } |
| 39 | 42 | ||
| 40 | /// What a new session needs. The id and timestamps are made by the store. | 43 | /// What a new session needs. The id and timestamps are made by the store. |
| @@ -54,6 +57,8 @@ pub struct NewSession { | |||
| 54 | pub ip: Option<String>, | 57 | pub ip: Option<String>, |
| 55 | /// User agent, when sent. | 58 | /// User agent, when sent. |
| 56 | pub user_agent: Option<String>, | 59 | pub user_agent: Option<String>, |
| 60 | + /// The sealed ID token of the sign-in. Sealed by the caller with the instance key. | ||
| 61 | + pub id_token_sealed: Option<String>, | ||
| 57 | } | 62 | } |
| 58 | 63 | ||
| 59 | /// Maps a row selected with [`SESSION_COLS`]. | 64 | /// Maps a row selected with [`SESSION_COLS`]. |
| @@ -69,6 +74,7 @@ pub fn map_session(row: &turso::Row) -> Result<Session> { | |||
| 69 | last_seen_at: col_text(row, 7)?, | 74 | last_seen_at: col_text(row, 7)?, |
| 70 | ip: col_opt_text(row, 8)?, | 75 | ip: col_opt_text(row, 8)?, |
| 71 | user_agent: col_opt_text(row, 9)?, | 76 | user_agent: col_opt_text(row, 9)?, |
| 77 | + id_token_sealed: col_opt_text(row, 10)?, | ||
| 72 | }) | 78 | }) |
| 73 | } | 79 | } |
| 74 | 80 | ||
| @@ -80,7 +86,8 @@ impl Store { | |||
| 80 | let conn = self.inner.conn.lock().await; | 86 | let conn = self.inner.conn.lock().await; |
| 81 | conn.execute( | 87 | conn.execute( |
| 82 | "INSERT INTO sessions (id, sub, token_hash, csrf_token, im_sid, created_at, expires_at, \ | 88 | "INSERT INTO sessions (id, sub, token_hash, csrf_token, im_sid, created_at, expires_at, \ |
| 83 | - last_seen_at, ip, user_agent) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?6, ?8, ?9)", | 89 | + last_seen_at, ip, user_agent, id_token_sealed) \ |
| 90 | + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?6, ?8, ?9, ?10)", | ||
| 84 | ( | 91 | ( |
| 85 | id.clone(), | 92 | id.clone(), |
| 86 | new.sub.clone(), | 93 | new.sub.clone(), |
| @@ -91,6 +98,7 @@ impl Store { | |||
| 91 | new.expires_at.clone(), | 98 | new.expires_at.clone(), |
| 92 | new.ip.clone(), | 99 | new.ip.clone(), |
| 93 | new.user_agent.clone(), | 100 | new.user_agent.clone(), |
| 101 | + new.id_token_sealed.clone(), | ||
| 94 | ), | 102 | ), |
| 95 | ) | 103 | ) |
| 96 | .await | 104 | .await |
| @@ -106,6 +114,7 @@ impl Store { | |||
| 106 | last_seen_at: now, | 114 | last_seen_at: now, |
| 107 | ip: new.ip, | 115 | ip: new.ip, |
| 108 | user_agent: new.user_agent, | 116 | user_agent: new.user_agent, |
| 117 | + id_token_sealed: new.id_token_sealed, | ||
| 109 | }) | 118 | }) |
| 110 | } | 119 | } |
| 111 | 120 | ||
| @@ -224,6 +233,7 @@ mod tests { | |||
| 224 | expires_at: stamp_after(Duration::from_secs(3600)), | 233 | expires_at: stamp_after(Duration::from_secs(3600)), |
| 225 | ip: None, | 234 | ip: None, |
| 226 | user_agent: None, | 235 | user_agent: None, |
| 236 | + id_token_sealed: None, | ||
| 227 | }) | 237 | }) |
| 228 | .await | 238 | .await |
| 229 | .unwrap(); | 239 | .unwrap(); |
crates/in-web/Cargo.tomlmodified+14 -3
| @@ -11,17 +11,28 @@ name = "in" | |||
| 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 |
| 15 | http.workspace = true | 16 | http.workspace = true |
| 16 | in-core.workspace = true | 17 | in-core.workspace = true |
| 17 | -# `net` and `signal` for the listener and the shutdown signals, `time` for the probe deadlines, and | 18 | +jsonwebtoken.workspace = true |
| 18 | -# `rt-multi-thread` and `macros` for the async entry point and `join!`. | 19 | +rand.workspace = true |
| 19 | -tokio = { workspace = true, features = ["net", "signal", "time", "rt-multi-thread", "macros"] } | 20 | +reqwest.workspace = true |
| 21 | +serde = { workspace = true, features = ["derive"] } | ||
| 22 | +serde_json.workspace = true | ||
| 23 | +sha2.workspace = true | ||
| 24 | +thiserror.workspace = true | ||
| 25 | +# `net` and `signal` for the listener and the shutdown signals, `time` for the probe deadlines and the | ||
| 26 | +# retry delays, `sync` for the token and key caches, `fs` for the photo cache, and `rt-multi-thread` | ||
| 27 | +# and `macros` for the async entry point and `join!`/`select!`. | ||
| 28 | +tokio = { workspace = true, features = ["net", "signal", "time", "sync", "fs", "io-util", "rt-multi-thread", "macros"] } | ||
| 20 | topcoat.workspace = true | 29 | topcoat.workspace = true |
| 21 | tracing.workspace = true | 30 | tracing.workspace = true |
| 22 | tracing-subscriber = { workspace = true, features = ["env-filter"] } | 31 | tracing-subscriber = { workspace = true, features = ["env-filter"] } |
| 23 | 32 | ||
| 24 | [dev-dependencies] | 33 | [dev-dependencies] |
| 34 | +# jsonwebtoken 11 pins ed25519-dalek 2.x; the tests make Ed25519 keys with the same version. | ||
| 35 | +ed25519-dalek = { workspace = true, features = ["pkcs8"] } | ||
| 25 | tempfile.workspace = true | 36 | tempfile.workspace = true |
| 26 | 37 | ||
| 27 | [build-dependencies] | 38 | [build-dependencies] |
crates/in-web/src/auth.rsadded+229 -0
| @@ -0,0 +1,229 @@ | |||
| 1 | +//! Who the viewer of a request is, and the checks that gate pages and forms. | ||
| 2 | +//! | ||
| 3 | +//! A signed-in viewer has a local session: a cookie with a random token, of which the database keeps only | ||
| 4 | +//! the SHA-256 (conventions section 5). Every check reads the store, never `im`, so pages keep working | ||
| 5 | +//! while `im` is down (contracts section 1.1). This module also owns the redirect target check, | ||
| 6 | +//! [`safe_next`], which every return path uses. | ||
| 7 | +//! | ||
| 8 | +//! The helpers here are called by the sign-in pages, the logout form, the photo proxy and the home | ||
| 9 | +//! page. The pages that come next (drive, admin) use [`require_member`], [`require_admin`] and | ||
| 10 | +//! [`require_csrf`] too. | ||
| 11 | + | ||
| 12 | +use std::time::Duration; | ||
| 13 | + | ||
| 14 | +use in_core::store::members::Member; | ||
| 15 | +use in_core::store::sessions::Session; | ||
| 16 | +use in_core::time::stamp_before; | ||
| 17 | +use in_core::token::{constant_time_eq, hash_token}; | ||
| 18 | +use topcoat::Result; | ||
| 19 | +use topcoat::context::{Cx, app_context}; | ||
| 20 | +use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time}; | ||
| 21 | +use topcoat::router::error::{forbidden, not_found, see_other}; | ||
| 22 | +use topcoat::router::request::uri; | ||
| 23 | + | ||
| 24 | +use crate::oidc::percent_encode; | ||
| 25 | +use crate::state::AppState; | ||
| 26 | + | ||
| 27 | +/// Cookie of the local session. The `__Host-` prefix pins it to this origin, to path `/`, and to HTTPS. | ||
| 28 | +pub const SESSION_COOKIE: &str = "__Host-in_session"; | ||
| 29 | + | ||
| 30 | +/// Cookie of a sign-in in progress: the sealed state, nonce, PKCE verifier and `next` target. | ||
| 31 | +pub const FLIGHT_COOKIE: &str = "__Host-in_flight"; | ||
| 32 | + | ||
| 33 | +/// Absolute age of a local session. Contracts section 2.4 caps it at 12 hours. | ||
| 34 | +pub const SESSION_TTL: Duration = Duration::from_secs(12 * 60 * 60); | ||
| 35 | + | ||
| 36 | +/// How long a sign-in may take from the redirect to `im` to the callback. | ||
| 37 | +pub const FLIGHT_TTL: Duration = Duration::from_secs(10 * 60); | ||
| 38 | + | ||
| 39 | +/// Longest `next` target accepted. Longer ones are refused rather than cut. | ||
| 40 | +pub const MAX_NEXT_BYTES: usize = 2048; | ||
| 41 | + | ||
| 42 | +/// How often `last_seen_at` is written. Writing it on every page view would make every read a write. | ||
| 43 | +const TOUCH_EVERY: Duration = Duration::from_secs(5 * 60); | ||
| 44 | + | ||
| 45 | +/// A request's signed-in person: the session that was presented and the member it belongs to. | ||
| 46 | +pub struct Viewer { | ||
| 47 | + /// The session. Its CSRF token checks the forms of this viewer. | ||
| 48 | + pub session: Session, | ||
| 49 | + /// The member the session belongs to. Disabled members never get here. | ||
| 50 | + pub member: Member, | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +/// Returns `candidate` when it is a safe place to redirect to, and `None` otherwise. | ||
| 54 | +/// | ||
| 55 | +/// A safe target is a single absolute path on this origin: it starts with one `/`, the next character is | ||
| 56 | +/// not `/` or `\` (browsers read `/\evil` as `//evil`), it has no control characters (no line breaks to | ||
| 57 | +/// inject headers) and no backslash anywhere, and it is at most [`MAX_NEXT_BYTES`] long. Anything that | ||
| 58 | +/// is not a path, such as a scheme, a percent-encoded slash or an empty string, is refused. | ||
| 59 | +pub fn safe_next(candidate: &str) -> Option<&str> { | ||
| 60 | + if candidate.len() > MAX_NEXT_BYTES { | ||
| 61 | + return None; | ||
| 62 | + } | ||
| 63 | + let mut chars = candidate.chars(); | ||
| 64 | + if chars.next() != Some('/') { | ||
| 65 | + return None; | ||
| 66 | + } | ||
| 67 | + if matches!(chars.next(), Some('/' | '\\')) { | ||
| 68 | + return None; | ||
| 69 | + } | ||
| 70 | + if candidate.chars().any(|c| c.is_control() || c == '\\') { | ||
| 71 | + return None; | ||
| 72 | + } | ||
| 73 | + Some(candidate) | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +/// The redirect target for an optional `next` value: the value when it is safe, else the start page. | ||
| 77 | +pub fn next_or_home(candidate: &str) -> String { | ||
| 78 | + safe_next(candidate).unwrap_or("/").to_owned() | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +/// The sign-in page URL that returns to `next` after sign-in. | ||
| 82 | +pub fn login_path(next: &str) -> String { | ||
| 83 | + format!("/auth/login?next={}", percent_encode(next)) | ||
| 84 | +} | ||
| 85 | + | ||
| 86 | +/// Sets a cookie that only this origin's root path can read, sent over HTTPS, and hidden from scripts. | ||
| 87 | +/// `SameSite=Lax` lets it arrive on the redirect back from `im`. A zero `ttl` deletes the cookie. | ||
| 88 | +pub fn set_cookie(cx: &Cx, name: &'static str, value: String, ttl: Duration) { | ||
| 89 | + let max_age = time::Duration::seconds(i64::try_from(ttl.as_secs()).unwrap_or(i64::MAX)); | ||
| 90 | + let cookie = Cookie::build((name, value)) | ||
| 91 | + .path("/") | ||
| 92 | + .http_only(true) | ||
| 93 | + .secure(true) | ||
| 94 | + .same_site(SameSite::Lax) | ||
| 95 | + .max_age(max_age) | ||
| 96 | + .build(); | ||
| 97 | + cookies(cx).add(cookie); | ||
| 98 | +} | ||
| 99 | + | ||
| 100 | +/// Reads a cookie's value, when it is present. | ||
| 101 | +pub fn cookie_value(cx: &Cx, name: &str) -> Option<String> { | ||
| 102 | + cookies(cx) | ||
| 103 | + .get(name) | ||
| 104 | + .map(|cookie| cookie.value().to_owned()) | ||
| 105 | +} | ||
| 106 | + | ||
| 107 | +/// The local session that the request presents, when it is still live. The store filters out expired | ||
| 108 | +/// sessions and sessions of disabled members. Touches `last_seen_at` at most every [`TOUCH_EVERY`]. | ||
| 109 | +pub async fn current_session(cx: &Cx) -> Result<Option<Session>> { | ||
| 110 | + let Some(token) = cookie_value(cx, SESSION_COOKIE) else { | ||
| 111 | + return Ok(None); | ||
| 112 | + }; | ||
| 113 | + let state = app_context::<AppState>(cx); | ||
| 114 | + let Some(session) = state | ||
| 115 | + .store | ||
| 116 | + .session_by_token_hash(&hash_token(&token)) | ||
| 117 | + .await? | ||
| 118 | + else { | ||
| 119 | + return Ok(None); | ||
| 120 | + }; | ||
| 121 | + if session.last_seen_at < stamp_before(TOUCH_EVERY) { | ||
| 122 | + state.store.touch_session(&session.id).await?; | ||
| 123 | + } | ||
| 124 | + Ok(Some(session)) | ||
| 125 | +} | ||
| 126 | + | ||
| 127 | +/// The signed-in person of the request, if any. | ||
| 128 | +pub async fn current_member(cx: &Cx) -> Result<Option<Viewer>> { | ||
| 129 | + let Some(session) = current_session(cx).await? else { | ||
| 130 | + return Ok(None); | ||
| 131 | + }; | ||
| 132 | + let state = app_context::<AppState>(cx); | ||
| 133 | + let Some(member) = state.store.member(&session.sub).await? else { | ||
| 134 | + return Ok(None); | ||
| 135 | + }; | ||
| 136 | + if member.disabled { | ||
| 137 | + return Ok(None); | ||
| 138 | + } | ||
| 139 | + Ok(Some(Viewer { session, member })) | ||
| 140 | +} | ||
| 141 | + | ||
| 142 | +/// The signed-in person, or a redirect to sign-in that returns to this request's path and query. | ||
| 143 | +pub async fn require_member(cx: &Cx) -> Result<Viewer> { | ||
| 144 | + match current_member(cx).await? { | ||
| 145 | + Some(viewer) => Ok(viewer), | ||
| 146 | + None => { | ||
| 147 | + let here = uri(cx) | ||
| 148 | + .path_and_query() | ||
| 149 | + .map_or("/", |path_and_query| path_and_query.as_str()); | ||
| 150 | + Err(see_other(login_path(here)).into()) | ||
| 151 | + } | ||
| 152 | + } | ||
| 153 | +} | ||
| 154 | + | ||
| 155 | +/// A signed-in administrator. A signed-in member who is not one gets `404`, so the admin pages do not | ||
| 156 | +/// reveal that they exist. | ||
| 157 | +#[allow(dead_code)] // The admin pages that come next are the first callers. | ||
| 158 | +pub async fn require_admin(cx: &Cx) -> Result<Viewer> { | ||
| 159 | + let viewer = require_member(cx).await?; | ||
| 160 | + if !viewer.member.is_admin { | ||
| 161 | + return Err(not_found().into()); | ||
| 162 | + } | ||
| 163 | + Ok(viewer) | ||
| 164 | +} | ||
| 165 | + | ||
| 166 | +/// Whether `submitted` is the CSRF token of `session`. The comparison is constant-time, and an empty | ||
| 167 | +/// stored token never matches, not even an empty submission. | ||
| 168 | +pub fn csrf_matches(session: &Session, submitted: &str) -> bool { | ||
| 169 | + !session.csrf_token.is_empty() | ||
| 170 | + && constant_time_eq(session.csrf_token.as_bytes(), submitted.as_bytes()) | ||
| 171 | +} | ||
| 172 | + | ||
| 173 | +/// The signed-in person, after the CSRF check of a state-changing form. A missing session redirects to | ||
| 174 | +/// sign-in; a wrong or missing token is `403`. Run it before any side effect. | ||
| 175 | +#[allow(dead_code)] // The first state-changing form that is not logout calls it. | ||
| 176 | +pub async fn require_csrf(cx: &Cx, submitted: &str) -> Result<Viewer> { | ||
| 177 | + let viewer = require_member(cx).await?; | ||
| 178 | + if !csrf_matches(&viewer.session, submitted) { | ||
| 179 | + return Err(forbidden().into()); | ||
| 180 | + } | ||
| 181 | + Ok(viewer) | ||
| 182 | +} | ||
| 183 | + | ||
| 184 | +#[cfg(test)] | ||
| 185 | +mod tests { | ||
| 186 | + use super::*; | ||
| 187 | + | ||
| 188 | + #[test] | ||
| 189 | + fn safe_next_accepts_local_paths() { | ||
| 190 | + assert_eq!(safe_next("/"), Some("/")); | ||
| 191 | + assert_eq!( | ||
| 192 | + safe_next("/drive/abc?sort=name"), | ||
| 193 | + Some("/drive/abc?sort=name") | ||
| 194 | + ); | ||
| 195 | + assert_eq!(next_or_home(""), "/"); | ||
| 196 | + assert_eq!(next_or_home("https://evil.example"), "/"); | ||
| 197 | + } | ||
| 198 | + | ||
| 199 | + #[test] | ||
| 200 | + fn safe_next_refuses_attack_strings() { | ||
| 201 | + let attacks = [ | ||
| 202 | + "//evil.example", | ||
| 203 | + "/\\evil.example", | ||
| 204 | + "\\\\evil.example", | ||
| 205 | + "/\\/evil.example", | ||
| 206 | + "https://evil.example", | ||
| 207 | + "http://evil.example", | ||
| 208 | + "javascript:alert(1)", | ||
| 209 | + "%2f%2fevil.example", | ||
| 210 | + "/\nSet-Cookie: x=1", | ||
| 211 | + "/\r\nLocation: https://evil.example", | ||
| 212 | + "/\t/evil.example", | ||
| 213 | + "/a\u{0}b", | ||
| 214 | + " //evil.example", | ||
| 215 | + "drive", | ||
| 216 | + "", | ||
| 217 | + ]; | ||
| 218 | + for attack in attacks { | ||
| 219 | + assert_eq!(safe_next(attack), None, "accepted {attack:?}"); | ||
| 220 | + } | ||
| 221 | + } | ||
| 222 | + | ||
| 223 | + #[test] | ||
| 224 | + fn safe_next_limits_the_length() { | ||
| 225 | + let longest = format!("/{}", "a".repeat(MAX_NEXT_BYTES - 1)); | ||
| 226 | + assert_eq!(safe_next(&longest), Some(longest.as_str())); | ||
| 227 | + assert_eq!(safe_next(&format!("{longest}a")), None); | ||
| 228 | + } | ||
| 229 | +} | ||
crates/in-web/src/boot.rsmodified+21 -3
| @@ -23,7 +23,9 @@ use tokio::sync::watch; | |||
| 23 | use topcoat::cookie::RouterBuilderCookieExt; | 23 | use topcoat::cookie::RouterBuilderCookieExt; |
| 24 | use topcoat::router::{Router, RouterBuilderDiscoverExt, RouterService}; | 24 | use topcoat::router::{Router, RouterBuilderDiscoverExt, RouterService}; |
| 25 | 25 | ||
| 26 | +use crate::directory; | ||
| 26 | use crate::live::LiveHub; | 27 | use crate::live::LiveHub; |
| 28 | +use crate::oidc::OidcClient; | ||
| 27 | use crate::pages::not_found::NotFoundLayer; | 29 | use crate::pages::not_found::NotFoundLayer; |
| 28 | use crate::security::{self, SecurityHeaders}; | 30 | use crate::security::{self, SecurityHeaders}; |
| 29 | use crate::state::AppState; | 31 | use crate::state::AppState; |
| @@ -39,6 +41,11 @@ pub async fn serve(config_path: &Path) -> Result<()> { | |||
| 39 | let config = Config::load(config_path)?; | 41 | let config = Config::load(config_path)?; |
| 40 | let listen = config.listen; | 42 | let listen = config.listen; |
| 41 | let state = open_state(config).await?; | 43 | let state = open_state(config).await?; |
| 44 | + // One stop flag. The signal task sets it; the server and every worker watch it and then drain. | ||
| 45 | + let (stop_tx, stop_rx) = watch::channel(false); | ||
| 46 | + if state.oidc.is_some() { | ||
| 47 | + tokio::spawn(directory::run(state.clone(), stop_rx.clone())); | ||
| 48 | + } | ||
| 42 | 49 | ||
| 43 | let listener = TcpListener::bind(listen).await.map_err(|error| { | 50 | let listener = TcpListener::bind(listen).await.map_err(|error| { |
| 44 | std::io::Error::new(error.kind(), format!("cannot bind {listen}: {error}")) | 51 | std::io::Error::new(error.kind(), format!("cannot bind {listen}: {error}")) |
| @@ -51,8 +58,6 @@ pub async fn serve(config_path: &Path) -> Result<()> { | |||
| 51 | "in starting" | 58 | "in starting" |
| 52 | ); | 59 | ); |
| 53 | 60 | ||
| 54 | - // One stop flag. The signal task sets it; the server watches it and then drains. | ||
| 55 | - let (stop_tx, stop_rx) = watch::channel(false); | ||
| 56 | tokio::spawn(async move { | 61 | tokio::spawn(async move { |
| 57 | shutdown_signal().await; | 62 | shutdown_signal().await; |
| 58 | tracing::info!("shutdown signal received"); | 63 | tracing::info!("shutdown signal received"); |
| @@ -86,12 +91,24 @@ async fn open_state(config: Config) -> Result<AppState> { | |||
| 86 | let key = secret::load_or_create_key(&data_dir.join(KEY_FILE))?; | 91 | let key = secret::load_or_create_key(&data_dir.join(KEY_FILE))?; |
| 87 | let store = Store::open(&config.database).await?; | 92 | let store = Store::open(&config.database).await?; |
| 88 | let blobs = open_blobs(&config, &data_dir)?; | 93 | let blobs = open_blobs(&config, &data_dir)?; |
| 94 | + let oidc = match &config.oidc { | ||
| 95 | + Some(oidc) => { | ||
| 96 | + let client_secret = read_secret(&oidc.client_secret_file)?; | ||
| 97 | + Some(Arc::new(OidcClient::new( | ||
| 98 | + oidc, | ||
| 99 | + &config.base_url, | ||
| 100 | + client_secret, | ||
| 101 | + )?)) | ||
| 102 | + } | ||
| 103 | + None => None, | ||
| 104 | + }; | ||
| 89 | Ok(AppState { | 105 | Ok(AppState { |
| 90 | config: Arc::new(config), | 106 | config: Arc::new(config), |
| 91 | store, | 107 | store, |
| 92 | blobs, | 108 | blobs, |
| 93 | key: Arc::new(key), | 109 | key: Arc::new(key), |
| 94 | live: Arc::new(LiveHub::default()), | 110 | live: Arc::new(LiveHub::default()), |
| 111 | + oidc, | ||
| 95 | }) | 112 | }) |
| 96 | } | 113 | } |
| 97 | 114 | ||
| @@ -191,8 +208,8 @@ pub(crate) use tests::test_state; | |||
| 191 | #[cfg(test)] | 208 | #[cfg(test)] |
| 192 | mod tests { | 209 | mod tests { |
| 193 | use super::*; | 210 | use super::*; |
| 194 | - use std::net::SocketAddr; | ||
| 195 | use http::header::{ACCEPT, CONTENT_SECURITY_POLICY, X_CONTENT_TYPE_OPTIONS}; | 211 | use http::header::{ACCEPT, CONTENT_SECURITY_POLICY, X_CONTENT_TYPE_OPTIONS}; |
| 212 | + use std::net::SocketAddr; | ||
| 196 | use topcoat::router::response::Response; | 213 | use topcoat::router::response::Response; |
| 197 | use topcoat::router::{Body, to_bytes}; | 214 | use topcoat::router::{Body, to_bytes}; |
| 198 | 215 | ||
| @@ -215,6 +232,7 @@ mod tests { | |||
| 215 | blobs, | 232 | blobs, |
| 216 | key: Arc::new(key), | 233 | key: Arc::new(key), |
| 217 | live: Arc::new(LiveHub::default()), | 234 | live: Arc::new(LiveHub::default()), |
| 235 | + oidc: None, | ||
| 218 | }; | 236 | }; |
| 219 | (dir, state) | 237 | (dir, state) |
| 220 | } | 238 | } |
crates/in-web/src/directory.rsadded+418 -0
| @@ -0,0 +1,418 @@ | |||
| 1 | +//! The members mirror: a local copy of the people directory of `im` (contracts section 3), kept current by | ||
| 2 | +//! a stream, so pages show a name or an avatar without calling `im`. | ||
| 3 | +//! | ||
| 4 | +//! The worker does a full fetch when it has no cursor yet, then follows the event stream from the cursor | ||
| 5 | +//! it stored in the `settings` table. A `resync` event means the cursor is too old: the next round does a | ||
| 6 | +//! full fetch. A `deleted` event, a `disabled` member, and a person missing from a full fetch all end the | ||
| 7 | +//! person's local sessions, which is the second of the two paths in contracts section 2.5. | ||
| 8 | +//! | ||
| 9 | +//! When the stream fails, the worker waits with exponential backoff from 1 s to 60 s, each wait a random | ||
| 10 | +//! point between half of the step and the whole step, so a restarted `im` is not hit all at once. A stream that ends | ||
| 11 | +//! on its own (the 50-minute close of contracts section 3.2) is reconnected after one second. | ||
| 12 | + | ||
| 13 | +use std::collections::HashSet; | ||
| 14 | +use std::time::Duration; | ||
| 15 | + | ||
| 16 | +use futures_util::StreamExt; | ||
| 17 | +use http::header::ACCEPT; | ||
| 18 | +use in_core::quota::DEFAULT_MEMBER_QUOTA; | ||
| 19 | +use in_core::store::members::MemberFields; | ||
| 20 | +use in_core::time::now_stamp; | ||
| 21 | +use serde::Deserialize; | ||
| 22 | +use tokio::sync::watch; | ||
| 23 | + | ||
| 24 | +use crate::oidc::{OidcClient, OidcError}; | ||
| 25 | +use crate::state::AppState; | ||
| 26 | + | ||
| 27 | +/// The `settings` key of the directory cursor. | ||
| 28 | +pub const CURSOR_KEY: &str = "directory_cursor"; | ||
| 29 | + | ||
| 30 | +/// The first wait after a failure. | ||
| 31 | +const BACKOFF_FIRST: Duration = Duration::from_secs(1); | ||
| 32 | + | ||
| 33 | +/// The longest wait between attempts after failures. | ||
| 34 | +const BACKOFF_MAX: Duration = Duration::from_secs(60); | ||
| 35 | + | ||
| 36 | +/// The pause after a stream that ended cleanly, before it is reconnected. | ||
| 37 | +const CLEAN_PAUSE: Duration = Duration::from_secs(1); | ||
| 38 | + | ||
| 39 | +/// Why one round of syncing failed. | ||
| 40 | +#[derive(Debug, thiserror::Error)] | ||
| 41 | +enum SyncError { | ||
| 42 | + /// A token could not be had from `im`. | ||
| 43 | + #[error(transparent)] | ||
| 44 | + Oidc(#[from] OidcError), | ||
| 45 | + /// A local write failed. | ||
| 46 | + #[error(transparent)] | ||
| 47 | + Store(#[from] in_core::error::Error), | ||
| 48 | + /// The request to `im` failed on the way. | ||
| 49 | + #[error("the request to im failed: {0}")] | ||
| 50 | + Transport(String), | ||
| 51 | + /// `im` answered with a non-success status. | ||
| 52 | + #[error("im answered {0}")] | ||
| 53 | + Status(reqwest::StatusCode), | ||
| 54 | + /// The full directory could not be read. | ||
| 55 | + #[error("the directory listing is not what the contracts describe")] | ||
| 56 | + Listing, | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +/// One member as the directory sends it (contracts section 3.1). Unknown fields are ignored. | ||
| 60 | +#[derive(Debug, Deserialize)] | ||
| 61 | +struct WireMember { | ||
| 62 | + sub: String, | ||
| 63 | + #[serde(default)] | ||
| 64 | + email: String, | ||
| 65 | + #[serde(default)] | ||
| 66 | + name: String, | ||
| 67 | + #[serde(default)] | ||
| 68 | + admin: bool, | ||
| 69 | + #[serde(default)] | ||
| 70 | + disabled: bool, | ||
| 71 | + #[serde(default)] | ||
| 72 | + locale: String, | ||
| 73 | + #[serde(default)] | ||
| 74 | + zoneinfo: String, | ||
| 75 | + #[serde(default)] | ||
| 76 | + picture_version: i64, | ||
| 77 | + #[serde(default)] | ||
| 78 | + updated_at: String, | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +/// The full listing (contracts section 3.2). | ||
| 82 | +#[derive(Debug, Deserialize)] | ||
| 83 | +struct Listing { | ||
| 84 | + #[serde(default)] | ||
| 85 | + members: Vec<WireMember>, | ||
| 86 | + #[serde(default)] | ||
| 87 | + cursor: String, | ||
| 88 | +} | ||
| 89 | + | ||
| 90 | +/// The data of a `deleted` event. | ||
| 91 | +#[derive(Debug, Deserialize)] | ||
| 92 | +struct DeletedEvent { | ||
| 93 | + sub: String, | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +/// One server-sent event: its id (the cursor), its name and its data. | ||
| 97 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 98 | +struct SseEvent { | ||
| 99 | + id: Option<String>, | ||
| 100 | + event: String, | ||
| 101 | + data: String, | ||
| 102 | +} | ||
| 103 | + | ||
| 104 | +/// Incremental parser of `text/event-stream`. Bytes go in in any split; complete events come out. | ||
| 105 | +#[derive(Debug, Default)] | ||
| 106 | +struct SseParser { | ||
| 107 | + buffer: Vec<u8>, | ||
| 108 | + id: Option<String>, | ||
| 109 | + event: String, | ||
| 110 | + data: Vec<String>, | ||
| 111 | +} | ||
| 112 | + | ||
| 113 | +impl SseParser { | ||
| 114 | + /// Adds bytes and returns the events they complete. A blank line ends an event; lines that start | ||
| 115 | + /// with `:` are comments (keep-alives) and are skipped. | ||
| 116 | + fn push(&mut self, chunk: &[u8]) -> Vec<SseEvent> { | ||
| 117 | + self.buffer.extend_from_slice(chunk); | ||
| 118 | + let mut events = Vec::new(); | ||
| 119 | + while let Some(end) = self.buffer.iter().position(|byte| *byte == b'\n') { | ||
| 120 | + let raw: Vec<u8> = self.buffer.drain(..=end).collect(); | ||
| 121 | + let line = String::from_utf8_lossy(&raw); | ||
| 122 | + let line = line.trim_end_matches(['\n', '\r']); | ||
| 123 | + if line.is_empty() { | ||
| 124 | + if !self.data.is_empty() { | ||
| 125 | + events.push(SseEvent { | ||
| 126 | + id: self.id.take(), | ||
| 127 | + event: if self.event.is_empty() { | ||
| 128 | + "message".to_owned() | ||
| 129 | + } else { | ||
| 130 | + std::mem::take(&mut self.event) | ||
| 131 | + }, | ||
| 132 | + data: self.data.join("\n"), | ||
| 133 | + }); | ||
| 134 | + self.data.clear(); | ||
| 135 | + } | ||
| 136 | + self.event.clear(); | ||
| 137 | + continue; | ||
| 138 | + } | ||
| 139 | + if line.starts_with(':') { | ||
| 140 | + continue; | ||
| 141 | + } | ||
| 142 | + let (field, value) = match line.split_once(':') { | ||
| 143 | + Some((field, value)) => (field, value.strip_prefix(' ').unwrap_or(value)), | ||
| 144 | + None => (line, ""), | ||
| 145 | + }; | ||
| 146 | + match field { | ||
| 147 | + "event" => self.event = value.to_owned(), | ||
| 148 | + "data" => self.data.push(value.to_owned()), | ||
| 149 | + "id" => self.id = Some(value.to_owned()), | ||
| 150 | + _ => {} | ||
| 151 | + } | ||
| 152 | + } | ||
| 153 | + events | ||
| 154 | + } | ||
| 155 | +} | ||
| 156 | + | ||
| 157 | +/// What a stream connection did when it stopped on its own. | ||
| 158 | +enum Ended { | ||
| 159 | + /// The server asked for a full fetch. | ||
| 160 | + Resync, | ||
| 161 | + /// The stream closed (the server's 50-minute close, or a stop). | ||
| 162 | + Closed, | ||
| 163 | +} | ||
| 164 | + | ||
| 165 | +/// Runs the mirror until `stop` is set. Does nothing without an OIDC client. | ||
| 166 | +pub async fn run(state: AppState, mut stop: watch::Receiver<bool>) { | ||
| 167 | + let Some(oidc) = state.oidc.clone() else { | ||
| 168 | + return; | ||
| 169 | + }; | ||
| 170 | + let mut needs_full = matches!(state.store.get_setting(CURSOR_KEY).await, Ok(None) | Err(_)); | ||
| 171 | + let mut backoff = BACKOFF_FIRST; | ||
| 172 | + loop { | ||
| 173 | + if *stop.borrow() { | ||
| 174 | + return; | ||
| 175 | + } | ||
| 176 | + let pause = match round(&state, &oidc, needs_full, &mut stop).await { | ||
| 177 | + Ok(Ended::Resync) => { | ||
| 178 | + needs_full = true; | ||
| 179 | + backoff = BACKOFF_FIRST; | ||
| 180 | + CLEAN_PAUSE | ||
| 181 | + } | ||
| 182 | + Ok(Ended::Closed) => { | ||
| 183 | + backoff = BACKOFF_FIRST; | ||
| 184 | + CLEAN_PAUSE | ||
| 185 | + } | ||
| 186 | + Err(error) => { | ||
| 187 | + tracing::warn!(error = %error, "directory: sync failed, retrying"); | ||
| 188 | + needs_full = true; | ||
| 189 | + let pause = jittered(backoff); | ||
| 190 | + backoff = (backoff * 2).min(BACKOFF_MAX); | ||
| 191 | + pause | ||
| 192 | + } | ||
| 193 | + }; | ||
| 194 | + tokio::select! { | ||
| 195 | + _ = stop.wait_for(|stopped| *stopped) => return, | ||
| 196 | + () = tokio::time::sleep(pause) => {} | ||
| 197 | + } | ||
| 198 | + } | ||
| 199 | +} | ||
| 200 | + | ||
| 201 | +/// One round: a full fetch when one is due, then the stream from the stored cursor. | ||
| 202 | +async fn round( | ||
| 203 | + state: &AppState, | ||
| 204 | + oidc: &OidcClient, | ||
| 205 | + needs_full: bool, | ||
| 206 | + stop: &mut watch::Receiver<bool>, | ||
| 207 | +) -> Result<Ended, SyncError> { | ||
| 208 | + if needs_full { | ||
| 209 | + full_sync(state, oidc).await?; | ||
| 210 | + } | ||
| 211 | + follow(state, oidc, stop).await | ||
| 212 | +} | ||
| 213 | + | ||
| 214 | +/// Fetches the whole directory, applies it, and stores its cursor. People the listing does not name any | ||
| 215 | +/// more are marked deleted, and their sessions end. | ||
| 216 | +async fn full_sync(state: &AppState, oidc: &OidcClient) -> Result<(), SyncError> { | ||
| 217 | + let token = oidc.service_token().await?; | ||
| 218 | + let response = oidc | ||
| 219 | + .http() | ||
| 220 | + .get(format!("{}/api/v1/directory", oidc.issuer())) | ||
| 221 | + .bearer_auth(token) | ||
| 222 | + .header(ACCEPT, "application/json") | ||
| 223 | + .send() | ||
| 224 | + .await | ||
| 225 | + .map_err(|e| SyncError::Transport(e.to_string()))?; | ||
| 226 | + if !response.status().is_success() { | ||
| 227 | + return Err(SyncError::Status(response.status())); | ||
| 228 | + } | ||
| 229 | + let bytes = response | ||
| 230 | + .bytes() | ||
| 231 | + .await | ||
| 232 | + .map_err(|e| SyncError::Transport(e.to_string()))?; | ||
| 233 | + let listing: Listing = serde_json::from_slice(&bytes).map_err(|_| SyncError::Listing)?; | ||
| 234 | + | ||
| 235 | + let mut named = HashSet::new(); | ||
| 236 | + for member in listing.members { | ||
| 237 | + named.insert(member.sub.clone()); | ||
| 238 | + apply_member(state, member).await?; | ||
| 239 | + } | ||
| 240 | + for local in state.store.list_members().await? { | ||
| 241 | + if !named.contains(&local.sub) && !local.disabled { | ||
| 242 | + end_person(state, &local.sub).await?; | ||
| 243 | + } | ||
| 244 | + } | ||
| 245 | + if !listing.cursor.is_empty() { | ||
| 246 | + state.store.set_setting(CURSOR_KEY, &listing.cursor).await?; | ||
| 247 | + } | ||
| 248 | + tracing::info!(members = named.len(), "directory: full sync applied"); | ||
| 249 | + Ok(()) | ||
| 250 | +} | ||
| 251 | + | ||
| 252 | +/// Opens the event stream from the stored cursor and applies events until the stream ends, a `resync` | ||
| 253 | +/// arrives, or `stop` is set. | ||
| 254 | +async fn follow( | ||
| 255 | + state: &AppState, | ||
| 256 | + oidc: &OidcClient, | ||
| 257 | + stop: &mut watch::Receiver<bool>, | ||
| 258 | +) -> Result<Ended, SyncError> { | ||
| 259 | + let cursor = state.store.get_setting(CURSOR_KEY).await?; | ||
| 260 | + let token = oidc.service_token().await?; | ||
| 261 | + let mut request = oidc | ||
| 262 | + .stream_http() | ||
| 263 | + .get(format!("{}/api/v1/directory/stream", oidc.issuer())) | ||
| 264 | + .bearer_auth(token) | ||
| 265 | + .header(ACCEPT, "text/event-stream"); | ||
| 266 | + if let Some(cursor) = &cursor { | ||
| 267 | + request = request.header("Last-Event-ID", cursor.as_str()); | ||
| 268 | + } | ||
| 269 | + let response = request | ||
| 270 | + .send() | ||
| 271 | + .await | ||
| 272 | + .map_err(|e| SyncError::Transport(e.to_string()))?; | ||
| 273 | + if !response.status().is_success() { | ||
| 274 | + return Err(SyncError::Status(response.status())); | ||
| 275 | + } | ||
| 276 | + tracing::info!("directory: stream connected"); | ||
| 277 | + | ||
| 278 | + let mut body = response.bytes_stream(); | ||
| 279 | + let mut parser = SseParser::default(); | ||
| 280 | + loop { | ||
| 281 | + let chunk = tokio::select! { | ||
| 282 | + chunk = body.next() => chunk, | ||
| 283 | + _ = stop.wait_for(|stopped| *stopped) => return Ok(Ended::Closed), | ||
| 284 | + }; | ||
| 285 | + let Some(chunk) = chunk else { | ||
| 286 | + return Ok(Ended::Closed); | ||
| 287 | + }; | ||
| 288 | + let chunk = chunk.map_err(|e| SyncError::Transport(e.to_string()))?; | ||
| 289 | + for event in parser.push(&chunk) { | ||
| 290 | + if let Some(ended) = apply_event(state, event).await? { | ||
| 291 | + return Ok(ended); | ||
| 292 | + } | ||
| 293 | + } | ||
| 294 | + } | ||
| 295 | +} | ||
| 296 | + | ||
| 297 | +/// Applies one stream event. `Some` means the stream must stop: a `resync`. An event that cannot be read | ||
| 298 | +/// is logged and skipped, so one bad event cannot stall the mirror forever. | ||
| 299 | +async fn apply_event(state: &AppState, event: SseEvent) -> Result<Option<Ended>, SyncError> { | ||
| 300 | + match event.event.as_str() { | ||
| 301 | + "member" => match serde_json::from_str::<WireMember>(&event.data) { | ||
| 302 | + Ok(member) => apply_member(state, member).await?, | ||
| 303 | + Err(_) => tracing::warn!("directory: a member event could not be read"), | ||
| 304 | + }, | ||
| 305 | + "deleted" => match serde_json::from_str::<DeletedEvent>(&event.data) { | ||
| 306 | + Ok(deleted) => end_person(state, &deleted.sub).await?, | ||
| 307 | + Err(_) => tracing::warn!("directory: a deleted event could not be read"), | ||
| 308 | + }, | ||
| 309 | + "resync" => return Ok(Some(Ended::Resync)), | ||
| 310 | + _ => {} | ||
| 311 | + } | ||
| 312 | + if let Some(id) = &event.id { | ||
| 313 | + state.store.set_setting(CURSOR_KEY, id).await?; | ||
| 314 | + } | ||
| 315 | + Ok(None) | ||
| 316 | +} | ||
| 317 | + | ||
| 318 | +/// Writes one member from the directory. A disabled member's sessions end as well. | ||
| 319 | +async fn apply_member(state: &AppState, member: WireMember) -> Result<(), SyncError> { | ||
| 320 | + if !valid_sub(&member.sub) { | ||
| 321 | + tracing::warn!("directory: a member has an invalid id and is skipped"); | ||
| 322 | + return Ok(()); | ||
| 323 | + } | ||
| 324 | + let name = if member.name.trim().is_empty() { | ||
| 325 | + member.email.clone() | ||
| 326 | + } else { | ||
| 327 | + member.name | ||
| 328 | + }; | ||
| 329 | + let fields = MemberFields { | ||
| 330 | + sub: member.sub.clone(), | ||
| 331 | + email: member.email, | ||
| 332 | + name, | ||
| 333 | + is_admin: member.admin, | ||
| 334 | + locale: if member.locale.is_empty() { | ||
| 335 | + "en".to_owned() | ||
| 336 | + } else { | ||
| 337 | + member.locale | ||
| 338 | + }, | ||
| 339 | + zoneinfo: if member.zoneinfo.is_empty() { | ||
| 340 | + "UTC".to_owned() | ||
| 341 | + } else { | ||
| 342 | + member.zoneinfo | ||
| 343 | + }, | ||
| 344 | + picture_version: member.picture_version.max(0), | ||
| 345 | + im_updated_at: if member.updated_at.is_empty() { | ||
| 346 | + now_stamp() | ||
| 347 | + } else { | ||
| 348 | + member.updated_at | ||
| 349 | + }, | ||
| 350 | + }; | ||
| 351 | + let stored = state | ||
| 352 | + .store | ||
| 353 | + .apply_directory_member(&fields, member.disabled, DEFAULT_MEMBER_QUOTA) | ||
| 354 | + .await?; | ||
| 355 | + if stored.disabled { | ||
| 356 | + state.store.delete_sessions_by_sub(&stored.sub).await?; | ||
| 357 | + } | ||
| 358 | + Ok(()) | ||
| 359 | +} | ||
| 360 | + | ||
| 361 | +/// Marks a person deleted and ends their sessions. | ||
| 362 | +async fn end_person(state: &AppState, sub: &str) -> Result<(), SyncError> { | ||
| 363 | + if !valid_sub(sub) { | ||
| 364 | + return Ok(()); | ||
| 365 | + } | ||
| 366 | + state.store.mark_member_deleted(sub).await?; | ||
| 367 | + state.store.delete_sessions_by_sub(sub).await?; | ||
| 368 | + Ok(()) | ||
| 369 | +} | ||
| 370 | + | ||
| 371 | +/// Whether `sub` is a plain identifier. Subjects are ULIDs; anything else is not stored. | ||
| 372 | +fn valid_sub(sub: &str) -> bool { | ||
| 373 | + !sub.is_empty() | ||
| 374 | + && sub.len() <= 64 | ||
| 375 | + && sub | ||
| 376 | + .bytes() | ||
| 377 | + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') | ||
| 378 | +} | ||
| 379 | + | ||
| 380 | +/// A random wait between half of `base` and `base`, so that retries spread out. | ||
| 381 | +fn jittered(base: Duration) -> Duration { | ||
| 382 | + let half = base / 2; | ||
| 383 | + let span = u64::try_from(half.as_millis()).unwrap_or(u64::MAX); | ||
| 384 | + let mut bytes = [0u8; 8]; | ||
| 385 | + rand::fill(&mut bytes); | ||
| 386 | + let offset = u64::from_le_bytes(bytes) % span.saturating_add(1); | ||
| 387 | + half + Duration::from_millis(offset) | ||
| 388 | +} | ||
| 389 | + | ||
| 390 | +#[cfg(test)] | ||
| 391 | +mod tests { | ||
| 392 | + use super::*; | ||
| 393 | + | ||
| 394 | + #[test] | ||
| 395 | + fn events_are_parsed_across_chunks_and_comments_are_skipped() { | ||
| 396 | + let mut parser = SseParser::default(); | ||
| 397 | + assert!(parser.push(b": keep-alive\nid: 7\nevent: mem").is_empty()); | ||
| 398 | + let events = parser.push(b"ber\ndata: {\"sub\":\"a\"}\n\n"); | ||
| 399 | + assert_eq!( | ||
| 400 | + events, | ||
| 401 | + vec![SseEvent { | ||
| 402 | + id: Some("7".into()), | ||
| 403 | + event: "member".into(), | ||
| 404 | + data: "{\"sub\":\"a\"}".into(), | ||
| 405 | + }] | ||
| 406 | + ); | ||
| 407 | + let events = parser.push(b"event: resync\ndata: {}\r\n\r\n"); | ||
| 408 | + assert_eq!(events[0].event, "resync"); | ||
| 409 | + } | ||
| 410 | + | ||
| 411 | + #[test] | ||
| 412 | + fn jitter_stays_in_the_upper_half_of_the_step() { | ||
| 413 | + for _ in 0..50 { | ||
| 414 | + let wait = jittered(Duration::from_secs(8)); | ||
| 415 | + assert!(wait >= Duration::from_secs(4) && wait <= Duration::from_secs(8)); | ||
| 416 | + } | ||
| 417 | + } | ||
| 418 | +} | ||
crates/in-web/src/i18n/shell.rsmodified+58 -2
| @@ -24,6 +24,32 @@ pub enum K { | |||
| 24 | SignedOutTitle, | 24 | SignedOutTitle, |
| 25 | /// The sentence under the signed-out heading on the start page. | 25 | /// The sentence under the signed-out heading on the start page. |
| 26 | SignedOutBody, | 26 | SignedOutBody, |
| 27 | + /// The button that starts sign-in. | ||
| 28 | + SignIn, | ||
| 29 | + /// The placeholder under the greeting until the drive exists. | ||
| 30 | + DriveComesNext, | ||
| 31 | + /// The button in the user menu that ends the session. | ||
| 32 | + SignOut, | ||
| 33 | + /// Heading of the page that explains a sign-in that did not finish. | ||
| 34 | + ProblemFailedTitle, | ||
| 35 | + /// Text of that page. | ||
| 36 | + ProblemFailedBody, | ||
| 37 | + /// Heading of the page shown when `im` cannot be reached. | ||
| 38 | + ProblemUnavailableTitle, | ||
| 39 | + /// Text of that page. | ||
| 40 | + ProblemUnavailableBody, | ||
| 41 | + /// Heading of the page shown to a disabled or refused account. | ||
| 42 | + ProblemDeniedTitle, | ||
| 43 | + /// Text of that page. | ||
| 44 | + ProblemDeniedBody, | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +/// The greeting for a signed-in person. The name is inserted as text; the view escapes it. | ||
| 48 | +pub fn greeting(lang: Lang, name: &str) -> String { | ||
| 49 | + match lang { | ||
| 50 | + Lang::En => format!("Hello, {name}."), | ||
| 51 | + Lang::Tr => format!("Merhaba, {name}."), | ||
| 52 | + } | ||
| 27 | } | 53 | } |
| 28 | 54 | ||
| 29 | /// The text of `key` in `lang`. | 55 | /// The text of `key` in `lang`. |
| @@ -45,7 +71,37 @@ pub fn t(lang: Lang, key: K) -> &'static str { | |||
| 45 | (K::SkipToContent, Lang::Tr) => "İçeriğe geç", | 71 | (K::SkipToContent, Lang::Tr) => "İçeriğe geç", |
| 46 | (K::SignedOutTitle, Lang::En) => "Sign in to open your files", | 72 | (K::SignedOutTitle, Lang::En) => "Sign in to open your files", |
| 47 | (K::SignedOutTitle, Lang::Tr) => "Dosyalarınızı açmak için oturum açın", | 73 | (K::SignedOutTitle, Lang::Tr) => "Dosyalarınızı açmak için oturum açın", |
| 48 | - (K::SignedOutBody, Lang::En) => "You are signed out. Sign-in is not part of this build yet.", | 74 | + (K::SignedOutBody, Lang::En) => "Sign in with your family account to open your files.", |
| 49 | - (K::SignedOutBody, Lang::Tr) => "Oturumunuz kapalı. Oturum açma bu sürümde henüz yok.", | 75 | + (K::SignedOutBody, Lang::Tr) => "Dosyalarınızı açmak için aile hesabınızla oturum açın.", |
| 76 | + (K::SignIn, Lang::En) => "Sign in", | ||
| 77 | + (K::SignIn, Lang::Tr) => "Oturum aç", | ||
| 78 | + (K::DriveComesNext, Lang::En) => "The drive comes next. Your files will appear here.", | ||
| 79 | + (K::DriveComesNext, Lang::Tr) => "Sürücü sıradaki adım. Dosyalarınız burada görünecek.", | ||
| 80 | + (K::SignOut, Lang::En) => "Sign out", | ||
| 81 | + (K::SignOut, Lang::Tr) => "Oturumu kapat", | ||
| 82 | + (K::ProblemFailedTitle, Lang::En) => "Sign-in did not finish", | ||
| 83 | + (K::ProblemFailedTitle, Lang::Tr) => "Oturum açma tamamlanamadı", | ||
| 84 | + (K::ProblemFailedBody, Lang::En) => { | ||
| 85 | + "The sign-in was cancelled or expired. Start again from the start page." | ||
| 86 | + } | ||
| 87 | + (K::ProblemFailedBody, Lang::Tr) => { | ||
| 88 | + "Oturum açma iptal edildi ya da süresi doldu. Başlangıç sayfasından yeniden deneyin." | ||
| 89 | + } | ||
| 90 | + (K::ProblemUnavailableTitle, Lang::En) => "Sign-in is unavailable", | ||
| 91 | + (K::ProblemUnavailableTitle, Lang::Tr) => "Oturum açma şu an kullanılamıyor", | ||
| 92 | + (K::ProblemUnavailableBody, Lang::En) => { | ||
| 93 | + "The account service cannot be reached. Try again in a few minutes." | ||
| 94 | + } | ||
| 95 | + (K::ProblemUnavailableBody, Lang::Tr) => { | ||
| 96 | + "Hesap servisine ulaşılamıyor. Birkaç dakika içinde yeniden deneyin." | ||
| 97 | + } | ||
| 98 | + (K::ProblemDeniedTitle, Lang::En) => "This account cannot sign in", | ||
| 99 | + (K::ProblemDeniedTitle, Lang::Tr) => "Bu hesapla oturum açılamaz", | ||
| 100 | + (K::ProblemDeniedBody, Lang::En) => { | ||
| 101 | + "Ask the administrator of this instance to check the account." | ||
| 102 | + } | ||
| 103 | + (K::ProblemDeniedBody, Lang::Tr) => { | ||
| 104 | + "Bu sunucunun yöneticisine hesabı kontrol etmesini isteyin." | ||
| 105 | + } | ||
| 50 | } | 106 | } |
| 51 | } | 107 | } |
crates/in-web/src/main.rsmodified+3 -0
| @@ -5,10 +5,13 @@ | |||
| 5 | //! then `IN_CONFIG`, then `config/in.toml`. Exit status 0 is success, 1 a failure, 2 a usage error. | 5 | //! then `IN_CONFIG`, then `config/in.toml`. Exit status 0 is success, 1 a failure, 2 a usage error. |
| 6 | 6 | ||
| 7 | mod assets; | 7 | mod assets; |
| 8 | +mod auth; | ||
| 8 | mod boot; | 9 | mod boot; |
| 10 | +mod directory; | ||
| 9 | mod health; | 11 | mod health; |
| 10 | mod i18n; | 12 | mod i18n; |
| 11 | mod live; | 13 | mod live; |
| 14 | +mod oidc; | ||
| 12 | mod pages; | 15 | mod pages; |
| 13 | mod security; | 16 | mod security; |
| 14 | mod state; | 17 | mod state; |
crates/in-web/src/oidc.rsadded+905 -0
| @@ -0,0 +1,905 @@ | |||
| 1 | +//! The OpenID Connect client of `in`, a relying party of `im` (docs/contracts.md section 2). | ||
| 2 | +//! | ||
| 3 | +//! It does four things and nothing more. It finds `im`'s endpoints (discovery, cached, with the | ||
| 4 | +//! standard paths as a fallback). It keeps `im`'s signing keys (JWKS, cached for an hour, refetched at | ||
| 5 | +//! most once a minute when a token names an unknown key). It verifies the three kinds of token `in` | ||
| 6 | +//! receives: ID tokens, logout tokens and access tokens. And it makes the calls `in` sends to `im`: the | ||
| 7 | +//! code exchange and the client-credentials token that the directory and the photos need. | ||
| 8 | +//! | ||
| 9 | +//! The verification rules are pure functions over a [`KeySet`], so they are tested without a network. | ||
| 10 | +//! Only EdDSA is accepted. The algorithm is checked on the raw header before any library parses it, so | ||
| 11 | +//! `none` and every other algorithm are refused with the same answer. | ||
| 12 | + | ||
| 13 | +use std::sync::Arc; | ||
| 14 | +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; | ||
| 15 | + | ||
| 16 | +use base64::prelude::{BASE64_STANDARD, BASE64_URL_SAFE_NO_PAD, Engine as _}; | ||
| 17 | +use in_core::config::Oidc; | ||
| 18 | +use in_core::error::{Error as CoreError, Result as CoreResult}; | ||
| 19 | +use in_core::token::constant_time_eq; | ||
| 20 | +use jsonwebtoken::errors::ErrorKind; | ||
| 21 | +use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header}; | ||
| 22 | +use serde::Deserialize; | ||
| 23 | +use serde_json::{Map, Value}; | ||
| 24 | +use sha2::{Digest, Sha256}; | ||
| 25 | +use tokio::sync::Mutex; | ||
| 26 | + | ||
| 27 | +/// Seconds of clock skew allowed on `exp`. The contracts do not name a value; `in` uses 60 s. | ||
| 28 | +pub const CLOCK_LEEWAY_SECS: i64 = 60; | ||
| 29 | + | ||
| 30 | +/// Seconds an `iat` may lie in the future. Contracts section 2.3 says five minutes. | ||
| 31 | +pub const MAX_FUTURE_IAT_SECS: i64 = 300; | ||
| 32 | + | ||
| 33 | +/// How long a fetched key set is used before it is fetched again (contracts section 2.2). | ||
| 34 | +pub const JWKS_MAX_AGE: Duration = Duration::from_secs(60 * 60); | ||
| 35 | + | ||
| 36 | +/// The shortest gap between two key fetches caused by an unknown `kid`. Protects `im` from a flood of | ||
| 37 | +/// tokens that name keys that do not exist. | ||
| 38 | +pub const JWKS_REFRESH_GAP: Duration = Duration::from_secs(60); | ||
| 39 | + | ||
| 40 | +/// How long a failed discovery is not retried. Until it succeeds the standard paths are used. | ||
| 41 | +const DISCOVERY_RETRY_GAP: Duration = Duration::from_secs(60); | ||
| 42 | + | ||
| 43 | +/// Time limit of every call to `im`, except the directory stream. | ||
| 44 | +pub const HTTP_TIMEOUT: Duration = Duration::from_secs(10); | ||
| 45 | + | ||
| 46 | +/// Longest silence on the directory stream before the connection is given up. The server sends a | ||
| 47 | +/// keep-alive every 30 seconds (contracts section 3.2), so three of them missed means it is dead. | ||
| 48 | +const STREAM_READ_TIMEOUT: Duration = Duration::from_secs(90); | ||
| 49 | + | ||
| 50 | +/// A service token is refreshed this long before its stated end (contracts section 2.6). | ||
| 51 | +const SERVICE_TOKEN_MARGIN: Duration = Duration::from_secs(60); | ||
| 52 | + | ||
| 53 | +/// The event name that marks a logout token (OIDC Back-Channel Logout 1.0). | ||
| 54 | +pub const LOGOUT_EVENT: &str = "http://schemas.openid.net/event/backchannel-logout"; | ||
| 55 | + | ||
| 56 | +/// The family key of `im`. Client-credentials tokens that `in` asks for carry it as `aud`. | ||
| 57 | +pub const IM_KEY: &str = "im"; | ||
| 58 | + | ||
| 59 | +/// The scope that reads the people directory and photos at `im`. | ||
| 60 | +pub const DIRECTORY_SCOPE: &str = "directory.read"; | ||
| 61 | + | ||
| 62 | +/// Why a token was refused. Every variant is a refusal; none of them says more than the cause. | ||
| 63 | +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] | ||
| 64 | +pub enum TokenError { | ||
| 65 | + /// The token is not three base64url segments with a JSON header and claims. | ||
| 66 | + #[error("the token is malformed")] | ||
| 67 | + Malformed, | ||
| 68 | + /// The header names an algorithm other than EdDSA, or none at all. | ||
| 69 | + #[error("the token is not signed with EdDSA")] | ||
| 70 | + Algorithm, | ||
| 71 | + /// The header has no `kid`, so the key cannot be chosen. | ||
| 72 | + #[error("the token has no key id")] | ||
| 73 | + NoKeyId, | ||
| 74 | + /// The `kid` is not in the published key set. The caller may refetch the keys once. | ||
| 75 | + #[error("the token names an unknown key")] | ||
| 76 | + UnknownKey, | ||
| 77 | + /// The signature does not verify with the named key. | ||
| 78 | + #[error("the signature does not verify")] | ||
| 79 | + Signature, | ||
| 80 | + /// `exp` is in the past, beyond the leeway. | ||
| 81 | + #[error("the token has expired")] | ||
| 82 | + Expired, | ||
| 83 | + /// A claim is missing, has the wrong type, or has the wrong value. | ||
| 84 | + #[error("the claim {0} is missing or wrong")] | ||
| 85 | + Claim(&'static str), | ||
| 86 | + /// The nonce does not equal the one this sign-in sent. | ||
| 87 | + #[error("the nonce does not match")] | ||
| 88 | + Nonce, | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +/// Why a call to `im` failed. | ||
| 92 | +#[derive(Debug, thiserror::Error)] | ||
| 93 | +pub enum OidcError { | ||
| 94 | + /// A token did not verify. | ||
| 95 | + #[error(transparent)] | ||
| 96 | + Token(#[from] TokenError), | ||
| 97 | + /// `im` could not be reached, or answered something that is not what the contracts describe. | ||
| 98 | + #[error("the identity provider is unavailable: {0}")] | ||
| 99 | + Unavailable(String), | ||
| 100 | + /// `im` answered with a refusal, such as a rejected code or a wrong client secret. | ||
| 101 | + #[error("the identity provider refused the request")] | ||
| 102 | + Refused, | ||
| 103 | +} | ||
| 104 | + | ||
| 105 | +/// The claims of an ID token that `in` uses. Each field is checked by [`verify_id_token`]. | ||
| 106 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 107 | +pub struct IdClaims { | ||
| 108 | + /// The person's stable id (a ULID). | ||
| 109 | + pub sub: String, | ||
| 110 | + /// The `im` browser session the sign-in belongs to. Back-channel logout names it. | ||
| 111 | + pub sid: String, | ||
| 112 | + /// The person's email address. | ||
| 113 | + pub email: String, | ||
| 114 | + /// The display name. The email address when the claim is empty. | ||
| 115 | + pub name: String, | ||
| 116 | + /// Whether the person administers the family instance. | ||
| 117 | + pub admin: bool, | ||
| 118 | + /// `en` or `tr`. Anything else from `im` is read as `en`. | ||
| 119 | + pub locale: String, | ||
| 120 | + /// IANA time zone name. | ||
| 121 | + pub zoneinfo: String, | ||
| 122 | + /// Photo version; bumps when the photo changes. | ||
| 123 | + pub picture_version: i64, | ||
| 124 | +} | ||
| 125 | + | ||
| 126 | +/// The claims of a back-channel logout token that `in` uses. | ||
| 127 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 128 | +pub struct LogoutClaims { | ||
| 129 | + /// Unique id of the token. A replayed id is refused for ten minutes. | ||
| 130 | + pub jti: String, | ||
| 131 | + /// The `im` session that ended, when the token names one. | ||
| 132 | + pub sid: Option<String>, | ||
| 133 | + /// The person, when the token names one. A token with only `sub` ends every session of the person. | ||
| 134 | + pub sub: Option<String>, | ||
| 135 | +} | ||
| 136 | + | ||
| 137 | +/// The endpoints of `im` that `in` calls. Discovery provides them; the standard paths replace them | ||
| 138 | +/// when discovery cannot be fetched. | ||
| 139 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 140 | +pub struct Endpoints { | ||
| 141 | + /// The sign-in page, `/authorize`. | ||
| 142 | + pub authorization: String, | ||
| 143 | + /// The token endpoint, `/token`. | ||
| 144 | + pub token: String, | ||
| 145 | + /// The signing keys, `/jwks.json`. | ||
| 146 | + pub jwks: String, | ||
| 147 | + /// The end-session page, `/logout`. | ||
| 148 | + pub end_session: String, | ||
| 149 | +} | ||
| 150 | + | ||
| 151 | +/// The fields of the discovery document that `in` reads. | ||
| 152 | +#[derive(Debug, Deserialize)] | ||
| 153 | +struct DiscoveryDocument { | ||
| 154 | + issuer: String, | ||
| 155 | + authorization_endpoint: String, | ||
| 156 | + token_endpoint: String, | ||
| 157 | + jwks_uri: String, | ||
| 158 | + end_session_endpoint: Option<String>, | ||
| 159 | +} | ||
| 160 | + | ||
| 161 | +/// One key of the published JWKS, as far as `in` reads it. | ||
| 162 | +#[derive(Debug, Deserialize)] | ||
| 163 | +pub struct Jwk { | ||
| 164 | + #[serde(default)] | ||
| 165 | + kty: String, | ||
| 166 | + #[serde(default)] | ||
| 167 | + crv: String, | ||
| 168 | + #[serde(default)] | ||
| 169 | + x: String, | ||
| 170 | + #[serde(default)] | ||
| 171 | + kid: String, | ||
| 172 | + #[serde(default)] | ||
| 173 | + alg: String, | ||
| 174 | + #[serde(default, rename = "use")] | ||
| 175 | + usage: String, | ||
| 176 | +} | ||
| 177 | + | ||
| 178 | +/// The JWKS document. | ||
| 179 | +#[derive(Debug, Deserialize)] | ||
| 180 | +pub struct Jwks { | ||
| 181 | + keys: Vec<Jwk>, | ||
| 182 | +} | ||
| 183 | + | ||
| 184 | +/// The usable Ed25519 keys of `im`, by `kid`. | ||
| 185 | +pub struct KeySet { | ||
| 186 | + keys: Vec<(String, DecodingKey)>, | ||
| 187 | +} | ||
| 188 | + | ||
| 189 | +impl KeySet { | ||
| 190 | + /// Keeps the keys that `in` can use: Ed25519 (`OKP`) signing keys whose algorithm, when named, is | ||
| 191 | + /// EdDSA. Anything else in the document is skipped, not an error. | ||
| 192 | + pub fn from_jwks(jwks: &Jwks) -> KeySet { | ||
| 193 | + let keys = jwks | ||
| 194 | + .keys | ||
| 195 | + .iter() | ||
| 196 | + .filter(|key| key.kty == "OKP" && key.crv == "Ed25519") | ||
| 197 | + .filter(|key| key.alg.is_empty() || key.alg == "EdDSA") | ||
| 198 | + .filter(|key| key.usage.is_empty() || key.usage == "sig") | ||
| 199 | + .filter(|key| !key.kid.is_empty()) | ||
| 200 | + .filter_map(|key| { | ||
| 201 | + DecodingKey::from_ed_components(&key.x) | ||
| 202 | + .ok() | ||
| 203 | + .map(|decoding| (key.kid.clone(), decoding)) | ||
| 204 | + }) | ||
| 205 | + .collect(); | ||
| 206 | + KeySet { keys } | ||
| 207 | + } | ||
| 208 | + | ||
| 209 | + /// The key with this `kid`, if it is published. | ||
| 210 | + fn get(&self, kid: &str) -> Option<&DecodingKey> { | ||
| 211 | + self.keys | ||
| 212 | + .iter() | ||
| 213 | + .find(|(known, _)| known == kid) | ||
| 214 | + .map(|(_, key)| key) | ||
| 215 | + } | ||
| 216 | +} | ||
| 217 | + | ||
| 218 | +/// The current time in whole seconds since the Unix epoch. | ||
| 219 | +pub fn now_secs() -> i64 { | ||
| 220 | + SystemTime::now() | ||
| 221 | + .duration_since(UNIX_EPOCH) | ||
| 222 | + .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX)) | ||
| 223 | +} | ||
| 224 | + | ||
| 225 | +/// Reads a non-empty string claim. | ||
| 226 | +fn text_claim<'a>( | ||
| 227 | + claims: &'a Map<String, Value>, | ||
| 228 | + name: &'static str, | ||
| 229 | +) -> Result<&'a str, TokenError> { | ||
| 230 | + claims | ||
| 231 | + .get(name) | ||
| 232 | + .and_then(Value::as_str) | ||
| 233 | + .filter(|value| !value.trim().is_empty()) | ||
| 234 | + .ok_or(TokenError::Claim(name)) | ||
| 235 | +} | ||
| 236 | + | ||
| 237 | +/// Reads an optional non-empty string claim. A present but empty value counts as absent. | ||
| 238 | +fn optional_text_claim<'a>(claims: &'a Map<String, Value>, name: &str) -> Option<&'a str> { | ||
| 239 | + claims | ||
| 240 | + .get(name) | ||
| 241 | + .and_then(Value::as_str) | ||
| 242 | + .filter(|value| !value.trim().is_empty()) | ||
| 243 | +} | ||
| 244 | + | ||
| 245 | +/// Whether `aud` names `expected`. A string must equal it; an array must hold exactly that one value. | ||
| 246 | +/// Contracts require an exact `client_id` for ID tokens, so a longer audience list is refused. | ||
| 247 | +fn audience_is(aud: Option<&Value>, expected: &str) -> bool { | ||
| 248 | + match aud { | ||
| 249 | + Some(Value::String(single)) => single == expected, | ||
| 250 | + Some(Value::Array(items)) => { | ||
| 251 | + items.len() == 1 && items.first().and_then(Value::as_str) == Some(expected) | ||
| 252 | + } | ||
| 253 | + _ => false, | ||
| 254 | + } | ||
| 255 | +} | ||
| 256 | + | ||
| 257 | +/// Refuses an `iat` that is missing or more than [`MAX_FUTURE_IAT_SECS`] ahead of `now`. | ||
| 258 | +fn check_iat(claims: &Map<String, Value>, now: i64) -> Result<(), TokenError> { | ||
| 259 | + let iat = claims | ||
| 260 | + .get("iat") | ||
| 261 | + .and_then(Value::as_i64) | ||
| 262 | + .ok_or(TokenError::Claim("iat"))?; | ||
| 263 | + if iat > now + MAX_FUTURE_IAT_SECS { | ||
| 264 | + return Err(TokenError::Claim("iat")); | ||
| 265 | + } | ||
| 266 | + Ok(()) | ||
| 267 | +} | ||
| 268 | + | ||
| 269 | +/// Checks the algorithm, the key id, the signature, the issuer and the expiry, and returns the claims. | ||
| 270 | +/// Audience, nonce and the rest are the job of the callers, which know what they expect. | ||
| 271 | +/// | ||
| 272 | +/// The algorithm is read from the raw header first, so `none` and any other algorithm are refused | ||
| 273 | +/// before a library sees the token. | ||
| 274 | +pub fn verify_signed( | ||
| 275 | + keys: &KeySet, | ||
| 276 | + token: &str, | ||
| 277 | + issuer: &str, | ||
| 278 | +) -> Result<Map<String, Value>, TokenError> { | ||
| 279 | + let first_segment = token.split('.').next().ok_or(TokenError::Malformed)?; | ||
| 280 | + let header_bytes = BASE64_URL_SAFE_NO_PAD | ||
| 281 | + .decode(first_segment) | ||
| 282 | + .map_err(|_| TokenError::Malformed)?; | ||
| 283 | + let header: Value = serde_json::from_slice(&header_bytes).map_err(|_| TokenError::Malformed)?; | ||
| 284 | + if header.get("alg").and_then(Value::as_str) != Some("EdDSA") { | ||
| 285 | + return Err(TokenError::Algorithm); | ||
| 286 | + } | ||
| 287 | + let parsed = decode_header(token).map_err(|_| TokenError::Malformed)?; | ||
| 288 | + let kid = parsed.kid.ok_or(TokenError::NoKeyId)?; | ||
| 289 | + let key = keys.get(&kid).ok_or(TokenError::UnknownKey)?; | ||
| 290 | + | ||
| 291 | + let mut validation = Validation::new(Algorithm::EdDSA); | ||
| 292 | + validation.leeway = u64::try_from(CLOCK_LEEWAY_SECS).unwrap_or(0); | ||
| 293 | + validation.validate_exp = true; | ||
| 294 | + // Audience is checked by the callers, because the rule differs by token kind. | ||
| 295 | + validation.validate_aud = false; | ||
| 296 | + validation.set_issuer(&[issuer]); | ||
| 297 | + // `sub` is not required here: a back-channel token may carry only `sid`, and each caller checks | ||
| 298 | + // the subject it needs. | ||
| 299 | + validation.set_required_spec_claims(&["exp", "iss", "iat"]); | ||
| 300 | + let data = | ||
| 301 | + decode::<Map<String, Value>>(token, key, &validation).map_err(|error| { | ||
| 302 | + match error.kind() { | ||
| 303 | + ErrorKind::ExpiredSignature => TokenError::Expired, | ||
| 304 | + ErrorKind::InvalidSignature => TokenError::Signature, | ||
| 305 | + ErrorKind::InvalidIssuer => TokenError::Claim("iss"), | ||
| 306 | + ErrorKind::InvalidAlgorithm => TokenError::Algorithm, | ||
| 307 | + ErrorKind::MissingRequiredClaim(_) => TokenError::Claim("required claim"), | ||
| 308 | + _ => TokenError::Malformed, | ||
| 309 | + } | ||
| 310 | + })?; | ||
| 311 | + Ok(data.claims) | ||
| 312 | +} | ||
| 313 | + | ||
| 314 | +/// Verifies an ID token from the code exchange: signature, issuer, `aud` equal to `client_id`, `exp`, | ||
| 315 | +/// `iat`, and the `nonce` this sign-in sent. Returns the claims `in` keeps about the person. | ||
| 316 | +pub fn verify_id_token( | ||
| 317 | + keys: &KeySet, | ||
| 318 | + token: &str, | ||
| 319 | + issuer: &str, | ||
| 320 | + client_id: &str, | ||
| 321 | + nonce: &str, | ||
| 322 | +) -> Result<IdClaims, TokenError> { | ||
| 323 | + let claims = verify_signed(keys, token, issuer)?; | ||
| 324 | + if !audience_is(claims.get("aud"), client_id) { | ||
| 325 | + return Err(TokenError::Claim("aud")); | ||
| 326 | + } | ||
| 327 | + check_iat(&claims, now_secs())?; | ||
| 328 | + let sent = text_claim(&claims, "nonce")?; | ||
| 329 | + if !constant_time_eq(sent.as_bytes(), nonce.as_bytes()) { | ||
| 330 | + return Err(TokenError::Nonce); | ||
| 331 | + } | ||
| 332 | + let sub = text_claim(&claims, "sub")?.to_owned(); | ||
| 333 | + let sid = text_claim(&claims, "sid")?.to_owned(); | ||
| 334 | + let email = text_claim(&claims, "email")?.to_owned(); | ||
| 335 | + let name = optional_text_claim(&claims, "name") | ||
| 336 | + .unwrap_or(&email) | ||
| 337 | + .to_owned(); | ||
| 338 | + let locale = match optional_text_claim(&claims, "locale") { | ||
| 339 | + Some("tr") => "tr".to_owned(), | ||
| 340 | + _ => "en".to_owned(), | ||
| 341 | + }; | ||
| 342 | + Ok(IdClaims { | ||
| 343 | + sub, | ||
| 344 | + sid, | ||
| 345 | + email, | ||
| 346 | + name, | ||
| 347 | + admin: claims | ||
| 348 | + .get("admin") | ||
| 349 | + .and_then(Value::as_bool) | ||
| 350 | + .unwrap_or(false), | ||
| 351 | + locale, | ||
| 352 | + zoneinfo: optional_text_claim(&claims, "zoneinfo") | ||
| 353 | + .unwrap_or("UTC") | ||
| 354 | + .to_owned(), | ||
| 355 | + picture_version: claims | ||
| 356 | + .get("picture_version") | ||
| 357 | + .and_then(Value::as_i64) | ||
| 358 | + .unwrap_or(0) | ||
| 359 | + .max(0), | ||
| 360 | + }) | ||
| 361 | +} | ||
| 362 | + | ||
| 363 | +/// Verifies a back-channel logout token (contracts section 2.5): signature, issuer, `aud` equal to | ||
| 364 | +/// `client_id`, `iat`, `exp`, the logout event, a `jti`, a `sid` or `sub`, and no `nonce`. | ||
| 365 | +pub fn verify_logout_token( | ||
| 366 | + keys: &KeySet, | ||
| 367 | + token: &str, | ||
| 368 | + issuer: &str, | ||
| 369 | + client_id: &str, | ||
| 370 | +) -> Result<LogoutClaims, TokenError> { | ||
| 371 | + let claims = verify_signed(keys, token, issuer)?; | ||
| 372 | + if !audience_is(claims.get("aud"), client_id) { | ||
| 373 | + return Err(TokenError::Claim("aud")); | ||
| 374 | + } | ||
| 375 | + check_iat(&claims, now_secs())?; | ||
| 376 | + if claims.contains_key("nonce") { | ||
| 377 | + return Err(TokenError::Claim("nonce")); | ||
| 378 | + } | ||
| 379 | + let has_event = claims | ||
| 380 | + .get("events") | ||
| 381 | + .and_then(Value::as_object) | ||
| 382 | + .and_then(|events| events.get(LOGOUT_EVENT)) | ||
| 383 | + .is_some_and(Value::is_object); | ||
| 384 | + if !has_event { | ||
| 385 | + return Err(TokenError::Claim("events")); | ||
| 386 | + } | ||
| 387 | + let jti = text_claim(&claims, "jti")?.to_owned(); | ||
| 388 | + let sid = optional_text_claim(&claims, "sid").map(str::to_owned); | ||
| 389 | + let sub = optional_text_claim(&claims, "sub").map(str::to_owned); | ||
| 390 | + if sid.is_none() && sub.is_none() { | ||
| 391 | + return Err(TokenError::Claim("sub")); | ||
| 392 | + } | ||
| 393 | + Ok(LogoutClaims { jti, sid, sub }) | ||
| 394 | +} | ||
| 395 | + | ||
| 396 | +/// Verifies an access token addressed to `audience` (for `in`, [`FAMILY_KEY`]) that grants | ||
| 397 | +/// `required_scope`. Returns the caller's family key (`svc`) and its subject. | ||
| 398 | +/// | ||
| 399 | +/// Nothing calls this yet; the object API that accepts service calls comes next. | ||
| 400 | +#[allow(dead_code)] // The object API that accepts other family apps' calls is the first caller. | ||
| 401 | +pub fn verify_access_token( | ||
| 402 | + keys: &KeySet, | ||
| 403 | + token: &str, | ||
| 404 | + issuer: &str, | ||
| 405 | + audience: &str, | ||
| 406 | + required_scope: &str, | ||
| 407 | +) -> Result<(String, String), TokenError> { | ||
| 408 | + let claims = verify_signed(keys, token, issuer)?; | ||
| 409 | + if !audience_is(claims.get("aud"), audience) { | ||
| 410 | + return Err(TokenError::Claim("aud")); | ||
| 411 | + } | ||
| 412 | + check_iat(&claims, now_secs())?; | ||
| 413 | + let scope = text_claim(&claims, "scope")?; | ||
| 414 | + if !scope.split(' ').any(|granted| granted == required_scope) { | ||
| 415 | + return Err(TokenError::Claim("scope")); | ||
| 416 | + } | ||
| 417 | + let sub = text_claim(&claims, "sub")?.to_owned(); | ||
| 418 | + let svc = text_claim(&claims, "svc")?.to_owned(); | ||
| 419 | + Ok((sub, svc)) | ||
| 420 | +} | ||
| 421 | + | ||
| 422 | +/// The PKCE code challenge of `verifier`: base64url of its SHA-256, without padding (RFC 7636). | ||
| 423 | +pub fn pkce_challenge(verifier: &str) -> String { | ||
| 424 | + BASE64_URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())) | ||
| 425 | +} | ||
| 426 | + | ||
| 427 | +/// Percent-encodes one value for a query, a form body or a Basic credential (RFC 6749 section 2.3.1): | ||
| 428 | +/// unreserved characters pass, everything else becomes `%XX`. | ||
| 429 | +pub fn percent_encode(value: &str) -> String { | ||
| 430 | + let mut out = String::with_capacity(value.len()); | ||
| 431 | + for byte in value.bytes() { | ||
| 432 | + if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') { | ||
| 433 | + out.push(char::from(byte)); | ||
| 434 | + } else { | ||
| 435 | + out.push_str(&format!("%{byte:02X}")); | ||
| 436 | + } | ||
| 437 | + } | ||
| 438 | + out | ||
| 439 | +} | ||
| 440 | + | ||
| 441 | +/// The body of a successful token response. Only the fields `in` reads are named. | ||
| 442 | +#[derive(Debug, Deserialize)] | ||
| 443 | +struct TokenResponse { | ||
| 444 | + #[serde(default)] | ||
| 445 | + id_token: Option<String>, | ||
| 446 | + #[serde(default)] | ||
| 447 | + access_token: Option<String>, | ||
| 448 | + #[serde(default)] | ||
| 449 | + expires_in: Option<u64>, | ||
| 450 | +} | ||
| 451 | + | ||
| 452 | +/// Cached state of the client. Every field is behind one lock, and no method holds it while it | ||
| 453 | +/// takes it again. | ||
| 454 | +#[derive(Default)] | ||
| 455 | +struct Cache { | ||
| 456 | + /// The endpoints from discovery, once fetched. | ||
| 457 | + endpoints: Option<Arc<Endpoints>>, | ||
| 458 | + /// When the last discovery failed. Until [`DISCOVERY_RETRY_GAP`] has passed, the standard paths | ||
| 459 | + /// are used without asking again. | ||
| 460 | + discovery_failed_at: Option<Instant>, | ||
| 461 | + /// The key set and when it was fetched. | ||
| 462 | + keys: Option<(Instant, Arc<KeySet>)>, | ||
| 463 | + /// When the keys were last fetched for an unknown `kid`. Limits those fetches. | ||
| 464 | + keys_refresh_at: Option<Instant>, | ||
| 465 | + /// The client-credentials token for `im`, and the instant it stops being used. | ||
| 466 | + service: Option<(String, Instant)>, | ||
| 467 | +} | ||
| 468 | + | ||
| 469 | +/// The OpenID Connect client. One per process, shared through the app state. | ||
| 470 | +pub struct OidcClient { | ||
| 471 | + issuer: String, | ||
| 472 | + client_id: String, | ||
| 473 | + client_secret: String, | ||
| 474 | + redirect_uri: String, | ||
| 475 | + http: reqwest::Client, | ||
| 476 | + stream_http: reqwest::Client, | ||
| 477 | + cache: Mutex<Cache>, | ||
| 478 | +} | ||
| 479 | + | ||
| 480 | +impl OidcClient { | ||
| 481 | + /// Builds the client from the `[oidc]` table, the public base URL and the client secret read from | ||
| 482 | + /// its file. No request is made here. | ||
| 483 | + pub fn new(config: &Oidc, base_url: &str, client_secret: String) -> CoreResult<Self> { | ||
| 484 | + let http = reqwest::Client::builder() | ||
| 485 | + .timeout(HTTP_TIMEOUT) | ||
| 486 | + .connect_timeout(HTTP_TIMEOUT) | ||
| 487 | + .redirect(reqwest::redirect::Policy::none()) | ||
| 488 | + .build() | ||
| 489 | + .map_err(|e| CoreError::Config(format!("cannot build the HTTP client: {e}")))?; | ||
| 490 | + // The directory stream lasts for minutes, so it gets no total time limit, only a read limit. | ||
| 491 | + let stream_http = reqwest::Client::builder() | ||
| 492 | + .connect_timeout(HTTP_TIMEOUT) | ||
| 493 | + .read_timeout(STREAM_READ_TIMEOUT) | ||
| 494 | + .redirect(reqwest::redirect::Policy::none()) | ||
| 495 | + .build() | ||
| 496 | + .map_err(|e| CoreError::Config(format!("cannot build the stream client: {e}")))?; | ||
| 497 | + Ok(Self { | ||
| 498 | + issuer: config.issuer.clone(), | ||
| 499 | + client_id: config.client_id.clone(), | ||
| 500 | + client_secret, | ||
| 501 | + redirect_uri: format!("{base_url}/auth/callback"), | ||
| 502 | + http, | ||
| 503 | + stream_http, | ||
| 504 | + cache: Mutex::new(Cache::default()), | ||
| 505 | + }) | ||
| 506 | + } | ||
| 507 | + | ||
| 508 | + /// The issuer URL of `im`, which is also the origin of its API. | ||
| 509 | + pub fn issuer(&self) -> &str { | ||
| 510 | + &self.issuer | ||
| 511 | + } | ||
| 512 | + | ||
| 513 | + /// The HTTP client for calls to `im` with a time limit. | ||
| 514 | + pub fn http(&self) -> &reqwest::Client { | ||
| 515 | + &self.http | ||
| 516 | + } | ||
| 517 | + | ||
| 518 | + /// The HTTP client for the directory stream, which has no total time limit. | ||
| 519 | + pub fn stream_http(&self) -> &reqwest::Client { | ||
| 520 | + &self.stream_http | ||
| 521 | + } | ||
| 522 | + | ||
| 523 | + /// The endpoints of `im`. Fetched from discovery once; when discovery fails, the standard paths | ||
| 524 | + /// under the issuer are used and discovery is retried after [`DISCOVERY_RETRY_GAP`]. | ||
| 525 | + pub async fn endpoints(&self) -> Arc<Endpoints> { | ||
| 526 | + let mut cache = self.cache.lock().await; | ||
| 527 | + if let Some(endpoints) = &cache.endpoints { | ||
| 528 | + return Arc::clone(endpoints); | ||
| 529 | + } | ||
| 530 | + let recently_failed = cache | ||
| 531 | + .discovery_failed_at | ||
| 532 | + .is_some_and(|at| at.elapsed() < DISCOVERY_RETRY_GAP); | ||
| 533 | + if !recently_failed { | ||
| 534 | + match self.fetch_discovery().await { | ||
| 535 | + Ok(endpoints) => { | ||
| 536 | + let endpoints = Arc::new(endpoints); | ||
| 537 | + cache.endpoints = Some(Arc::clone(&endpoints)); | ||
| 538 | + cache.discovery_failed_at = None; | ||
| 539 | + return endpoints; | ||
| 540 | + } | ||
| 541 | + Err(error) => { | ||
| 542 | + tracing::warn!(error = %error, "oidc: discovery failed, using the standard paths"); | ||
| 543 | + cache.discovery_failed_at = Some(Instant::now()); | ||
| 544 | + } | ||
| 545 | + } | ||
| 546 | + } | ||
| 547 | + Arc::new(self.standard_endpoints()) | ||
| 548 | + } | ||
| 549 | + | ||
| 550 | + /// The paths of contracts section 2.1, under the issuer. | ||
| 551 | + fn standard_endpoints(&self) -> Endpoints { | ||
| 552 | + Endpoints { | ||
| 553 | + authorization: format!("{}/authorize", self.issuer), | ||
| 554 | + token: format!("{}/token", self.issuer), | ||
| 555 | + jwks: format!("{}/jwks.json", self.issuer), | ||
| 556 | + end_session: format!("{}/logout", self.issuer), | ||
| 557 | + } | ||
| 558 | + } | ||
| 559 | + | ||
| 560 | + /// Fetches and checks the discovery document. Its `issuer` must equal the configured one exactly. | ||
| 561 | + async fn fetch_discovery(&self) -> Result<Endpoints, OidcError> { | ||
| 562 | + let url = format!("{}/.well-known/openid-configuration", self.issuer); | ||
| 563 | + let document: DiscoveryDocument = self.get_json(&url).await?; | ||
| 564 | + if document.issuer != self.issuer { | ||
| 565 | + return Err(OidcError::Unavailable( | ||
| 566 | + "discovery names another issuer".to_owned(), | ||
| 567 | + )); | ||
| 568 | + } | ||
| 569 | + let end_session = document | ||
| 570 | + .end_session_endpoint | ||
| 571 | + .unwrap_or_else(|| format!("{}/logout", self.issuer)); | ||
| 572 | + Ok(Endpoints { | ||
| 573 | + authorization: document.authorization_endpoint, | ||
| 574 | + token: document.token_endpoint, | ||
| 575 | + jwks: document.jwks_uri, | ||
| 576 | + end_session, | ||
| 577 | + }) | ||
| 578 | + } | ||
| 579 | + | ||
| 580 | + /// GETs a JSON document. A non-2xx answer is unavailable: the caller cannot do anything with it. | ||
| 581 | + async fn get_json<T: serde::de::DeserializeOwned>(&self, url: &str) -> Result<T, OidcError> { | ||
| 582 | + let response = self | ||
| 583 | + .http | ||
| 584 | + .get(url) | ||
| 585 | + .send() | ||
| 586 | + .await | ||
| 587 | + .map_err(|e| OidcError::Unavailable(e.to_string()))?; | ||
| 588 | + if !response.status().is_success() { | ||
| 589 | + return Err(OidcError::Unavailable(format!( | ||
| 590 | + "{url} answered {}", | ||
| 591 | + response.status() | ||
| 592 | + ))); | ||
| 593 | + } | ||
| 594 | + let bytes = response | ||
| 595 | + .bytes() | ||
| 596 | + .await | ||
| 597 | + .map_err(|e| OidcError::Unavailable(e.to_string()))?; | ||
| 598 | + serde_json::from_slice(&bytes).map_err(|e| OidcError::Unavailable(e.to_string())) | ||
| 599 | + } | ||
| 600 | + | ||
| 601 | + /// The key set in use. A fresh cache is used as it is; an expired one is refetched, and a failed | ||
| 602 | + /// refetch keeps the old set, because a stale key still verifies tokens that were signed with it. | ||
| 603 | + async fn load_keys(&self, force: bool) -> Result<Arc<KeySet>, OidcError> { | ||
| 604 | + let endpoints = self.endpoints().await; | ||
| 605 | + let mut cache = self.cache.lock().await; | ||
| 606 | + let fresh = cache | ||
| 607 | + .keys | ||
| 608 | + .as_ref() | ||
| 609 | + .is_some_and(|(at, _)| at.elapsed() < JWKS_MAX_AGE); | ||
| 610 | + if fresh | ||
| 611 | + && !force | ||
| 612 | + && let Some((_, keys)) = &cache.keys | ||
| 613 | + { | ||
| 614 | + return Ok(Arc::clone(keys)); | ||
| 615 | + } | ||
| 616 | + // A forced refetch (unknown kid) is rate limited. Within the gap the old set is the answer. | ||
| 617 | + let refreshed_recently = cache | ||
| 618 | + .keys_refresh_at | ||
| 619 | + .is_some_and(|at| at.elapsed() < JWKS_REFRESH_GAP); | ||
| 620 | + if force | ||
| 621 | + && refreshed_recently | ||
| 622 | + && let Some((_, keys)) = &cache.keys | ||
| 623 | + { | ||
| 624 | + return Ok(Arc::clone(keys)); | ||
| 625 | + } | ||
| 626 | + cache.keys_refresh_at = Some(Instant::now()); | ||
| 627 | + match self.get_json::<Jwks>(&endpoints.jwks).await { | ||
| 628 | + Ok(jwks) => { | ||
| 629 | + let keys = Arc::new(KeySet::from_jwks(&jwks)); | ||
| 630 | + cache.keys = Some((Instant::now(), Arc::clone(&keys))); | ||
| 631 | + Ok(keys) | ||
| 632 | + } | ||
| 633 | + Err(error) => match &cache.keys { | ||
| 634 | + Some((_, keys)) => { | ||
| 635 | + tracing::warn!(error = %error, "oidc: key fetch failed, keeping the cached keys"); | ||
| 636 | + Ok(Arc::clone(keys)) | ||
| 637 | + } | ||
| 638 | + None => Err(error), | ||
| 639 | + }, | ||
| 640 | + } | ||
| 641 | + } | ||
| 642 | + | ||
| 643 | + /// Runs `check` against the key set. An unknown key id triggers one rate-limited refetch. | ||
| 644 | + async fn verify_with<T>( | ||
| 645 | + &self, | ||
| 646 | + check: impl Fn(&KeySet) -> Result<T, TokenError>, | ||
| 647 | + ) -> Result<T, OidcError> { | ||
| 648 | + let keys = self.load_keys(false).await?; | ||
| 649 | + match check(&keys) { | ||
| 650 | + Err(TokenError::UnknownKey) => { | ||
| 651 | + let keys = self.load_keys(true).await?; | ||
| 652 | + Ok(check(&keys)?) | ||
| 653 | + } | ||
| 654 | + outcome => Ok(outcome?), | ||
| 655 | + } | ||
| 656 | + } | ||
| 657 | + | ||
| 658 | + /// Verifies an ID token of this sign-in. See [`verify_id_token`]. | ||
| 659 | + pub async fn verify_id_token(&self, token: &str, nonce: &str) -> Result<IdClaims, OidcError> { | ||
| 660 | + self.verify_with(|keys| verify_id_token(keys, token, &self.issuer, &self.client_id, nonce)) | ||
| 661 | + .await | ||
| 662 | + } | ||
| 663 | + | ||
| 664 | + /// Verifies a back-channel logout token. See [`verify_logout_token`]. | ||
| 665 | + pub async fn verify_logout_token(&self, token: &str) -> Result<LogoutClaims, OidcError> { | ||
| 666 | + self.verify_with(|keys| verify_logout_token(keys, token, &self.issuer, &self.client_id)) | ||
| 667 | + .await | ||
| 668 | + } | ||
| 669 | + | ||
| 670 | + /// The URL that sends the browser to `im` to sign in (contracts section 2.3, step 1). | ||
| 671 | + pub async fn authorize_url( | ||
| 672 | + &self, | ||
| 673 | + state: &str, | ||
| 674 | + nonce: &str, | ||
| 675 | + challenge: &str, | ||
| 676 | + ) -> Result<String, OidcError> { | ||
| 677 | + let endpoints = self.endpoints().await; | ||
| 678 | + let mut url = reqwest::Url::parse(&endpoints.authorization) | ||
| 679 | + .map_err(|e| OidcError::Unavailable(format!("bad authorization endpoint: {e}")))?; | ||
| 680 | + url.query_pairs_mut() | ||
| 681 | + .append_pair("response_type", "code") | ||
| 682 | + .append_pair("client_id", &self.client_id) | ||
| 683 | + .append_pair("redirect_uri", &self.redirect_uri) | ||
| 684 | + .append_pair("scope", "openid profile email") | ||
| 685 | + .append_pair("state", state) | ||
| 686 | + .append_pair("nonce", nonce) | ||
| 687 | + .append_pair("code_challenge", challenge) | ||
| 688 | + .append_pair("code_challenge_method", "S256"); | ||
| 689 | + Ok(url.to_string()) | ||
| 690 | + } | ||
| 691 | + | ||
| 692 | + /// The URL that ends the `im` session (RP-initiated logout, contracts section 2.5). | ||
| 693 | + pub async fn end_session_url( | ||
| 694 | + &self, | ||
| 695 | + id_token_hint: &str, | ||
| 696 | + post_logout_redirect: &str, | ||
| 697 | + state: &str, | ||
| 698 | + ) -> Result<String, OidcError> { | ||
| 699 | + let endpoints = self.endpoints().await; | ||
| 700 | + let mut url = reqwest::Url::parse(&endpoints.end_session) | ||
| 701 | + .map_err(|e| OidcError::Unavailable(format!("bad end-session endpoint: {e}")))?; | ||
| 702 | + url.query_pairs_mut() | ||
| 703 | + .append_pair("id_token_hint", id_token_hint) | ||
| 704 | + .append_pair("post_logout_redirect_uri", post_logout_redirect) | ||
| 705 | + .append_pair("state", state); | ||
| 706 | + Ok(url.to_string()) | ||
| 707 | + } | ||
| 708 | + | ||
| 709 | + /// Exchanges the authorization code for the ID token (contracts section 2.3, step 3). The access | ||
| 710 | + /// and refresh tokens are not kept: this family does not use them. | ||
| 711 | + pub async fn exchange_code(&self, code: &str, verifier: &str) -> Result<String, OidcError> { | ||
| 712 | + let endpoints = self.endpoints().await; | ||
| 713 | + let response = self | ||
| 714 | + .token_request( | ||
| 715 | + &endpoints.token, | ||
| 716 | + &[ | ||
| 717 | + ("grant_type", "authorization_code"), | ||
| 718 | + ("code", code), | ||
| 719 | + ("redirect_uri", &self.redirect_uri), | ||
| 720 | + ("code_verifier", verifier), | ||
| 721 | + ], | ||
| 722 | + ) | ||
| 723 | + .await?; | ||
| 724 | + response | ||
| 725 | + .id_token | ||
| 726 | + .ok_or(OidcError::Token(TokenError::Claim("id_token"))) | ||
| 727 | + } | ||
| 728 | + | ||
| 729 | + /// A client-credentials token for the directory at `im` (contracts section 2.6). Cached until | ||
| 730 | + /// [`SERVICE_TOKEN_MARGIN`] before its stated lifetime ends. | ||
| 731 | + pub async fn service_token(&self) -> Result<String, OidcError> { | ||
| 732 | + let endpoints = self.endpoints().await; | ||
| 733 | + let mut cache = self.cache.lock().await; | ||
| 734 | + if let Some((token, until)) = &cache.service | ||
| 735 | + && Instant::now() < *until | ||
| 736 | + { | ||
| 737 | + return Ok(token.clone()); | ||
| 738 | + } | ||
| 739 | + let response = self | ||
| 740 | + .token_request( | ||
| 741 | + &endpoints.token, | ||
| 742 | + &[ | ||
| 743 | + ("grant_type", "client_credentials"), | ||
| 744 | + ("scope", DIRECTORY_SCOPE), | ||
| 745 | + ("audience", IM_KEY), | ||
| 746 | + ], | ||
| 747 | + ) | ||
| 748 | + .await?; | ||
| 749 | + let token = response | ||
| 750 | + .access_token | ||
| 751 | + .ok_or(OidcError::Token(TokenError::Claim("access_token")))?; | ||
| 752 | + let lifetime = Duration::from_secs(response.expires_in.unwrap_or(0)); | ||
| 753 | + let until = Instant::now() + lifetime.saturating_sub(SERVICE_TOKEN_MARGIN); | ||
| 754 | + cache.service = Some((token.clone(), until)); | ||
| 755 | + Ok(token) | ||
| 756 | + } | ||
| 757 | + | ||
| 758 | + /// Posts a form to a token endpoint with client_secret_basic authentication (RFC 6749 section | ||
| 759 | + /// 2.3.1). A 4xx answer is a refusal; anything else that is not a success is unavailable. | ||
| 760 | + async fn token_request( | ||
| 761 | + &self, | ||
| 762 | + url: &str, | ||
| 763 | + form: &[(&str, &str)], | ||
| 764 | + ) -> Result<TokenResponse, OidcError> { | ||
| 765 | + let credentials = format!( | ||
| 766 | + "{}:{}", | ||
| 767 | + percent_encode(&self.client_id), | ||
| 768 | + percent_encode(&self.client_secret) | ||
| 769 | + ); | ||
| 770 | + let response = self | ||
| 771 | + .http | ||
| 772 | + .post(url) | ||
| 773 | + .header( | ||
| 774 | + reqwest::header::AUTHORIZATION, | ||
| 775 | + format!("Basic {}", BASE64_STANDARD.encode(credentials)), | ||
| 776 | + ) | ||
| 777 | + .header(reqwest::header::ACCEPT, "application/json") | ||
| 778 | + .form(form) | ||
| 779 | + .send() | ||
| 780 | + .await | ||
| 781 | + .map_err(|e| OidcError::Unavailable(e.to_string()))?; | ||
| 782 | + let status = response.status(); | ||
| 783 | + if status.is_client_error() { | ||
| 784 | + tracing::warn!(status = %status, "oidc: the token endpoint refused the request"); | ||
| 785 | + return Err(OidcError::Refused); | ||
| 786 | + } | ||
| 787 | + if !status.is_success() { | ||
| 788 | + return Err(OidcError::Unavailable(format!( | ||
| 789 | + "token endpoint answered {status}" | ||
| 790 | + ))); | ||
| 791 | + } | ||
| 792 | + let bytes = response | ||
| 793 | + .bytes() | ||
| 794 | + .await | ||
| 795 | + .map_err(|e| OidcError::Unavailable(e.to_string()))?; | ||
| 796 | + serde_json::from_slice(&bytes).map_err(|e| OidcError::Unavailable(e.to_string())) | ||
| 797 | + } | ||
| 798 | +} | ||
| 799 | + | ||
| 800 | +#[cfg(test)] | ||
| 801 | +mod tests { | ||
| 802 | + use super::*; | ||
| 803 | + use ed25519_dalek::SigningKey; | ||
| 804 | + use ed25519_dalek::pkcs8::EncodePrivateKey; | ||
| 805 | + use jsonwebtoken::{EncodingKey, Header, encode}; | ||
| 806 | + use serde_json::json; | ||
| 807 | + | ||
| 808 | + const ISSUER: &str = "https://im.example.test"; | ||
| 809 | + const CLIENT: &str = "in"; | ||
| 810 | + const KID: &str = "k1"; | ||
| 811 | + const NONCE: &str = "nonce-value"; | ||
| 812 | + | ||
| 813 | + /// A fresh Ed25519 key: the signing half as PKCS#8 DER, and the key set that publishes it. | ||
| 814 | + fn test_key() -> (Vec<u8>, KeySet) { | ||
| 815 | + let mut seed = [0u8; 32]; | ||
| 816 | + rand::fill(&mut seed); | ||
| 817 | + let signing = SigningKey::from_bytes(&seed); | ||
| 818 | + let der = signing.to_pkcs8_der().expect("pkcs8").as_bytes().to_vec(); | ||
| 819 | + let x = BASE64_URL_SAFE_NO_PAD.encode(signing.verifying_key().to_bytes()); | ||
| 820 | + let jwks: Jwks = serde_json::from_value(json!({ | ||
| 821 | + "keys": [{"kty": "OKP", "crv": "Ed25519", "x": x, "kid": KID, "use": "sig", "alg": "EdDSA"}] | ||
| 822 | + })) | ||
| 823 | + .expect("jwks"); | ||
| 824 | + (der, KeySet::from_jwks(&jwks)) | ||
| 825 | + } | ||
| 826 | + | ||
| 827 | + /// Signs `claims` with `der` under `kid`. | ||
| 828 | + fn sign(der: &[u8], claims: &Value) -> String { | ||
| 829 | + let mut header = Header::new(Algorithm::EdDSA); | ||
| 830 | + header.kid = Some(KID.to_owned()); | ||
| 831 | + encode(&header, claims, &EncodingKey::from_ed_der(der)).expect("sign") | ||
| 832 | + } | ||
| 833 | + | ||
| 834 | + fn id_claims(now: i64) -> Value { | ||
| 835 | + json!({ | ||
| 836 | + "iss": ISSUER, "sub": "01JTESTSUB", "aud": CLIENT, "exp": now + 300, "iat": now, | ||
| 837 | + "nonce": NONCE, "sid": "im-session-1", "email": "ann@example.test", "name": "Ann", | ||
| 838 | + }) | ||
| 839 | + } | ||
| 840 | + | ||
| 841 | + #[test] | ||
| 842 | + fn a_valid_id_token_is_accepted() { | ||
| 843 | + let (der, keys) = test_key(); | ||
| 844 | + let token = sign(&der, &id_claims(now_secs())); | ||
| 845 | + let claims = verify_id_token(&keys, &token, ISSUER, CLIENT, NONCE).expect("valid"); | ||
| 846 | + assert_eq!(claims.sub, "01JTESTSUB"); | ||
| 847 | + assert_eq!(claims.sid, "im-session-1"); | ||
| 848 | + assert_eq!(claims.locale, "en"); | ||
| 849 | + } | ||
| 850 | + | ||
| 851 | + #[test] | ||
| 852 | + fn an_unsigned_alg_none_token_is_refused() { | ||
| 853 | + let (_der, keys) = test_key(); | ||
| 854 | + let header = BASE64_URL_SAFE_NO_PAD.encode(br#"{"alg":"none","kid":"k1","typ":"JWT"}"#); | ||
| 855 | + let payload = BASE64_URL_SAFE_NO_PAD.encode(id_claims(now_secs()).to_string()); | ||
| 856 | + let token = format!("{header}.{payload}."); | ||
| 857 | + assert_eq!( | ||
| 858 | + verify_id_token(&keys, &token, ISSUER, CLIENT, NONCE).err(), | ||
| 859 | + Some(TokenError::Algorithm) | ||
| 860 | + ); | ||
| 861 | + } | ||
| 862 | + | ||
| 863 | + #[test] | ||
| 864 | + fn a_token_for_another_audience_is_refused() { | ||
| 865 | + let (der, keys) = test_key(); | ||
| 866 | + let mut claims = id_claims(now_secs()); | ||
| 867 | + claims["aud"] = json!("iz"); | ||
| 868 | + let token = sign(&der, &claims); | ||
| 869 | + assert_eq!( | ||
| 870 | + verify_id_token(&keys, &token, ISSUER, CLIENT, NONCE).err(), | ||
| 871 | + Some(TokenError::Claim("aud")) | ||
| 872 | + ); | ||
| 873 | + } | ||
| 874 | + | ||
| 875 | + #[test] | ||
| 876 | + fn an_expired_token_is_refused_beyond_the_leeway() { | ||
| 877 | + let (der, keys) = test_key(); | ||
| 878 | + let now = now_secs(); | ||
| 879 | + let mut claims = id_claims(now); | ||
| 880 | + claims["exp"] = json!(now - 3 * CLOCK_LEEWAY_SECS); | ||
| 881 | + let token = sign(&der, &claims); | ||
| 882 | + assert_eq!( | ||
| 883 | + verify_id_token(&keys, &token, ISSUER, CLIENT, NONCE).err(), | ||
| 884 | + Some(TokenError::Expired) | ||
| 885 | + ); | ||
| 886 | + } | ||
| 887 | + | ||
| 888 | + #[test] | ||
| 889 | + fn a_wrong_nonce_is_refused() { | ||
| 890 | + let (der, keys) = test_key(); | ||
| 891 | + let token = sign(&der, &id_claims(now_secs())); | ||
| 892 | + assert_eq!( | ||
| 893 | + verify_id_token(&keys, &token, ISSUER, CLIENT, "another-nonce").err(), | ||
| 894 | + Some(TokenError::Nonce) | ||
| 895 | + ); | ||
| 896 | + } | ||
| 897 | + | ||
| 898 | + #[test] | ||
| 899 | + fn the_pkce_challenge_matches_the_rfc_7636_vector() { | ||
| 900 | + assert_eq!( | ||
| 901 | + pkce_challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"), | ||
| 902 | + "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" | ||
| 903 | + ); | ||
| 904 | + } | ||
| 905 | +} | ||
crates/in-web/src/pages/backchannel.rsadded+223 -0
| @@ -0,0 +1,223 @@ | |||
| 1 | +//! The back-channel logout endpoint (contracts section 2.5). `im` POSTs a logout token here when a session | ||
| 2 | +//! of ours has to end: on sign-out, admin revoke, password change, or a disabled or deleted person. | ||
| 3 | +//! | ||
| 4 | +//! The endpoint is for machines, so it has no CSRF token. Its protection is the token itself: the | ||
| 5 | +//! signature, the issuer, the audience, the event and the `jti` replay guard. The body is capped at 16 KiB. | ||
| 6 | +//! Every answer that is not success is an error with a JSON body, which `im` reads as a failed delivery and | ||
| 7 | +//! retries. | ||
| 8 | +//! | ||
| 9 | +//! It is served at `/auth/backchannel-logout`, the path architecture.md names. | ||
| 10 | + | ||
| 11 | +use http::header::CONTENT_TYPE; | ||
| 12 | +use http::{HeaderMap, HeaderValue}; | ||
| 13 | +use in_core::error::Result as CoreResult; | ||
| 14 | +use in_core::store::Store; | ||
| 15 | +use in_core::time::stamp_after; | ||
| 16 | +use serde::Deserialize; | ||
| 17 | +use std::time::Duration; | ||
| 18 | +use topcoat::Result; | ||
| 19 | +use topcoat::context::{Cx, app_context}; | ||
| 20 | +use topcoat::router::content::Form; | ||
| 21 | +use topcoat::router::error::ContentTooLargeError; | ||
| 22 | +use topcoat::router::{Body, StatusCode, route, to_bytes}; | ||
| 23 | + | ||
| 24 | +use crate::oidc::{LogoutClaims, OidcError}; | ||
| 25 | +use crate::state::AppState; | ||
| 26 | + | ||
| 27 | +/// The largest body the endpoint reads. A logout form is a few kilobytes; this is generous. | ||
| 28 | +pub const BODY_LIMIT: usize = 16 * 1024; | ||
| 29 | + | ||
| 30 | +/// How long a logout token's `jti` is remembered. Contracts section 2.5 says ten minutes, which is longer | ||
| 31 | +/// than the token's own two-minute life. | ||
| 32 | +pub const REPLAY_WINDOW: Duration = Duration::from_secs(10 * 60); | ||
| 33 | + | ||
| 34 | +/// What the endpoint answers: status, headers and body. | ||
| 35 | +pub type Answer = (StatusCode, HeaderMap, String); | ||
| 36 | + | ||
| 37 | +/// The form body of a delivery: the one field `im` sends. | ||
| 38 | +#[derive(Debug, Default, Deserialize)] | ||
| 39 | +#[serde(default)] | ||
| 40 | +struct LogoutTokenForm { | ||
| 41 | + logout_token: String, | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +/// What ending the sessions for one token did. | ||
| 45 | +#[derive(Debug, PartialEq, Eq)] | ||
| 46 | +pub enum Outcome { | ||
| 47 | + /// The token was new. This many sessions ended (possibly none). | ||
| 48 | + Ended(u64), | ||
| 49 | + /// The `jti` was seen before. The token is refused and nothing is ended. | ||
| 50 | + Replayed, | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +/// Ends the sessions a verified logout token names, after recording its `jti`. | ||
| 54 | +/// | ||
| 55 | +/// The `jti` is recorded first, and the insert decides: two deliveries of one token cannot both be | ||
| 56 | +/// acted on, and a replay ends nothing. The `sid` names one `im` session; a token with only `sub` ends | ||
| 57 | +/// every session of the person. | ||
| 58 | +pub async fn end_sessions(store: &Store, claims: &LogoutClaims) -> CoreResult<Outcome> { | ||
| 59 | + if !store | ||
| 60 | + .seen_jti(&claims.jti, &stamp_after(REPLAY_WINDOW)) | ||
| 61 | + .await? | ||
| 62 | + { | ||
| 63 | + return Ok(Outcome::Replayed); | ||
| 64 | + } | ||
| 65 | + let ended = match (&claims.sid, &claims.sub) { | ||
| 66 | + (Some(sid), _) => store.delete_sessions_by_im_sid(sid).await?, | ||
| 67 | + (None, Some(sub)) => store.delete_sessions_by_sub(sub).await?, | ||
| 68 | + (None, None) => 0, | ||
| 69 | + }; | ||
| 70 | + Ok(Outcome::Ended(ended)) | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +/// A JSON error answer, in the shape of contracts section 7. | ||
| 74 | +pub fn json_error(status: StatusCode, code: &str, message: &str) -> Answer { | ||
| 75 | + let mut headers = HeaderMap::new(); | ||
| 76 | + headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); | ||
| 77 | + let body = serde_json::json!({ "error": code, "message": message }).to_string(); | ||
| 78 | + (status, headers, body) | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +/// The answer of a successful delivery: `200` with an empty body. | ||
| 82 | +fn accepted() -> Answer { | ||
| 83 | + (StatusCode::OK, HeaderMap::new(), String::new()) | ||
| 84 | +} | ||
| 85 | + | ||
| 86 | +/// Runs one delivery from start to answer. | ||
| 87 | +async fn deliver(cx: &Cx, body: Body) -> Answer { | ||
| 88 | + let state = app_context::<AppState>(cx); | ||
| 89 | + let bytes = match to_bytes(body, BODY_LIMIT).await { | ||
| 90 | + Ok(bytes) => bytes, | ||
| 91 | + Err(error) if error.downcast_ref::<ContentTooLargeError>().is_some() => { | ||
| 92 | + return json_error( | ||
| 93 | + StatusCode::PAYLOAD_TOO_LARGE, | ||
| 94 | + "too_large", | ||
| 95 | + "The logout request body is too large.", | ||
| 96 | + ); | ||
| 97 | + } | ||
| 98 | + Err(_) => { | ||
| 99 | + return json_error( | ||
| 100 | + StatusCode::BAD_REQUEST, | ||
| 101 | + "invalid_request", | ||
| 102 | + "The logout request body cannot be read.", | ||
| 103 | + ); | ||
| 104 | + } | ||
| 105 | + }; | ||
| 106 | + let token = match Form::<LogoutTokenForm>::from_bytes(&bytes) { | ||
| 107 | + Ok(Form(form)) if !form.logout_token.is_empty() => form.logout_token, | ||
| 108 | + _ => { | ||
| 109 | + return json_error( | ||
| 110 | + StatusCode::BAD_REQUEST, | ||
| 111 | + "invalid_request", | ||
| 112 | + "The logout_token field is missing.", | ||
| 113 | + ); | ||
| 114 | + } | ||
| 115 | + }; | ||
| 116 | + let Some(oidc) = state.oidc.as_ref() else { | ||
| 117 | + return json_error( | ||
| 118 | + StatusCode::SERVICE_UNAVAILABLE, | ||
| 119 | + "unavailable", | ||
| 120 | + "Sign-in is not configured on this instance.", | ||
| 121 | + ); | ||
| 122 | + }; | ||
| 123 | + let claims = match oidc.verify_logout_token(&token).await { | ||
| 124 | + Ok(claims) => claims, | ||
| 125 | + Err(OidcError::Unavailable(_)) => { | ||
| 126 | + return json_error( | ||
| 127 | + StatusCode::SERVICE_UNAVAILABLE, | ||
| 128 | + "unavailable", | ||
| 129 | + "The signing keys cannot be fetched right now.", | ||
| 130 | + ); | ||
| 131 | + } | ||
| 132 | + Err(error) => { | ||
| 133 | + tracing::warn!(error = %error, "backchannel: logout token refused"); | ||
| 134 | + return json_error( | ||
| 135 | + StatusCode::BAD_REQUEST, | ||
| 136 | + "invalid_request", | ||
| 137 | + "The logout token is not valid.", | ||
| 138 | + ); | ||
| 139 | + } | ||
| 140 | + }; | ||
| 141 | + match end_sessions(&state.store, &claims).await { | ||
| 142 | + Ok(Outcome::Ended(count)) => { | ||
| 143 | + tracing::info!(sessions = count, "backchannel: logout applied"); | ||
| 144 | + accepted() | ||
| 145 | + } | ||
| 146 | + Ok(Outcome::Replayed) => json_error( | ||
| 147 | + StatusCode::BAD_REQUEST, | ||
| 148 | + "invalid_request", | ||
| 149 | + "The logout token was already used.", | ||
| 150 | + ), | ||
| 151 | + Err(error) => { | ||
| 152 | + tracing::error!(error = %error, "backchannel: could not end the sessions"); | ||
| 153 | + json_error( | ||
| 154 | + StatusCode::INTERNAL_SERVER_ERROR, | ||
| 155 | + "internal", | ||
| 156 | + "The sessions could not be ended.", | ||
| 157 | + ) | ||
| 158 | + } | ||
| 159 | + } | ||
| 160 | +} | ||
| 161 | + | ||
| 162 | +/// `POST /auth/backchannel-logout`. | ||
| 163 | +#[route(POST "/auth/backchannel-logout")] | ||
| 164 | +async fn backchannel(cx: &Cx, body: Body) -> Result<Answer> { | ||
| 165 | + Ok(deliver(cx, body).await) | ||
| 166 | +} | ||
| 167 | + | ||
| 168 | +#[cfg(test)] | ||
| 169 | +mod tests { | ||
| 170 | + use super::*; | ||
| 171 | + use in_core::store::members::MemberFields; | ||
| 172 | + use in_core::store::sessions::NewSession; | ||
| 173 | + use in_core::time::stamp_after; | ||
| 174 | + | ||
| 175 | + #[tokio::test] | ||
| 176 | + async fn a_replayed_jti_ends_nothing_the_second_time() { | ||
| 177 | + let dir = tempfile::tempdir().expect("temp dir"); | ||
| 178 | + let store = Store::open(&dir.path().join("in.db")).await.expect("store"); | ||
| 179 | + store | ||
| 180 | + .upsert_member_from_claims( | ||
| 181 | + &MemberFields { | ||
| 182 | + sub: "ann".into(), | ||
| 183 | + email: "ann@example.test".into(), | ||
| 184 | + name: "Ann".into(), | ||
| 185 | + is_admin: false, | ||
| 186 | + locale: "en".into(), | ||
| 187 | + zoneinfo: "UTC".into(), | ||
| 188 | + picture_version: 0, | ||
| 189 | + im_updated_at: String::new(), | ||
| 190 | + }, | ||
| 191 | + 1024, | ||
| 192 | + ) | ||
| 193 | + .await | ||
| 194 | + .expect("member"); | ||
| 195 | + store | ||
| 196 | + .create_session(NewSession { | ||
| 197 | + sub: "ann".into(), | ||
| 198 | + token_hash: "h-ann".into(), | ||
| 199 | + csrf_token: "c".into(), | ||
| 200 | + im_sid: "im-1".into(), | ||
| 201 | + expires_at: stamp_after(Duration::from_secs(3600)), | ||
| 202 | + ip: None, | ||
| 203 | + user_agent: None, | ||
| 204 | + id_token_sealed: None, | ||
| 205 | + }) | ||
| 206 | + .await | ||
| 207 | + .expect("session"); | ||
| 208 | + | ||
| 209 | + let claims = LogoutClaims { | ||
| 210 | + jti: "jti-1".into(), | ||
| 211 | + sid: Some("im-1".into()), | ||
| 212 | + sub: None, | ||
| 213 | + }; | ||
| 214 | + assert_eq!( | ||
| 215 | + end_sessions(&store, &claims).await.expect("first"), | ||
| 216 | + Outcome::Ended(1) | ||
| 217 | + ); | ||
| 218 | + assert_eq!( | ||
| 219 | + end_sessions(&store, &claims).await.expect("replay"), | ||
| 220 | + Outcome::Replayed | ||
| 221 | + ); | ||
| 222 | + } | ||
| 223 | +} | ||
crates/in-web/src/pages/home.rsmodified+34 -8
| @@ -1,25 +1,51 @@ | |||
| 1 | -//! The start page. For now it is a placeholder that shows the signed-out state; it becomes the | 1 | +//! The start page. Signed out, it offers sign-in. Signed in, it greets the person; the drive that |
| 2 | -//! account home (the drive redirect) once sign-in exists. | 2 | +//! follows it is not built yet, so it says so. |
| 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; | ||
| 9 | use crate::i18n::lang; | 10 | use crate::i18n::lang; |
| 10 | -use crate::i18n::shell::{K, t}; | 11 | +use crate::i18n::shell::{K, greeting, t}; |
| 11 | -use crate::views::{notice, shell}; | 12 | +use crate::views::{ViewerInfo, shell}; |
| 12 | 13 | ||
| 13 | /// `GET /`. | 14 | /// `GET /`. |
| 14 | #[page("/")] | 15 | #[page("/")] |
| 15 | async fn home(cx: &Cx) -> Result<impl View> { | 16 | async fn home(cx: &Cx) -> Result<impl View> { |
| 16 | - let lang = lang(cx, None); | 17 | + let viewer = current_member(cx).await?; |
| 18 | + // The language follows the stored override, else the one `im` reports, else the request. | ||
| 19 | + let lang = lang( | ||
| 20 | + cx, | ||
| 21 | + viewer.as_ref().map(|viewer| { | ||
| 22 | + viewer | ||
| 23 | + .member | ||
| 24 | + .locale_override | ||
| 25 | + .as_deref() | ||
| 26 | + .unwrap_or(viewer.member.locale.as_str()) | ||
| 27 | + }), | ||
| 28 | + ); | ||
| 29 | + let info = viewer.map(|viewer| ViewerInfo { | ||
| 30 | + name: viewer.member.name, | ||
| 31 | + is_admin: viewer.member.is_admin, | ||
| 32 | + csrf: viewer.session.csrf_token, | ||
| 33 | + }); | ||
| 34 | + let heading = match &info { | ||
| 35 | + Some(info) => greeting(lang, &info.name), | ||
| 36 | + None => t(lang, K::SignedOutTitle).to_owned(), | ||
| 37 | + }; | ||
| 17 | Ok(view! { | 38 | Ok(view! { |
| 18 | - shell(title: t(lang, K::SignedOutTitle), lang: lang, viewer: None, | 39 | + shell(title: heading.as_str(), lang: lang, viewer: info.as_ref(), |
| 19 | <section class="card"> | 40 | <section class="card"> |
| 20 | <p class="kicker">"in"</p> | 41 | <p class="kicker">"in"</p> |
| 21 | - <h1>(t(lang, K::SignedOutTitle))</h1> | 42 | + <h1>(heading.as_str())</h1> |
| 22 | - notice(message: t(lang, K::SignedOutBody)) | 43 | + if info.is_some() { |
| 44 | + <p>(t(lang, K::DriveComesNext))</p> | ||
| 45 | + } else { | ||
| 46 | + <p>(t(lang, K::SignedOutBody))</p> | ||
| 47 | + <a class="button primary" href="/auth/login">(t(lang, K::SignIn))</a> | ||
| 48 | + } | ||
| 23 | </section> | 49 | </section> |
| 24 | ) | 50 | ) |
| 25 | }) | 51 | }) |
crates/in-web/src/pages/mod.rsmodified+4 -1
| @@ -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 or per closely related group of pages. |
| 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/in-web/src/pages/photo.rsadded+248 -0
| @@ -0,0 +1,248 @@ | |||
| 1 | +//! `GET /avatar/{sub}`: a member's photo, served by `in` to signed-in members only. | ||
| 2 | +//! | ||
| 3 | +//! A browser never talks to `im` for a photo (contracts section 3). On a miss, `in` fetches the photo from | ||
| 4 | +//! `im` with its service token and keeps it on disk under `data_dir/photos/<sub>/<picture_version>`, so a | ||
| 5 | +//! photo is fetched once per version. The bytes go out with an ETag of the version (`"p<version>"`), | ||
| 6 | +//! `nosniff`, and a content type from a short allowlist. Anything else `im` sends is not served. | ||
| 7 | +//! | ||
| 8 | +//! A signed-out viewer, an unknown person and an unknown sub all get `404`: the answer does not say | ||
| 9 | +//! which of them it was. | ||
| 10 | + | ||
| 11 | +use std::path::{Path, PathBuf}; | ||
| 12 | + | ||
| 13 | +use http::header::{CONTENT_TYPE, ETAG, IF_NONE_MATCH}; | ||
| 14 | +use http::{HeaderMap, HeaderValue}; | ||
| 15 | +use topcoat::Result; | ||
| 16 | +use topcoat::context::{Cx, app_context}; | ||
| 17 | +use topcoat::router::error::{not_found, service_unavailable}; | ||
| 18 | +use topcoat::router::request::{headers, uri}; | ||
| 19 | +use topcoat::router::{StatusCode, route}; | ||
| 20 | + | ||
| 21 | +use crate::auth::current_member; | ||
| 22 | +use crate::oidc::OidcClient; | ||
| 23 | +use crate::state::AppState; | ||
| 24 | + | ||
| 25 | +/// The image types a photo may be served as. `im` may store others; they are not served. | ||
| 26 | +const ALLOWED_TYPES: [&str; 4] = ["image/png", "image/jpeg", "image/webp", "image/gif"]; | ||
| 27 | + | ||
| 28 | +/// The largest photo kept or served. Larger ones from `im` are not served. | ||
| 29 | +const MAX_PHOTO_BYTES: usize = 5 * 1024 * 1024; | ||
| 30 | + | ||
| 31 | +/// Seconds a client is told to wait when a photo cannot be fetched. | ||
| 32 | +const PHOTO_RETRY_SECS: u64 = 30; | ||
| 33 | + | ||
| 34 | +/// Directory under the data directory that holds the photo cache. | ||
| 35 | +const PHOTO_DIR: &str = "photos"; | ||
| 36 | + | ||
| 37 | +/// The answer of a photo request: status, headers and the image bytes. | ||
| 38 | +type PhotoAnswer = (StatusCode, HeaderMap, Vec<u8>); | ||
| 39 | + | ||
| 40 | +/// The allowlisted content type that `raw` names, ignoring parameters such as `; charset=...`. | ||
| 41 | +fn allowed_type(raw: &str) -> Option<&'static str> { | ||
| 42 | + let essence = raw.split(';').next()?.trim().to_ascii_lowercase(); | ||
| 43 | + ALLOWED_TYPES | ||
| 44 | + .into_iter() | ||
| 45 | + .find(|allowed| *allowed == essence) | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +/// A subject from the path. It must be a short id of ASCII letters, digits, `-` and `_`, so that it can | ||
| 49 | +/// be a directory name and never a path. | ||
| 50 | +fn valid_sub(sub: &str) -> bool { | ||
| 51 | + !sub.is_empty() | ||
| 52 | + && sub.len() <= 64 | ||
| 53 | + && sub | ||
| 54 | + .bytes() | ||
| 55 | + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') | ||
| 56 | +} | ||
| 57 | + | ||
| 58 | +/// The cache files of one photo version: the bytes and their content type. | ||
| 59 | +fn cache_paths(photo_dir: &Path, sub: &str, version: i64) -> (PathBuf, PathBuf) { | ||
| 60 | + let dir = photo_dir.join(sub); | ||
| 61 | + ( | ||
| 62 | + dir.join(format!("{version}.bin")), | ||
| 63 | + dir.join(format!("{version}.type")), | ||
| 64 | + ) | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +/// Reads a cached photo. A missing or incomplete entry is `None`, and the photo is fetched again. | ||
| 68 | +async fn read_cache(photo_dir: &Path, sub: &str, version: i64) -> Option<(&'static str, Vec<u8>)> { | ||
| 69 | + let (bytes_path, type_path) = cache_paths(photo_dir, sub, version); | ||
| 70 | + let content_type = allowed_type(&tokio::fs::read_to_string(type_path).await.ok()?)?; | ||
| 71 | + let bytes = tokio::fs::read(bytes_path).await.ok()?; | ||
| 72 | + Some((content_type, bytes)) | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +/// Stores a photo in the cache: the type first, then the bytes, each through a temporary file and a | ||
| 76 | +/// rename, so a reader never sees half of a photo. A failure is logged; the photo is still served. | ||
| 77 | +async fn write_cache(photo_dir: &Path, sub: &str, version: i64, content_type: &str, bytes: &[u8]) { | ||
| 78 | + let (bytes_path, type_path) = cache_paths(photo_dir, sub, version); | ||
| 79 | + let Some(dir) = bytes_path.parent() else { | ||
| 80 | + return; | ||
| 81 | + }; | ||
| 82 | + let written = async { | ||
| 83 | + tokio::fs::create_dir_all(dir).await?; | ||
| 84 | + write_atomically(&type_path, content_type.as_bytes()).await?; | ||
| 85 | + write_atomically(&bytes_path, bytes).await | ||
| 86 | + } | ||
| 87 | + .await; | ||
| 88 | + if let Err(error) = written { | ||
| 89 | + tracing::error!(error = %error, "photo: cannot write the cache"); | ||
| 90 | + } | ||
| 91 | +} | ||
| 92 | + | ||
| 93 | +/// Writes `bytes` to `path` through a sibling temporary file and a rename. | ||
| 94 | +async fn write_atomically(path: &Path, bytes: &[u8]) -> std::io::Result<()> { | ||
| 95 | + let temporary = path.with_extension("tmp"); | ||
| 96 | + tokio::fs::write(&temporary, bytes).await?; | ||
| 97 | + tokio::fs::rename(&temporary, path).await | ||
| 98 | +} | ||
| 99 | + | ||
| 100 | +/// Fetches a photo from `im` with the service token. `Ok(None)` means `im` has no photo, or one of a | ||
| 101 | +/// type or size that is not served. | ||
| 102 | +async fn fetch_photo( | ||
| 103 | + oidc: &OidcClient, | ||
| 104 | + sub: &str, | ||
| 105 | + version: i64, | ||
| 106 | +) -> Result<Option<(&'static str, Vec<u8>)>> { | ||
| 107 | + let token = match oidc.service_token().await { | ||
| 108 | + Ok(token) => token, | ||
| 109 | + Err(error) => { | ||
| 110 | + tracing::warn!(error = %error, "photo: no service token"); | ||
| 111 | + return Err(unavailable()); | ||
| 112 | + } | ||
| 113 | + }; | ||
| 114 | + let url = format!("{}/api/v1/people/{sub}/photo?v={version}", oidc.issuer()); | ||
| 115 | + let response = match oidc.http().get(url).bearer_auth(token).send().await { | ||
| 116 | + Ok(response) => response, | ||
| 117 | + Err(error) => { | ||
| 118 | + tracing::warn!(error = %error, "photo: im could not be reached"); | ||
| 119 | + return Err(unavailable()); | ||
| 120 | + } | ||
| 121 | + }; | ||
| 122 | + match response.status() { | ||
| 123 | + status if status == reqwest::StatusCode::NOT_FOUND => return Ok(None), | ||
| 124 | + status if !status.is_success() => { | ||
| 125 | + tracing::warn!(status = %status, "photo: im refused the photo"); | ||
| 126 | + return Err(unavailable()); | ||
| 127 | + } | ||
| 128 | + _ => {} | ||
| 129 | + } | ||
| 130 | + let content_type = response | ||
| 131 | + .headers() | ||
| 132 | + .get(reqwest::header::CONTENT_TYPE) | ||
| 133 | + .and_then(|value| value.to_str().ok()) | ||
| 134 | + .and_then(allowed_type); | ||
| 135 | + let Some(content_type) = content_type else { | ||
| 136 | + return Ok(None); | ||
| 137 | + }; | ||
| 138 | + if response | ||
| 139 | + .content_length() | ||
| 140 | + .is_some_and(|length| length > MAX_PHOTO_BYTES as u64) | ||
| 141 | + { | ||
| 142 | + return Ok(None); | ||
| 143 | + } | ||
| 144 | + let bytes = match response.bytes().await { | ||
| 145 | + Ok(bytes) if bytes.len() <= MAX_PHOTO_BYTES => bytes.to_vec(), | ||
| 146 | + Ok(_) => return Ok(None), | ||
| 147 | + Err(error) => { | ||
| 148 | + tracing::warn!(error = %error, "photo: the body could not be read"); | ||
| 149 | + return Err(unavailable()); | ||
| 150 | + } | ||
| 151 | + }; | ||
| 152 | + Ok(Some((content_type, bytes))) | ||
| 153 | +} | ||
| 154 | + | ||
| 155 | +/// The error of a photo that cannot be had right now: `503` with a retry hint. | ||
| 156 | +fn unavailable() -> topcoat::Error { | ||
| 157 | + service_unavailable(PHOTO_RETRY_SECS).into() | ||
| 158 | +} | ||
| 159 | + | ||
| 160 | +/// The answer that carries a photo: the bytes, the type, the version ETag, and the cache policy. | ||
| 161 | +/// `private, no-cache` makes the browser ask again, and the ETag makes that ask cheap. | ||
| 162 | +fn photo_answer(content_type: &'static str, etag: &str, bytes: Vec<u8>) -> PhotoAnswer { | ||
| 163 | + let mut headers = HeaderMap::new(); | ||
| 164 | + headers.insert(CONTENT_TYPE, HeaderValue::from_static(content_type)); | ||
| 165 | + headers.insert( | ||
| 166 | + http::header::X_CONTENT_TYPE_OPTIONS, | ||
| 167 | + HeaderValue::from_static("nosniff"), | ||
| 168 | + ); | ||
| 169 | + headers.insert( | ||
| 170 | + http::header::CACHE_CONTROL, | ||
| 171 | + HeaderValue::from_static("private, no-cache"), | ||
| 172 | + ); | ||
| 173 | + if let Ok(value) = HeaderValue::from_str(etag) { | ||
| 174 | + headers.insert(ETAG, value); | ||
| 175 | + } | ||
| 176 | + (StatusCode::OK, headers, bytes) | ||
| 177 | +} | ||
| 178 | + | ||
| 179 | +/// `GET /avatar/{sub}`. | ||
| 180 | +#[route(GET "/avatar/{sub}")] | ||
| 181 | +async fn photo(cx: &Cx) -> Result<PhotoAnswer> { | ||
| 182 | + let state = app_context::<AppState>(cx); | ||
| 183 | + let segments: Vec<&str> = uri(cx).path().split('/').collect(); | ||
| 184 | + let sub = match segments.as_slice() { | ||
| 185 | + ["", "people", sub, "photo"] if valid_sub(sub) => *sub, | ||
| 186 | + _ => return Err(not_found().into()), | ||
| 187 | + }; | ||
| 188 | + if current_member(cx).await?.is_none() { | ||
| 189 | + return Err(not_found().into()); | ||
| 190 | + } | ||
| 191 | + let Some(member) = state.store.member(sub).await? else { | ||
| 192 | + return Err(not_found().into()); | ||
| 193 | + }; | ||
| 194 | + let version = member.picture_version; | ||
| 195 | + let etag = format!("\"p{version}\""); | ||
| 196 | + if headers(cx) | ||
| 197 | + .get(IF_NONE_MATCH) | ||
| 198 | + .and_then(|value| value.to_str().ok()) | ||
| 199 | + .is_some_and(|value| value == etag) | ||
| 200 | + { | ||
| 201 | + let mut headers = HeaderMap::new(); | ||
| 202 | + if let Ok(value) = HeaderValue::from_str(&etag) { | ||
| 203 | + headers.insert(ETAG, value); | ||
| 204 | + } | ||
| 205 | + headers.insert( | ||
| 206 | + http::header::CACHE_CONTROL, | ||
| 207 | + HeaderValue::from_static("private, no-cache"), | ||
| 208 | + ); | ||
| 209 | + return Ok((StatusCode::NOT_MODIFIED, headers, Vec::new())); | ||
| 210 | + } | ||
| 211 | + | ||
| 212 | + let photo_dir = state.config.data_dir.join(PHOTO_DIR); | ||
| 213 | + if let Some((content_type, bytes)) = read_cache(&photo_dir, sub, version).await { | ||
| 214 | + return Ok(photo_answer(content_type, &etag, bytes)); | ||
| 215 | + } | ||
| 216 | + let Some(oidc) = state.oidc.as_ref() else { | ||
| 217 | + return Err(unavailable()); | ||
| 218 | + }; | ||
| 219 | + let Some((content_type, bytes)) = fetch_photo(oidc, sub, version).await? else { | ||
| 220 | + return Err(not_found().into()); | ||
| 221 | + }; | ||
| 222 | + write_cache(&photo_dir, sub, version, content_type, &bytes).await; | ||
| 223 | + Ok(photo_answer(content_type, &etag, bytes)) | ||
| 224 | +} | ||
| 225 | + | ||
| 226 | +#[cfg(test)] | ||
| 227 | +mod tests { | ||
| 228 | + use super::*; | ||
| 229 | + | ||
| 230 | + #[test] | ||
| 231 | + fn only_allowlisted_image_types_are_served() { | ||
| 232 | + assert_eq!( | ||
| 233 | + allowed_type("image/jpeg; charset=binary"), | ||
| 234 | + Some("image/jpeg") | ||
| 235 | + ); | ||
| 236 | + assert_eq!(allowed_type("IMAGE/PNG"), Some("image/png")); | ||
| 237 | + assert_eq!(allowed_type("image/svg+xml"), None); | ||
| 238 | + assert_eq!(allowed_type("text/html"), None); | ||
| 239 | + assert_eq!(allowed_type(""), None); | ||
| 240 | + } | ||
| 241 | + | ||
| 242 | + #[test] | ||
| 243 | + fn subjects_are_plain_identifiers() { | ||
| 244 | + assert!(valid_sub("01JABCDEF0123456789ABCDEFG")); | ||
| 245 | + assert!(!valid_sub("../etc")); | ||
| 246 | + assert!(!valid_sub("")); | ||
| 247 | + } | ||
| 248 | +} | ||
crates/in-web/src/pages/sign_in.rsadded+385 -0
| @@ -0,0 +1,385 @@ | |||
| 1 | +//! The sign-in pages: `/auth/login` starts sign-in, `/auth/callback` finishes it, `/auth/logout` ends the local | ||
| 2 | +//! session and the `im` session, and `/sign-in/problem` explains a sign-in that did not finish. | ||
| 3 | +//! | ||
| 4 | +//! The flow is contracts section 2.3. The state of a sign-in in progress (the state, nonce, PKCE verifier | ||
| 5 | +//! and the safe `next` target) lives in one sealed cookie, `__Host-in_flight`, for ten minutes. It is cleared | ||
| 6 | +//! on every outcome, so it is single use. After the callback the local session is created (section 2.4). | ||
| 7 | +//! Failures redirect to the problem page with a fixed reason word; no text from the request is reflected. | ||
| 8 | + | ||
| 9 | +use std::sync::Arc; | ||
| 10 | +use std::time::Duration; | ||
| 11 | + | ||
| 12 | +use http::header::USER_AGENT; | ||
| 13 | +use in_core::error::{Error as CoreError, Result as CoreResult}; | ||
| 14 | +use in_core::quota::DEFAULT_MEMBER_QUOTA; | ||
| 15 | +use in_core::secret; | ||
| 16 | +use in_core::store::members::MemberFields; | ||
| 17 | +use in_core::store::sessions::NewSession; | ||
| 18 | +use in_core::time::stamp_after; | ||
| 19 | +use in_core::token::{constant_time_eq, generate_token, hash_token}; | ||
| 20 | +use serde::{Deserialize, Serialize}; | ||
| 21 | +use topcoat::Result; | ||
| 22 | +use topcoat::context::{Cx, app_context}; | ||
| 23 | +use topcoat::router::content::Form; | ||
| 24 | +use topcoat::router::error::{SeeOther, forbidden, see_other}; | ||
| 25 | +use topcoat::router::page; | ||
| 26 | +use topcoat::router::request::{client_ip, headers}; | ||
| 27 | +use topcoat::router::{StatusCode, route}; | ||
| 28 | +use topcoat::view::{View, view}; | ||
| 29 | + | ||
| 30 | +use crate::auth::{ | ||
| 31 | + FLIGHT_COOKIE, FLIGHT_TTL, SESSION_COOKIE, SESSION_TTL, cookie_value, csrf_matches, | ||
| 32 | + current_session, next_or_home, set_cookie, | ||
| 33 | +}; | ||
| 34 | +use crate::i18n::lang; | ||
| 35 | +use crate::i18n::shell::{K, t}; | ||
| 36 | +use crate::oidc::{OidcClient, OidcError, now_secs, pkce_challenge}; | ||
| 37 | +use crate::state::AppState; | ||
| 38 | +use crate::views::shell; | ||
| 39 | + | ||
| 40 | +/// The reason word for a sign-in that did not finish: a refusal, a bad state, an expired flight. | ||
| 41 | +const REASON_FAILED: &str = "failed"; | ||
| 42 | +/// The reason word for `im` being unreachable. | ||
| 43 | +const REASON_UNAVAILABLE: &str = "unavailable"; | ||
| 44 | +/// The reason word for an account that may not sign in. | ||
| 45 | +const REASON_DENIED: &str = "denied"; | ||
| 46 | + | ||
| 47 | +/// The longest User-Agent kept with a session. Longer values are cut. | ||
| 48 | +const MAX_USER_AGENT_CHARS: usize = 256; | ||
| 49 | + | ||
| 50 | +/// The query of `/auth/login`. An absent or empty `next` means the start page. | ||
| 51 | +#[derive(Debug, Default, Deserialize)] | ||
| 52 | +#[serde(default)] | ||
| 53 | +struct LoginQuery { | ||
| 54 | + next: String, | ||
| 55 | +} | ||
| 56 | + | ||
| 57 | +/// The query of `/auth/callback`, as `im` sends it. Only the fields `in` reads are named. | ||
| 58 | +#[derive(Debug, Default, Deserialize)] | ||
| 59 | +#[serde(default)] | ||
| 60 | +struct CallbackQuery { | ||
| 61 | + code: String, | ||
| 62 | + state: String, | ||
| 63 | + error: String, | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +/// The form of `/auth/logout`: the CSRF token of the session. | ||
| 67 | +#[derive(Debug, Default, Deserialize)] | ||
| 68 | +#[serde(default)] | ||
| 69 | +struct LogoutForm { | ||
| 70 | + csrf: String, | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +/// The sealed content of the flight cookie. | ||
| 74 | +#[derive(Debug, Serialize, Deserialize)] | ||
| 75 | +struct Flight { | ||
| 76 | + state: String, | ||
| 77 | + nonce: String, | ||
| 78 | + verifier: String, | ||
| 79 | + next: String, | ||
| 80 | + /// When the flight stops being valid, in Unix seconds. | ||
| 81 | + expires_at: i64, | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +/// Redirects to the problem page with one of the fixed reason words. | ||
| 85 | +fn problem(reason: &str) -> SeeOther { | ||
| 86 | + see_other(format!("/sign-in/problem?reason={reason}")) | ||
| 87 | +} | ||
| 88 | + | ||
| 89 | +/// The problem a failed call to `im` leads to: unreachable is its own page, anything else is a | ||
| 90 | +/// sign-in that did not finish. | ||
| 91 | +fn problem_for(error: &OidcError) -> SeeOther { | ||
| 92 | + match error { | ||
| 93 | + OidcError::Unavailable(_) => problem(REASON_UNAVAILABLE), | ||
| 94 | + OidcError::Token(_) | OidcError::Refused => problem(REASON_FAILED), | ||
| 95 | + } | ||
| 96 | +} | ||
| 97 | + | ||
| 98 | +/// The client, when the configuration has one. | ||
| 99 | +fn client(state: &AppState) -> Option<Arc<OidcClient>> { | ||
| 100 | + state.oidc.clone() | ||
| 101 | +} | ||
| 102 | + | ||
| 103 | +/// Seals `bytes` with the instance key. | ||
| 104 | +fn seal(state: &AppState, bytes: &[u8]) -> CoreResult<String> { | ||
| 105 | + secret::seal(&state.key, bytes) | ||
| 106 | +} | ||
| 107 | + | ||
| 108 | +/// Opens a sealed value. Any failure reads as "not there", which the callers treat as a refusal. | ||
| 109 | +fn open(state: &AppState, sealed: &str) -> Option<Vec<u8>> { | ||
| 110 | + secret::open(&state.key, sealed).ok() | ||
| 111 | +} | ||
| 112 | + | ||
| 113 | +/// Reads the flight cookie. An unreadable, malformed or expired flight is `None`. | ||
| 114 | +fn read_flight(state: &AppState, sealed: &str) -> Option<Flight> { | ||
| 115 | + let bytes = open(state, sealed)?; | ||
| 116 | + let flight: Flight = serde_json::from_slice(&bytes).ok()?; | ||
| 117 | + (flight.expires_at > now_secs()).then_some(flight) | ||
| 118 | +} | ||
| 119 | + | ||
| 120 | +/// `GET /auth/login?next=`. Creates the flight, then sends the browser to `im` to sign in. | ||
| 121 | +#[route(GET "/auth/login")] | ||
| 122 | +async fn login(cx: &Cx, query: Option<Form<LoginQuery>>) -> Result<SeeOther> { | ||
| 123 | + let state = app_context::<AppState>(cx); | ||
| 124 | + let Some(oidc) = client(state) else { | ||
| 125 | + return Ok(problem(REASON_UNAVAILABLE)); | ||
| 126 | + }; | ||
| 127 | + let requested = query.map(|Form(query)| query.next).unwrap_or_default(); | ||
| 128 | + let flight = Flight { | ||
| 129 | + state: generate_token(), | ||
| 130 | + nonce: generate_token(), | ||
| 131 | + verifier: generate_token(), | ||
| 132 | + next: next_or_home(&requested), | ||
| 133 | + expires_at: now_secs() + i64::try_from(FLIGHT_TTL.as_secs()).unwrap_or(0), | ||
| 134 | + }; | ||
| 135 | + let url = match oidc | ||
| 136 | + .authorize_url( | ||
| 137 | + &flight.state, | ||
| 138 | + &flight.nonce, | ||
| 139 | + &pkce_challenge(&flight.verifier), | ||
| 140 | + ) | ||
| 141 | + .await | ||
| 142 | + { | ||
| 143 | + Ok(url) => url, | ||
| 144 | + Err(error) => { | ||
| 145 | + tracing::warn!(error = %error, "sign-in: cannot start the flow"); | ||
| 146 | + return Ok(problem(REASON_UNAVAILABLE)); | ||
| 147 | + } | ||
| 148 | + }; | ||
| 149 | + let bytes = serde_json::to_vec(&flight).map_err(|e| CoreError::Crypto(e.to_string()))?; | ||
| 150 | + set_cookie(cx, FLIGHT_COOKIE, seal(state, &bytes)?, FLIGHT_TTL); | ||
| 151 | + Ok(see_other(url)) | ||
| 152 | +} | ||
| 153 | + | ||
| 154 | +/// `GET /auth/callback`. Checks the state, exchanges the code, verifies the ID token, records the member | ||
| 155 | +/// and starts the local session. | ||
| 156 | +#[route(GET "/auth/callback")] | ||
| 157 | +async fn callback(cx: &Cx, query: Option<Form<CallbackQuery>>) -> Result<SeeOther> { | ||
| 158 | + let state = app_context::<AppState>(cx); | ||
| 159 | + let sealed_flight = cookie_value(cx, FLIGHT_COOKIE); | ||
| 160 | + // The flight is single use. It is cleared whatever the outcome. | ||
| 161 | + set_cookie(cx, FLIGHT_COOKIE, String::new(), Duration::ZERO); | ||
| 162 | + | ||
| 163 | + let query = query.map(|Form(query)| query).unwrap_or_default(); | ||
| 164 | + // `im` reported an error. Its text is not shown or reflected; the reason word is fixed. | ||
| 165 | + if !query.error.is_empty() { | ||
| 166 | + return Ok(problem(REASON_FAILED)); | ||
| 167 | + } | ||
| 168 | + let Some(oidc) = client(state) else { | ||
| 169 | + return Ok(problem(REASON_UNAVAILABLE)); | ||
| 170 | + }; | ||
| 171 | + let Some(flight) = sealed_flight.and_then(|sealed| read_flight(state, &sealed)) else { | ||
| 172 | + return Ok(problem(REASON_FAILED)); | ||
| 173 | + }; | ||
| 174 | + if query.code.is_empty() || !constant_time_eq(query.state.as_bytes(), flight.state.as_bytes()) { | ||
| 175 | + return Ok(problem(REASON_FAILED)); | ||
| 176 | + } | ||
| 177 | + | ||
| 178 | + let id_token = match oidc.exchange_code(&query.code, &flight.verifier).await { | ||
| 179 | + Ok(token) => token, | ||
| 180 | + Err(error) => return Ok(problem_for(&error)), | ||
| 181 | + }; | ||
| 182 | + let claims = match oidc.verify_id_token(&id_token, &flight.nonce).await { | ||
| 183 | + Ok(claims) => claims, | ||
| 184 | + Err(error) => return Ok(problem_for(&error)), | ||
| 185 | + }; | ||
| 186 | + | ||
| 187 | + let member = state | ||
| 188 | + .store | ||
| 189 | + .upsert_member_from_claims( | ||
| 190 | + &MemberFields { | ||
| 191 | + sub: claims.sub.clone(), | ||
| 192 | + email: claims.email, | ||
| 193 | + name: claims.name, | ||
| 194 | + is_admin: claims.admin, | ||
| 195 | + locale: claims.locale, | ||
| 196 | + zoneinfo: claims.zoneinfo, | ||
| 197 | + picture_version: claims.picture_version, | ||
| 198 | + // Sign-in claims carry no directory timestamp, so the store uses the sign-in time. | ||
| 199 | + im_updated_at: String::new(), | ||
| 200 | + }, | ||
| 201 | + DEFAULT_MEMBER_QUOTA, | ||
| 202 | + ) | ||
| 203 | + .await?; | ||
| 204 | + if member.disabled { | ||
| 205 | + return Ok(problem(REASON_DENIED)); | ||
| 206 | + } | ||
| 207 | + | ||
| 208 | + // A new sign-in replaces the session it started from, so an old token cannot stay alive. | ||
| 209 | + if let Some(old) = cookie_value(cx, SESSION_COOKIE) | ||
| 210 | + && let Some(session) = state.store.session_by_token_hash(&hash_token(&old)).await? | ||
| 211 | + { | ||
| 212 | + state.store.delete_session(&session.id).await?; | ||
| 213 | + } | ||
| 214 | + | ||
| 215 | + let token = generate_token(); | ||
| 216 | + let id_token_sealed = seal(state, id_token.as_bytes())?; | ||
| 217 | + let user_agent = headers(cx) | ||
| 218 | + .get(USER_AGENT) | ||
| 219 | + .and_then(|value| value.to_str().ok()) | ||
| 220 | + .map(|value| value.chars().take(MAX_USER_AGENT_CHARS).collect()); | ||
| 221 | + state | ||
| 222 | + .store | ||
| 223 | + .create_session(NewSession { | ||
| 224 | + sub: claims.sub, | ||
| 225 | + token_hash: hash_token(&token), | ||
| 226 | + csrf_token: generate_token(), | ||
| 227 | + im_sid: claims.sid, | ||
| 228 | + expires_at: stamp_after(SESSION_TTL), | ||
| 229 | + ip: client_ip(cx).map(|ip| ip.to_string()), | ||
| 230 | + user_agent, | ||
| 231 | + id_token_sealed: Some(id_token_sealed), | ||
| 232 | + }) | ||
| 233 | + .await?; | ||
| 234 | + set_cookie(cx, SESSION_COOKIE, token, SESSION_TTL); | ||
| 235 | + Ok(see_other(next_or_home(&flight.next))) | ||
| 236 | +} | ||
| 237 | + | ||
| 238 | +/// `POST /auth/logout`. Ends the local session, then ends the `im` session with RP-initiated logout. | ||
| 239 | +/// | ||
| 240 | +/// Without a session there is nothing to end, so the answer is the start page. A session with a missing | ||
| 241 | +/// or wrong CSRF token is refused with `403` before anything changes. | ||
| 242 | +#[route(POST "/auth/logout")] | ||
| 243 | +async fn logout(cx: &Cx, Form(form): Form<LogoutForm>) -> Result<SeeOther> { | ||
| 244 | + let state = app_context::<AppState>(cx); | ||
| 245 | + let Some(session) = current_session(cx).await? else { | ||
| 246 | + set_cookie(cx, SESSION_COOKIE, String::new(), Duration::ZERO); | ||
| 247 | + return Ok(see_other("/")); | ||
| 248 | + }; | ||
| 249 | + if !csrf_matches(&session, &form.csrf) { | ||
| 250 | + return Err(forbidden().into()); | ||
| 251 | + } | ||
| 252 | + state.store.delete_session(&session.id).await?; | ||
| 253 | + set_cookie(cx, SESSION_COOKIE, String::new(), Duration::ZERO); | ||
| 254 | + | ||
| 255 | + let hint = session | ||
| 256 | + .id_token_sealed | ||
| 257 | + .as_deref() | ||
| 258 | + .and_then(|sealed| open(state, sealed)) | ||
| 259 | + .and_then(|bytes| String::from_utf8(bytes).ok()); | ||
| 260 | + let (Some(oidc), Some(hint)) = (client(state), hint) else { | ||
| 261 | + return Ok(see_other("/")); | ||
| 262 | + }; | ||
| 263 | + let post_logout = format!("{}/", state.config.base_url); | ||
| 264 | + match oidc | ||
| 265 | + .end_session_url(&hint, &post_logout, &generate_token()) | ||
| 266 | + .await | ||
| 267 | + { | ||
| 268 | + Ok(url) => Ok(see_other(url)), | ||
| 269 | + Err(error) => { | ||
| 270 | + tracing::warn!(error = %error, "logout: cannot build the im logout URL"); | ||
| 271 | + Ok(see_other("/")) | ||
| 272 | + } | ||
| 273 | + } | ||
| 274 | +} | ||
| 275 | + | ||
| 276 | +/// The query of the problem page. The reason is matched against the fixed words; anything else is a | ||
| 277 | +/// failed sign-in. | ||
| 278 | +#[topcoat::router::query_params] | ||
| 279 | +pub struct ProblemQuery { | ||
| 280 | + /// One of the reason words above. | ||
| 281 | + pub reason: Option<String>, | ||
| 282 | +} | ||
| 283 | + | ||
| 284 | +/// `GET /sign-in/problem?reason=`. Explains a sign-in that did not finish, with a way back. | ||
| 285 | +#[page("/sign-in/problem")] | ||
| 286 | +async fn problem_page(cx: &Cx) -> Result<impl View> { | ||
| 287 | + let lang = lang(cx, None); | ||
| 288 | + let reason = topcoat::router::query_params::<ProblemQuery>(cx) | ||
| 289 | + .ok() | ||
| 290 | + .and_then(|query| query.reason.as_deref()) | ||
| 291 | + .unwrap_or(REASON_FAILED); | ||
| 292 | + let (status, title, body) = match reason { | ||
| 293 | + REASON_UNAVAILABLE => ( | ||
| 294 | + StatusCode::SERVICE_UNAVAILABLE, | ||
| 295 | + K::ProblemUnavailableTitle, | ||
| 296 | + K::ProblemUnavailableBody, | ||
| 297 | + ), | ||
| 298 | + REASON_DENIED => ( | ||
| 299 | + StatusCode::FORBIDDEN, | ||
| 300 | + K::ProblemDeniedTitle, | ||
| 301 | + K::ProblemDeniedBody, | ||
| 302 | + ), | ||
| 303 | + _ => ( | ||
| 304 | + StatusCode::BAD_REQUEST, | ||
| 305 | + K::ProblemFailedTitle, | ||
| 306 | + K::ProblemFailedBody, | ||
| 307 | + ), | ||
| 308 | + }; | ||
| 309 | + Ok(view! { | ||
| 310 | + (status) | ||
| 311 | + shell(title: t(lang, title), lang: lang, viewer: None, | ||
| 312 | + <section class="card"> | ||
| 313 | + <p class="kicker">"in"</p> | ||
| 314 | + <h1>(t(lang, title))</h1> | ||
| 315 | + <p>(t(lang, body))</p> | ||
| 316 | + <a class="button primary" href="/">(t(lang, K::BackHome))</a> | ||
| 317 | + </section> | ||
| 318 | + ) | ||
| 319 | + }) | ||
| 320 | +} | ||
| 321 | + | ||
| 322 | +#[cfg(test)] | ||
| 323 | +mod tests { | ||
| 324 | + use super::*; | ||
| 325 | + use crate::boot::{router, test_state}; | ||
| 326 | + use http::Request; | ||
| 327 | + use http::header::{CONTENT_TYPE, COOKIE}; | ||
| 328 | + use in_core::store::members::MemberFields; | ||
| 329 | + use topcoat::router::Body; | ||
| 330 | + | ||
| 331 | + #[tokio::test] | ||
| 332 | + async fn logout_without_the_csrf_token_is_refused_and_ends_nothing() { | ||
| 333 | + let (_dir, state) = test_state().await; | ||
| 334 | + state | ||
| 335 | + .store | ||
| 336 | + .upsert_member_from_claims( | ||
| 337 | + &MemberFields { | ||
| 338 | + sub: "01JANN".into(), | ||
| 339 | + email: "ann@example.test".into(), | ||
| 340 | + name: "Ann".into(), | ||
| 341 | + is_admin: false, | ||
| 342 | + locale: "en".into(), | ||
| 343 | + zoneinfo: "UTC".into(), | ||
| 344 | + picture_version: 0, | ||
| 345 | + im_updated_at: String::new(), | ||
| 346 | + }, | ||
| 347 | + DEFAULT_MEMBER_QUOTA, | ||
| 348 | + ) | ||
| 349 | + .await | ||
| 350 | + .expect("member"); | ||
| 351 | + let token = "session-token-for-the-test"; | ||
| 352 | + state | ||
| 353 | + .store | ||
| 354 | + .create_session(NewSession { | ||
| 355 | + sub: "01JANN".into(), | ||
| 356 | + token_hash: hash_token(token), | ||
| 357 | + csrf_token: "the-real-csrf-token".into(), | ||
| 358 | + im_sid: "im-session".into(), | ||
| 359 | + expires_at: stamp_after(SESSION_TTL), | ||
| 360 | + ip: None, | ||
| 361 | + user_agent: None, | ||
| 362 | + id_token_sealed: None, | ||
| 363 | + }) | ||
| 364 | + .await | ||
| 365 | + .expect("session"); | ||
| 366 | + | ||
| 367 | + let request = Request::post("/auth/logout") | ||
| 368 | + .header(COOKIE, format!("{SESSION_COOKIE}={token}")) | ||
| 369 | + .header(CONTENT_TYPE, "application/x-www-form-urlencoded") | ||
| 370 | + .body(Body::from("")) | ||
| 371 | + .expect("request"); | ||
| 372 | + let response = router(state.clone()).handle(request).await; | ||
| 373 | + | ||
| 374 | + assert_eq!(response.status(), 403); | ||
| 375 | + assert!( | ||
| 376 | + state | ||
| 377 | + .store | ||
| 378 | + .session_by_token_hash(&hash_token(token)) | ||
| 379 | + .await | ||
| 380 | + .expect("lookup") | ||
| 381 | + .is_some(), | ||
| 382 | + "a refused logout must leave the session alone" | ||
| 383 | + ); | ||
| 384 | + } | ||
| 385 | +} | ||
crates/in-web/src/state.rsmodified+5 -1
| @@ -7,9 +7,10 @@ use in_core::config::Config; | |||
| 7 | use in_core::store::Store; | 7 | use in_core::store::Store; |
| 8 | 8 | ||
| 9 | use crate::live::LiveHub; | 9 | use crate::live::LiveHub; |
| 10 | +use crate::oidc::OidcClient; | ||
| 10 | 11 | ||
| 11 | /// Everything a request handler reaches through the app context. Every field is cheap to clone. | 12 | /// Everything a request handler reaches through the app context. Every field is cheap to clone. |
| 12 | -#[allow(dead_code)] // The key and the hub are read by the sign-in and live pages that come next. | 13 | +#[allow(dead_code)] // The live hub is read by the live pages, which come after sign-in. |
| 13 | #[derive(Clone)] | 14 | #[derive(Clone)] |
| 14 | pub struct AppState { | 15 | pub struct AppState { |
| 15 | /// The configuration the process booted with. | 16 | /// The configuration the process booted with. |
| @@ -22,4 +23,7 @@ pub struct AppState { | |||
| 22 | pub key: Arc<[u8; 32]>, | 23 | pub key: Arc<[u8; 32]>, |
| 23 | /// The change counters of the live pages. | 24 | /// The change counters of the live pages. |
| 24 | pub live: Arc<LiveHub>, | 25 | pub live: Arc<LiveHub>, |
| 26 | + /// The OpenID Connect client of `im`. `None` when the configuration has no `[oidc]` table, in which | ||
| 27 | + /// case nobody can sign in and the sign-in routes say so. | ||
| 28 | + pub oidc: Option<Arc<OidcClient>>, | ||
| 25 | } | 29 | } |
crates/in-web/src/views/mod.rsmodified+13 -5
| @@ -10,21 +10,23 @@ 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, the administrator badge, and the CSRF |
| 14 | -/// is built for an anonymous viewer. | 14 | +/// token of the session for the sign-out form. |
| 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 topbar. |
| 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, which the sign-out form sends. | ||
| 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 |
| 24 | /// app name. `child` is the page, placed in `<main>`. | 25 | /// app name. `child` is the page, placed in `<main>`. |
| 25 | /// | 26 | /// |
| 26 | /// The topbar has the wordmark on the left, the service switcher in the middle (empty for now) and | 27 | /// The topbar has the wordmark on the left, the service switcher in the middle (empty for now) and |
| 27 | -/// the viewer's name on the right. `nav.js` reads the restart text from `<body data-restart-text>`. | 28 | +/// the viewer's user menu on the right. The menu's sign-out form opts out of soft navigation, because |
| 29 | +/// it ends in a redirect to `im`. `nav.js` reads the restart text from `<body data-restart-text>`. | ||
| 28 | #[component] | 30 | #[component] |
| 29 | pub async fn shell( | 31 | pub async fn shell( |
| 30 | title: &str, | 32 | title: &str, |
| @@ -51,7 +53,13 @@ pub async fn shell( | |||
| 51 | <nav class="switcher" aria-label=(t(lang, K::Services))></nav> | 53 | <nav class="switcher" aria-label=(t(lang, K::Services))></nav> |
| 52 | <div class="topbar-end"> | 54 | <div class="topbar-end"> |
| 53 | if let Some(viewer) = viewer { | 55 | if let Some(viewer) = viewer { |
| 54 | - <span>(viewer.name.as_str())</span> | 56 | + <details class="user-menu"> |
| 57 | + <summary>(viewer.name.as_str())</summary> | ||
| 58 | + <form method="post" action="/auth/logout" data-hard=""> | ||
| 59 | + <input type="hidden" name="csrf" value=(viewer.csrf.as_str())> | ||
| 60 | + <button class="button" type="submit">(t(lang, K::SignOut))</button> | ||
| 61 | + </form> | ||
| 62 | + </details> | ||
| 55 | if viewer.is_admin { | 63 | if viewer.is_admin { |
| 56 | <span class="badge accent">(t(lang, K::Admin))</span> | 64 | <span class="badge accent">(t(lang, K::Admin))</span> |
| 57 | } | 65 | } |