diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 000000000..e71e40057 --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,4 @@ +[cargo-new] +name = "Humanode Team" +email = "core@humanode.io" +vcs = "git" diff --git a/Cargo.lock b/Cargo.lock index f19c99a9d..d29e48088 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,12 +2,55 @@ # It is not intended for manual editing. version = 3 +[[package]] +name = "aho-corasick" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7404febffaa47dac81aa44dba71523c9d069b1bdc50a77db41195149e17f68e5" +dependencies = [ + "memchr", +] + [[package]] name = "anyhow" version = "1.0.40" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28b2cd92db5cbd74e8e5028f7e27dd7aa3090e89e4f2a197cc7c8dfb69c7063b" +[[package]] +name = "arrayvec" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b62fc65de8e4e7f52534fb52b0f3ed04746ae267519eef2a83941e8085068b" + +[[package]] +name = "assert_matches" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b34d609dfbaf33d6889b2b7106d3ca345eacad44200913df5ba02bfd31d2ba9" + +[[package]] +name = "async-channel" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2114d64672151c0c5eaa5e131ec84a74f06e1e559830dabba01ca30605d66319" +dependencies = [ + "concurrent-queue", + "event-listener", + "futures-core", +] + +[[package]] +name = "async-trait" +version = "0.1.50" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b98e84bbb4cbcdd97da190ba0c58a1bb0de2c1fdf67d159e192ed766aeca722" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "autocfg" version = "1.0.1" @@ -26,18 +69,49 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" +[[package]] +name = "block-buffer" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" +dependencies = [ + "generic-array", +] + +[[package]] +name = "buf_redux" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b953a6887648bb07a535631f2bc00fbdb2a2216f135552cb3f534ed136b9c07f" +dependencies = [ + "memchr", + "safemem", +] + [[package]] name = "bumpalo" version = "3.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63396b8a4b9de3f4fdfb320ab6080762242f66a8ef174c49d8e19b674db4cdbe" +[[package]] +name = "byteorder" +version = "1.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" + [[package]] name = "bytes" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b700ce4376041dcd0a327fd0097c41095743c4c8af8887265942faf1100bd040" +[[package]] +name = "cache-padded" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "631ae5198c9be5e753e5cc215e1bd73c2b466a3565173db433f52bb9d3e66dba" + [[package]] name = "cc" version = "1.0.67" @@ -50,6 +124,26 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +[[package]] +name = "concurrent-queue" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30ed07550be01594c6026cff2a1d7fe9c8f683caa798e12b68694ac9e88286a3" +dependencies = [ + "cache-padded", +] + +[[package]] +name = "config" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19b076e143e1d9538dde65da30f8481c2a6c44040edb8e02b9bf1351edb92ce3" +dependencies = [ + "lazy_static", + "nom", + "serde", +] + [[package]] name = "core-foundation" version = "0.9.1" @@ -66,6 +160,62 @@ version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea221b5284a47e40033bf9b66f35f984ec0ea2931eb03505246cd27a963f981b" +[[package]] +name = "cpuid-bool" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8aebca1129a03dc6dc2b127edd729435bbc4a37e1d5f4d7513165089ceb02634" + +[[package]] +name = "crossbeam-queue" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f6cb3c7f5b8e51bc3ebb73a2327ad4abdbd119dc13223f14f961d2f38486756" +dependencies = [ + "cfg-if", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4feb231f0d4d6af81aed15928e58ecf5816aa62a2393e2c82f46973e92a9a278" +dependencies = [ + "autocfg", + "cfg-if", + "lazy_static", +] + +[[package]] +name = "data-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ee2393c4a91429dffb4bedf19f4d6abf27d8a732c8ce4980305d782e5426d57" + +[[package]] +name = "deadpool" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d126179d86aee4556e54f5f3c6bf6d9884e7cc52cef82f77ee6f90a7747616d" +dependencies = [ + "async-trait", + "config", + "crossbeam-queue", + "num_cpus", + "serde", + "tokio", +] + +[[package]] +name = "digest" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" +dependencies = [ + "generic-array", +] + [[package]] name = "encoding_rs" version = "0.8.28" @@ -75,6 +225,34 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "event-listener" +version = "2.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7531096570974c3a9dcf9e4b8e1cede1ec26cf5046219fb3b9d897503b9be59" + +[[package]] +name = "facetec-api-client" +version = "0.1.0" +dependencies = [ + "assert_matches", + "reqwest", + "serde", + "serde_json", + "thiserror", + "tokio", + "wiremock", +] + +[[package]] +name = "fastrand" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77b705829d1e87f762c2df6da140b26af5839e1033aa84aa5f56bb688e4e1bdb" +dependencies = [ + "instant", +] + [[package]] name = "fnv" version = "1.0.7" @@ -106,6 +284,21 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "futures" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d5813545e459ad3ca1bff9915e9ad7f1a47dc6a91b627ce321d5863b7dd253" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + [[package]] name = "futures-channel" version = "0.3.14" @@ -113,6 +306,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce79c6a52a299137a6013061e0cf0e688fce5d7f1bc60125f520912fdb29ec25" dependencies = [ "futures-core", + "futures-sink", ] [[package]] @@ -121,6 +315,50 @@ version = "0.3.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "098cd1c6dda6ca01650f1a37a794245eb73181d0d4d4e955e2f3c37db7af1815" +[[package]] +name = "futures-executor" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10f6cb7042eda00f0049b1d2080aa4b93442997ee507eb3828e8bd7577f94c9d" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "365a1a1fb30ea1c03a830fdb2158f5236833ac81fa0ad12fe35b29cddc35cb04" + +[[package]] +name = "futures-lite" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4481d0cd0de1d204a4fa55e7d45f07b1d958abcb06714b3446438e2eff695fb" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "memchr", + "parking", + "pin-project-lite", + "waker-fn", +] + +[[package]] +name = "futures-macro" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "668c6733a182cd7deb4f1de7ba3bf2120823835b3bcfbeacf7d2c4a773c1bb8b" +dependencies = [ + "proc-macro-hack", + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "futures-sink" version = "0.3.14" @@ -133,16 +371,51 @@ version = "0.3.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba7aa51095076f3ba6d9a1f702f74bd05ec65f555d70d2033d55ba8d69f581bc" +[[package]] +name = "futures-timer" +version = "3.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e64b03909df88034c26dc1547e8970b91f98bdb65165d6a4e9110d94263dbb2c" + [[package]] name = "futures-util" version = "0.3.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c144ad54d60f23927f0a6b6d816e4271278b64f005ad65e4e35291d2de9c025" dependencies = [ + "futures-channel", "futures-core", + "futures-io", + "futures-macro", + "futures-sink", "futures-task", + "memchr", "pin-project-lite", "pin-utils", + "proc-macro-hack", + "proc-macro-nested", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "501466ecc8a30d1d3b7fc9229b122b2ce8ed6e9d9223f1138d4babb253e51817" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce" +dependencies = [ + "cfg-if", + "libc", + "wasi 0.9.0+wasi-snapshot-preview1", ] [[package]] @@ -153,7 +426,7 @@ checksum = "c9495705279e7140bf035dde1f6e750c162df8b625267cd52cc44e0b156732c8" dependencies = [ "cfg-if", "libc", - "wasi", + "wasi 0.10.2+wasi-snapshot-preview1", ] [[package]] @@ -181,6 +454,31 @@ version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d7afe4a420e3fe79967a00898cc1f4db7c8a49a9333a29f8a4bd76a253d5cd04" +[[package]] +name = "headers" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0b7591fb62902706ae8e7aaff416b1b0fa2c0fd0878b46dc13baa3712d8a855" +dependencies = [ + "base64", + "bitflags", + "bytes", + "headers-core", + "http", + "mime", + "sha-1", + "time", +] + +[[package]] +name = "headers-core" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7f66481bfee273957b1f20485a4ff3362987f85b2c236580d81b4eb7a326429" +dependencies = [ + "http", +] + [[package]] name = "hermit-abi" version = "0.1.18" @@ -212,6 +510,27 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "http-types" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad077d89137cd3debdce53c66714dc536525ef43fe075d41ddc0a8ac11f85957" +dependencies = [ + "anyhow", + "async-channel", + "base64", + "futures-lite", + "http", + "infer", + "pin-project-lite", + "rand 0.7.3", + "serde", + "serde_json", + "serde_qs", + "serde_urlencoded", + "url", +] + [[package]] name = "httparse" version = "1.4.0" @@ -290,6 +609,21 @@ dependencies = [ "hashbrown", ] +[[package]] +name = "infer" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64e9829a50b42bb782c1df523f78d332fe371b10c661e78b7a3c34b0198e9fac" + +[[package]] +name = "input_buffer" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f97967975f448f1a7ddb12b0bc41069d09ed6a1c161a92687e057325db35d413" +dependencies = [ + "bytes", +] + [[package]] name = "instant" version = "0.1.9" @@ -326,6 +660,19 @@ version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" +[[package]] +name = "lexical-core" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6607c62aa161d23d17a9072cc5da0be67cdfc89d3afb1e8d9c842bebc2525ffe" +dependencies = [ + "arrayvec", + "bitflags", + "cfg-if", + "ryu", + "static_assertions", +] + [[package]] name = "libc" version = "0.2.93" @@ -368,6 +715,16 @@ version = "0.3.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d" +[[package]] +name = "mime_guess" +version = "2.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2684d4c2e97d99848d30b324b00c8fcc7e5c897b7cbb5819b09e7c90e8baf212" +dependencies = [ + "mime", + "unicase", +] + [[package]] name = "mio" version = "0.7.11" @@ -390,6 +747,24 @@ dependencies = [ "winapi", ] +[[package]] +name = "multipart" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d050aeedc89243f5347c3e237e3e13dc76fbe4ae3742a57b94dc14f69acf76d4" +dependencies = [ + "buf_redux", + "httparse", + "log", + "mime", + "mime_guess", + "quick-error", + "rand 0.7.3", + "safemem", + "tempfile", + "twoway", +] + [[package]] name = "native-tls" version = "0.2.7" @@ -408,6 +783,17 @@ dependencies = [ "tempfile", ] +[[package]] +name = "nom" +version = "5.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffb4262d26ed83a1c0a33a38fe2bb15797329c85770da05e6b828ddb782627af" +dependencies = [ + "lexical-core", + "memchr", + "version_check", +] + [[package]] name = "ntapi" version = "0.3.6" @@ -433,6 +819,12 @@ version = "1.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af8b08b04175473088b46763e51ee54da5f9a164bc162f615b91bc179dbf15a3" +[[package]] +name = "opaque-debug" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" + [[package]] name = "openssl" version = "0.10.33" @@ -466,6 +858,12 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "parking" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "427c3892f9e783d91cc128285287e70a59e206ca452770ece88a76f7a3eddd72" + [[package]] name = "parking_lot" version = "0.11.1" @@ -541,6 +939,18 @@ version = "0.2.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac74c624d6b2d21f425f752262f42188365d7b8ff1aff74c82e45136510a4857" +[[package]] +name = "proc-macro-hack" +version = "0.5.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5" + +[[package]] +name = "proc-macro-nested" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc881b2c22681370c6a780e47af9840ef841837bc98118431d4e1868bd0c1086" + [[package]] name = "proc-macro2" version = "1.0.26" @@ -550,6 +960,12 @@ dependencies = [ "unicode-xid", ] +[[package]] +name = "quick-error" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + [[package]] name = "quote" version = "1.0.9" @@ -559,6 +975,19 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "rand" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03" +dependencies = [ + "getrandom 0.1.16", + "libc", + "rand_chacha 0.2.2", + "rand_core 0.5.1", + "rand_hc 0.2.0", +] + [[package]] name = "rand" version = "0.8.3" @@ -566,9 +995,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ef9e7e66b4468674bfcb0c81af8b7fa0bb154fa9f28eb840da5c447baeb8d7e" dependencies = [ "libc", - "rand_chacha", - "rand_core", - "rand_hc", + "rand_chacha 0.3.0", + "rand_core 0.6.2", + "rand_hc 0.3.0", +] + +[[package]] +name = "rand_chacha" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402" +dependencies = [ + "ppv-lite86", + "rand_core 0.5.1", ] [[package]] @@ -578,7 +1017,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e12735cf05c9e10bf21534da50a147b924d555dc7a547c42e6bb2d5b6017ae0d" dependencies = [ "ppv-lite86", - "rand_core", + "rand_core 0.6.2", +] + +[[package]] +name = "rand_core" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" +dependencies = [ + "getrandom 0.1.16", ] [[package]] @@ -587,7 +1035,16 @@ version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34cf66eb183df1c5876e2dcf6b13d57340741e8dc255b48e40a26de954d06ae7" dependencies = [ - "getrandom", + "getrandom 0.2.2", +] + +[[package]] +name = "rand_hc" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c" +dependencies = [ + "rand_core 0.5.1", ] [[package]] @@ -596,7 +1053,7 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3190ef7066a446f2e7f42e239d161e905420ccab01eb967c9eb27d21b2322a73" dependencies = [ - "rand_core", + "rand_core 0.6.2", ] [[package]] @@ -608,6 +1065,23 @@ dependencies = [ "bitflags", ] +[[package]] +name = "regex" +version = "1.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a26af418b574bd56588335b3a3659a65725d4e636eb1016c2f9e3b38c7cc759" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.6.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f497285884f3fcff424ffc933e56d7cbca511def0c9831a7f9b5f6153e3cc89b" + [[package]] name = "remove_dir_all" version = "0.5.3" @@ -656,17 +1130,24 @@ dependencies = [ name = "robonode-client" version = "0.1.0" dependencies = [ + "assert_matches", "reqwest", "serde", + "serde_json", "thiserror", + "tokio", + "wiremock", ] [[package]] name = "robonode-server" version = "0.1.0" dependencies = [ - "hyper", + "facetec-api-client", + "reqwest", + "serde", "tokio", + "warp", ] [[package]] @@ -675,6 +1156,12 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e" +[[package]] +name = "safemem" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef703b7cb59335eae2eb93ceb664c0eb7ea6bf567079d843e09420219668e072" + [[package]] name = "schannel" version = "0.1.19" @@ -685,6 +1172,12 @@ dependencies = [ "winapi", ] +[[package]] +name = "scoped-tls" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6a9290e3c9cf0f18145ef7ffa62d68ee0bf5fcd651017e586dc7fd5da448c2" + [[package]] name = "scopeguard" version = "1.1.0" @@ -745,6 +1238,18 @@ dependencies = [ "serde", ] +[[package]] +name = "serde_qs" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5af82de3c6549b001bec34961ff2d6a54339a87bab37ce901b693401f27de6cb" +dependencies = [ + "data-encoding", + "percent-encoding", + "serde", + "thiserror", +] + [[package]] name = "serde_urlencoded" version = "0.7.0" @@ -757,6 +1262,19 @@ dependencies = [ "serde", ] +[[package]] +name = "sha-1" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfebf75d25bd900fd1e7d11501efab59bc846dbc76196839663e6637bba9f25f" +dependencies = [ + "block-buffer", + "cfg-if", + "cpuid-bool", + "digest", + "opaque-debug", +] + [[package]] name = "signal-hook-registry" version = "1.3.0" @@ -778,6 +1296,12 @@ version = "1.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fe0f37c9e8f3c5a4a66ad655a93c74daac4ad00c441533bf5c6e7990bb42604e" +[[package]] +name = "smawk" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f67ad224767faa3c7d8b6d91985b78e70a1324408abcb1cfcc2be4c06bc06043" + [[package]] name = "socket2" version = "0.4.0" @@ -788,6 +1312,12 @@ dependencies = [ "winapi", ] +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + [[package]] name = "syn" version = "1.0.70" @@ -807,12 +1337,22 @@ checksum = "dac1c663cfc93810f88aed9b8941d48cabf856a1b111c29a40439018d870eb22" dependencies = [ "cfg-if", "libc", - "rand", + "rand 0.8.3", "redox_syscall", "remove_dir_all", "winapi", ] +[[package]] +name = "textwrap" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd05616119e612a8041ef58f2b578906cc2531a6069047ae092cfb86a325d835" +dependencies = [ + "smawk", + "unicode-width", +] + [[package]] name = "thiserror" version = "1.0.24" @@ -833,6 +1373,16 @@ dependencies = [ "syn", ] +[[package]] +name = "time" +version = "0.1.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca8a50ef2360fbd1eeb0ecd46795a87a19024eb4b53c5dc916ca1fd95fe62438" +dependencies = [ + "libc", + "winapi", +] + [[package]] name = "tinyvec" version = "1.2.0" @@ -889,6 +1439,30 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-stream" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e177a5d8c3bf36de9ebe6d58537d8879e964332f93fb3339e43f618c81361af0" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1a5f475f1b9d077ea1017ecbc60890fda8e54942d680ca0b1d2b47cfa2d861b" +dependencies = [ + "futures-util", + "log", + "pin-project", + "tokio", + "tungstenite", +] + [[package]] name = "tokio-util" version = "0.6.6" @@ -916,6 +1490,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "01ebdc2bb4498ab1ab5f5b73c5803825e60199229ccba0698170e3be0e7f959f" dependencies = [ "cfg-if", + "log", "pin-project-lite", "tracing-core", ] @@ -935,6 +1510,49 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "59547bce71d9c38b83d9c0e92b6066c4253371f15005def0c30d9657f50c7642" +[[package]] +name = "tungstenite" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ada8297e8d70872fa9a551d93250a9f407beb9f37ef86494eb20012a2ff7c24" +dependencies = [ + "base64", + "byteorder", + "bytes", + "http", + "httparse", + "input_buffer", + "log", + "rand 0.8.3", + "sha-1", + "url", + "utf-8", +] + +[[package]] +name = "twoway" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59b11b2b5241ba34be09c3cc85a36e56e48f9888862e19cedf23336d35316ed1" +dependencies = [ + "memchr", +] + +[[package]] +name = "typenum" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f6906492a7cd215bfa4cf595b600146ccfac0c79bcbd1f3000162af5e8b06" + +[[package]] +name = "unicase" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6" +dependencies = [ + "version_check", +] + [[package]] name = "unicode-bidi" version = "0.3.5" @@ -953,6 +1571,12 @@ dependencies = [ "tinyvec", ] +[[package]] +name = "unicode-width" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9337591893a19b88d8d87f2cec1e73fad5cdfd10e5a6f349f498ad6ea2ffb1e3" + [[package]] name = "unicode-xid" version = "0.2.1" @@ -969,14 +1593,33 @@ dependencies = [ "idna", "matches", "percent-encoding", + "serde", ] +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + [[package]] name = "vcpkg" version = "0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cbdbff6266a24120518560b5dc983096efb98462e51d0d68169895b237be3e5d" +[[package]] +name = "version_check" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fecdca9a5291cc2b8dcf7dc02453fee791a280f3743cb0905f8822ae463b3fe" + +[[package]] +name = "waker-fn" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d5b2c62b4012a3e1eca5a7e077d13b3bf498c4073e33ccd58626607748ceeca" + [[package]] name = "want" version = "0.3.0" @@ -987,6 +1630,41 @@ dependencies = [ "try-lock", ] +[[package]] +name = "warp" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "332d47745e9a0c38636dbd454729b147d16bd1ed08ae67b3ab281c4506771054" +dependencies = [ + "bytes", + "futures", + "headers", + "http", + "hyper", + "log", + "mime", + "mime_guess", + "multipart", + "percent-encoding", + "pin-project", + "scoped-tls", + "serde", + "serde_json", + "serde_urlencoded", + "tokio", + "tokio-stream", + "tokio-tungstenite", + "tokio-util", + "tower-service", + "tracing", +] + +[[package]] +name = "wasi" +version = "0.9.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" + [[package]] name = "wasi" version = "0.10.2+wasi-snapshot-preview1" @@ -1101,3 +1779,24 @@ checksum = "0120db82e8a1e0b9fb3345a539c478767c0048d842860994d96113d5b667bd69" dependencies = [ "winapi", ] + +[[package]] +name = "wiremock" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1cbd58fcf4ac80633ef8f48abdfa1d8743150593c6def666d114c10aa90afac8" +dependencies = [ + "async-trait", + "deadpool", + "futures", + "futures-timer", + "http-types", + "hyper", + "log", + "once_cell", + "regex", + "serde", + "serde_json", + "textwrap", + "tokio", +] diff --git a/Cargo.toml b/Cargo.toml index dc13eba27..92ed4e8a3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,2 +1,7 @@ [workspace] -members = ["humanode-peer", "robonode-server", "robonode-client"] +members = [ + "humanode-peer", + "robonode-server", + "robonode-client", + "facetec-api-client", +] diff --git a/facetec-api-client/Cargo.toml b/facetec-api-client/Cargo.toml new file mode 100644 index 000000000..b6f776b40 --- /dev/null +++ b/facetec-api-client/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "facetec-api-client" +version = "0.1.0" +edition = "2018" +authors = ["Humanode Team "] +publish = false + +[dependencies] +reqwest = { version = "0.11", features = ["json"] } +serde = { version = "1", features = ["derive"] } +thiserror = "1" + +[dev-dependencies] +assert_matches = "1.5" +serde_json = "1" +tokio = { version = "1", features = ["full"] } +wiremock = "0.5" diff --git a/facetec-api-client/src/db_enroll.rs b/facetec-api-client/src/db_enroll.rs new file mode 100644 index 000000000..230c94f74 --- /dev/null +++ b/facetec-api-client/src/db_enroll.rs @@ -0,0 +1,271 @@ +//! POST `/3d-db/enroll` + +use reqwest::StatusCode; +use serde::{Deserialize, Serialize}; + +use crate::{CommonResponse, Error}; + +use super::Client; + +impl Client { + /// Perform the `/3d-db/enroll` call to the server. + pub async fn db_enroll( + &self, + req: DBEnrollRequest<'_>, + ) -> Result> { + let url = format!("{}/3d-db/enroll", self.base_url); + let res = self.reqwest.post(url).json(&req).send().await?; + match res.status() { + StatusCode::OK => Ok(res.json().await?), + StatusCode::BAD_REQUEST => { + Err(Error::Call(DBEnrollError::BadRequest(res.json().await?))) + } + _ => Err(Error::Call(DBEnrollError::Unknown(res.text().await?))), + } + } +} + +/// Input data for the `/3d-db/enroll` request. +#[derive(Debug, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct DBEnrollRequest<'a> { + /// The ID of the pre-enrolled FaceMap to use. + #[serde(rename = "externalDatabaseRefID")] + pub external_database_ref_id: &'a str, + /// The name of the group to enroll the specified FaceMap at. + pub group_name: &'a str, +} + +/// The response from `/3d-db/enroll`. +#[derive(Debug, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct DBEnrollResponse { + /// Common response portion. + #[serde(flatten)] + pub common: CommonResponse, + /// The external database ID that was used. + #[serde(rename = "externalDatabaseRefID")] + pub external_database_ref_id: String, + /// Whether the request had any errors during the execution. + pub error: bool, + /// Whether the request was successful. + pub success: bool, +} + +/// The `/3d-db/enroll`-specific error kind. +#[derive(Error, Debug, PartialEq)] +pub enum DBEnrollError { + /// The face scan or public key were already enrolled. + #[error("already enrolled")] + AlreadyEnrolled, + /// Bad request error occured. + #[error("bad request: {0}")] + BadRequest(DBEnrollErrorBadRequest), + /// Some other error occured. + #[error("unknown error: {0}")] + Unknown(String), +} + +/// The error kind for the `/3d-db/enroll`-specific 400 response. +#[derive(Error, Debug, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +#[error("bad request: {error_message}")] +pub struct DBEnrollErrorBadRequest { + /// Whether the request had any errors during the execution. + /// Expected to always be `true` in this context. + pub error: bool, + /// Whether the request was successful. + /// Expected to always be `false` in this context. + pub success: bool, + /// The error message. + pub error_message: String, +} + +#[cfg(test)] +mod tests { + use wiremock::{matchers, Mock, MockServer, ResponseTemplate}; + + use super::*; + + #[test] + fn request_serialization() { + let expected_request = serde_json::json!({ + "externalDatabaseRefID": "my_test_id", + "groupName": "" + }); + + let actual_request = serde_json::to_value(&DBEnrollRequest { + external_database_ref_id: "my_test_id", + group_name: "", + }) + .unwrap(); + + assert_eq!(expected_request, actual_request); + } + + #[test] + fn response_deserialization() { + let sample_response = serde_json::json!({ + "additionalSessionData": { + "isAdditionalDataPartiallyIncomplete": true + }, + "callData": { + "tid": "4uJgQnnkRAW-d737c7a4-ff7e-11ea-8db5-0232fd4aba88", + "path": "/3d-db/enroll", + "date": "Sep 25, 2020 22:31:22 PM", + "epochSecond": 1601073082, + "requestMethod": "POST" + }, + "error": false, + "externalDatabaseRefID": "test_external_dbref_id", + "serverInfo": { + "version": "9.0.0", + "mode": "Development Only", + "notice": "You should only be reading this if you are in server-side code. Please make sure you do not allow the FaceTec Server to be called from the public internet." + }, + "success": true + }); + + let response: DBEnrollResponse = serde_json::from_value(sample_response).unwrap(); + assert_matches!( + response, + DBEnrollResponse { + external_database_ref_id, + error: false, + success: true, + .. + } if external_database_ref_id == "test_external_dbref_id" + ) + } + #[test] + fn bad_request_error_response_deserialization() { + let sample_response = serde_json::json!({ + "error": true, + "errorMessage": "No entry found in the database.", + "success": false + }); + + let response: DBEnrollErrorBadRequest = serde_json::from_value(sample_response).unwrap(); + assert_eq!( + response, + DBEnrollErrorBadRequest { + error: true, + success: false, + error_message: "No entry found in the database.".to_owned(), + } + ) + } + + #[tokio::test] + async fn mock_success() { + let mock_server = MockServer::start().await; + + let sample_request = DBEnrollRequest { + external_database_ref_id: "my_test_id", + group_name: "", + }; + let sample_response = serde_json::json!({ + "additionalSessionData": { + "isAdditionalDataPartiallyIncomplete": true + }, + "callData": { + "tid": "4uJgQnnkRAW-d737c7a4-ff7e-11ea-8db5-0232fd4aba88", + "path": "/3d-db/enroll", + "date": "Sep 25, 2020 22:31:22 PM", + "epochSecond": 1601073082, + "requestMethod": "POST" + }, + "error": false, + "externalDatabaseRefID": "test_external_dbref_id", + "serverInfo": { + "version": "9.0.0", + "mode": "Development Only", + "notice": "You should only be reading this if you are in server-side code. Please make sure you do not allow the FaceTec Server to be called from the public internet." + }, + "success": true + }); + + let expected_response: DBEnrollResponse = + serde_json::from_value(sample_response.clone()).unwrap(); + + Mock::given(matchers::method("POST")) + .and(matchers::path("/3d-db/enroll")) + .and(matchers::body_json(&sample_request)) + .respond_with(ResponseTemplate::new(200).set_body_json(&sample_response)) + .mount(&mock_server) + .await; + + let client = Client { + base_url: mock_server.uri(), + reqwest: reqwest::Client::new(), + }; + + let actual_response = client.db_enroll(sample_request).await.unwrap(); + assert_eq!(actual_response, expected_response); + } + + #[tokio::test] + async fn mock_error_unknown() { + let mock_server = MockServer::start().await; + + let sample_request = DBEnrollRequest { + external_database_ref_id: "my_test_id", + group_name: "", + }; + let sample_response = "Some error text"; + + Mock::given(matchers::method("POST")) + .and(matchers::path("/3d-db/enroll")) + .and(matchers::body_json(&sample_request)) + .respond_with(ResponseTemplate::new(500).set_body_string(sample_response)) + .mount(&mock_server) + .await; + + let client = Client { + base_url: mock_server.uri(), + reqwest: reqwest::Client::new(), + }; + + let actual_error = client.db_enroll(sample_request).await.unwrap_err(); + assert_matches!( + actual_error, + Error::Call(DBEnrollError::Unknown(error_text)) if error_text == sample_response + ); + } + + #[tokio::test] + async fn mock_error_bad_request() { + let mock_server = MockServer::start().await; + + let sample_request = DBEnrollRequest { + external_database_ref_id: "my_test_id", + group_name: "", + }; + let sample_response = serde_json::json!({ + "error": true, + "errorMessage": "No entry found in the database.", + "success": false + }); + + let expected_error: DBEnrollErrorBadRequest = + serde_json::from_value(sample_response.clone()).unwrap(); + + Mock::given(matchers::method("POST")) + .and(matchers::path("/3d-db/enroll")) + .and(matchers::body_json(&sample_request)) + .respond_with(ResponseTemplate::new(400).set_body_json(&sample_response)) + .mount(&mock_server) + .await; + + let client = Client { + base_url: mock_server.uri(), + reqwest: reqwest::Client::new(), + }; + + let actual_error = client.db_enroll(sample_request).await.unwrap_err(); + assert_matches!( + actual_error, + Error::Call(DBEnrollError::BadRequest(err)) if err == expected_error + ); + } +} diff --git a/facetec-api-client/src/db_search.rs b/facetec-api-client/src/db_search.rs new file mode 100644 index 000000000..b78d646c7 --- /dev/null +++ b/facetec-api-client/src/db_search.rs @@ -0,0 +1,311 @@ +//! POST `/3d-db/search` + +use reqwest::StatusCode; +use serde::{Deserialize, Serialize}; + +use crate::{CommonResponse, Error, MatchLevel}; + +use super::Client; + +impl Client { + /// Perform the `/3d-db/search` call to the server. + pub async fn db_search( + &self, + req: DBSearchRequest<'_>, + ) -> Result> { + let url = format!("{}/3d-db/search", self.base_url); + let res = self.reqwest.post(url).json(&req).send().await?; + match res.status() { + StatusCode::OK => Ok(res.json().await?), + StatusCode::BAD_REQUEST => { + Err(Error::Call(DBSearchError::BadRequest(res.json().await?))) + } + _ => Err(Error::Call(DBSearchError::Unknown(res.text().await?))), + } + } +} + +/// Input data for the `/3d-db/search` request. +#[derive(Debug, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct DBSearchRequest<'a> { + /// The ID of the pre-enrolled FaceMap to search with. + #[serde(rename = "externalDatabaseRefID")] + pub external_database_ref_id: &'a str, + /// The name of the group to search at. + pub group_name: &'a str, + /// The minimal matching level to accept into the search result. + pub min_match_level: MatchLevel, +} + +/// The response from `/3d-db/search`. +#[derive(Debug, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct DBSearchResponse { + /// Common response portion. + #[serde(flatten)] + pub common: CommonResponse, + /// The ID of the pre-enrolled FaceMap that was used for searching + /// as an input. + #[serde(rename = "externalDatabaseRefID")] + pub external_database_ref_id: String, + /// Whether the request had any errors during the execution. + pub error: bool, + /// Whether the request was successful. + pub success: bool, + /// The set of all the matched entries enrolled on the group. + pub results: Vec, +} + +/// A single entry that matched the search request. +#[derive(Debug, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct DBSearchResponseResult { + /// The external database ID associated with this entry. + pub identifier: String, + /// The level of matching this entry funfills to the input FaceMap. + pub match_level: MatchLevel, +} + +/// The `/3d-db/search`-specific error kind. +#[derive(Error, Debug, PartialEq)] +pub enum DBSearchError { + /// Bad request error occured. + #[error("bad request: {0}")] + BadRequest(DBSearchErrorBadRequest), + /// Some other error occured. + #[error("unknown error: {0}")] + Unknown(String), +} + +/// The error kind for the `/3d-db/search`-specific 400 response. +#[derive(Error, Debug, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +#[error("bad request: {error_message}")] +pub struct DBSearchErrorBadRequest { + /// Whether the request had any errors during the execution. + /// Expected to always be `true` in this context. + pub error: bool, + /// Whether the request was successful. + /// Expected to always be `false` in this context. + pub success: bool, + /// The error message. + pub error_message: String, +} + +#[cfg(test)] +mod tests { + use wiremock::{matchers, Mock, MockServer, ResponseTemplate}; + + use super::*; + + #[test] + fn request_serialization() { + let expected_request = serde_json::json!({ + "externalDatabaseRefID": "my_test_id", + "groupName": "", + "minMatchLevel": 10, + }); + + let actual_request = serde_json::to_value(&DBSearchRequest { + external_database_ref_id: "my_test_id", + group_name: "", + min_match_level: 10, + }) + .unwrap(); + + assert_eq!(expected_request, actual_request); + } + + #[test] + fn response_deserialization() { + let sample_response = serde_json::json!({ + "results": [ + { + "identifier": "test_external_dbref_id_1", + "matchLevel": 10 + } + ], + "externalDatabaseRefID": "test_external_dbref_id", + "success": true, + "serverInfo": { + "version": "9.0.0", + "mode": "Development Only", + "notice": "You should only be reading this if you are in server-side code. Please make sure you do not allow the FaceTec Server to be called from the public internet." + }, + "error": false, + "additionalSessionData": { + "isAdditionalDataPartiallyIncomplete": true + }, + "callData": { + "tid": "IbERPISdrAW-edea765f-ff7e-11ea-8db5-0232fd4aba88", + "path": "/3d-db/search", + "date": "Sep 25, 2020 22:32:01 PM", + "epochSecond": 1601073121, + "requestMethod": "POST" + } + }); + + let response: DBSearchResponse = serde_json::from_value(sample_response).unwrap(); + assert_matches!( + response, + DBSearchResponse { + ref external_database_ref_id, + error: false, + success: true, + results, + .. + } if external_database_ref_id == "test_external_dbref_id" && + results.len() == 1 && + matches!( + &results[0], + &DBSearchResponseResult{ + ref identifier, + match_level: 10, + .. + } if identifier == "test_external_dbref_id_1" + ) + ) + } + + #[test] + fn bad_request_error_response_deserialization() { + let sample_response = serde_json::json!({ + "error": true, + "errorMessage": "No entry found in the database.", + "success": false + }); + + let response: DBSearchErrorBadRequest = serde_json::from_value(sample_response).unwrap(); + assert_eq!( + response, + DBSearchErrorBadRequest { + error: true, + success: false, + error_message: "No entry found in the database.".to_owned(), + } + ) + } + + #[tokio::test] + async fn mock_success() { + let mock_server = MockServer::start().await; + + let sample_request = DBSearchRequest { + external_database_ref_id: "my_test_id", + group_name: "", + min_match_level: 10, + }; + let sample_response = serde_json::json!({ + "results": [ + { + "identifier": "test_external_dbref_id_1", + "matchLevel": 10 + } + ], + "externalDatabaseRefID": "test_external_dbref_id", + "success": true, + "serverInfo": { + "version": "9.0.0", + "mode": "Development Only", + "notice": "You should only be reading this if you are in server-side code. Please make sure you do not allow the FaceTec Server to be called from the public internet." + }, + "error": false, + "additionalSessionData": { + "isAdditionalDataPartiallyIncomplete": true + }, + "callData": { + "tid": "IbERPISdrAW-edea765f-ff7e-11ea-8db5-0232fd4aba88", + "path": "/3d-db/search", + "date": "Sep 25, 2020 22:32:01 PM", + "epochSecond": 1601073121, + "requestMethod": "POST" + } + }); + + let expected_response: DBSearchResponse = + serde_json::from_value(sample_response.clone()).unwrap(); + + Mock::given(matchers::method("POST")) + .and(matchers::path("/3d-db/search")) + .and(matchers::body_json(&sample_request)) + .respond_with(ResponseTemplate::new(200).set_body_json(&sample_response)) + .mount(&mock_server) + .await; + + let client = Client { + base_url: mock_server.uri(), + reqwest: reqwest::Client::new(), + }; + + let actual_response = client.db_search(sample_request).await.unwrap(); + assert_eq!(actual_response, expected_response); + } + + #[tokio::test] + async fn mock_error_unknown() { + let mock_server = MockServer::start().await; + + let sample_request = DBSearchRequest { + external_database_ref_id: "my_test_id", + group_name: "", + min_match_level: 10, + }; + let sample_response = "Some error text"; + + Mock::given(matchers::method("POST")) + .and(matchers::path("/3d-db/search")) + .and(matchers::body_json(&sample_request)) + .respond_with(ResponseTemplate::new(500).set_body_string(sample_response)) + .mount(&mock_server) + .await; + + let client = Client { + base_url: mock_server.uri(), + reqwest: reqwest::Client::new(), + }; + + let actual_error = client.db_search(sample_request).await.unwrap_err(); + assert_matches!( + actual_error, + Error::Call(DBSearchError::Unknown(error_text)) if error_text == sample_response + ); + } + + #[tokio::test] + async fn mock_error_bad_request() { + let mock_server = MockServer::start().await; + + let sample_request = DBSearchRequest { + external_database_ref_id: "my_test_id", + group_name: "", + min_match_level: 10, + }; + let sample_response = serde_json::json!({ + "error": true, + "errorMessage": "No entry found in the database.", + "success": false + }); + + let expected_error: DBSearchErrorBadRequest = + serde_json::from_value(sample_response.clone()).unwrap(); + + Mock::given(matchers::method("POST")) + .and(matchers::path("/3d-db/search")) + .and(matchers::body_json(&sample_request)) + .respond_with(ResponseTemplate::new(400).set_body_json(&sample_response)) + .mount(&mock_server) + .await; + + let client = Client { + base_url: mock_server.uri(), + reqwest: reqwest::Client::new(), + }; + + let actual_error = client.db_search(sample_request).await.unwrap_err(); + assert_matches!( + actual_error, + Error::Call(DBSearchError::BadRequest(err)) if err == expected_error + ); + } +} diff --git a/facetec-api-client/src/enrollment3d.rs b/facetec-api-client/src/enrollment3d.rs new file mode 100644 index 000000000..5e854735b --- /dev/null +++ b/facetec-api-client/src/enrollment3d.rs @@ -0,0 +1,357 @@ +//! POST `/enrollment-3d` + +use reqwest::StatusCode; +use serde::{Deserialize, Serialize}; + +use crate::{CommonResponse, Error, FaceScanResponse, OpaqueBase64DataRef, ServerInfo}; + +use super::Client; + +impl Client { + /// Perform the `/enrollment-3d` call to the server. + pub async fn enrollment_3d( + &self, + req: Enrollment3DRequest<'_>, + ) -> Result> { + let url = format!("{}/enrollment-3d", self.base_url); + let res = self.reqwest.post(url).json(&req).send().await?; + match res.status() { + StatusCode::OK => Ok(res.json().await?), + StatusCode::BAD_REQUEST => Err(Error::Call(Enrollment3DError::BadRequest( + res.json().await?, + ))), + _ => Err(Error::Call(Enrollment3DError::Unknown(res.text().await?))), + } + } +} + +/// Input data for the `/enrollment-3d` request. +#[derive(Debug, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Enrollment3DRequest<'a> { + /// The ID that the FaceTec Server will associate the data with. + #[serde(rename = "externalDatabaseRefID")] + pub external_database_ref_id: &'a str, + /// The FaceTec 3D FaceScan to enroll into the server. + pub face_scan: OpaqueBase64DataRef<'a>, + /// The audit trail for liveness check. + pub audit_trail_image: OpaqueBase64DataRef<'a>, + /// The low quality audit trail for liveness check. + pub low_quality_audit_trail_image: OpaqueBase64DataRef<'a>, +} + +/// The response from `/enrollment-3d`. +#[derive(Debug, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Enrollment3DResponse { + /// Common response portion. + #[serde(flatten)] + pub common: CommonResponse, + /// FaceScan response portion. + #[serde(flatten)] + pub face_scan: FaceScanResponse, + /// The external database ID that was associated with this item. + #[serde(rename = "externalDatabaseRefID")] + pub external_database_ref_id: String, + /// Whether the request had any errors during the execution. + pub error: bool, + /// Whether the request was successful. + pub success: bool, +} + +/// The `/enrollment-3d`-specific error kind. +#[derive(Error, Debug, PartialEq)] +pub enum Enrollment3DError { + /// Bad request error occured. + #[error("bad request: {0}")] + BadRequest(Enrollment3DErrorBadRequest), + /// Some other error occured. + #[error("unknown error: {0}")] + Unknown(String), +} + +/// The error kind for the `/enrollment-3d`-specific 400 response. +#[derive(Error, Debug, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +#[error("bad request: {error_message}")] +pub struct Enrollment3DErrorBadRequest { + /// The information about the server. + pub server_info: ServerInfo, + /// Whether the request had any errors during the execution. + /// Expected to always be `true` in this context. + pub error: bool, + /// Whether the request was successful. + /// Expected to always be `false` in this context. + pub success: bool, + /// The error message. + pub error_message: String, +} + +#[cfg(test)] +mod tests { + use wiremock::{ + matchers::{self}, + Mock, MockServer, ResponseTemplate, + }; + + use crate::{AdditionalSessionData, CallData, ServerInfo}; + + use super::*; + + #[test] + fn request_serialization() { + let expected_request = serde_json::json!({ + "externalDatabaseRefID": "my_test_id", + "faceScan": "123", + "auditTrailImage": "456", + "lowQualityAuditTrailImage": "789" + }); + + let actual_request = serde_json::to_value(&Enrollment3DRequest { + external_database_ref_id: "my_test_id", + face_scan: "123", + audit_trail_image: "456", + low_quality_audit_trail_image: "789", + }) + .unwrap(); + + assert_eq!(expected_request, actual_request); + } + + #[test] + fn response_deserialization() { + let sample_response = serde_json::json!({ + "additionalSessionData": { + "isAdditionalDataPartiallyIncomplete": false, + "platform": "android", + "appID": "com.facetec.sampleapp", + "installationID": "0000000000000000", + "deviceModel": "Pixel 4", + "deviceSDKVersion": "9.0.2", + "sessionID": "00000000-0000-0000-0000-000000000000", + "userAgent": "UserAgent", + "ipAddress": "1.2.3.4" + }, + "ageEstimateGroupEnumInt": -1, + "callData": { + "tid": "AAAAAAAAAAA-00000000-0000-0000-0000-000000000000", + "path": "/enrollment-3d", + "date": "Jan 01, 2000 00:00:00 AM", + "epochSecond": 946684800, + "requestMethod": "POST" + }, + "error": false, + "externalDatabaseRefID": "test_external_dbref_id", + "faceScanSecurityChecks": { + "auditTrailVerificationCheckSucceeded": true, + "faceScanLivenessCheckSucceeded": false, + "replayCheckSucceeded": true, + "sessionTokenCheckSucceeded": true + }, + "faceTecRetryScreen": 0, + "retryScreenEnumInt": 0, + "serverInfo": { + "version": "9.0.5", + "mode": "Development Only", + "notice": "Notice" + }, + "success": false + }); + + let response: Enrollment3DResponse = serde_json::from_value(sample_response).unwrap(); + assert_matches!( + response, + Enrollment3DResponse { + external_database_ref_id, + error: false, + success: false, + face_scan: FaceScanResponse { + age_estimate_group_enum_int: -1, + .. + }, + common: CommonResponse { + additional_session_data: AdditionalSessionData { + is_additional_data_partially_incomplete: false, + .. + }, + call_data: CallData { + .. + }, + .. + }, + .. + } if external_database_ref_id == "test_external_dbref_id" + ) + } + + #[test] + fn bad_request_error_response_deserialization() { + let sample_response = serde_json::json!({ + "error": true, + "errorMessage": "An enrollment already exists for this externalDatabaseRefID.", + "success": false, + "serverInfo": { + "version": "9.0.0-SNAPSHOT", + "mode": "Development Only", + "notice": "You should only be reading this if you are in server-side code. Please make sure you do not allow the FaceTec Server to be called from the public internet." + } + }); + + let response: Enrollment3DErrorBadRequest = + serde_json::from_value(sample_response).unwrap(); + assert_eq!( + response, + Enrollment3DErrorBadRequest { + error: true, + success: false, + server_info: ServerInfo { + version: "9.0.0-SNAPSHOT".to_owned(), + mode: "Development Only".to_owned(), + notice: "You should only be reading this if you are in server-side code. Please make sure you do not allow the FaceTec Server to be called from the public internet.".to_owned(), + }, + error_message: "An enrollment already exists for this externalDatabaseRefID.".to_owned(), + } + ) + } + + #[tokio::test] + async fn mock_success() { + let mock_server = MockServer::start().await; + + let sample_request = Enrollment3DRequest { + external_database_ref_id: "my_test_id", + face_scan: "123", + audit_trail_image: "456", + low_quality_audit_trail_image: "789", + }; + let sample_response = serde_json::json!({ + "additionalSessionData": { + "isAdditionalDataPartiallyIncomplete": false, + "platform": "android", + "appID": "com.facetec.sampleapp", + "installationID": "0000000000000000", + "deviceModel": "Pixel 4", + "deviceSDKVersion": "9.0.2", + "sessionID": "00000000-0000-0000-0000-000000000000", + "userAgent": "UserAgent", + "ipAddress": "1.2.3.4" + }, + "ageEstimateGroupEnumInt": -1, + "callData": { + "tid": "AAAAAAAAAAA-00000000-0000-0000-0000-000000000000", + "path": "/enrollment-3d", + "date": "Jan 01, 2000 00:00:00 AM", + "epochSecond": 946684800, + "requestMethod": "POST" + }, + "error": false, + "externalDatabaseRefID": "test_external_dbref_id", + "faceScanSecurityChecks": { + "auditTrailVerificationCheckSucceeded": true, + "faceScanLivenessCheckSucceeded": false, + "replayCheckSucceeded": true, + "sessionTokenCheckSucceeded": true + }, + "faceTecRetryScreen": 0, + "retryScreenEnumInt": 0, + "serverInfo": { + "version": "9.0.5", + "mode": "Development Only", + "notice": "Notice" + }, + "success": false + }); + + let expected_response: Enrollment3DResponse = + serde_json::from_value(sample_response.clone()).unwrap(); + + Mock::given(matchers::method("POST")) + .and(matchers::path("/enrollment-3d")) + .and(matchers::body_json(&sample_request)) + .respond_with(ResponseTemplate::new(200).set_body_json(&sample_response)) + .mount(&mock_server) + .await; + + let client = Client { + base_url: mock_server.uri(), + reqwest: reqwest::Client::new(), + }; + + let actual_response = client.enrollment_3d(sample_request).await.unwrap(); + assert_eq!(actual_response, expected_response); + } + + #[tokio::test] + async fn mock_error_unknown() { + let mock_server = MockServer::start().await; + + let sample_request = Enrollment3DRequest { + external_database_ref_id: "my_test_id", + face_scan: "123", + audit_trail_image: "456", + low_quality_audit_trail_image: "789", + }; + let sample_response = "Some error text"; + + Mock::given(matchers::method("POST")) + .and(matchers::path("/enrollment-3d")) + .and(matchers::body_json(&sample_request)) + .respond_with(ResponseTemplate::new(500).set_body_string(sample_response)) + .mount(&mock_server) + .await; + + let client = Client { + base_url: mock_server.uri(), + reqwest: reqwest::Client::new(), + }; + + let actual_error = client.enrollment_3d(sample_request).await.unwrap_err(); + assert_matches!( + actual_error, + Error::Call(Enrollment3DError::Unknown(error_text)) if error_text == sample_response + ); + } + + #[tokio::test] + async fn mock_error_bad_request() { + let mock_server = MockServer::start().await; + + let sample_request = Enrollment3DRequest { + external_database_ref_id: "my_test_id", + face_scan: "123", + audit_trail_image: "456", + low_quality_audit_trail_image: "789", + }; + let sample_response = serde_json::json!({ + "error": true, + "errorMessage": "An enrollment already exists for this externalDatabaseRefID.", + "success": false, + "serverInfo": { + "version": "9.0.0-SNAPSHOT", + "mode": "Development Only", + "notice": "You should only be reading this if you are in server-side code. Please make sure you do not allow the FaceTec Server to be called from the public internet." + } + }); + + let expected_error: Enrollment3DErrorBadRequest = + serde_json::from_value(sample_response.clone()).unwrap(); + + Mock::given(matchers::method("POST")) + .and(matchers::path("/enrollment-3d")) + .and(matchers::body_json(&sample_request)) + .respond_with(ResponseTemplate::new(400).set_body_json(&sample_response)) + .mount(&mock_server) + .await; + + let client = Client { + base_url: mock_server.uri(), + reqwest: reqwest::Client::new(), + }; + + let actual_error = client.enrollment_3d(sample_request).await.unwrap_err(); + assert_matches!( + actual_error, + Error::Call(Enrollment3DError::BadRequest(err)) if err == expected_error + ); + } +} diff --git a/facetec-api-client/src/lib.rs b/facetec-api-client/src/lib.rs new file mode 100644 index 000000000..122160c87 --- /dev/null +++ b/facetec-api-client/src/lib.rs @@ -0,0 +1,39 @@ +//! Client API for the FaceTec Server SDK. + +#![warn(missing_docs, clippy::missing_docs_in_private_items)] + +#[cfg(test)] +#[macro_use] +extern crate assert_matches; + +use thiserror::Error; + +mod db_enroll; +mod db_search; +mod enrollment3d; +mod types; + +pub use db_enroll::*; +pub use db_search::*; +pub use enrollment3d::*; +pub use types::*; + +/// The generic error type for the client calls. +#[derive(Error, Debug)] +pub enum Error { + /// A call-specific error. + #[error("server error: {0}")] + Call(T), + /// An error coming from the underlying reqwest layer. + #[error("reqwest error: {0}")] + Reqwest(#[from] reqwest::Error), +} + +/// The robonode client. +#[derive(Debug)] +pub struct Client { + /// Underyling HTTP client used to execute network calls. + pub reqwest: reqwest::Client, + /// The base URL to use for the routes. + pub base_url: String, +} diff --git a/facetec-api-client/src/types.rs b/facetec-api-client/src/types.rs new file mode 100644 index 000000000..448e2b549 --- /dev/null +++ b/facetec-api-client/src/types.rs @@ -0,0 +1,110 @@ +//! Common types. + +use serde::Deserialize; + +/// A type that represents an opaque Base64 data. +/// +/// Opaque in a sense that our code does not try to validate or decode it. +/// We could decode the opaque Base64 representation, and then reencode it, +/// but since we're just passing this value through - we can leave it as is, +/// and we don't really have to do anything with it. +pub type OpaqueBase64DataRef<'a> = &'a str; + +/// The type to be used everywhere as the match level. +pub type MatchLevel = i64; + +/// The additional data about the session that FaceTec communicates back to us +/// with each response. +#[derive(Debug, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct AdditionalSessionData { + /// TODO: document. + pub is_additional_data_partially_incomplete: bool, + // "platform": "android", + // "appID": "com.facetec.sampleapp", + // "installationID": "0000000000000000", + // "deviceModel": "Pixel 4", + // "deviceSDKVersion": "9.0.2", + // "sessionID": "00000000-0000-0000-0000-000000000000", + // "userAgent": "UserAgent", + // "ipAddress": "1.2.3.4" +} + +/// The report on the security checks. +#[derive(Debug, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct FaceScanSecurityChecks { + /// TODO: document + audit_trail_verification_check_succeeded: bool, + /// TODO: document + face_scan_liveness_check_succeeded: bool, + /// TODO: document + replay_check_succeeded: bool, + /// TODO: document + session_token_check_succeeded: bool, +} + +impl FaceScanSecurityChecks { + /// Returns `true` only if all of the underlying checks are `true`. + pub fn all_checks_succeeded(&self) -> bool { + self.audit_trail_verification_check_succeeded + && self.face_scan_liveness_check_succeeded + && self.replay_check_succeeded + && self.session_token_check_succeeded + } +} + +/// The call data that FaceTec includes with each response. +#[derive(Debug, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct CallData { + /// Some opaque transaction identifier. + tid: String, + /// Request URI path. + path: String, + /// Request date, as a string in the US locale, without timezone or offset. + date: String, + /// The unix-time representation of the request date. + epoch_second: i64, + /// The HTTP method the request was issued with. + request_method: String, +} + +/// The server info that FaceTec sends us with each response. +#[derive(Debug, Deserialize, PartialEq, Eq)] +pub struct ServerInfo { + /// Version of the server. + pub version: String, + /// Mode of the operation of the server. + pub mode: String, + /// A notice that server gives with this response. + pub notice: String, +} + +/// A common FaceTec API response portion. +#[derive(Debug, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct CommonResponse { + /// The additional session information included in this response. + pub additional_session_data: AdditionalSessionData, + /// The information about the API call the request was to. + pub call_data: CallData, + /// The information about the server. + pub server_info: ServerInfo, +} + +/// A FaceScan-related FaceTec API response portion. +#[derive(Debug, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct FaceScanResponse { + /// The the information about the security checks over the FaceScan data. + pub face_scan_security_checks: FaceScanSecurityChecks, + /// Something to do with the retry screen of the FaceTec Device SDK. + /// TODO: find more info on this parameter. + pub face_tec_retry_screen: i64, + /// Something to do with the retry screen of the FaceTec Device SDK. + /// TODO: find more info on this parameter. + pub retry_screen_enum_int: i64, + /// The age group enum id that the input FaceScan was classified to. + pub age_estimate_group_enum_int: i64, +} diff --git a/robonode-client/Cargo.toml b/robonode-client/Cargo.toml index b060d910b..e06649f5a 100644 --- a/robonode-client/Cargo.toml +++ b/robonode-client/Cargo.toml @@ -9,3 +9,9 @@ publish = false reqwest = { version = "0.11", features = ["json"] } serde = { version = "1", features = ["derive"] } thiserror = "1" + +[dev-dependencies] +assert_matches = "1.5" +serde_json = "1" +tokio = { version = "1", features = ["full"] } +wiremock = "0.5" diff --git a/robonode-client/src/authenticate.rs b/robonode-client/src/authenticate.rs new file mode 100644 index 000000000..6f64fe374 --- /dev/null +++ b/robonode-client/src/authenticate.rs @@ -0,0 +1,181 @@ +//! Client API for the Humanode's Bioauth Robonode. + +use reqwest::StatusCode; +use serde::{Deserialize, Serialize}; + +use crate::{Client, Error}; + +impl Client { + /// Perform the authenticate call to the server. + pub async fn authenticate( + &self, + req: AuthenticateRequest<'_>, + ) -> Result> { + let url = format!("{}/authenticate", self.base_url); + let res = self.reqwest.post(url).json(&req).send().await?; + match res.status() { + StatusCode::OK => Ok(res.json().await?), + StatusCode::NOT_FOUND => Err(Error::Call(AuthenticateError::MatchNotFound)), + _ => Err(Error::Call(AuthenticateError::Unknown(res.text().await?))), + } + } +} + +/// Input data for the authenticate request. +#[derive(Debug, Serialize)] +pub struct AuthenticateRequest<'a> { + /// The FaceTec 3D FaceScan to associate with the identity. + face_scan: &'a [u8], + /// The signature of the FaceTec 3D FaceScan, proving the posession of the + /// private key by the issuer of this request. + face_scan_signature: &'a [u8], +} + +/// Input data for the authenticate request. +#[derive(Debug, Deserialize, PartialEq)] +pub struct AuthenticateResponse { + /// The public key that matched with the provided FaceTec 3D FaceScan. + public_key: Box<[u8]>, + /// The robonode signatire for this public key. + // TODO: we need a nonce to prevent replay attack, don't we? + public_key_signature: Box<[u8]>, +} + +/// The authenticate-specific error condition. +#[derive(Error, Debug, PartialEq)] +pub enum AuthenticateError { + /// The match was not found, user likely needs to register first, or retry + /// with another face scan. + #[error("match not found")] + MatchNotFound, + /// Some other error occured. + #[error("unknown error: {0}")] + Unknown(String), +} + +#[cfg(test)] +mod tests { + use assert_matches::assert_matches; + use wiremock::{matchers, Mock, MockServer, ResponseTemplate}; + + use super::*; + + #[test] + fn request_serialization() { + let expected_request = serde_json::json!({ + "face_scan": [1, 2, 3], + "face_scan_signature": [4, 5, 6], + }); + + let actual_request = serde_json::to_value(&AuthenticateRequest { + face_scan: &[1, 2, 3], + face_scan_signature: &[4, 5, 6], + }) + .unwrap(); + + assert_eq!(expected_request, actual_request); + } + + #[test] + fn response_deserialization() { + let sample_response = serde_json::json!({ + "public_key": [1, 2, 3], + "public_key_signature": [4, 5, 6], + }); + + let response: AuthenticateResponse = serde_json::from_value(sample_response).unwrap(); + assert_eq!( + response, + AuthenticateResponse { + public_key: vec![1, 2, 3].into(), + public_key_signature: vec![4, 5, 6].into(), + } + ) + } + + #[tokio::test] + async fn mock_success() { + let mock_server = MockServer::start().await; + + let sample_request = AuthenticateRequest { + face_scan: b"dummy face scan", + face_scan_signature: b"123", + }; + let sample_response = serde_json::json!({ + "public_key": b"456", + "public_key_signature": b"789", + }); + + let expected_response: AuthenticateResponse = + serde_json::from_value(sample_response.clone()).unwrap(); + + Mock::given(matchers::method("POST")) + .and(matchers::path("/authenticate")) + .and(matchers::body_json(&sample_request)) + .respond_with(ResponseTemplate::new(200).set_body_json(&sample_response)) + .mount(&mock_server) + .await; + + let client = Client { + base_url: mock_server.uri(), + reqwest: reqwest::Client::new(), + }; + + let actual_response = client.authenticate(sample_request).await.unwrap(); + assert_eq!(actual_response, expected_response); + } + + #[tokio::test] + async fn mock_error_match_not_found() { + let mock_server = MockServer::start().await; + + let sample_request = AuthenticateRequest { + face_scan: b"dummy face scan", + face_scan_signature: b"123", + }; + + Mock::given(matchers::method("POST")) + .and(matchers::path("/authenticate")) + .and(matchers::body_json(&sample_request)) + .respond_with(ResponseTemplate::new(404)) + .mount(&mock_server) + .await; + + let client = Client { + base_url: mock_server.uri(), + reqwest: reqwest::Client::new(), + }; + + let actual_error = client.authenticate(sample_request).await.unwrap_err(); + assert_matches!(actual_error, Error::Call(AuthenticateError::MatchNotFound)); + } + + #[tokio::test] + async fn mock_error_unknown() { + let mock_server = MockServer::start().await; + + let sample_request = AuthenticateRequest { + face_scan: b"dummy face scan", + face_scan_signature: b"123", + }; + let sample_response = "Some error text"; + + Mock::given(matchers::method("POST")) + .and(matchers::path("/authenticate")) + .and(matchers::body_json(&sample_request)) + .respond_with(ResponseTemplate::new(500).set_body_string(sample_response)) + .mount(&mock_server) + .await; + + let client = Client { + base_url: mock_server.uri(), + reqwest: reqwest::Client::new(), + }; + + let actual_error = client.authenticate(sample_request).await.unwrap_err(); + assert_matches!( + actual_error, + Error::Call(AuthenticateError::Unknown(error_text)) if error_text == sample_response + ); + } +} diff --git a/robonode-client/src/enroll.rs b/robonode-client/src/enroll.rs new file mode 100644 index 000000000..853a484f2 --- /dev/null +++ b/robonode-client/src/enroll.rs @@ -0,0 +1,141 @@ +//! Client API for the Humanode's Bioauth Robonode. + +use reqwest::StatusCode; +use serde::Serialize; + +use crate::{Client, Error}; + +impl Client { + /// Perform the enroll call to the server. + pub async fn enroll(&self, req: EnrollRequest<'_>) -> Result<(), Error> { + let url = format!("{}/enroll", self.base_url); + let res = self.reqwest.post(url).json(&req).send().await?; + match res.status() { + StatusCode::CREATED => Ok(()), + StatusCode::CONFLICT => Err(Error::Call(EnrollError::AlreadyEnrolled)), + _ => Err(Error::Call(EnrollError::Unknown(res.text().await?))), + } + } +} + +/// Input data for the enroll request. +#[derive(Debug, Serialize)] +pub struct EnrollRequest<'a> { + /// The public key to be used as an identity. + public_key: &'a [u8], + /// The FaceTec 3D FaceScan to associate with the identity. + face_scan: &'a [u8], +} + +/// The enroll-specific error condition. +#[derive(Error, Debug, PartialEq)] +pub enum EnrollError { + /// The face scan or public key were already enrolled. + #[error("already enrolled")] + AlreadyEnrolled, + /// Some other error occured. + #[error("unknown error: {0}")] + Unknown(String), +} + +#[cfg(test)] +mod tests { + use assert_matches::assert_matches; + use wiremock::{matchers, Mock, MockServer, ResponseTemplate}; + + use super::*; + + #[test] + fn request_serialization() { + let expected_request = serde_json::json!({ + "face_scan": [1, 2, 3], + "public_key": [4, 5, 6], + }); + + let actual_request = serde_json::to_value(&EnrollRequest { + face_scan: &[1, 2, 3], + public_key: &[4, 5, 6], + }) + .unwrap(); + + assert_eq!(expected_request, actual_request); + } + + #[tokio::test] + async fn mock_success() { + let mock_server = MockServer::start().await; + + let sample_request = EnrollRequest { + face_scan: b"dummy face scan", + public_key: b"123", + }; + + Mock::given(matchers::method("POST")) + .and(matchers::path("/enroll")) + .and(matchers::body_json(&sample_request)) + .respond_with(ResponseTemplate::new(201)) + .mount(&mock_server) + .await; + + let client = Client { + base_url: mock_server.uri(), + reqwest: reqwest::Client::new(), + }; + + client.enroll(sample_request).await.unwrap(); + } + + #[tokio::test] + async fn mock_error_conflict() { + let mock_server = MockServer::start().await; + + let sample_request = EnrollRequest { + face_scan: b"dummy face scan", + public_key: b"123", + }; + + Mock::given(matchers::method("POST")) + .and(matchers::path("/enroll")) + .and(matchers::body_json(&sample_request)) + .respond_with(ResponseTemplate::new(409)) + .mount(&mock_server) + .await; + + let client = Client { + base_url: mock_server.uri(), + reqwest: reqwest::Client::new(), + }; + + let actual_error = client.enroll(sample_request).await.unwrap_err(); + assert_matches!(actual_error, Error::Call(EnrollError::AlreadyEnrolled)); + } + + #[tokio::test] + async fn mock_error_unknown() { + let mock_server = MockServer::start().await; + + let sample_request = EnrollRequest { + face_scan: b"dummy face scan", + public_key: b"123", + }; + let sample_response = "Some error text"; + + Mock::given(matchers::method("POST")) + .and(matchers::path("/enroll")) + .and(matchers::body_json(&sample_request)) + .respond_with(ResponseTemplate::new(500).set_body_string(sample_response)) + .mount(&mock_server) + .await; + + let client = Client { + base_url: mock_server.uri(), + reqwest: reqwest::Client::new(), + }; + + let actual_error = client.enroll(sample_request).await.unwrap_err(); + assert_matches!( + actual_error, + Error::Call(EnrollError::Unknown(error_text)) if error_text == sample_response + ); + } +} diff --git a/robonode-client/src/lib.rs b/robonode-client/src/lib.rs index d505c165d..c060bd71e 100644 --- a/robonode-client/src/lib.rs +++ b/robonode-client/src/lib.rs @@ -2,10 +2,14 @@ #![deny(missing_docs, clippy::missing_docs_in_private_items)] -use reqwest::StatusCode; -use serde::Serialize; use thiserror::Error; +mod authenticate; +mod enroll; + +pub use authenticate::*; +pub use enroll::*; + /// The generic error type for the client calls. #[derive(Error, Debug)] pub enum Error { @@ -25,82 +29,3 @@ pub struct Client { /// The base URL to use for the routes. pub base_url: String, } - -impl Client { - /// Perform the enroll call to the server. - pub async fn enroll(&self, req: EnrollRequest<'_>) -> Result<(), Error> { - let url = format!("{}/enroll", self.base_url); - let res = self.reqwest.post(url).json(&req).send().await?; - match res.status() { - StatusCode::CREATED => Ok(()), - StatusCode::CONFLICT => Err(Error::Call(EnrollError::AlreadyEnrolled)), - _ => Err(Error::Call(EnrollError::Unknown(res.text().await?))), - } - } - - /// Perform the authenticate call to the server. - pub async fn authenticate( - &self, - req: AuthenticateRequest<'_>, - ) -> Result<(), Error> { - let url = format!("{}/authenticate", self.base_url); - let res = self.reqwest.post(url).json(&req).send().await?; - match res.status() { - StatusCode::OK => Ok(res.json().await?), - StatusCode::NOT_FOUND => Err(Error::Call(AuthenticateError::MatchNotFound)), - _ => Err(Error::Call(AuthenticateError::Unknown(res.text().await?))), - } - } -} - -/// Input data for the enroll request. -#[derive(Debug, Serialize)] -pub struct EnrollRequest<'a> { - /// The public key to be used as an identity. - public_key: &'a [u8], - /// The FaceTec 3D FaceScan to associate with the identity. - face_scan: &'a [u8], -} - -/// The enroll-specific error condition. -#[derive(Error, Debug)] -pub enum EnrollError { - /// The face scan or public key were already enrolled. - #[error("already enrolled")] - AlreadyEnrolled, - /// Some other error occured. - #[error("unknown error: {0}")] - Unknown(String), -} - -/// Input data for the authenticate request. -#[derive(Debug, Serialize)] -pub struct AuthenticateRequest<'a> { - /// The FaceTec 3D FaceScan to associate with the identity. - face_scan: &'a [u8], - /// The signature of the FaceTec 3D FaceScan, proving the posession of the - /// private key by the issuer of this request. - face_scan_signature: &'a [u8], -} - -/// Input data for the authenticate request. -#[derive(Debug, Serialize)] -pub struct AuthenticateResponse { - /// The public key that matched with the provided FaceTec 3D FaceScan. - public_key: Box<[u8]>, - /// The robonode signatire for this public key. - // TODO: we need a nonce to prevent replay attack, don't we? - public_key_signature: Box<[u8]>, -} - -/// The authenticate-specific error condition. -#[derive(Error, Debug)] -pub enum AuthenticateError { - /// The match was not found, user likely needs to register first, or retry - /// with another face scan. - #[error("match not found")] - MatchNotFound, - /// Some other error occured. - #[error("unknown error: {0}")] - Unknown(String), -} diff --git a/robonode-server/Cargo.toml b/robonode-server/Cargo.toml index 42eb4fcfb..df7d7f94f 100644 --- a/robonode-server/Cargo.toml +++ b/robonode-server/Cargo.toml @@ -6,5 +6,8 @@ authors = ["Humanode Team "] publish = false [dependencies] -hyper = { version = "0.14", features = ["full"] } +facetec-api-client = { version = "0.1", path = "../facetec-api-client" } +reqwest = "0.11" +serde = { version = "1", features = ["derive"] } tokio = { version = "1", features = ["full"] } +warp = "0.3" diff --git a/robonode-server/src/http.rs b/robonode-server/src/http.rs new file mode 100644 index 000000000..4b8610cd8 --- /dev/null +++ b/robonode-server/src/http.rs @@ -0,0 +1,6 @@ +//! The HTTP transport realted stuff. + +mod filters; +mod handlers; + +pub use filters::root; diff --git a/robonode-server/src/http/filters.rs b/robonode-server/src/http/filters.rs new file mode 100644 index 000000000..cdbab1e13 --- /dev/null +++ b/robonode-server/src/http/filters.rs @@ -0,0 +1,71 @@ +//! Filters, essentially how [`warp`] implements routes and middlewares. + +use std::{convert::TryFrom, sync::Arc}; + +use warp::Filter; + +use crate::{ + http::handlers, + logic::{AuthenticateRequest, EnrollRequest, Logic, Signer, Verifier}, +}; + +/// Pass the [`Arc`] to the handler. +fn with_arc( + val: Arc, +) -> impl Filter,), Error = std::convert::Infallible> + Clone +where + Arc: Send, +{ + warp::any().map(move || Arc::clone(&val)) +} + +/// Extract the JSON body from the request, rejecting the excessive inputs size. +fn json_body() -> impl Filter + Clone +where + T: Send + for<'de> serde::de::Deserialize<'de>, +{ + // When accepting a body, we want a JSON body + // (and to reject huge payloads)... + warp::body::content_length_limit(1024 * 16).and(warp::body::json::()) +} + +/// The root mount point with all the routes. +pub fn root( + logic: Arc>, +) -> impl Filter + Clone +where + S: Signer + Send + 'static, + PK: Send + for<'a> TryFrom<&'a str> + Verifier + AsRef<[u8]> + Into, +{ + enroll(Arc::clone(&logic)).or(authenticate(logic)) +} + +/// POST /enroll with JSON body. +fn enroll( + logic: Arc>, +) -> impl Filter + Clone +where + S: Signer + Send + 'static, + PK: Send + for<'a> TryFrom<&'a str>, +{ + warp::path!("enroll") + .and(warp::post()) + .and(with_arc(logic)) + .and(json_body::()) + .and_then(handlers::enroll) +} + +/// POST /authenticate with JSON body. +fn authenticate( + logic: Arc>, +) -> impl Filter + Clone +where + S: Signer + Send + 'static, + PK: Send + for<'a> TryFrom<&'a str> + Verifier + AsRef<[u8]> + Into, +{ + warp::path!("authenticate") + .and(warp::post()) + .and(with_arc(logic)) + .and(json_body::()) + .and_then(handlers::authenticate) +} diff --git a/robonode-server/src/http/handlers.rs b/robonode-server/src/http/handlers.rs new file mode 100644 index 000000000..25bc1e40a --- /dev/null +++ b/robonode-server/src/http/handlers.rs @@ -0,0 +1,43 @@ +//! Handlers, the HTTP transport coupling for the internal logic. + +use std::{ + convert::{Infallible, TryFrom}, + sync::Arc, +}; +use warp::Reply; + +use warp::hyper::StatusCode; + +use crate::logic::{AuthenticateRequest, EnrollRequest, Logic, Signer, Verifier}; + +/// Enroll operation HTTP transport coupling. +pub async fn enroll( + logic: Arc>, + input: EnrollRequest, +) -> Result +where + S: Signer + Send + 'static, + PK: Send + for<'a> TryFrom<&'a str>, +{ + match logic.enroll(input).await { + Ok(()) => Ok(StatusCode::CREATED), + Err(_) => Ok(StatusCode::INTERNAL_SERVER_ERROR), // TODO: fix the error handling + } +} + +/// Authenticate operation HTTP transport coupling. +pub async fn authenticate( + logic: Arc>, + input: AuthenticateRequest, +) -> Result +where + S: Signer + Send + 'static, + PK: Send + for<'a> TryFrom<&'a str> + Verifier + AsRef<[u8]> + Into, +{ + match logic.authenticate(input).await { + Ok(res) => { + Ok(warp::reply::with_status(warp::reply::json(&res), StatusCode::OK).into_response()) + } + Err(_) => Ok(StatusCode::INTERNAL_SERVER_ERROR.into_response()), // TODO: fix the error handling + } +} diff --git a/robonode-server/src/lib.rs b/robonode-server/src/lib.rs new file mode 100644 index 000000000..a38222cfb --- /dev/null +++ b/robonode-server/src/lib.rs @@ -0,0 +1,44 @@ +//! Humanode's Bioauth Robonode server internal API. + +#![deny(missing_docs, clippy::missing_docs_in_private_items)] + +use std::{marker::PhantomData, sync::Arc}; + +use http::root; +use tokio::sync::Mutex; +use warp::Filter; + +mod http; +mod logic; +mod sequence; + +/// Initialize the [`warp::Filter`] implementing the HTTP transport for +/// the robonode. +pub fn init() -> impl Filter + Clone { + let logic = logic::Logic { + locked: Mutex::new(logic::Locked { + sequence: sequence::Sequence::new(0), + facetec: facetec_api_client::Client { + base_url: "localhost:5113".to_owned(), + reqwest: reqwest::Client::new(), + }, + signer: (), + public_key_type: PhantomData::, + }), + }; + root(Arc::new(logic)) +} + +// TODO! +impl logic::Signer for () { + fn sign>(&self, _data: &D) -> Vec { + todo!() + } +} + +// TODO! +impl logic::Verifier for String { + fn verify, S: AsRef<[u8]>>(&self, _data: &D, _signature: &S) -> bool { + todo!() + } +} diff --git a/robonode-server/src/logic.rs b/robonode-server/src/logic.rs new file mode 100644 index 000000000..c508e7c1d --- /dev/null +++ b/robonode-server/src/logic.rs @@ -0,0 +1,316 @@ +//! Core logic of the system. + +use std::{convert::TryFrom, marker::PhantomData}; + +use facetec_api_client::{ + Client as FaceTecClient, DBEnrollError, DBEnrollRequest, DBSearchError, DBSearchRequest, + Enrollment3DError, Enrollment3DErrorBadRequest, Enrollment3DRequest, Error as FaceTecError, +}; +use tokio::sync::Mutex; + +use crate::sequence::Sequence; +use serde::{Deserialize, Serialize}; + +/// Signer provides signatures for the data. +pub trait Signer { + /// Sign the provided data and return the signature. + fn sign>(&self, data: &D) -> Vec; +} + +/// Verifier provides the verification of the data accompanied with the +/// signature or proof data. +pub trait Verifier { + /// Verify that provided data is indeed correctly signed with the provided + /// signature. + fn verify, S: AsRef<[u8]>>(&self, data: &D, signature: &S) -> bool; +} + +/// The inner state, to be hidden behind the mutex to ensure we don't have +/// access to it unless we lock the mutex. +pub struct Locked +where + S: Signer + 'static, + PK: Send + for<'a> TryFrom<&'a str>, +{ + /// The sequence number. + pub sequence: Sequence, + /// The client for the FaceTec Server API. + pub facetec: FaceTecClient, + /// The utility for signing the responses. + pub signer: S, + /// Public key type to use under the hood. + pub public_key_type: PhantomData, +} + +/// The overall generic logic. +pub struct Logic +where + S: Signer + Send + 'static, + PK: Send + for<'a> TryFrom<&'a str>, +{ + /// The mutex over the locked portions of the logic. + /// This way we're ensureing the operations can only be conducted under + /// the lock. + pub locked: Mutex>, +} + +/// The request for the enroll operation. +#[derive(Debug, Deserialize)] +pub struct EnrollRequest { + /// The public key of the validator. + public_key: String, + /// The face scan that validator owner provided. + face_scan: String, +} + +/// The errors on the enroll operation. +pub enum EnrollError { + /// The provided public key failed to load because it was invalid. + InvalidPublicKey, + /// This FaceScan was rejected. + FaceScanRejected, + /// This Public Key was already used. + PublicKeyAlreadyUsed, + /// This person has already enrolled into the system. + /// It can also happen if matching returns false-positive. + PersonAlreadyEnrolled, + /// Internal error at server-level enrollment due to the underlying request + /// error at the API level. + InternalErrorEnrollment(FaceTecError), + /// Internal error at server-level enrollment due to unsuccessful response, + /// but for some other reason but the FaceScan being rejected. + /// Rejected FaceScan is explicitly encoded via a different error condition. + InternalErrorEnrollmentUnsuccessful, + /// Internal error at 3D-DB search due to the underlying request + /// error at the API level. + InternalErrorDbSearch(FaceTecError), + /// Internal error at 3D-DB search due to unsuccessful response. + InternalErrorDbSearchUnsuccessful, + /// Internal error at 3D-DB enrollment due to the underlying request + /// error at the API level. + InternalErrorDbEnroll(FaceTecError), + /// Internal error at 3D-DB enrollment due to unsuccessful response. + InternalErrorDbEnrollUnsuccessful, +} + +/// This is the error message that FaceTec server returns when it +/// encounters an `externalDatabaseRefID` that is already in use. +/// For the lack of a better option, we have to compare the error messages, +/// which is not a good idea, and there should've been a better way. +const EXTERNAL_DATABASE_REF_ID_ALREADY_IN_USE_ERROR_MESSAGE: &str = + "An enrollment already exists for this externalDatabaseRefID."; + +/// The group name at 3D DB. +const DB_GROUP_NAME: &str = ""; +/// The match level to use throughout the code. +const MATCH_LEVEL: i64 = 10; + +impl Logic +where + S: Signer + Send + 'static, + PK: Send + for<'a> TryFrom<&'a str>, +{ + /// An enroll invocation handler. + pub async fn enroll(&self, req: EnrollRequest) -> Result<(), EnrollError> { + if PK::try_from(&req.public_key).is_err() { + return Err(EnrollError::InvalidPublicKey); + } + + let unlocked = self.locked.lock().await; + let enroll_res = unlocked + .facetec + .enrollment_3d(Enrollment3DRequest { + external_database_ref_id: &req.public_key, + face_scan: &req.face_scan, + audit_trail_image: "TODO", + low_quality_audit_trail_image: "TODO", + }) + .await + .map_err(|err| match err { + FaceTecError::Call(Enrollment3DError::BadRequest( + Enrollment3DErrorBadRequest { error_message, .. }, + )) if error_message == EXTERNAL_DATABASE_REF_ID_ALREADY_IN_USE_ERROR_MESSAGE => { + EnrollError::PublicKeyAlreadyUsed + } + err => EnrollError::InternalErrorEnrollment(err), + })?; + + if !enroll_res.success { + if !enroll_res + .face_scan + .face_scan_security_checks + .all_checks_succeeded() + { + return Err(EnrollError::FaceScanRejected); + } + return Err(EnrollError::InternalErrorEnrollmentUnsuccessful); + } + + let search_res = unlocked + .facetec + .db_search(DBSearchRequest { + external_database_ref_id: &req.public_key, + group_name: DB_GROUP_NAME, + min_match_level: MATCH_LEVEL, + }) + .await + .map_err(EnrollError::InternalErrorDbSearch)?; + + if !enroll_res.success { + return Err(EnrollError::InternalErrorDbSearchUnsuccessful); + } + + // If the results set is non-empty - this means that this person has + // already enrolled with the system. It might also be a false-positive. + if !search_res.results.is_empty() { + return Err(EnrollError::PersonAlreadyEnrolled); + } + + let enroll_res = unlocked + .facetec + .db_enroll(DBEnrollRequest { + external_database_ref_id: &req.public_key, + group_name: "", + }) + .await + .map_err(EnrollError::InternalErrorDbEnroll)?; + + if !enroll_res.success { + return Err(EnrollError::InternalErrorDbEnrollUnsuccessful); + } + + Ok(()) + } +} + +/// The request of the authenticate operation. +#[derive(Debug, Deserialize)] +pub struct AuthenticateRequest { + /// The FaceScan that node owner provided. + face_scan: String, + /// The signature of the FaceScan with the private key of the node. + /// Proves the posession of the private key by the FaceScan bearer. + face_scan_signature: Vec, +} + +/// The response of the authenticate operation. +#[derive(Debug, Serialize)] +pub struct AuthenticateResponse { + /// The public key that matched with the provided FaceScan. + public_key: String, + /// The signature of the public key, signed with the robonode's private key. + /// Can be used together with the public key above to prove that this + /// public key was vetted by the robonode and verified to be associated + /// with a FaceScan. + authentication_signature: Vec, +} + +/// Errors for the authenticate operation. +pub enum AuthenticateError { + /// This FaceScan was rejected. + FaceScanRejected, + /// This person was not found. + /// Unually this means they need to enroll, but it can also happen if + /// matching returns false-negative. + PersonNotFound, + /// The FaceScan signature validation failed. + /// This means that the user might've provided a signature using different + /// keypair from what was used for the original enrollment. + SignatureValidationFailed, + /// Internal error at server-level enrollment due to the underlying request + /// error at the API level. + InternalErrorEnrollment(FaceTecError), + /// Internal error at server-level enrollment due to unsuccessful response, + /// but for some other reason but the FaceScan being rejected. + /// Rejected FaceScan is explicitly encoded via a different error condition. + InternalErrorEnrollmentUnsuccessful, + /// Internal error at 3D-DB search due to the underlying request + /// error at the API level. + InternalErrorDbSearch(FaceTecError), + /// Internal error at 3D-DB search due to unsuccessful response. + InternalErrorDbSearchUnsuccessful, + /// Internal error at 3D-DB search due to match-level mismatch in + /// the search results. + InternalErrorDbSearchMatchLevelMismatch, + /// Internal error at public key loading due to invalid public key. + InternalErrorInvalidPublicKey, +} + +impl Logic +where + S: Signer + Send + 'static, + PK: Send + for<'a> TryFrom<&'a str> + Verifier + AsRef<[u8]> + Into, +{ + /// An authenticate invocation handler. + pub async fn authenticate( + &self, + req: AuthenticateRequest, + ) -> Result { + let mut unlocked = self.locked.lock().await; + + // Bump the sequence counter. + unlocked.sequence.inc(); + + // Prepare the ID to be used for this temporary FaceScan. + let tmp_external_database_ref_id = format!("tmp-{}", unlocked.sequence.get()); + + let enroll_res = unlocked + .facetec + .enrollment_3d(Enrollment3DRequest { + external_database_ref_id: &tmp_external_database_ref_id, + face_scan: &req.face_scan, + audit_trail_image: "TODO", + low_quality_audit_trail_image: "TODO", + }) + .await + .map_err(AuthenticateError::InternalErrorEnrollment)?; + + if !enroll_res.success { + if !enroll_res + .face_scan + .face_scan_security_checks + .all_checks_succeeded() + { + return Err(AuthenticateError::FaceScanRejected); + } + return Err(AuthenticateError::InternalErrorEnrollmentUnsuccessful); + } + + let search_res = unlocked + .facetec + .db_search(DBSearchRequest { + external_database_ref_id: &tmp_external_database_ref_id, + group_name: DB_GROUP_NAME, + min_match_level: MATCH_LEVEL, + }) + .await + .map_err(AuthenticateError::InternalErrorDbSearch)?; + + if !enroll_res.success { + return Err(AuthenticateError::InternalErrorDbSearchUnsuccessful); + } + + // If the results set is empty - this means that this person was not + // found in the system. + let found = search_res + .results + .first() + .ok_or(AuthenticateError::PersonNotFound)?; + if found.match_level != MATCH_LEVEL { + return Err(AuthenticateError::InternalErrorDbSearchMatchLevelMismatch); + } + + let public_key = PK::try_from(&found.identifier) + .map_err(|_| AuthenticateError::InternalErrorInvalidPublicKey)?; + + if !public_key.verify(&req.face_scan, &req.face_scan_signature) { + return Err(AuthenticateError::SignatureValidationFailed); + } + + let signed_public_key = unlocked.signer.sign(&public_key); + Ok(AuthenticateResponse { + public_key: public_key.into(), + authentication_signature: signed_public_key, + }) + } +} diff --git a/robonode-server/src/main.rs b/robonode-server/src/main.rs index 609ae3fe2..879b98edc 100644 --- a/robonode-server/src/main.rs +++ b/robonode-server/src/main.rs @@ -2,44 +2,17 @@ #![deny(missing_docs, clippy::missing_docs_in_private_items)] -use std::convert::Infallible; - -use hyper::service::{make_service_fn, service_fn}; -use hyper::{Body, Request, Response, Server}; - -/// A dummy hello world handler. -async fn hello(_: Request) -> Result, Infallible> { - Ok(Response::new(Body::from("Hello World!"))) -} - #[tokio::main] async fn main() -> Result<(), Box> { - // For every connection, we must make a `Service` to handle all - // incoming HTTP requests on said connection. - let make_svc = make_service_fn(|_conn| { - // This is the `Service` that will handle the connection. - // `service_fn` is a helper to convert a function that - // returns a Response into a `Service`. - async { Ok::<_, Infallible>(service_fn(hello)) } - }); - - let addr = ([127, 0, 0, 1], 3000).into(); - - let server = Server::bind(&addr).serve(make_svc); - + let root_filter = robonode_server::init(); + let (addr, server) = warp::serve(root_filter) + .bind_with_graceful_shutdown(([127, 0, 0, 1], 3030), shutdown_signal()); println!("Listening on http://{}", addr); - - let graceful = server.with_graceful_shutdown(shutdown_signal()); - - // Run this server for... forever! - if let Err(e) = graceful.await { - eprintln!("server error: {}", e); - } - + server.await; Ok(()) } -/// A future that resolves when the interrup signal is received, and panics +/// A future that resolves when the interrupt signal is received, and panics /// if the interrupt handler failed to set up. async fn shutdown_signal() { // Wait for the CTRL+C signal diff --git a/robonode-server/src/sequence.rs b/robonode-server/src/sequence.rs new file mode 100644 index 000000000..28383da32 --- /dev/null +++ b/robonode-server/src/sequence.rs @@ -0,0 +1,22 @@ +//! Sequence implementation. + +/// An increment-only sequence. +#[derive(Debug)] +pub struct Sequence(u64); + +impl Sequence { + /// Create a new sequence with the specified initial value. + pub fn new(init: u64) -> Self { + Self(init) + } + + /// Increment the sequence value. + pub fn inc(&mut self) { + self.0 += 1; + } + + /// Obtain the current value of the sequence. + pub fn get(&self) -> u64 { + self.0 + } +}