S002: test server with faults, fixtures and proxy stubs

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-24 23:40:52 -06:00
commit 9ff6bd8876
13 changed files with 3065 additions and 15 deletions

View file

@ -71,6 +71,7 @@ Never modify: everything outside this folder. `~/Projects/*` is read-only refere
|---|---|---|
| `nice cargo test -j 2` | unit and engine tests | 01 Foundation |
| `nice cargo build --release -j 2` | release build (never at the same time as the tests) | 01 Foundation |
| `nice cargo test -j 2 -p medlar-testserver` / `cargo run -p medlar-testserver -- [--port N] [--tls] [--media] [--proxies]` | local server with faults and proxy stubs; API in the `crates/testserver/src/lib.rs` header | S002 |
| `ssh [email protected] hub-release` | release notes on Astar Hub (release only, after the user's yes) | now |
Don't assume a tool exists: check first. When your plan creates a tool, add its row here.

588
Cargo.lock generated
View file

@ -20,24 +20,93 @@ dependencies = [
"libc",
]
[[package]]
name = "asn1-rs"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8"
dependencies = [
"asn1-rs-derive",
"asn1-rs-impl",
"displaydoc",
"nom",
"num-traits",
"rusticata-macros",
"thiserror",
"time",
]
[[package]]
name = "asn1-rs-derive"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
"synstructure 0.13.2",
]
[[package]]
name = "asn1-rs-impl"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "base64"
version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
[[package]]
name = "bit-vec"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"
dependencies = [
"serde",
]
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "block-buffer"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
dependencies = [
"hybrid-array",
]
[[package]]
name = "bumpalo"
version = "3.20.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db"
[[package]]
name = "bytes"
version = "1.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c"
[[package]]
name = "cc"
version = "1.11.3"
@ -65,12 +134,73 @@ dependencies = [
"windows-link",
]
[[package]]
name = "const-oid"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
[[package]]
name = "core-foundation-sys"
version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
[[package]]
name = "cpufeatures"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
dependencies = [
"libc",
]
[[package]]
name = "crypto-common"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
dependencies = [
"hybrid-array",
]
[[package]]
name = "data-encoding"
version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
[[package]]
name = "der-parser"
version = "10.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6"
dependencies = [
"asn1-rs",
"displaydoc",
"nom",
"num-bigint",
"num-traits",
"rusticata-macros",
]
[[package]]
name = "deranged"
version = "0.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
[[package]]
name = "digest"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
dependencies = [
"block-buffer",
"const-oid",
"crypto-common",
]
[[package]]
name = "dirs"
version = "6.0.0"
@ -89,7 +219,7 @@ dependencies = [
"libc",
"option-ext",
"redox_users",
"windows-sys",
"windows-sys 0.61.2",
]
[[package]]
@ -110,7 +240,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776"
dependencies = [
"libc",
"windows-sys",
"windows-sys 0.61.2",
]
[[package]]
@ -176,6 +306,17 @@ dependencies = [
"slab",
]
[[package]]
name = "getrandom"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "getrandom"
version = "0.4.3"
@ -205,6 +346,15 @@ dependencies = [
"hashbrown",
]
[[package]]
name = "hybrid-array"
version = "0.4.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
dependencies = [
"typenum",
]
[[package]]
name = "iana-time-zone"
version = "0.1.65"
@ -350,6 +500,12 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "lazy_static"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
[[package]]
name = "libc"
version = "0.2.191"
@ -394,6 +550,16 @@ version = "0.4.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
[[package]]
name = "md-5"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98"
dependencies = [
"cfg-if",
"digest",
]
[[package]]
name = "medlar"
version = "0.1.0"
@ -426,6 +592,15 @@ dependencies = [
[[package]]
name = "medlar-testserver"
version = "0.1.0"
dependencies = [
"md-5",
"rcgen",
"sha1",
"sha2",
"socket2",
"tokio",
"tokio-rustls",
]
[[package]]
name = "memchr"
@ -433,6 +608,58 @@ version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "minimal-lexical"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]]
name = "mio"
version = "1.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a"
dependencies = [
"libc",
"wasi",
"windows-sys 0.61.2",
]
[[package]]
name = "nom"
version = "7.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
dependencies = [
"memchr",
"minimal-lexical",
]
[[package]]
name = "num-bigint"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
dependencies = [
"num-integer",
"num-traits",
]
[[package]]
name = "num-conv"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
[[package]]
name = "num-integer"
version = "0.1.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
dependencies = [
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.19"
@ -442,6 +669,15 @@ dependencies = [
"autocfg",
]
[[package]]
name = "oid-registry"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7"
dependencies = [
"asn1-rs",
]
[[package]]
name = "once_cell"
version = "1.21.4"
@ -454,6 +690,16 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
[[package]]
name = "pem"
version = "4.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120"
dependencies = [
"base64",
"serde_core",
]
[[package]]
name = "percent-encoding"
version = "2.3.2"
@ -481,6 +727,12 @@ dependencies = [
"zerovec",
]
[[package]]
name = "powerfmt"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958"
[[package]]
name = "proc-macro2"
version = "1.0.107"
@ -505,6 +757,20 @@ version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rcgen"
version = "0.14.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8"
dependencies = [
"pem",
"ring",
"rustls-pki-types",
"time",
"x509-parser",
"yasna",
]
[[package]]
name = "redox_users"
version = "0.5.3"
@ -544,6 +810,20 @@ version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
[[package]]
name = "ring"
version = "0.17.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
dependencies = [
"cc",
"cfg-if",
"getrandom 0.2.17",
"libc",
"untrusted",
"windows-sys 0.52.0",
]
[[package]]
name = "rsqlite-vfs"
version = "0.2.0"
@ -568,6 +848,15 @@ dependencies = [
"sqlite-wasm-rs",
]
[[package]]
name = "rusticata-macros"
version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632"
dependencies = [
"nom",
]
[[package]]
name = "rustix"
version = "1.1.6"
@ -578,7 +867,41 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys",
"windows-sys",
"windows-sys 0.61.2",
]
[[package]]
name = "rustls"
version = "0.23.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
dependencies = [
"once_cell",
"ring",
"rustls-pki-types",
"rustls-webpki",
"subtle",
"zeroize",
]
[[package]]
name = "rustls-pki-types"
version = "1.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb"
dependencies = [
"zeroize",
]
[[package]]
name = "rustls-webpki"
version = "0.103.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5"
dependencies = [
"ring",
"rustls-pki-types",
"untrusted",
]
[[package]]
@ -630,12 +953,44 @@ dependencies = [
"zmij",
]
[[package]]
name = "sha1"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "sha2"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "shlex"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "signal-hook-registry"
version = "1.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
dependencies = [
"errno",
"libc",
]
[[package]]
name = "slab"
version = "0.4.12"
@ -648,6 +1003,16 @@ version = "1.16.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59"
[[package]]
name = "socket2"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
dependencies = [
"libc",
"windows-sys 0.61.2",
]
[[package]]
name = "sqlite-wasm-rs"
version = "0.6.3"
@ -664,6 +1029,12 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "syn"
version = "2.0.119"
@ -686,6 +1057,17 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "synstructure"
version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "synstructure"
version = "0.14.0"
@ -704,10 +1086,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom",
"getrandom 0.4.3",
"once_cell",
"rustix",
"windows-sys",
"windows-sys 0.61.2",
]
[[package]]
@ -730,6 +1112,36 @@ dependencies = [
"syn 3.0.10",
]
[[package]]
name = "time"
version = "0.3.55"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134"
dependencies = [
"deranged",
"num-conv",
"powerfmt",
"serde_core",
"time-core",
"time-macros",
]
[[package]]
name = "time-core"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"
[[package]]
name = "time-macros"
version = "0.2.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85"
dependencies = [
"num-conv",
"time-core",
]
[[package]]
name = "tinystr"
version = "0.8.5"
@ -740,12 +1152,61 @@ dependencies = [
"zerovec",
]
[[package]]
name = "tokio"
version = "1.54.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3"
dependencies = [
"bytes",
"libc",
"mio",
"pin-project-lite",
"signal-hook-registry",
"socket2",
"tokio-macros",
"windows-sys 0.61.2",
]
[[package]]
name = "tokio-macros"
version = "2.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "tokio-rustls"
version = "0.26.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db"
dependencies = [
"rustls",
"tokio",
]
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "untrusted"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "url"
version = "2.5.9"
@ -779,6 +1240,12 @@ version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
name = "wasm-bindgen"
version = "0.2.130"
@ -882,6 +1349,15 @@ dependencies = [
"windows-link",
]
[[package]]
name = "windows-sys"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-sys"
version = "0.61.2"
@ -891,12 +1367,104 @@ dependencies = [
"windows-link",
]
[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_gnullvm",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "writeable"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
[[package]]
name = "x509-parser"
version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202"
dependencies = [
"asn1-rs",
"data-encoding",
"der-parser",
"lazy_static",
"nom",
"oid-registry",
"ring",
"rusticata-macros",
"thiserror",
"time",
]
[[package]]
name = "yasna"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282"
dependencies = [
"bit-vec",
"time",
]
[[package]]
name = "yoke"
version = "0.8.4"
@ -917,7 +1485,7 @@ dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
"synstructure",
"synstructure 0.14.0",
]
[[package]]
@ -938,9 +1506,15 @@ dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
"synstructure",
"synstructure 0.14.0",
]
[[package]]
name = "zeroize"
version = "1.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa"
[[package]]
name = "zerotrie"
version = "0.2.5"

View file

@ -11,13 +11,13 @@ One local server that can behave like every good and bad host, so the engine is
- crates/testserver (skeleton)
## Steps
- [ ] Deterministic content by seed and length, so any byte range can be checked without storing files (up to 100 GB virtual)
- [ ] HTTP/1.1 with ranges, ETag, Last-Modified, Content-Disposition variants, redirects, chunked and no-length replies; optional TLS with a generated certificate
- [ ] Faults per path or on command: throttle per connection and total, latency, stall, cut after N bytes, reset, 403/404/410/416/429 with Retry-After/500/503, wrong length, ignores Range, changes content mid-way, forces gzip, link that expires after N seconds or requests, cap on connections per client
- [ ] Logins (Basic, Digest, cookie, referrer check), an open directory listing, a ZIP and TAR, a small site tree, HLS and DASH fixtures made with /usr/bin/ffmpeg at test time, Metalink files, checksum sidecars
- [ ] HTTP and SOCKS5 proxy stubs on loopback that record what passed
- [ ] Library API (`TestServer::start()` on port 0, request log, live fault switches) and a `medlar-testserver` binary; row added to CLAUDE.md §5
- [ ] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S002: …`, push
- [x] Deterministic content by seed and length, so any byte range can be checked without storing files (up to 100 GB virtual)
- [x] HTTP/1.1 with ranges, ETag, Last-Modified, Content-Disposition variants, redirects, chunked and no-length replies; optional TLS with a generated certificate
- [x] Faults per path or on command: throttle per connection and total, latency, stall, cut after N bytes, reset, 403/404/410/416/429 with Retry-After/500/503, wrong length, ignores Range, changes content mid-way, forces gzip, link that expires after N seconds or requests, cap on connections per client
- [x] Logins (Basic, Digest, cookie, referrer check), an open directory listing, a ZIP and TAR, a small site tree, HLS and DASH fixtures made with /usr/bin/ffmpeg at test time, Metalink files, checksum sidecars
- [x] HTTP and SOCKS5 proxy stubs on loopback that record what passed
- [x] Library API (`TestServer::start()` on port 0, request log, live fault switches) and a `medlar-testserver` binary; row added to CLAUDE.md §5
- [x] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S002: …`, push
## End criteria
- `nice cargo test -j 2 -p medlar-testserver` green, with a test per fault

View file

@ -7,7 +7,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H
## 01 Foundation
- [x] [S001](01%20Foundation/S001-workspace-store-settings.md) Workspace, store, settings and strings
- [ ] [S002](01%20Foundation/S002-test-server.md) Test server with faults
- [x] [S002](01%20Foundation/S002-test-server.md) Test server with faults
- [ ] [S003](01%20Foundation/S003-shell-motion-tools.md) App shell, theme, motion and screenshot tools
## 02 Engine

View file

@ -6,3 +6,10 @@ license.workspace = true
description = "Local server with faults, for Medlar's tests"
[dependencies]
md-5 = "0.11.0"
rcgen = { version = "0.14.10", default-features = false, features = ["crypto", "ring", "pem"] }
sha1 = "0.11.0"
sha2 = "0.11.1"
socket2 = { version = "0.6.5", features = ["all"] }
tokio = { version = "1.54.1", features = ["rt-multi-thread", "net", "io-util", "time", "sync", "macros", "signal"] }
tokio-rustls = { version = "0.26.6", default-features = false, features = ["ring", "tls12"] }

View file

@ -0,0 +1,344 @@
//! Deterministic bytes by seed, and the small hand-made fixtures (zip, tar, hashes).
use std::sync::Arc;
use md5::Md5;
use sha1::Sha1;
use sha2::{Digest, Sha256, Sha512};
fn splitmix(mut x: u64) -> u64 {
x = x.wrapping_add(0x9E37_79B9_7F4A_7C15);
x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
x ^ (x >> 31)
}
/// Fill `buf` with the bytes of virtual file `seed` starting at offset `start`.
pub fn fill(seed: u64, start: u64, buf: &mut [u8]) {
let mut pos = start;
let mut i = 0;
while i < buf.len() {
let block = pos / 8;
let word = splitmix(seed ^ block.wrapping_mul(0xA24B_AED4_963E_E407)).to_le_bytes();
let skip = (pos % 8) as usize;
let n = (8 - skip).min(buf.len() - i);
buf[i..i + n].copy_from_slice(&word[skip..skip + n]);
i += n;
pos += n as u64;
}
}
/// The bytes a client must get for `len` bytes of file `seed` from `start`.
pub fn expected(seed: u64, start: u64, len: usize) -> Vec<u8> {
let mut v = vec![0; len];
fill(seed, start, &mut v);
v
}
/// Where the bytes of a reply come from.
#[derive(Clone)]
pub enum Source {
Gen { seed: u64, len: u64 },
Bytes(Arc<Vec<u8>>),
}
impl Source {
pub fn bytes(v: impl Into<Vec<u8>>) -> Source {
Source::Bytes(Arc::new(v.into()))
}
#[allow(clippy::len_without_is_empty)]
pub fn len(&self) -> u64 {
match self {
Source::Gen { len, .. } => *len,
Source::Bytes(b) => b.len() as u64,
}
}
/// Read at `start`; `changed` returns the "other version" of the bytes.
pub fn read(&self, start: u64, buf: &mut [u8], changed: bool) {
match self {
Source::Gen { seed, .. } => fill(if changed { !seed } else { *seed }, start, buf),
Source::Bytes(b) => {
let s = start as usize;
buf.copy_from_slice(&b[s..s + buf.len()]);
if changed {
buf.iter_mut().for_each(|x| *x ^= 0xFF);
}
}
}
}
/// Same file with another version number (another seed, so other bytes).
pub fn versioned(&self, version: u32) -> Source {
match self {
Source::Gen { seed, len } if version > 0 => Source::Gen {
seed: seed ^ (u64::from(version) * 0x1234_5678_9ABC_DEF1),
len: *len,
},
other => other.clone(),
}
}
}
/// `12`, `4k`, `3m`, `100g`, `2t` → bytes.
pub fn parse_len(s: &str) -> Option<u64> {
let (num, mul) = match s.as_bytes().last()? {
b'k' | b'K' => (&s[..s.len() - 1], 1 << 10),
b'm' | b'M' => (&s[..s.len() - 1], 1 << 20),
b'g' | b'G' => (&s[..s.len() - 1], 1 << 30),
b't' | b'T' => (&s[..s.len() - 1], 1u64 << 40),
_ => (s, 1),
};
num.parse::<u64>().ok()?.checked_mul(mul)
}
pub fn crc32(data: &[u8]) -> u32 {
let mut crc = !0u32;
for &b in data {
crc ^= u32::from(b);
for _ in 0..8 {
crc = (crc >> 1) ^ (0xEDB8_8320 & (!(crc & 1)).wrapping_add(1));
}
}
!crc
}
pub fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
pub fn base64(data: &[u8]) -> String {
const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::new();
for c in data.chunks(3) {
let n = (u32::from(c[0]) << 16)
| (u32::from(*c.get(1).unwrap_or(&0)) << 8)
| u32::from(*c.get(2).unwrap_or(&0));
for i in 0..4 {
if i <= c.len() {
out.push(T[((n >> (18 - 6 * i)) & 63) as usize] as char);
} else {
out.push('=');
}
}
}
out
}
pub fn md5_hex(data: &[u8]) -> String {
hex(&Md5::digest(data))
}
/// Hash of a virtual file (streamed, so a big length is fine but slow).
pub fn hash_source(algo: &str, src: &Source) -> Option<Vec<u8>> {
fn run<D: Digest>(src: &Source) -> Vec<u8> {
let mut d = D::new();
let mut buf = vec![0u8; 1 << 16];
let mut pos = 0;
while pos < src.len() {
let n = buf.len().min((src.len() - pos) as usize);
src.read(pos, &mut buf[..n], false);
d.update(&buf[..n]);
pos += n as u64;
}
d.finalize().to_vec()
}
Some(match algo {
"md5" => run::<Md5>(src),
"sha1" => run::<Sha1>(src),
"sha256" => run::<Sha256>(src),
"sha512" => run::<Sha512>(src),
_ => return None,
})
}
/// Files inside the fixed ZIP and TAR: (name, seed, length).
pub const ARCHIVE_FILES: [(&str, u64, usize); 3] =
[("one.bin", 11, 3000), ("two/inner.bin", 12, 5000), ("three.bin", 13, 40000)];
/// A ZIP with stored (uncompressed) entries; the central directory is at the end.
pub fn make_zip() -> Vec<u8> {
let mut out = Vec::new();
let mut central = Vec::new();
for (name, seed, len) in ARCHIVE_FILES {
let data = expected(seed, 0, len);
let crc = crc32(&data);
let offset = out.len() as u32;
let mut common = Vec::new();
common.extend(20u16.to_le_bytes()); // version needed
common.extend(0u16.to_le_bytes()); // flags
common.extend(0u16.to_le_bytes()); // stored
common.extend(0u16.to_le_bytes()); // time
common.extend(0x5821u16.to_le_bytes()); // date
common.extend(crc.to_le_bytes());
common.extend((len as u32).to_le_bytes());
common.extend((len as u32).to_le_bytes());
common.extend((name.len() as u16).to_le_bytes());
common.extend(0u16.to_le_bytes()); // extra
out.extend(0x0403_4b50u32.to_le_bytes());
out.extend(&common);
out.extend(name.as_bytes());
out.extend(&data);
central.extend(0x0201_4b50u32.to_le_bytes());
central.extend(20u16.to_le_bytes()); // made by
central.extend(&common);
central.extend(0u16.to_le_bytes()); // comment
central.extend(0u16.to_le_bytes()); // disk
central.extend(0u16.to_le_bytes()); // internal attrs
central.extend(0u32.to_le_bytes()); // external attrs
central.extend(offset.to_le_bytes());
central.extend(name.as_bytes());
}
let cd_offset = out.len() as u32;
out.extend(&central);
out.extend(0x0605_4b50u32.to_le_bytes());
out.extend([0u8; 4]); // disk numbers
out.extend((ARCHIVE_FILES.len() as u16).to_le_bytes());
out.extend((ARCHIVE_FILES.len() as u16).to_le_bytes());
out.extend((central.len() as u32).to_le_bytes());
out.extend(cd_offset.to_le_bytes());
out.extend(0u16.to_le_bytes());
out
}
/// A ustar TAR with the same files.
pub fn make_tar() -> Vec<u8> {
let mut out = Vec::new();
for (name, seed, len) in ARCHIVE_FILES {
let mut h = [0u8; 512];
h[..name.len()].copy_from_slice(name.as_bytes());
h[100..107].copy_from_slice(b"0000644");
h[108..115].copy_from_slice(b"0000000");
h[116..123].copy_from_slice(b"0000000");
h[124..135].copy_from_slice(format!("{len:011o}").as_bytes());
h[136..147].copy_from_slice(b"14000000000");
h[156] = b'0';
h[257..263].copy_from_slice(b"ustar\0");
h[263..265].copy_from_slice(b"00");
h[148..156].fill(b' ');
let sum: u32 = h.iter().map(|&b| u32::from(b)).sum();
h[148..155].copy_from_slice(format!("{sum:06o}\0").as_bytes());
out.extend(h);
out.extend(expected(seed, 0, len));
out.resize(out.len().div_ceil(512) * 512, 0);
}
out.extend([0u8; 1024]);
out
}
/// The open directory tree: (dir, entries). A trailing `/` marks a sub directory.
pub fn dir_entries(path: &str) -> Option<Vec<(&'static str, u64)>> {
match path {
"/dir/" => Some(vec![
("a.bin", 10_000),
("b.bin", 20_000),
("notes.txt", 12),
("sub/", 0),
("pack.zip", make_zip().len() as u64),
("pack.tar", make_tar().len() as u64),
]),
"/dir/sub/" => Some(vec![("deep.bin", 5_000), ("../", 0)]),
_ => None,
}
}
/// A file of the open directory tree.
pub fn dir_file(path: &str) -> Option<Source> {
Some(match path {
"/dir/a.bin" => Source::Gen { seed: 1, len: 10_000 },
"/dir/b.bin" => Source::Gen { seed: 2, len: 20_000 },
"/dir/notes.txt" => Source::bytes("hello notes\n"),
"/dir/sub/deep.bin" => Source::Gen { seed: 3, len: 5_000 },
"/dir/pack.zip" => Source::bytes(make_zip()),
"/dir/pack.tar" => Source::bytes(make_tar()),
_ => return None,
})
}
pub fn dir_listing(path: &str) -> Option<String> {
let entries = dir_entries(path)?;
let mut html = format!("<html><head><title>Index of {path}</title></head><body><h1>Index of {path}</h1><pre>\n");
for (name, size) in entries {
if name.ends_with('/') {
html.push_str(&format!("<a href=\"{name}\">{name}</a>\n"));
} else {
html.push_str(&format!("<a href=\"{name}\">{name}</a> {size}\n"));
}
}
html.push_str("</pre></body></html>\n");
Some(html)
}
/// The small site: (content type, body).
pub fn site_page(path: &str) -> Option<(&'static str, Source)> {
let html = |s: &str| Some(("text/html", Source::bytes(s)));
match path {
"/site/" | "/site/index.html" => html(
"<html><body><a href=\"page1.html\">one</a> <a href=\"a/page2.html\">two</a> \
<a href=\"/site/a/b/page3.html\">three</a> <a href=\"http://elsewhere.invalid/x.html\">out</a> \
<img src=\"img/logo.bin\"><link rel=\"stylesheet\" href=\"style.css\"></body></html>",
),
"/site/page1.html" => html("<html><body><a href=\"index.html\">home</a> <a href=\"a/page2.html\">two</a></body></html>"),
"/site/a/page2.html" => html("<html><body><a href=\"../index.html\">home</a> <a href=\"b/page3.html\">three</a></body></html>"),
"/site/a/b/page3.html" => html("<html><body><a href=\"../../index.html\">home</a> <a href=\"../../files/big.bin\">big</a></body></html>"),
"/site/style.css" => Some(("text/css", Source::bytes("body{color:#123}"))),
"/site/img/logo.bin" => Some(("application/octet-stream", Source::Gen { seed: 21, len: 2_000 })),
"/site/files/big.bin" => Some(("application/octet-stream", Source::Gen { seed: 22, len: 50_000 })),
_ => None,
}
}
/// The fixed file the metalink fixtures describe.
pub const META_SEED: u64 = 5;
pub const META_LEN: u64 = 50_000;
pub fn metalink4(base: &str) -> String {
let src = Source::Gen { seed: META_SEED, len: META_LEN };
let sha = hex(&hash_source("sha256", &src).unwrap());
format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<metalink xmlns=\"urn:ietf:params:xml:ns:metalink\">\n\
<file name=\"meta.bin\"><size>{META_LEN}</size><hash type=\"sha-256\">{sha}</hash>\n\
<url priority=\"1\">{base}/data/{META_SEED}/{META_LEN}</url>\n\
<url priority=\"2\">{base}/data/{META_SEED}/{META_LEN}/mirror.bin</url></file></metalink>\n"
)
}
pub fn metalink3(base: &str) -> String {
let src = Source::Gen { seed: META_SEED, len: META_LEN };
let md5 = hex(&hash_source("md5", &src).unwrap());
let sha = hex(&hash_source("sha1", &src).unwrap());
format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<metalink version=\"3.0\" xmlns=\"http://www.metalinker.org/\"><files>\n\
<file name=\"meta.bin\"><size>{META_LEN}</size><verification><hash type=\"md5\">{md5}</hash><hash type=\"sha1\">{sha}</hash></verification>\n\
<resources><url type=\"http\" preference=\"100\">{base}/data/{META_SEED}/{META_LEN}</url>\n\
<url type=\"http\" preference=\"50\">{base}/data/{META_SEED}/{META_LEN}/mirror.bin</url></resources></file></files></metalink>\n"
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ranges_match_whole() {
let whole = expected(7, 0, 1000);
assert_eq!(expected(7, 13, 100), whole[13..113]);
assert_eq!(expected(7, 999, 1), whole[999..]);
assert_ne!(expected(8, 0, 64), whole[..64]);
}
#[test]
fn lengths() {
assert_eq!(parse_len("100g"), Some(100 << 30));
assert_eq!(parse_len("12"), Some(12));
assert_eq!(parse_len("x"), None);
}
#[test]
fn known_values() {
assert_eq!(crc32(b"123456789"), 0xCBF4_3926);
assert_eq!(base64(b"Aladdin:open sesame"), "QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
assert_eq!(md5_hex(b""), "d41d8cd98f00b204e9800998ecf8427e");
}
}

View file

@ -0,0 +1,122 @@
//! Faults: set live on the server for a path, or on one request through the query string.
/// Every field is off by default. The query names are the field names:
/// `/data/1/1000?cut_after=500&latency_ms=200`. Booleans take `1`.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Faults {
/// Body bytes per second, for each connection.
pub throttle_conn: Option<u64>,
/// Body bytes per second, shared by all connections of the server.
pub throttle_total: Option<u64>,
/// Wait before the reply starts.
pub latency_ms: Option<u64>,
/// After this many body bytes, say nothing more for `stall_ms` (default one hour).
pub stall_after: Option<u64>,
pub stall_ms: Option<u64>,
/// After this many body bytes, close the connection cleanly.
pub cut_after: Option<u64>,
/// After this many body bytes, reset the connection (TCP RST).
pub reset_after: Option<u64>,
/// Answer with this status instead of the file (403, 404, 410, 416, 429, 500, 503 ...).
pub status: Option<u16>,
/// `Retry-After` seconds on the status answer.
pub retry_after: Option<u64>,
/// Give the status only to the first N requests of the path.
pub status_count: Option<u32>,
/// Added to the declared `Content-Length` (the body keeps its real size).
pub wrong_length: Option<i64>,
/// Answer `Range` requests with the whole file and 200.
pub ignore_range: bool,
/// After this many body bytes the content switches to other bytes.
pub change_after: Option<u64>,
/// From request N+1 on the path serves a new version: other bytes, ETag and date.
pub version_after_requests: Option<u32>,
/// Claim `Content-Encoding: gzip` (the body stays plain).
pub gzip: bool,
/// The link dies this many seconds after its first request ...
pub expire_secs: Option<u64>,
/// ... or after this many requests. Dead links answer `expire_status` (default 403).
pub expire_requests: Option<u32>,
pub expire_status: Option<u16>,
/// More open connections than this from one client get 429.
pub max_conns: Option<usize>,
}
impl Faults {
pub fn status(code: u16) -> Faults {
Faults { status: Some(code), ..Faults::default() }
}
/// Faults named in a query string; `None` for a bad name or value.
pub fn from_query(query: &str) -> Option<Faults> {
let mut f = Faults::default();
for (k, v) in query.split('&').filter(|p| !p.is_empty()).filter_map(|p| p.split_once('=')) {
f.set(k, v)?;
}
Some(f)
}
/// Set one field by name. Names that aren't faults (like `disp`) are not an error.
fn set(&mut self, k: &str, v: &str) -> Option<()> {
macro_rules! num {
($f:ident) => {
self.$f = Some(v.parse().ok()?)
};
}
match k {
"throttle_conn" => num!(throttle_conn),
"throttle_total" => num!(throttle_total),
"latency_ms" => num!(latency_ms),
"stall_after" => num!(stall_after),
"stall_ms" => num!(stall_ms),
"cut_after" => num!(cut_after),
"reset_after" => num!(reset_after),
"status" => num!(status),
"retry_after" => num!(retry_after),
"status_count" => num!(status_count),
"wrong_length" => num!(wrong_length),
"ignore_range" => self.ignore_range = v == "1",
"change_after" => num!(change_after),
"version_after_requests" => num!(version_after_requests),
"gzip" => self.gzip = v == "1",
"expire_secs" => num!(expire_secs),
"expire_requests" => num!(expire_requests),
"expire_status" => num!(expire_status),
"max_conns" => num!(max_conns),
_ => {}
}
Some(())
}
/// `other` wins where it sets something.
pub fn merged(&self, other: &Faults) -> Faults {
macro_rules! pick {
($($f:ident),*) => { Faults {
$($f: other.$f.clone().or_else(|| self.$f.clone()),)*
ignore_range: self.ignore_range || other.ignore_range,
gzip: self.gzip || other.gzip,
} };
}
pick!(
throttle_conn, throttle_total, latency_ms, stall_after, stall_ms, cut_after, reset_after, status,
retry_after, status_count, wrong_length, change_after, version_after_requests, expire_secs,
expire_requests, expire_status, max_conns
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn query_and_merge() {
let q = Faults::from_query("cut_after=5&ignore_range=1&disp=star").unwrap();
assert_eq!(q.cut_after, Some(5));
assert!(q.ignore_range);
assert!(Faults::from_query("cut_after=x").is_none());
let base = Faults { latency_ms: Some(1), cut_after: Some(9), ..Faults::default() };
let m = base.merged(&q);
assert_eq!((m.latency_ms, m.cut_after), (Some(1), Some(5)));
}
}

View file

@ -0,0 +1,626 @@
//! HTTP/1.1 by hand: full control of every byte, so faults can be exact.
use std::io;
use std::net::IpAddr;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader};
use tokio::time::{Instant, sleep, sleep_until};
use crate::content::{self, Source, base64, md5_hex};
use crate::faults::Faults;
use crate::{Request, State};
const REALM: &str = "medlar-test";
const NONCE: &str = "dcd98b7102dd2f0e8b11d0f600bfb0c093";
const CHUNK: usize = 16 * 1024;
/// What a route decided to answer, before faults and ranges.
pub struct Reply {
pub status: u16,
pub headers: Vec<(String, String)>,
pub source: Source,
pub ctype: String,
/// A file: ranges, ETag and Last-Modified apply.
pub file: bool,
/// Identity for the ETag.
pub id: String,
pub chunked: bool,
pub no_length: bool,
pub etag: bool,
pub last_modified: bool,
pub weak: bool,
}
impl Reply {
pub fn text(status: u16, ctype: &str, body: impl Into<Vec<u8>>) -> Reply {
Reply {
status,
headers: Vec::new(),
source: Source::bytes(body),
ctype: ctype.into(),
file: false,
id: String::new(),
chunked: false,
no_length: false,
etag: true,
last_modified: true,
weak: false,
}
}
fn file(source: Source, ctype: &str, id: String) -> Reply {
Reply { file: true, id, source, ..Reply::text(200, ctype, Vec::new()) }
}
fn with(mut self, k: &str, v: impl Into<String>) -> Reply {
self.headers.push((k.into(), v.into()));
self
}
}
struct Ctx<'a> {
req: &'a Request,
query: Vec<(String, String)>,
st: &'a State,
scheme: &'a str,
}
impl Ctx<'_> {
fn q(&self, k: &str) -> Option<&str> {
self.query.iter().find(|(a, _)| a == k).map(|(_, v)| v.as_str())
}
fn base(&self) -> String {
format!("{}://{}", self.scheme, self.req.header("host").unwrap_or("127.0.0.1"))
}
}
pub fn pct_decode(s: &str) -> String {
let b = s.as_bytes();
let mut out = Vec::new();
let mut i = 0;
while i < b.len() {
let hex = (b[i] == b'%' && i + 2 < b.len())
.then(|| std::str::from_utf8(&b[i + 1..i + 3]).ok().and_then(|h| u8::from_str_radix(h, 16).ok()))
.flatten();
if let Some(v) = hex {
out.push(v);
i += 3;
} else {
out.push(if b[i] == b'+' { b' ' } else { b[i] });
i += 1;
}
}
String::from_utf8_lossy(&out).into_owned()
}
fn split_target(target: &str) -> (&str, Vec<(String, String)>) {
let (path, q) = target.split_once('?').unwrap_or((target, ""));
let query = q
.split('&')
.filter(|p| !p.is_empty())
.map(|p| {
let (k, v) = p.split_once('=').unwrap_or((p, ""));
(pct_decode(k), pct_decode(v))
})
.collect();
(path, query)
}
fn unauthorized(scheme: &str) -> Reply {
Reply::text(401, "text/plain", "login needed").with("WWW-Authenticate", scheme)
}
fn kv_params(s: &str) -> Vec<(String, String)> {
let mut out = Vec::new();
let (mut cur, mut quoted) = (String::new(), false);
for c in s.chars().chain(std::iter::once(',')) {
match c {
'"' => quoted = !quoted,
',' if !quoted => {
if let Some((k, v)) = cur.split_once('=') {
out.push((k.trim().to_lowercase(), v.trim().to_string()));
}
cur.clear();
}
_ => cur.push(c),
}
}
out
}
fn digest_ok(auth: &str, method: &str, user: &str, pass: &str) -> bool {
let Some(rest) = auth.strip_prefix("Digest ") else { return false };
let p = kv_params(rest);
let get = |k: &str| p.iter().find(|(a, _)| a == k).map(|(_, v)| v.as_str()).unwrap_or("");
if get("username") != user || get("nonce") != NONCE || get("realm") != REALM {
return false;
}
let ha1 = md5_hex(format!("{user}:{REALM}:{pass}").as_bytes());
let ha2 = md5_hex(format!("{method}:{}", get("uri")).as_bytes());
let want = if get("qop") == "auth" {
md5_hex(format!("{ha1}:{NONCE}:{}:{}:auth:{ha2}", get("nc"), get("cnonce")).as_bytes())
} else {
md5_hex(format!("{ha1}:{NONCE}:{ha2}").as_bytes())
};
get("response") == want
}
fn pct_encode(s: &str) -> String {
s.bytes()
.map(|b| if b.is_ascii_alphanumeric() || b"-._~".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") })
.collect()
}
fn disposition(kind: &str, name: &str) -> Option<String> {
let star = format!("UTF-8''{}", pct_encode("naïve file.bin"));
Some(match kind {
"attachment" => format!("attachment; filename=\"{name}\""),
"bare" => format!("attachment; filename={name}"),
"star" => format!("attachment; filename*={star}"),
"both" => format!("attachment; filename=\"fallback.bin\"; filename*={star}"),
"inline" => format!("inline; filename=\"{name}\""),
"evil" => "attachment; filename=\"../../etc/passwd\"".into(),
"dotfile" => "attachment; filename=\".hidden.bin\"".into(),
_ => return None,
})
}
fn content_type_of(name: &str) -> &'static str {
match name.rsplit('.').next().unwrap_or("") {
"m3u8" => "application/vnd.apple.mpegurl",
"ts" => "video/mp2t",
"mpd" => "application/dash+xml",
"m4s" | "mp4" => "video/mp4",
_ => "application/octet-stream",
}
}
fn route(cx: &Ctx, path: &str) -> Reply {
let segs: Vec<&str> = path.trim_start_matches('/').split('/').collect();
let rest = |n: usize| format!("/{}", segs[n..].join("/"));
match segs[0] {
"" => Reply::text(200, "text/plain", "medlar-testserver"),
"data" if segs.len() >= 3 => {
let (Ok(seed), Some(len)) = (segs[1].parse::<u64>(), content::parse_len(segs[2])) else {
return Reply::text(400, "text/plain", "bad data path");
};
let name = segs.get(3).copied().filter(|n| !n.is_empty()).map(pct_decode).unwrap_or(format!("data-{seed}.bin"));
let mut r = Reply::file(Source::Gen { seed, len }, "application/octet-stream", format!("{seed:x}-{len:x}"));
if let Some(d) = cx.q("disp").and_then(|k| disposition(k, &name)) {
r = r.with("Content-Disposition", d);
}
r.chunked = cx.q("chunked") == Some("1");
r.no_length = cx.q("nolen") == Some("1");
r.etag = cx.q("etag") != Some("0");
r.last_modified = cx.q("lm") != Some("0");
r.weak = cx.q("weak") == Some("1");
r
}
"redirect" if segs.len() >= 2 => {
let code = cx.q("code").and_then(|c| c.parse().ok()).unwrap_or(302);
let to = if segs[1] == "loop" {
"/redirect/loop".to_string()
} else {
let n: u32 = segs[1].parse().unwrap_or(1);
let target = cx.q("to").unwrap_or("/data/1/1000");
if n <= 1 {
target.to_string()
} else {
format!("/redirect/{}?to={}&code={code}", n - 1, pct_encode(target))
}
};
Reply::text(code, "text/plain", "moved").with("Location", to)
}
"status" if segs.len() >= 2 => {
let code = segs[1].parse().unwrap_or(500);
Reply::text(code, "text/plain", format!("status {code}"))
}
"basic" if segs.len() >= 4 => {
let want = format!("Basic {}", base64(format!("{}:{}", segs[1], segs[2]).as_bytes()));
if cx.req.header("authorization").map(str::trim) == Some(want.as_str()) {
route(cx, &rest(3))
} else {
unauthorized(&format!("Basic realm=\"{REALM}\""))
}
}
"digest" if segs.len() >= 4 => {
let ok = cx.req.header("authorization").is_some_and(|a| digest_ok(a, &cx.req.method, segs[1], segs[2]));
if ok {
route(cx, &rest(3))
} else {
unauthorized(&format!("Digest realm=\"{REALM}\", nonce=\"{NONCE}\", qop=\"auth\", algorithm=MD5"))
}
}
"cookie" if segs.len() >= 3 => {
if segs[2] == "login" {
return Reply::text(200, "text/plain", "ok").with("Set-Cookie", format!("session={}; Path=/", segs[1]));
}
let want = format!("session={}", segs[1]);
let has = cx.req.header("cookie").is_some_and(|c| c.split(';').any(|p| p.trim() == want));
if has { route(cx, &rest(2)) } else { Reply::text(403, "text/plain", "login needed") }
}
"referrer" if segs.len() >= 3 => {
if cx.req.header("referer").is_some_and(|r| r.contains(segs[1])) {
route(cx, &rest(2))
} else {
Reply::text(403, "text/plain", "bad referrer")
}
}
"dir" => {
if let Some(html) = content::dir_listing(path) {
Reply::text(200, "text/html", html)
} else if let Some(src) = content::dir_file(path) {
Reply::file(src, content_type_of(path), path.to_string())
} else {
Reply::text(404, "text/plain", "not found")
}
}
"site" => match content::site_page(path) {
Some((ct, src)) => Reply::file(src, ct, path.to_string()),
None => Reply::text(404, "text/plain", "not found"),
},
"archive.zip" => Reply::file(Source::bytes(content::make_zip()), "application/zip", "zip".into()),
"archive.tar" => Reply::file(Source::bytes(content::make_tar()), "application/x-tar", "tar".into()),
"sum" if segs.len() == 4 => {
let (Ok(seed), Some(len)) = (segs[2].parse::<u64>(), content::parse_len(segs[3])) else {
return Reply::text(400, "text/plain", "bad sum path");
};
match content::hash_source(segs[1], &Source::Gen { seed, len }) {
Some(h) => Reply::text(200, "text/plain", format!("{} data-{seed}.bin\n", content::hex(&h))),
None => Reply::text(404, "text/plain", "unknown algorithm"),
}
}
"meta" if segs.len() == 2 => match segs[1] {
"v4.meta4" => Reply::text(200, "application/metalink4+xml", content::metalink4(&cx.base())),
"v3.metalink" => Reply::text(200, "application/metalink+xml", content::metalink3(&cx.base())),
// A file whose headers point at mirrors and carry a digest (metalink in HTTP headers).
"header.bin" => {
let src = Source::Gen { seed: content::META_SEED, len: content::META_LEN };
let digest = base64(&content::hash_source("sha256", &src).unwrap());
Reply::file(src, "application/octet-stream", "meta".into())
.with("Link", format!("<{}/data/{}/{}/mirror.bin>; rel=duplicate; pri=1", cx.base(), content::META_SEED, content::META_LEN))
.with("Digest", format!("SHA-256={digest}"))
}
_ => Reply::text(404, "text/plain", "not found"),
},
"media" if segs.len() == 2 && !segs[1].contains("..") => {
let dir = cx.st.media.lock().unwrap().clone();
match dir.and_then(|d| std::fs::read(d.join(segs[1])).ok()) {
Some(b) => Reply::file(Source::bytes(b), content_type_of(segs[1]), format!("media-{}", segs[1])),
None => Reply::text(404, "text/plain", "no media (call build_media first)"),
}
}
_ => Reply::text(404, "text/plain", "not found"),
}
}
fn status_text(code: u16) -> &'static str {
match code {
200 => "OK",
206 => "Partial Content",
301 => "Moved Permanently",
302 => "Found",
303 => "See Other",
304 => "Not Modified",
307 => "Temporary Redirect",
308 => "Permanent Redirect",
400 => "Bad Request",
401 => "Unauthorized",
403 => "Forbidden",
404 => "Not Found",
407 => "Proxy Authentication Required",
410 => "Gone",
416 => "Range Not Satisfiable",
429 => "Too Many Requests",
500 => "Internal Server Error",
503 => "Service Unavailable",
_ => "Status",
}
}
fn http_date(version: u32) -> String {
const DAYS: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
let n = version % 27;
format!("{}, {:02} Jan 2024 00:00:00 GMT", DAYS[n as usize % 7], 1 + n)
}
/// `Err` = unsatisfiable, `Ok(None)` = ignore the header.
fn parse_range(h: &str, total: u64) -> Result<Option<(u64, u64)>, ()> {
let Some(spec) = h.trim().strip_prefix("bytes=") else { return Ok(None) };
if spec.contains(',') {
return Ok(None);
}
let Some((a, b)) = spec.split_once('-') else { return Ok(None) };
match (a.trim(), b.trim()) {
("", n) => {
let n: u64 = n.parse().map_err(|_| ()).or(Ok(0))?;
if n == 0 || total == 0 { Err(()) } else { Ok(Some((total.saturating_sub(n), total - 1))) }
}
(a, b) => {
let Ok(a) = a.parse::<u64>() else { return Ok(None) };
let b = if b.is_empty() { u64::MAX } else { match b.parse::<u64>() { Ok(v) => v, Err(_) => return Ok(None) } };
if b < a {
Ok(None)
} else if a >= total {
Err(())
} else {
Ok(Some((a, b.min(total - 1))))
}
}
}
}
enum Pace {
Done,
Abort,
}
async fn pace_total(st: &State, n: u64, rate: u64) {
let at = {
let mut next = st.pacer.lock().await;
let start = (*next).max(Instant::now());
*next = start + Duration::from_secs_f64(n as f64 / rate.max(1) as f64);
start
};
sleep_until(at).await;
}
struct BodyJob<'a> {
src: &'a Source,
start: u64,
len: u64,
chunked: bool,
}
async fn write_body<W: AsyncWrite + Unpin>(
io: &mut W,
job: BodyJob<'_>,
f: &Faults,
st: &State,
reset: &socket2::Socket,
sent_out: &mut u64,
) -> io::Result<Pace> {
let BodyJob { src, start, len, chunked } = job;
let (mut sent, mut stalled) = (0u64, false);
let mut buf = vec![0u8; CHUNK];
while sent < len {
if f.cut_after == Some(sent) {
io.flush().await?;
return Ok(Pace::Abort);
}
if f.reset_after == Some(sent) {
io.flush().await?;
let _ = reset.set_linger(Some(Duration::ZERO));
return Err(io::Error::from(io::ErrorKind::ConnectionReset));
}
if f.stall_after == Some(sent) && !stalled {
stalled = true;
io.flush().await?;
sleep(Duration::from_millis(f.stall_ms.unwrap_or(3_600_000))).await;
}
let mut limit = len - sent;
for t in [f.cut_after, f.reset_after, f.stall_after, f.change_after].into_iter().flatten() {
if t > sent {
limit = limit.min(t - sent);
}
}
let mut max_chunk = CHUNK as u64;
for r in [f.throttle_conn, f.throttle_total].into_iter().flatten() {
max_chunk = max_chunk.min((r / 20).max(1));
}
let n = limit.min(max_chunk) as usize;
let changed = f.change_after.is_some_and(|c| sent >= c);
src.read(start + sent, &mut buf[..n], changed);
if chunked {
io.write_all(format!("{n:x}\r\n").as_bytes()).await?;
}
io.write_all(&buf[..n]).await?;
if chunked {
io.write_all(b"\r\n").await?;
}
io.flush().await?;
sent += n as u64;
*sent_out = sent;
if let Some(r) = f.throttle_conn {
sleep(Duration::from_secs_f64(n as f64 / r.max(1) as f64)).await;
}
if let Some(r) = f.throttle_total {
pace_total(st, n as u64, r).await;
}
}
if chunked {
io.write_all(b"0\r\n\r\n").await?;
io.flush().await?;
}
Ok(Pace::Done)
}
async fn read_head<S: AsyncRead + Unpin>(io: &mut BufReader<S>) -> io::Result<Option<(String, String, String, Vec<(String, String)>)>> {
let mut line = String::new();
if io.read_line(&mut line).await? == 0 {
return Ok(None);
}
let mut it = line.split_whitespace();
let (m, t, v) = (it.next().unwrap_or("").to_string(), it.next().unwrap_or("/").to_string(), it.next().unwrap_or("HTTP/1.1").to_string());
let mut headers = Vec::new();
loop {
line.clear();
if io.read_line(&mut line).await? == 0 || headers.len() > 200 {
return Err(io::ErrorKind::UnexpectedEof.into());
}
let l = line.trim_end();
if l.is_empty() {
break;
}
if let Some((k, v)) = l.split_once(':') {
headers.push((k.trim().to_string(), v.trim().to_string()));
}
}
Ok(Some((m, t, v, headers)))
}
/// One connection: requests until the client or a fault closes it.
pub async fn serve_conn<S>(stream: S, st: Arc<State>, ip: IpAddr, conn: u64, reset: socket2::Socket, scheme: &'static str) -> io::Result<()>
where
S: AsyncRead + AsyncWrite + Unpin,
{
let mut io = BufReader::new(stream);
loop {
let Some((method, target, version, headers)) = read_head(&mut io).await? else { return Ok(()) };
let mut req = Request { id: 0, conn, method, target, headers, status: 0, sent: 0 };
let close_req = req.header("connection").is_some_and(|c| c.eq_ignore_ascii_case("close")) || version == "HTTP/1.0";
if let Some(n) = req.header("content-length").and_then(|v| v.parse::<u64>().ok()) {
let mut sink = vec![0u8; 4096];
let mut left = n.min(1 << 20);
while left > 0 {
let k = io.read(&mut sink[..left.min(4096) as usize]).await?;
if k == 0 {
return Ok(());
}
left -= k as u64;
}
}
let idx = st.log_push(&mut req);
let result = respond(&mut io, &st, &req, ip, &reset, scheme).await;
match result {
Ok((status, sent, keep)) => {
st.log_done(idx, status, sent);
if !keep || close_req {
return Ok(());
}
}
Err(e) => {
st.log_done(idx, 0, 0);
return Err(e);
}
}
}
}
async fn respond<S>(io: &mut BufReader<S>, st: &State, req: &Request, ip: IpAddr, reset: &socket2::Socket, scheme: &str) -> io::Result<(u16, u64, bool)>
where
S: AsyncRead + AsyncWrite + Unpin,
{
let (path, query) = split_target(&req.target);
let path = path.to_string();
let mut f = st.faults_for(&path);
if let Some(q) = Faults::from_query(req.target.split_once('?').map_or("", |x| x.1)) {
f = f.merged(&q);
}
if let Some(ms) = f.latency_ms {
sleep(Duration::from_millis(ms)).await;
}
let (req_no, age) = st.touch(&path);
let cx = Ctx { req, query, st, scheme };
let mut reply = route(&cx, &path);
let mut retry_after = None;
let version = f.version_after_requests.map_or(0, |k| u32::from(req_no > k));
let expired = f.expire_requests.is_some_and(|n| req_no > n) || f.expire_secs.is_some_and(|s| age >= Duration::from_secs(s));
if expired {
let code = f.expire_status.unwrap_or(403);
reply = Reply::text(code, "text/plain", "link expired");
} else if f.max_conns.is_some_and(|m| st.conns_of(ip) > m) {
reply = Reply::text(429, "text/plain", "too many connections");
retry_after = Some(1);
} else if let Some(code) = f.status.filter(|_| f.status_count.is_none_or(|n| req_no <= n)) {
let total = reply.source.len();
reply = Reply::text(code, "text/plain", format!("status {code}"));
if code == 416 {
reply = reply.with("Content-Range", format!("bytes */{total}"));
}
retry_after = f.retry_after;
}
if let Some(r) = retry_after.or(f.retry_after.filter(|_| reply.status == 429 || reply.status == 503)) {
reply = reply.with("Retry-After", r.to_string());
}
let src = reply.source.versioned(version);
let total = src.len();
let head_only = req.method == "HEAD";
let mut status = reply.status;
let mut headers = std::mem::take(&mut reply.headers);
let etag = format!("{}\"{}-v{version}\"", if reply.weak { "W/" } else { "" }, reply.id);
let modified = http_date(version);
let mut range = None;
let ranges_on = reply.file && !f.ignore_range && !reply.chunked && !reply.no_length;
if reply.file && status == 200 {
if reply.etag {
headers.push(("ETag".into(), etag.clone()));
}
if reply.last_modified {
headers.push(("Last-Modified".into(), modified.clone()));
}
if ranges_on {
headers.push(("Accept-Ranges".into(), "bytes".into()));
}
let not_modified = req.header("if-none-match").is_some_and(|v| v == etag);
if not_modified {
status = 304;
} else if ranges_on && let Some(h) = req.header("range") {
let if_range_ok = req.header("if-range").is_none_or(|v| v == etag || v == modified);
if if_range_ok {
match parse_range(h, total) {
Ok(Some(r)) => range = Some(r),
Ok(None) => {}
Err(()) => {
status = 416;
headers.push(("Content-Range".into(), format!("bytes */{total}")));
}
}
}
}
}
let (start, len) = match range {
Some((a, b)) => {
status = 206;
headers.push(("Content-Range".into(), format!("bytes {a}-{b}/{total}")));
(a, b - a + 1)
}
None if status == 200 || status == 206 || reply.status != 200 => (0, total),
None => (0, 0),
};
let no_body = head_only || status == 304 || (status == 416 && reply.file);
let body_len = if no_body { 0 } else { len };
if f.gzip {
headers.push(("Content-Encoding".into(), "gzip".into()));
}
if reply.status != 304 && status != 304 {
headers.push(("Content-Type".into(), reply.ctype.clone()));
}
let mut keep = true;
let chunked = reply.chunked && !no_body;
if chunked {
headers.push(("Transfer-Encoding".into(), "chunked".into()));
} else if reply.no_length && !head_only {
keep = false;
} else {
let declared = (len as i64 + f.wrong_length.unwrap_or(0)).max(0);
if f.wrong_length.is_some() {
keep = false;
}
let shown = if status == 416 && reply.file || status == 304 { 0 } else { declared };
headers.push(("Content-Length".into(), shown.to_string()));
}
if !keep {
headers.push(("Connection".into(), "close".into()));
}
let mut head = format!("HTTP/1.1 {status} {}\r\n", status_text(status));
for (k, v) in &headers {
head.push_str(&format!("{k}: {v}\r\n"));
}
head.push_str("\r\n");
io.write_all(head.as_bytes()).await?;
io.flush().await?;
let mut sent = 0;
if body_len > 0 || (chunked && !head_only) {
let job = BodyJob { src: &src, start, len: body_len, chunked };
match write_body(io, job, &f, st, reset, &mut sent).await? {
Pace::Done => {}
Pace::Abort => keep = false,
}
}
Ok((status, sent, keep))
}

View file

@ -1 +1,342 @@
//! Local server with faults (ranges, throttle, cuts, expiry, logins) for the engine tests.
//!
//! `TestServer::start().await` binds 127.0.0.1 on a free port. Routes (all GET/HEAD):
//! - `/data/<seed>/<len>[/<name>]` deterministic file (`len` accepts k, m, g, t; 100g is fine).
//! Query: `disp=attachment|bare|star|both|inline|evil|dotfile`, `chunked=1`, `nolen=1`, `etag=0`,
//! `lm=0`, `weak=1`, plus any fault by name (see [`Faults`]).
//! - `/redirect/<n>?to=<path>&code=<30x>`, `/redirect/loop`, `/status/<code>`
//! - `/basic/<user>/<pass>/…`, `/digest/<user>/<pass>/…`, `/cookie/<token>/login` then `/cookie/<token>/…`,
//! `/referrer/<needle>/…`: the rest of the path is served after the check.
//! - `/dir/` (open listing, with `sub/`, `pack.zip`, `pack.tar`), `/site/` (small linked site),
//! `/archive.zip`, `/archive.tar`, `/sum/<md5|sha1|sha256|sha512>/<seed>/<len>`,
//! `/meta/v4.meta4`, `/meta/v3.metalink`, `/meta/header.bin` (Link and Digest headers),
//! `/media/<file>` (HLS and DASH, after [`TestServer::build_media`]).
mod content;
mod faults;
mod http;
pub mod proxy;
use std::collections::HashMap;
use std::io;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::net::{TcpListener, TcpStream};
use tokio::task::{JoinHandle, JoinSet};
use tokio::time::Instant;
pub use content::{ARCHIVE_FILES, META_LEN, META_SEED, expected, make_tar, make_zip, md5_hex};
pub use faults::Faults;
/// One request as the server saw it.
#[derive(Clone, Debug)]
pub struct Request {
pub id: usize,
pub conn: u64,
pub method: String,
/// Path and query as sent.
pub target: String,
pub headers: Vec<(String, String)>,
/// 0 until the answer is written.
pub status: u16,
/// Body bytes written.
pub sent: u64,
}
impl Request {
pub fn header(&self, name: &str) -> Option<&str> {
self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
}
pub fn path(&self) -> &str {
self.target.split('?').next().unwrap_or("")
}
}
#[derive(Default)]
struct PathStat {
requests: u32,
first: Option<Instant>,
}
pub(crate) struct State {
faults: Mutex<HashMap<String, Faults>>,
stats: Mutex<HashMap<String, PathStat>>,
log: Mutex<Vec<Request>>,
conns: Mutex<HashMap<IpAddr, usize>>,
pub(crate) pacer: tokio::sync::Mutex<Instant>,
pub(crate) media: Mutex<Option<PathBuf>>,
}
impl State {
/// Faults of a path: `*` for all, `prefix*` for a prefix (longest wins), else exact. Exact wins.
pub(crate) fn faults_for(&self, path: &str) -> Faults {
let map = self.faults.lock().unwrap();
if let Some(f) = map.get(path) {
return f.clone();
}
map.iter()
.filter_map(|(k, f)| k.strip_suffix('*').filter(|p| path.starts_with(p)).map(|p| (p.len(), f)))
.max_by_key(|(n, _)| *n)
.map(|(_, f)| f.clone())
.unwrap_or_default()
}
/// Count a request on a path: its number (from 1) and the age of the first one.
pub(crate) fn touch(&self, path: &str) -> (u32, Duration) {
let mut stats = self.stats.lock().unwrap();
let s = stats.entry(path.to_string()).or_default();
s.requests += 1;
let first = *s.first.get_or_insert_with(Instant::now);
(s.requests, first.elapsed())
}
pub(crate) fn conns_of(&self, ip: IpAddr) -> usize {
self.conns.lock().unwrap().get(&ip).copied().unwrap_or(0)
}
pub(crate) fn log_push(&self, req: &mut Request) -> usize {
let mut log = self.log.lock().unwrap();
req.id = log.len();
log.push(req.clone());
req.id
}
pub(crate) fn log_done(&self, idx: usize, status: u16, sent: u64) {
if let Some(r) = self.log.lock().unwrap().get_mut(idx) {
r.status = status;
r.sent = sent;
}
}
}
struct ConnGuard {
st: Arc<State>,
ip: IpAddr,
}
impl ConnGuard {
fn new(st: &Arc<State>, ip: IpAddr) -> ConnGuard {
*st.conns.lock().unwrap().entry(ip).or_default() += 1;
ConnGuard { st: st.clone(), ip }
}
}
impl Drop for ConnGuard {
fn drop(&mut self) {
if let Some(n) = self.st.conns.lock().unwrap().get_mut(&self.ip) {
*n = n.saturating_sub(1);
}
}
}
struct Tls {
cert_der: Vec<u8>,
cert_pem: String,
}
pub struct TestServer {
addr: SocketAddr,
st: Arc<State>,
tls: Option<Tls>,
task: JoinHandle<()>,
}
impl TestServer {
/// Plain HTTP on a free port of 127.0.0.1.
pub async fn start() -> TestServer {
Self::launch(0, false).await.expect("bind test server")
}
/// HTTPS with a fresh self-signed certificate for `localhost` and `127.0.0.1`.
pub async fn start_tls() -> TestServer {
Self::launch(0, true).await.expect("bind test server")
}
/// A fixed port (for the binary).
pub async fn start_on(port: u16, tls: bool) -> io::Result<TestServer> {
Self::launch(port, tls).await
}
async fn launch(port: u16, tls: bool) -> io::Result<TestServer> {
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, port)).await?;
let addr = listener.local_addr()?;
let st = Arc::new(State {
faults: Mutex::default(),
stats: Mutex::default(),
log: Mutex::default(),
conns: Mutex::default(),
pacer: tokio::sync::Mutex::new(Instant::now()),
media: Mutex::default(),
});
let (acceptor, tls_info) = if tls {
let (cfg, info) = make_tls();
(Some(tokio_rustls::TlsAcceptor::from(Arc::new(cfg))), Some(info))
} else {
(None, None)
};
let st2 = st.clone();
let task = tokio::spawn(async move {
let mut conns = JoinSet::new();
let counter = AtomicU64::new(0);
loop {
tokio::select! {
Ok((tcp, peer)) = listener.accept() => {
let conn = counter.fetch_add(1, Ordering::Relaxed);
conns.spawn(handle_conn(tcp, peer.ip(), st2.clone(), acceptor.clone(), conn));
}
Some(_) = conns.join_next(), if !conns.is_empty() => {}
}
}
});
Ok(TestServer { addr, st, tls: tls_info, task })
}
pub fn addr(&self) -> SocketAddr {
self.addr
}
pub fn port(&self) -> u16 {
self.addr.port()
}
/// `http://127.0.0.1:PORT` (or https).
pub fn base(&self) -> String {
format!("{}://127.0.0.1:{}", if self.tls.is_some() { "https" } else { "http" }, self.addr.port())
}
/// Full URL of a path (with query).
pub fn url(&self, path: &str) -> String {
format!("{}{path}", self.base())
}
/// Path of the deterministic file `seed`/`len`.
pub fn data_path(seed: u64, len: u64) -> String {
format!("/data/{seed}/{len}")
}
/// DER of the server certificate (HTTPS only), to trust in a client.
pub fn cert_der(&self) -> Option<Vec<u8>> {
self.tls.as_ref().map(|t| t.cert_der.clone())
}
pub fn cert_pem(&self) -> Option<String> {
self.tls.as_ref().map(|t| t.cert_pem.clone())
}
/// Faults for a path: exact (`/data/1/1000`), prefix (`/data/*`) or all (`*`). Counters of an exact path restart.
pub fn set_faults(&self, path: &str, faults: Faults) {
self.st.stats.lock().unwrap().remove(path);
self.st.faults.lock().unwrap().insert(path.to_string(), faults);
}
pub fn clear_faults(&self, path: &str) {
self.st.faults.lock().unwrap().remove(path);
}
pub fn clear_all_faults(&self) {
self.st.faults.lock().unwrap().clear();
self.st.stats.lock().unwrap().clear();
}
/// Every request so far, oldest first.
pub fn log(&self) -> Vec<Request> {
self.st.log.lock().unwrap().clone()
}
/// Requests whose path (without query) is `path`.
pub fn requests_for(&self, path: &str) -> Vec<Request> {
self.log().into_iter().filter(|r| r.path() == path).collect()
}
pub fn clear_log(&self) {
self.st.log.lock().unwrap().clear();
}
/// Open connections from 127.0.0.1 now.
pub fn open_connections(&self) -> usize {
self.st.conns_of(IpAddr::V4(Ipv4Addr::LOCALHOST))
}
/// Make the HLS and DASH fixtures with ffmpeg (3 s of test video, 1 s segments) and serve them under
/// `/media/`: `master.m3u8`, `index.m3u8`, `seg*.ts`, `manifest.mpd`, `*.m4s`.
pub async fn build_media(&self) -> io::Result<()> {
let dir = std::env::temp_dir().join(format!("medlar-testserver-{}-{}", std::process::id(), self.addr.port()));
let d2 = dir.clone();
tokio::task::spawn_blocking(move || media::build(&d2)).await.map_err(io::Error::other)??;
*self.st.media.lock().unwrap() = Some(dir);
Ok(())
}
}
impl Drop for TestServer {
fn drop(&mut self) {
self.task.abort();
if let Some(dir) = self.st.media.lock().unwrap().take() {
let _ = std::fs::remove_dir_all(dir);
}
}
}
async fn handle_conn(tcp: TcpStream, ip: IpAddr, st: Arc<State>, acceptor: Option<tokio_rustls::TlsAcceptor>, conn: u64) {
let _ = tcp.set_nodelay(true);
let _guard = ConnGuard::new(&st, ip);
let Ok(reset) = socket2::SockRef::from(&tcp).try_clone() else { return };
let _ = match acceptor {
Some(a) => match a.accept(tcp).await {
Ok(s) => http::serve_conn(s, st, ip, conn, reset, "https").await,
Err(_) => return,
},
None => http::serve_conn(tcp, st, ip, conn, reset, "http").await,
};
}
fn make_tls() -> (tokio_rustls::rustls::ServerConfig, Tls) {
use tokio_rustls::rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
let certified = rcgen::generate_simple_self_signed(vec!["localhost".to_string(), "127.0.0.1".to_string()]).expect("make certificate");
let der = certified.cert.der().to_vec();
let key = PrivatePkcs8KeyDer::from(certified.signing_key.serialize_der());
let provider = Arc::new(tokio_rustls::rustls::crypto::ring::default_provider());
let cfg = tokio_rustls::rustls::ServerConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.expect("tls versions")
.with_no_client_auth()
.with_single_cert(vec![CertificateDer::from(der.clone())], PrivateKeyDer::Pkcs8(key))
.expect("tls config");
(cfg, Tls { cert_der: der, cert_pem: certified.cert.pem() })
}
mod media {
use std::io;
use std::path::Path;
use std::process::{Command, Stdio};
fn ffmpeg(dir: &Path, args: &[&str]) -> io::Result<()> {
let out = Command::new("/usr/bin/ffmpeg")
.current_dir(dir)
.args(["-y", "-loglevel", "error", "-f", "lavfi", "-i", "testsrc=size=160x120:rate=10", "-t", "3", "-c:v", "mpeg4", "-g", "10"])
.args(args)
.stdin(Stdio::null())
.output()?;
if out.status.success() {
Ok(())
} else {
Err(io::Error::other(String::from_utf8_lossy(&out.stderr).into_owned()))
}
}
pub fn build(dir: &Path) -> io::Result<()> {
std::fs::create_dir_all(dir)?;
ffmpeg(dir, &["-f", "hls", "-hls_time", "1", "-hls_playlist_type", "vod", "-hls_segment_filename", "seg%d.ts", "index.m3u8"])?;
std::fs::write(
dir.join("master.m3u8"),
"#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=200000,RESOLUTION=160x120\nindex.m3u8\n",
)?;
ffmpeg(dir, &["-f", "dash", "-seg_duration", "1", "manifest.mpd"])?;
Ok(())
}
}

View file

@ -0,0 +1,38 @@
//! `medlar-testserver [--port N] [--tls] [--media]`: run the test server by hand.
use medlar_testserver::{TestServer, proxy::Proxy};
#[tokio::main]
async fn main() {
let mut port = 0;
let (mut tls, mut media, mut proxies) = (false, false, false);
let mut args = std::env::args().skip(1);
while let Some(a) = args.next() {
match a.as_str() {
"--port" => port = args.next().and_then(|p| p.parse().ok()).unwrap_or_else(|| usage()),
"--tls" => tls = true,
"--media" => media = true,
"--proxies" => proxies = true,
_ => usage(),
}
}
let server = TestServer::start_on(port, tls).await.expect("start");
if media {
server.build_media().await.expect("build media (needs /usr/bin/ffmpeg)");
}
println!("listening {}", server.base());
let _proxies = if proxies {
let (h, s) = (Proxy::start_http(None).await, Proxy::start_socks5(None).await);
println!("http proxy 127.0.0.1:{}", h.port());
println!("socks5 proxy 127.0.0.1:{}", s.port());
Some((h, s))
} else {
None
};
let _ = tokio::signal::ctrl_c().await;
}
fn usage() -> ! {
eprintln!("usage: medlar-testserver [--port N] [--tls] [--media] [--proxies]");
std::process::exit(2)
}

View file

@ -0,0 +1,264 @@
//! HTTP and SOCKS5 proxy stubs on loopback. They record what passed and only ever connect to
//! 127.0.0.0/8, `localhost`, or a name you mapped with [`Proxy::map_host`]: no real network.
use std::collections::HashMap;
use std::io;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::sync::{Arc, Mutex};
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader, copy_bidirectional};
use tokio::net::{TcpListener, TcpStream};
use tokio::task::{JoinHandle, JoinSet};
use crate::content::base64;
/// One thing a client asked of the proxy.
#[derive(Clone, Debug, PartialEq)]
pub struct Seen {
/// `http` (absolute-URI request), `connect` (HTTP CONNECT) or `socks5`.
pub kind: &'static str,
/// `host:port` the client wanted.
pub target: String,
/// The request line (HTTP only).
pub request_line: String,
/// `Proxy-Authorization` value, or the SOCKS user name, if the client sent one.
pub credentials: Option<String>,
/// False if the proxy refused (bad login, target outside loopback).
pub allowed: bool,
}
type Hosts = Arc<Mutex<HashMap<String, SocketAddr>>>;
type Log = Arc<Mutex<Vec<Seen>>>;
pub struct Proxy {
addr: SocketAddr,
seen: Log,
hosts: Hosts,
task: JoinHandle<()>,
}
impl Proxy {
/// HTTP proxy (plain requests and CONNECT). With `auth`, wants `Proxy-Authorization: Basic`.
pub async fn start_http(auth: Option<(&str, &str)>) -> Proxy {
Self::start(auth, false).await
}
/// SOCKS5 proxy (CONNECT only). With `auth`, wants user and password (RFC 1929).
pub async fn start_socks5(auth: Option<(&str, &str)>) -> Proxy {
Self::start(auth, true).await
}
async fn start(auth: Option<(&str, &str)>, socks: bool) -> Proxy {
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.expect("bind proxy");
let addr = listener.local_addr().unwrap();
let (seen, hosts): (Log, Hosts) = Default::default();
let auth = auth.map(|(u, p)| (u.to_string(), p.to_string()));
let (s2, h2) = (seen.clone(), hosts.clone());
let task = tokio::spawn(async move {
let mut conns = JoinSet::new();
loop {
tokio::select! {
Ok((c, _)) = listener.accept() => {
let (s, h, a) = (s2.clone(), h2.clone(), auth.clone());
conns.spawn(async move {
let _ = if socks { socks5(c, s, h, a).await } else { http(c, s, h, a).await };
});
}
Some(_) = conns.join_next(), if !conns.is_empty() => {}
}
}
});
Proxy { addr, seen, hosts, task }
}
pub fn addr(&self) -> SocketAddr {
self.addr
}
/// `http://127.0.0.1:PORT` or the same with `socks5://` is up to the caller.
pub fn port(&self) -> u16 {
self.addr.port()
}
/// Let clients reach `name` (a made-up host name) through this proxy: it connects to `addr`.
pub fn map_host(&self, name: &str, addr: SocketAddr) {
self.hosts.lock().unwrap().insert(name.to_string(), addr);
}
pub fn seen(&self) -> Vec<Seen> {
self.seen.lock().unwrap().clone()
}
}
impl Drop for Proxy {
fn drop(&mut self) {
self.task.abort();
}
}
async fn connect(host: &str, port: u16, hosts: &Hosts) -> Option<TcpStream> {
let addr = if let Some(a) = hosts.lock().unwrap().get(host) {
*a
} else if host == "localhost" {
SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port)
} else {
let ip: IpAddr = host.trim_matches(['[', ']']).parse().ok()?;
if !ip.is_loopback() {
return None;
}
SocketAddr::new(ip, port)
};
TcpStream::connect(addr).await.ok()
}
fn split_host_port(s: &str, default: u16) -> (String, u16) {
match s.rsplit_once(':') {
Some((h, p)) if p.parse::<u16>().is_ok() && !h.ends_with(':') => (h.to_string(), p.parse().unwrap()),
_ => (s.to_string(), default),
}
}
async fn http(client: TcpStream, seen: Log, hosts: Hosts, auth: Option<(String, String)>) -> io::Result<()> {
let mut io = BufReader::new(client);
let mut line = String::new();
io.read_line(&mut line).await?;
let request_line = line.trim_end().to_string();
let mut it = request_line.split_whitespace();
let (method, target) = (it.next().unwrap_or("").to_string(), it.next().unwrap_or("").to_string());
let mut headers = Vec::new();
loop {
line.clear();
if io.read_line(&mut line).await? == 0 {
return Ok(());
}
let l = line.trim_end();
if l.is_empty() {
break;
}
if let Some((k, v)) = l.split_once(':') {
headers.push((k.trim().to_string(), v.trim().to_string()));
}
}
let creds = headers.iter().find(|(k, _)| k.eq_ignore_ascii_case("proxy-authorization")).map(|(_, v)| v.clone());
let login_ok = auth.as_ref().is_none_or(|(u, p)| creds.as_deref() == Some(format!("Basic {}", base64(format!("{u}:{p}").as_bytes())).as_str()));
let is_connect = method.eq_ignore_ascii_case("CONNECT");
let (host, port, path) = if is_connect {
let (h, p) = split_host_port(&target, 443);
(h, p, String::new())
} else {
let rest = target.strip_prefix("http://").unwrap_or("");
let (hp, path) = rest.split_once('/').map_or((rest, "/".to_string()), |(a, b)| (a, format!("/{b}")));
let (h, p) = split_host_port(hp, 80);
(h, p, path)
};
let record = |allowed| {
seen.lock().unwrap().push(Seen {
kind: if is_connect { "connect" } else { "http" },
target: format!("{host}:{port}"),
request_line: request_line.clone(),
credentials: creds.clone(),
allowed,
})
};
let mut client = io.into_inner();
if !login_ok {
record(false);
client
.write_all(b"HTTP/1.1 407 Proxy Authentication Required\r\nProxy-Authenticate: Basic realm=\"medlar-test\"\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
.await?;
return Ok(());
}
let Some(mut up) = (if host.is_empty() { None } else { connect(&host, port, &hosts).await }) else {
record(false);
client.write_all(b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").await?;
return Ok(());
};
record(true);
if is_connect {
client.write_all(b"HTTP/1.1 200 Connection established\r\n\r\n").await?;
} else {
let mut head = format!("{method} {path} HTTP/1.1\r\n");
for (k, v) in &headers {
if !k.to_lowercase().starts_with("proxy-") && !k.eq_ignore_ascii_case("connection") {
head.push_str(&format!("{k}: {v}\r\n"));
}
}
head.push_str("Connection: close\r\n\r\n");
up.write_all(head.as_bytes()).await?;
}
copy_bidirectional(&mut client, &mut up).await?;
Ok(())
}
async fn socks5(mut c: TcpStream, seen: Log, hosts: Hosts, auth: Option<(String, String)>) -> io::Result<()> {
let mut hello = [0u8; 2];
c.read_exact(&mut hello).await?;
let mut methods = vec![0u8; hello[1] as usize];
c.read_exact(&mut methods).await?;
let mut user = None;
match &auth {
Some((u, p)) if methods.contains(&2) => {
c.write_all(&[5, 2]).await?;
let mut v = [0u8; 2];
c.read_exact(&mut v).await?;
let mut name = vec![0u8; v[1] as usize];
c.read_exact(&mut name).await?;
let mut plen = [0u8; 1];
c.read_exact(&mut plen).await?;
let mut pass = vec![0u8; plen[0] as usize];
c.read_exact(&mut pass).await?;
user = Some(String::from_utf8_lossy(&name).into_owned());
if name != u.as_bytes() || pass != p.as_bytes() {
seen.lock().unwrap().push(Seen { kind: "socks5", target: String::new(), request_line: String::new(), credentials: user, allowed: false });
c.write_all(&[1, 1]).await?;
return Ok(());
}
c.write_all(&[1, 0]).await?;
}
Some(_) => {
c.write_all(&[5, 0xFF]).await?;
return Ok(());
}
None => c.write_all(&[5, 0]).await?,
}
let mut req = [0u8; 4];
c.read_exact(&mut req).await?;
let host = match req[3] {
1 => {
let mut a = [0u8; 4];
c.read_exact(&mut a).await?;
IpAddr::from(a).to_string()
}
4 => {
let mut a = [0u8; 16];
c.read_exact(&mut a).await?;
IpAddr::from(a).to_string()
}
3 => {
let mut n = [0u8; 1];
c.read_exact(&mut n).await?;
let mut name = vec![0u8; n[0] as usize];
c.read_exact(&mut name).await?;
String::from_utf8_lossy(&name).into_owned()
}
_ => return Ok(()),
};
let mut p = [0u8; 2];
c.read_exact(&mut p).await?;
let port = u16::from_be_bytes(p);
let up = if req[1] == 1 { connect(&host, port, &hosts).await } else { None };
seen.lock().unwrap().push(Seen {
kind: "socks5",
target: format!("{host}:{port}"),
request_line: String::new(),
credentials: user,
allowed: up.is_some(),
});
let Some(mut up) = up else {
c.write_all(&[5, 5, 0, 1, 0, 0, 0, 0, 0, 0]).await?;
return Ok(());
};
c.write_all(&[5, 0, 0, 1, 0, 0, 0, 0, 0, 0]).await?;
copy_bidirectional(&mut c, &mut up).await?;
Ok(())
}

View file

@ -0,0 +1,724 @@
//! One test (or more) per route and per fault. A tiny raw client, so nothing hides the bytes.
use std::net::SocketAddr;
use std::time::{Duration, Instant};
use medlar_testserver::proxy::Proxy;
use medlar_testserver::{Faults, TestServer, expected, md5_hex};
use sha2::{Digest, Sha256};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
struct Resp {
status: u16,
headers: Vec<(String, String)>,
body: Vec<u8>,
/// The read ended with an error (a reset) instead of a clean end.
broken: bool,
}
impl Resp {
fn h(&self, name: &str) -> Option<&str> {
self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
}
}
fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
hay.windows(needle.len()).position(|w| w == needle)
}
fn dechunk(mut b: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
while let Some(i) = find(b, b"\r\n") {
let n = usize::from_str_radix(std::str::from_utf8(&b[..i]).unwrap(), 16).unwrap();
if n == 0 || b.len() < i + 2 + n {
break;
}
out.extend(&b[i + 2..i + 2 + n]);
b = &b[i + 2 + n + 2..];
}
out
}
fn parse(raw: Vec<u8>, broken: bool) -> Resp {
let split = find(&raw, b"\r\n\r\n").expect("response head");
let head = String::from_utf8_lossy(&raw[..split]).into_owned();
let mut lines = head.lines();
let status = lines.next().unwrap().split_whitespace().nth(1).unwrap().parse().unwrap();
let headers: Vec<(String, String)> =
lines.filter_map(|l| l.split_once(':')).map(|(k, v)| (k.trim().to_string(), v.trim().to_string())).collect();
let mut body = raw[split + 4..].to_vec();
if headers.iter().any(|(k, v)| k.eq_ignore_ascii_case("transfer-encoding") && v == "chunked") {
body = dechunk(&body);
}
Resp { status, headers, body, broken }
}
async fn read_all<S: AsyncReadExt + Unpin>(s: &mut S) -> (Vec<u8>, bool) {
let mut raw = Vec::new();
let mut buf = vec![0u8; 16384];
loop {
match tokio::time::timeout(Duration::from_secs(10), s.read(&mut buf)).await {
Ok(Ok(0)) => return (raw, false),
Ok(Ok(n)) => raw.extend(&buf[..n]),
_ => return (raw, true),
}
}
}
/// GET on a fresh connection that closes after the answer.
async fn get_with(addr: SocketAddr, target: &str, extra: &[(&str, &str)]) -> Resp {
request(addr, "GET", target, extra).await
}
async fn request(addr: SocketAddr, method: &str, target: &str, extra: &[(&str, &str)]) -> Resp {
let mut s = TcpStream::connect(addr).await.unwrap();
let mut req = format!("{method} {target} HTTP/1.1\r\nHost: 127.0.0.1:{}\r\nConnection: close\r\n", addr.port());
for (k, v) in extra {
req.push_str(&format!("{k}: {v}\r\n"));
}
req.push_str("\r\n");
s.write_all(req.as_bytes()).await.unwrap();
let (raw, broken) = read_all(&mut s).await;
parse(raw, broken)
}
async fn get(srv: &TestServer, target: &str) -> Resp {
get_with(srv.addr(), target, &[]).await
}
// ---------- content, ranges, validators ----------
#[tokio::test]
async fn full_file_and_ranges() {
let srv = TestServer::start().await;
let r = get(&srv, "/data/7/1000").await;
assert_eq!((r.status, r.h("content-length")), (200, Some("1000")));
assert_eq!(r.h("accept-ranges"), Some("bytes"));
assert!(r.h("etag").is_some() && r.h("last-modified").is_some());
assert_eq!(r.body, expected(7, 0, 1000));
let r = get_with(srv.addr(), "/data/7/1000", &[("Range", "bytes=10-19")]).await;
assert_eq!((r.status, r.h("content-range")), (206, Some("bytes 10-19/1000")));
assert_eq!(r.body, expected(7, 10, 10));
let r = get_with(srv.addr(), "/data/7/1000", &[("Range", "bytes=990-")]).await;
assert_eq!((r.status, r.body), (206, expected(7, 990, 10)));
let r = get_with(srv.addr(), "/data/7/1000", &[("Range", "bytes=-5")]).await;
assert_eq!((r.status, r.body), (206, expected(7, 995, 5)));
let r = get_with(srv.addr(), "/data/7/1000", &[("Range", "bytes=990-5000")]).await;
assert_eq!(r.h("content-range"), Some("bytes 990-999/1000"));
}
#[tokio::test]
async fn range_416_head_and_validators() {
let srv = TestServer::start().await;
let r = get_with(srv.addr(), "/data/7/1000", &[("Range", "bytes=1000-")]).await;
assert_eq!((r.status, r.h("content-range")), (416, Some("bytes */1000")));
let r = request(srv.addr(), "HEAD", "/data/7/1000", &[]).await;
assert_eq!((r.status, r.h("content-length"), r.body.len()), (200, Some("1000"), 0));
let etag = get(&srv, "/data/7/1000").await.h("etag").unwrap().to_string();
let r = get_with(srv.addr(), "/data/7/1000", &[("If-None-Match", &etag)]).await;
assert_eq!(r.status, 304);
// If-Range with a stale validator: whole file again.
let r = get_with(srv.addr(), "/data/7/1000", &[("Range", "bytes=0-9"), ("If-Range", "\"old\"")]).await;
assert_eq!((r.status, r.body.len()), (200, 1000));
let r = get_with(srv.addr(), "/data/7/1000", &[("Range", "bytes=0-9"), ("If-Range", &etag)]).await;
assert_eq!(r.status, 206);
// Optional validators.
let r = get(&srv, "/data/7/10?etag=0&lm=0&weak=1").await;
assert!(r.h("etag").is_none() && r.h("last-modified").is_none());
assert!(get(&srv, "/data/7/10?weak=1").await.h("etag").unwrap().starts_with("W/"));
}
#[tokio::test]
async fn hundred_gigabytes_virtual() {
let srv = TestServer::start().await;
let off = 99u64 << 30;
let r = get_with(srv.addr(), "/data/9/100g", &[("Range", &format!("bytes={off}-{}", off + 99))]).await;
assert_eq!(r.h("content-range"), Some(format!("bytes {off}-{}/{}", off + 99, 100u64 << 30).as_str()));
assert_eq!(r.body, expected(9, off, 100));
let r = request(srv.addr(), "HEAD", "/data/9/100g", &[]).await;
assert_eq!(r.h("content-length"), Some((100u64 << 30).to_string().as_str()));
}
#[tokio::test]
async fn disposition_variants() {
let srv = TestServer::start().await;
let cd = |q: &'static str| {
let srv = &srv;
async move { get(srv, &format!("/data/1/10/report.bin?disp={q}")).await.h("content-disposition").map(String::from) }
};
assert_eq!(cd("attachment").await.unwrap(), "attachment; filename=\"report.bin\"");
assert_eq!(cd("bare").await.unwrap(), "attachment; filename=report.bin");
assert!(cd("star").await.unwrap().contains("filename*=UTF-8''na%C3%AFve%20file.bin"));
assert!(cd("both").await.unwrap().contains("fallback.bin"));
assert!(cd("inline").await.unwrap().starts_with("inline"));
assert!(cd("evil").await.unwrap().contains("../../etc/passwd"));
assert!(cd("dotfile").await.unwrap().contains(".hidden.bin"));
assert!(get(&srv, "/data/1/10").await.h("content-disposition").is_none());
}
#[tokio::test]
async fn redirects() {
let srv = TestServer::start().await;
let r = get(&srv, "/redirect/1?to=/data/1/10").await;
assert_eq!((r.status, r.h("location")), (302, Some("/data/1/10")));
let r = get(&srv, "/redirect/3?to=/data/1/10&code=307").await;
assert_eq!(r.status, 307);
let loc = r.h("location").unwrap().to_string();
assert!(loc.starts_with("/redirect/2?"), "{loc}");
let r = get(&srv, &loc).await;
let r = get(&srv, r.h("location").unwrap()).await;
assert_eq!((r.status, r.h("location")), (307, Some("/data/1/10")));
for code in [301, 303, 308] {
assert_eq!(get(&srv, &format!("/redirect/1?code={code}")).await.status, code);
}
assert_eq!(get(&srv, "/redirect/loop").await.h("location"), Some("/redirect/loop"));
}
#[tokio::test]
async fn chunked_and_no_length() {
let srv = TestServer::start().await;
let r = get(&srv, "/data/3/40000?chunked=1").await;
assert_eq!(r.h("transfer-encoding"), Some("chunked"));
assert!(r.h("content-length").is_none());
assert_eq!(r.body, expected(3, 0, 40000));
let r = get(&srv, "/data/3/5000?nolen=1").await;
assert!(r.h("content-length").is_none() && r.h("transfer-encoding").is_none());
assert_eq!(r.body, expected(3, 0, 5000));
// A reply with no length can't do ranges.
let r = get_with(srv.addr(), "/data/3/5000?nolen=1", &[("Range", "bytes=0-9")]).await;
assert_eq!(r.status, 200);
}
#[tokio::test]
async fn keep_alive_serves_many_requests() {
let srv = TestServer::start().await;
let mut s = TcpStream::connect(srv.addr()).await.unwrap();
for _ in 0..3 {
s.write_all(b"GET /data/1/5 HTTP/1.1\r\nHost: x\r\n\r\n").await.unwrap();
}
s.write_all(b"GET /data/1/5 HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n").await.unwrap();
let (raw, _) = read_all(&mut s).await;
assert_eq!(raw.windows(15).filter(|w| *w == b"HTTP/1.1 200 OK").count(), 4);
assert_eq!(srv.log().iter().map(|r| r.conn).collect::<std::collections::HashSet<_>>().len(), 1);
}
#[tokio::test]
async fn https_with_generated_certificate() {
use tokio_rustls::rustls::pki_types::{CertificateDer, ServerName};
use tokio_rustls::rustls::{ClientConfig, RootCertStore, crypto::ring::default_provider};
let srv = TestServer::start_tls().await;
assert!(srv.base().starts_with("https://"));
let mut roots = RootCertStore::empty();
roots.add(CertificateDer::from(srv.cert_der().unwrap())).unwrap();
let cfg = ClientConfig::builder_with_provider(default_provider().into())
.with_safe_default_protocol_versions()
.unwrap()
.with_root_certificates(roots)
.with_no_client_auth();
let tcp = TcpStream::connect(srv.addr()).await.unwrap();
let mut tls = tokio_rustls::TlsConnector::from(std::sync::Arc::new(cfg))
.connect(ServerName::try_from("localhost").unwrap(), tcp)
.await
.unwrap();
tls.write_all(b"GET /data/4/2000 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n").await.unwrap();
let (raw, _) = read_all(&mut tls).await;
assert_eq!(parse(raw, false).body, expected(4, 0, 2000));
assert!(srv.cert_pem().unwrap().starts_with("-----BEGIN CERTIFICATE"));
}
// ---------- faults ----------
#[tokio::test]
async fn fault_throttle_per_connection() {
let srv = TestServer::start().await;
srv.set_faults("/data/1/4000", Faults { throttle_conn: Some(20_000), ..Faults::default() });
let t = Instant::now();
let r = get(&srv, "/data/1/4000").await;
assert_eq!(r.body, expected(1, 0, 4000));
assert!(t.elapsed() >= Duration::from_millis(150), "{:?}", t.elapsed());
}
#[tokio::test]
async fn fault_throttle_total() {
let srv = TestServer::start().await;
srv.set_faults("*", Faults { throttle_total: Some(20_000), ..Faults::default() });
let t = Instant::now();
let a = srv.addr();
let (x, y) = tokio::join!(get_with(a, "/data/1/4000", &[]), get_with(a, "/data/2/4000", &[]));
assert_eq!((x.body.len(), y.body.len()), (4000, 4000));
// 8000 bytes through 20000 B/s, however many connections.
assert!(t.elapsed() >= Duration::from_millis(300), "{:?}", t.elapsed());
}
#[tokio::test]
async fn fault_latency() {
let srv = TestServer::start().await;
let t = Instant::now();
get(&srv, "/data/1/10?latency_ms=250").await;
assert!(t.elapsed() >= Duration::from_millis(250));
}
#[tokio::test]
async fn fault_stall() {
let srv = TestServer::start().await;
srv.set_faults("/data/1/1000", Faults { stall_after: Some(100), stall_ms: Some(300), ..Faults::default() });
let mut s = TcpStream::connect(srv.addr()).await.unwrap();
s.write_all(b"GET /data/1/1000 HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n").await.unwrap();
let mut got = vec![0u8; 4096];
let mut total = 0;
let t = Instant::now();
// The head and 100 bytes come at once, then nothing for a while.
loop {
let n = tokio::time::timeout(Duration::from_millis(150), s.read(&mut got[total..])).await;
match n {
Ok(Ok(n)) if n > 0 => total += n,
_ => break,
}
}
assert!(total < 600, "body should be stalled at 100 bytes, got {total}");
let (rest, _) = read_all(&mut s).await;
assert!(t.elapsed() >= Duration::from_millis(300));
let all = [&got[..total], &rest[..]].concat();
assert_eq!(parse(all, false).body, expected(1, 0, 1000));
}
#[tokio::test]
async fn fault_cut_after() {
let srv = TestServer::start().await;
let r = get(&srv, "/data/1/1000?cut_after=400").await;
assert_eq!(r.h("content-length"), Some("1000"));
assert_eq!((r.body, r.broken), (expected(1, 0, 400), false));
// Works inside a chunked reply and a ranged one too.
let r = get_with(srv.addr(), "/data/1/1000?cut_after=50", &[("Range", "bytes=100-")]).await;
assert_eq!(r.body, expected(1, 100, 50));
}
#[tokio::test]
async fn fault_reset_after() {
let srv = TestServer::start().await;
let r = get(&srv, "/data/1/100000?reset_after=20000").await;
assert!(r.broken, "expected a reset");
assert!(r.body.len() <= 20000 + 16384);
assert_eq!(srv.log().last().unwrap().status, 0);
}
#[tokio::test]
async fn fault_statuses_with_retry_after() {
let srv = TestServer::start().await;
for code in [403u16, 404, 410, 416, 429, 500, 503] {
let r = get(&srv, &format!("/data/1/100?status={code}&retry_after=7")).await;
assert_eq!(r.status, code);
let want = (code == 429 || code == 503).then_some("7");
assert_eq!(r.h("retry-after").filter(|_| want.is_some()), want, "{code}");
}
let r = get(&srv, "/data/1/100?status=416").await;
assert_eq!(r.h("content-range"), Some("bytes */100"));
// Live switch, per path; cleared again.
srv.set_faults("/data/5/50", Faults::status(503));
assert_eq!(get(&srv, "/data/5/50").await.status, 503);
assert_eq!(get(&srv, "/data/6/50").await.status, 200);
srv.clear_faults("/data/5/50");
assert_eq!(get(&srv, "/data/5/50").await.status, 200);
}
#[tokio::test]
async fn fault_status_only_first_requests() {
let srv = TestServer::start().await;
srv.set_faults("/data/1/10", Faults { status: Some(503), status_count: Some(2), ..Faults::default() });
let codes = [get(&srv, "/data/1/10").await.status, get(&srv, "/data/1/10").await.status, get(&srv, "/data/1/10").await.status];
assert_eq!(codes, [503, 503, 200]);
}
#[tokio::test]
async fn fault_wrong_length() {
let srv = TestServer::start().await;
let r = get(&srv, "/data/1/100?wrong_length=50").await;
assert_eq!(r.h("content-length"), Some("150"));
assert_eq!(r.body.len(), 100);
let r = get(&srv, "/data/1/100?wrong_length=-40").await;
assert_eq!(r.h("content-length"), Some("60"));
}
#[tokio::test]
async fn fault_ignore_range() {
let srv = TestServer::start().await;
let r = get_with(srv.addr(), "/data/1/1000?ignore_range=1", &[("Range", "bytes=10-19")]).await;
assert_eq!((r.status, r.body.len()), (200, 1000));
assert!(r.h("accept-ranges").is_none() && r.h("content-range").is_none());
}
#[tokio::test]
async fn fault_change_after() {
let srv = TestServer::start().await;
let r = get(&srv, "/data/1/1000?change_after=300").await;
assert_eq!(r.body.len(), 1000);
assert_eq!(r.body[..300], expected(1, 0, 300)[..]);
assert_ne!(r.body[300..], expected(1, 300, 700)[..]);
}
#[tokio::test]
async fn fault_new_version_after_requests() {
let srv = TestServer::start().await;
srv.set_faults("/data/1/500", Faults { version_after_requests: Some(1), ..Faults::default() });
let a = get(&srv, "/data/1/500").await;
let b = get(&srv, "/data/1/500").await;
assert_ne!((a.h("etag"), a.h("last-modified")), (b.h("etag"), b.h("last-modified")));
assert_ne!(a.body, b.body);
assert_eq!(b.body.len(), 500);
}
#[tokio::test]
async fn fault_gzip_header() {
let srv = TestServer::start().await;
let r = get(&srv, "/data/1/100?gzip=1").await;
assert_eq!(r.h("content-encoding"), Some("gzip"));
assert!(get(&srv, "/data/1/100").await.h("content-encoding").is_none());
}
#[tokio::test]
async fn fault_link_expires_by_requests() {
let srv = TestServer::start().await;
srv.set_faults("/data/1/10", Faults { expire_requests: Some(2), expire_status: Some(410), ..Faults::default() });
let codes: Vec<u16> = vec![get(&srv, "/data/1/10").await.status, get(&srv, "/data/1/10").await.status, get(&srv, "/data/1/10").await.status];
assert_eq!(codes, [200, 200, 410]);
// Setting the faults again makes a fresh link.
srv.set_faults("/data/1/10", Faults { expire_requests: Some(1), ..Faults::default() });
assert_eq!(get(&srv, "/data/1/10").await.status, 200);
assert_eq!(get(&srv, "/data/1/10").await.status, 403);
}
#[tokio::test]
async fn fault_link_expires_by_time() {
let srv = TestServer::start().await;
srv.set_faults("/data/1/10", Faults { expire_secs: Some(1), ..Faults::default() });
assert_eq!(get(&srv, "/data/1/10").await.status, 200);
tokio::time::sleep(Duration::from_millis(1100)).await;
assert_eq!(get(&srv, "/data/1/10").await.status, 403);
}
#[tokio::test]
async fn fault_cap_on_connections_per_client() {
let srv = TestServer::start().await;
srv.set_faults("*", Faults { max_conns: Some(2), ..Faults::default() });
let _idle1 = TcpStream::connect(srv.addr()).await.unwrap();
let _idle2 = TcpStream::connect(srv.addr()).await.unwrap();
tokio::time::sleep(Duration::from_millis(100)).await;
assert_eq!(srv.open_connections(), 2);
let r = get(&srv, "/data/1/10").await; // third connection
assert_eq!((r.status, r.h("retry-after")), (429, Some("1")));
drop(_idle1);
tokio::time::sleep(Duration::from_millis(100)).await;
assert_eq!(get(&srv, "/data/1/10").await.status, 200);
}
#[tokio::test]
async fn faults_by_prefix_and_query_override() {
let srv = TestServer::start().await;
srv.set_faults("/data/*", Faults::status(500));
srv.set_faults("/data/1/*", Faults::status(404));
assert_eq!(get(&srv, "/data/2/10").await.status, 500);
assert_eq!(get(&srv, "/data/1/10").await.status, 404);
assert_eq!(get(&srv, "/data/1/10?status=410").await.status, 410);
srv.clear_all_faults();
assert_eq!(get(&srv, "/data/2/10").await.status, 200);
}
// ---------- logins ----------
#[tokio::test]
async fn login_basic() {
let srv = TestServer::start().await;
let r = get(&srv, "/basic/ann/pw/data/1/10").await;
assert_eq!(r.status, 401);
assert!(r.h("www-authenticate").unwrap().starts_with("Basic"));
// ann:pw
let r = get_with(srv.addr(), "/basic/ann/pw/data/1/10", &[("Authorization", "Basic YW5uOnB3")]).await;
assert_eq!((r.status, r.body), (200, expected(1, 0, 10)));
let r = get_with(srv.addr(), "/basic/ann/pw/data/1/10", &[("Authorization", "Basic YW5uOnh4")]).await;
assert_eq!(r.status, 401);
}
#[tokio::test]
async fn login_digest() {
let srv = TestServer::start().await;
let path = "/digest/ann/pw/data/1/10";
let r = get(&srv, path).await;
assert_eq!(r.status, 401);
let challenge = r.h("www-authenticate").unwrap();
assert!(challenge.starts_with("Digest") && challenge.contains("qop=\"auth\""));
let nonce = challenge.split("nonce=\"").nth(1).unwrap().split('"').next().unwrap();
let ha1 = md5_hex(b"ann:medlar-test:pw");
let ha2 = md5_hex(format!("GET:{path}").as_bytes());
let resp = md5_hex(format!("{ha1}:{nonce}:00000001:abc:auth:{ha2}").as_bytes());
let auth = format!(
"Digest username=\"ann\", realm=\"medlar-test\", nonce=\"{nonce}\", uri=\"{path}\", qop=auth, nc=00000001, cnonce=\"abc\", response=\"{resp}\""
);
let r = get_with(srv.addr(), path, &[("Authorization", &auth)]).await;
assert_eq!((r.status, r.body.len()), (200, 10));
let bad = auth.replace(&resp, "0000");
assert_eq!(get_with(srv.addr(), path, &[("Authorization", &bad)]).await.status, 401);
}
#[tokio::test]
async fn login_cookie_and_referrer() {
let srv = TestServer::start().await;
assert_eq!(get(&srv, "/cookie/tok/data/1/10").await.status, 403);
let r = get(&srv, "/cookie/tok/login").await;
assert_eq!(r.h("set-cookie"), Some("session=tok; Path=/"));
let r = get_with(srv.addr(), "/cookie/tok/data/1/10", &[("Cookie", "a=b; session=tok")]).await;
assert_eq!(r.status, 200);
assert_eq!(get(&srv, "/referrer/mysite/data/1/10").await.status, 403);
let r = get_with(srv.addr(), "/referrer/mysite/data/1/10", &[("Referer", "http://mysite.test/page")]).await;
assert_eq!(r.status, 200);
}
// ---------- fixtures ----------
#[tokio::test]
async fn open_directory_listing() {
let srv = TestServer::start().await;
let r = get(&srv, "/dir/").await;
let html = String::from_utf8(r.body).unwrap();
for name in ["a.bin", "b.bin", "notes.txt", "sub/", "pack.zip", "pack.tar"] {
assert!(html.contains(&format!("href=\"{name}\"")), "{name}");
}
assert!(String::from_utf8(get(&srv, "/dir/sub/").await.body).unwrap().contains("deep.bin"));
assert_eq!(get(&srv, "/dir/a.bin").await.body, expected(1, 0, 10_000));
assert_eq!(get(&srv, "/dir/sub/deep.bin").await.body, expected(3, 0, 5_000));
assert_eq!(get(&srv, "/dir/notes.txt").await.body, b"hello notes\n");
assert_eq!(get(&srv, "/dir/nope").await.status, 404);
}
fn tool(cmd: &str, args: &[&str]) -> String {
let out = std::process::Command::new(cmd).args(args).output().unwrap();
assert!(out.status.success(), "{cmd} {args:?}: {}", String::from_utf8_lossy(&out.stderr));
String::from_utf8_lossy(&out.stdout).into_owned()
}
#[tokio::test]
async fn zip_and_tar_are_valid() {
let srv = TestServer::start().await;
let dir = std::env::temp_dir().join(format!("medlar-ts-archives-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let (zip, tar) = (dir.join("a.zip"), dir.join("a.tar"));
std::fs::write(&zip, get(&srv, "/archive.zip").await.body).unwrap();
std::fs::write(&tar, get(&srv, "/dir/pack.tar").await.body).unwrap();
assert!(tool("unzip", &["-t", zip.to_str().unwrap()]).contains("No errors"));
let list = tool("unzip", &["-Z1", zip.to_str().unwrap()]);
assert_eq!(list.lines().collect::<Vec<_>>(), ["one.bin", "two/inner.bin", "three.bin"]);
let out = dir.join("out");
std::fs::create_dir_all(&out).unwrap();
tool("bsdtar", &["-xf", tar.to_str().unwrap(), "-C", out.to_str().unwrap()]);
assert_eq!(std::fs::read(out.join("two/inner.bin")).unwrap(), expected(12, 0, 5000));
tool("unzip", &["-o", "-q", zip.to_str().unwrap(), "-d", out.to_str().unwrap()]);
assert_eq!(std::fs::read(out.join("three.bin")).unwrap(), expected(13, 0, 40000));
// The zip supports a range read of its end (central directory), as a remote peek needs.
let r = get_with(srv.addr(), "/archive.zip", &[("Range", "bytes=-22")]).await;
assert_eq!((r.status, &r.body[..4]), (206, &b"PK\x05\x06"[..]));
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn small_site_tree() {
let srv = TestServer::start().await;
let index = String::from_utf8(get(&srv, "/site/").await.body).unwrap();
for part in ["page1.html", "a/page2.html", "/site/a/b/page3.html", "http://elsewhere.invalid", "img/logo.bin", "style.css"] {
assert!(index.contains(part), "{part}");
}
assert_eq!(get(&srv, "/site/a/b/page3.html").await.h("content-type"), Some("text/html"));
assert_eq!(get(&srv, "/site/files/big.bin").await.body, expected(22, 0, 50_000));
assert_eq!(get(&srv, "/site/missing.html").await.status, 404);
}
#[tokio::test]
async fn checksum_sidecars() {
let srv = TestServer::start().await;
let data = expected(7, 0, 3000);
let r = get(&srv, "/sum/sha256/7/3000").await;
let want: String = Sha256::digest(&data).iter().map(|b| format!("{b:02x}")).collect();
assert_eq!(String::from_utf8(r.body).unwrap(), format!("{want} data-7.bin\n"));
for algo in ["md5", "sha1", "sha512"] {
assert_eq!(get(&srv, &format!("/sum/{algo}/7/3000")).await.status, 200, "{algo}");
}
assert_eq!(get(&srv, "/sum/crc/7/3000").await.status, 404);
}
#[tokio::test]
async fn metalink_files() {
let srv = TestServer::start().await;
let v4 = String::from_utf8(get(&srv, "/meta/v4.meta4").await.body).unwrap();
let sha: String = Sha256::digest(expected(5, 0, 50_000)).iter().map(|b| format!("{b:02x}")).collect();
assert!(v4.contains(&sha) && v4.contains(&srv.url("/data/5/50000")) && v4.contains("urn:ietf:params:xml:ns:metalink"));
let v3 = String::from_utf8(get(&srv, "/meta/v3.metalink").await.body).unwrap();
assert!(v3.contains("version=\"3.0\"") && v3.contains("type=\"md5\"") && v3.contains(&srv.url("/data/5/50000/mirror.bin")));
let r = get(&srv, "/meta/header.bin").await;
assert!(r.h("link").unwrap().contains("rel=duplicate"));
assert!(r.h("digest").unwrap().starts_with("SHA-256="));
assert_eq!(r.body, expected(5, 0, 50_000));
}
#[tokio::test]
async fn hls_and_dash_fixtures() {
let srv = TestServer::start().await;
assert_eq!(get(&srv, "/media/master.m3u8").await.status, 404);
srv.build_media().await.expect("ffmpeg fixtures");
let master = String::from_utf8(get(&srv, "/media/master.m3u8").await.body).unwrap();
assert!(master.contains("index.m3u8"));
let index = String::from_utf8(get(&srv, "/media/index.m3u8").await.body).unwrap();
assert!(index.contains("seg0.ts") && index.contains("#EXT-X-ENDLIST"));
let seg = get(&srv, "/media/seg0.ts").await;
assert_eq!((seg.status, seg.body[0]), (200, 0x47));
assert_eq!(seg.h("content-type"), Some("video/mp2t"));
let mpd = String::from_utf8(get(&srv, "/media/manifest.mpd").await.body).unwrap();
assert!(mpd.contains("<MPD"));
assert_eq!(get(&srv, "/media/..%2Fx").await.status, 404);
}
// ---------- log ----------
#[tokio::test]
async fn request_log() {
let srv = TestServer::start().await;
get_with(srv.addr(), "/data/1/100", &[("Range", "bytes=5-9"), ("User-Agent", "probe")]).await;
get(&srv, "/data/1/100?status=404").await;
let log = srv.log();
assert_eq!(log.len(), 2);
assert_eq!((log[0].method.as_str(), log[0].path(), log[0].status, log[0].sent), ("GET", "/data/1/100", 206, 5));
assert_eq!((log[0].header("range"), log[0].header("user-agent")), (Some("bytes=5-9"), Some("probe")));
assert_eq!(log[1].status, 404);
assert_eq!(srv.requests_for("/data/1/100").len(), 2);
srv.clear_log();
assert!(srv.log().is_empty());
}
// ---------- proxies ----------
fn echo_target(srv: &TestServer, path: &str) -> String {
format!("http://127.0.0.1:{}{path}", srv.port())
}
#[tokio::test]
async fn http_proxy_forwards_and_records() {
let srv = TestServer::start().await;
let proxy = Proxy::start_http(None).await;
let r = get_with(proxy.addr(), &echo_target(&srv, "/data/2/777"), &[]).await;
assert_eq!((r.status, r.body), (200, expected(2, 0, 777)));
let seen = proxy.seen();
assert_eq!(seen.len(), 1);
assert_eq!((seen[0].kind, seen[0].allowed), ("http", true));
assert_eq!(seen[0].target, format!("127.0.0.1:{}", srv.port()));
assert!(seen[0].request_line.starts_with("GET http://127.0.0.1"));
// The server saw an ordinary origin-form request.
assert_eq!(srv.log()[0].target, "/data/2/777");
}
#[tokio::test]
async fn http_proxy_connect_and_login() {
let srv = TestServer::start().await;
let proxy = Proxy::start_http(Some(("u", "p"))).await;
let r = get_with(proxy.addr(), &echo_target(&srv, "/data/2/10"), &[]).await;
assert_eq!(r.status, 407);
assert!(!proxy.seen()[0].allowed);
// u:p
let mut s = TcpStream::connect(proxy.addr()).await.unwrap();
let target = format!("127.0.0.1:{}", srv.port());
s.write_all(format!("CONNECT {target} HTTP/1.1\r\nHost: {target}\r\nProxy-Authorization: Basic dTpw\r\n\r\n").as_bytes()).await.unwrap();
let mut head = [0u8; 39];
s.read_exact(&mut head).await.unwrap();
assert!(head.starts_with(b"HTTP/1.1 200"));
s.write_all(b"GET /data/2/10 HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n").await.unwrap();
let (raw, _) = read_all(&mut s).await;
assert_eq!(parse(raw, false).body, expected(2, 0, 10));
let seen = proxy.seen();
assert_eq!((seen[1].kind, seen[1].allowed), ("connect", true));
assert!(seen[1].credentials.as_deref().unwrap().starts_with("Basic"));
}
#[tokio::test]
async fn proxies_refuse_the_real_network() {
let proxy = Proxy::start_http(None).await;
let r = get_with(proxy.addr(), "http://8.8.8.8/x", &[]).await;
assert_eq!(r.status, 502);
assert!(!proxy.seen()[0].allowed);
let socks = Proxy::start_socks5(None).await;
let mut s = TcpStream::connect(socks.addr()).await.unwrap();
s.write_all(&[5, 1, 0]).await.unwrap();
let mut two = [0u8; 2];
s.read_exact(&mut two).await.unwrap();
s.write_all(&[5, 1, 0, 3, 11]).await.unwrap();
s.write_all(b"example.com").await.unwrap();
s.write_all(&80u16.to_be_bytes()).await.unwrap();
let mut reply = [0u8; 10];
s.read_exact(&mut reply).await.unwrap();
assert_eq!(reply[1], 5);
assert_eq!(socks.seen()[0].target, "example.com:80");
assert!(!socks.seen()[0].allowed);
}
async fn socks_get(proxy: &Proxy, host: &[u8], atyp: u8, port: u16, auth: Option<(&str, &str)>) -> (Option<TcpStream>, u8) {
let mut s = TcpStream::connect(proxy.addr()).await.unwrap();
if let Some((u, p)) = auth {
s.write_all(&[5, 1, 2]).await.unwrap();
let mut two = [0u8; 2];
s.read_exact(&mut two).await.unwrap();
assert_eq!(two, [5, 2]);
let mut m = vec![1, u.len() as u8];
m.extend(u.as_bytes());
m.push(p.len() as u8);
m.extend(p.as_bytes());
s.write_all(&m).await.unwrap();
s.read_exact(&mut two).await.unwrap();
if two[1] != 0 {
return (None, two[1]);
}
} else {
s.write_all(&[5, 1, 0]).await.unwrap();
let mut two = [0u8; 2];
s.read_exact(&mut two).await.unwrap();
}
let mut m = vec![5, 1, 0, atyp];
if atyp == 3 {
m.push(host.len() as u8);
}
m.extend(host);
m.extend(port.to_be_bytes());
s.write_all(&m).await.unwrap();
let mut reply = [0u8; 10];
s.read_exact(&mut reply).await.unwrap();
(Some(s), reply[1])
}
#[tokio::test]
async fn socks5_proxy_records_and_maps_names() {
let srv = TestServer::start().await;
let proxy = Proxy::start_socks5(None).await;
let (s, code) = socks_get(&proxy, &[127, 0, 0, 1], 1, srv.port(), None).await;
assert_eq!(code, 0);
let mut s = s.unwrap();
s.write_all(b"GET /data/2/321 HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n").await.unwrap();
let (raw, _) = read_all(&mut s).await;
assert_eq!(parse(raw, false).body, expected(2, 0, 321));
// A made-up name works only when mapped.
proxy.map_host("files.test", srv.addr());
let (s, code) = socks_get(&proxy, b"files.test", 3, 80, None).await;
assert_eq!(code, 0);
drop(s);
let seen = proxy.seen();
assert_eq!(seen[0].target, format!("127.0.0.1:{}", srv.port()));
assert_eq!(seen[1].target, "files.test:80");
}
#[tokio::test]
async fn socks5_proxy_login() {
let srv = TestServer::start().await;
let proxy = Proxy::start_socks5(Some(("u", "p"))).await;
let (s, code) = socks_get(&proxy, &[127, 0, 0, 1], 1, srv.port(), Some(("u", "bad"))).await;
assert!((s.is_none(), code) == (true, 1));
let (s, code) = socks_get(&proxy, &[127, 0, 0, 1], 1, srv.port(), Some(("u", "p"))).await;
assert_eq!((s.is_some(), code), (true, 0));
let seen = proxy.seen();
assert_eq!((seen[0].allowed, seen[0].credentials.as_deref()), (false, Some("u")));
assert!(seen[1].allowed);
}

View file

@ -13,5 +13,14 @@ Verified: `nice cargo test -j 2` green (34 tests; kill test run 5 times, 5 kills
- `ErrorKind` is empty (S007): add variants and `error.<name>` texts.
Not done: statistics and quota tables (their plans add a migration).
## S002 — Test server with faults (2026-11-24)
Done: `crates/testserver` (hand-made HTTP/1.1 on tokio, 127.0.0.1 only), binary `medlar-testserver [--port N] [--tls] [--media] [--proxies]`.
Verified: `nice cargo test -j 2 -p medlar-testserver` green (44 tests, ~1 s, one per fault and fixture); clippy clean; zip/tar checked with unzip/bsdtar.
- API: `TestServer::start()/start_tls()` (async, port 0), `url(path)`, `log()/requests_for(path)/clear_log()`, `set_faults(path, Faults)` (exact, `prefix*`, or `*`), `clear_faults`, `open_connections()`, `build_media()` (ffmpeg → `/media/`), `cert_der()` for HTTPS clients. Content: `expected(seed, start, len)`.
- Files: `/data/<seed>/<len>[/name]` (len takes k m g t; 100g ok). Query: `disp=attachment|bare|star|both|inline|evil|dotfile`, `chunked=1`, `nolen=1`, `etag=0`, `lm=0`, `weak=1`. Also `/redirect/<n>?to=&code=`, `/redirect/loop`, `/status/<code>`, `/basic|digest/<u>/<p>/…`, `/cookie/<tok>/login`, `/referrer/<needle>/…`, `/dir/`, `/site/`, `/archive.zip|tar`, `/sum/<algo>/<seed>/<len>`, `/meta/v4.meta4|v3.metalink|header.bin`.
- Faults (field of `Faults`, or same name in the query): throttle_conn, throttle_total (bytes/s), latency_ms, stall_after (+stall_ms), cut_after (clean close), reset_after (RST), status (+retry_after, status_count), wrong_length (added to Content-Length), ignore_range, change_after (bytes switch), version_after_requests (new ETag, date, bytes), gzip (header only, body stays plain), expire_secs / expire_requests (+expire_status, default 403), max_conns (open connections per client; over it → 429).
- Proxies: `proxy::Proxy::start_http(auth)` / `start_socks5(auth)`; `seen()` lists kind, target, credentials, allowed; they connect only to loopback or names set with `map_host`.
Not done: BLAKE3 sidecar, HTTP/2, a real gzip body, FTP/SFTP servers (their plans).
## Later
-