AWS WAF and other CAPTCHAs
How to solve CAPTCHAs from Rust
Rust suits long running crawlers and monitoring daemons, and the CAPTCHA API fits neatly into its async world. This guide builds a small typed client on reqwest, serde and tokio that works with every supported task type.
The design
The client has three parts: serde types for the API's replies, an error enum that keeps the API's error codes, and an async solve method that creates a task and polls until it is ready. The task itself stays a serde_json::Value, built with the json! macro, so one client handles reCAPTCHA, Turnstile, AWS WAF, image text and every other type without a struct per type. The solution comes back as a Value too, and the caller picks the field it needs.
Dependencies
Add these to Cargo.toml. The versions are the current major lines at the time of writing; check crates.io for newer releases.
[dependencies]
reqwest = { version = "0.12", features = ["json"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] }
thiserror = "1"
reqwest's json feature adds .json() for request bodies and responses. thiserror is optional but makes the error enum short; newer major versions work the same way for this use.
Reply types and errors
The API returns camelCase keys, so rename_all maps them onto Rust names. Every field is optional or defaulted, because the same shape is used for success and error replies.
use serde::Deserialize;
use serde_json::Value;
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Reply {
#[serde(default)]
error_id: u32,
error_code: Option<String>,
error_description: Option<String>,
task_id: Option<String>,
status: Option<String>,
solution: Option<Value>,
}
#[derive(Debug, thiserror::Error)]
pub enum SolveError {
#[error("http: {0}")]
Http(#[from] reqwest::Error),
#[error("api {code}: {detail}")]
Api { code: String, detail: String },
#[error("task {0} failed (not charged)")]
Failed(String),
#[error("task {0} timed out")]
Timeout(String),
}
Keeping the API code as a string in SolveError::Api lets the caller match on values such as ERROR_ZERO_BALANCE or ERROR_CAPTCHA_UNSOLVABLE and decide whether a retry makes sense.
The client
use std::time::Duration;
use serde_json::json;
pub struct Solver { http: reqwest::Client, key: String }
impl Solver {
pub fn new(key: impl Into<String>) -> Result<Self, SolveError> {
let http = reqwest::Client::builder().timeout(Duration::from_secs(30)).build()?;
Ok(Self { http, key: key.into() })
}
async fn post(&self, method: &str, mut body: Value) -> Result<Reply, SolveError> {
body["clientKey"] = json!(self.key);
let url = format!("https://gatesolver.com/{method}");
let reply: Reply = self.http.post(url).json(&body).send().await?.json().await?;
if reply.error_id != 0 {
return Err(SolveError::Api {
code: reply.error_code.unwrap_or_default(),
detail: reply.error_description.unwrap_or_default(),
});
}
Ok(reply)
}
pub async fn solve(&self, task: Value, every: Duration) -> Result<Value, SolveError> {
let made = self.post("createTask", json!({ "task": task })).await?;
let id = made.task_id.unwrap_or_default();
let rounds = 125 / every.as_secs().max(1);
for _ in 0..rounds {
tokio::time::sleep(every).await;
let r = self.post("getTaskResult", json!({ "taskId": id })).await?;
match r.status.as_deref() {
Some("ready") => return Ok(r.solution.unwrap_or(Value::Null)),
Some("failed") => return Err(SolveError::Failed(id)),
_ => {}
}
}
Err(SolveError::Timeout(id))
}
}
One reqwest::Client is created per solver and reused for every call, which keeps connections pooled. The poll interval is a parameter: pass three seconds for token tasks and one second for image tasks. The round count is derived from it so the loop always ends a little after 120 seconds, when unsolved tasks are marked failed.
Running tasks concurrently
The API has no limit on concurrent tasks, so a Rust program can wait on several at once. tokio::join! runs a fixed set; for a dynamic list use futures::future::join_all or a JoinSet.
#[tokio::main]
async fn main() -> Result<(), SolveError> {
let key = std::env::var("GS_API_KEY").unwrap_or_else(|_| "YOUR_API_KEY".into());
let solver = Solver::new(key)?;
let slow = Duration::from_secs(3);
let turnstile = json!({ "type": "AntiTurnstileTaskProxyLess",
"websiteURL": "https://app.example.io/signup", "websiteKey": "0x4AAAAAAAxxxxxxxxxxxx" });
let waf = json!({ "type": "AntiAwsWafTaskProxyLess",
"websiteURL": "https://store.example.io/catalog?sort=new" });
let (a, b) = tokio::join!(solver.solve(turnstile, slow), solver.solve(waf, slow));
println!("turnstile token: {}", a?["token"]);
println!("aws-waf-token: {}", b?["cookie"]);
Ok(())
}
Indexing a Value with a missing key returns Null instead of panicking, so printing an unexpected shape shows null rather than crashing. For production code, use .get("token").and_then(Value::as_str) and handle the None case.
Retries that respect the error codes
Retry only what can succeed on a second try. A small wrapper does it:
pub async fn solve_retry(s: &Solver, task: Value, every: Duration) -> Result<Value, SolveError> {
let mut left = 3;
loop {
match s.solve(task.clone(), every).await {
Err(SolveError::Api { code, .. })
if left > 0 && (code == "ERROR_CAPTCHA_UNSOLVABLE" || code == "ERROR_SERVICE_UNAVAILABLE") => {}
Err(SolveError::Failed(_)) if left > 0 => {}
other => return other,
}
left -= 1;
tokio::time::sleep(Duration::from_secs(2)).await;
}
}
Unsolvable tasks, failed tasks and service errors are free, so a couple of retries cost nothing. Codes such as ERROR_KEY_DENIED_ACCESS, ERROR_ZERO_BALANCE or ERROR_INVALID_TASK_DATA return immediately, because no retry would change them.
Cancellation and deadlines
Async Rust makes it easy to put an outer deadline on a solve. Wrapping the call in tokio::time::timeout(Duration::from_secs(60), solver.solve(task, slow)) drops the future when the minute is up, which stops your side from polling. It does not cancel the task on the server: a task that gets solved after you stopped listening is still charged, while one that stays unsolved expires for free after 120 seconds. So pick deadlines with that in mind. A short outer timeout is useful when the token would be too old to use anyway, for example when a form session on the target site expires after a minute. In other cases, let the built in loop run to its natural end.
The same rule applies to graceful shutdown. When your crawler receives a stop signal, it is fine to drop in flight solves, but log their task ids so that a later look at the account history makes sense.
Testing without spending
Unit tests should not create real tasks. Put the HTTP part behind a small trait, or point the client at a local mock server, and feed it canned replies: one processing, then ready with a fake solution, plus an error reply with errorId 1. That covers the parsing, the error enum and the retry rules. For one live check, call getBalance in an ignored integration test; it is free and proves the key and network path work.
Fitting it into a crawler
- Share one
Solverbehind anArcacross tasks in your crawler; reqwest clients are cheap to clone and safe to share. - Keep total polling under 600 requests per minute per key. With a three second interval that means up to about 30 tasks in flight at once; poll less often or use a semaphore if you need more.
- Read the key from the environment or a secrets file. Never compile it into the binary.
- Log the task id from
SolveErrorvalues; it is the quickest way to trace a problem.
The API docs list the fields of every task type, and the task polling glossary entry explains the timing rules this client follows. For comparison, the C++ guide builds the same client on libcurl.
Common questions
Which async runtime does this client need?
tokio, because reqwest runs on it. The example enables the macros, multi thread runtime and time features.
Why keep the task as serde_json::Value?
It lets one client send any task type without a struct per type. You can add typed structs later if you prefer.
Can I use reqwest blocking instead?
Yes, with the blocking feature and std::thread::sleep, but async lets one thread wait on many tasks at once.
How many tasks can run at the same time?
The API sets no cap on tasks in flight. Keep total requests under 600 per minute per key by tuning the poll interval.
Is there an official Rust crate?
No SDK packages are offered. The client on this page is around a hundred lines and covers every task type.
Keep reading
- API docscreateTask, getTaskResult, getBalance, error codes and the in.php format.
- Task pollingAsking getTaskResult for an answer on a timer: sensible intervals for token and image tasks, and when to give up.
- Solve CAPTCHAs from C++A compact C++17 client on libcurl and nlohmann/json, with RAII handles, typed exceptions and one polling loop for any task.
- Error handling for CAPTCHA APIsSort every CAPTCHA API error into retry, fix or stop, follow those rules in code, and know which outcomes cost nothing.