hcaptcha_no_wasm/client.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
//!
//! # Hcaptcha Client
//!
//! The Hcaptcha Client struct provides an http client to connect to
//! the Hcaptcha API.
//!
//! The url for the API is stored in the url field of the struct.
//! A default url is stored in the const VERIFY_URL.
//! The new_with method allows the specification of an alternative url.
//!
//! # Examples
//! Create client to connect to default API endpoint.
//! ```
//! use hcaptcha_no_wasm::Client;
//! let client = Client::new();
//! ```
//!
//! Create a client and submit for verification.
//!```no_run
//! use hcaptcha_no_wasm::{Captcha, Client, Request};
//!
//! # #[tokio::main]
//! # async fn main() -> Result<(), hcaptcha_no_wasm::Error> {
//! # let secret = get_your_secret();
//! # let captcha = dummy_captcha();
//! # let request = Request::new(&secret, captcha)?; // <- returns error
//! let client = Client::new();
//! let response = client.verify(request).await?;
//! # Ok(())
//! # }
//!
//! # fn get_your_secret() -> String {
//! # "0x123456789abcde0f123456789abcdef012345678".to_string()
//! # }
//! # use rand::distributions::Alphanumeric;
//! # use rand::{thread_rng, Rng};
//! # use std::iter;
//! # fn random_response() -> String {
//! # let mut rng = thread_rng();
//! # iter::repeat(())
//! # .map(|()| rng.sample(Alphanumeric))
//! # .map(char::from)
//! # .take(100)
//! # .collect()
//! # }
//! # fn dummy_captcha() -> Captcha {
//! # Captcha::new(&random_response())
//! # .unwrap()
//! # .set_remoteip(&mockd::internet::ipv4_address())
//! # .unwrap()
//! # .set_sitekey(&mockd::unique::uuid_v4())
//! # .unwrap()
//! # }
//!
//! ```
// const CYAN: &str = "\u{001b}[35m";
// const RESET: &str = "\u{001b}[0m";
use crate::Error;
use crate::Request;
use crate::Response;
use reqwest::Url;
mod form;
use form::Form;
/// Endpoint url for the Hcaptcha siteverify API.
pub const VERIFY_URL: &str = "https://hcaptcha.com/siteverify";
/// Client to submit a request to a Hcaptcha validation endpoint.
#[cfg_attr(docsrs, allow(rustdoc::missing_doc_code_examples))]
#[derive(Debug)]
pub struct Client {
/// HTTP Client to submit request to endpoint and read the response.
client: reqwest::Client,
/// Url for the endpoint.
url: Url,
}
#[cfg_attr(docsrs, allow(rustdoc::missing_doc_code_examples))]
impl Default for Client {
fn default() -> Client {
Client::new()
}
}
#[cfg_attr(docsrs, allow(rustdoc::missing_doc_code_examples))]
impl Client {
/// Create a new Hcaptcha Client to connect with the default Hcaptcha
/// siteverify API endpoint specified in [VERIFY_URL].
///
/// # Example
/// Initialise client to connect to default API endpoint.
/// ```
/// use hcaptcha_no_wasm::Client;
/// let client = Client::new();
/// ```
/// # Panic
///
/// If the default API url constant is corrupted the function with
/// will panic.
#[allow(unknown_lints)]
#[cfg_attr(docsrs, allow(rustdoc::bare_urls))]
pub fn new() -> Client {
Client {
client: reqwest::Client::new(),
url: Url::parse(VERIFY_URL).expect("API url string corrupt"),
}
}
/// Create a new Hcaptcha Client and specify the url for the API.
///
/// Specify the url for the hcaptcha API.
///
/// # Example
/// Initialise client to connect to custom Hcaptcha API
/// ```
/// use hcaptcha_no_wasm::Client;
/// use url::Url;
///
/// let url = "https://domain.com/siteverify";
/// let _client = Client::new_with(url);
/// ```
pub fn new_with(url: &str) -> Result<Client, url::ParseError> {
Ok(Client {
client: reqwest::Client::new(),
url: Url::parse(url)?,
})
}
/// Set the url.
///
/// Specify the url for the hcaptcha API. This method is useful
/// during testing to provide a mock url.
///
/// # Example
/// Initialise client to connect to custom Hcaptcha API
/// ```no_run
/// # fn main() -> Result<(), hcaptcha_no_wasm::Error> {
/// use hcaptcha_no_wasm::Client;
/// use url::Url;
///
/// let url = "https://domain.com/siteverify";
/// let client = Client::new()
/// .set_url(url)?;
/// # Ok(())
/// # }
/// ```
pub fn set_url(mut self, url: &str) -> Result<Self, Error> {
self.url = Url::parse(url)?;
Ok(self)
}
/// Verify the client token with the Hcaptcha service API.
///
/// Call the Hcaptcha api and provide a [Request] struct.
///
/// # Inputs
///
/// Request contains the required and optional fields
/// for the Hcaptcha API. The required fields include the response
/// code to validate and the secret key.
///
/// # Outputs
///
/// This method returns [Response] if successful and [Error] if
/// unsuccessful.
///
/// # Example
///
///
/// ```no_run
/// use hcaptcha_no_wasm::{Client, Request};
/// # use hcaptcha_no_wasm::Captcha;
/// # use rand::distributions::Alphanumeric;
/// # use rand::{thread_rng, Rng};
/// # use std::iter;
/// # #[tokio::main]
/// # async fn main() -> Result<(), hcaptcha_no_wasm::Error> {
/// let secret = get_your_secret(); // your secret key
/// let captcha = get_captcha(); // user's token
///
/// let request = Request::new(&secret, captcha)?;
///
/// let client = Client::new();
///
/// let response = client.verify_client_response(request).await?;
///
/// # #[cfg(feature = "enterprise")]
/// let score = response.score();
/// # #[cfg(feature = "enterprise")]
/// let score_reasons = response.score_reason();
///
/// # Ok(())
/// # }
/// # fn get_your_secret() -> String {
/// # "0x123456789abcde0f123456789abcdef012345678".to_string()
/// # }
/// # fn random_response() -> String {
/// # let mut rng = thread_rng();
/// # iter::repeat(())
/// # .map(|()| rng.sample(Alphanumeric))
/// # .map(char::from)
/// # .take(100)
/// # .collect()
/// # }
/// # fn get_captcha() -> Captcha {
/// # Captcha::new(&random_response())
/// # .unwrap()
/// # .set_remoteip(&mockd::internet::ipv4_address())
/// # .unwrap()
/// # .set_sitekey(&mockd::unique::uuid_v4())
/// # .unwrap()
/// # }
/// ```
///
/// # Logging
///
/// If the `trace` feature is enabled a debug level span is set for the
/// method and an event logs the response.
///
#[allow(dead_code)]
#[cfg_attr(
feature = "trace",
tracing::instrument(
name = "Request verification from hcaptcha.",
skip(self),
level = "debug"
)
)]
#[deprecated(since = "3.0.0", note = "please use `verify` instead")]
pub async fn verify_client_response(self, request: Request) -> Result<Response, Error> {
let form: Form = request.into();
#[cfg(feature = "trace")]
tracing::debug!(
"The form to submit to Hcaptcha API: {:?}",
serde_urlencoded::to_string(&form).unwrap_or_else(|_| "form corrupted".to_owned())
);
let response = self
.client
.post(self.url.clone())
.form(&form)
.send()
.await?
.json::<Response>()
.await?;
#[cfg(feature = "trace")]
tracing::debug!("The response is: {:?}", response);
response.check_error()?;
Ok(response)
}
/// Verify the client token with the Hcaptcha service API.
///
/// Call the Hcaptcha api and provide a [Request] struct.
///
/// # Inputs
///
/// Request contains the required and optional fields
/// for the Hcaptcha API. The required fields include the response
/// code to validate and the secret key.
///
/// # Outputs
///
/// This method returns [Response] if successful and [Error] if
/// unsuccessful.
///
/// # Example
///
///
/// ```no_run
/// use hcaptcha_no_wasm::{Client, Request};
/// # use hcaptcha_no_wasm::Captcha;
/// # use rand::distributions::Alphanumeric;
/// # use rand::{thread_rng, Rng};
/// # use std::iter;
/// # #[tokio::main]
/// # async fn main() -> Result<(), hcaptcha_no_wasm::Error> {
/// let secret = get_your_secret(); // your secret key
/// let captcha = get_captcha(); // user's token
///
/// let request = Request::new(&secret, captcha)?;
///
/// let client = Client::new();
///
/// let response = client.verify(request).await?;
///
/// # #[cfg(feature = "enterprise")]
/// let score = response.score();
/// # #[cfg(feature = "enterprise")]
/// let score_reasons = response.score_reason();
///
/// # Ok(())
/// # }
/// # fn get_your_secret() -> String {
/// # "0x123456789abcde0f123456789abcdef012345678".to_string()
/// # }
/// # fn random_response() -> String {
/// # let mut rng = thread_rng();
/// # iter::repeat(())
/// # .map(|()| rng.sample(Alphanumeric))
/// # .map(char::from)
/// # .take(100)
/// # .collect()
/// # }
/// # fn get_captcha() -> Captcha {
/// # Captcha::new(&random_response())
/// # .unwrap()
/// # .set_remoteip(&mockd::internet::ipv4_address())
/// # .unwrap()
/// # .set_sitekey(&mockd::unique::uuid_v4())
/// # .unwrap()
/// # }
/// ```
///
/// # Logging
///
/// If the `trace` feature is enabled a debug level span is set for the
/// method and an event logs the response.
///
#[allow(dead_code)]
#[cfg_attr(
feature = "trace",
tracing::instrument(
name = "Request verification from hcaptcha.",
skip(self),
level = "debug"
)
)]
pub async fn verify(self, request: Request) -> Result<Response, Error> {
let form: Form = request.into();
#[cfg(feature = "trace")]
tracing::debug!(
"The form to submit to Hcaptcha API: {:?}",
serde_urlencoded::to_string(&form).unwrap_or_else(|_| "form corrupted".to_owned())
);
let response = self
.client
.post(self.url.clone())
.form(&form)
.send()
.await?
.json::<Response>()
.await?;
#[cfg(feature = "trace")]
tracing::debug!("The response is: {:?}", response);
response.check_error()?;
Ok(response)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Code, Error};
use chrono::{TimeDelta, Utc};
use claims::{assert_err, assert_ok};
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
use serde_json::json;
use std::iter;
#[cfg(feature = "trace")]
use tracing_test::traced_test;
use wiremock::matchers::{body_string, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
// const RED: &str = "\t\u{001b}[31m";
// const GREEN: &str = "\t\u{001b}[32m";
// const CYAN: &str = "\t\u{001b}[36m";
// const RESET: &str = "\t\u{001b}[0m";
fn random_string(characters: usize) -> String {
let mut rng = thread_rng();
iter::repeat(())
.map(|()| rng.sample(Alphanumeric))
.map(char::from)
.take(characters)
.collect()
}
#[tokio::test]
#[cfg_attr(feature = "trace", traced_test)]
async fn hcaptcha_mock_verify() {
let token = random_string(100);
let secret = format!("0x{}", hex::encode(random_string(20)));
let request = Request::new_from_response(&secret, &token).unwrap();
let expected_body = format!("response={}&secret={}", &token, &secret);
let timestamp = Utc::now()
.checked_sub_signed(TimeDelta::try_minutes(10).unwrap())
.unwrap()
.to_rfc3339();
let response_template = ResponseTemplate::new(200).set_body_json(json!({
"success": true,
"challenge_ts": timestamp,
"hostname": "test-host",
}));
let mock_server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/siteverify"))
.and(body_string(&expected_body))
.respond_with(response_template)
.mount(&mock_server)
.await;
let uri = format!("{}{}", mock_server.uri(), "/siteverify");
let client = Client::new_with(&uri).unwrap();
let response = client.verify(request).await;
assert_ok!(&response);
let response = response.unwrap();
assert!(&response.success());
assert_eq!(&response.timestamp().unwrap(), ×tamp);
#[cfg(feature = "trace")]
assert!(logs_contain("Hcaptcha API"));
#[cfg(feature = "trace")]
assert!(logs_contain("The response is"));
}
#[tokio::test]
#[cfg_attr(feature = "trace", traced_test)]
async fn hcaptcha_mock_verify_not_found() {
let token = random_string(100);
let secret = format!("0x{}", hex::encode(random_string(20)));
let request = Request::new_from_response(&secret, &token).unwrap();
let expected_body = format!("response={}&secret={}", &token, &secret);
let response_template = ResponseTemplate::new(404);
let mock_server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/siteverify"))
.and(body_string(&expected_body))
.respond_with(response_template)
.mount(&mock_server)
.await;
let uri = format!("{}{}", mock_server.uri(), "/siteverify");
let client = Client::new_with(&uri).unwrap();
let response = client.verify(request).await;
assert_err!(&response);
}
#[tokio::test]
#[cfg_attr(feature = "trace", traced_test)]
async fn hcaptcha_mock_verify_client_response() {
let token = random_string(100);
let secret = format!("0x{}", hex::encode(random_string(20)));
let request = Request::new_from_response(&secret, &token).unwrap();
let expected_body = format!("response={}&secret={}", &token, &secret);
let timestamp = Utc::now()
.checked_sub_signed(TimeDelta::try_minutes(10).unwrap())
.unwrap()
.to_rfc3339();
let response_template = ResponseTemplate::new(200).set_body_json(json!({
"success": true,
"challenge_ts": timestamp,
"hostname": "test-host",
}));
let mock_server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/siteverify"))
.and(body_string(&expected_body))
.respond_with(response_template)
.mount(&mock_server)
.await;
let uri = format!("{}{}", mock_server.uri(), "/siteverify");
let client = Client::new_with(&uri).unwrap();
#[allow(deprecated)]
let response = client.verify_client_response(request).await;
assert_ok!(&response);
let response = response.unwrap();
assert!(&response.success());
assert_eq!(&response.timestamp().unwrap(), ×tamp);
#[cfg(feature = "trace")]
assert!(logs_contain("Hcaptcha API"));
#[cfg(feature = "trace")]
assert!(logs_contain("The response is"));
}
#[tokio::test]
#[cfg_attr(feature = "trace", traced_test)]
async fn hcaptcha_mock_verify_client_response_not_found() {
let token = random_string(100);
let secret = format!("0x{}", hex::encode(random_string(20)));
let request = Request::new_from_response(&secret, &token).unwrap();
let expected_body = format!("response={}&secret={}", &token, &secret);
let response_template = ResponseTemplate::new(404);
let mock_server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/siteverify"))
.and(body_string(&expected_body))
.respond_with(response_template)
.mount(&mock_server)
.await;
let uri = format!("{}{}", mock_server.uri(), "/siteverify");
let client = Client::new_with(&uri).unwrap();
#[allow(deprecated)]
let response = client.verify_client_response(request).await;
assert_err!(&response);
}
#[tokio::test]
#[cfg_attr(feature = "trace", traced_test)]
async fn hcaptcha_mock_with_remoteip() {
let token = random_string(100);
let secret = format!("0x{}", hex::encode(random_string(20)));
let remoteip = mockd::internet::ipv4_address();
let request = Request::new_from_response(&secret, &token)
.unwrap()
.set_remoteip(&remoteip)
.unwrap();
let expected_body = format!(
"response={}&remoteip={}&secret={}",
&token, &remoteip, &secret
);
let timestamp = Utc::now()
.checked_sub_signed(TimeDelta::try_minutes(10).unwrap())
.unwrap()
.to_rfc3339();
let response_template = ResponseTemplate::new(200).set_body_json(json!({
"success": true,
"challenge_ts": timestamp,
"hostname": "test-host",
}));
let mock_server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/siteverify"))
.and(body_string(&expected_body))
.respond_with(response_template)
.mount(&mock_server)
.await;
let uri = format!("{}{}", mock_server.uri(), "/siteverify");
let client = Client::new_with(&uri).unwrap();
let response = client.verify(request).await;
assert_ok!(&response);
let response = response.unwrap();
assert!(&response.success());
assert_eq!(&response.timestamp().unwrap(), ×tamp);
#[cfg(feature = "trace")]
assert!(logs_contain("Hcaptcha API"));
#[cfg(feature = "trace")]
assert!(logs_contain("The response is"));
}
#[tokio::test]
#[cfg_attr(feature = "trace", traced_test)]
async fn hcaptcha_mock_with_sitekey() {
let token = random_string(100);
let secret = format!("0x{}", hex::encode(random_string(20)));
let sitekey = mockd::unique::uuid_v4();
let request = Request::new_from_response(&secret, &token)
.unwrap()
.set_sitekey(&sitekey)
.unwrap();
let expected_body = format!(
"response={}&sitekey={}&secret={}",
&token, &sitekey, &secret
);
let timestamp = Utc::now()
.checked_sub_signed(TimeDelta::try_minutes(10).unwrap())
.unwrap()
.to_rfc3339();
let response_template = ResponseTemplate::new(200).set_body_json(json!({
"success": true,
"challenge_ts": timestamp,
"hostname": "test-host",
}));
let mock_server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/siteverify"))
.and(body_string(&expected_body))
.respond_with(response_template)
.mount(&mock_server)
.await;
let uri = format!("{}{}", mock_server.uri(), "/siteverify");
let client = Client::new_with(&uri).unwrap();
let response = client.verify(request).await;
assert_ok!(&response);
let response = response.unwrap();
assert!(&response.success());
assert_eq!(&response.timestamp().unwrap(), ×tamp);
#[cfg(feature = "trace")]
assert!(logs_contain("Hcaptcha API"));
#[cfg(feature = "trace")]
assert!(logs_contain("The response is"));
}
#[test]
fn test_success_response() {
let api_response = json!({
"success": true,
"challenge_ts": "2020-11-11T23:27:00Z",
"hostname": "my-host.ie",
"credit": true,
"error-codes": [],
"score": null,
"score_reason": [],
});
let response: Response = serde_json::from_value(api_response).unwrap();
assert!(response.success());
assert_eq!(
response.timestamp(),
Some("2020-11-11T23:27:00Z".to_owned())
);
assert_eq!(response.hostname(), Some("my-host.ie".to_owned()));
}
#[test]
fn test_error_response() {
let api_response = json!({
"success": false,
"challenge_ts": null,
"hostname": null,
"credit": null,
"error-codes": ["missing-input-secret", "foo"],
"score": null,
"score_reason": [],
});
let response: Response = serde_json::from_value(api_response).unwrap();
assert!(!response.success());
assert!(response.error_codes().is_some());
if let Some(hash_set) = response.error_codes() {
assert_eq!(hash_set.len(), 2);
assert!(hash_set.contains(&Code::MissingSecret));
assert!(hash_set.contains(&Code::Unknown("foo".to_owned())));
}
}
#[test]
fn test_hcaptcha_client_default_initialization() {
let client = Client::default();
assert!(matches!(client, Client { .. }));
}
#[test]
fn test_hcaptcha_client_default_calls_new() {
// Assuming Client::new() has some side effect or state change
// that can be checked to ensure it was called.
let client = Client::default();
// Here we would check the side effect or state change
// For example, if new() sets a specific field, we would assert that field's value
let expected_value = Url::parse(VERIFY_URL).unwrap();
assert!(client.url == expected_value);
}
#[test]
fn test_set_url_with_valid_url() {
let client = Client::default();
let result = client.set_url("https://example.com");
assert!(result.is_ok());
assert_eq!(result.unwrap().url.as_str(), "https://example.com/");
}
#[test]
fn test_set_url_with_invalid_url() {
let client = Client::default();
let result = client.set_url("invalid-url");
assert!(result.is_err());
match result {
Err(Error::Url(_)) => (),
_ => panic!("Expected UrlParseError"),
}
}
#[test]
fn test_set_url_with_empty_string() {
let client = Client::default();
let result = client.set_url("");
assert!(result.is_err());
match result {
Err(Error::Url(_)) => (),
_ => panic!("Expected UrlParseError"),
}
}
}