Core: sniffing, quota, authz, blob backends (local, s3), staging and drive store
Browse files at this commit810b0f6cbcde5a1753d5925ab1313018d9eacba0Parent: c997f70- feat
- core: sniffing, quota, authz, blob backends (local, s3), staging and drive store
17 changed files +4152 -6
- Cargo.lock +899 -4
- Cargo.toml +4 -0
- crates/in-core/Cargo.toml +4 -0
- crates/in-core/src/authz.rs +272 -0
- crates/in-core/src/blob/local.rs +292 -0
- crates/in-core/src/blob/mod.rs +118 -0
- crates/in-core/src/blob/s3.rs +215 -0
- crates/in-core/src/lib.rs +8 -2
- crates/in-core/src/quota.rs +47 -0
- crates/in-core/src/sniff.rs +247 -0
- crates/in-core/src/staging.rs +151 -0
- crates/in-core/src/store/files.rs +322 -0
- crates/in-core/src/store/folders.rs +351 -0
- crates/in-core/src/store/members.rs +271 -0
- crates/in-core/src/store/mod.rs +97 -0
- crates/in-core/src/store/sessions.rs +273 -0
- crates/in-core/src/store/trash.rs +581 -0
Cargo.lockmodified+899 -4
| @@ -167,12 +167,41 @@ dependencies = [ | ||
| 167 | 167 | "syn 3.0.9", |
| 168 | 168 | ] |
| 169 | 169 | |
| 170 | +[[package]] | |
| 171 | +name = "atomic-waker" | |
| 172 | +version = "1.1.2" | |
| 173 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 174 | +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" | |
| 175 | + | |
| 170 | 176 | [[package]] |
| 171 | 177 | name = "autocfg" |
| 172 | 178 | version = "1.5.1" |
| 173 | 179 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 174 | 180 | checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" |
| 175 | 181 | |
| 182 | +[[package]] | |
| 183 | +name = "aws-lc-rs" | |
| 184 | +version = "1.18.2" | |
| 185 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 186 | +checksum = "faac5829c2b74c28f830747e7818ccfb684261b5f48a1118b1e2a13d36dfab13" | |
| 187 | +dependencies = [ | |
| 188 | + "aws-lc-sys", | |
| 189 | + "zeroize", | |
| 190 | +] | |
| 191 | + | |
| 192 | +[[package]] | |
| 193 | +name = "aws-lc-sys" | |
| 194 | +version = "0.46.0" | |
| 195 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 196 | +checksum = "f1622d8446a2d4b2ce0c7eefc73dd43a99779028d5ee5c2dd8073a658ba8a2bc" | |
| 197 | +dependencies = [ | |
| 198 | + "cc", | |
| 199 | + "cmake", | |
| 200 | + "dunce", | |
| 201 | + "fs_extra", | |
| 202 | + "pkg-config", | |
| 203 | +] | |
| 204 | + | |
| 176 | 205 | [[package]] |
| 177 | 206 | name = "base64" |
| 178 | 207 | version = "0.22.1" |
| @@ -260,7 +289,7 @@ version = "0.11.0" | ||
| 260 | 289 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 261 | 290 | checksum = "5b5d4d889834ee8ecfc0f8426ad30faf7cdcb10f741a8e6d7224d95325479f6f" |
| 262 | 291 | dependencies = [ |
| 263 | - "digest", | |
| 292 | + "digest 0.11.3", | |
| 264 | 293 | ] |
| 265 | 294 | |
| 266 | 295 | [[package]] |
| @@ -420,6 +449,7 @@ dependencies = [ | ||
| 420 | 449 | "iana-time-zone", |
| 421 | 450 | "js-sys", |
| 422 | 451 | "num-traits", |
| 452 | + "serde", | |
| 423 | 453 | "wasm-bindgen", |
| 424 | 454 | "windows-link", |
| 425 | 455 | ] |
| @@ -456,12 +486,31 @@ dependencies = [ | ||
| 456 | 486 | "libloading", |
| 457 | 487 | ] |
| 458 | 488 | |
| 489 | +[[package]] | |
| 490 | +name = "cmake" | |
| 491 | +version = "0.1.58" | |
| 492 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 493 | +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" | |
| 494 | +dependencies = [ | |
| 495 | + "cc", | |
| 496 | +] | |
| 497 | + | |
| 459 | 498 | [[package]] |
| 460 | 499 | name = "cmov" |
| 461 | 500 | version = "0.5.4" |
| 462 | 501 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 463 | 502 | checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" |
| 464 | 503 | |
| 504 | +[[package]] | |
| 505 | +name = "combine" | |
| 506 | +version = "4.6.9" | |
| 507 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 508 | +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" | |
| 509 | +dependencies = [ | |
| 510 | + "bytes", | |
| 511 | + "memchr", | |
| 512 | +] | |
| 513 | + | |
| 465 | 514 | [[package]] |
| 466 | 515 | name = "concurrent-queue" |
| 467 | 516 | version = "2.5.0" |
| @@ -477,6 +526,16 @@ version = "0.10.2" | ||
| 477 | 526 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 478 | 527 | checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" |
| 479 | 528 | |
| 529 | +[[package]] | |
| 530 | +name = "core-foundation" | |
| 531 | +version = "0.10.1" | |
| 532 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 533 | +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" | |
| 534 | +dependencies = [ | |
| 535 | + "core-foundation-sys", | |
| 536 | + "libc", | |
| 537 | +] | |
| 538 | + | |
| 480 | 539 | [[package]] |
| 481 | 540 | name = "core-foundation-sys" |
| 482 | 541 | version = "0.8.7" |
| @@ -501,6 +560,16 @@ dependencies = [ | ||
| 501 | 560 | "libc", |
| 502 | 561 | ] |
| 503 | 562 | |
| 563 | +[[package]] | |
| 564 | +name = "crc-fast" | |
| 565 | +version = "1.10.0" | |
| 566 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 567 | +checksum = "e75b2483e97a5a7da73ac68a05b629f9c53cff58d8ed1c77866079e18b00dba5" | |
| 568 | +dependencies = [ | |
| 569 | + "digest 0.10.7", | |
| 570 | + "spin", | |
| 571 | +] | |
| 572 | + | |
| 504 | 573 | [[package]] |
| 505 | 574 | name = "crc32c" |
| 506 | 575 | version = "0.6.8" |
| @@ -648,6 +717,15 @@ dependencies = [ | ||
| 648 | 717 | "serde_core", |
| 649 | 718 | ] |
| 650 | 719 | |
| 720 | +[[package]] | |
| 721 | +name = "digest" | |
| 722 | +version = "0.10.7" | |
| 723 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 724 | +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" | |
| 725 | +dependencies = [ | |
| 726 | + "crypto-common 0.1.7", | |
| 727 | +] | |
| 728 | + | |
| 651 | 729 | [[package]] |
| 652 | 730 | name = "digest" |
| 653 | 731 | version = "0.11.3" |
| @@ -677,6 +755,12 @@ version = "2.0.2" | ||
| 677 | 755 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 678 | 756 | checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc" |
| 679 | 757 | |
| 758 | +[[package]] | |
| 759 | +name = "dunce" | |
| 760 | +version = "1.0.5" | |
| 761 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 762 | +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" | |
| 763 | + | |
| 680 | 764 | [[package]] |
| 681 | 765 | name = "either" |
| 682 | 766 | version = "1.19.0" |
| @@ -777,6 +861,15 @@ version = "0.2.0" | ||
| 777 | 861 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 778 | 862 | checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" |
| 779 | 863 | |
| 864 | +[[package]] | |
| 865 | +name = "form_urlencoded" | |
| 866 | +version = "1.2.2" | |
| 867 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 868 | +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" | |
| 869 | +dependencies = [ | |
| 870 | + "percent-encoding", | |
| 871 | +] | |
| 872 | + | |
| 780 | 873 | [[package]] |
| 781 | 874 | name = "fs4" |
| 782 | 875 | version = "0.13.1" |
| @@ -787,18 +880,40 @@ dependencies = [ | ||
| 787 | 880 | "windows-sys 0.59.0", |
| 788 | 881 | ] |
| 789 | 882 | |
| 883 | +[[package]] | |
| 884 | +name = "fs_extra" | |
| 885 | +version = "1.3.0" | |
| 886 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 887 | +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" | |
| 888 | + | |
| 790 | 889 | [[package]] |
| 791 | 890 | name = "funty" |
| 792 | 891 | version = "2.0.0" |
| 793 | 892 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 794 | 893 | checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" |
| 795 | 894 | |
| 895 | +[[package]] | |
| 896 | +name = "futures-channel" | |
| 897 | +version = "0.3.34" | |
| 898 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 899 | +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" | |
| 900 | +dependencies = [ | |
| 901 | + "futures-core", | |
| 902 | + "futures-sink", | |
| 903 | +] | |
| 904 | + | |
| 796 | 905 | [[package]] |
| 797 | 906 | name = "futures-core" |
| 798 | 907 | version = "0.3.34" |
| 799 | 908 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 800 | 909 | checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" |
| 801 | 910 | |
| 911 | +[[package]] | |
| 912 | +name = "futures-io" | |
| 913 | +version = "0.3.34" | |
| 914 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 915 | +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" | |
| 916 | + | |
| 802 | 917 | [[package]] |
| 803 | 918 | name = "futures-macro" |
| 804 | 919 | version = "0.3.34" |
| @@ -810,6 +925,12 @@ dependencies = [ | ||
| 810 | 925 | "syn 3.0.9", |
| 811 | 926 | ] |
| 812 | 927 | |
| 928 | +[[package]] | |
| 929 | +name = "futures-sink" | |
| 930 | +version = "0.3.34" | |
| 931 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 932 | +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" | |
| 933 | + | |
| 813 | 934 | [[package]] |
| 814 | 935 | name = "futures-task" |
| 815 | 936 | version = "0.3.34" |
| @@ -823,8 +944,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 823 | 944 | checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" |
| 824 | 945 | dependencies = [ |
| 825 | 946 | "futures-core", |
| 947 | + "futures-io", | |
| 826 | 948 | "futures-macro", |
| 949 | + "futures-sink", | |
| 827 | 950 | "futures-task", |
| 951 | + "memchr", | |
| 828 | 952 | "pin-project-lite", |
| 829 | 953 | "slab", |
| 830 | 954 | ] |
| @@ -926,6 +1050,25 @@ version = "0.3.4" | ||
| 926 | 1050 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 927 | 1051 | checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" |
| 928 | 1052 | |
| 1053 | +[[package]] | |
| 1054 | +name = "h2" | |
| 1055 | +version = "0.4.20" | |
| 1056 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1057 | +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" | |
| 1058 | +dependencies = [ | |
| 1059 | + "atomic-waker", | |
| 1060 | + "bytes", | |
| 1061 | + "fnv", | |
| 1062 | + "futures-core", | |
| 1063 | + "futures-sink", | |
| 1064 | + "http", | |
| 1065 | + "indexmap", | |
| 1066 | + "slab", | |
| 1067 | + "tokio", | |
| 1068 | + "tokio-util", | |
| 1069 | + "tracing", | |
| 1070 | +] | |
| 1071 | + | |
| 929 | 1072 | [[package]] |
| 930 | 1073 | name = "hashbrown" |
| 931 | 1074 | version = "0.16.1" |
| @@ -967,7 +1110,7 @@ version = "0.13.0" | ||
| 967 | 1110 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 968 | 1111 | checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" |
| 969 | 1112 | dependencies = [ |
| 970 | - "digest", | |
| 1113 | + "digest 0.11.3", | |
| 971 | 1114 | ] |
| 972 | 1115 | |
| 973 | 1116 | [[package]] |
| @@ -995,6 +1138,41 @@ dependencies = [ | ||
| 995 | 1138 | "itoa", |
| 996 | 1139 | ] |
| 997 | 1140 | |
| 1141 | +[[package]] | |
| 1142 | +name = "http-body" | |
| 1143 | +version = "1.1.0" | |
| 1144 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1145 | +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" | |
| 1146 | +dependencies = [ | |
| 1147 | + "bytes", | |
| 1148 | + "http", | |
| 1149 | +] | |
| 1150 | + | |
| 1151 | +[[package]] | |
| 1152 | +name = "http-body-util" | |
| 1153 | +version = "0.1.5" | |
| 1154 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1155 | +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" | |
| 1156 | +dependencies = [ | |
| 1157 | + "bytes", | |
| 1158 | + "futures-core", | |
| 1159 | + "http", | |
| 1160 | + "http-body", | |
| 1161 | + "pin-project-lite", | |
| 1162 | +] | |
| 1163 | + | |
| 1164 | +[[package]] | |
| 1165 | +name = "httparse" | |
| 1166 | +version = "1.10.1" | |
| 1167 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1168 | +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" | |
| 1169 | + | |
| 1170 | +[[package]] | |
| 1171 | +name = "humantime" | |
| 1172 | +version = "2.4.0" | |
| 1173 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1174 | +checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15" | |
| 1175 | + | |
| 998 | 1176 | [[package]] |
| 999 | 1177 | name = "hybrid-array" |
| 1000 | 1178 | version = "0.4.15" |
| @@ -1004,6 +1182,66 @@ dependencies = [ | ||
| 1004 | 1182 | "typenum", |
| 1005 | 1183 | ] |
| 1006 | 1184 | |
| 1185 | +[[package]] | |
| 1186 | +name = "hyper" | |
| 1187 | +version = "1.12.0" | |
| 1188 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1189 | +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" | |
| 1190 | +dependencies = [ | |
| 1191 | + "atomic-waker", | |
| 1192 | + "bytes", | |
| 1193 | + "futures-channel", | |
| 1194 | + "futures-core", | |
| 1195 | + "h2", | |
| 1196 | + "http", | |
| 1197 | + "http-body", | |
| 1198 | + "httparse", | |
| 1199 | + "itoa", | |
| 1200 | + "pin-project-lite", | |
| 1201 | + "smallvec", | |
| 1202 | + "tokio", | |
| 1203 | + "want", | |
| 1204 | +] | |
| 1205 | + | |
| 1206 | +[[package]] | |
| 1207 | +name = "hyper-rustls" | |
| 1208 | +version = "0.27.10" | |
| 1209 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1210 | +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" | |
| 1211 | +dependencies = [ | |
| 1212 | + "http", | |
| 1213 | + "hyper", | |
| 1214 | + "hyper-util", | |
| 1215 | + "rustls", | |
| 1216 | + "tokio", | |
| 1217 | + "tokio-rustls", | |
| 1218 | + "tower-service", | |
| 1219 | +] | |
| 1220 | + | |
| 1221 | +[[package]] | |
| 1222 | +name = "hyper-util" | |
| 1223 | +version = "0.1.21" | |
| 1224 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1225 | +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" | |
| 1226 | +dependencies = [ | |
| 1227 | + "base64 0.23.1", | |
| 1228 | + "bytes", | |
| 1229 | + "futures-channel", | |
| 1230 | + "futures-util", | |
| 1231 | + "http", | |
| 1232 | + "http-body", | |
| 1233 | + "httparse", | |
| 1234 | + "hyper", | |
| 1235 | + "ipnet", | |
| 1236 | + "libc", | |
| 1237 | + "percent-encoding", | |
| 1238 | + "pin-project-lite", | |
| 1239 | + "socket2", | |
| 1240 | + "tokio", | |
| 1241 | + "tower-service", | |
| 1242 | + "tracing", | |
| 1243 | +] | |
| 1244 | + | |
| 1007 | 1245 | [[package]] |
| 1008 | 1246 | name = "iana-time-zone" |
| 1009 | 1247 | version = "0.1.65" |
| @@ -1189,16 +1427,41 @@ version = "1.0.1" | ||
| 1189 | 1427 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1190 | 1428 | checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" |
| 1191 | 1429 | |
| 1430 | +[[package]] | |
| 1431 | +name = "idna" | |
| 1432 | +version = "1.1.0" | |
| 1433 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1434 | +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" | |
| 1435 | +dependencies = [ | |
| 1436 | + "idna_adapter", | |
| 1437 | + "smallvec", | |
| 1438 | + "utf8_iter", | |
| 1439 | +] | |
| 1440 | + | |
| 1441 | +[[package]] | |
| 1442 | +name = "idna_adapter" | |
| 1443 | +version = "1.2.2" | |
| 1444 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1445 | +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" | |
| 1446 | +dependencies = [ | |
| 1447 | + "icu_normalizer", | |
| 1448 | + "icu_properties", | |
| 1449 | +] | |
| 1450 | + | |
| 1192 | 1451 | [[package]] |
| 1193 | 1452 | name = "in-core" |
| 1194 | 1453 | version = "0.1.0" |
| 1195 | 1454 | dependencies = [ |
| 1196 | 1455 | "argon2", |
| 1456 | + "async-trait", | |
| 1197 | 1457 | "base64 0.23.1", |
| 1458 | + "bytes", | |
| 1198 | 1459 | "chacha20poly1305", |
| 1460 | + "futures-util", | |
| 1199 | 1461 | "hex", |
| 1200 | 1462 | "hmac", |
| 1201 | 1463 | "ipnet", |
| 1464 | + "object_store", | |
| 1202 | 1465 | "rand 0.10.3", |
| 1203 | 1466 | "serde", |
| 1204 | 1467 | "serde_json", |
| @@ -1299,12 +1562,70 @@ dependencies = [ | ||
| 1299 | 1562 | "either", |
| 1300 | 1563 | ] |
| 1301 | 1564 | |
| 1565 | +[[package]] | |
| 1566 | +name = "itertools" | |
| 1567 | +version = "0.15.0" | |
| 1568 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1569 | +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" | |
| 1570 | +dependencies = [ | |
| 1571 | + "either", | |
| 1572 | +] | |
| 1573 | + | |
| 1302 | 1574 | [[package]] |
| 1303 | 1575 | name = "itoa" |
| 1304 | 1576 | version = "1.0.18" |
| 1305 | 1577 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1306 | 1578 | checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" |
| 1307 | 1579 | |
| 1580 | +[[package]] | |
| 1581 | +name = "jni" | |
| 1582 | +version = "0.22.4" | |
| 1583 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1584 | +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" | |
| 1585 | +dependencies = [ | |
| 1586 | + "cfg-if", | |
| 1587 | + "combine", | |
| 1588 | + "jni-macros", | |
| 1589 | + "jni-sys", | |
| 1590 | + "log", | |
| 1591 | + "simd_cesu8", | |
| 1592 | + "thiserror", | |
| 1593 | + "walkdir", | |
| 1594 | + "windows-link", | |
| 1595 | +] | |
| 1596 | + | |
| 1597 | +[[package]] | |
| 1598 | +name = "jni-macros" | |
| 1599 | +version = "0.22.4" | |
| 1600 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1601 | +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" | |
| 1602 | +dependencies = [ | |
| 1603 | + "proc-macro2", | |
| 1604 | + "quote", | |
| 1605 | + "rustc_version", | |
| 1606 | + "simd_cesu8", | |
| 1607 | + "syn 2.0.119", | |
| 1608 | +] | |
| 1609 | + | |
| 1610 | +[[package]] | |
| 1611 | +name = "jni-sys" | |
| 1612 | +version = "0.4.1" | |
| 1613 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1614 | +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" | |
| 1615 | +dependencies = [ | |
| 1616 | + "jni-sys-macros", | |
| 1617 | +] | |
| 1618 | + | |
| 1619 | +[[package]] | |
| 1620 | +name = "jni-sys-macros" | |
| 1621 | +version = "0.4.1" | |
| 1622 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1623 | +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" | |
| 1624 | +dependencies = [ | |
| 1625 | + "quote", | |
| 1626 | + "syn 2.0.119", | |
| 1627 | +] | |
| 1628 | + | |
| 1308 | 1629 | [[package]] |
| 1309 | 1630 | name = "jobserver" |
| 1310 | 1631 | version = "0.1.35" |
| @@ -1450,6 +1771,12 @@ dependencies = [ | ||
| 1450 | 1771 | "hashbrown 0.16.1", |
| 1451 | 1772 | ] |
| 1452 | 1773 | |
| 1774 | +[[package]] | |
| 1775 | +name = "lru-slab" | |
| 1776 | +version = "0.1.3" | |
| 1777 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1778 | +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" | |
| 1779 | + | |
| 1453 | 1780 | [[package]] |
| 1454 | 1781 | name = "lz4_flex" |
| 1455 | 1782 | version = "0.13.1" |
| @@ -1465,6 +1792,16 @@ dependencies = [ | ||
| 1465 | 1792 | "regex-automata", |
| 1466 | 1793 | ] |
| 1467 | 1794 | |
| 1795 | +[[package]] | |
| 1796 | +name = "md-5" | |
| 1797 | +version = "0.11.0" | |
| 1798 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1799 | +checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" | |
| 1800 | +dependencies = [ | |
| 1801 | + "cfg-if", | |
| 1802 | + "digest 0.11.3", | |
| 1803 | +] | |
| 1804 | + | |
| 1468 | 1805 | [[package]] |
| 1469 | 1806 | name = "measure_time" |
| 1470 | 1807 | version = "0.9.0" |
| @@ -1535,12 +1872,35 @@ version = "0.2.1" | ||
| 1535 | 1872 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1536 | 1873 | checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" |
| 1537 | 1874 | |
| 1875 | +[[package]] | |
| 1876 | +name = "mio" | |
| 1877 | +version = "1.2.4" | |
| 1878 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1879 | +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" | |
| 1880 | +dependencies = [ | |
| 1881 | + "libc", | |
| 1882 | + "wasi", | |
| 1883 | + "windows-sys 0.61.2", | |
| 1884 | +] | |
| 1885 | + | |
| 1538 | 1886 | [[package]] |
| 1539 | 1887 | name = "murmurhash32" |
| 1540 | 1888 | version = "0.3.1" |
| 1541 | 1889 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1542 | 1890 | checksum = "2195bf6aa996a481483b29d62a7663eed3fe39600c460e323f8ff41e90bdd89b" |
| 1543 | 1891 | |
| 1892 | +[[package]] | |
| 1893 | +name = "nix" | |
| 1894 | +version = "0.31.3" | |
| 1895 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1896 | +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" | |
| 1897 | +dependencies = [ | |
| 1898 | + "bitflags", | |
| 1899 | + "cfg-if", | |
| 1900 | + "cfg_aliases", | |
| 1901 | + "libc", | |
| 1902 | +] | |
| 1903 | + | |
| 1544 | 1904 | [[package]] |
| 1545 | 1905 | name = "nom" |
| 1546 | 1906 | version = "7.1.3" |
| @@ -1594,6 +1954,48 @@ dependencies = [ | ||
| 1594 | 1954 | "autocfg", |
| 1595 | 1955 | ] |
| 1596 | 1956 | |
| 1957 | +[[package]] | |
| 1958 | +name = "object_store" | |
| 1959 | +version = "0.14.2" | |
| 1960 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1961 | +checksum = "f1796bc93603f78c5760a69f2d58badc9618d22adade0a95385bb2adbae4eb94" | |
| 1962 | +dependencies = [ | |
| 1963 | + "async-trait", | |
| 1964 | + "aws-lc-rs", | |
| 1965 | + "base64 0.23.1", | |
| 1966 | + "bytes", | |
| 1967 | + "chrono", | |
| 1968 | + "crc-fast", | |
| 1969 | + "form_urlencoded", | |
| 1970 | + "futures-channel", | |
| 1971 | + "futures-core", | |
| 1972 | + "futures-util", | |
| 1973 | + "http", | |
| 1974 | + "http-body-util", | |
| 1975 | + "humantime", | |
| 1976 | + "hyper", | |
| 1977 | + "itertools 0.15.0", | |
| 1978 | + "md-5", | |
| 1979 | + "nix", | |
| 1980 | + "parking_lot", | |
| 1981 | + "percent-encoding", | |
| 1982 | + "quick-xml", | |
| 1983 | + "rand 0.10.3", | |
| 1984 | + "reqwest", | |
| 1985 | + "rustls-pki-types", | |
| 1986 | + "serde", | |
| 1987 | + "serde_json", | |
| 1988 | + "serde_urlencoded", | |
| 1989 | + "thiserror", | |
| 1990 | + "tokio", | |
| 1991 | + "tracing", | |
| 1992 | + "url", | |
| 1993 | + "walkdir", | |
| 1994 | + "wasm-bindgen-futures", | |
| 1995 | + "web-time", | |
| 1996 | + "windows-sys 0.61.2", | |
| 1997 | +] | |
| 1998 | + | |
| 1597 | 1999 | [[package]] |
| 1598 | 2000 | name = "once_cell" |
| 1599 | 2001 | version = "1.21.4" |
| @@ -1612,6 +2014,12 @@ version = "0.3.1" | ||
| 1612 | 2014 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1613 | 2015 | checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" |
| 1614 | 2016 | |
| 2017 | +[[package]] | |
| 2018 | +name = "openssl-probe" | |
| 2019 | +version = "0.2.2" | |
| 2020 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2021 | +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" | |
| 2022 | + | |
| 1615 | 2023 | [[package]] |
| 1616 | 2024 | name = "ordered-float" |
| 1617 | 2025 | version = "5.5.1" |
| @@ -1684,6 +2092,12 @@ version = "0.2.3" | ||
| 1684 | 2092 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1685 | 2093 | checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" |
| 1686 | 2094 | |
| 2095 | +[[package]] | |
| 2096 | +name = "percent-encoding" | |
| 2097 | +version = "2.3.2" | |
| 2098 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2099 | +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" | |
| 2100 | + | |
| 1687 | 2101 | [[package]] |
| 1688 | 2102 | name = "phc" |
| 1689 | 2103 | version = "0.6.1" |
| @@ -1821,6 +2235,73 @@ dependencies = [ | ||
| 1821 | 2235 | "syn 2.0.119", |
| 1822 | 2236 | ] |
| 1823 | 2237 | |
| 2238 | +[[package]] | |
| 2239 | +name = "quick-xml" | |
| 2240 | +version = "0.41.0" | |
| 2241 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2242 | +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" | |
| 2243 | +dependencies = [ | |
| 2244 | + "memchr", | |
| 2245 | + "serde", | |
| 2246 | +] | |
| 2247 | + | |
| 2248 | +[[package]] | |
| 2249 | +name = "quinn" | |
| 2250 | +version = "0.11.12" | |
| 2251 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2252 | +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" | |
| 2253 | +dependencies = [ | |
| 2254 | + "bytes", | |
| 2255 | + "cfg_aliases", | |
| 2256 | + "pin-project-lite", | |
| 2257 | + "quinn-proto", | |
| 2258 | + "quinn-udp", | |
| 2259 | + "rustc-hash 2.1.3", | |
| 2260 | + "rustls", | |
| 2261 | + "socket2", | |
| 2262 | + "thiserror", | |
| 2263 | + "tokio", | |
| 2264 | + "tracing", | |
| 2265 | + "web-time", | |
| 2266 | +] | |
| 2267 | + | |
| 2268 | +[[package]] | |
| 2269 | +name = "quinn-proto" | |
| 2270 | +version = "0.11.19" | |
| 2271 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2272 | +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" | |
| 2273 | +dependencies = [ | |
| 2274 | + "aws-lc-rs", | |
| 2275 | + "bytes", | |
| 2276 | + "getrandom 0.4.3", | |
| 2277 | + "lru-slab", | |
| 2278 | + "rand 0.10.3", | |
| 2279 | + "rand_pcg 0.10.2", | |
| 2280 | + "ring", | |
| 2281 | + "rustc-hash 2.1.3", | |
| 2282 | + "rustls", | |
| 2283 | + "rustls-pki-types", | |
| 2284 | + "slab", | |
| 2285 | + "thiserror", | |
| 2286 | + "tinyvec", | |
| 2287 | + "tracing", | |
| 2288 | + "web-time", | |
| 2289 | +] | |
| 2290 | + | |
| 2291 | +[[package]] | |
| 2292 | +name = "quinn-udp" | |
| 2293 | +version = "0.5.16" | |
| 2294 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2295 | +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" | |
| 2296 | +dependencies = [ | |
| 2297 | + "cfg_aliases", | |
| 2298 | + "libc", | |
| 2299 | + "once_cell", | |
| 2300 | + "socket2", | |
| 2301 | + "tracing", | |
| 2302 | + "windows-sys 0.61.2", | |
| 2303 | +] | |
| 2304 | + | |
| 1824 | 2305 | [[package]] |
| 1825 | 2306 | name = "quote" |
| 1826 | 2307 | version = "1.0.47" |
| @@ -1933,6 +2414,15 @@ dependencies = [ | ||
| 1933 | 2414 | "rand_core 0.6.4", |
| 1934 | 2415 | ] |
| 1935 | 2416 | |
| 2417 | +[[package]] | |
| 2418 | +name = "rand_pcg" | |
| 2419 | +version = "0.10.2" | |
| 2420 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2421 | +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" | |
| 2422 | +dependencies = [ | |
| 2423 | + "rand_core 0.10.1", | |
| 2424 | +] | |
| 2425 | + | |
| 1936 | 2426 | [[package]] |
| 1937 | 2427 | name = "rapidhash" |
| 1938 | 2428 | version = "4.5.1" |
| @@ -2000,6 +2490,59 @@ version = "0.8.11" | ||
| 2000 | 2490 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2001 | 2491 | checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" |
| 2002 | 2492 | |
| 2493 | +[[package]] | |
| 2494 | +name = "reqwest" | |
| 2495 | +version = "0.13.5" | |
| 2496 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2497 | +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" | |
| 2498 | +dependencies = [ | |
| 2499 | + "base64 0.23.1", | |
| 2500 | + "bytes", | |
| 2501 | + "futures-core", | |
| 2502 | + "futures-util", | |
| 2503 | + "h2", | |
| 2504 | + "http", | |
| 2505 | + "http-body", | |
| 2506 | + "http-body-util", | |
| 2507 | + "hyper", | |
| 2508 | + "hyper-rustls", | |
| 2509 | + "hyper-util", | |
| 2510 | + "js-sys", | |
| 2511 | + "log", | |
| 2512 | + "percent-encoding", | |
| 2513 | + "pin-project-lite", | |
| 2514 | + "quinn", | |
| 2515 | + "rustls", | |
| 2516 | + "rustls-pki-types", | |
| 2517 | + "rustls-platform-verifier", | |
| 2518 | + "sync_wrapper", | |
| 2519 | + "tokio", | |
| 2520 | + "tokio-rustls", | |
| 2521 | + "tokio-util", | |
| 2522 | + "tower", | |
| 2523 | + "tower-http", | |
| 2524 | + "tower-service", | |
| 2525 | + "url", | |
| 2526 | + "wasm-bindgen", | |
| 2527 | + "wasm-bindgen-futures", | |
| 2528 | + "wasm-streams", | |
| 2529 | + "web-sys", | |
| 2530 | +] | |
| 2531 | + | |
| 2532 | +[[package]] | |
| 2533 | +name = "ring" | |
| 2534 | +version = "0.17.14" | |
| 2535 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2536 | +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" | |
| 2537 | +dependencies = [ | |
| 2538 | + "cc", | |
| 2539 | + "cfg-if", | |
| 2540 | + "getrandom 0.2.17", | |
| 2541 | + "libc", | |
| 2542 | + "untrusted", | |
| 2543 | + "windows-sys 0.52.0", | |
| 2544 | +] | |
| 2545 | + | |
| 2003 | 2546 | [[package]] |
| 2004 | 2547 | name = "roaring" |
| 2005 | 2548 | version = "0.11.5" |
| @@ -2077,6 +2620,81 @@ dependencies = [ | ||
| 2077 | 2620 | "windows-sys 0.61.2", |
| 2078 | 2621 | ] |
| 2079 | 2622 | |
| 2623 | +[[package]] | |
| 2624 | +name = "rustls" | |
| 2625 | +version = "0.23.46" | |
| 2626 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2627 | +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" | |
| 2628 | +dependencies = [ | |
| 2629 | + "aws-lc-rs", | |
| 2630 | + "once_cell", | |
| 2631 | + "rustls-pki-types", | |
| 2632 | + "rustls-webpki", | |
| 2633 | + "subtle", | |
| 2634 | + "zeroize", | |
| 2635 | +] | |
| 2636 | + | |
| 2637 | +[[package]] | |
| 2638 | +name = "rustls-native-certs" | |
| 2639 | +version = "0.8.5" | |
| 2640 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2641 | +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" | |
| 2642 | +dependencies = [ | |
| 2643 | + "openssl-probe", | |
| 2644 | + "rustls-pki-types", | |
| 2645 | + "schannel", | |
| 2646 | + "security-framework", | |
| 2647 | +] | |
| 2648 | + | |
| 2649 | +[[package]] | |
| 2650 | +name = "rustls-pki-types" | |
| 2651 | +version = "1.15.1" | |
| 2652 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2653 | +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" | |
| 2654 | +dependencies = [ | |
| 2655 | + "web-time", | |
| 2656 | + "zeroize", | |
| 2657 | +] | |
| 2658 | + | |
| 2659 | +[[package]] | |
| 2660 | +name = "rustls-platform-verifier" | |
| 2661 | +version = "0.7.1" | |
| 2662 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2663 | +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" | |
| 2664 | +dependencies = [ | |
| 2665 | + "core-foundation", | |
| 2666 | + "core-foundation-sys", | |
| 2667 | + "jni", | |
| 2668 | + "log", | |
| 2669 | + "once_cell", | |
| 2670 | + "rustls", | |
| 2671 | + "rustls-native-certs", | |
| 2672 | + "rustls-platform-verifier-android", | |
| 2673 | + "rustls-webpki", | |
| 2674 | + "security-framework", | |
| 2675 | + "security-framework-sys", | |
| 2676 | + "webpki-root-certs", | |
| 2677 | + "windows-sys 0.61.2", | |
| 2678 | +] | |
| 2679 | + | |
| 2680 | +[[package]] | |
| 2681 | +name = "rustls-platform-verifier-android" | |
| 2682 | +version = "0.2.0" | |
| 2683 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2684 | +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" | |
| 2685 | + | |
| 2686 | +[[package]] | |
| 2687 | +name = "rustls-webpki" | |
| 2688 | +version = "0.103.16" | |
| 2689 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2690 | +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" | |
| 2691 | +dependencies = [ | |
| 2692 | + "aws-lc-rs", | |
| 2693 | + "ring", | |
| 2694 | + "rustls-pki-types", | |
| 2695 | + "untrusted", | |
| 2696 | +] | |
| 2697 | + | |
| 2080 | 2698 | [[package]] |
| 2081 | 2699 | name = "rustversion" |
| 2082 | 2700 | version = "1.0.23" |
| @@ -2089,6 +2707,24 @@ version = "1.0.23" | ||
| 2089 | 2707 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2090 | 2708 | checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" |
| 2091 | 2709 | |
| 2710 | +[[package]] | |
| 2711 | +name = "same-file" | |
| 2712 | +version = "1.0.6" | |
| 2713 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2714 | +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" | |
| 2715 | +dependencies = [ | |
| 2716 | + "winapi-util", | |
| 2717 | +] | |
| 2718 | + | |
| 2719 | +[[package]] | |
| 2720 | +name = "schannel" | |
| 2721 | +version = "0.1.30" | |
| 2722 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2723 | +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" | |
| 2724 | +dependencies = [ | |
| 2725 | + "windows-sys 0.61.2", | |
| 2726 | +] | |
| 2727 | + | |
| 2092 | 2728 | [[package]] |
| 2093 | 2729 | name = "scoped-tls" |
| 2094 | 2730 | version = "1.0.1" |
| @@ -2101,6 +2737,29 @@ version = "1.2.0" | ||
| 2101 | 2737 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2102 | 2738 | checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" |
| 2103 | 2739 | |
| 2740 | +[[package]] | |
| 2741 | +name = "security-framework" | |
| 2742 | +version = "3.7.0" | |
| 2743 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2744 | +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" | |
| 2745 | +dependencies = [ | |
| 2746 | + "bitflags", | |
| 2747 | + "core-foundation", | |
| 2748 | + "core-foundation-sys", | |
| 2749 | + "libc", | |
| 2750 | + "security-framework-sys", | |
| 2751 | +] | |
| 2752 | + | |
| 2753 | +[[package]] | |
| 2754 | +name = "security-framework-sys" | |
| 2755 | +version = "2.17.0" | |
| 2756 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2757 | +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" | |
| 2758 | +dependencies = [ | |
| 2759 | + "core-foundation-sys", | |
| 2760 | + "libc", | |
| 2761 | +] | |
| 2762 | + | |
| 2104 | 2763 | [[package]] |
| 2105 | 2764 | name = "semver" |
| 2106 | 2765 | version = "1.0.28" |
| @@ -2159,6 +2818,18 @@ dependencies = [ | ||
| 2159 | 2818 | "serde_core", |
| 2160 | 2819 | ] |
| 2161 | 2820 | |
| 2821 | +[[package]] | |
| 2822 | +name = "serde_urlencoded" | |
| 2823 | +version = "0.7.1" | |
| 2824 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2825 | +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" | |
| 2826 | +dependencies = [ | |
| 2827 | + "form_urlencoded", | |
| 2828 | + "itoa", | |
| 2829 | + "ryu", | |
| 2830 | + "serde", | |
| 2831 | +] | |
| 2832 | + | |
| 2162 | 2833 | [[package]] |
| 2163 | 2834 | name = "sha1_smol" |
| 2164 | 2835 | version = "1.0.1" |
| @@ -2173,7 +2844,7 @@ checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" | ||
| 2173 | 2844 | dependencies = [ |
| 2174 | 2845 | "cfg-if", |
| 2175 | 2846 | "cpufeatures 0.3.1", |
| 2176 | - "digest", | |
| 2847 | + "digest 0.11.3", | |
| 2177 | 2848 | ] |
| 2178 | 2849 | |
| 2179 | 2850 | [[package]] |
| @@ -2211,12 +2882,22 @@ dependencies = [ | ||
| 2211 | 2882 | "owo-colors", |
| 2212 | 2883 | "rand 0.8.8", |
| 2213 | 2884 | "rand_core 0.6.4", |
| 2214 | - "rand_pcg", | |
| 2885 | + "rand_pcg 0.3.1", | |
| 2215 | 2886 | "scoped-tls", |
| 2216 | 2887 | "smallvec", |
| 2217 | 2888 | "tracing", |
| 2218 | 2889 | ] |
| 2219 | 2890 | |
| 2891 | +[[package]] | |
| 2892 | +name = "simd_cesu8" | |
| 2893 | +version = "1.2.0" | |
| 2894 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2895 | +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" | |
| 2896 | +dependencies = [ | |
| 2897 | + "rustc_version", | |
| 2898 | + "simdutf8", | |
| 2899 | +] | |
| 2900 | + | |
| 2220 | 2901 | [[package]] |
| 2221 | 2902 | name = "simdutf8" |
| 2222 | 2903 | version = "0.1.5" |
| @@ -2259,12 +2940,28 @@ version = "1.16.4" | ||
| 2259 | 2940 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2260 | 2941 | checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" |
| 2261 | 2942 | |
| 2943 | +[[package]] | |
| 2944 | +name = "socket2" | |
| 2945 | +version = "0.6.5" | |
| 2946 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2947 | +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" | |
| 2948 | +dependencies = [ | |
| 2949 | + "libc", | |
| 2950 | + "windows-sys 0.61.2", | |
| 2951 | +] | |
| 2952 | + | |
| 2262 | 2953 | [[package]] |
| 2263 | 2954 | name = "softaes" |
| 2264 | 2955 | version = "0.1.7" |
| 2265 | 2956 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2266 | 2957 | checksum = "c4fdfe13e1c42e45f497416afb8dc4e783bf0e25b7be9077c1c77c5fb14cb998" |
| 2267 | 2958 | |
| 2959 | +[[package]] | |
| 2960 | +name = "spin" | |
| 2961 | +version = "0.10.1" | |
| 2962 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 2963 | +checksum = "023a211cb3138dbc438680b32560ad89f699977624c9f8dbb95a47d5b4c07dd3" | |
| 2964 | + | |
| 2268 | 2965 | [[package]] |
| 2269 | 2966 | name = "stable_deref_trait" |
| 2270 | 2967 | version = "1.2.1" |
| @@ -2333,6 +3030,15 @@ dependencies = [ | ||
| 2333 | 3030 | "unicode-ident", |
| 2334 | 3031 | ] |
| 2335 | 3032 | |
| 3033 | +[[package]] | |
| 3034 | +name = "sync_wrapper" | |
| 3035 | +version = "1.0.2" | |
| 3036 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3037 | +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" | |
| 3038 | +dependencies = [ | |
| 3039 | + "futures-core", | |
| 3040 | +] | |
| 3041 | + | |
| 2336 | 3042 | [[package]] |
| 2337 | 3043 | name = "synstructure" |
| 2338 | 3044 | version = "0.14.0" |
| @@ -2581,6 +3287,12 @@ dependencies = [ | ||
| 2581 | 3287 | "zerovec", |
| 2582 | 3288 | ] |
| 2583 | 3289 | |
| 3290 | +[[package]] | |
| 3291 | +name = "tinyvec" | |
| 3292 | +version = "1.13.3" | |
| 3293 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3294 | +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" | |
| 3295 | + | |
| 2584 | 3296 | [[package]] |
| 2585 | 3297 | name = "tokio" |
| 2586 | 3298 | version = "1.54.1" |
| @@ -2588,8 +3300,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2588 | 3300 | checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" |
| 2589 | 3301 | dependencies = [ |
| 2590 | 3302 | "bytes", |
| 3303 | + "libc", | |
| 3304 | + "mio", | |
| 2591 | 3305 | "pin-project-lite", |
| 3306 | + "socket2", | |
| 2592 | 3307 | "tokio-macros", |
| 3308 | + "windows-sys 0.61.2", | |
| 2593 | 3309 | ] |
| 2594 | 3310 | |
| 2595 | 3311 | [[package]] |
| @@ -2603,6 +3319,30 @@ dependencies = [ | ||
| 2603 | 3319 | "syn 3.0.9", |
| 2604 | 3320 | ] |
| 2605 | 3321 | |
| 3322 | +[[package]] | |
| 3323 | +name = "tokio-rustls" | |
| 3324 | +version = "0.26.6" | |
| 3325 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3326 | +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" | |
| 3327 | +dependencies = [ | |
| 3328 | + "rustls", | |
| 3329 | + "tokio", | |
| 3330 | +] | |
| 3331 | + | |
| 3332 | +[[package]] | |
| 3333 | +name = "tokio-util" | |
| 3334 | +version = "0.7.20" | |
| 3335 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3336 | +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" | |
| 3337 | +dependencies = [ | |
| 3338 | + "bytes", | |
| 3339 | + "futures-core", | |
| 3340 | + "futures-sink", | |
| 3341 | + "libc", | |
| 3342 | + "pin-project-lite", | |
| 3343 | + "tokio", | |
| 3344 | +] | |
| 3345 | + | |
| 2606 | 3346 | [[package]] |
| 2607 | 3347 | name = "toml" |
| 2608 | 3348 | version = "1.1.8+spec-1.1.0" |
| @@ -2642,6 +3382,51 @@ version = "1.1.3+spec-1.1.0" | ||
| 2642 | 3382 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2643 | 3383 | checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" |
| 2644 | 3384 | |
| 3385 | +[[package]] | |
| 3386 | +name = "tower" | |
| 3387 | +version = "0.5.3" | |
| 3388 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3389 | +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" | |
| 3390 | +dependencies = [ | |
| 3391 | + "futures-core", | |
| 3392 | + "futures-util", | |
| 3393 | + "pin-project-lite", | |
| 3394 | + "sync_wrapper", | |
| 3395 | + "tokio", | |
| 3396 | + "tower-layer", | |
| 3397 | + "tower-service", | |
| 3398 | +] | |
| 3399 | + | |
| 3400 | +[[package]] | |
| 3401 | +name = "tower-http" | |
| 3402 | +version = "0.6.11" | |
| 3403 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3404 | +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" | |
| 3405 | +dependencies = [ | |
| 3406 | + "bitflags", | |
| 3407 | + "bytes", | |
| 3408 | + "futures-util", | |
| 3409 | + "http", | |
| 3410 | + "http-body", | |
| 3411 | + "pin-project-lite", | |
| 3412 | + "tower", | |
| 3413 | + "tower-layer", | |
| 3414 | + "tower-service", | |
| 3415 | + "url", | |
| 3416 | +] | |
| 3417 | + | |
| 3418 | +[[package]] | |
| 3419 | +name = "tower-layer" | |
| 3420 | +version = "0.3.3" | |
| 3421 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3422 | +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" | |
| 3423 | + | |
| 3424 | +[[package]] | |
| 3425 | +name = "tower-service" | |
| 3426 | +version = "0.3.3" | |
| 3427 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3428 | +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" | |
| 3429 | + | |
| 2645 | 3430 | [[package]] |
| 2646 | 3431 | name = "tracing" |
| 2647 | 3432 | version = "0.1.44" |
| @@ -2716,6 +3501,12 @@ dependencies = [ | ||
| 2716 | 3501 | "tracing-log", |
| 2717 | 3502 | ] |
| 2718 | 3503 | |
| 3504 | +[[package]] | |
| 3505 | +name = "try-lock" | |
| 3506 | +version = "0.2.5" | |
| 3507 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3508 | +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" | |
| 3509 | + | |
| 2719 | 3510 | [[package]] |
| 2720 | 3511 | name = "turso" |
| 2721 | 3512 | version = "0.8.3" |
| @@ -3009,6 +3800,24 @@ dependencies = [ | ||
| 3009 | 3800 | "ctutils", |
| 3010 | 3801 | ] |
| 3011 | 3802 | |
| 3803 | +[[package]] | |
| 3804 | +name = "untrusted" | |
| 3805 | +version = "0.9.0" | |
| 3806 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3807 | +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" | |
| 3808 | + | |
| 3809 | +[[package]] | |
| 3810 | +name = "url" | |
| 3811 | +version = "2.5.8" | |
| 3812 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3813 | +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" | |
| 3814 | +dependencies = [ | |
| 3815 | + "form_urlencoded", | |
| 3816 | + "idna", | |
| 3817 | + "percent-encoding", | |
| 3818 | + "serde", | |
| 3819 | +] | |
| 3820 | + | |
| 3012 | 3821 | [[package]] |
| 3013 | 3822 | name = "utf16_iter" |
| 3014 | 3823 | version = "1.0.5" |
| @@ -3052,6 +3861,25 @@ version = "0.9.5" | ||
| 3052 | 3861 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 3053 | 3862 | checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" |
| 3054 | 3863 | |
| 3864 | +[[package]] | |
| 3865 | +name = "walkdir" | |
| 3866 | +version = "2.5.0" | |
| 3867 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3868 | +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" | |
| 3869 | +dependencies = [ | |
| 3870 | + "same-file", | |
| 3871 | + "winapi-util", | |
| 3872 | +] | |
| 3873 | + | |
| 3874 | +[[package]] | |
| 3875 | +name = "want" | |
| 3876 | +version = "0.3.2" | |
| 3877 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3878 | +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" | |
| 3879 | +dependencies = [ | |
| 3880 | + "try-lock", | |
| 3881 | +] | |
| 3882 | + | |
| 3055 | 3883 | [[package]] |
| 3056 | 3884 | name = "wasi" |
| 3057 | 3885 | version = "0.11.1+wasi-snapshot-preview1" |
| @@ -3080,6 +3908,17 @@ dependencies = [ | ||
| 3080 | 3908 | "wasm-bindgen-shared", |
| 3081 | 3909 | ] |
| 3082 | 3910 | |
| 3911 | +[[package]] | |
| 3912 | +name = "wasm-bindgen-futures" | |
| 3913 | +version = "0.4.79" | |
| 3914 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3915 | +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" | |
| 3916 | +dependencies = [ | |
| 3917 | + "js-sys", | |
| 3918 | + "tokio", | |
| 3919 | + "wasm-bindgen", | |
| 3920 | +] | |
| 3921 | + | |
| 3083 | 3922 | [[package]] |
| 3084 | 3923 | name = "wasm-bindgen-macro" |
| 3085 | 3924 | version = "0.2.129" |
| @@ -3112,6 +3951,29 @@ dependencies = [ | ||
| 3112 | 3951 | "unicode-ident", |
| 3113 | 3952 | ] |
| 3114 | 3953 | |
| 3954 | +[[package]] | |
| 3955 | +name = "wasm-streams" | |
| 3956 | +version = "0.5.0" | |
| 3957 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3958 | +checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" | |
| 3959 | +dependencies = [ | |
| 3960 | + "futures-util", | |
| 3961 | + "js-sys", | |
| 3962 | + "wasm-bindgen", | |
| 3963 | + "wasm-bindgen-futures", | |
| 3964 | + "web-sys", | |
| 3965 | +] | |
| 3966 | + | |
| 3967 | +[[package]] | |
| 3968 | +name = "web-sys" | |
| 3969 | +version = "0.3.106" | |
| 3970 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3971 | +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" | |
| 3972 | +dependencies = [ | |
| 3973 | + "js-sys", | |
| 3974 | + "wasm-bindgen", | |
| 3975 | +] | |
| 3976 | + | |
| 3115 | 3977 | [[package]] |
| 3116 | 3978 | name = "web-time" |
| 3117 | 3979 | version = "1.1.0" |
| @@ -3122,6 +3984,15 @@ dependencies = [ | ||
| 3122 | 3984 | "wasm-bindgen", |
| 3123 | 3985 | ] |
| 3124 | 3986 | |
| 3987 | +[[package]] | |
| 3988 | +name = "webpki-root-certs" | |
| 3989 | +version = "1.0.11" | |
| 3990 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 3991 | +checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" | |
| 3992 | +dependencies = [ | |
| 3993 | + "rustls-pki-types", | |
| 3994 | +] | |
| 3995 | + | |
| 3125 | 3996 | [[package]] |
| 3126 | 3997 | name = "which" |
| 3127 | 3998 | version = "4.4.2" |
| @@ -3150,6 +4021,15 @@ version = "0.4.0" | ||
| 3150 | 4021 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 3151 | 4022 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" |
| 3152 | 4023 | |
| 4024 | +[[package]] | |
| 4025 | +name = "winapi-util" | |
| 4026 | +version = "0.1.11" | |
| 4027 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 4028 | +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" | |
| 4029 | +dependencies = [ | |
| 4030 | + "windows-sys 0.61.2", | |
| 4031 | +] | |
| 4032 | + | |
| 3153 | 4033 | [[package]] |
| 3154 | 4034 | name = "winapi-x86_64-pc-windows-gnu" |
| 3155 | 4035 | version = "0.4.0" |
| @@ -3215,6 +4095,15 @@ dependencies = [ | ||
| 3215 | 4095 | "windows-link", |
| 3216 | 4096 | ] |
| 3217 | 4097 | |
| 4098 | +[[package]] | |
| 4099 | +name = "windows-sys" | |
| 4100 | +version = "0.52.0" | |
| 4101 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 4102 | +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" | |
| 4103 | +dependencies = [ | |
| 4104 | + "windows-targets", | |
| 4105 | +] | |
| 4106 | + | |
| 3218 | 4107 | [[package]] |
| 3219 | 4108 | name = "windows-sys" |
| 3220 | 4109 | version = "0.59.0" |
| @@ -3394,6 +4283,12 @@ dependencies = [ | ||
| 3394 | 4283 | "synstructure", |
| 3395 | 4284 | ] |
| 3396 | 4285 | |
| 4286 | +[[package]] | |
| 4287 | +name = "zeroize" | |
| 4288 | +version = "1.9.1" | |
| 4289 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 4290 | +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" | |
| 4291 | + | |
| 3397 | 4292 | [[package]] |
| 3398 | 4293 | name = "zerotrie" |
| 3399 | 4294 | version = "0.2.5" |
Cargo.tomlmodified+4 -0
| @@ -41,11 +41,15 @@ codegen-units = 1 | ||
| 41 | 41 | |
| 42 | 42 | [workspace.dependencies] |
| 43 | 43 | argon2 = "0.6.0" |
| 44 | +async-trait = "0.1.92" | |
| 44 | 45 | base64 = "0.23.1" |
| 46 | +bytes = "1.12.1" | |
| 45 | 47 | chacha20poly1305 = "0.11.0" |
| 48 | +futures-util = "0.3.34" | |
| 46 | 49 | hex = "0.4.3" |
| 47 | 50 | hmac = "0.13.0" |
| 48 | 51 | ipnet = "2.12.2" |
| 52 | +object_store = { version = "0.14.2", features = ["aws"] } | |
| 49 | 53 | rand = "0.10.3" |
| 50 | 54 | serde = "1.0.229" |
| 51 | 55 | serde_json = "1.0.154" |
crates/in-core/Cargo.tomlmodified+4 -0
| @@ -8,11 +8,15 @@ publish = false | ||
| 8 | 8 | |
| 9 | 9 | [dependencies] |
| 10 | 10 | argon2.workspace = true |
| 11 | +async-trait.workspace = true | |
| 11 | 12 | base64.workspace = true |
| 13 | +bytes.workspace = true | |
| 12 | 14 | chacha20poly1305.workspace = true |
| 15 | +futures-util.workspace = true | |
| 13 | 16 | hex.workspace = true |
| 14 | 17 | hmac.workspace = true |
| 15 | 18 | ipnet.workspace = true |
| 19 | +object_store.workspace = true | |
| 16 | 20 | rand.workspace = true |
| 17 | 21 | serde = { workspace = true, features = ["derive"] } |
| 18 | 22 | serde_json.workspace = true |
crates/in-core/src/authz.rsadded+272 -0
| @@ -0,0 +1,272 @@ | ||
| 1 | +//! Authorization for drive items: one pure function that every page, form, API route and live stream | |
| 2 | +//! calls before it acts. A denial is either `NotFound` (the viewer must not learn that the item exists) | |
| 3 | +//! or `Forbidden` (the viewer can see the item but may not do this). | |
| 4 | +//! | |
| 5 | +//! Rules (architecture section 6): | |
| 6 | +//! - Anonymous and service callers never reach drive items. | |
| 7 | +//! - The owner may do everything on live items except `Purge` and `Restore`, which apply to trashed | |
| 8 | +//! items only. On trashed items the owner may only view, download, restore and purge. | |
| 9 | +//! - An admin may `Administer` any item but reads nobody else's files. | |
| 10 | +//! - A grantee sees a live item with a grant, lists and views it, and downloads it only with a | |
| 11 | +//! download grant. Nothing else. | |
| 12 | +//! - A link visitor is a grantee for the link's subtree (`Target::inside_link`) with the link's download | |
| 13 | +//! setting. | |
| 14 | + | |
| 15 | +/// Who is asking. | |
| 16 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 17 | +pub enum Actor<'a> { | |
| 18 | + /// Nobody signed in. | |
| 19 | + Anonymous, | |
| 20 | + /// A signed-in person. | |
| 21 | + Member { | |
| 22 | + /// The OIDC subject of the person. | |
| 23 | + sub: &'a str, | |
| 24 | + /// Whether the person is an instance administrator. | |
| 25 | + is_admin: bool, | |
| 26 | + }, | |
| 27 | + /// A visitor who opened a validated public share link. | |
| 28 | + Link { | |
| 29 | + /// Whether the link allows downloads. | |
| 30 | + can_download: bool, | |
| 31 | + }, | |
| 32 | + /// A machine caller of another family app. It has no access to drive items. | |
| 33 | + Service { | |
| 34 | + /// The service key from the token's `svc` claim. | |
| 35 | + key: &'a str, | |
| 36 | + }, | |
| 37 | +} | |
| 38 | + | |
| 39 | +/// The item being asked about. | |
| 40 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 41 | +pub struct Target<'a> { | |
| 42 | + /// The owner of the item. | |
| 43 | + pub owner: &'a str, | |
| 44 | + /// Whether the item or one of its ancestors is in the trash. | |
| 45 | + pub trashed: bool, | |
| 46 | + /// For link visitors: whether the item lies inside the linked folder (or is the linked item). | |
| 47 | + pub inside_link: bool, | |
| 48 | +} | |
| 49 | + | |
| 50 | +/// The most permissive grant that applies to the item: a direct grant on it or on any live ancestor. | |
| 51 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] | |
| 52 | +pub enum Grant { | |
| 53 | + /// No grant applies. | |
| 54 | + None, | |
| 55 | + /// The grantee may see and open the item. | |
| 56 | + View, | |
| 57 | + /// The grantee may also download it. | |
| 58 | + Download, | |
| 59 | +} | |
| 60 | + | |
| 61 | +/// What the actor wants to do. | |
| 62 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 63 | +pub enum Action { | |
| 64 | + /// See the item in a listing or search. | |
| 65 | + List, | |
| 66 | + /// Open the item and preview its bytes inline. | |
| 67 | + View, | |
| 68 | + /// Download the bytes. | |
| 69 | + Download, | |
| 70 | + /// Rename, move, upload into, or trash. | |
| 71 | + Write, | |
| 72 | + /// Restore a trashed item to its place. | |
| 73 | + Restore, | |
| 74 | + /// Change who can see the item (grants and links). | |
| 75 | + Share, | |
| 76 | + /// Permanently delete a trashed item. | |
| 77 | + Purge, | |
| 78 | + /// Administer the instance. | |
| 79 | + Administer, | |
| 80 | +} | |
| 81 | + | |
| 82 | +/// Why an action was refused. | |
| 83 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 84 | +pub enum Denied { | |
| 85 | + /// The item is hidden from this actor, or the action is not something it may know about. | |
| 86 | + NotFound, | |
| 87 | + /// The actor can see the item but may not do this. | |
| 88 | + Forbidden, | |
| 89 | +} | |
| 90 | + | |
| 91 | +/// Decides whether `actor` may perform `action` on `target`, given the effective `grant`. | |
| 92 | +pub fn authorize( | |
| 93 | + actor: Actor<'_>, | |
| 94 | + target: Target<'_>, | |
| 95 | + grant: Grant, | |
| 96 | + action: Action, | |
| 97 | +) -> Result<(), Denied> { | |
| 98 | + match actor { | |
| 99 | + Actor::Anonymous | Actor::Service { .. } => Err(Denied::NotFound), | |
| 100 | + Actor::Link { can_download } => { | |
| 101 | + if !target.inside_link || target.trashed { | |
| 102 | + return Err(Denied::NotFound); | |
| 103 | + } | |
| 104 | + match action { | |
| 105 | + Action::List | Action::View => Ok(()), | |
| 106 | + Action::Download if can_download => Ok(()), | |
| 107 | + Action::Download => Err(Denied::Forbidden), | |
| 108 | + Action::Administer => Err(Denied::NotFound), | |
| 109 | + _ => Err(Denied::Forbidden), | |
| 110 | + } | |
| 111 | + } | |
| 112 | + Actor::Member { is_admin, .. } if is_admin && action == Action::Administer => Ok(()), | |
| 113 | + Actor::Member { sub, .. } if sub == target.owner => owner_rule(target.trashed, action), | |
| 114 | + Actor::Member { .. } => { | |
| 115 | + if target.trashed || grant == Grant::None || action == Action::Administer { | |
| 116 | + return Err(Denied::NotFound); | |
| 117 | + } | |
| 118 | + match action { | |
| 119 | + Action::List | Action::View => Ok(()), | |
| 120 | + Action::Download if grant == Grant::Download => Ok(()), | |
| 121 | + _ => Err(Denied::Forbidden), | |
| 122 | + } | |
| 123 | + } | |
| 124 | + } | |
| 125 | +} | |
| 126 | + | |
| 127 | +/// The owner's rule: everything on live items, and only the trash actions on trashed ones. | |
| 128 | +fn owner_rule(trashed: bool, action: Action) -> Result<(), Denied> { | |
| 129 | + match (trashed, action) { | |
| 130 | + (_, Action::Administer) => Err(Denied::NotFound), | |
| 131 | + (false, Action::Purge | Action::Restore) => Err(Denied::Forbidden), | |
| 132 | + (false, _) => Ok(()), | |
| 133 | + (true, Action::View | Action::Download | Action::Restore | Action::Purge) => Ok(()), | |
| 134 | + (true, _) => Err(Denied::Forbidden), | |
| 135 | + } | |
| 136 | +} | |
| 137 | + | |
| 138 | +#[cfg(test)] | |
| 139 | +mod tests { | |
| 140 | + use super::*; | |
| 141 | + | |
| 142 | + const OWNER: &str = "owner"; | |
| 143 | + const OTHER: &str = "other"; | |
| 144 | + | |
| 145 | + fn live() -> Target<'static> { | |
| 146 | + Target { | |
| 147 | + owner: OWNER, | |
| 148 | + trashed: false, | |
| 149 | + inside_link: false, | |
| 150 | + } | |
| 151 | + } | |
| 152 | + | |
| 153 | + fn trashed() -> Target<'static> { | |
| 154 | + Target { | |
| 155 | + trashed: true, | |
| 156 | + ..live() | |
| 157 | + } | |
| 158 | + } | |
| 159 | + | |
| 160 | + fn owner() -> Actor<'static> { | |
| 161 | + Actor::Member { | |
| 162 | + sub: OWNER, | |
| 163 | + is_admin: false, | |
| 164 | + } | |
| 165 | + } | |
| 166 | + | |
| 167 | + fn grantee() -> Actor<'static> { | |
| 168 | + Actor::Member { | |
| 169 | + sub: OTHER, | |
| 170 | + is_admin: false, | |
| 171 | + } | |
| 172 | + } | |
| 173 | + | |
| 174 | + fn admin() -> Actor<'static> { | |
| 175 | + Actor::Member { | |
| 176 | + sub: "root", | |
| 177 | + is_admin: true, | |
| 178 | + } | |
| 179 | + } | |
| 180 | + | |
| 181 | + /// The truth table, one row per (actor, target, grant, action) with the expected answer. | |
| 182 | + #[test] | |
| 183 | + fn truth_table() { | |
| 184 | + use Action::*; | |
| 185 | + use Denied::*; | |
| 186 | + let link_dl = Actor::Link { can_download: true }; | |
| 187 | + let link_view = Actor::Link { | |
| 188 | + can_download: false, | |
| 189 | + }; | |
| 190 | + let inside = Target { | |
| 191 | + inside_link: true, | |
| 192 | + ..live() | |
| 193 | + }; | |
| 194 | + type Case<'a> = (Actor<'a>, Target<'a>, Grant, Action, Result<(), Denied>); | |
| 195 | + let cases: Vec<Case> = vec![ | |
| 196 | + // Anonymous and services never see drive items. | |
| 197 | + ( | |
| 198 | + Actor::Anonymous, | |
| 199 | + live(), | |
| 200 | + Grant::Download, | |
| 201 | + View, | |
| 202 | + Err(NotFound), | |
| 203 | + ), | |
| 204 | + ( | |
| 205 | + Actor::Service { key: "im" }, | |
| 206 | + live(), | |
| 207 | + Grant::Download, | |
| 208 | + List, | |
| 209 | + Err(NotFound), | |
| 210 | + ), | |
| 211 | + // Owner, live. | |
| 212 | + (owner(), live(), Grant::None, List, Ok(())), | |
| 213 | + (owner(), live(), Grant::None, View, Ok(())), | |
| 214 | + (owner(), live(), Grant::None, Download, Ok(())), | |
| 215 | + (owner(), live(), Grant::None, Write, Ok(())), | |
| 216 | + (owner(), live(), Grant::None, Share, Ok(())), | |
| 217 | + (owner(), live(), Grant::None, Purge, Err(Forbidden)), | |
| 218 | + (owner(), live(), Grant::None, Restore, Err(Forbidden)), | |
| 219 | + (owner(), live(), Grant::None, Administer, Err(NotFound)), | |
| 220 | + // Owner, trashed. | |
| 221 | + (owner(), trashed(), Grant::None, View, Ok(())), | |
| 222 | + (owner(), trashed(), Grant::None, Download, Ok(())), | |
| 223 | + (owner(), trashed(), Grant::None, Restore, Ok(())), | |
| 224 | + (owner(), trashed(), Grant::None, Purge, Ok(())), | |
| 225 | + (owner(), trashed(), Grant::None, Write, Err(Forbidden)), | |
| 226 | + (owner(), trashed(), Grant::None, Share, Err(Forbidden)), | |
| 227 | + (owner(), trashed(), Grant::None, List, Err(Forbidden)), | |
| 228 | + // Grantee with view only, live. | |
| 229 | + (grantee(), live(), Grant::View, List, Ok(())), | |
| 230 | + (grantee(), live(), Grant::View, View, Ok(())), | |
| 231 | + (grantee(), live(), Grant::View, Download, Err(Forbidden)), | |
| 232 | + (grantee(), live(), Grant::View, Write, Err(Forbidden)), | |
| 233 | + // Grantee with download. | |
| 234 | + (grantee(), live(), Grant::Download, Download, Ok(())), | |
| 235 | + (grantee(), live(), Grant::Download, Share, Err(Forbidden)), | |
| 236 | + // Grantee without any grant, or on a trashed item, learns nothing. | |
| 237 | + (grantee(), live(), Grant::None, View, Err(NotFound)), | |
| 238 | + (grantee(), trashed(), Grant::Download, View, Err(NotFound)), | |
| 239 | + // Admin: administers, but reads nobody else's files. | |
| 240 | + (admin(), live(), Grant::None, Administer, Ok(())), | |
| 241 | + (admin(), live(), Grant::None, View, Err(NotFound)), | |
| 242 | + // An admin who holds no grant on someone else's item sees nothing of it. | |
| 243 | + (admin(), live(), Grant::None, Download, Err(NotFound)), | |
| 244 | + // With a grant the admin is simply a grantee. | |
| 245 | + (admin(), live(), Grant::Download, Download, Ok(())), | |
| 246 | + // Owner who is also admin keeps the owner rules. | |
| 247 | + ( | |
| 248 | + Actor::Member { | |
| 249 | + sub: OWNER, | |
| 250 | + is_admin: true, | |
| 251 | + }, | |
| 252 | + live(), | |
| 253 | + Grant::None, | |
| 254 | + Write, | |
| 255 | + Ok(()), | |
| 256 | + ), | |
| 257 | + // Link visitors. | |
| 258 | + (link_dl, inside, Grant::None, Download, Ok(())), | |
| 259 | + (link_view, inside, Grant::None, Download, Err(Forbidden)), | |
| 260 | + (link_view, inside, Grant::None, View, Ok(())), | |
| 261 | + (link_dl, live(), Grant::None, View, Err(NotFound)), | |
| 262 | + (link_dl, trashed(), Grant::None, View, Err(NotFound)), | |
| 263 | + ]; | |
| 264 | + for (actor, target, grant, action, want) in cases { | |
| 265 | + assert_eq!( | |
| 266 | + authorize(actor, target, grant, action), | |
| 267 | + want, | |
| 268 | + "actor {actor:?}, target {target:?}, grant {grant:?}, action {action:?}" | |
| 269 | + ); | |
| 270 | + } | |
| 271 | + } | |
| 272 | +} |
crates/in-core/src/blob/local.rsadded+292 -0
| @@ -0,0 +1,292 @@ | ||
| 1 | +//! The local-disk blob backend. Blobs are plain files under one root directory, named by their key. | |
| 2 | +//! | |
| 3 | +//! Writes go to a temporary file in the destination directory, are fsynced, renamed into place, and the | |
| 4 | +//! directory is fsynced, so a crash leaves either the old state or the whole new blob. Files are created | |
| 5 | +//! with mode 0600 and directories with 0700. Blocking filesystem work runs on `spawn_blocking`. | |
| 6 | + | |
| 7 | +use std::fs::{self, File}; | |
| 8 | +use std::io::{self, Read, Seek, SeekFrom}; | |
| 9 | +use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt}; | |
| 10 | +use std::path::{Path, PathBuf}; | |
| 11 | +use std::time::SystemTime; | |
| 12 | + | |
| 13 | +use async_trait::async_trait; | |
| 14 | +use bytes::Bytes; | |
| 15 | +use futures_util::stream; | |
| 16 | + | |
| 17 | +use super::{BlobEntry, BlobStore, BlobStream, FRAME_BYTES, validate_key}; | |
| 18 | +use crate::error::{Error, Result}; | |
| 19 | + | |
| 20 | +/// Blobs kept as files under `root`. | |
| 21 | +#[derive(Debug, Clone)] | |
| 22 | +pub struct LocalBlobs { | |
| 23 | + root: PathBuf, | |
| 24 | +} | |
| 25 | + | |
| 26 | +impl LocalBlobs { | |
| 27 | + /// Uses `root` as the blob directory, creating it with mode 0700 when missing. | |
| 28 | + pub fn new(root: impl Into<PathBuf>) -> Result<Self> { | |
| 29 | + let root = root.into(); | |
| 30 | + create_dirs(&root)?; | |
| 31 | + Ok(Self { root }) | |
| 32 | + } | |
| 33 | + | |
| 34 | + /// The on-disk path of `key`. The key must already be validated. | |
| 35 | + fn path_of(&self, key: &str) -> PathBuf { | |
| 36 | + self.root.join(key) | |
| 37 | + } | |
| 38 | +} | |
| 39 | + | |
| 40 | +/// Creates `dir` and its parents with mode 0700. Existing directories are left alone. | |
| 41 | +fn create_dirs(dir: &Path) -> io::Result<()> { | |
| 42 | + fs::DirBuilder::new() | |
| 43 | + .recursive(true) | |
| 44 | + .mode(0o700) | |
| 45 | + .create(dir) | |
| 46 | +} | |
| 47 | + | |
| 48 | +/// Fsyncs a directory so that a rename inside it survives a crash. | |
| 49 | +fn sync_dir(dir: &Path) -> io::Result<()> { | |
| 50 | + File::open(dir)?.sync_all() | |
| 51 | +} | |
| 52 | + | |
| 53 | +/// Moves `src` to `dest` atomically. Rename is tried first; a file on another filesystem is copied to a | |
| 54 | +/// temporary file beside `dest` and then renamed, so `dest` is never half written. | |
| 55 | +fn place_file(src: &Path, dest: &Path, temp: &Path) -> io::Result<()> { | |
| 56 | + if fs::rename(src, temp).is_err() { | |
| 57 | + let mut from = File::open(src)?; | |
| 58 | + let mut to = create_private(temp)?; | |
| 59 | + io::copy(&mut from, &mut to)?; | |
| 60 | + to.sync_all()?; | |
| 61 | + drop(to); | |
| 62 | + fs::remove_file(src)?; | |
| 63 | + } | |
| 64 | + File::open(temp)?.sync_all()?; | |
| 65 | + fs::rename(temp, dest)?; | |
| 66 | + Ok(()) | |
| 67 | +} | |
| 68 | + | |
| 69 | +/// Creates a file that did not exist, with mode 0600. | |
| 70 | +fn create_private(path: &Path) -> io::Result<File> { | |
| 71 | + fs::OpenOptions::new() | |
| 72 | + .write(true) | |
| 73 | + .create_new(true) | |
| 74 | + .mode(0o600) | |
| 75 | + .open(path) | |
| 76 | +} | |
| 77 | + | |
| 78 | +/// Blocking half of [`BlobStore::put_file`]. | |
| 79 | +fn put_blocking(path_of_key: PathBuf, src: PathBuf) -> Result<()> { | |
| 80 | + let Some(dir) = path_of_key.parent().map(Path::to_path_buf) else { | |
| 81 | + return Err(Error::Invalid("bad_key".into())); | |
| 82 | + }; | |
| 83 | + create_dirs(&dir)?; | |
| 84 | + // A temporary name that no valid key can take: keys have no upper case and no leading dot. | |
| 85 | + let temp = dir.join(format!(".{}.tmp", ulid::Ulid::generate())); | |
| 86 | + place_file(&src, &path_of_key, &temp)?; | |
| 87 | + fs::set_permissions(&path_of_key, fs::Permissions::from_mode(0o600))?; | |
| 88 | + sync_dir(&dir)?; | |
| 89 | + Ok(()) | |
| 90 | +} | |
| 91 | + | |
| 92 | +/// Blocking half of [`BlobStore::list`]: walks the tree under `root`. | |
| 93 | +fn list_blocking(root: PathBuf, prefix: String) -> Result<Vec<BlobEntry>> { | |
| 94 | + let mut out = Vec::new(); | |
| 95 | + let mut pending = vec![root.clone()]; | |
| 96 | + while let Some(dir) = pending.pop() { | |
| 97 | + let entries = match fs::read_dir(&dir) { | |
| 98 | + Ok(entries) => entries, | |
| 99 | + Err(e) if e.kind() == io::ErrorKind::NotFound => continue, | |
| 100 | + Err(e) => return Err(e.into()), | |
| 101 | + }; | |
| 102 | + for entry in entries { | |
| 103 | + let entry = entry?; | |
| 104 | + let name = entry.file_name(); | |
| 105 | + // Temporary files and anything else dot-named is not a blob. | |
| 106 | + if name.to_string_lossy().starts_with('.') { | |
| 107 | + continue; | |
| 108 | + } | |
| 109 | + let meta = entry.metadata()?; | |
| 110 | + if meta.is_dir() { | |
| 111 | + pending.push(entry.path()); | |
| 112 | + continue; | |
| 113 | + } | |
| 114 | + let Ok(rel) = entry.path().strip_prefix(&root).map(Path::to_path_buf) else { | |
| 115 | + continue; | |
| 116 | + }; | |
| 117 | + let key = rel | |
| 118 | + .components() | |
| 119 | + .map(|c| c.as_os_str().to_string_lossy().into_owned()) | |
| 120 | + .collect::<Vec<_>>() | |
| 121 | + .join("/"); | |
| 122 | + if key.starts_with(&prefix) { | |
| 123 | + let modified = meta.modified().unwrap_or(SystemTime::UNIX_EPOCH); | |
| 124 | + out.push((key, meta.len(), modified)); | |
| 125 | + } | |
| 126 | + } | |
| 127 | + } | |
| 128 | + out.sort_by(|a, b| a.0.cmp(&b.0)); | |
| 129 | + Ok(out) | |
| 130 | +} | |
| 131 | + | |
| 132 | +#[async_trait] | |
| 133 | +impl BlobStore for LocalBlobs { | |
| 134 | + async fn put_file(&self, key: &str, path: &Path) -> Result<()> { | |
| 135 | + validate_key(key)?; | |
| 136 | + let dest = self.path_of(key); | |
| 137 | + let src = path.to_path_buf(); | |
| 138 | + tokio::task::spawn_blocking(move || put_blocking(dest, src)) | |
| 139 | + .await | |
| 140 | + .map_err(|e| Error::Io(io::Error::other(e)))? | |
| 141 | + } | |
| 142 | + | |
| 143 | + async fn open_range(&self, key: &str, start: u64, len: u64) -> Result<BlobStream> { | |
| 144 | + validate_key(key)?; | |
| 145 | + let path = self.path_of(key); | |
| 146 | + let file = tokio::task::spawn_blocking(move || -> Result<File> { | |
| 147 | + let mut file = File::open(&path).map_err(not_found_or_io)?; | |
| 148 | + file.seek(SeekFrom::Start(start))?; | |
| 149 | + Ok(file) | |
| 150 | + }) | |
| 151 | + .await | |
| 152 | + .map_err(|e| Error::Io(io::Error::other(e)))??; | |
| 153 | + Ok(Box::pin(read_frames(file, len))) | |
| 154 | + } | |
| 155 | + | |
| 156 | + async fn size(&self, key: &str) -> Result<Option<u64>> { | |
| 157 | + validate_key(key)?; | |
| 158 | + match tokio::fs::metadata(self.path_of(key)).await { | |
| 159 | + Ok(meta) if meta.is_file() => Ok(Some(meta.len())), | |
| 160 | + Ok(_) => Ok(None), | |
| 161 | + Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None), | |
| 162 | + Err(e) => Err(e.into()), | |
| 163 | + } | |
| 164 | + } | |
| 165 | + | |
| 166 | + async fn delete(&self, key: &str) -> Result<()> { | |
| 167 | + validate_key(key)?; | |
| 168 | + let path = self.path_of(key); | |
| 169 | + match tokio::fs::remove_file(&path).await { | |
| 170 | + Ok(()) => {} | |
| 171 | + Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()), | |
| 172 | + Err(e) => return Err(e.into()), | |
| 173 | + } | |
| 174 | + if let Some(dir) = path.parent().map(Path::to_path_buf) { | |
| 175 | + tokio::task::spawn_blocking(move || sync_dir(&dir)) | |
| 176 | + .await | |
| 177 | + .map_err(|e| Error::Io(io::Error::other(e)))??; | |
| 178 | + } | |
| 179 | + Ok(()) | |
| 180 | + } | |
| 181 | + | |
| 182 | + async fn list(&self, prefix: &str) -> Result<Vec<BlobEntry>> { | |
| 183 | + let root = self.root.clone(); | |
| 184 | + let prefix = prefix.to_string(); | |
| 185 | + tokio::task::spawn_blocking(move || list_blocking(root, prefix)) | |
| 186 | + .await | |
| 187 | + .map_err(|e| Error::Io(io::Error::other(e)))? | |
| 188 | + } | |
| 189 | +} | |
| 190 | + | |
| 191 | +/// Maps a missing file to [`Error::NotFound`] and anything else to `Io`. | |
| 192 | +fn not_found_or_io(e: io::Error) -> Error { | |
| 193 | + if e.kind() == io::ErrorKind::NotFound { | |
| 194 | + Error::NotFound | |
| 195 | + } else { | |
| 196 | + Error::Io(e) | |
| 197 | + } | |
| 198 | +} | |
| 199 | + | |
| 200 | +/// Streams `remaining` bytes from `file`, one frame per read. Ends early when the file ends. A read | |
| 201 | +/// error is yielded once and then the stream ends. | |
| 202 | +fn read_frames( | |
| 203 | + file: File, | |
| 204 | + remaining: u64, | |
| 205 | +) -> impl futures_util::Stream<Item = Result<Bytes>> + Send { | |
| 206 | + stream::unfold(Some((file, remaining)), |state| async move { | |
| 207 | + let (mut file, remaining) = state?; | |
| 208 | + if remaining == 0 { | |
| 209 | + return None; | |
| 210 | + } | |
| 211 | + let want = remaining.min(FRAME_BYTES as u64) as usize; | |
| 212 | + // Blocking reads run on a dedicated thread so the async runtime stays free. | |
| 213 | + let read = tokio::task::spawn_blocking(move || { | |
| 214 | + let mut buf = vec![0u8; want]; | |
| 215 | + let n = read_full(&mut file, &mut buf); | |
| 216 | + (file, buf, n) | |
| 217 | + }) | |
| 218 | + .await; | |
| 219 | + match read { | |
| 220 | + Ok((_, _, Ok(0))) => None, | |
| 221 | + Ok((file, mut buf, Ok(n))) => { | |
| 222 | + buf.truncate(n); | |
| 223 | + let left = remaining - n as u64; | |
| 224 | + Some((Ok(Bytes::from(buf)), Some((file, left)))) | |
| 225 | + } | |
| 226 | + Ok((_, _, Err(e))) => Some((Err(Error::Io(e)), None)), | |
| 227 | + Err(e) => Some((Err(Error::Io(io::Error::other(e))), None)), | |
| 228 | + } | |
| 229 | + }) | |
| 230 | +} | |
| 231 | + | |
| 232 | +/// Reads until `buf` is full or the file ends. Returns the number of bytes read. | |
| 233 | +fn read_full(file: &mut File, buf: &mut [u8]) -> io::Result<usize> { | |
| 234 | + let mut filled = 0; | |
| 235 | + while filled < buf.len() { | |
| 236 | + match file.read(&mut buf[filled..])? { | |
| 237 | + 0 => break, | |
| 238 | + n => filled += n, | |
| 239 | + } | |
| 240 | + } | |
| 241 | + Ok(filled) | |
| 242 | +} | |
| 243 | + | |
| 244 | +#[cfg(test)] | |
| 245 | +mod tests { | |
| 246 | + use super::*; | |
| 247 | + use futures_util::StreamExt; | |
| 248 | + | |
| 249 | + #[tokio::test] | |
| 250 | + async fn put_range_delete_round_trip_with_private_modes_and_key_checks() { | |
| 251 | + let dir = tempfile::tempdir().unwrap(); | |
| 252 | + let blobs = LocalBlobs::new(dir.path().join("blobs")).unwrap(); | |
| 253 | + let src = dir.path().join("staged.bin"); | |
| 254 | + let data: Vec<u8> = (0..FRAME_BYTES * 2 + 10).map(|i| (i % 251) as u8).collect(); | |
| 255 | + std::fs::write(&src, &data).unwrap(); | |
| 256 | + | |
| 257 | + blobs.put_file("files/ab/abcd", &src).await.unwrap(); | |
| 258 | + assert!(!src.exists(), "the staged file moves into the blob tree"); | |
| 259 | + assert_eq!( | |
| 260 | + blobs.size("files/ab/abcd").await.unwrap(), | |
| 261 | + Some(data.len() as u64) | |
| 262 | + ); | |
| 263 | + | |
| 264 | + let mut stream = blobs | |
| 265 | + .open_range("files/ab/abcd", 10, 100_000) | |
| 266 | + .await | |
| 267 | + .unwrap(); | |
| 268 | + let mut out = Vec::new(); | |
| 269 | + while let Some(frame) = stream.next().await { | |
| 270 | + let frame = frame.unwrap(); | |
| 271 | + assert!(frame.len() <= FRAME_BYTES); | |
| 272 | + out.extend_from_slice(&frame); | |
| 273 | + } | |
| 274 | + assert_eq!(out, data[10..100_010]); | |
| 275 | + | |
| 276 | + let file_mode = std::fs::metadata(dir.path().join("blobs/files/ab/abcd")) | |
| 277 | + .unwrap() | |
| 278 | + .permissions() | |
| 279 | + .mode(); | |
| 280 | + assert_eq!(file_mode & 0o777, 0o600); | |
| 281 | + assert_eq!(blobs.list("files/").await.unwrap().len(), 1); | |
| 282 | + | |
| 283 | + blobs.delete("files/ab/abcd").await.unwrap(); | |
| 284 | + blobs.delete("files/ab/abcd").await.unwrap(); | |
| 285 | + assert_eq!(blobs.size("files/ab/abcd").await.unwrap(), None); | |
| 286 | + | |
| 287 | + assert!(matches!( | |
| 288 | + blobs.put_file("../x", &src).await, | |
| 289 | + Err(Error::Invalid(_)) | |
| 290 | + )); | |
| 291 | + } | |
| 292 | +} |
crates/in-core/src/blob/mod.rsadded+118 -0
| @@ -0,0 +1,118 @@ | ||
| 1 | +//! Blob storage: the bytes of files, thumbnails and objects, addressed by key. Two backends implement | |
| 2 | +//! [`BlobStore`]: [`local::LocalBlobs`] (plain files under a root directory) and [`s3::S3Blobs`] (any | |
| 3 | +//! S3-compatible bucket through `object_store`). | |
| 4 | +//! | |
| 5 | +//! Ordering contract for callers: bytes are put at their key before the row that names them commits, | |
| 6 | +//! and deleted only after that row is gone. Keys are validated here, before any backend sees them. | |
| 7 | + | |
| 8 | +pub mod local; | |
| 9 | +pub mod s3; | |
| 10 | + | |
| 11 | +use std::path::Path; | |
| 12 | +use std::pin::Pin; | |
| 13 | +use std::time::SystemTime; | |
| 14 | + | |
| 15 | +use async_trait::async_trait; | |
| 16 | +use bytes::Bytes; | |
| 17 | +use futures_util::Stream; | |
| 18 | + | |
| 19 | +use crate::error::{Error, Result}; | |
| 20 | + | |
| 21 | +/// Size of every frame a range read yields. Bytes are never buffered whole. | |
| 22 | +pub const FRAME_BYTES: usize = 64 * 1024; | |
| 23 | + | |
| 24 | +/// Longest key in bytes. Keys are short ids, so this is only a guard against absurd input. | |
| 25 | +pub const MAX_KEY_BYTES: usize = 512; | |
| 26 | + | |
| 27 | +/// A stream of byte frames, each at most [`FRAME_BYTES`] long. | |
| 28 | +pub type BlobStream = Pin<Box<dyn Stream<Item = Result<Bytes>> + Send + 'static>>; | |
| 29 | + | |
| 30 | +/// One entry of [`BlobStore::list`]: key, size in bytes and last modification time. | |
| 31 | +pub type BlobEntry = (String, u64, SystemTime); | |
| 32 | + | |
| 33 | +/// Storage for blobs. Object-safe, so the app holds an `Arc<dyn BlobStore>`. | |
| 34 | +#[async_trait] | |
| 35 | +pub trait BlobStore: Send + Sync { | |
| 36 | + /// Stores the finished file at `path` under `key`. The local backend moves the file into place; the | |
| 37 | + /// S3 backend uploads it (multipart above 8 MiB). The file at `path` is gone afterwards. | |
| 38 | + async fn put_file(&self, key: &str, path: &Path) -> Result<()>; | |
| 39 | + | |
| 40 | + /// Streams `len` bytes starting at `start`. A range past the end yields fewer bytes; a missing key | |
| 41 | + /// is [`Error::NotFound`]. | |
| 42 | + async fn open_range(&self, key: &str, start: u64, len: u64) -> Result<BlobStream>; | |
| 43 | + | |
| 44 | + /// The size of the blob, or `None` when there is no such key. | |
| 45 | + async fn size(&self, key: &str) -> Result<Option<u64>>; | |
| 46 | + | |
| 47 | + /// Removes the blob. Deleting a missing key succeeds. | |
| 48 | + async fn delete(&self, key: &str) -> Result<()>; | |
| 49 | + | |
| 50 | + /// Every key that starts with `prefix`, with its size and modification time. | |
| 51 | + async fn list(&self, prefix: &str) -> Result<Vec<BlobEntry>>; | |
| 52 | +} | |
| 53 | + | |
| 54 | +/// Checks a blob key. Allowed: lowercase ASCII letters, digits, `/`, `.`, `_` and `-`. A key has no | |
| 55 | +/// empty segment, no leading or trailing `/`, and no segment that is `.`, `..` or starts with a dot. The | |
| 56 | +/// last rule keeps temporary files, which start with a dot, out of the key space. | |
| 57 | +pub fn validate_key(key: &str) -> Result<()> { | |
| 58 | + let bad = || Error::Invalid("bad_key".into()); | |
| 59 | + if key.is_empty() || key.len() > MAX_KEY_BYTES || key.starts_with('/') || key.ends_with('/') { | |
| 60 | + return Err(bad()); | |
| 61 | + } | |
| 62 | + let allowed = key.bytes().all(|b| { | |
| 63 | + b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'/' | b'.' | b'_' | b'-') | |
| 64 | + }); | |
| 65 | + if !allowed { | |
| 66 | + return Err(bad()); | |
| 67 | + } | |
| 68 | + for segment in key.split('/') { | |
| 69 | + if segment.is_empty() || segment.starts_with('.') { | |
| 70 | + return Err(bad()); | |
| 71 | + } | |
| 72 | + } | |
| 73 | + Ok(()) | |
| 74 | +} | |
| 75 | + | |
| 76 | +/// Splits a buffer into frames of at most [`FRAME_BYTES`]. Shared by both backends. | |
| 77 | +pub(crate) fn frames(bytes: Bytes) -> impl Iterator<Item = Bytes> { | |
| 78 | + (0..bytes.len()) | |
| 79 | + .step_by(FRAME_BYTES) | |
| 80 | + .map(move |start| bytes.slice(start..(start + FRAME_BYTES).min(bytes.len()))) | |
| 81 | +} | |
| 82 | + | |
| 83 | +#[cfg(test)] | |
| 84 | +mod tests { | |
| 85 | + use super::*; | |
| 86 | + | |
| 87 | + #[test] | |
| 88 | + fn keys_are_checked_before_any_backend_sees_them() { | |
| 89 | + for good in ["files/ab/01hx9k", "thumbs/ab/x.webp", "objects/svc-1/a_b.c"] { | |
| 90 | + assert!(validate_key(good).is_ok(), "{good}"); | |
| 91 | + } | |
| 92 | + for bad in [ | |
| 93 | + "../x", | |
| 94 | + "files/../x", | |
| 95 | + "/abs", | |
| 96 | + "a//b", | |
| 97 | + "a/", | |
| 98 | + "", | |
| 99 | + ".hidden", | |
| 100 | + "a/.tmp", | |
| 101 | + "Upper", | |
| 102 | + "a b", | |
| 103 | + "a\0b", | |
| 104 | + "a/./b", | |
| 105 | + ] { | |
| 106 | + assert!(validate_key(bad).is_err(), "{bad:?} should be refused"); | |
| 107 | + } | |
| 108 | + } | |
| 109 | + | |
| 110 | + #[test] | |
| 111 | + fn frames_cover_the_whole_buffer_in_bounded_pieces() { | |
| 112 | + let data = Bytes::from(vec![7u8; FRAME_BYTES * 2 + 5]); | |
| 113 | + let parts: Vec<Bytes> = frames(data.clone()).collect(); | |
| 114 | + assert_eq!(parts.len(), 3); | |
| 115 | + assert!(parts.iter().all(|p| p.len() <= FRAME_BYTES)); | |
| 116 | + assert_eq!(parts.concat(), data.to_vec()); | |
| 117 | + } | |
| 118 | +} |
crates/in-core/src/blob/s3.rsadded+215 -0
| @@ -0,0 +1,215 @@ | ||
| 1 | +//! The S3-compatible blob backend (AWS S3, Cloudflare R2, Hetzner Object Storage, MinIO and others), | |
| 2 | +//! built on the `object_store` crate. | |
| 3 | +//! | |
| 4 | +//! Small files are one PUT. Files above [`MULTIPART_THRESHOLD`] are uploaded as a multipart upload in | |
| 5 | +//! [`PART_BYTES`] parts, read from the staged file one part at a time, so memory use stays bounded. A | |
| 6 | +//! failed multipart upload is aborted so no orphaned parts are billed. | |
| 7 | + | |
| 8 | +use std::io; | |
| 9 | +use std::path::Path; | |
| 10 | +use std::sync::Arc; | |
| 11 | +use std::time::SystemTime; | |
| 12 | + | |
| 13 | +use async_trait::async_trait; | |
| 14 | +use bytes::Bytes; | |
| 15 | +use futures_util::{StreamExt, TryStreamExt, stream}; | |
| 16 | +use object_store::aws::AmazonS3Builder; | |
| 17 | +use object_store::path::Path as ObjectPath; | |
| 18 | +use object_store::{ | |
| 19 | + GetOptions, GetRange, MultipartUpload, ObjectStore, ObjectStoreExt, PutPayload, | |
| 20 | +}; | |
| 21 | +use tokio::io::AsyncReadExt; | |
| 22 | + | |
| 23 | +use super::{BlobEntry, BlobStore, BlobStream, frames, validate_key}; | |
| 24 | +use crate::error::{Error, Result}; | |
| 25 | + | |
| 26 | +/// Files larger than this are uploaded in parts. The S3 minimum part size is 5 MiB, so 8 MiB is safe. | |
| 27 | +pub const MULTIPART_THRESHOLD: u64 = 8 * 1024 * 1024; | |
| 28 | +/// Size of each part of a multipart upload. Every part except the last is exactly this long. | |
| 29 | +pub const PART_BYTES: usize = 8 * 1024 * 1024; | |
| 30 | + | |
| 31 | +/// Connection details for one bucket. Credentials are read from a file or the admin UI by the caller; | |
| 32 | +/// this struct does not come from the TOML file. | |
| 33 | +#[derive(Clone)] | |
| 34 | +pub struct S3Settings { | |
| 35 | + /// Endpoint URL, for example `https://<account>.r2.cloudflarestorage.com`. | |
| 36 | + pub endpoint: String, | |
| 37 | + /// Signing region. R2 uses `auto`. | |
| 38 | + pub region: String, | |
| 39 | + /// Bucket name. | |
| 40 | + pub bucket: String, | |
| 41 | + /// Access key id. | |
| 42 | + pub access_key_id: String, | |
| 43 | + /// Secret access key. Never logged. | |
| 44 | + pub secret_access_key: String, | |
| 45 | + /// Allows plain HTTP. For local test servers only. | |
| 46 | + pub allow_http: bool, | |
| 47 | +} | |
| 48 | + | |
| 49 | +impl std::fmt::Debug for S3Settings { | |
| 50 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | |
| 51 | + f.debug_struct("S3Settings") | |
| 52 | + .field("endpoint", &self.endpoint) | |
| 53 | + .field("region", &self.region) | |
| 54 | + .field("bucket", &self.bucket) | |
| 55 | + .field("access_key_id", &"<redacted>") | |
| 56 | + .field("secret_access_key", &"<redacted>") | |
| 57 | + .field("allow_http", &self.allow_http) | |
| 58 | + .finish() | |
| 59 | + } | |
| 60 | +} | |
| 61 | + | |
| 62 | +/// Blobs kept in an S3-compatible bucket, keyed exactly as the local backend keys them. | |
| 63 | +#[derive(Clone)] | |
| 64 | +pub struct S3Blobs { | |
| 65 | + store: Arc<dyn ObjectStore>, | |
| 66 | +} | |
| 67 | + | |
| 68 | +impl S3Blobs { | |
| 69 | + /// Builds the client. No request is made here, so a wrong bucket shows on the first use. | |
| 70 | + pub fn new(settings: &S3Settings) -> Result<Self> { | |
| 71 | + let store = AmazonS3Builder::new() | |
| 72 | + .with_endpoint(&settings.endpoint) | |
| 73 | + .with_region(&settings.region) | |
| 74 | + .with_bucket_name(&settings.bucket) | |
| 75 | + .with_access_key_id(&settings.access_key_id) | |
| 76 | + .with_secret_access_key(&settings.secret_access_key) | |
| 77 | + .with_allow_http(settings.allow_http) | |
| 78 | + .build() | |
| 79 | + .map_err(os_err)?; | |
| 80 | + Ok(Self { | |
| 81 | + store: Arc::new(store), | |
| 82 | + }) | |
| 83 | + } | |
| 84 | +} | |
| 85 | + | |
| 86 | +/// Maps an `object_store` error. A missing object is [`Error::NotFound`]; anything else is an I/O error | |
| 87 | +/// carrying the provider's message. | |
| 88 | +fn os_err(e: object_store::Error) -> Error { | |
| 89 | + match e { | |
| 90 | + object_store::Error::NotFound { .. } => Error::NotFound, | |
| 91 | + other => Error::Io(io::Error::other(other.to_string())), | |
| 92 | + } | |
| 93 | +} | |
| 94 | + | |
| 95 | +/// Reads up to `buf.len()` bytes, returning fewer only at the end of the file. | |
| 96 | +async fn fill(file: &mut tokio::fs::File, buf: &mut [u8]) -> io::Result<usize> { | |
| 97 | + let mut filled = 0; | |
| 98 | + while filled < buf.len() { | |
| 99 | + match file.read(&mut buf[filled..]).await? { | |
| 100 | + 0 => break, | |
| 101 | + n => filled += n, | |
| 102 | + } | |
| 103 | + } | |
| 104 | + Ok(filled) | |
| 105 | +} | |
| 106 | + | |
| 107 | +/// Uploads the file in parts. The caller aborts the upload if this fails. | |
| 108 | +async fn upload_parts( | |
| 109 | + upload: &mut Box<dyn MultipartUpload>, | |
| 110 | + file: &mut tokio::fs::File, | |
| 111 | +) -> Result<()> { | |
| 112 | + let mut buf = vec![0u8; PART_BYTES]; | |
| 113 | + loop { | |
| 114 | + let n = fill(file, &mut buf).await?; | |
| 115 | + if n == 0 { | |
| 116 | + return Ok(()); | |
| 117 | + } | |
| 118 | + let part = Bytes::copy_from_slice(&buf[..n]); | |
| 119 | + upload | |
| 120 | + .put_part(PutPayload::from(part)) | |
| 121 | + .await | |
| 122 | + .map_err(os_err)?; | |
| 123 | + if n < PART_BYTES { | |
| 124 | + return Ok(()); | |
| 125 | + } | |
| 126 | + } | |
| 127 | +} | |
| 128 | + | |
| 129 | +#[async_trait] | |
| 130 | +impl BlobStore for S3Blobs { | |
| 131 | + async fn put_file(&self, key: &str, path: &Path) -> Result<()> { | |
| 132 | + validate_key(key)?; | |
| 133 | + let location = ObjectPath::from(key); | |
| 134 | + let size = tokio::fs::metadata(path).await?.len(); | |
| 135 | + let mut file = tokio::fs::File::open(path).await?; | |
| 136 | + if size <= MULTIPART_THRESHOLD { | |
| 137 | + let mut data = Vec::with_capacity(size as usize); | |
| 138 | + file.read_to_end(&mut data).await?; | |
| 139 | + self.store | |
| 140 | + .put(&location, PutPayload::from(Bytes::from(data))) | |
| 141 | + .await | |
| 142 | + .map_err(os_err)?; | |
| 143 | + } else { | |
| 144 | + let mut upload = self.store.put_multipart(&location).await.map_err(os_err)?; | |
| 145 | + if let Err(e) = upload_parts(&mut upload, &mut file).await { | |
| 146 | + // Parts already sent would otherwise sit in the bucket and be billed. | |
| 147 | + let _ = upload.abort().await; | |
| 148 | + return Err(e); | |
| 149 | + } | |
| 150 | + upload.complete().await.map_err(os_err)?; | |
| 151 | + } | |
| 152 | + tokio::fs::remove_file(path).await?; | |
| 153 | + Ok(()) | |
| 154 | + } | |
| 155 | + | |
| 156 | + async fn open_range(&self, key: &str, start: u64, len: u64) -> Result<BlobStream> { | |
| 157 | + validate_key(key)?; | |
| 158 | + let location = ObjectPath::from(key); | |
| 159 | + // The size clamps the range, so a request past the end does not become a provider error. | |
| 160 | + let size = self.size(key).await?.ok_or(Error::NotFound)?; | |
| 161 | + let end = start.saturating_add(len).min(size); | |
| 162 | + if start >= end { | |
| 163 | + return Ok(Box::pin(stream::empty())); | |
| 164 | + } | |
| 165 | + let options = GetOptions::new().with_range(Some(GetRange::Bounded(start..end))); | |
| 166 | + let result = self | |
| 167 | + .store | |
| 168 | + .get_opts(&location, options) | |
| 169 | + .await | |
| 170 | + .map_err(os_err)?; | |
| 171 | + let frames_stream = result.into_stream().flat_map(|item| match item { | |
| 172 | + Ok(bytes) => stream::iter(frames(bytes).map(Ok).collect::<Vec<_>>()), | |
| 173 | + Err(e) => stream::iter(vec![Err(os_err(e))]), | |
| 174 | + }); | |
| 175 | + Ok(Box::pin(frames_stream)) | |
| 176 | + } | |
| 177 | + | |
| 178 | + async fn size(&self, key: &str) -> Result<Option<u64>> { | |
| 179 | + validate_key(key)?; | |
| 180 | + match self.store.head(&ObjectPath::from(key)).await { | |
| 181 | + Ok(meta) => Ok(Some(meta.size)), | |
| 182 | + Err(object_store::Error::NotFound { .. }) => Ok(None), | |
| 183 | + Err(e) => Err(os_err(e)), | |
| 184 | + } | |
| 185 | + } | |
| 186 | + | |
| 187 | + async fn delete(&self, key: &str) -> Result<()> { | |
| 188 | + validate_key(key)?; | |
| 189 | + match self.store.delete(&ObjectPath::from(key)).await { | |
| 190 | + Ok(()) | Err(object_store::Error::NotFound { .. }) => Ok(()), | |
| 191 | + Err(e) => Err(os_err(e)), | |
| 192 | + } | |
| 193 | + } | |
| 194 | + | |
| 195 | + async fn list(&self, prefix: &str) -> Result<Vec<BlobEntry>> { | |
| 196 | + let prefix = if prefix.is_empty() { | |
| 197 | + None | |
| 198 | + } else { | |
| 199 | + Some(ObjectPath::from(prefix)) | |
| 200 | + }; | |
| 201 | + let metas: Vec<object_store::ObjectMeta> = self | |
| 202 | + .store | |
| 203 | + .list(prefix.as_ref()) | |
| 204 | + .try_collect() | |
| 205 | + .await | |
| 206 | + .map_err(os_err)?; | |
| 207 | + Ok(metas | |
| 208 | + .into_iter() | |
| 209 | + .map(|m| { | |
| 210 | + let modified: SystemTime = m.last_modified.into(); | |
| 211 | + (m.location.to_string(), m.size, modified) | |
| 212 | + }) | |
| 213 | + .collect()) | |
| 214 | + } | |
| 215 | +} |
crates/in-core/src/lib.rsmodified+8 -2
| @@ -1,11 +1,17 @@ | ||
| 1 | -//! Core of `in`: errors, time stamps, secrets, tokens, passwords, display-name rules, configuration | |
| 2 | -//! and the Turso-backed store. Nothing here serves HTTP; `in-web` builds on it. | |
| 1 | +//! Core of `in`: errors, time stamps, secrets, tokens, passwords, display-name rules, sniffing, quota | |
| 2 | +//! arithmetic, authorization, configuration, blob storage, staging and the Turso-backed store. Nothing | |
| 3 | +//! here serves HTTP; `in-web` builds on it. | |
| 3 | 4 | |
| 5 | +pub mod authz; | |
| 6 | +pub mod blob; | |
| 4 | 7 | pub mod config; |
| 5 | 8 | pub mod error; |
| 6 | 9 | pub mod names; |
| 7 | 10 | pub mod password; |
| 11 | +pub mod quota; | |
| 8 | 12 | pub mod secret; |
| 13 | +pub mod sniff; | |
| 14 | +pub mod staging; | |
| 9 | 15 | pub mod store; |
| 10 | 16 | pub mod time; |
| 11 | 17 | pub mod token; |
crates/in-core/src/quota.rsadded+47 -0
| @@ -0,0 +1,47 @@ | ||
| 1 | +//! Quota arithmetic. Pure functions, so the rule is written once and tested without a database. | |
| 2 | +//! | |
| 3 | +//! `used` counts every byte of the person's files, live and trashed, because trashed bytes still occupy | |
| 4 | +//! the blob store. `staged_claims` is the sum of declared sizes of the person's other active uploads: | |
| 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. | |
| 7 | + | |
| 8 | +/// Bytes a new upload may still use: the quota less what is stored and what is promised to uploads | |
| 9 | +/// in progress. Never negative. | |
| 10 | +pub fn headroom(quota: i64, used: i64, staged_claims: i64) -> i64 { | |
| 11 | + quota | |
| 12 | + .saturating_sub(used) | |
| 13 | + .saturating_sub(staged_claims) | |
| 14 | + .max(0) | |
| 15 | +} | |
| 16 | + | |
| 17 | +/// Whether `size` bytes fit in `headroom`. A zero-byte file always fits. | |
| 18 | +pub fn fits(size: i64, headroom: i64) -> bool { | |
| 19 | + size >= 0 && size <= headroom | |
| 20 | +} | |
| 21 | + | |
| 22 | +#[cfg(test)] | |
| 23 | +mod tests { | |
| 24 | + use super::*; | |
| 25 | + | |
| 26 | + #[test] | |
| 27 | + fn headroom_subtracts_usage_and_claims() { | |
| 28 | + assert_eq!(headroom(100, 40, 10), 50); | |
| 29 | + assert_eq!(headroom(100, 100, 0), 0); | |
| 30 | + } | |
| 31 | + | |
| 32 | + #[test] | |
| 33 | + fn headroom_saturates_instead_of_going_negative() { | |
| 34 | + assert_eq!(headroom(100, 150, 0), 0); | |
| 35 | + assert_eq!(headroom(100, 0, 500), 0); | |
| 36 | + assert_eq!(headroom(i64::MIN, i64::MAX, 0), 0); | |
| 37 | + assert_eq!(headroom(i64::MAX, -5, i64::MIN), i64::MAX); | |
| 38 | + } | |
| 39 | + | |
| 40 | + #[test] | |
| 41 | + fn fits_is_inclusive_and_rejects_negative_sizes() { | |
| 42 | + assert!(fits(50, 50)); | |
| 43 | + assert!(!fits(51, 50)); | |
| 44 | + assert!(fits(0, 0)); | |
| 45 | + assert!(!fits(-1, 10)); | |
| 46 | + } | |
| 47 | +} |
crates/in-core/src/sniff.rsadded+247 -0
| @@ -0,0 +1,247 @@ | ||
| 1 | +//! Content sniffing: the MIME type of a file is decided from its first bytes, never from the | |
| 2 | +//! uploader's claim. The result drives thumbnails and the `Content-Disposition` of every byte response, | |
| 3 | +//! so SVG and HTML are recognised explicitly: they must never be served inline. | |
| 4 | +//! | |
| 5 | +//! This is a pure function over a prefix. Callers pass the first kilobyte or megabyte of the file; | |
| 6 | +//! an empty prefix is `application/octet-stream`. | |
| 7 | + | |
| 8 | +/// How many leading bytes the text heuristics look at when searching for a markup marker. | |
| 9 | +const TEXT_WINDOW: usize = 1024; | |
| 10 | + | |
| 11 | +/// The MIME type for `prefix`, the first bytes of a file. | |
| 12 | +pub fn sniff(prefix: &[u8]) -> String { | |
| 13 | + if prefix.is_empty() { | |
| 14 | + return "application/octet-stream".into(); | |
| 15 | + } | |
| 16 | + let mime = binary_magic(prefix) | |
| 17 | + .or(is_svg(prefix).then_some("image/svg+xml")) | |
| 18 | + .or(is_html(prefix).then_some("text/html")) | |
| 19 | + .or_else(|| iso_bmff(prefix)) | |
| 20 | + .unwrap_or_else(|| { | |
| 21 | + if is_utf8_text(prefix) { | |
| 22 | + "text/plain" | |
| 23 | + } else { | |
| 24 | + "application/octet-stream" | |
| 25 | + } | |
| 26 | + }); | |
| 27 | + mime.into() | |
| 28 | +} | |
| 29 | + | |
| 30 | +/// Magic numbers of the binary formats. `None` when nothing matches. | |
| 31 | +fn binary_magic(b: &[u8]) -> Option<&'static str> { | |
| 32 | + let starts = |magic: &[u8]| b.starts_with(magic); | |
| 33 | + if starts(&[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]) { | |
| 34 | + return Some("image/png"); | |
| 35 | + } | |
| 36 | + if starts(&[0xFF, 0xD8, 0xFF]) { | |
| 37 | + return Some("image/jpeg"); | |
| 38 | + } | |
| 39 | + if starts(b"GIF87a") || starts(b"GIF89a") { | |
| 40 | + return Some("image/gif"); | |
| 41 | + } | |
| 42 | + if starts(b"%PDF-") { | |
| 43 | + return Some("application/pdf"); | |
| 44 | + } | |
| 45 | + if starts(&[0x1F, 0x8B]) { | |
| 46 | + return Some("application/gzip"); | |
| 47 | + } | |
| 48 | + if starts(&[0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]) { | |
| 49 | + return Some(if contains_utf16(b, "Workbook") { | |
| 50 | + "application/vnd.ms-excel" | |
| 51 | + } else { | |
| 52 | + "application/x-ole-storage" | |
| 53 | + }); | |
| 54 | + } | |
| 55 | + if starts(b"PK\x03\x04") { | |
| 56 | + return Some(zip_flavour(b)); | |
| 57 | + } | |
| 58 | + if starts(&[0x1A, 0x45, 0xDF, 0xA3]) { | |
| 59 | + // The EBML header names its document type ("webm" or "matroska") in the first bytes. | |
| 60 | + let head = &b[..b.len().min(TEXT_WINDOW)]; | |
| 61 | + return Some(if contains(head, b"webm") { | |
| 62 | + "video/webm" | |
| 63 | + } else { | |
| 64 | + "video/x-matroska" | |
| 65 | + }); | |
| 66 | + } | |
| 67 | + if starts(b"fLaC") { | |
| 68 | + return Some("audio/flac"); | |
| 69 | + } | |
| 70 | + if starts(b"OggS") { | |
| 71 | + return Some("audio/ogg"); | |
| 72 | + } | |
| 73 | + if b.len() >= 12 && starts(b"RIFF") && &b[8..12] == b"WEBP" { | |
| 74 | + return Some("image/webp"); | |
| 75 | + } | |
| 76 | + if b.len() >= 12 && starts(b"RIFF") && &b[8..12] == b"WAVE" { | |
| 77 | + return Some("audio/wav"); | |
| 78 | + } | |
| 79 | + if starts(b"ID3") || starts(&[0xFF, 0xFB]) || starts(&[0xFF, 0xF3]) || starts(&[0xFF, 0xF2]) { | |
| 80 | + return Some("audio/mpeg"); | |
| 81 | + } | |
| 82 | + None | |
| 83 | +} | |
| 84 | + | |
| 85 | +/// Tells an OOXML or OpenDocument container from a plain zip by the entry names it contains. | |
| 86 | +/// Zip entry names are stored in the clear, so a substring scan finds them. | |
| 87 | +fn zip_flavour(b: &[u8]) -> &'static str { | |
| 88 | + if contains(b, b"xl/workbook.xml") { | |
| 89 | + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" | |
| 90 | + } else if contains(b, b"ppt/presentation.xml") { | |
| 91 | + "application/vnd.openxmlformats-officedocument.presentationml.presentation" | |
| 92 | + } else if contains(b, b"opendocument.spreadsheet") { | |
| 93 | + "application/vnd.oasis.opendocument.spreadsheet" | |
| 94 | + } else { | |
| 95 | + "application/zip" | |
| 96 | + } | |
| 97 | +} | |
| 98 | + | |
| 99 | +/// ISO base media files (`ftyp` box at offset 4). The major brand decides the type. A brand that is | |
| 100 | +/// not listed here is treated as generic MP4. | |
| 101 | +fn iso_bmff(b: &[u8]) -> Option<&'static str> { | |
| 102 | + if b.len() < 12 || &b[4..8] != b"ftyp" { | |
| 103 | + return None; | |
| 104 | + } | |
| 105 | + Some(match &b[8..12] { | |
| 106 | + b"avif" | b"avis" => "image/avif", | |
| 107 | + b"heic" | b"heix" | b"hevc" | b"heim" | b"heis" | b"hevx" => "image/heic", | |
| 108 | + b"heif" | b"mif1" | b"msf1" => "image/heif", | |
| 109 | + b"qt " => "video/quicktime", | |
| 110 | + b"M4A " | b"M4B " => "audio/mp4", | |
| 111 | + _ => "video/mp4", | |
| 112 | + }) | |
| 113 | +} | |
| 114 | + | |
| 115 | +/// Whether the text starts with an `<svg` root element, after an optional byte order mark, XML | |
| 116 | +/// prolog, comments, and a DOCTYPE that does not name HTML. | |
| 117 | +fn is_svg(b: &[u8]) -> bool { | |
| 118 | + let mut rest = strip_bom(b); | |
| 119 | + loop { | |
| 120 | + rest = trim_start_ws(rest); | |
| 121 | + if rest.starts_with(b"<?") { | |
| 122 | + rest = match find(rest, b"?>") { | |
| 123 | + Some(i) => &rest[i + 2..], | |
| 124 | + None => return false, | |
| 125 | + }; | |
| 126 | + } else if rest.starts_with(b"<!--") { | |
| 127 | + rest = match find(rest, b"-->") { | |
| 128 | + Some(i) => &rest[i + 3..], | |
| 129 | + None => return false, | |
| 130 | + }; | |
| 131 | + } else if starts_with_ci(rest, b"<!doctype") { | |
| 132 | + let end = find(rest, b">").map_or(rest.len(), |i| i + 1); | |
| 133 | + if contains_ci(&rest[..end], b"html") { | |
| 134 | + return false; | |
| 135 | + } | |
| 136 | + rest = &rest[end..]; | |
| 137 | + } else { | |
| 138 | + break; | |
| 139 | + } | |
| 140 | + } | |
| 141 | + starts_with_ci(rest, b"<svg") | |
| 142 | +} | |
| 143 | + | |
| 144 | +/// Whether the text carries an HTML marker near its start. Matching is case-insensitive. | |
| 145 | +fn is_html(b: &[u8]) -> bool { | |
| 146 | + let body = trim_start_ws(strip_bom(b)); | |
| 147 | + let window = &body[..body.len().min(TEXT_WINDOW)]; | |
| 148 | + [ | |
| 149 | + &b"<!doctype html"[..], | |
| 150 | + b"<html", | |
| 151 | + b"<script", | |
| 152 | + b"<head", | |
| 153 | + b"<body", | |
| 154 | + ] | |
| 155 | + .iter() | |
| 156 | + .any(|marker| contains_ci(window, marker)) | |
| 157 | +} | |
| 158 | + | |
| 159 | +/// Whether the prefix is valid UTF-8. A prefix cut in the middle of a character is accepted, because | |
| 160 | +/// the cut is an artefact of reading only the first bytes. | |
| 161 | +fn is_utf8_text(b: &[u8]) -> bool { | |
| 162 | + match std::str::from_utf8(b) { | |
| 163 | + Ok(_) => true, | |
| 164 | + Err(e) => e.error_len().is_none(), | |
| 165 | + } | |
| 166 | +} | |
| 167 | + | |
| 168 | +fn strip_bom(b: &[u8]) -> &[u8] { | |
| 169 | + b.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(b) | |
| 170 | +} | |
| 171 | + | |
| 172 | +fn trim_start_ws(b: &[u8]) -> &[u8] { | |
| 173 | + let n = b.iter().take_while(|c| c.is_ascii_whitespace()).count(); | |
| 174 | + &b[n..] | |
| 175 | +} | |
| 176 | + | |
| 177 | +fn find(hay: &[u8], needle: &[u8]) -> Option<usize> { | |
| 178 | + hay.windows(needle.len()).position(|w| w == needle) | |
| 179 | +} | |
| 180 | + | |
| 181 | +fn contains(hay: &[u8], needle: &[u8]) -> bool { | |
| 182 | + find(hay, needle).is_some() | |
| 183 | +} | |
| 184 | + | |
| 185 | +fn starts_with_ci(hay: &[u8], needle: &[u8]) -> bool { | |
| 186 | + hay.len() >= needle.len() && hay[..needle.len()].eq_ignore_ascii_case(needle) | |
| 187 | +} | |
| 188 | + | |
| 189 | +fn contains_ci(hay: &[u8], needle: &[u8]) -> bool { | |
| 190 | + hay.windows(needle.len()) | |
| 191 | + .any(|w| w.eq_ignore_ascii_case(needle)) | |
| 192 | +} | |
| 193 | + | |
| 194 | +/// Whether `word` appears as UTF-16LE text in `b`, as it does inside OLE2 directory entries. | |
| 195 | +fn contains_utf16(b: &[u8], word: &str) -> bool { | |
| 196 | + let wide: Vec<u8> = word.bytes().flat_map(|c| [c, 0]).collect(); | |
| 197 | + contains(b, &wide) | |
| 198 | +} | |
| 199 | + | |
| 200 | +#[cfg(test)] | |
| 201 | +mod tests { | |
| 202 | + use super::*; | |
| 203 | + | |
| 204 | + #[test] | |
| 205 | + fn recognises_binary_formats_by_magic_number() { | |
| 206 | + assert_eq!(sniff(b"\x89PNG\r\n\x1a\n rest"), "image/png"); | |
| 207 | + assert_eq!(sniff(b"%PDF-1.7\n"), "application/pdf"); | |
| 208 | + assert_eq!(sniff(b"\xFF\xD8\xFF\xE0 jpeg"), "image/jpeg"); | |
| 209 | + } | |
| 210 | + | |
| 211 | + #[test] | |
| 212 | + fn svg_is_detected_after_prolog_comments_and_whitespace() { | |
| 213 | + assert_eq!(sniff(b"<svg xmlns='x'/>"), "image/svg+xml"); | |
| 214 | + let prolog = b"\xEF\xBB\xBF<?xml version=\"1.0\"?>\n<!-- hi -->\n <SVG></SVG>"; | |
| 215 | + assert_eq!(sniff(prolog), "image/svg+xml"); | |
| 216 | + let doctype = b"<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"x.dtd\">\n<svg/>"; | |
| 217 | + assert_eq!(sniff(doctype), "image/svg+xml"); | |
| 218 | + } | |
| 219 | + | |
| 220 | + #[test] | |
| 221 | + fn html_is_detected_near_the_start_case_insensitively() { | |
| 222 | + assert_eq!(sniff(b"<!DOCTYPE html>\n<p>x</p>"), "text/html"); | |
| 223 | + assert_eq!(sniff(b" <Script>alert(1)</Script>"), "text/html"); | |
| 224 | + assert_eq!(sniff(b"<!doctype html><svg/>"), "text/html"); | |
| 225 | + assert_eq!(sniff(b"just words"), "text/plain"); | |
| 226 | + } | |
| 227 | + | |
| 228 | + #[test] | |
| 229 | + fn audio_and_video_brands_are_told_apart() { | |
| 230 | + assert_eq!(sniff(b"\x00\x00\x00\x20ftypM4A \x00\x00"), "audio/mp4"); | |
| 231 | + assert_eq!(sniff(b"\x00\x00\x00\x20ftypM4B \x00\x00"), "audio/mp4"); | |
| 232 | + assert_eq!(sniff(b"\x00\x00\x00\x20ftypisom\x00\x00"), "video/mp4"); | |
| 233 | + } | |
| 234 | + | |
| 235 | + #[test] | |
| 236 | + fn empty_and_unknown_binary_are_octet_stream() { | |
| 237 | + assert_eq!(sniff(b""), "application/octet-stream"); | |
| 238 | + assert_eq!(sniff(&[0xFF, 0x00, 0xFE, 0x81]), "application/octet-stream"); | |
| 239 | + } | |
| 240 | + | |
| 241 | + #[test] | |
| 242 | + fn a_cut_multibyte_character_at_the_end_still_counts_as_text() { | |
| 243 | + let mut bytes = "héllo".as_bytes().to_vec(); | |
| 244 | + bytes.push("é".as_bytes()[0]); | |
| 245 | + assert_eq!(sniff(&bytes), "text/plain"); | |
| 246 | + } | |
| 247 | +} |
crates/in-core/src/staging.rsadded+151 -0
| @@ -0,0 +1,151 @@ | ||
| 1 | +//! Streaming intake of an upload. Incoming bytes go to `data_dir/tmp/<ulid>` while the SHA-256 and the | |
| 2 | +//! size are computed, so nothing is buffered whole and the file is never trusted before it is complete. | |
| 3 | +//! | |
| 4 | +//! The finished file is handed to a blob store with `BlobStore::put_file`, which moves it into place. | |
| 5 | +//! A file that is never finished stays in `data_dir/tmp` until the sweeper removes it. | |
| 6 | + | |
| 7 | +use std::fmt::Display; | |
| 8 | +use std::path::{Path, PathBuf}; | |
| 9 | + | |
| 10 | +use bytes::Bytes; | |
| 11 | +use futures_util::{Stream, StreamExt}; | |
| 12 | +use sha2::{Digest, Sha256}; | |
| 13 | +use tokio::io::AsyncWriteExt; | |
| 14 | + | |
| 15 | +use crate::error::{Error, Result}; | |
| 16 | + | |
| 17 | +/// Name of the staging directory inside the data directory. | |
| 18 | +pub const TMP_DIR: &str = "tmp"; | |
| 19 | + | |
| 20 | +/// A file being written. Create it with [`StagedFile::create`], feed it with [`StagedFile::write`] or | |
| 21 | +/// [`StagedFile::consume`], then call [`StagedFile::finish`]. | |
| 22 | +pub struct StagedFile { | |
| 23 | + path: PathBuf, | |
| 24 | + file: tokio::fs::File, | |
| 25 | + hasher: Sha256, | |
| 26 | + size: u64, | |
| 27 | + max_size: u64, | |
| 28 | +} | |
| 29 | + | |
| 30 | +/// A complete staged file, ready for a blob store. | |
| 31 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 32 | +pub struct Staged { | |
| 33 | + /// Where the bytes are. The blob store moves or uploads this file. | |
| 34 | + pub path: PathBuf, | |
| 35 | + /// Number of bytes written. | |
| 36 | + pub size: u64, | |
| 37 | + /// Lowercase hex SHA-256 of the bytes. | |
| 38 | + pub sha256: String, | |
| 39 | +} | |
| 40 | + | |
| 41 | +impl StagedFile { | |
| 42 | + /// Starts a new staged file in `data_dir/tmp`. The directory is created with mode 0700 and the file | |
| 43 | + /// with mode 0600. Writing more than `max_size` bytes fails with `Invalid("too_large")`. | |
| 44 | + pub async fn create(data_dir: &Path, max_size: u64) -> Result<Self> { | |
| 45 | + let dir = data_dir.join(TMP_DIR); | |
| 46 | + tokio::fs::DirBuilder::new() | |
| 47 | + .recursive(true) | |
| 48 | + .mode(0o700) | |
| 49 | + .create(&dir) | |
| 50 | + .await?; | |
| 51 | + let path = dir.join(ulid::Ulid::generate().to_string()); | |
| 52 | + let file = tokio::fs::OpenOptions::new() | |
| 53 | + .write(true) | |
| 54 | + .create_new(true) | |
| 55 | + .mode(0o600) | |
| 56 | + .open(&path) | |
| 57 | + .await?; | |
| 58 | + Ok(Self { | |
| 59 | + path, | |
| 60 | + file, | |
| 61 | + hasher: Sha256::new(), | |
| 62 | + size: 0, | |
| 63 | + max_size, | |
| 64 | + }) | |
| 65 | + } | |
| 66 | + | |
| 67 | + /// Appends `chunk`. Refused, without writing, when it would take the file past the size limit. | |
| 68 | + pub async fn write(&mut self, chunk: &[u8]) -> Result<()> { | |
| 69 | + let len = chunk.len() as u64; | |
| 70 | + if self.size.saturating_add(len) > self.max_size { | |
| 71 | + return Err(Error::Invalid("too_large".into())); | |
| 72 | + } | |
| 73 | + self.file.write_all(chunk).await?; | |
| 74 | + self.hasher.update(chunk); | |
| 75 | + self.size += len; | |
| 76 | + Ok(()) | |
| 77 | + } | |
| 78 | + | |
| 79 | + /// Writes every frame of `stream`. On any error, including the size limit, the partial file is | |
| 80 | + /// removed and the error is returned. `E` is the stream's error type, for example an HTTP body error. | |
| 81 | + pub async fn consume<S, E>(mut self, mut stream: S) -> Result<Staged> | |
| 82 | + where | |
| 83 | + S: Stream<Item = std::result::Result<Bytes, E>> + Unpin, | |
| 84 | + E: Display, | |
| 85 | + { | |
| 86 | + while let Some(frame) = stream.next().await { | |
| 87 | + let outcome = match frame { | |
| 88 | + Ok(bytes) => self.write(&bytes).await, | |
| 89 | + Err(e) => Err(Error::Io(std::io::Error::other(e.to_string()))), | |
| 90 | + }; | |
| 91 | + if let Err(e) = outcome { | |
| 92 | + self.abort().await; | |
| 93 | + return Err(e); | |
| 94 | + } | |
| 95 | + } | |
| 96 | + self.finish().await | |
| 97 | + } | |
| 98 | + | |
| 99 | + /// Flushes and fsyncs the file and its directory, then returns it as [`Staged`]. | |
| 100 | + pub async fn finish(mut self) -> Result<Staged> { | |
| 101 | + self.file.flush().await?; | |
| 102 | + self.file.sync_all().await?; | |
| 103 | + drop(self.file); | |
| 104 | + if let Some(dir) = self.path.parent() { | |
| 105 | + tokio::fs::File::open(dir).await?.sync_all().await?; | |
| 106 | + } | |
| 107 | + let digest = std::mem::take(&mut self.hasher).finalize(); | |
| 108 | + Ok(Staged { | |
| 109 | + path: self.path, | |
| 110 | + size: self.size, | |
| 111 | + sha256: hex::encode(digest), | |
| 112 | + }) | |
| 113 | + } | |
| 114 | + | |
| 115 | + /// Removes the partial file. Errors are ignored: the sweeper removes leftovers anyway. | |
| 116 | + pub async fn abort(self) { | |
| 117 | + drop(self.file); | |
| 118 | + let _ = tokio::fs::remove_file(&self.path).await; | |
| 119 | + } | |
| 120 | +} | |
| 121 | + | |
| 122 | +#[cfg(test)] | |
| 123 | +mod tests { | |
| 124 | + use super::*; | |
| 125 | + use futures_util::stream; | |
| 126 | + | |
| 127 | + #[tokio::test] | |
| 128 | + async fn streams_hash_and_size_and_refuses_oversize() { | |
| 129 | + let dir = tempfile::tempdir().unwrap(); | |
| 130 | + let frames = vec![Ok::<_, std::io::Error>(Bytes::from_static(b"abc"))]; | |
| 131 | + let staged = StagedFile::create(dir.path(), 10) | |
| 132 | + .await | |
| 133 | + .unwrap() | |
| 134 | + .consume(stream::iter(frames)) | |
| 135 | + .await | |
| 136 | + .unwrap(); | |
| 137 | + assert_eq!(staged.size, 3); | |
| 138 | + assert_eq!( | |
| 139 | + staged.sha256, | |
| 140 | + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" | |
| 141 | + ); | |
| 142 | + assert!(staged.path.starts_with(dir.path().join(TMP_DIR))); | |
| 143 | + | |
| 144 | + let mut big = StagedFile::create(dir.path(), 4).await.unwrap(); | |
| 145 | + big.write(b"abc").await.unwrap(); | |
| 146 | + match big.write(b"de").await { | |
| 147 | + Err(Error::Invalid(msg)) => assert_eq!(msg, "too_large"), | |
| 148 | + other => panic!("expected too_large, got {other:?}"), | |
| 149 | + } | |
| 150 | + } | |
| 151 | +} |
crates/in-core/src/store/files.rsadded+322 -0
| @@ -0,0 +1,322 @@ | ||
| 1 | +//! Files: insertion (with the quota check in the same transaction), renaming, moving, lookup, search and | |
| 2 | +//! the download counter. | |
| 3 | +//! | |
| 4 | +//! The blob key of a file is derived from its id (`files/<2 hex>/<id>`), so the caller can write the | |
| 5 | +//! bytes under the key before it inserts the row, and the row can never name a key with other bytes. | |
| 6 | + | |
| 7 | +use crate::error::{Error, Result}; | |
| 8 | +use crate::names; | |
| 9 | +use crate::quota; | |
| 10 | +use crate::store::folders::{FOLDER_COLS, Listing, live_folder, map_folder}; | |
| 11 | +use crate::store::{ | |
| 12 | + Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, first_free_name, | |
| 13 | + insert_err, | |
| 14 | +}; | |
| 15 | +use crate::time::now_stamp; | |
| 16 | +use turso::{Connection, Row}; | |
| 17 | + | |
| 18 | +/// Column list for [`map_file`]. Keep the two in step. | |
| 19 | +pub const FILE_COLS: &str = "id, owner, folder_id, name, mime, size, sha256, blob_key, thumb_state, \ | |
| 20 | + download_count, created_at, updated_at, trashed_at, trash_root"; | |
| 21 | + | |
| 22 | +/// Largest number of results a search returns for each kind. | |
| 23 | +const MAX_SEARCH_LIMIT: usize = 100; | |
| 24 | + | |
| 25 | +/// One row of the `files` table. | |
| 26 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 27 | +pub struct File { | |
| 28 | + /// File id (a lower-case ULID). | |
| 29 | + pub id: String, | |
| 30 | + /// The person who owns the file. | |
| 31 | + pub owner: String, | |
| 32 | + /// Containing folder, or `None` at the top level. | |
| 33 | + pub folder_id: Option<String>, | |
| 34 | + /// Display name. | |
| 35 | + pub name: String, | |
| 36 | + /// MIME type decided by sniffing the bytes. | |
| 37 | + pub mime: String, | |
| 38 | + /// Size in bytes. | |
| 39 | + pub size: i64, | |
| 40 | + /// Hex SHA-256 of the bytes. | |
| 41 | + pub sha256: String, | |
| 42 | + /// Key of the bytes in the blob store. | |
| 43 | + pub blob_key: String, | |
| 44 | + /// Thumbnail state: `none`, `pending`, `ready`, `failed` or `skip`. | |
| 45 | + pub thumb_state: String, | |
| 46 | + /// Forced downloads that started at byte 0. | |
| 47 | + pub download_count: i64, | |
| 48 | + /// When the file was uploaded. | |
| 49 | + pub created_at: String, | |
| 50 | + /// When the file was last renamed or moved. | |
| 51 | + pub updated_at: String, | |
| 52 | + /// When the file was trashed, if it is. | |
| 53 | + pub trashed_at: Option<String>, | |
| 54 | + /// The trashed folder whose trashing took this file along; `None` when trashed directly or live. | |
| 55 | + pub trash_root: Option<String>, | |
| 56 | +} | |
| 57 | + | |
| 58 | +/// What a new file needs. The bytes must already be stored under [`files_blob_key`] of `id`. | |
| 59 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 60 | +pub struct NewFile { | |
| 61 | + /// Id, made by the caller with `store::new_id` so the blob key can be chosen first. | |
| 62 | + pub id: String, | |
| 63 | + /// The person who uploads the file. | |
| 64 | + pub owner: String, | |
| 65 | + /// Destination folder, or `None` for the top level. | |
| 66 | + pub folder: Option<String>, | |
| 67 | + /// Name as the uploader typed it. It is cleaned, and a clash gets a postfix. | |
| 68 | + pub name: String, | |
| 69 | + /// MIME type from sniffing. | |
| 70 | + pub mime: String, | |
| 71 | + /// Size in bytes. | |
| 72 | + pub size: i64, | |
| 73 | + /// Hex SHA-256 of the bytes. | |
| 74 | + pub sha256: String, | |
| 75 | + /// Bytes this owner's other active uploads have declared. They are not yet stored, so they still | |
| 76 | + /// count against the quota. | |
| 77 | + pub staged_claims: i64, | |
| 78 | +} | |
| 79 | + | |
| 80 | +/// The blob key of a file: `files/<first two id characters>/<id>`. | |
| 81 | +pub fn files_blob_key(id: &str) -> String { | |
| 82 | + format!("files/{}/{id}", &id[..2]) | |
| 83 | +} | |
| 84 | + | |
| 85 | +/// The blob key of a file's thumbnail: `thumbs/<first two id characters>/<id>.webp`. | |
| 86 | +pub fn thumb_blob_key(id: &str) -> String { | |
| 87 | + format!("thumbs/{}/{id}.webp", &id[..2]) | |
| 88 | +} | |
| 89 | + | |
| 90 | +/// Maps a row selected with [`FILE_COLS`]. | |
| 91 | +pub fn map_file(row: &Row) -> Result<File> { | |
| 92 | + Ok(File { | |
| 93 | + id: col_text(row, 0)?, | |
| 94 | + owner: col_text(row, 1)?, | |
| 95 | + folder_id: col_opt_text(row, 2)?, | |
| 96 | + name: col_text(row, 3)?, | |
| 97 | + mime: col_text(row, 4)?, | |
| 98 | + size: col_int(row, 5)?, | |
| 99 | + sha256: col_text(row, 6)?, | |
| 100 | + blob_key: col_text(row, 7)?, | |
| 101 | + thumb_state: col_text(row, 8)?, | |
| 102 | + download_count: col_int(row, 9)?, | |
| 103 | + created_at: col_text(row, 10)?, | |
| 104 | + updated_at: col_text(row, 11)?, | |
| 105 | + trashed_at: col_opt_text(row, 12)?, | |
| 106 | + trash_root: col_opt_text(row, 13)?, | |
| 107 | + }) | |
| 108 | +} | |
| 109 | + | |
| 110 | +/// Any file by id, without an owner check. Callers authorise the result with `authz`. | |
| 111 | +pub(crate) async fn file_by_id(conn: &Connection, id: &str) -> Result<Option<File>> { | |
| 112 | + fetch_opt( | |
| 113 | + conn, | |
| 114 | + &format!("SELECT {FILE_COLS} FROM files WHERE id = ?1"), | |
| 115 | + (id.to_string(),), | |
| 116 | + map_file, | |
| 117 | + ) | |
| 118 | + .await | |
| 119 | +} | |
| 120 | + | |
| 121 | +/// A live file that `owner` owns. | |
| 122 | +pub(crate) async fn live_file(conn: &Connection, owner: &str, id: &str) -> Result<File> { | |
| 123 | + fetch_opt( | |
| 124 | + conn, | |
| 125 | + &format!( | |
| 126 | + "SELECT {FILE_COLS} FROM files WHERE id = ?1 AND owner = ?2 AND trashed_at IS NULL" | |
| 127 | + ), | |
| 128 | + (id.to_string(), owner.to_string()), | |
| 129 | + map_file, | |
| 130 | + ) | |
| 131 | + .await? | |
| 132 | + .ok_or(Error::NotFound) | |
| 133 | +} | |
| 134 | + | |
| 135 | +/// Escapes `%`, `_` and the escape character itself for a `LIKE ... ESCAPE '\'` pattern. | |
| 136 | +fn like_escape(q: &str) -> String { | |
| 137 | + let mut out = String::with_capacity(q.len()); | |
| 138 | + for c in q.chars() { | |
| 139 | + if matches!(c, '\\' | '%' | '_') { | |
| 140 | + out.push('\\'); | |
| 141 | + } | |
| 142 | + out.push(c); | |
| 143 | + } | |
| 144 | + out | |
| 145 | +} | |
| 146 | + | |
| 147 | +impl Store { | |
| 148 | + /// The file with this id, whoever owns it. Authorise the result before showing it. | |
| 149 | + pub async fn file(&self, id: &str) -> Result<Option<File>> { | |
| 150 | + let conn = self.read_conn().await; | |
| 151 | + file_by_id(&conn, id).await | |
| 152 | + } | |
| 153 | + | |
| 154 | + /// Records a new file. In one transaction: the folder must be a live folder of the owner, the size | |
| 155 | + /// must fit the quota after the headroom for other uploads, the name gets the first free postfix, | |
| 156 | + /// the row is inserted and `used_bytes` is raised. A quota refusal is `Conflict("quota_exceeded")`. | |
| 157 | + pub async fn insert_file(&self, new: NewFile) -> Result<File> { | |
| 158 | + if new.size < 0 { | |
| 159 | + return Err(Error::Invalid("size_negative".into())); | |
| 160 | + } | |
| 161 | + let base = names::display_name(&new.name); | |
| 162 | + let blob_key = files_blob_key(&new.id); | |
| 163 | + let now = now_stamp(); | |
| 164 | + let conn = self.inner.conn.lock().await; | |
| 165 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 166 | + let outcome: Result<File> = async { | |
| 167 | + if let Some(f) = new.folder.as_deref() { | |
| 168 | + live_folder(&tx, &new.owner, f).await?; | |
| 169 | + } | |
| 170 | + let (quota, used) = fetch_opt( | |
| 171 | + &tx, | |
| 172 | + "SELECT quota_bytes, used_bytes FROM members WHERE sub = ?1", | |
| 173 | + (new.owner.clone(),), | |
| 174 | + |row| Ok((col_int(row, 0)?, col_int(row, 1)?)), | |
| 175 | + ) | |
| 176 | + .await? | |
| 177 | + .ok_or(Error::NotFound)?; | |
| 178 | + let room = quota::headroom(quota, used, new.staged_claims.max(0)); | |
| 179 | + if !quota::fits(new.size, room) { | |
| 180 | + return Err(Error::Conflict("quota_exceeded".into())); | |
| 181 | + } | |
| 182 | + let name = | |
| 183 | + first_free_name(&tx, "files", &new.owner, new.folder.as_deref(), &base, true) | |
| 184 | + .await?; | |
| 185 | + tx.execute( | |
| 186 | + "INSERT INTO files (id, owner, folder_id, name, mime, size, sha256, blob_key, \ | |
| 187 | + created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?9)", | |
| 188 | + ( | |
| 189 | + new.id.clone(), | |
| 190 | + new.owner.clone(), | |
| 191 | + new.folder.clone(), | |
| 192 | + name, | |
| 193 | + new.mime.clone(), | |
| 194 | + new.size, | |
| 195 | + new.sha256.clone(), | |
| 196 | + blob_key, | |
| 197 | + now.clone(), | |
| 198 | + ), | |
| 199 | + ) | |
| 200 | + .await | |
| 201 | + .map_err(|e| insert_err(e, "name_taken"))?; | |
| 202 | + tx.execute( | |
| 203 | + "UPDATE members SET used_bytes = used_bytes + ?2 WHERE sub = ?1", | |
| 204 | + (new.owner.clone(), new.size), | |
| 205 | + ) | |
| 206 | + .await | |
| 207 | + .map_err(db_err)?; | |
| 208 | + file_by_id(&tx, &new.id).await?.ok_or(Error::NotFound) | |
| 209 | + } | |
| 210 | + .await; | |
| 211 | + finish(tx, outcome).await | |
| 212 | + } | |
| 213 | + | |
| 214 | + /// Renames a live file of `owner`. A name used by a live sibling is a conflict. Renaming to the | |
| 215 | + /// current name changes nothing. | |
| 216 | + pub async fn rename_file(&self, owner: &str, id: &str, name: &str) -> Result<File> { | |
| 217 | + let base = names::display_name(name); | |
| 218 | + let conn = self.inner.conn.lock().await; | |
| 219 | + let current = live_file(&conn, owner, id).await?; | |
| 220 | + if current.name == base { | |
| 221 | + return Ok(current); | |
| 222 | + } | |
| 223 | + conn.execute( | |
| 224 | + "UPDATE files SET name = ?3, updated_at = ?4 WHERE id = ?1 AND owner = ?2 AND trashed_at IS NULL", | |
| 225 | + (id.to_string(), owner.to_string(), base, now_stamp()), | |
| 226 | + ) | |
| 227 | + .await | |
| 228 | + .map_err(|e| insert_err(e, "name_taken"))?; | |
| 229 | + live_file(&conn, owner, id).await | |
| 230 | + } | |
| 231 | + | |
| 232 | + /// Moves a live file to `folder` (`None` for the top level). The target must be a live folder of | |
| 233 | + /// `owner`. A name used there by a live file is a conflict. | |
| 234 | + pub async fn move_file(&self, owner: &str, id: &str, folder: Option<&str>) -> Result<File> { | |
| 235 | + let conn = self.inner.conn.lock().await; | |
| 236 | + let current = live_file(&conn, owner, id).await?; | |
| 237 | + if let Some(f) = folder { | |
| 238 | + live_folder(&conn, owner, f).await?; | |
| 239 | + } | |
| 240 | + if current.folder_id.as_deref() == folder { | |
| 241 | + return Ok(current); | |
| 242 | + } | |
| 243 | + conn.execute( | |
| 244 | + "UPDATE files SET folder_id = ?3, updated_at = ?4 \ | |
| 245 | + WHERE id = ?1 AND owner = ?2 AND trashed_at IS NULL", | |
| 246 | + ( | |
| 247 | + id.to_string(), | |
| 248 | + owner.to_string(), | |
| 249 | + folder.map(str::to_string), | |
| 250 | + now_stamp(), | |
| 251 | + ), | |
| 252 | + ) | |
| 253 | + .await | |
| 254 | + .map_err(|e| insert_err(e, "name_taken"))?; | |
| 255 | + live_file(&conn, owner, id).await | |
| 256 | + } | |
| 257 | + | |
| 258 | + /// Counts one forced download of a file. The caller counts only a download that starts at byte 0. | |
| 259 | + pub async fn record_download(&self, id: &str) -> Result<()> { | |
| 260 | + let conn = self.inner.conn.lock().await; | |
| 261 | + let changed = conn | |
| 262 | + .execute( | |
| 263 | + "UPDATE files SET download_count = download_count + 1 WHERE id = ?1", | |
| 264 | + (id.to_string(),), | |
| 265 | + ) | |
| 266 | + .await | |
| 267 | + .map_err(db_err)?; | |
| 268 | + if changed == 0 { | |
| 269 | + return Err(Error::NotFound); | |
| 270 | + } | |
| 271 | + Ok(()) | |
| 272 | + } | |
| 273 | + | |
| 274 | + /// Live folders and files of `owner` whose names contain `q`, ignoring ASCII case. `%`, `_` and | |
| 275 | + /// `\` in `q` match themselves. At most `limit` of each kind, clamped to 1 to 100. | |
| 276 | + pub async fn search(&self, owner: &str, q: &str, limit: usize) -> Result<Listing> { | |
| 277 | + let q = q.trim(); | |
| 278 | + if q.is_empty() { | |
| 279 | + return Ok(Listing::default()); | |
| 280 | + } | |
| 281 | + let limit = limit.clamp(1, MAX_SEARCH_LIMIT) as i64; | |
| 282 | + let pattern = format!("%{}%", like_escape(q)); | |
| 283 | + let conn = self.read_conn().await; | |
| 284 | + let folders = fetch_all( | |
| 285 | + &conn, | |
| 286 | + &format!( | |
| 287 | + "SELECT {FOLDER_COLS} FROM folders WHERE owner = ?1 AND trashed_at IS NULL \ | |
| 288 | + AND name LIKE ?2 ESCAPE '\\' ORDER BY name, id LIMIT ?3" | |
| 289 | + ), | |
| 290 | + (owner.to_string(), pattern.clone(), limit), | |
| 291 | + map_folder, | |
| 292 | + ) | |
| 293 | + .await?; | |
| 294 | + let files = fetch_all( | |
| 295 | + &conn, | |
| 296 | + &format!( | |
| 297 | + "SELECT {FILE_COLS} FROM files WHERE owner = ?1 AND trashed_at IS NULL \ | |
| 298 | + AND name LIKE ?2 ESCAPE '\\' ORDER BY name, id LIMIT ?3" | |
| 299 | + ), | |
| 300 | + (owner.to_string(), pattern, limit), | |
| 301 | + map_file, | |
| 302 | + ) | |
| 303 | + .await?; | |
| 304 | + Ok(Listing { folders, files }) | |
| 305 | + } | |
| 306 | +} | |
| 307 | + | |
| 308 | +#[cfg(test)] | |
| 309 | +mod tests { | |
| 310 | + use super::*; | |
| 311 | + | |
| 312 | + #[test] | |
| 313 | + fn blob_keys_follow_the_id_prefix_layout() { | |
| 314 | + assert_eq!(files_blob_key("01abcdef"), "files/01/01abcdef"); | |
| 315 | + assert_eq!(thumb_blob_key("01abcdef"), "thumbs/01/01abcdef.webp"); | |
| 316 | + } | |
| 317 | + | |
| 318 | + #[test] | |
| 319 | + fn like_pattern_escapes_wildcards() { | |
| 320 | + assert_eq!(like_escape("100%_a\\b"), "100\\%\\_a\\\\b"); | |
| 321 | + } | |
| 322 | +} |
crates/in-core/src/store/folders.rsadded+351 -0
| @@ -0,0 +1,351 @@ | ||
| 1 | +//! Folders: creation, renaming, moving, listing and breadcrumbs. Every write names its owner in the | |
| 2 | +//! `WHERE` clause, so a request can never touch another person's folder by id. | |
| 3 | +//! | |
| 4 | +//! Live names are unique per owner and parent through a partial unique index. Creation relies on that | |
| 5 | +//! index: a clash is retried with the next postfix (`name (2)`, `name (3)`, ...). Moves and renames do | |
| 6 | +//! not postfix; a clash there is the user's choice and is reported as a conflict. | |
| 7 | + | |
| 8 | +use turso::{Connection, Row}; | |
| 9 | + | |
| 10 | +use crate::error::{Error, Result}; | |
| 11 | +use crate::names; | |
| 12 | +use crate::store::files::{FILE_COLS, File, map_file}; | |
| 13 | +use crate::store::{ | |
| 14 | + MAX_POSTFIX_TRIES, Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, insert_err, | |
| 15 | + new_id, | |
| 16 | +}; | |
| 17 | +use crate::time::now_stamp; | |
| 18 | + | |
| 19 | +/// Column list for [`map_folder`]. Keep the two in step. | |
| 20 | +pub const FOLDER_COLS: &str = | |
| 21 | + "id, owner, parent_id, name, created_at, updated_at, trashed_at, trash_root"; | |
| 22 | + | |
| 23 | +/// Deepest folder tree the walks will follow. A real tree is far shallower; the bound stops a corrupt | |
| 24 | +/// cycle from looping forever. | |
| 25 | +const MAX_DEPTH: usize = 512; | |
| 26 | + | |
| 27 | +/// One row of the `folders` table. | |
| 28 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 29 | +pub struct Folder { | |
| 30 | + /// Folder id (a lower-case ULID). | |
| 31 | + pub id: String, | |
| 32 | + /// The person who owns the folder. | |
| 33 | + pub owner: String, | |
| 34 | + /// Parent folder, or `None` at the top level. | |
| 35 | + pub parent_id: Option<String>, | |
| 36 | + /// Display name. | |
| 37 | + pub name: String, | |
| 38 | + /// When the folder was created. | |
| 39 | + pub created_at: String, | |
| 40 | + /// When the folder was last renamed or moved. | |
| 41 | + pub updated_at: String, | |
| 42 | + /// When the folder was trashed, if it is. | |
| 43 | + pub trashed_at: Option<String>, | |
| 44 | + /// The trashed folder whose trashing took this one along; `None` for a folder trashed directly. | |
| 45 | + pub trash_root: Option<String>, | |
| 46 | +} | |
| 47 | + | |
| 48 | +/// The live contents of one folder, or a search or trash listing: folders and files separately. | |
| 49 | +#[derive(Debug, Clone, Default, PartialEq, Eq)] | |
| 50 | +pub struct Listing { | |
| 51 | + /// Folders, by name. | |
| 52 | + pub folders: Vec<Folder>, | |
| 53 | + /// Files, by name. | |
| 54 | + pub files: Vec<File>, | |
| 55 | +} | |
| 56 | + | |
| 57 | +/// Maps a row selected with [`FOLDER_COLS`]. | |
| 58 | +pub fn map_folder(row: &Row) -> Result<Folder> { | |
| 59 | + Ok(Folder { | |
| 60 | + id: col_text(row, 0)?, | |
| 61 | + owner: col_text(row, 1)?, | |
| 62 | + parent_id: col_opt_text(row, 2)?, | |
| 63 | + name: col_text(row, 3)?, | |
| 64 | + created_at: col_text(row, 4)?, | |
| 65 | + updated_at: col_text(row, 5)?, | |
| 66 | + trashed_at: col_opt_text(row, 6)?, | |
| 67 | + trash_root: col_opt_text(row, 7)?, | |
| 68 | + }) | |
| 69 | +} | |
| 70 | + | |
| 71 | +/// A live folder that `owner` owns. Anything else is `NotFound`, which is what the viewer should see. | |
| 72 | +pub(crate) async fn live_folder(conn: &Connection, owner: &str, id: &str) -> Result<Folder> { | |
| 73 | + fetch_opt( | |
| 74 | + conn, | |
| 75 | + &format!( | |
| 76 | + "SELECT {FOLDER_COLS} FROM folders WHERE id = ?1 AND owner = ?2 AND trashed_at IS NULL" | |
| 77 | + ), | |
| 78 | + (id.to_string(), owner.to_string()), | |
| 79 | + map_folder, | |
| 80 | + ) | |
| 81 | + .await? | |
| 82 | + .ok_or(Error::NotFound) | |
| 83 | +} | |
| 84 | + | |
| 85 | +/// Any folder by id, without an owner check. Callers authorise the result with `authz`. | |
| 86 | +pub(crate) async fn folder_by_id(conn: &Connection, id: &str) -> Result<Option<Folder>> { | |
| 87 | + fetch_opt( | |
| 88 | + conn, | |
| 89 | + &format!("SELECT {FOLDER_COLS} FROM folders WHERE id = ?1"), | |
| 90 | + (id.to_string(),), | |
| 91 | + map_folder, | |
| 92 | + ) | |
| 93 | + .await | |
| 94 | +} | |
| 95 | + | |
| 96 | +/// Whether `folder` or one of its ancestors is trashed. `None` (the top level) is never trashed. | |
| 97 | +pub(crate) async fn has_trashed_chain(conn: &Connection, folder: Option<&str>) -> Result<bool> { | |
| 98 | + let mut cur = folder.map(str::to_string); | |
| 99 | + for _ in 0..MAX_DEPTH { | |
| 100 | + let Some(id) = cur else { | |
| 101 | + return Ok(false); | |
| 102 | + }; | |
| 103 | + let row = folder_by_id(conn, &id).await?; | |
| 104 | + let Some(row) = row else { | |
| 105 | + return Ok(false); | |
| 106 | + }; | |
| 107 | + if row.trashed_at.is_some() { | |
| 108 | + return Ok(true); | |
| 109 | + } | |
| 110 | + cur = row.parent_id; | |
| 111 | + } | |
| 112 | + Err(Error::Database("folder tree is too deep".into())) | |
| 113 | +} | |
| 114 | + | |
| 115 | +/// Inserts a folder with the first free postfix. The partial unique index decides each attempt. | |
| 116 | +async fn insert_folder_postfixed( | |
| 117 | + conn: &Connection, | |
| 118 | + owner: &str, | |
| 119 | + parent: Option<&str>, | |
| 120 | + base: &str, | |
| 121 | +) -> Result<Folder> { | |
| 122 | + let now = now_stamp(); | |
| 123 | + for n in 1..=MAX_POSTFIX_TRIES { | |
| 124 | + let name = if n == 1 { | |
| 125 | + base.to_string() | |
| 126 | + } else { | |
| 127 | + names::postfix(base, n, false) | |
| 128 | + }; | |
| 129 | + let id = new_id(); | |
| 130 | + let inserted = conn | |
| 131 | + .execute( | |
| 132 | + "INSERT INTO folders (id, owner, parent_id, name, created_at, updated_at) \ | |
| 133 | + VALUES (?1, ?2, ?3, ?4, ?5, ?5)", | |
| 134 | + ( | |
| 135 | + id.clone(), | |
| 136 | + owner.to_string(), | |
| 137 | + parent.map(str::to_string), | |
| 138 | + name.clone(), | |
| 139 | + now.clone(), | |
| 140 | + ), | |
| 141 | + ) | |
| 142 | + .await; | |
| 143 | + match inserted { | |
| 144 | + Ok(_) => { | |
| 145 | + return Ok(Folder { | |
| 146 | + id, | |
| 147 | + owner: owner.to_string(), | |
| 148 | + parent_id: parent.map(str::to_string), | |
| 149 | + name, | |
| 150 | + created_at: now.clone(), | |
| 151 | + updated_at: now, | |
| 152 | + trashed_at: None, | |
| 153 | + trash_root: None, | |
| 154 | + }); | |
| 155 | + } | |
| 156 | + Err(e) => match insert_err(e, "name_taken") { | |
| 157 | + Error::Conflict(_) => continue, | |
| 158 | + other => return Err(other), | |
| 159 | + }, | |
| 160 | + } | |
| 161 | + } | |
| 162 | + Err(Error::Conflict("too_many_names".into())) | |
| 163 | +} | |
| 164 | + | |
| 165 | +impl Store { | |
| 166 | + /// The folder with this id, whoever owns it. Authorise the result before showing it. | |
| 167 | + pub async fn folder(&self, id: &str) -> Result<Option<Folder>> { | |
| 168 | + let conn = self.read_conn().await; | |
| 169 | + folder_by_id(&conn, id).await | |
| 170 | + } | |
| 171 | + | |
| 172 | + /// Creates a folder under `parent` (or at the top level). The parent must be a live folder of the | |
| 173 | + /// same owner. A name that is taken gets the next postfix. | |
| 174 | + pub async fn create_folder( | |
| 175 | + &self, | |
| 176 | + owner: &str, | |
| 177 | + parent: Option<&str>, | |
| 178 | + name: &str, | |
| 179 | + ) -> Result<Folder> { | |
| 180 | + let base = names::display_name(name); | |
| 181 | + let conn = self.inner.conn.lock().await; | |
| 182 | + if let Some(p) = parent { | |
| 183 | + live_folder(&conn, owner, p).await?; | |
| 184 | + } | |
| 185 | + insert_folder_postfixed(&conn, owner, parent, &base).await | |
| 186 | + } | |
| 187 | + | |
| 188 | + /// Renames a live folder of `owner`. A name already used by a live sibling is a conflict. | |
| 189 | + pub async fn rename_folder(&self, owner: &str, id: &str, name: &str) -> Result<Folder> { | |
| 190 | + let base = names::display_name(name); | |
| 191 | + let conn = self.inner.conn.lock().await; | |
| 192 | + let current = live_folder(&conn, owner, id).await?; | |
| 193 | + if current.name == base { | |
| 194 | + return Ok(current); | |
| 195 | + } | |
| 196 | + conn.execute( | |
| 197 | + "UPDATE folders SET name = ?3, updated_at = ?4 WHERE id = ?1 AND owner = ?2 AND trashed_at IS NULL", | |
| 198 | + (id.to_string(), owner.to_string(), base, now_stamp()), | |
| 199 | + ) | |
| 200 | + .await | |
| 201 | + .map_err(|e| insert_err(e, "name_taken"))?; | |
| 202 | + live_folder(&conn, owner, id).await | |
| 203 | + } | |
| 204 | + | |
| 205 | + /// Moves a live folder under `parent` (`None` for the top level). Refuses a move into the folder | |
| 206 | + /// itself or into one of its own descendants, by walking the ancestors of the new parent. | |
| 207 | + pub async fn move_folder(&self, owner: &str, id: &str, parent: Option<&str>) -> Result<Folder> { | |
| 208 | + let conn = self.inner.conn.lock().await; | |
| 209 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 210 | + let outcome: Result<Folder> = async { | |
| 211 | + live_folder(&tx, owner, id).await?; | |
| 212 | + if let Some(p) = parent { | |
| 213 | + live_folder(&tx, owner, p).await?; | |
| 214 | + let mut cur = Some(p.to_string()); | |
| 215 | + for _ in 0..MAX_DEPTH { | |
| 216 | + let Some(c) = cur else { | |
| 217 | + break; | |
| 218 | + }; | |
| 219 | + if c == id { | |
| 220 | + return Err(Error::Forbidden("cycle".into())); | |
| 221 | + } | |
| 222 | + cur = folder_by_id(&tx, &c).await?.and_then(|f| f.parent_id); | |
| 223 | + } | |
| 224 | + } | |
| 225 | + tx.execute( | |
| 226 | + "UPDATE folders SET parent_id = ?3, updated_at = ?4 \ | |
| 227 | + WHERE id = ?1 AND owner = ?2 AND trashed_at IS NULL", | |
| 228 | + ( | |
| 229 | + id.to_string(), | |
| 230 | + owner.to_string(), | |
| 231 | + parent.map(str::to_string), | |
| 232 | + now_stamp(), | |
| 233 | + ), | |
| 234 | + ) | |
| 235 | + .await | |
| 236 | + .map_err(|e| insert_err(e, "name_taken"))?; | |
| 237 | + live_folder(&tx, owner, id).await | |
| 238 | + } | |
| 239 | + .await; | |
| 240 | + crate::store::finish(tx, outcome).await | |
| 241 | + } | |
| 242 | + | |
| 243 | + /// The live contents of `folder` (`None` for the top level), folders first, each group by name. | |
| 244 | + /// The folder must be a live folder of `owner`. | |
| 245 | + pub async fn list_children(&self, owner: &str, folder: Option<&str>) -> Result<Listing> { | |
| 246 | + let conn = self.read_conn().await; | |
| 247 | + if let Some(f) = folder { | |
| 248 | + live_folder(&conn, owner, f).await?; | |
| 249 | + } | |
| 250 | + let parent = folder.unwrap_or("").to_string(); | |
| 251 | + let folders = fetch_all( | |
| 252 | + &conn, | |
| 253 | + &format!( | |
| 254 | + "SELECT {FOLDER_COLS} FROM folders WHERE owner = ?1 AND COALESCE(parent_id, '') = ?2 \ | |
| 255 | + AND trashed_at IS NULL ORDER BY name, id" | |
| 256 | + ), | |
| 257 | + (owner.to_string(), parent.clone()), | |
| 258 | + map_folder, | |
| 259 | + ) | |
| 260 | + .await?; | |
| 261 | + let files = fetch_all( | |
| 262 | + &conn, | |
| 263 | + &format!( | |
| 264 | + "SELECT {FILE_COLS} FROM files WHERE owner = ?1 AND COALESCE(folder_id, '') = ?2 \ | |
| 265 | + AND trashed_at IS NULL ORDER BY name, id" | |
| 266 | + ), | |
| 267 | + (owner.to_string(), parent), | |
| 268 | + map_file, | |
| 269 | + ) | |
| 270 | + .await?; | |
| 271 | + Ok(Listing { folders, files }) | |
| 272 | + } | |
| 273 | + | |
| 274 | + /// The chain of folders from the top level down to `folder`, inclusive, for breadcrumbs. The folder | |
| 275 | + /// must be owned by `owner`; trashed folders are shown too, so the trash page can use it. | |
| 276 | + pub async fn folder_path(&self, owner: &str, folder: &str) -> Result<Vec<Folder>> { | |
| 277 | + let conn = self.read_conn().await; | |
| 278 | + let mut path = Vec::new(); | |
| 279 | + let mut cur = Some(folder.to_string()); | |
| 280 | + while let Some(id) = cur { | |
| 281 | + if path.len() >= MAX_DEPTH { | |
| 282 | + return Err(Error::Database("folder tree is too deep".into())); | |
| 283 | + } | |
| 284 | + let row = fetch_opt( | |
| 285 | + &conn, | |
| 286 | + &format!("SELECT {FOLDER_COLS} FROM folders WHERE id = ?1 AND owner = ?2"), | |
| 287 | + (id.clone(), owner.to_string()), | |
| 288 | + map_folder, | |
| 289 | + ) | |
| 290 | + .await?; | |
| 291 | + match row { | |
| 292 | + Some(f) => { | |
| 293 | + cur = f.parent_id.clone(); | |
| 294 | + path.push(f); | |
| 295 | + } | |
| 296 | + None if path.is_empty() => return Err(Error::NotFound), | |
| 297 | + None => break, | |
| 298 | + } | |
| 299 | + } | |
| 300 | + path.reverse(); | |
| 301 | + Ok(path) | |
| 302 | + } | |
| 303 | +} | |
| 304 | + | |
| 305 | +#[cfg(test)] | |
| 306 | +mod tests { | |
| 307 | + use super::*; | |
| 308 | + use crate::store::test_support::store_with_member; | |
| 309 | + | |
| 310 | + #[tokio::test] | |
| 311 | + async fn colliding_names_get_postfixes_and_moves_refuse_cycles() { | |
| 312 | + let (_dir, store) = store_with_member("ann").await; | |
| 313 | + let first = store.create_folder("ann", None, "Trips").await.unwrap(); | |
| 314 | + let second = store.create_folder("ann", None, "Trips").await.unwrap(); | |
| 315 | + let third = store.create_folder("ann", None, "Trips").await.unwrap(); | |
| 316 | + assert_eq!(first.name, "Trips"); | |
| 317 | + assert_eq!(second.name, "Trips (2)"); | |
| 318 | + assert_eq!(third.name, "Trips (3)"); | |
| 319 | + | |
| 320 | + // A folder inside `first`, and one inside that, then try to move `first` under its own child. | |
| 321 | + let child = store | |
| 322 | + .create_folder("ann", Some(&first.id), "Days") | |
| 323 | + .await | |
| 324 | + .unwrap(); | |
| 325 | + let grandchild = store | |
| 326 | + .create_folder("ann", Some(&child.id), "Day 1") | |
| 327 | + .await | |
| 328 | + .unwrap(); | |
| 329 | + assert!(matches!( | |
| 330 | + store | |
| 331 | + .move_folder("ann", &first.id, Some(&grandchild.id)) | |
| 332 | + .await, | |
| 333 | + Err(Error::Forbidden(_)) | |
| 334 | + )); | |
| 335 | + assert!(matches!( | |
| 336 | + store.move_folder("ann", &first.id, Some(&first.id)).await, | |
| 337 | + Err(Error::Forbidden(_)) | |
| 338 | + )); | |
| 339 | + // A legal move still works. | |
| 340 | + let moved = store | |
| 341 | + .move_folder("ann", &grandchild.id, Some(&second.id)) | |
| 342 | + .await | |
| 343 | + .unwrap(); | |
| 344 | + assert_eq!(moved.parent_id.as_deref(), Some(second.id.as_str())); | |
| 345 | + // Another person's folder is simply not found. | |
| 346 | + assert!(matches!( | |
| 347 | + store.create_folder("bob", Some(&first.id), "x").await, | |
| 348 | + Err(Error::NotFound) | |
| 349 | + )); | |
| 350 | + } | |
| 351 | +} |
crates/in-core/src/store/members.rsadded+271 -0
| @@ -0,0 +1,271 @@ | ||
| 1 | +//! The local mirror of the people in `im`. A member row is written in two ways: from the claims of a | |
| 2 | +//! sign-in (so a person can use `in` before the directory stream catches up) and from the directory | |
| 3 | +//! stream. A row is never deleted; a removed person is marked `disabled`, which keeps their files and | |
| 4 | +//! their quota history addressable. | |
| 5 | + | |
| 6 | +use turso::Row; | |
| 7 | + | |
| 8 | +use crate::error::{Error, Result}; | |
| 9 | +use crate::store::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt}; | |
| 10 | +use crate::time::now_stamp; | |
| 11 | + | |
| 12 | +/// Column list for [`map_member`]. Keep the two in step. | |
| 13 | +pub const MEMBER_COLS: &str = "sub, email, name, is_admin, disabled, locale, zoneinfo, \ | |
| 14 | + picture_version, im_updated_at, first_seen_at, last_sign_in_at, theme, locale_override, \ | |
| 15 | + quota_bytes, used_bytes"; | |
| 16 | + | |
| 17 | +/// Themes a member may choose. Anything else is refused before it reaches the CHECK constraint. | |
| 18 | +const THEMES: [&str; 3] = ["system", "light", "dark"]; | |
| 19 | + | |
| 20 | +/// One row of the `members` table. | |
| 21 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 22 | +pub struct Member { | |
| 23 | + /// OIDC subject. Never changes for a person. | |
| 24 | + pub sub: String, | |
| 25 | + /// Email address as `im` reports it. | |
| 26 | + pub email: String, | |
| 27 | + /// Display name. | |
| 28 | + pub name: String, | |
| 29 | + /// Whether the person administers the instance. | |
| 30 | + pub is_admin: bool, | |
| 31 | + /// Disabled people cannot sign in and have no sessions. | |
| 32 | + pub disabled: bool, | |
| 33 | + /// Locale from the claims. | |
| 34 | + pub locale: String, | |
| 35 | + /// Time zone from the claims. | |
| 36 | + pub zoneinfo: String, | |
| 37 | + /// Version of the photo; the avatar cache is keyed by it. | |
| 38 | + pub picture_version: i64, | |
| 39 | + /// When `im` last changed this person, as the directory reports it. | |
| 40 | + pub im_updated_at: String, | |
| 41 | + /// When this instance first saw the person. | |
| 42 | + pub first_seen_at: String, | |
| 43 | + /// When the person last signed in here. | |
| 44 | + pub last_sign_in_at: Option<String>, | |
| 45 | + /// `system`, `light` or `dark`. | |
| 46 | + pub theme: String, | |
| 47 | + /// A language chosen in `in` that overrides the one from `im`. | |
| 48 | + pub locale_override: Option<String>, | |
| 49 | + /// Quota in bytes. | |
| 50 | + pub quota_bytes: i64, | |
| 51 | + /// Bytes of live and trashed files. | |
| 52 | + pub used_bytes: i64, | |
| 53 | +} | |
| 54 | + | |
| 55 | +/// The fields `im` provides for one person. | |
| 56 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 57 | +pub struct MemberFields { | |
| 58 | + /// OIDC subject. | |
| 59 | + pub sub: String, | |
| 60 | + /// Email address. | |
| 61 | + pub email: String, | |
| 62 | + /// Display name. | |
| 63 | + pub name: String, | |
| 64 | + /// Administrator flag. | |
| 65 | + pub is_admin: bool, | |
| 66 | + /// Locale. | |
| 67 | + pub locale: String, | |
| 68 | + /// Time zone. | |
| 69 | + pub zoneinfo: String, | |
| 70 | + /// Photo version. | |
| 71 | + pub picture_version: i64, | |
| 72 | + /// Directory timestamp of the change. Sign-in claims carry none, so the sign-in path ignores it. | |
| 73 | + pub im_updated_at: String, | |
| 74 | +} | |
| 75 | + | |
| 76 | +/// Maps a row selected with [`MEMBER_COLS`]. | |
| 77 | +pub fn map_member(row: &Row) -> Result<Member> { | |
| 78 | + Ok(Member { | |
| 79 | + sub: col_text(row, 0)?, | |
| 80 | + email: col_text(row, 1)?, | |
| 81 | + name: col_text(row, 2)?, | |
| 82 | + is_admin: col_int(row, 3)? != 0, | |
| 83 | + disabled: col_int(row, 4)? != 0, | |
| 84 | + locale: col_text(row, 5)?, | |
| 85 | + zoneinfo: col_text(row, 6)?, | |
| 86 | + picture_version: col_int(row, 7)?, | |
| 87 | + im_updated_at: col_text(row, 8)?, | |
| 88 | + first_seen_at: col_text(row, 9)?, | |
| 89 | + last_sign_in_at: col_opt_text(row, 10)?, | |
| 90 | + theme: col_text(row, 11)?, | |
| 91 | + locale_override: col_opt_text(row, 12)?, | |
| 92 | + quota_bytes: col_int(row, 13)?, | |
| 93 | + used_bytes: col_int(row, 14)?, | |
| 94 | + }) | |
| 95 | +} | |
| 96 | + | |
| 97 | +async fn fetch_member(conn: &turso::Connection, sub: &str) -> Result<Option<Member>> { | |
| 98 | + fetch_opt( | |
| 99 | + conn, | |
| 100 | + &format!("SELECT {MEMBER_COLS} FROM members WHERE sub = ?1"), | |
| 101 | + (sub.to_string(),), | |
| 102 | + map_member, | |
| 103 | + ) | |
| 104 | + .await | |
| 105 | +} | |
| 106 | + | |
| 107 | +impl Store { | |
| 108 | + /// Records a sign-in. Creates the member with `default_quota` when new; otherwise refreshes the | |
| 109 | + /// claim fields. Quota, theme and the disabled flag are left alone. A sign-in also stamps | |
| 110 | + /// `last_sign_in_at`. | |
| 111 | + pub async fn upsert_member_from_claims( | |
| 112 | + &self, | |
| 113 | + fields: &MemberFields, | |
| 114 | + default_quota: i64, | |
| 115 | + ) -> Result<Member> { | |
| 116 | + let now = now_stamp(); | |
| 117 | + let conn = self.inner.conn.lock().await; | |
| 118 | + conn.execute( | |
| 119 | + "INSERT INTO members (sub, email, name, is_admin, locale, zoneinfo, picture_version, \ | |
| 120 | + im_updated_at, first_seen_at, last_sign_in_at, quota_bytes) \ | |
| 121 | + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?9, ?10) \ | |
| 122 | + ON CONFLICT (sub) DO UPDATE SET email = excluded.email, name = excluded.name, \ | |
| 123 | + is_admin = excluded.is_admin, locale = excluded.locale, zoneinfo = excluded.zoneinfo, \ | |
| 124 | + picture_version = excluded.picture_version, last_sign_in_at = excluded.last_sign_in_at", | |
| 125 | + ( | |
| 126 | + fields.sub.clone(), | |
| 127 | + fields.email.clone(), | |
| 128 | + fields.name.clone(), | |
| 129 | + i64::from(fields.is_admin), | |
| 130 | + fields.locale.clone(), | |
| 131 | + fields.zoneinfo.clone(), | |
| 132 | + fields.picture_version, | |
| 133 | + // The insert needs a value; an existing row keeps its own im_updated_at because the | |
| 134 | + // conflict clause does not touch that column. | |
| 135 | + if fields.im_updated_at.is_empty() { | |
| 136 | + now.clone() | |
| 137 | + } else { | |
| 138 | + fields.im_updated_at.clone() | |
| 139 | + }, | |
| 140 | + now, | |
| 141 | + default_quota, | |
| 142 | + ), | |
| 143 | + ) | |
| 144 | + .await | |
| 145 | + .map_err(db_err)?; | |
| 146 | + fetch_member(&conn, &fields.sub) | |
| 147 | + .await? | |
| 148 | + .ok_or(Error::NotFound) | |
| 149 | + } | |
| 150 | + | |
| 151 | + /// Applies one directory change. A change older than the stored one is ignored, so replays and | |
| 152 | + /// out-of-order events cannot roll a person back. `disabled` comes from the directory. | |
| 153 | + pub async fn apply_directory_member( | |
| 154 | + &self, | |
| 155 | + fields: &MemberFields, | |
| 156 | + disabled: bool, | |
| 157 | + default_quota: i64, | |
| 158 | + ) -> Result<Member> { | |
| 159 | + let conn = self.inner.conn.lock().await; | |
| 160 | + conn.execute( | |
| 161 | + "INSERT INTO members (sub, email, name, is_admin, disabled, locale, zoneinfo, \ | |
| 162 | + picture_version, im_updated_at, first_seen_at, quota_bytes) \ | |
| 163 | + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11) \ | |
| 164 | + ON CONFLICT (sub) DO UPDATE SET email = excluded.email, name = excluded.name, \ | |
| 165 | + is_admin = excluded.is_admin, disabled = excluded.disabled, locale = excluded.locale, \ | |
| 166 | + zoneinfo = excluded.zoneinfo, picture_version = excluded.picture_version, \ | |
| 167 | + im_updated_at = excluded.im_updated_at \ | |
| 168 | + WHERE excluded.im_updated_at >= members.im_updated_at", | |
| 169 | + ( | |
| 170 | + fields.sub.clone(), | |
| 171 | + fields.email.clone(), | |
| 172 | + fields.name.clone(), | |
| 173 | + i64::from(fields.is_admin), | |
| 174 | + i64::from(disabled), | |
| 175 | + fields.locale.clone(), | |
| 176 | + fields.zoneinfo.clone(), | |
| 177 | + fields.picture_version, | |
| 178 | + fields.im_updated_at.clone(), | |
| 179 | + now_stamp(), | |
| 180 | + default_quota, | |
| 181 | + ), | |
| 182 | + ) | |
| 183 | + .await | |
| 184 | + .map_err(db_err)?; | |
| 185 | + fetch_member(&conn, &fields.sub) | |
| 186 | + .await? | |
| 187 | + .ok_or(Error::NotFound) | |
| 188 | + } | |
| 189 | + | |
| 190 | + /// Marks a person as removed by the directory. The row stays; the person is disabled. Unknown | |
| 191 | + /// subjects are ignored, because a delete event can arrive for someone never seen here. | |
| 192 | + pub async fn mark_member_deleted(&self, sub: &str) -> Result<()> { | |
| 193 | + let conn = self.inner.conn.lock().await; | |
| 194 | + conn.execute( | |
| 195 | + "UPDATE members SET disabled = 1 WHERE sub = ?1", | |
| 196 | + (sub.to_string(),), | |
| 197 | + ) | |
| 198 | + .await | |
| 199 | + .map_err(db_err)?; | |
| 200 | + Ok(()) | |
| 201 | + } | |
| 202 | + | |
| 203 | + /// The member with this subject, if any. | |
| 204 | + pub async fn member(&self, sub: &str) -> Result<Option<Member>> { | |
| 205 | + let conn = self.read_conn().await; | |
| 206 | + fetch_member(&conn, sub).await | |
| 207 | + } | |
| 208 | + | |
| 209 | + /// The first member whose email matches, ignoring ASCII case. | |
| 210 | + pub async fn member_by_email(&self, email: &str) -> Result<Option<Member>> { | |
| 211 | + let conn = self.read_conn().await; | |
| 212 | + fetch_opt( | |
| 213 | + &conn, | |
| 214 | + &format!("SELECT {MEMBER_COLS} FROM members WHERE email = ?1 COLLATE NOCASE LIMIT 1"), | |
| 215 | + (email.to_string(),), | |
| 216 | + map_member, | |
| 217 | + ) | |
| 218 | + .await | |
| 219 | + } | |
| 220 | + | |
| 221 | + /// Every member, by name then subject. | |
| 222 | + pub async fn list_members(&self) -> Result<Vec<Member>> { | |
| 223 | + let conn = self.read_conn().await; | |
| 224 | + fetch_all( | |
| 225 | + &conn, | |
| 226 | + &format!("SELECT {MEMBER_COLS} FROM members ORDER BY name, sub"), | |
| 227 | + (), | |
| 228 | + map_member, | |
| 229 | + ) | |
| 230 | + .await | |
| 231 | + } | |
| 232 | + | |
| 233 | + /// Sets a member's quota in bytes. Lowering it below current use is allowed: the person then has | |
| 234 | + /// no headroom until they free space. | |
| 235 | + pub async fn set_quota(&self, sub: &str, bytes: i64) -> Result<()> { | |
| 236 | + if bytes < 0 { | |
| 237 | + return Err(Error::Invalid("quota_negative".into())); | |
| 238 | + } | |
| 239 | + let conn = self.inner.conn.lock().await; | |
| 240 | + let changed = conn | |
| 241 | + .execute( | |
| 242 | + "UPDATE members SET quota_bytes = ?2 WHERE sub = ?1", | |
| 243 | + (sub.to_string(), bytes), | |
| 244 | + ) | |
| 245 | + .await | |
| 246 | + .map_err(db_err)?; | |
| 247 | + if changed == 0 { | |
| 248 | + return Err(Error::NotFound); | |
| 249 | + } | |
| 250 | + Ok(()) | |
| 251 | + } | |
| 252 | + | |
| 253 | + /// Sets a member's theme. Only `system`, `light` and `dark` are accepted. | |
| 254 | + pub async fn set_theme(&self, sub: &str, theme: &str) -> Result<()> { | |
| 255 | + if !THEMES.contains(&theme) { | |
| 256 | + return Err(Error::Invalid("bad_theme".into())); | |
| 257 | + } | |
| 258 | + let conn = self.inner.conn.lock().await; | |
| 259 | + let changed = conn | |
| 260 | + .execute( | |
| 261 | + "UPDATE members SET theme = ?2 WHERE sub = ?1", | |
| 262 | + (sub.to_string(), theme.to_string()), | |
| 263 | + ) | |
| 264 | + .await | |
| 265 | + .map_err(db_err)?; | |
| 266 | + if changed == 0 { | |
| 267 | + return Err(Error::NotFound); | |
| 268 | + } | |
| 269 | + Ok(()) | |
| 270 | + } | |
| 271 | +} |
crates/in-core/src/store/mod.rsmodified+97 -0
| @@ -4,9 +4,14 @@ | ||
| 4 | 4 | //! Every connection gets the same pragmas (WAL, `synchronous = FULL`, foreign keys, a 5 s busy |
| 5 | 5 | //! timeout). The helpers at the bottom of this file are shared by every table module. |
| 6 | 6 | |
| 7 | +pub mod files; | |
| 8 | +pub mod folders; | |
| 9 | +pub mod members; | |
| 7 | 10 | pub mod migrate; |
| 11 | +pub mod sessions; | |
| 8 | 12 | pub mod settings; |
| 9 | 13 | pub mod snapshot; |
| 14 | +pub mod trash; | |
| 10 | 15 | |
| 11 | 16 | use std::path::Path; |
| 12 | 17 | use std::sync::Arc; |
| @@ -17,6 +22,7 @@ use tokio::sync::{Mutex, MutexGuard}; | ||
| 17 | 22 | use turso::{Builder, Connection, Database, IntoParams, Row, Value}; |
| 18 | 23 | |
| 19 | 24 | use crate::error::{Error, Result}; |
| 25 | +use crate::names; | |
| 20 | 26 | |
| 21 | 27 | /// How long a connection waits for a lock before it gives up. |
| 22 | 28 | const BUSY_TIMEOUT: Duration = Duration::from_millis(5000); |
| @@ -229,6 +235,97 @@ pub fn col_to_string(row: &Row, i: usize) -> Result<String> { | ||
| 229 | 235 | } |
| 230 | 236 | } |
| 231 | 237 | |
| 238 | +/// A new id: a ULID in lower case. Lower case keeps every id a valid blob key segment. | |
| 239 | +pub fn new_id() -> String { | |
| 240 | + ulid::Ulid::generate().to_string().to_ascii_lowercase() | |
| 241 | +} | |
| 242 | + | |
| 243 | +/// Reads column `i` as optional text: SQL NULL is `None`. | |
| 244 | +pub fn col_opt_text(row: &Row, i: usize) -> Result<Option<String>> { | |
| 245 | + match row.get_value(i).map_err(db_err)? { | |
| 246 | + Value::Null => Ok(None), | |
| 247 | + Value::Text(s) => Ok(Some(s)), | |
| 248 | + _ => Err(Error::Database(format!("column {i} is not text or NULL"))), | |
| 249 | + } | |
| 250 | +} | |
| 251 | + | |
| 252 | +/// The largest number of postfixed names tried before a clash is reported as a conflict. | |
| 253 | +pub const MAX_POSTFIX_TRIES: u32 = 1000; | |
| 254 | + | |
| 255 | +/// Finds the first name in `parent` that no live sibling uses, starting with `base` and then | |
| 256 | +/// `base (2)`, `base (3)`, and so on. `table` is `files` or `folders`; it is one of two fixed names | |
| 257 | +/// from this crate, never user input. Runs on the caller's connection so it sees the same | |
| 258 | +/// transaction, and the writer lock makes the check and the following insert race-free. | |
| 259 | +pub(crate) async fn first_free_name( | |
| 260 | + conn: &Connection, | |
| 261 | + table: &'static str, | |
| 262 | + owner: &str, | |
| 263 | + parent: Option<&str>, | |
| 264 | + base: &str, | |
| 265 | + is_file: bool, | |
| 266 | +) -> Result<String> { | |
| 267 | + let (parent_col, name_col) = if table == "files" { | |
| 268 | + ("folder_id", "name") | |
| 269 | + } else { | |
| 270 | + ("parent_id", "name") | |
| 271 | + }; | |
| 272 | + let sql = format!( | |
| 273 | + "SELECT 1 FROM {table} WHERE owner = ?1 AND COALESCE({parent_col}, '') = ?2 \ | |
| 274 | + AND {name_col} = ?3 AND trashed_at IS NULL" | |
| 275 | + ); | |
| 276 | + let parent = parent.unwrap_or("").to_string(); | |
| 277 | + for n in 1..=MAX_POSTFIX_TRIES { | |
| 278 | + let candidate = if n == 1 { | |
| 279 | + names::display_name(base) | |
| 280 | + } else { | |
| 281 | + names::postfix(base, n, is_file) | |
| 282 | + }; | |
| 283 | + let taken = fetch_opt( | |
| 284 | + conn, | |
| 285 | + &sql, | |
| 286 | + (owner.to_string(), parent.clone(), candidate.clone()), | |
| 287 | + |_| Ok(()), | |
| 288 | + ) | |
| 289 | + .await? | |
| 290 | + .is_some(); | |
| 291 | + if !taken { | |
| 292 | + return Ok(candidate); | |
| 293 | + } | |
| 294 | + } | |
| 295 | + Err(Error::Conflict("too_many_names".into())) | |
| 296 | +} | |
| 297 | + | |
| 298 | +#[cfg(test)] | |
| 299 | +pub(crate) mod test_support { | |
| 300 | + //! Helpers shared by the store tests: a fresh database in a temp dir with one member. | |
| 301 | + | |
| 302 | + use super::Store; | |
| 303 | + use crate::store::members::MemberFields; | |
| 304 | + | |
| 305 | + /// A store in a new temp directory, and a member `sub` with a 1 GiB quota. | |
| 306 | + pub async fn store_with_member(sub: &str) -> (tempfile::TempDir, Store) { | |
| 307 | + let dir = tempfile::tempdir().unwrap(); | |
| 308 | + let store = Store::open(&dir.path().join("in.db")).await.unwrap(); | |
| 309 | + store | |
| 310 | + .upsert_member_from_claims( | |
| 311 | + &MemberFields { | |
| 312 | + sub: sub.into(), | |
| 313 | + email: format!("{sub}@example.test"), | |
| 314 | + name: sub.into(), | |
| 315 | + is_admin: false, | |
| 316 | + locale: "en".into(), | |
| 317 | + zoneinfo: "UTC".into(), | |
| 318 | + picture_version: 0, | |
| 319 | + im_updated_at: String::new(), | |
| 320 | + }, | |
| 321 | + 1 << 30, | |
| 322 | + ) | |
| 323 | + .await | |
| 324 | + .unwrap(); | |
| 325 | + (dir, store) | |
| 326 | + } | |
| 327 | +} | |
| 328 | + | |
| 232 | 329 | #[cfg(test)] |
| 233 | 330 | mod tests { |
| 234 | 331 | use super::*; |
crates/in-core/src/store/sessions.rsadded+273 -0
| @@ -0,0 +1,273 @@ | ||
| 1 | +//! Local sign-in sessions and the replay guard for back-channel logout tokens. | |
| 2 | +//! | |
| 3 | +//! A session's cookie token is never stored: only its SHA-256 (`token_hash`) is. Expired sessions and | |
| 4 | +//! sessions of disabled people are never returned by [`Store::session_by_token_hash`], so a session | |
| 5 | +//! stops working the moment it expires, even before the sweeper removes it. | |
| 6 | + | |
| 7 | +use crate::error::Result; | |
| 8 | +use crate::store::{Store, col_opt_text, col_text, db_err, fetch_opt, new_id}; | |
| 9 | +use crate::time::now_stamp; | |
| 10 | + | |
| 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, \ | |
| 13 | + last_seen_at, ip, user_agent"; | |
| 14 | + | |
| 15 | +/// One row of the `sessions` table. The token itself is not in here. | |
| 16 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 17 | +pub struct Session { | |
| 18 | + /// Session id (a ULID). | |
| 19 | + pub id: String, | |
| 20 | + /// The person the session belongs to. | |
| 21 | + pub sub: String, | |
| 22 | + /// Hex SHA-256 of the cookie token. | |
| 23 | + pub token_hash: String, | |
| 24 | + /// Per-session CSRF token, checked on every state-changing form. | |
| 25 | + pub csrf_token: String, | |
| 26 | + /// The `im` session id, used to end this session on back-channel logout. | |
| 27 | + pub im_sid: String, | |
| 28 | + /// When the session began. | |
| 29 | + pub created_at: String, | |
| 30 | + /// When the session stops working. | |
| 31 | + pub expires_at: String, | |
| 32 | + /// Last time the session was used. | |
| 33 | + pub last_seen_at: String, | |
| 34 | + /// Client address at sign-in, when known. | |
| 35 | + pub ip: Option<String>, | |
| 36 | + /// User agent at sign-in, when sent. | |
| 37 | + pub user_agent: Option<String>, | |
| 38 | +} | |
| 39 | + | |
| 40 | +/// What a new session needs. The id and timestamps are made by the store. | |
| 41 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 42 | +pub struct NewSession { | |
| 43 | + /// The person. | |
| 44 | + pub sub: String, | |
| 45 | + /// Hex SHA-256 of the cookie token. | |
| 46 | + pub token_hash: String, | |
| 47 | + /// CSRF token for the session. | |
| 48 | + pub csrf_token: String, | |
| 49 | + /// The `im` session id. | |
| 50 | + pub im_sid: String, | |
| 51 | + /// When the session stops working, as a stamp. | |
| 52 | + pub expires_at: String, | |
| 53 | + /// Client address, when known. | |
| 54 | + pub ip: Option<String>, | |
| 55 | + /// User agent, when sent. | |
| 56 | + pub user_agent: Option<String>, | |
| 57 | +} | |
| 58 | + | |
| 59 | +/// Maps a row selected with [`SESSION_COLS`]. | |
| 60 | +pub fn map_session(row: &turso::Row) -> Result<Session> { | |
| 61 | + Ok(Session { | |
| 62 | + id: col_text(row, 0)?, | |
| 63 | + sub: col_text(row, 1)?, | |
| 64 | + token_hash: col_text(row, 2)?, | |
| 65 | + csrf_token: col_text(row, 3)?, | |
| 66 | + im_sid: col_text(row, 4)?, | |
| 67 | + created_at: col_text(row, 5)?, | |
| 68 | + expires_at: col_text(row, 6)?, | |
| 69 | + last_seen_at: col_text(row, 7)?, | |
| 70 | + ip: col_opt_text(row, 8)?, | |
| 71 | + user_agent: col_opt_text(row, 9)?, | |
| 72 | + }) | |
| 73 | +} | |
| 74 | + | |
| 75 | +impl Store { | |
| 76 | + /// Creates a session and returns it. The caller sets the cookie with the plaintext token it made. | |
| 77 | + pub async fn create_session(&self, new: NewSession) -> Result<Session> { | |
| 78 | + let id = new_id(); | |
| 79 | + let now = now_stamp(); | |
| 80 | + let conn = self.inner.conn.lock().await; | |
| 81 | + conn.execute( | |
| 82 | + "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)", | |
| 84 | + ( | |
| 85 | + id.clone(), | |
| 86 | + new.sub.clone(), | |
| 87 | + new.token_hash.clone(), | |
| 88 | + new.csrf_token.clone(), | |
| 89 | + new.im_sid.clone(), | |
| 90 | + now.clone(), | |
| 91 | + new.expires_at.clone(), | |
| 92 | + new.ip.clone(), | |
| 93 | + new.user_agent.clone(), | |
| 94 | + ), | |
| 95 | + ) | |
| 96 | + .await | |
| 97 | + .map_err(db_err)?; | |
| 98 | + Ok(Session { | |
| 99 | + id, | |
| 100 | + sub: new.sub, | |
| 101 | + token_hash: new.token_hash, | |
| 102 | + csrf_token: new.csrf_token, | |
| 103 | + im_sid: new.im_sid, | |
| 104 | + created_at: now.clone(), | |
| 105 | + expires_at: new.expires_at, | |
| 106 | + last_seen_at: now, | |
| 107 | + ip: new.ip, | |
| 108 | + user_agent: new.user_agent, | |
| 109 | + }) | |
| 110 | + } | |
| 111 | + | |
| 112 | + /// The live session for this token hash: unexpired, and its person is not disabled. | |
| 113 | + pub async fn session_by_token_hash(&self, token_hash: &str) -> Result<Option<Session>> { | |
| 114 | + let conn = self.read_conn().await; | |
| 115 | + fetch_opt( | |
| 116 | + &conn, | |
| 117 | + &format!( | |
| 118 | + "SELECT {SESSION_COLS} FROM sessions WHERE token_hash = ?1 AND expires_at > ?2 \ | |
| 119 | + AND sub IN (SELECT sub FROM members WHERE disabled = 0)" | |
| 120 | + ), | |
| 121 | + (token_hash.to_string(), now_stamp()), | |
| 122 | + map_session, | |
| 123 | + ) | |
| 124 | + .await | |
| 125 | + } | |
| 126 | + | |
| 127 | + /// Records that a session was used now. | |
| 128 | + pub async fn touch_session(&self, id: &str) -> Result<()> { | |
| 129 | + let conn = self.inner.conn.lock().await; | |
| 130 | + conn.execute( | |
| 131 | + "UPDATE sessions SET last_seen_at = ?2 WHERE id = ?1", | |
| 132 | + (id.to_string(), now_stamp()), | |
| 133 | + ) | |
| 134 | + .await | |
| 135 | + .map_err(db_err)?; | |
| 136 | + Ok(()) | |
| 137 | + } | |
| 138 | + | |
| 139 | + /// Ends one session. Unknown ids are ignored. | |
| 140 | + pub async fn delete_session(&self, id: &str) -> Result<()> { | |
| 141 | + let conn = self.inner.conn.lock().await; | |
| 142 | + conn.execute("DELETE FROM sessions WHERE id = ?1", (id.to_string(),)) | |
| 143 | + .await | |
| 144 | + .map_err(db_err)?; | |
| 145 | + Ok(()) | |
| 146 | + } | |
| 147 | + | |
| 148 | + /// Ends every session started from one `im` session. Returns how many ended. Used by back-channel | |
| 149 | + /// logout. | |
| 150 | + pub async fn delete_sessions_by_im_sid(&self, im_sid: &str) -> Result<u64> { | |
| 151 | + let conn = self.inner.conn.lock().await; | |
| 152 | + conn.execute( | |
| 153 | + "DELETE FROM sessions WHERE im_sid = ?1", | |
| 154 | + (im_sid.to_string(),), | |
| 155 | + ) | |
| 156 | + .await | |
| 157 | + .map_err(db_err) | |
| 158 | + } | |
| 159 | + | |
| 160 | + /// Ends every session of one person. Returns how many ended. Used when the person is disabled or | |
| 161 | + /// deleted. | |
| 162 | + pub async fn delete_sessions_by_sub(&self, sub: &str) -> Result<u64> { | |
| 163 | + let conn = self.inner.conn.lock().await; | |
| 164 | + conn.execute("DELETE FROM sessions WHERE sub = ?1", (sub.to_string(),)) | |
| 165 | + .await | |
| 166 | + .map_err(db_err) | |
| 167 | + } | |
| 168 | + | |
| 169 | + /// Removes sessions that expired at or before `now`. Returns how many were removed. | |
| 170 | + pub async fn sweep_expired_sessions(&self, now: &str) -> Result<u64> { | |
| 171 | + let conn = self.inner.conn.lock().await; | |
| 172 | + conn.execute( | |
| 173 | + "DELETE FROM sessions WHERE expires_at <= ?1", | |
| 174 | + (now.to_string(),), | |
| 175 | + ) | |
| 176 | + .await | |
| 177 | + .map_err(db_err) | |
| 178 | + } | |
| 179 | + | |
| 180 | + /// Records a back-channel logout token id. Returns `true` when the id was new and is now recorded | |
| 181 | + /// (the token may be acted on), and `false` when it was already recorded (a replay, to be refused). | |
| 182 | + /// The insert decides, so two deliveries of one token cannot both be accepted. | |
| 183 | + pub async fn seen_jti(&self, jti: &str, expires_at: &str) -> Result<bool> { | |
| 184 | + let conn = self.inner.conn.lock().await; | |
| 185 | + let inserted = conn | |
| 186 | + .execute( | |
| 187 | + "INSERT INTO seen_logout_jti (jti, expires_at) VALUES (?1, ?2) \ | |
| 188 | + ON CONFLICT (jti) DO NOTHING", | |
| 189 | + (jti.to_string(), expires_at.to_string()), | |
| 190 | + ) | |
| 191 | + .await | |
| 192 | + .map_err(db_err)?; | |
| 193 | + Ok(inserted == 1) | |
| 194 | + } | |
| 195 | + | |
| 196 | + /// Removes logout token ids that expired at or before `now`. | |
| 197 | + pub async fn sweep_jti(&self, now: &str) -> Result<u64> { | |
| 198 | + let conn = self.inner.conn.lock().await; | |
| 199 | + conn.execute( | |
| 200 | + "DELETE FROM seen_logout_jti WHERE expires_at <= ?1", | |
| 201 | + (now.to_string(),), | |
| 202 | + ) | |
| 203 | + .await | |
| 204 | + .map_err(db_err) | |
| 205 | + } | |
| 206 | +} | |
| 207 | + | |
| 208 | +#[cfg(test)] | |
| 209 | +mod tests { | |
| 210 | + use super::*; | |
| 211 | + use crate::store::test_support::store_with_member; | |
| 212 | + use crate::time::{stamp_after, stamp_before}; | |
| 213 | + use std::time::Duration; | |
| 214 | + | |
| 215 | + #[tokio::test] | |
| 216 | + async fn sessions_expire_and_disabled_members_lose_them() { | |
| 217 | + let (_dir, store) = store_with_member("ann").await; | |
| 218 | + let made = store | |
| 219 | + .create_session(NewSession { | |
| 220 | + sub: "ann".into(), | |
| 221 | + token_hash: "h1".into(), | |
| 222 | + csrf_token: "c".into(), | |
| 223 | + im_sid: "s1".into(), | |
| 224 | + expires_at: stamp_after(Duration::from_secs(3600)), | |
| 225 | + ip: None, | |
| 226 | + user_agent: None, | |
| 227 | + }) | |
| 228 | + .await | |
| 229 | + .unwrap(); | |
| 230 | + assert!(store.session_by_token_hash("h1").await.unwrap().is_some()); | |
| 231 | + | |
| 232 | + store | |
| 233 | + .apply_directory_member( | |
| 234 | + &crate::store::members::MemberFields { | |
| 235 | + sub: "ann".into(), | |
| 236 | + email: "ann@example.test".into(), | |
| 237 | + name: "Ann".into(), | |
| 238 | + is_admin: false, | |
| 239 | + locale: "en".into(), | |
| 240 | + zoneinfo: "UTC".into(), | |
| 241 | + picture_version: 0, | |
| 242 | + im_updated_at: stamp_after(Duration::from_secs(1)), | |
| 243 | + }, | |
| 244 | + true, | |
| 245 | + 0, | |
| 246 | + ) | |
| 247 | + .await | |
| 248 | + .unwrap(); | |
| 249 | + assert!(store.session_by_token_hash("h1").await.unwrap().is_none()); | |
| 250 | + assert_eq!(store.delete_sessions_by_sub("ann").await.unwrap(), 1); | |
| 251 | + assert!(store.delete_session(&made.id).await.is_ok()); | |
| 252 | + | |
| 253 | + assert!( | |
| 254 | + store | |
| 255 | + .seen_jti("j1", &stamp_after(Duration::from_secs(60))) | |
| 256 | + .await | |
| 257 | + .unwrap() | |
| 258 | + ); | |
| 259 | + assert!( | |
| 260 | + !store | |
| 261 | + .seen_jti("j1", &stamp_after(Duration::from_secs(60))) | |
| 262 | + .await | |
| 263 | + .unwrap() | |
| 264 | + ); | |
| 265 | + assert_eq!( | |
| 266 | + store | |
| 267 | + .sweep_jti(&stamp_before(Duration::from_secs(1))) | |
| 268 | + .await | |
| 269 | + .unwrap(), | |
| 270 | + 0 | |
| 271 | + ); | |
| 272 | + } | |
| 273 | +} |
crates/in-core/src/store/trash.rsadded+581 -0
| @@ -0,0 +1,581 @@ | ||
| 1 | +//! The trash: soft delete, restore, and permanent purge. | |
| 2 | +//! | |
| 3 | +//! Trashing a folder marks the folder (its `trash_root` stays empty: it is the root of that trash) and | |
| 4 | +//! every live item beneath it with the same `trashed_at`, and points their `trash_root` at it. Restoring | |
| 5 | +//! that root restores exactly the items that point at it. An item trashed on its own before its folder | |
| 6 | +//! keeps its own root, so restoring the folder leaves it in the trash. | |
| 7 | +//! | |
| 8 | +//! Purging returns the blob keys to delete. They are returned only after the transaction commits, so a | |
| 9 | +//! failed purge never leaves a row pointing at bytes that were already removed. | |
| 10 | + | |
| 11 | +use crate::error::{Error, Result}; | |
| 12 | +use crate::store::files::thumb_blob_key; | |
| 13 | +use crate::store::files::{FILE_COLS, File, map_file}; | |
| 14 | +use crate::store::folders::{FOLDER_COLS, Listing, has_trashed_chain, live_folder, map_folder}; | |
| 15 | +use crate::store::{Store, col_text, db_err, fetch_all, fetch_opt, finish, first_free_name}; | |
| 16 | +use crate::time::now_stamp; | |
| 17 | +use turso::Connection; | |
| 18 | + | |
| 19 | +/// Which kind of item a trash operation names. | |
| 20 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 21 | +pub enum ItemKind { | |
| 22 | + /// A file. | |
| 23 | + File, | |
| 24 | + /// A folder and everything beneath it. | |
| 25 | + Folder, | |
| 26 | +} | |
| 27 | + | |
| 28 | +/// Removes a file row and everything that names it, and gives back its bytes in the quota. The blob keys | |
| 29 | +/// are added to `keys` for deletion after commit. | |
| 30 | +async fn purge_file_row(conn: &Connection, file: &File, keys: &mut Vec<String>) -> Result<()> { | |
| 31 | + conn.execute("DELETE FROM files WHERE id = ?1", (file.id.clone(),)) | |
| 32 | + .await | |
| 33 | + .map_err(db_err)?; | |
| 34 | + conn.execute( | |
| 35 | + "DELETE FROM grants WHERE target_kind = 'file' AND target_id = ?1", | |
| 36 | + (file.id.clone(),), | |
| 37 | + ) | |
| 38 | + .await | |
| 39 | + .map_err(db_err)?; | |
| 40 | + conn.execute( | |
| 41 | + "DELETE FROM links WHERE target_kind = 'file' AND target_id = ?1", | |
| 42 | + (file.id.clone(),), | |
| 43 | + ) | |
| 44 | + .await | |
| 45 | + .map_err(db_err)?; | |
| 46 | + conn.execute( | |
| 47 | + "UPDATE members SET used_bytes = MAX(used_bytes - ?2, 0) WHERE sub = ?1", | |
| 48 | + (file.owner.clone(), file.size), | |
| 49 | + ) | |
| 50 | + .await | |
| 51 | + .map_err(db_err)?; | |
| 52 | + keys.push(file.blob_key.clone()); | |
| 53 | + keys.push(thumb_blob_key(&file.id)); | |
| 54 | + Ok(()) | |
| 55 | +} | |
| 56 | + | |
| 57 | +/// Permanently removes a trashed folder, its subtree, and the files in it. Children are removed before | |
| 58 | +/// their parents (deepest first), because the schema restricts deleting a parent that still has rows. | |
| 59 | +async fn purge_folder_rows( | |
| 60 | + conn: &Connection, | |
| 61 | + owner: &str, | |
| 62 | + id: &str, | |
| 63 | + keys: &mut Vec<String>, | |
| 64 | +) -> Result<()> { | |
| 65 | + let root = fetch_opt( | |
| 66 | + conn, | |
| 67 | + &format!("SELECT {FOLDER_COLS} FROM folders WHERE id = ?1 AND owner = ?2"), | |
| 68 | + (id.to_string(), owner.to_string()), | |
| 69 | + map_folder, | |
| 70 | + ) | |
| 71 | + .await? | |
| 72 | + .ok_or(Error::NotFound)?; | |
| 73 | + if root.trashed_at.is_none() { | |
| 74 | + return Err(Error::Conflict("not_in_trash".into())); | |
| 75 | + } | |
| 76 | + // Breadth first, so every parent comes before its children; walked backwards below. | |
| 77 | + let mut order = vec![root.id]; | |
| 78 | + let mut next = 0; | |
| 79 | + while next < order.len() { | |
| 80 | + let children = fetch_all( | |
| 81 | + conn, | |
| 82 | + "SELECT id FROM folders WHERE parent_id = ?1 AND owner = ?2", | |
| 83 | + (order[next].clone(), owner.to_string()), | |
| 84 | + |row| col_text(row, 0), | |
| 85 | + ) | |
| 86 | + .await?; | |
| 87 | + order.extend(children); | |
| 88 | + next += 1; | |
| 89 | + } | |
| 90 | + for folder_id in order.iter().rev() { | |
| 91 | + let files = fetch_all( | |
| 92 | + conn, | |
| 93 | + &format!("SELECT {FILE_COLS} FROM files WHERE folder_id = ?1 AND owner = ?2"), | |
| 94 | + (folder_id.clone(), owner.to_string()), | |
| 95 | + map_file, | |
| 96 | + ) | |
| 97 | + .await?; | |
| 98 | + for file in &files { | |
| 99 | + purge_file_row(conn, file, keys).await?; | |
| 100 | + } | |
| 101 | + // Uploads still in progress into this folder fall back to the top level. Finished ones are | |
| 102 | + // history and go with the folder. | |
| 103 | + conn.execute( | |
| 104 | + "UPDATE uploads SET folder_id = NULL WHERE folder_id = ?1 AND state = 'active'", | |
| 105 | + (folder_id.clone(),), | |
| 106 | + ) | |
| 107 | + .await | |
| 108 | + .map_err(db_err)?; | |
| 109 | + conn.execute( | |
| 110 | + "DELETE FROM uploads WHERE folder_id = ?1", | |
| 111 | + (folder_id.clone(),), | |
| 112 | + ) | |
| 113 | + .await | |
| 114 | + .map_err(db_err)?; | |
| 115 | + conn.execute( | |
| 116 | + "DELETE FROM grants WHERE target_kind = 'folder' AND target_id = ?1", | |
| 117 | + (folder_id.clone(),), | |
| 118 | + ) | |
| 119 | + .await | |
| 120 | + .map_err(db_err)?; | |
| 121 | + conn.execute( | |
| 122 | + "DELETE FROM links WHERE target_kind = 'folder' AND target_id = ?1", | |
| 123 | + (folder_id.clone(),), | |
| 124 | + ) | |
| 125 | + .await | |
| 126 | + .map_err(db_err)?; | |
| 127 | + conn.execute("DELETE FROM folders WHERE id = ?1", (folder_id.clone(),)) | |
| 128 | + .await | |
| 129 | + .map_err(db_err)?; | |
| 130 | + } | |
| 131 | + Ok(()) | |
| 132 | +} | |
| 133 | + | |
| 134 | +impl Store { | |
| 135 | + /// Moves a live file to the trash. Its bytes still count toward the quota until it is purged. | |
| 136 | + pub async fn trash_file(&self, owner: &str, id: &str) -> Result<()> { | |
| 137 | + let conn = self.inner.conn.lock().await; | |
| 138 | + let changed = conn | |
| 139 | + .execute( | |
| 140 | + "UPDATE files SET trashed_at = ?3, trash_root = NULL \ | |
| 141 | + WHERE id = ?1 AND owner = ?2 AND trashed_at IS NULL", | |
| 142 | + (id.to_string(), owner.to_string(), now_stamp()), | |
| 143 | + ) | |
| 144 | + .await | |
| 145 | + .map_err(db_err)?; | |
| 146 | + if changed == 0 { | |
| 147 | + return Err(Error::NotFound); | |
| 148 | + } | |
| 149 | + Ok(()) | |
| 150 | + } | |
| 151 | + | |
| 152 | + /// Moves a live folder and everything beneath it to the trash, in one transaction. The folder is | |
| 153 | + /// the trash root of the whole set. Each level is marked by one statement, repeated until nothing | |
| 154 | + /// new is marked; files are marked last, in one statement. | |
| 155 | + pub async fn trash_folder(&self, owner: &str, id: &str) -> Result<()> { | |
| 156 | + let now = now_stamp(); | |
| 157 | + let conn = self.inner.conn.lock().await; | |
| 158 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 159 | + let outcome: Result<()> = async { | |
| 160 | + live_folder(&tx, owner, id).await?; | |
| 161 | + tx.execute( | |
| 162 | + "UPDATE folders SET trashed_at = ?2, trash_root = NULL WHERE id = ?1 AND owner = ?3", | |
| 163 | + (id.to_string(), now.clone(), owner.to_string()), | |
| 164 | + ) | |
| 165 | + .await | |
| 166 | + .map_err(db_err)?; | |
| 167 | + loop { | |
| 168 | + let marked = tx | |
| 169 | + .execute( | |
| 170 | + "UPDATE folders SET trashed_at = ?2, trash_root = ?1 \ | |
| 171 | + WHERE owner = ?3 AND trashed_at IS NULL AND parent_id IN ( \ | |
| 172 | + SELECT id FROM folders WHERE owner = ?3 AND (id = ?1 OR trash_root = ?1))", | |
| 173 | + (id.to_string(), now.clone(), owner.to_string()), | |
| 174 | + ) | |
| 175 | + .await | |
| 176 | + .map_err(db_err)?; | |
| 177 | + if marked == 0 { | |
| 178 | + break; | |
| 179 | + } | |
| 180 | + } | |
| 181 | + tx.execute( | |
| 182 | + "UPDATE files SET trashed_at = ?2, trash_root = ?1 \ | |
| 183 | + WHERE owner = ?3 AND trashed_at IS NULL AND folder_id IN ( \ | |
| 184 | + SELECT id FROM folders WHERE owner = ?3 AND (id = ?1 OR trash_root = ?1))", | |
| 185 | + (id.to_string(), now.clone(), owner.to_string()), | |
| 186 | + ) | |
| 187 | + .await | |
| 188 | + .map_err(db_err)?; | |
| 189 | + Ok(()) | |
| 190 | + } | |
| 191 | + .await; | |
| 192 | + finish(tx, outcome).await | |
| 193 | + } | |
| 194 | + | |
| 195 | + /// The trashed items of `owner` that are trash roots: items trashed directly. Items that went to | |
| 196 | + /// the trash with a folder are shown under that folder's entry. | |
| 197 | + pub async fn list_trash(&self, owner: &str) -> Result<Listing> { | |
| 198 | + let conn = self.read_conn().await; | |
| 199 | + let folders = fetch_all( | |
| 200 | + &conn, | |
| 201 | + &format!( | |
| 202 | + "SELECT {FOLDER_COLS} FROM folders WHERE owner = ?1 AND trashed_at IS NOT NULL \ | |
| 203 | + AND trash_root IS NULL ORDER BY trashed_at DESC, id" | |
| 204 | + ), | |
| 205 | + (owner.to_string(),), | |
| 206 | + map_folder, | |
| 207 | + ) | |
| 208 | + .await?; | |
| 209 | + let files = fetch_all( | |
| 210 | + &conn, | |
| 211 | + &format!( | |
| 212 | + "SELECT {FILE_COLS} FROM files WHERE owner = ?1 AND trashed_at IS NOT NULL \ | |
| 213 | + AND trash_root IS NULL ORDER BY trashed_at DESC, id" | |
| 214 | + ), | |
| 215 | + (owner.to_string(),), | |
| 216 | + map_file, | |
| 217 | + ) | |
| 218 | + .await?; | |
| 219 | + Ok(Listing { folders, files }) | |
| 220 | + } | |
| 221 | + | |
| 222 | + /// Restores a trashed item of `owner` to its place. Refused with `Conflict("ancestor_trashed")` when | |
| 223 | + /// an ancestor is still in the trash, or when the item went to the trash with its folder (restore | |
| 224 | + /// that folder instead). A name taken in the place now gets the next postfix. | |
| 225 | + pub async fn restore(&self, owner: &str, kind: ItemKind, id: &str) -> Result<()> { | |
| 226 | + let now = now_stamp(); | |
| 227 | + let conn = self.inner.conn.lock().await; | |
| 228 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 229 | + let outcome: Result<()> = async { | |
| 230 | + match kind { | |
| 231 | + ItemKind::File => { | |
| 232 | + let file = fetch_opt( | |
| 233 | + &tx, | |
| 234 | + &format!( | |
| 235 | + "SELECT {FILE_COLS} FROM files WHERE id = ?1 AND owner = ?2 AND trashed_at IS NOT NULL" | |
| 236 | + ), | |
| 237 | + (id.to_string(), owner.to_string()), | |
| 238 | + map_file, | |
| 239 | + ) | |
| 240 | + .await? | |
| 241 | + .ok_or(Error::NotFound)?; | |
| 242 | + if file.trash_root.is_some() | |
| 243 | + || has_trashed_chain(&tx, file.folder_id.as_deref()).await? | |
| 244 | + { | |
| 245 | + return Err(Error::Conflict("ancestor_trashed".into())); | |
| 246 | + } | |
| 247 | + let name = first_free_name( | |
| 248 | + &tx, | |
| 249 | + "files", | |
| 250 | + owner, | |
| 251 | + file.folder_id.as_deref(), | |
| 252 | + &file.name, | |
| 253 | + true, | |
| 254 | + ) | |
| 255 | + .await?; | |
| 256 | + tx.execute( | |
| 257 | + "UPDATE files SET trashed_at = NULL, trash_root = NULL, name = ?3, updated_at = ?4 \ | |
| 258 | + WHERE id = ?1 AND owner = ?2", | |
| 259 | + (id.to_string(), owner.to_string(), name, now.clone()), | |
| 260 | + ) | |
| 261 | + .await | |
| 262 | + .map_err(db_err)?; | |
| 263 | + } | |
| 264 | + ItemKind::Folder => { | |
| 265 | + let folder = fetch_opt( | |
| 266 | + &tx, | |
| 267 | + &format!( | |
| 268 | + "SELECT {FOLDER_COLS} FROM folders WHERE id = ?1 AND owner = ?2 \ | |
| 269 | + AND trashed_at IS NOT NULL AND trash_root IS NULL" | |
| 270 | + ), | |
| 271 | + (id.to_string(), owner.to_string()), | |
| 272 | + map_folder, | |
| 273 | + ) | |
| 274 | + .await? | |
| 275 | + .ok_or(Error::NotFound)?; | |
| 276 | + if has_trashed_chain(&tx, folder.parent_id.as_deref()).await? { | |
| 277 | + return Err(Error::Conflict("ancestor_trashed".into())); | |
| 278 | + } | |
| 279 | + let name = first_free_name( | |
| 280 | + &tx, | |
| 281 | + "folders", | |
| 282 | + owner, | |
| 283 | + folder.parent_id.as_deref(), | |
| 284 | + &folder.name, | |
| 285 | + false, | |
| 286 | + ) | |
| 287 | + .await?; | |
| 288 | + tx.execute( | |
| 289 | + "UPDATE folders SET trashed_at = NULL, trash_root = NULL, name = ?3, updated_at = ?4 \ | |
| 290 | + WHERE id = ?1 AND owner = ?2", | |
| 291 | + (id.to_string(), owner.to_string(), name, now.clone()), | |
| 292 | + ) | |
| 293 | + .await | |
| 294 | + .map_err(db_err)?; | |
| 295 | + // Exactly the items that went to the trash with this folder come back. | |
| 296 | + tx.execute( | |
| 297 | + "UPDATE folders SET trashed_at = NULL, trash_root = NULL, updated_at = ?3 \ | |
| 298 | + WHERE owner = ?2 AND trash_root = ?1", | |
| 299 | + (id.to_string(), owner.to_string(), now.clone()), | |
| 300 | + ) | |
| 301 | + .await | |
| 302 | + .map_err(db_err)?; | |
| 303 | + tx.execute( | |
| 304 | + "UPDATE files SET trashed_at = NULL, trash_root = NULL, updated_at = ?3 \ | |
| 305 | + WHERE owner = ?2 AND trash_root = ?1", | |
| 306 | + (id.to_string(), owner.to_string(), now.clone()), | |
| 307 | + ) | |
| 308 | + .await | |
| 309 | + .map_err(db_err)?; | |
| 310 | + } | |
| 311 | + } | |
| 312 | + Ok(()) | |
| 313 | + } | |
| 314 | + .await; | |
| 315 | + finish(tx, outcome).await | |
| 316 | + } | |
| 317 | + | |
| 318 | + /// Permanently deletes a trashed file of `owner`. Returns the blob keys to delete now that the row is | |
| 319 | + /// gone. A live file is `Conflict("not_in_trash")`. | |
| 320 | + pub async fn purge_file(&self, owner: &str, id: &str) -> Result<Vec<String>> { | |
| 321 | + let conn = self.inner.conn.lock().await; | |
| 322 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 323 | + let mut keys = Vec::new(); | |
| 324 | + let outcome: Result<()> = async { | |
| 325 | + let file = fetch_opt( | |
| 326 | + &tx, | |
| 327 | + &format!("SELECT {FILE_COLS} FROM files WHERE id = ?1 AND owner = ?2"), | |
| 328 | + (id.to_string(), owner.to_string()), | |
| 329 | + map_file, | |
| 330 | + ) | |
| 331 | + .await? | |
| 332 | + .ok_or(Error::NotFound)?; | |
| 333 | + if file.trashed_at.is_none() { | |
| 334 | + return Err(Error::Conflict("not_in_trash".into())); | |
| 335 | + } | |
| 336 | + purge_file_row(&tx, &file, &mut keys).await | |
| 337 | + } | |
| 338 | + .await; | |
| 339 | + finish(tx, outcome).await?; | |
| 340 | + Ok(keys) | |
| 341 | + } | |
| 342 | + | |
| 343 | + /// Permanently deletes a trashed folder of `owner` with everything beneath it. Returns the blob keys | |
| 344 | + /// to delete after commit. | |
| 345 | + pub async fn purge_folder(&self, owner: &str, id: &str) -> Result<Vec<String>> { | |
| 346 | + let conn = self.inner.conn.lock().await; | |
| 347 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 348 | + let mut keys = Vec::new(); | |
| 349 | + let outcome: Result<()> = purge_folder_rows(&tx, owner, id, &mut keys).await; | |
| 350 | + finish(tx, outcome).await?; | |
| 351 | + Ok(keys) | |
| 352 | + } | |
| 353 | + | |
| 354 | + /// Permanently deletes everything `owner` has in the trash. Folder roots go first, which takes their | |
| 355 | + /// subtrees with them; the files left over are then purged. One transaction. | |
| 356 | + pub async fn empty_trash(&self, owner: &str) -> Result<Vec<String>> { | |
| 357 | + let conn = self.inner.conn.lock().await; | |
| 358 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 359 | + let mut keys = Vec::new(); | |
| 360 | + let outcome: Result<()> = async { | |
| 361 | + let roots = fetch_all( | |
| 362 | + &tx, | |
| 363 | + "SELECT id FROM folders WHERE owner = ?1 AND trashed_at IS NOT NULL AND trash_root IS NULL", | |
| 364 | + (owner.to_string(),), | |
| 365 | + |row| col_text(row, 0), | |
| 366 | + ) | |
| 367 | + .await?; | |
| 368 | + for root in &roots { | |
| 369 | + purge_folder_rows(&tx, owner, root, &mut keys).await?; | |
| 370 | + } | |
| 371 | + let files = fetch_all( | |
| 372 | + &tx, | |
| 373 | + &format!("SELECT {FILE_COLS} FROM files WHERE owner = ?1 AND trashed_at IS NOT NULL"), | |
| 374 | + (owner.to_string(),), | |
| 375 | + map_file, | |
| 376 | + ) | |
| 377 | + .await?; | |
| 378 | + for file in &files { | |
| 379 | + purge_file_row(&tx, file, &mut keys).await?; | |
| 380 | + } | |
| 381 | + Ok(()) | |
| 382 | + } | |
| 383 | + .await; | |
| 384 | + finish(tx, outcome).await?; | |
| 385 | + Ok(keys) | |
| 386 | + } | |
| 387 | + | |
| 388 | + /// Permanently deletes every trash root trashed before `cutoff` (a stamp), for every owner. Each | |
| 389 | + /// purge is its own transaction, so one slow purge does not hold the writer for the whole pass. A | |
| 390 | + /// failed purge is logged and skipped. Returns all blob keys to delete. | |
| 391 | + pub async fn purge_trashed_before(&self, cutoff: &str) -> Result<Vec<String>> { | |
| 392 | + let (folder_roots, file_roots) = { | |
| 393 | + let conn = self.read_conn().await; | |
| 394 | + let folders = fetch_all( | |
| 395 | + &conn, | |
| 396 | + "SELECT owner, id FROM folders WHERE trashed_at IS NOT NULL AND trash_root IS NULL \ | |
| 397 | + AND trashed_at < ?1", | |
| 398 | + (cutoff.to_string(),), | |
| 399 | + |row| Ok((col_text(row, 0)?, col_text(row, 1)?)), | |
| 400 | + ) | |
| 401 | + .await?; | |
| 402 | + let files = fetch_all( | |
| 403 | + &conn, | |
| 404 | + "SELECT owner, id FROM files WHERE trashed_at IS NOT NULL AND trash_root IS NULL \ | |
| 405 | + AND trashed_at < ?1", | |
| 406 | + (cutoff.to_string(),), | |
| 407 | + |row| Ok((col_text(row, 0)?, col_text(row, 1)?)), | |
| 408 | + ) | |
| 409 | + .await?; | |
| 410 | + (folders, files) | |
| 411 | + }; | |
| 412 | + let mut keys = Vec::new(); | |
| 413 | + for (owner, id) in &folder_roots { | |
| 414 | + match self.purge_folder(owner, id).await { | |
| 415 | + Ok(k) => keys.extend(k), | |
| 416 | + Err(Error::NotFound | Error::Conflict(_)) => {} | |
| 417 | + Err(e) => tracing::warn!(folder = %id, error = %e, "trash purge skipped"), | |
| 418 | + } | |
| 419 | + } | |
| 420 | + for (owner, id) in &file_roots { | |
| 421 | + match self.purge_file(owner, id).await { | |
| 422 | + Ok(k) => keys.extend(k), | |
| 423 | + Err(Error::NotFound | Error::Conflict(_)) => {} | |
| 424 | + Err(e) => tracing::warn!(file = %id, error = %e, "trash purge skipped"), | |
| 425 | + } | |
| 426 | + } | |
| 427 | + Ok(keys) | |
| 428 | + } | |
| 429 | +} | |
| 430 | + | |
| 431 | +#[cfg(test)] | |
| 432 | +mod tests { | |
| 433 | + use super::*; | |
| 434 | + use crate::store::files::{NewFile, files_blob_key}; | |
| 435 | + use crate::store::new_id; | |
| 436 | + use crate::store::test_support::store_with_member; | |
| 437 | + | |
| 438 | + /// Inserts a file of `size` bytes named `name` into `folder` and returns it. | |
| 439 | + async fn put(store: &Store, owner: &str, folder: Option<&str>, name: &str, size: i64) -> File { | |
| 440 | + store | |
| 441 | + .insert_file(NewFile { | |
| 442 | + id: new_id(), | |
| 443 | + owner: owner.into(), | |
| 444 | + folder: folder.map(str::to_string), | |
| 445 | + name: name.into(), | |
| 446 | + mime: "text/plain".into(), | |
| 447 | + size, | |
| 448 | + sha256: "0".repeat(64), | |
| 449 | + staged_claims: 0, | |
| 450 | + }) | |
| 451 | + .await | |
| 452 | + .unwrap() | |
| 453 | + } | |
| 454 | + | |
| 455 | + #[tokio::test] | |
| 456 | + async fn quota_refuses_overflow_and_purge_gives_bytes_back() { | |
| 457 | + let (_dir, store) = store_with_member("ann").await; | |
| 458 | + store.set_quota("ann", 150).await.unwrap(); | |
| 459 | + let first = put(&store, "ann", None, "a.bin", 100).await; | |
| 460 | + assert_eq!(first.blob_key, files_blob_key(&first.id)); | |
| 461 | + let refused = store | |
| 462 | + .insert_file(NewFile { | |
| 463 | + id: new_id(), | |
| 464 | + owner: "ann".into(), | |
| 465 | + folder: None, | |
| 466 | + name: "b.bin".into(), | |
| 467 | + mime: "application/octet-stream".into(), | |
| 468 | + size: 100, | |
| 469 | + sha256: "0".repeat(64), | |
| 470 | + staged_claims: 0, | |
| 471 | + }) | |
| 472 | + .await; | |
| 473 | + assert!(matches!(refused, Err(Error::Conflict(ref m)) if m == "quota_exceeded")); | |
| 474 | + assert_eq!(store.member("ann").await.unwrap().unwrap().used_bytes, 100); | |
| 475 | + | |
| 476 | + // Trashed bytes still count; purging them frees the quota and reports the blob keys. | |
| 477 | + store.trash_file("ann", &first.id).await.unwrap(); | |
| 478 | + assert_eq!(store.member("ann").await.unwrap().unwrap().used_bytes, 100); | |
| 479 | + let keys = store.purge_file("ann", &first.id).await.unwrap(); | |
| 480 | + assert!(keys.contains(&first.blob_key)); | |
| 481 | + assert_eq!(store.member("ann").await.unwrap().unwrap().used_bytes, 0); | |
| 482 | + assert!(store.file(&first.id).await.unwrap().is_none()); | |
| 483 | + } | |
| 484 | + | |
| 485 | + #[tokio::test] | |
| 486 | + async fn trashing_a_folder_and_restoring_it_restores_exactly_its_subtree() { | |
| 487 | + let (_dir, store) = store_with_member("ann").await; | |
| 488 | + let top = store.create_folder("ann", None, "Top").await.unwrap(); | |
| 489 | + let inner = store | |
| 490 | + .create_folder("ann", Some(&top.id), "Inner") | |
| 491 | + .await | |
| 492 | + .unwrap(); | |
| 493 | + let in_top = put(&store, "ann", Some(&top.id), "in-top.txt", 1).await; | |
| 494 | + let in_inner = put(&store, "ann", Some(&inner.id), "in-inner.txt", 1).await; | |
| 495 | + // Trashed on its own before its folder: must stay in the trash after the folder is restored. | |
| 496 | + let alone = put(&store, "ann", Some(&top.id), "alone.txt", 1).await; | |
| 497 | + store.trash_file("ann", &alone.id).await.unwrap(); | |
| 498 | + let outside = store.create_folder("ann", None, "Other").await.unwrap(); | |
| 499 | + | |
| 500 | + store.trash_folder("ann", &top.id).await.unwrap(); | |
| 501 | + let trash = store.list_trash("ann").await.unwrap(); | |
| 502 | + assert_eq!( | |
| 503 | + trash | |
| 504 | + .folders | |
| 505 | + .iter() | |
| 506 | + .map(|f| f.id.as_str()) | |
| 507 | + .collect::<Vec<_>>(), | |
| 508 | + [top.id.as_str()] | |
| 509 | + ); | |
| 510 | + assert_eq!( | |
| 511 | + trash | |
| 512 | + .files | |
| 513 | + .iter() | |
| 514 | + .map(|f| f.id.as_str()) | |
| 515 | + .collect::<Vec<_>>(), | |
| 516 | + [alone.id.as_str()] | |
| 517 | + ); | |
| 518 | + assert!( | |
| 519 | + store | |
| 520 | + .list_children("ann", None) | |
| 521 | + .await | |
| 522 | + .unwrap() | |
| 523 | + .folders | |
| 524 | + .iter() | |
| 525 | + .all(|f| f.id != top.id) | |
| 526 | + ); | |
| 527 | + assert!( | |
| 528 | + store | |
| 529 | + .list_children("ann", None) | |
| 530 | + .await | |
| 531 | + .unwrap() | |
| 532 | + .folders | |
| 533 | + .iter() | |
| 534 | + .any(|f| f.id == outside.id) | |
| 535 | + ); | |
| 536 | + | |
| 537 | + store | |
| 538 | + .restore("ann", ItemKind::Folder, &top.id) | |
| 539 | + .await | |
| 540 | + .unwrap(); | |
| 541 | + let root = store.list_children("ann", None).await.unwrap(); | |
| 542 | + assert!(root.folders.iter().any(|f| f.id == top.id)); | |
| 543 | + let under_top = store.list_children("ann", Some(&top.id)).await.unwrap(); | |
| 544 | + assert_eq!( | |
| 545 | + under_top | |
| 546 | + .folders | |
| 547 | + .iter() | |
| 548 | + .map(|f| f.id.as_str()) | |
| 549 | + .collect::<Vec<_>>(), | |
| 550 | + [inner.id.as_str()] | |
| 551 | + ); | |
| 552 | + assert_eq!( | |
| 553 | + under_top | |
| 554 | + .files | |
| 555 | + .iter() | |
| 556 | + .map(|f| f.id.as_str()) | |
| 557 | + .collect::<Vec<_>>(), | |
| 558 | + [in_top.id.as_str()] | |
| 559 | + ); | |
| 560 | + let under_inner = store.list_children("ann", Some(&inner.id)).await.unwrap(); | |
| 561 | + assert_eq!( | |
| 562 | + under_inner | |
| 563 | + .files | |
| 564 | + .iter() | |
| 565 | + .map(|f| f.id.as_str()) | |
| 566 | + .collect::<Vec<_>>(), | |
| 567 | + [in_inner.id.as_str()] | |
| 568 | + ); | |
| 569 | + // The individually trashed file is still in the trash, and is not restored with the folder. | |
| 570 | + let trash = store.list_trash("ann").await.unwrap(); | |
| 571 | + assert_eq!( | |
| 572 | + trash | |
| 573 | + .files | |
| 574 | + .iter() | |
| 575 | + .map(|f| f.id.as_str()) | |
| 576 | + .collect::<Vec<_>>(), | |
| 577 | + [alone.id.as_str()] | |
| 578 | + ); | |
| 579 | + assert!(trash.folders.is_empty()); | |
| 580 | + } | |
| 581 | +} |