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
//! captval
//!
//! # Build the request and verify
//!
//! Initialise a client using the [`Client`] builder to submit requests to the captval service validation.
//!
//! For each request build the request using the [`Request`] builder.
//!
//! Submit the request using the [`Client`] struct's [`Client::verify`] method.
//!
//! A [`Response`] is returned if the validation was successful or the method fails with a set of [`Error`] [`Code`]s if the validation failed.
//!
//! ## Examples
//!
//! ### Enterprise example (requires `enterprise` feature)
//!
//! Token needs to be supplied by the client.
//! This example will fail as a client-provided token is not used.
//! ```no_run
//! use captval::{Client, Request};
//! # use itertools::Itertools;
//!
//! # #[tokio::main]
//! # async fn main() -> Result<(), captval::Error> {
//! # let secret = "0x123456789abcde0f123456789abcdef012345678".to_string();
//! # let captcha = Captcha::new(&random_response())?
//! # .set_remoteip(&mockd::internet::ipv4_address())?
//! # .set_sitekey(&mockd::unique::uuid_v4())?;
//! # let remoteip = mockd::internet::ipv4_address();
//!
//! let request = Request::new(&secret, captcha)?
//! .set_remoteip(&remoteip)?;
//!
//! let client = Client::new();
//!
//! let response = client.verify(request).await?;
//!
//!# #[cfg(feature = "enterprise")]
//! let score = match &response.score() {
//! Some(v) => *v,
//! None => 0.0,
//! };
//!
//!# #[cfg(feature = "enterprise")]
//! let score_reasons = match &response.score_reason() {
//! Some(v) => v.iter().join(", "),
//! None => "".to_owned(),
//! };
//!
//!# #[cfg(feature = "enterprise")]
//! println!("\tScore: {:?}\n\tReasons: {:?}", score, score_reasons);
//! # Ok(())
//! # }
//! # use captval::Captcha;
//! # use rand::distr::Alphanumeric;
//! # use rand::{rng, Rng};
//! # use std::iter;
//! # fn random_response() -> String {
//! # let mut rng = rng();
//! # iter::repeat(())
//! # .map(|()| rng.sample(Alphanumeric))
//! # .map(char::from)
//! # .take(100)
//! # .collect()
//! # }
//! ```
//!
//! ### Lambda backend implementation.
//!
//! See examples for more detail.
//!
//! ``` no_run
//! # use lambda_runtime::Error;
//! # use tracing_bunyan_formatter::{BunyanFormattingLayer, JsonStorageLayer};
//! # use tracing_log::LogTracer;
//! # use tracing_subscriber::layer::SubscriberExt;
//! # use tracing_subscriber::{EnvFilter, Registry};
//! #
//! mod handler {
//! # mod error {
//! # use thiserror::Error;
//! # #[derive(Error, Debug)]
//! # pub enum ContactError {
//! # #[error("{0}")]
//! # Hcaptcha(#[from] captval::Error),
//! # #[error("{0}")]
//! # Json(#[from] serde_json::Error),
//! # }
//! # }
//! #
//! # mod param {
//! # use super::error::ContactError;
//! # #[cfg(feature = "trace")]
//! # use tracing::instrument;
//! # #[cfg(feature = "trace")]
//! # #[instrument(name = "get the secret key from parameter store")]
//! # pub async fn get_parameter(key: &str) -> Result<String, ContactError> {
//! # // Extract the secret key from your parameter store
//! # Ok("0x123456789abcedf0123456789abcedf012345678".to_owned())
//! # }
//! # #[cfg(not(feature = "trace"))]
//! # pub async fn get_parameter(key: &str) -> Result<String, ContactError> {
//! # // Extract the secret key from your parameter store
//! # Ok("0x123456789abcedf0123456789abcedf012345678".to_owned())
//! # }
//! # }
//! #
//! # mod record {
//! # use super::error::ContactError;
//! # use super::send::ContactForm;
//! # #[cfg(feature = "trace")]
//! # use tracing::instrument;
//! # #[cfg(feature = "trace")]
//! # #[instrument(
//! # name = "Write record to database"
//! # skip(form)
//! # fields(email = %form.email)
//! # )]
//! # pub async fn write(form: &ContactForm) -> Result<(), ContactError> {
//! # // Write the contact form data to dynamodb
//! # Ok(())
//! # }
//! # #[cfg(not(feature = "trace"))]
//! # pub async fn write(form: &ContactForm) -> Result<(), ContactError> {
//! # // Write the contact form data to dynamodb
//! # Ok(())
//! # }
//! # }
//! #
//! # mod send {
//! # use super::error::ContactError;
//! # use serde::{Deserialize, Serialize};
//! # #[cfg(feature = "trace")]
//! # use tracing::instrument;
//! #
//! # #[derive(Deserialize, Serialize, Clone, Debug, Default)]
//! # pub struct ContactForm {
//! # #[serde(default)]
//! # pub name: String,
//! # #[serde(default)]
//! # pub phone: String,
//! # #[serde(default)]
//! # pub email: String,
//! # #[serde(default)]
//! # pub message: String,
//! # #[serde(default)]
//! # pub page: String,
//! # #[serde(default)]
//! # pub site: String,
//! # }
//! #
//! # #[cfg(feature = "trace")]
//! # #[instrument(name = "send notification to info mailbox", skip(_contact_form))]
//! # pub async fn notify_office(
//! # _contact_form: &ContactForm,
//! # ) -> Result<(), ContactError> {
//! # // Construct email and send message to the office info mailbox
//! #
//! # Ok(())
//! # }
//! #
//! # #[cfg(not(feature = "trace"))]
//! # pub async fn notify_office(
//! # _contact_form: &ContactForm,
//! # ) -> Result<(), ContactError> {
//! # // Construct email and send message to the office info mailbox
//! #
//! # Ok(())
//! # }
//! #
//! # #[cfg(feature = "trace")]
//! # #[instrument(name = "Send notification to the contact", skip(_contact_form))]
//! # pub async fn notify_contact(
//! # _contact_form: &ContactForm,
//! # ) -> Result<(), ContactError> {
//! # // Construct and send email to the contact
//! #
//! # Ok(())
//! # }
//! # #[cfg(not(feature = "trace"))]
//! # pub async fn notify_contact(
//! # _contact_form: &ContactForm,
//! # ) -> Result<(), ContactError> {
//! # // Construct and send email to the contact
//! #
//! # Ok(())
//! # }
//! # }
//!
//! # const HCAPTCHA_SECRET: &str = "/captval/secret";
//! #
//! # use captval::{Captcha, Client, Request};
//! # use lambda_runtime::{Context, Error};
//! # use send::ContactForm;
//! # use serde::{Deserialize, Serialize};
//! # use tokio::join;
//! # #[cfg(feature = "trace")]
//! # use tracing::{debug, error};
//! #
//! # #[derive(Deserialize, Serialize, Clone, Debug, Default)]
//! # pub struct CustomEvent {
//! # body: Option<String>,
//! # }
//! #
//! # #[derive(Deserialize, Serialize, Clone, Default)]
//! # pub struct Recaptcha {
//! # #[serde(rename = "reCaptchaResponse")]
//! # re_captcha_response: String,
//! # }
//! #
//! # #[derive(Serialize, Clone, Debug, PartialEq)]
//! # pub struct CustomOutput {
//! # #[serde(rename = "isBase64Encoded")]
//! # is_base64_encoded: bool,
//! # #[serde(rename = "statusCode")]
//! # status_code: u16,
//! # body: String,
//! # }
//! #
//! # impl CustomOutput {
//! # fn new(status_code: u16, body: String) -> CustomOutput {
//! # CustomOutput {
//! # is_base64_encoded: false,
//! # status_code,
//! # body,
//! # }
//! # }
//! # }
//! #
//! #
//! pub async fn my_handler(e: CustomEvent, _c: Context) -> Result<CustomOutput, Error> {
//! # #[cfg(feature = "trace")]
//! debug!("The event logged is: {:?}", e);
//!
//! let body_str = e.body.unwrap_or_else(|| "".to_owned());
//! let captcha: Captcha = serde_json::from_str(&body_str)?;
//!
//! let captval_secret = param::get_parameter(HCAPTCHA_SECRET).await?;
//!
//! let request = Request::new(&captval_secret,
//! captcha)?;
//!
//! let client = Client::new();
//! let _response = client.verify(request).await?;
//!
//! let contact_form: ContactForm = serde_json::from_str(&body_str)?;
//!
//! let notify_office_fut = send::notify_office(&contact_form);
//! let notify_contact_fut = send::notify_contact(&contact_form);
//! let write_fut = record::write(&contact_form);
//!
//! let (notify_office, notify_contact, write) =
//! join!(notify_office_fut, notify_contact_fut, write_fut);
//!
//! if let Err(e) = notify_contact {
//!# #[cfg(feature = "trace")]
//! error!("Notification to the contact not sent: {}", e);
//! return Err("Notification not sent".into());
//! }
//!
//! if let Err(e) = notify_office {
//!# #[cfg(feature = "trace")]
//! error!("Notification to the office not sent: {}", e);
//! return Err("Info not sent to office".into());
//! }
//!
//! if let Err(e) = write {
//!# #[cfg(feature = "trace")]
//! error!("Contact information not written to database: {}", e);
//! }
//!
//! Ok(CustomOutput::new(
//! 200,
//! format!("{}, thank you for your contact request.", contact_form.name),
//! ))
//! }
//! }
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Error> {
//! # LogTracer::init()?;
//! #
//! # let app_name = concat!(env!("CARGO_PKG_NAME"), "-", env!("CARGO_PKG_VERSION")).to_string();
//! # let (non_blocking_writer, _guard) = tracing_appender::non_blocking(std::io::stdout());
//! # let bunyan_formatting_layer = BunyanFormattingLayer::new(app_name, non_blocking_writer);
//! # let subscriber = Registry::default()
//! # .with(EnvFilter::new(
//! # std::env::var("RUST_LOG").unwrap_or_else(|_| "INFO".to_owned()),
//! # ))
//! # .with(JsonStorageLayer)
//! # .with(bunyan_formatting_layer);
//! # #[cfg(feature = "trace")]
//! # tracing::subscriber::set_global_default(subscriber)?;
//!
//! lambda_runtime::run(lambda_runtime::handler_fn(handler::my_handler)).await?;
//! Ok(())
//! }
//!
//! ```
//! ## Feature Flags
//!
//! The default library includes extended validation for the secret field and use of rustls TLS as the TLS backend.
//! Disable this validation by setting default-features = false and enable rustls with features=["nativetls-backend"].
//!
//! ```toml
//! [dependency]
//! captval = { version = "0.1.2", default-features = false }
//! ```
//!
//! The following feature flags are available:
//! * `enterprise` - Enable methods to access enterprise service fields in the `Response`
//! * `ext` - Enables extended validation of secret
//! * `trace` - Enables tracing instrumentation on all functions. Traces are logged at the debug level. The value of the secret is not logged.
//! * `nativetls-backend` - Enables native-tls backend in reqwests
//! * `rustls-backend` - Enables rustls backend in reqwests
//!
//! ## Rust Version
//!
//! This version of captval requires Rust v1.82 or later.
pub use Captcha;
pub use Client;
pub use Error;
pub use Request;
pub use Response;
pub use Remoteip;
pub use crateCaptval;
pub use *;
pub use *;