From ea3e965f417b0c6c6e52757d97790be810cea890 Mon Sep 17 00:00:00 2001 From: MOZGIII Date: Sun, 2 May 2021 10:55:15 +0300 Subject: [PATCH 01/12] Implement more of the dummy structure at the robonode-server --- Cargo.lock | 368 ++++++++++++++++++++++++++- robonode-server/Cargo.toml | 3 +- robonode-server/src/http.rs | 6 + robonode-server/src/http/filters.rs | 59 +++++ robonode-server/src/http/handlers.rs | 32 +++ robonode-server/src/lib.rs | 26 ++ robonode-server/src/logic.rs | 103 ++++++++ robonode-server/src/main.rs | 35 +-- robonode-server/src/sequence.rs | 22 ++ 9 files changed, 613 insertions(+), 41 deletions(-) create mode 100644 robonode-server/src/http.rs create mode 100644 robonode-server/src/http/filters.rs create mode 100644 robonode-server/src/http/handlers.rs create mode 100644 robonode-server/src/lib.rs create mode 100644 robonode-server/src/logic.rs create mode 100644 robonode-server/src/sequence.rs diff --git a/Cargo.lock b/Cargo.lock index f19c99a9d..696956a16 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -26,12 +26,37 @@ 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" @@ -66,6 +91,21 @@ 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 = "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" @@ -106,6 +146,20 @@ 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-io", + "futures-sink", + "futures-task", + "futures-util", +] + [[package]] name = "futures-channel" version = "0.3.14" @@ -113,6 +167,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce79c6a52a299137a6013061e0cf0e688fce5d7f1bc60125f520912fdb29ec25" dependencies = [ "futures-core", + "futures-sink", ] [[package]] @@ -121,6 +176,12 @@ version = "0.3.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "098cd1c6dda6ca01650f1a37a794245eb73181d0d4d4e955e2f3c37db7af1815" +[[package]] +name = "futures-io" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "365a1a1fb30ea1c03a830fdb2158f5236833ac81fa0ad12fe35b29cddc35cb04" + [[package]] name = "futures-sink" version = "0.3.14" @@ -140,9 +201,32 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c144ad54d60f23927f0a6b6d816e4271278b64f005ad65e4e35291d2de9c025" dependencies = [ "futures-core", + "futures-sink", "futures-task", "pin-project-lite", "pin-utils", + "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 +237,7 @@ checksum = "c9495705279e7140bf035dde1f6e750c162df8b625267cd52cc44e0b156732c8" dependencies = [ "cfg-if", "libc", - "wasi", + "wasi 0.10.2+wasi-snapshot-preview1", ] [[package]] @@ -181,6 +265,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" @@ -290,6 +399,15 @@ dependencies = [ "hashbrown", ] +[[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" @@ -368,6 +486,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 +518,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" @@ -433,6 +579,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" @@ -550,6 +702,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 +717,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 +737,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 +759,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 +777,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 +795,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]] @@ -665,8 +864,9 @@ dependencies = [ name = "robonode-server" version = "0.1.0" dependencies = [ - "hyper", + "serde", "tokio", + "warp", ] [[package]] @@ -675,6 +875,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 +891,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" @@ -757,6 +969,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" @@ -807,7 +1032,7 @@ checksum = "dac1c663cfc93810f88aed9b8941d48cabf856a1b111c29a40439018d870eb22" dependencies = [ "cfg-if", "libc", - "rand", + "rand 0.8.3", "redox_syscall", "remove_dir_all", "winapi", @@ -833,6 +1058,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 +1124,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 +1175,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "01ebdc2bb4498ab1ab5f5b73c5803825e60199229ccba0698170e3be0e7f959f" dependencies = [ "cfg-if", + "log", "pin-project-lite", "tracing-core", ] @@ -935,6 +1195,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" @@ -971,12 +1274,24 @@ dependencies = [ "percent-encoding", ] +[[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 = "want" version = "0.3.0" @@ -987,6 +1302,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" diff --git a/robonode-server/Cargo.toml b/robonode-server/Cargo.toml index 42eb4fcfb..8a4a0f873 100644 --- a/robonode-server/Cargo.toml +++ b/robonode-server/Cargo.toml @@ -6,5 +6,6 @@ authors = ["Humanode Team "] publish = false [dependencies] -hyper = { version = "0.14", features = ["full"] } +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..8350428c9 --- /dev/null +++ b/robonode-server/src/http/filters.rs @@ -0,0 +1,59 @@ +//! Filters, essentially how [`warp`] implements routes and middlewares. + +use std::sync::Arc; + +use warp::Filter; + +use crate::{ + http::handlers, + logic::{AuthenticateRequest, EnrollRequest, Logic}, +}; + +/// 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 { + enroll(logic.clone()).or(authenticate(logic)) +} + +/// POST /enroll with JSON body. +fn enroll( + logic: Arc, +) -> impl Filter + Clone { + 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 { + 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..7acad849a --- /dev/null +++ b/robonode-server/src/http/handlers.rs @@ -0,0 +1,32 @@ +//! Handlers, the HTTP transport coupling for the internal logic. + +use std::{convert::Infallible, sync::Arc}; +use warp::Reply; + +use warp::hyper::StatusCode; + +use crate::logic::{AuthenticateRequest, EnrollRequest, Logic}; + +/// Enroll operation HTTP transport coupling. +pub async fn enroll( + logic: Arc, + input: EnrollRequest, +) -> Result { + 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 { + 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..ff6a98799 --- /dev/null +++ b/robonode-server/src/lib.rs @@ -0,0 +1,26 @@ +//! Humanode's Bioauth Robonode server internal API. + +#![deny(missing_docs, clippy::missing_docs_in_private_items)] + +use std::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: (), + signer: (), + }), + }; + root(Arc::new(logic)) +} diff --git a/robonode-server/src/logic.rs b/robonode-server/src/logic.rs new file mode 100644 index 000000000..86e4f44c7 --- /dev/null +++ b/robonode-server/src/logic.rs @@ -0,0 +1,103 @@ +//! Core logic of the system. + +use tokio::sync::Mutex; + +use crate::sequence::Sequence; +use serde::{Deserialize, Serialize}; + +/// 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 { + /// The sequence number. + pub sequence: Sequence, + /// The client for the FaceTec Server. + pub facetec: (), + /// The utility for signing the responses. + pub signer: (), +} + +/// The overall generic logic. +pub struct Logic { + /// 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 { + /// This public key is already used. + AlreadyEnrolled, +} + +impl Logic { + /// An enroll invocation handler. + pub async fn enroll(&self, req: EnrollRequest) -> Result<(), EnrollError> { + let mut _unlocked = self.locked.lock().await; + // unlocked.facetec.enrollment_3d(&req.public_key, &req.face_scan).await?; + // match unlocked.facetec.3d_db_search(&req.public_key).await { + // Err(NotFound) => {}, + // Ok(_) => return Ok(Response::builder().status(409).body(Body::empty())?), + // Err(error) => return Ok(Response::builder().status(500).body(Body::new(error))?), + // } + // unlocked.facetec.3d_db_enroll(&public_key).await?; + 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: String, +} + +/// 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: String, +} + +/// Errors for the authenticate operation. +pub enum AuthenticateError { + /// The FaceScan did not match. + NotFound, +} + +impl Logic { + /// An authenticate invocation handler. + pub async fn authenticate( + &self, + req: AuthenticateRequest, + ) -> Result { + let mut unlocked = self.locked.lock().await; + unlocked.sequence.inc(); + // unlocked.facetec.enroll(unlocked.sequence.get(), face_scan).await; + // let public_key = unlocked.facetec.3d_db_search(unlocked.sequence.get()).await?; + // public_key.validate(face_scan_signature)?; + // let signed_public_key = unlocked.signer.sign(public_key); + // return both public_key and signed_public_key + Ok(AuthenticateResponse { + public_key: String::new(), + authentication_signature: String::new(), + }) + } +} diff --git a/robonode-server/src/main.rs b/robonode-server/src/main.rs index 609ae3fe2..7f94aa369 100644 --- a/robonode-server/src/main.rs +++ b/robonode-server/src/main.rs @@ -2,40 +2,13 @@ #![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(()) } 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 + } +} From d8858ffdb5853c6d81c5c953fb06209cb48cdbf3 Mon Sep 17 00:00:00 2001 From: MOZGIII Date: Sun, 2 May 2021 11:06:02 +0300 Subject: [PATCH 02/12] Add .cargo/config.toml --- .cargo/config.toml | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 .cargo/config.toml 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" From 442d99dda8210eaa71181a3afc5c27bd67ade45a Mon Sep 17 00:00:00 2001 From: MOZGIII Date: Mon, 3 May 2021 10:55:39 +0300 Subject: [PATCH 03/12] Add initial version of the FaceTec API client --- Cargo.lock | 10 ++ Cargo.toml | 7 +- facetec-api-client/Cargo.toml | 14 +++ facetec-api-client/src/db_enroll.rs | 111 ++++++++++++++++++ facetec-api-client/src/db_search.rs | 142 +++++++++++++++++++++++ facetec-api-client/src/enrollment3d.rs | 153 +++++++++++++++++++++++++ facetec-api-client/src/lib.rs | 35 ++++++ facetec-api-client/src/types.rs | 54 +++++++++ 8 files changed, 525 insertions(+), 1 deletion(-) create mode 100644 facetec-api-client/Cargo.toml create mode 100644 facetec-api-client/src/db_enroll.rs create mode 100644 facetec-api-client/src/db_search.rs create mode 100644 facetec-api-client/src/enrollment3d.rs create mode 100644 facetec-api-client/src/lib.rs create mode 100644 facetec-api-client/src/types.rs diff --git a/Cargo.lock b/Cargo.lock index 696956a16..fa164f706 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -115,6 +115,16 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "facetec-api-client" +version = "0.1.0" +dependencies = [ + "reqwest", + "serde", + "serde_json", + "thiserror", +] + [[package]] name = "fnv" version = "1.0.7" 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..1ffdb1558 --- /dev/null +++ b/facetec-api-client/Cargo.toml @@ -0,0 +1,14 @@ +[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] +serde_json = "1" diff --git a/facetec-api-client/src/db_enroll.rs b/facetec-api-client/src/db_enroll.rs new file mode 100644 index 000000000..0c0bb8d13 --- /dev/null +++ b/facetec-api-client/src/db_enroll.rs @@ -0,0 +1,111 @@ +//! POST `/3d-db/enroll` + +use reqwest::StatusCode; +use serde::{Deserialize, Serialize}; + +use crate::Error; + +use super::Client; + +impl Client { + /// Perform the `/3d-db/enroll` call to the server. + pub async fn db_enroll(&self, req: DBEnrollRequest<'_>) -> Result<(), Error> { + let url = format!("{}/3d-db/enroll", self.base_url); + let client = reqwest::Client::new(); + let res = client.post(url).json(&req).send().await?; + match res.status() { + StatusCode::CREATED => Ok(()), + _ => Err(Error::Call(DBEnrollError::Unknown(res.text().await?))), + } + } +} + +/// Input data for the `/3d-db/enroll` request. +#[derive(Debug, Serialize)] +pub struct DBEnrollRequest<'a> { + /// The ID of the pre-enrolled FaceMap to use. + #[serde(rename = "externalDatabaseRefID")] + external_database_ref_id: &'a str, + /// The name of the group to enroll the specified FaceMap at. + #[serde(rename = "groupName")] + group_name: &'a str, +} + +/// The response from `/3d-db/enroll`. +#[derive(Debug, Deserialize)] +pub struct DBEnrollResponse { + /// The external database ID that was used. + #[serde(rename = "externalDatabaseRefID")] + external_database_ref_id: String, + /// Whether the request had any errors during the execution. + error: bool, + /// Whether the request was successful. + success: bool, +} + +/// The `/3d-db/enroll`-specific error kind. +#[derive(Error, Debug)] +pub enum DBEnrollError { + /// 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 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" + )) + } +} diff --git a/facetec-api-client/src/db_search.rs b/facetec-api-client/src/db_search.rs new file mode 100644 index 000000000..ed8e194ad --- /dev/null +++ b/facetec-api-client/src/db_search.rs @@ -0,0 +1,142 @@ +//! POST `/3d-db/search` + +use reqwest::StatusCode; +use serde::{Deserialize, Serialize}; + +use crate::{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<(), Error> { + let url = format!("{}/3d-db/search", self.base_url); + let client = reqwest::Client::new(); + let res = client.post(url).json(&req).send().await?; + match res.status() { + StatusCode::CREATED => Ok(()), + _ => Err(Error::Call(DBSearchError::Unknown(res.text().await?))), + } + } +} + +/// Input data for the `/3d-db/search` request. +#[derive(Debug, Serialize)] +pub struct DBSearchRequest<'a> { + /// The ID of the pre-enrolled FaceMap to search with. + #[serde(rename = "externalDatabaseRefID")] + external_database_ref_id: &'a str, + /// The name of the group to search at. + #[serde(rename = "groupName")] + group_name: &'a str, + /// The minimal matching level to accept into the search result. + #[serde(rename = "minMatchLevel")] + min_match_level: MatchLevel, +} + +/// The response from `/3d-db/search`. +#[derive(Debug, Deserialize)] +pub struct DBSearchResponse { + /// The ID of the pre-enrolled FaceMap that was used for searching + /// as an input. + #[serde(rename = "externalDatabaseRefID")] + external_database_ref_id: String, + /// Whether the request had any errors during the execution. + error: bool, + /// Whether the request was successful. + success: bool, + /// The set of all the matched entries enrolled on the group. + results: Vec, +} + +/// A single entry that matched the search request. +#[derive(Debug, Deserialize)] +pub struct DBSearchResponseResult { + /// The external database ID associated with this entry. + identifier: String, + /// The level of matching this entry funfills to the input FaceMap. + #[serde(rename = "matchLevel")] + match_level: MatchLevel, +} + +/// The `/3d-db/search`-specific error kind. +#[derive(Error, Debug)] +pub enum DBSearchError { + /// Some other error occured. + #[error("unknown error: {0}")] + Unknown(String), +} + +#[cfg(test)] +mod tests { + 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" + ) + )) + } +} diff --git a/facetec-api-client/src/enrollment3d.rs b/facetec-api-client/src/enrollment3d.rs new file mode 100644 index 000000000..01d4b0258 --- /dev/null +++ b/facetec-api-client/src/enrollment3d.rs @@ -0,0 +1,153 @@ +//! POST `/enrollment-3d` + +use reqwest::StatusCode; +use serde::{Deserialize, Serialize}; + +use crate::{Error, OpaqueBase64DataRef}; + +use super::Client; + +impl Client { + /// Perform the `/enrollment-3d` call to the server. + pub async fn enrollment_3d( + &self, + req: Enrollment3DRequest<'_>, + ) -> Result<(), Error> { + let url = format!("{}/enrollment-3d", self.base_url); + let client = reqwest::Client::new(); + let res = client.post(url).json(&req).send().await?; + match res.status() { + StatusCode::CREATED => Ok(()), + _ => Err(Error::Call(Enrollment3DError::Unknown(res.text().await?))), + } + } +} + +/// Input data for the `/enrollment-3d` request. +#[derive(Debug, Serialize)] +pub struct Enrollment3DRequest<'a> { + /// The ID that the FaceTec Server will associate the data with. + #[serde(rename = "externalDatabaseRefID")] + external_database_ref_id: &'a str, + /// The FaceTec 3D FaceScan to enroll into the server. + #[serde(rename = "faceScan")] + face_scan: OpaqueBase64DataRef<'a>, + /// The audit trail for liveness check. + #[serde(rename = "auditTrailImage")] + audit_trail_image: OpaqueBase64DataRef<'a>, + /// The low quality audit trail for liveness check. + #[serde(rename = "lowQualityAuditTrailImage")] + low_quality_audit_trail_image: OpaqueBase64DataRef<'a>, +} + +/// The response from `/enrollment-3d`. +#[derive(Debug, Deserialize)] +pub struct Enrollment3DResponse { + /// The external database ID that was associated with this item. + #[serde(rename = "externalDatabaseRefID")] + external_database_ref_id: String, + /// Whether the request had any errors during the execution. + error: bool, + /// Whether the request was successful. + success: bool, + /// Something to do with the retry screen. + /// TODO: find more info on this parameter. + #[serde(rename = "faceTecRetryScreen")] + face_tec_retry_screen: i64, + /// Something to do with the retry screen. + /// TODO: find more info on this parameter. + #[serde(rename = "retryScreenEnumInt")] + retry_screen_enum_int: i64, + /// The age group enum id that the input face scan was classified to. + #[serde(rename = "ageEstimateGroupEnumInt")] + age_estimate_group_enum_int: i64, +} + +/// The `/enrollment-3d`-specific error kind. +#[derive(Error, Debug)] +pub enum Enrollment3DError { + /// 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 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, + age_estimate_group_enum_int: -1, + .. + } if external_database_ref_id == "test_external_dbref_id" + )) + } +} diff --git a/facetec-api-client/src/lib.rs b/facetec-api-client/src/lib.rs new file mode 100644 index 000000000..d7cf1cd94 --- /dev/null +++ b/facetec-api-client/src/lib.rs @@ -0,0 +1,35 @@ +//! Client API for the FaceTec Server SDK. + +#![warn(missing_docs, clippy::missing_docs_in_private_items)] + +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..c2b730fcd --- /dev/null +++ b/facetec-api-client/src/types.rs @@ -0,0 +1,54 @@ +//! Common types. + +/// 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)] +pub struct 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" +} + +/// The report on the security checks. +#[derive(Debug)] +pub struct FaceScanSecurityChecks { + // "auditTrailVerificationCheckSucceeded": true, +// "faceScanLivenessCheckSucceeded": false, +// "replayCheckSucceeded": true, +// "sessionTokenCheckSucceeded": true +} + +/// The call data that FaceTec includes with each response. +#[derive(Debug)] +pub struct CallData { + // "tid": "AAAAAAAAAAA-00000000-0000-0000-0000-000000000000", +// "path": "/enrollment-3d", +// "date": "Jan 01, 2000 00:00:00 AM", +// "epochSecond": 946684800, +// "requestMethod": "POST" +} + +/// The server info that FaceTec sends us with each response. +#[derive(Debug)] +pub struct ServerInfo { + // "version": "9.0.5", +// "mode": "Development Only", +// "notice": "Notice" +} From c1b12afb3b5af4a991ba67003f51e6f0bb6c7741 Mon Sep 17 00:00:00 2001 From: MOZGIII Date: Wed, 5 May 2021 11:52:54 +0300 Subject: [PATCH 04/12] Better types and responses composition at facetec-api-client --- facetec-api-client/src/db_enroll.rs | 3 +- facetec-api-client/src/db_search.rs | 11 ++- facetec-api-client/src/enrollment3d.rs | 41 ++++++---- facetec-api-client/src/types.rs | 101 +++++++++++++++++++------ 4 files changed, 110 insertions(+), 46 deletions(-) diff --git a/facetec-api-client/src/db_enroll.rs b/facetec-api-client/src/db_enroll.rs index 0c0bb8d13..a90bff327 100644 --- a/facetec-api-client/src/db_enroll.rs +++ b/facetec-api-client/src/db_enroll.rs @@ -22,17 +22,18 @@ impl Client { /// Input data for the `/3d-db/enroll` request. #[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] pub struct DBEnrollRequest<'a> { /// The ID of the pre-enrolled FaceMap to use. #[serde(rename = "externalDatabaseRefID")] external_database_ref_id: &'a str, /// The name of the group to enroll the specified FaceMap at. - #[serde(rename = "groupName")] group_name: &'a str, } /// The response from `/3d-db/enroll`. #[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] pub struct DBEnrollResponse { /// The external database ID that was used. #[serde(rename = "externalDatabaseRefID")] diff --git a/facetec-api-client/src/db_search.rs b/facetec-api-client/src/db_search.rs index ed8e194ad..a85e71ef8 100644 --- a/facetec-api-client/src/db_search.rs +++ b/facetec-api-client/src/db_search.rs @@ -3,7 +3,7 @@ use reqwest::StatusCode; use serde::{Deserialize, Serialize}; -use crate::{Error, MatchLevel}; +use crate::{CommonResponse, Error, FaceScanResponse, MatchLevel}; use super::Client; @@ -22,21 +22,24 @@ impl Client { /// Input data for the `/3d-db/search` request. #[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] pub struct DBSearchRequest<'a> { /// The ID of the pre-enrolled FaceMap to search with. #[serde(rename = "externalDatabaseRefID")] external_database_ref_id: &'a str, /// The name of the group to search at. - #[serde(rename = "groupName")] group_name: &'a str, /// The minimal matching level to accept into the search result. - #[serde(rename = "minMatchLevel")] min_match_level: MatchLevel, } /// The response from `/3d-db/search`. #[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] pub struct DBSearchResponse { + /// Common response portion. + #[serde(flatten)] + common: CommonResponse, /// The ID of the pre-enrolled FaceMap that was used for searching /// as an input. #[serde(rename = "externalDatabaseRefID")] @@ -51,11 +54,11 @@ pub struct DBSearchResponse { /// A single entry that matched the search request. #[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] pub struct DBSearchResponseResult { /// The external database ID associated with this entry. identifier: String, /// The level of matching this entry funfills to the input FaceMap. - #[serde(rename = "matchLevel")] match_level: MatchLevel, } diff --git a/facetec-api-client/src/enrollment3d.rs b/facetec-api-client/src/enrollment3d.rs index 01d4b0258..1b7bab7dd 100644 --- a/facetec-api-client/src/enrollment3d.rs +++ b/facetec-api-client/src/enrollment3d.rs @@ -3,7 +3,7 @@ use reqwest::StatusCode; use serde::{Deserialize, Serialize}; -use crate::{Error, OpaqueBase64DataRef}; +use crate::{CommonResponse, Error, FaceScanResponse, OpaqueBase64DataRef}; use super::Client; @@ -25,24 +25,29 @@ impl Client { /// Input data for the `/enrollment-3d` request. #[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] pub struct Enrollment3DRequest<'a> { /// The ID that the FaceTec Server will associate the data with. #[serde(rename = "externalDatabaseRefID")] external_database_ref_id: &'a str, /// The FaceTec 3D FaceScan to enroll into the server. - #[serde(rename = "faceScan")] face_scan: OpaqueBase64DataRef<'a>, /// The audit trail for liveness check. - #[serde(rename = "auditTrailImage")] audit_trail_image: OpaqueBase64DataRef<'a>, /// The low quality audit trail for liveness check. - #[serde(rename = "lowQualityAuditTrailImage")] low_quality_audit_trail_image: OpaqueBase64DataRef<'a>, } /// The response from `/enrollment-3d`. #[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] pub struct Enrollment3DResponse { + /// Common response portion. + #[serde(flatten)] + common: CommonResponse, + /// FaceScan response portion. + #[serde(flatten)] + face_scan: FaceScanResponse, /// The external database ID that was associated with this item. #[serde(rename = "externalDatabaseRefID")] external_database_ref_id: String, @@ -50,17 +55,6 @@ pub struct Enrollment3DResponse { error: bool, /// Whether the request was successful. success: bool, - /// Something to do with the retry screen. - /// TODO: find more info on this parameter. - #[serde(rename = "faceTecRetryScreen")] - face_tec_retry_screen: i64, - /// Something to do with the retry screen. - /// TODO: find more info on this parameter. - #[serde(rename = "retryScreenEnumInt")] - retry_screen_enum_int: i64, - /// The age group enum id that the input face scan was classified to. - #[serde(rename = "ageEstimateGroupEnumInt")] - age_estimate_group_enum_int: i64, } /// The `/enrollment-3d`-specific error kind. @@ -76,6 +70,8 @@ pub enum Enrollment3DError { #[cfg(test)] mod tests { + use crate::{AdditionalSessionData, CallData}; + use super::*; #[test] @@ -145,7 +141,20 @@ mod tests { external_database_ref_id, error: false, success: false, - age_estimate_group_enum_int: -1, + 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" )) diff --git a/facetec-api-client/src/types.rs b/facetec-api-client/src/types.rs index c2b730fcd..24a1e71d6 100644 --- a/facetec-api-client/src/types.rs +++ b/facetec-api-client/src/types.rs @@ -1,5 +1,7 @@ //! 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. @@ -13,42 +15,91 @@ pub type MatchLevel = i64; /// The additional data about the session that FaceTec communicates back to us /// with each response. -#[derive(Debug)] +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] pub struct 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" + /// 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)] +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] pub struct FaceScanSecurityChecks { - // "auditTrailVerificationCheckSucceeded": true, -// "faceScanLivenessCheckSucceeded": false, -// "replayCheckSucceeded": true, -// "sessionTokenCheckSucceeded": true + /// 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, } /// The call data that FaceTec includes with each response. -#[derive(Debug)] +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] pub struct CallData { - // "tid": "AAAAAAAAAAA-00000000-0000-0000-0000-000000000000", -// "path": "/enrollment-3d", -// "date": "Jan 01, 2000 00:00:00 AM", -// "epochSecond": 946684800, -// "requestMethod": "POST" + /// 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)] +#[derive(Debug, Deserialize)] pub struct ServerInfo { - // "version": "9.0.5", -// "mode": "Development Only", -// "notice": "Notice" + /// 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)] +pub struct CommonResponse { + /// The additional session information included in this response. + #[serde(rename = "additionalSessionData")] + pub additional_session_data: AdditionalSessionData, + /// The information about the API call the request was to. + #[serde(rename = "callData")] + pub call_data: CallData, + /// The information about the server. + #[serde(rename = "serverInfo")] + pub server_info: ServerInfo, +} + +/// A FaceScan-related FaceTec API response portion. +#[derive(Debug, Deserialize)] +pub struct FaceScanResponse { + /// The the information about the security checks over the FaceScan data. + #[serde(rename = "faceScanSecurityChecks")] + 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. + #[serde(rename = "faceTecRetryScreen")] + 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. + #[serde(rename = "retryScreenEnumInt")] + pub retry_screen_enum_int: i64, + /// The age group enum id that the input FaceScan was classified to. + #[serde(rename = "ageEstimateGroupEnumInt")] + pub age_estimate_group_enum_int: i64, } From 9e0b934c10a80d80fbad4da880d5063845963036 Mon Sep 17 00:00:00 2001 From: MOZGIII Date: Fri, 7 May 2021 13:59:47 +0300 Subject: [PATCH 05/12] More ground work on the FaceTec API client --- Cargo.lock | 333 +++++++++++++++++++++++++ facetec-api-client/Cargo.toml | 3 + facetec-api-client/src/db_enroll.rs | 186 +++++++++++++- facetec-api-client/src/db_search.rs | 205 +++++++++++++-- facetec-api-client/src/enrollment3d.rs | 238 ++++++++++++++++-- facetec-api-client/src/lib.rs | 4 + facetec-api-client/src/types.rs | 31 ++- 7 files changed, 934 insertions(+), 66 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fa164f706..ff37ee6de 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" @@ -63,6 +106,12 @@ 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" @@ -75,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" @@ -97,6 +166,47 @@ 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" @@ -115,14 +225,32 @@ 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]] @@ -164,6 +292,7 @@ checksum = "a9d5813545e459ad3ca1bff9915e9ad7f1a47dc6a91b627ce321d5863b7dd253" dependencies = [ "futures-channel", "futures-core", + "futures-executor", "futures-io", "futures-sink", "futures-task", @@ -186,12 +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" @@ -204,17 +371,29 @@ 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", ] @@ -331,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" @@ -409,6 +609,12 @@ 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" @@ -454,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" @@ -564,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" @@ -628,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" @@ -703,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" @@ -817,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" @@ -967,6 +1232,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" @@ -1013,6 +1290,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" @@ -1023,6 +1306,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" @@ -1048,6 +1337,16 @@ dependencies = [ "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" @@ -1266,6 +1565,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" @@ -1282,6 +1587,7 @@ dependencies = [ "idna", "matches", "percent-encoding", + "serde", ] [[package]] @@ -1302,6 +1608,12 @@ 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" @@ -1461,3 +1773,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/facetec-api-client/Cargo.toml b/facetec-api-client/Cargo.toml index 1ffdb1558..b6f776b40 100644 --- a/facetec-api-client/Cargo.toml +++ b/facetec-api-client/Cargo.toml @@ -11,4 +11,7 @@ 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 index a90bff327..76f5bcc7a 100644 --- a/facetec-api-client/src/db_enroll.rs +++ b/facetec-api-client/src/db_enroll.rs @@ -3,60 +3,89 @@ use reqwest::StatusCode; use serde::{Deserialize, Serialize}; -use crate::Error; +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<(), Error> { + pub async fn db_enroll( + &self, + req: DBEnrollRequest<'_>, + ) -> Result> { let url = format!("{}/3d-db/enroll", self.base_url); let client = reqwest::Client::new(); let res = client.post(url).json(&req).send().await?; match res.status() { - StatusCode::CREATED => Ok(()), + 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)] +#[derive(Debug, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct DBEnrollRequest<'a> { /// The ID of the pre-enrolled FaceMap to use. #[serde(rename = "externalDatabaseRefID")] - external_database_ref_id: &'a str, + pub external_database_ref_id: &'a str, /// The name of the group to enroll the specified FaceMap at. - group_name: &'a str, + pub group_name: &'a str, } /// The response from `/3d-db/enroll`. -#[derive(Debug, Deserialize)] +#[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")] - external_database_ref_id: String, + pub external_database_ref_id: String, /// Whether the request had any errors during the execution. - error: bool, + pub error: bool, /// Whether the request was successful. - success: bool, + pub success: bool, } /// The `/3d-db/enroll`-specific error kind. -#[derive(Error, Debug)] +#[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] @@ -99,7 +128,7 @@ mod tests { }); let response: DBEnrollResponse = serde_json::from_value(sample_response).unwrap(); - assert!(matches!( + assert_matches!( response, DBEnrollResponse { external_database_ref_id, @@ -107,6 +136,137 @@ mod tests { 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 index a85e71ef8..a69d526f6 100644 --- a/facetec-api-client/src/db_search.rs +++ b/facetec-api-client/src/db_search.rs @@ -3,75 +3,101 @@ use reqwest::StatusCode; use serde::{Deserialize, Serialize}; -use crate::{CommonResponse, Error, FaceScanResponse, MatchLevel}; +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<(), Error> { + pub async fn db_search( + &self, + req: DBSearchRequest<'_>, + ) -> Result> { let url = format!("{}/3d-db/search", self.base_url); let client = reqwest::Client::new(); let res = client.post(url).json(&req).send().await?; match res.status() { - StatusCode::CREATED => Ok(()), + 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)] +#[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")] - external_database_ref_id: &'a str, + pub external_database_ref_id: &'a str, /// The name of the group to search at. - group_name: &'a str, + pub group_name: &'a str, /// The minimal matching level to accept into the search result. - min_match_level: MatchLevel, + pub min_match_level: MatchLevel, } /// The response from `/3d-db/search`. -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct DBSearchResponse { /// Common response portion. #[serde(flatten)] - common: CommonResponse, + pub common: CommonResponse, /// The ID of the pre-enrolled FaceMap that was used for searching /// as an input. #[serde(rename = "externalDatabaseRefID")] - external_database_ref_id: String, + pub external_database_ref_id: String, /// Whether the request had any errors during the execution. - error: bool, + pub error: bool, /// Whether the request was successful. - success: bool, + pub success: bool, /// The set of all the matched entries enrolled on the group. - results: Vec, + pub results: Vec, } /// A single entry that matched the search request. -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct DBSearchResponseResult { /// The external database ID associated with this entry. - identifier: String, + pub identifier: String, /// The level of matching this entry funfills to the input FaceMap. - match_level: MatchLevel, + pub match_level: MatchLevel, } /// The `/3d-db/search`-specific error kind. -#[derive(Error, Debug)] +#[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] @@ -122,7 +148,7 @@ mod tests { }); let response: DBSearchResponse = serde_json::from_value(sample_response).unwrap(); - assert!(matches!( + assert_matches!( response, DBSearchResponse { ref external_database_ref_id, @@ -140,6 +166,147 @@ mod tests { .. } 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 index 1b7bab7dd..ab2e6b6b4 100644 --- a/facetec-api-client/src/enrollment3d.rs +++ b/facetec-api-client/src/enrollment3d.rs @@ -3,7 +3,7 @@ use reqwest::StatusCode; use serde::{Deserialize, Serialize}; -use crate::{CommonResponse, Error, FaceScanResponse, OpaqueBase64DataRef}; +use crate::{CommonResponse, Error, FaceScanResponse, OpaqueBase64DataRef, ServerInfo}; use super::Client; @@ -12,65 +12,90 @@ impl Client { pub async fn enrollment_3d( &self, req: Enrollment3DRequest<'_>, - ) -> Result<(), Error> { + ) -> Result> { let url = format!("{}/enrollment-3d", self.base_url); let client = reqwest::Client::new(); let res = client.post(url).json(&req).send().await?; match res.status() { - StatusCode::CREATED => Ok(()), + 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)] +#[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")] - external_database_ref_id: &'a str, + pub external_database_ref_id: &'a str, /// The FaceTec 3D FaceScan to enroll into the server. - face_scan: OpaqueBase64DataRef<'a>, + pub face_scan: OpaqueBase64DataRef<'a>, /// The audit trail for liveness check. - audit_trail_image: OpaqueBase64DataRef<'a>, + pub audit_trail_image: OpaqueBase64DataRef<'a>, /// The low quality audit trail for liveness check. - low_quality_audit_trail_image: OpaqueBase64DataRef<'a>, + pub low_quality_audit_trail_image: OpaqueBase64DataRef<'a>, } /// The response from `/enrollment-3d`. -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Enrollment3DResponse { /// Common response portion. #[serde(flatten)] - common: CommonResponse, + pub common: CommonResponse, /// FaceScan response portion. #[serde(flatten)] - face_scan: FaceScanResponse, + pub face_scan: FaceScanResponse, /// The external database ID that was associated with this item. #[serde(rename = "externalDatabaseRefID")] - external_database_ref_id: String, + pub external_database_ref_id: String, /// Whether the request had any errors during the execution. - error: bool, + pub error: bool, /// Whether the request was successful. - success: bool, + pub success: bool, } /// The `/enrollment-3d`-specific error kind. -#[derive(Error, Debug)] +#[derive(Error, Debug, PartialEq)] pub enum Enrollment3DError { - /// The face scan or public key were already enrolled. - #[error("already enrolled")] - AlreadyEnrolled, + /// 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 crate::{AdditionalSessionData, CallData}; + use wiremock::{ + matchers::{self}, + Mock, MockServer, ResponseTemplate, + }; + + use crate::{AdditionalSessionData, CallData, ServerInfo}; use super::*; @@ -135,7 +160,7 @@ mod tests { }); let response: Enrollment3DResponse = serde_json::from_value(sample_response).unwrap(); - assert!(matches!( + assert_matches!( response, Enrollment3DResponse { external_database_ref_id, @@ -157,6 +182,177 @@ mod tests { }, .. } 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 index d7cf1cd94..122160c87 100644 --- a/facetec-api-client/src/lib.rs +++ b/facetec-api-client/src/lib.rs @@ -2,6 +2,10 @@ #![warn(missing_docs, clippy::missing_docs_in_private_items)] +#[cfg(test)] +#[macro_use] +extern crate assert_matches; + use thiserror::Error; mod db_enroll; diff --git a/facetec-api-client/src/types.rs b/facetec-api-client/src/types.rs index 24a1e71d6..448e2b549 100644 --- a/facetec-api-client/src/types.rs +++ b/facetec-api-client/src/types.rs @@ -15,7 +15,7 @@ pub type MatchLevel = i64; /// The additional data about the session that FaceTec communicates back to us /// with each response. -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, PartialEq, Eq)] #[serde(rename_all = "camelCase")] pub struct AdditionalSessionData { /// TODO: document. @@ -31,7 +31,7 @@ pub struct AdditionalSessionData { } /// The report on the security checks. -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, PartialEq, Eq)] #[serde(rename_all = "camelCase")] pub struct FaceScanSecurityChecks { /// TODO: document @@ -44,8 +44,18 @@ pub struct FaceScanSecurityChecks { 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)] +#[derive(Debug, Deserialize, PartialEq, Eq)] #[serde(rename_all = "camelCase")] pub struct CallData { /// Some opaque transaction identifier. @@ -61,7 +71,7 @@ pub struct CallData { } /// The server info that FaceTec sends us with each response. -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, PartialEq, Eq)] pub struct ServerInfo { /// Version of the server. pub version: String, @@ -72,34 +82,29 @@ pub struct ServerInfo { } /// A common FaceTec API response portion. -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] pub struct CommonResponse { /// The additional session information included in this response. - #[serde(rename = "additionalSessionData")] pub additional_session_data: AdditionalSessionData, /// The information about the API call the request was to. - #[serde(rename = "callData")] pub call_data: CallData, /// The information about the server. - #[serde(rename = "serverInfo")] pub server_info: ServerInfo, } /// A FaceScan-related FaceTec API response portion. -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] pub struct FaceScanResponse { /// The the information about the security checks over the FaceScan data. - #[serde(rename = "faceScanSecurityChecks")] 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. - #[serde(rename = "faceTecRetryScreen")] 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. - #[serde(rename = "retryScreenEnumInt")] pub retry_screen_enum_int: i64, /// The age group enum id that the input FaceScan was classified to. - #[serde(rename = "ageEstimateGroupEnumInt")] pub age_estimate_group_enum_int: i64, } From b384728363fb84be195ebd647e4f9d662ba47236 Mon Sep 17 00:00:00 2001 From: MOZGIII Date: Fri, 7 May 2021 14:00:55 +0300 Subject: [PATCH 06/12] Initial robonode logic implementation --- Cargo.lock | 2 + robonode-server/Cargo.toml | 2 + robonode-server/src/lib.rs | 5 +- robonode-server/src/logic.rs | 186 ++++++++++++++++++++++++++++++++--- 4 files changed, 178 insertions(+), 17 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ff37ee6de..0a640addd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1139,6 +1139,8 @@ dependencies = [ name = "robonode-server" version = "0.1.0" dependencies = [ + "facetec-api-client", + "reqwest", "serde", "tokio", "warp", diff --git a/robonode-server/Cargo.toml b/robonode-server/Cargo.toml index 8a4a0f873..df7d7f94f 100644 --- a/robonode-server/Cargo.toml +++ b/robonode-server/Cargo.toml @@ -6,6 +6,8 @@ authors = ["Humanode Team "] publish = false [dependencies] +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/lib.rs b/robonode-server/src/lib.rs index ff6a98799..3d1b8683a 100644 --- a/robonode-server/src/lib.rs +++ b/robonode-server/src/lib.rs @@ -18,7 +18,10 @@ pub fn init() -> impl Filter), + /// 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 = ""; + impl Logic { /// An enroll invocation handler. pub async fn enroll(&self, req: EnrollRequest) -> Result<(), EnrollError> { - let mut _unlocked = self.locked.lock().await; - // unlocked.facetec.enrollment_3d(&req.public_key, &req.face_scan).await?; - // match unlocked.facetec.3d_db_search(&req.public_key).await { - // Err(NotFound) => {}, - // Ok(_) => return Ok(Response::builder().status(409).body(Body::empty())?), - // Err(error) => return Ok(Response::builder().status(500).body(Body::new(error))?), - // } - // unlocked.facetec.3d_db_enroll(&public_key).await?; + 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: 10, + }) + .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(()) } } @@ -78,8 +169,24 @@ pub struct AuthenticateResponse { /// Errors for the authenticate operation. pub enum AuthenticateError { - /// The FaceScan did not match. - NotFound, + /// 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, + /// 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, } impl Logic { @@ -89,9 +196,56 @@ impl Logic { req: AuthenticateRequest, ) -> Result { let mut unlocked = self.locked.lock().await; + + // Bump the sequence counter. unlocked.sequence.inc(); - // unlocked.facetec.enroll(unlocked.sequence.get(), face_scan).await; - // let public_key = unlocked.facetec.3d_db_search(unlocked.sequence.get()).await?; + + // 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: 10, + }) + .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. + if search_res.results.is_empty() { + return Err(AuthenticateError::PersonNotFound); + } + + // TODO: // public_key.validate(face_scan_signature)?; // let signed_public_key = unlocked.signer.sign(public_key); // return both public_key and signed_public_key From ed9acadd19cb6a62972d4384eac79192306835a4 Mon Sep 17 00:00:00 2001 From: MOZGIII Date: Tue, 11 May 2021 13:43:56 +0300 Subject: [PATCH 07/12] Complete the logic implementation via traits --- robonode-server/src/http/filters.rs | 34 ++++++---- robonode-server/src/http/handlers.rs | 27 +++++--- robonode-server/src/lib.rs | 17 ++++- robonode-server/src/logic.rs | 95 ++++++++++++++++++++++------ 4 files changed, 135 insertions(+), 38 deletions(-) diff --git a/robonode-server/src/http/filters.rs b/robonode-server/src/http/filters.rs index 8350428c9..09b437d51 100644 --- a/robonode-server/src/http/filters.rs +++ b/robonode-server/src/http/filters.rs @@ -1,12 +1,12 @@ //! Filters, essentially how [`warp`] implements routes and middlewares. -use std::sync::Arc; +use std::{convert::TryFrom, sync::Arc}; use warp::Filter; use crate::{ http::handlers, - logic::{AuthenticateRequest, EnrollRequest, Logic}, + logic::{AuthenticateRequest, EnrollRequest, Logic, Signer, Verifier}, }; /// Pass the [`Arc`] to the handler. @@ -30,16 +30,24 @@ where } /// The root mount point with all the routes. -pub fn root( - logic: Arc, -) -> impl Filter + Clone { +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(logic.clone()).or(authenticate(logic)) } /// POST /enroll with JSON body. -fn enroll( - logic: Arc, -) -> impl Filter + Clone { +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)) @@ -48,9 +56,13 @@ fn enroll( } /// POST /authenticate with JSON body. -fn authenticate( - logic: Arc, -) -> impl Filter + Clone { +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)) diff --git a/robonode-server/src/http/handlers.rs b/robonode-server/src/http/handlers.rs index 7acad849a..25bc1e40a 100644 --- a/robonode-server/src/http/handlers.rs +++ b/robonode-server/src/http/handlers.rs @@ -1,17 +1,24 @@ //! Handlers, the HTTP transport coupling for the internal logic. -use std::{convert::Infallible, sync::Arc}; +use std::{ + convert::{Infallible, TryFrom}, + sync::Arc, +}; use warp::Reply; use warp::hyper::StatusCode; -use crate::logic::{AuthenticateRequest, EnrollRequest, Logic}; +use crate::logic::{AuthenticateRequest, EnrollRequest, Logic, Signer, Verifier}; /// Enroll operation HTTP transport coupling. -pub async fn enroll( - logic: Arc, +pub async fn enroll( + logic: Arc>, input: EnrollRequest, -) -> Result { +) -> 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 @@ -19,10 +26,14 @@ pub async fn enroll( } /// Authenticate operation HTTP transport coupling. -pub async fn authenticate( - logic: Arc, +pub async fn authenticate( + logic: Arc>, input: AuthenticateRequest, -) -> Result { +) -> 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()) diff --git a/robonode-server/src/lib.rs b/robonode-server/src/lib.rs index 3d1b8683a..a38222cfb 100644 --- a/robonode-server/src/lib.rs +++ b/robonode-server/src/lib.rs @@ -2,7 +2,7 @@ #![deny(missing_docs, clippy::missing_docs_in_private_items)] -use std::sync::Arc; +use std::{marker::PhantomData, sync::Arc}; use http::root; use tokio::sync::Mutex; @@ -23,7 +23,22 @@ pub fn init() -> impl Filter, }), }; 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 index a0a887714..4e09e72f7 100644 --- a/robonode-server/src/logic.rs +++ b/robonode-server/src/logic.rs @@ -1,5 +1,7 @@ //! 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, @@ -9,23 +11,47 @@ 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 { +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: (), + pub signer: S, + /// Public key type to use under the hood. + pub public_key_type: PhantomData, } /// The overall generic logic. -pub struct 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, + pub locked: Mutex>, } /// The request for the enroll operation. @@ -39,6 +65,8 @@ pub struct EnrollRequest { /// 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. @@ -74,10 +102,20 @@ const EXTERNAL_DATABASE_REF_ID_ALREADY_IN_USE_ERROR_MESSAGE: &str = /// 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 { +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 @@ -113,7 +151,7 @@ impl Logic { .db_search(DBSearchRequest { external_database_ref_id: &req.public_key, group_name: DB_GROUP_NAME, - min_match_level: 10, + min_match_level: MATCH_LEVEL, }) .await .map_err(EnrollError::InternalErrorDbSearch)?; @@ -152,7 +190,7 @@ pub struct AuthenticateRequest { 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: String, + face_scan_signature: Vec, } /// The response of the authenticate operation. @@ -164,7 +202,7 @@ pub struct AuthenticateResponse { /// 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: String, + authentication_signature: Vec, } /// Errors for the authenticate operation. @@ -175,6 +213,10 @@ pub enum AuthenticateError { /// 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), @@ -187,9 +229,18 @@ pub enum AuthenticateError { 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 { +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, @@ -230,7 +281,7 @@ impl Logic { .db_search(DBSearchRequest { external_database_ref_id: &tmp_external_database_ref_id, group_name: DB_GROUP_NAME, - min_match_level: 10, + min_match_level: MATCH_LEVEL, }) .await .map_err(AuthenticateError::InternalErrorDbSearch)?; @@ -241,17 +292,25 @@ impl Logic { // If the results set is empty - this means that this person was not // found in the system. - if search_res.results.is_empty() { - return Err(AuthenticateError::PersonNotFound); + let found = search_res + .results + .first() + .ok_or_else(|| 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); } - // TODO: - // public_key.validate(face_scan_signature)?; - // let signed_public_key = unlocked.signer.sign(public_key); - // return both public_key and signed_public_key + let signed_public_key = unlocked.signer.sign(&public_key); Ok(AuthenticateResponse { - public_key: String::new(), - authentication_signature: String::new(), + public_key: public_key.into(), + authentication_signature: signed_public_key, }) } } From 365c40caeaaf863646e78543e8990108e5dd2fa2 Mon Sep 17 00:00:00 2001 From: MOZGIII Date: Tue, 18 May 2021 14:53:57 +0300 Subject: [PATCH 08/12] Fix a typo at docstring --- robonode-server/src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/robonode-server/src/main.rs b/robonode-server/src/main.rs index 7f94aa369..879b98edc 100644 --- a/robonode-server/src/main.rs +++ b/robonode-server/src/main.rs @@ -12,7 +12,7 @@ async fn main() -> Result<(), Box> { 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 From ee1e2c412e81f3df038a32e5d10dbf95da6ce5c5 Mon Sep 17 00:00:00 2001 From: MOZGIII Date: Tue, 18 May 2021 14:58:25 +0300 Subject: [PATCH 09/12] Fix clippy offense --- robonode-server/src/logic.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/robonode-server/src/logic.rs b/robonode-server/src/logic.rs index 4e09e72f7..c508e7c1d 100644 --- a/robonode-server/src/logic.rs +++ b/robonode-server/src/logic.rs @@ -295,7 +295,7 @@ where let found = search_res .results .first() - .ok_or_else(|| AuthenticateError::PersonNotFound)?; + .ok_or(AuthenticateError::PersonNotFound)?; if found.match_level != MATCH_LEVEL { return Err(AuthenticateError::InternalErrorDbSearchMatchLevelMismatch); } From e0e51ccf8077fc4cbcac0263a0b427d58869ca0d Mon Sep 17 00:00:00 2001 From: MOZGIII Date: Tue, 18 May 2021 17:42:23 +0300 Subject: [PATCH 10/12] Do not create the reqwest client locally at facetec API client --- facetec-api-client/src/db_enroll.rs | 3 +-- facetec-api-client/src/db_search.rs | 3 +-- facetec-api-client/src/enrollment3d.rs | 3 +-- 3 files changed, 3 insertions(+), 6 deletions(-) diff --git a/facetec-api-client/src/db_enroll.rs b/facetec-api-client/src/db_enroll.rs index 76f5bcc7a..230c94f74 100644 --- a/facetec-api-client/src/db_enroll.rs +++ b/facetec-api-client/src/db_enroll.rs @@ -14,8 +14,7 @@ impl Client { req: DBEnrollRequest<'_>, ) -> Result> { let url = format!("{}/3d-db/enroll", self.base_url); - let client = reqwest::Client::new(); - let res = client.post(url).json(&req).send().await?; + let res = self.reqwest.post(url).json(&req).send().await?; match res.status() { StatusCode::OK => Ok(res.json().await?), StatusCode::BAD_REQUEST => { diff --git a/facetec-api-client/src/db_search.rs b/facetec-api-client/src/db_search.rs index a69d526f6..b78d646c7 100644 --- a/facetec-api-client/src/db_search.rs +++ b/facetec-api-client/src/db_search.rs @@ -14,8 +14,7 @@ impl Client { req: DBSearchRequest<'_>, ) -> Result> { let url = format!("{}/3d-db/search", self.base_url); - let client = reqwest::Client::new(); - let res = client.post(url).json(&req).send().await?; + let res = self.reqwest.post(url).json(&req).send().await?; match res.status() { StatusCode::OK => Ok(res.json().await?), StatusCode::BAD_REQUEST => { diff --git a/facetec-api-client/src/enrollment3d.rs b/facetec-api-client/src/enrollment3d.rs index ab2e6b6b4..5e854735b 100644 --- a/facetec-api-client/src/enrollment3d.rs +++ b/facetec-api-client/src/enrollment3d.rs @@ -14,8 +14,7 @@ impl Client { req: Enrollment3DRequest<'_>, ) -> Result> { let url = format!("{}/enrollment-3d", self.base_url); - let client = reqwest::Client::new(); - let res = client.post(url).json(&req).send().await?; + 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( From 5af914ef0c6afc20d297489d649cad22b83a186c Mon Sep 17 00:00:00 2001 From: MOZGIII Date: Tue, 18 May 2021 17:44:05 +0300 Subject: [PATCH 11/12] Use the Arc::clone instead of .clone --- robonode-server/src/http/filters.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/robonode-server/src/http/filters.rs b/robonode-server/src/http/filters.rs index 09b437d51..cdbab1e13 100644 --- a/robonode-server/src/http/filters.rs +++ b/robonode-server/src/http/filters.rs @@ -37,7 +37,7 @@ where S: Signer + Send + 'static, PK: Send + for<'a> TryFrom<&'a str> + Verifier + AsRef<[u8]> + Into, { - enroll(logic.clone()).or(authenticate(logic)) + enroll(Arc::clone(&logic)).or(authenticate(logic)) } /// POST /enroll with JSON body. From 86443ddeba8cd7c9cf4f2b00a23bfd0aac85c726 Mon Sep 17 00:00:00 2001 From: MOZGIII Date: Tue, 1 Jun 2021 11:52:56 +0300 Subject: [PATCH 12/12] Add tests and reorganize the robonode-client --- Cargo.lock | 4 + robonode-client/Cargo.toml | 6 + robonode-client/src/authenticate.rs | 181 ++++++++++++++++++++++++++++ robonode-client/src/enroll.rs | 141 ++++++++++++++++++++++ robonode-client/src/lib.rs | 87 +------------ 5 files changed, 338 insertions(+), 81 deletions(-) create mode 100644 robonode-client/src/authenticate.rs create mode 100644 robonode-client/src/enroll.rs diff --git a/Cargo.lock b/Cargo.lock index 0a640addd..d29e48088 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1130,9 +1130,13 @@ dependencies = [ name = "robonode-client" version = "0.1.0" dependencies = [ + "assert_matches", "reqwest", "serde", + "serde_json", "thiserror", + "tokio", + "wiremock", ] [[package]] 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), -}