Dregs Rust SDK
The official Rust client for Dregs, which scores the users of your application for fraud and abuse across four categories: humanity, authenticity, uniqueness, and behavior.
Send events from your backend, read back the scores and the observations behind them.
The client is async and runs on Tokio. Rust 1.85 or newer.
Getting started
You need the secret key from an API credential, which you will find under Settings → Credentials
in the Dregs dashboard. It starts with sk_. The pk_ public key is for the browser tracker and cannot
read identities or scores.
use Client;
let client = new?;
Client::from_env() reads the key from DREGS_SECRET_KEY for you, which is usually all you need. The
client holds a connection pool: build one at startup and keep it, rather than making a new one per
request. Cloning is cheap and every clone shares the pool, so put it in your application state and hand
clones to handlers and tasks freely.
Tracking events
use Event;
use json;
client
.track
.await?;
The second argument to Event::new is your own id for the user — the same one you pass to
dregs.identify() in the browser tracker, and the one you look scores up by. It is required: a
server-side event carries no device signature, so the identity is the only thing tying the event to a
user.
identity_data carries attributes of the user rather than the event. The analyzers lean on these
heavily, so send them whenever you have them. Name the keys the way your application already does and
map them to Dregs's canonical fields under Settings → Mappings; the same goes for event names.
data and identity_data take anything that serializes to a JSON object: a json! value, a map, or
your own #[derive(Serialize)] struct.
Groups
If your application groups users into organizations, teams, workspaces, or the like, pass the groups the
user is acting in. Dregs records each group and makes the identity a member of it. Each group has your
own id, a type that is your own name for the kind of group ("organization" when empty, and what
Group::organization gives you), and optional data that Dregs merges into the group, so later events can
send the type and id alone. Dregs normalizes types to lower_snake_case, so
ParentCompany and parent-company are the same type, and an event can carry one group of each type.
use ;
client
.track
.await?;
Idempotency
Every event is sent with an id, which makes ingestion idempotent: reposting the same id returns the original event instead of recording a second one. Pass the id your application already has, and a retry after a timeout can never double-count.
client
.track
.await?;
When you omit it the SDK generates one, which is what makes its own retries safe.
What comes back
let result = client.track.await?;
result.accepted; // true when Dregs recorded the event
result.id; // the event's id
accepted() is false in the uncommon case where Dregs accepts the request without recording an
event. Failures that are yours to act on come back as errors instead — see Errors.
Reading scores
let scores = client.identities.scores.await?;
scores.humanity; // Some(85)
scores.authenticity; // Some(72)
scores.uniqueness; // Some(91)
scores.behavior; // Some(68)
This is the cheap read and the one most integrations want. A category Dregs has not scored yet reads as
None, and a brand-new identity comes back empty. Scores also dereferences to a slice of Score, so
you can iterate it.
Scoring is asynchronous. Scores appear moments after the events that move them, not in the same
breath, so read them at a decision point rather than immediately after a track() call.
if scores.authenticity.is_some_and
Seeing exactly why
The scores are the summary; the observations are the evidence. When you need to show or log why an identity scored the way it did, ask for the analysis.
let analysis = client.identities.analysis.await?;
for observation in analysis.observations
Each observation carries the analyzer that produced it, a value from 0.0 (suspicious) to 1.0
(legitimate), a confidence, a weight, and the counts behind the finding in metadata. analysis()
returns a NotFound error until the identity has been analyzed at least once.
The whole identity
let identity = client.identities.get.await?;
identity.display_email; // Some("ada@example.com")
identity.humanity_score; // Some(85)
identity.badges; // [Badge { name: Some("Account Takeover Suspected"), .. }]
identity.data; // every attribute you have sent
Forcing a rescore
client.identities.analyze.await?;
This queues the work and returns; it does not wait for the cycle to finish. Dregs rescores on its own as events arrive, so you rarely need this outside of a support or backfill flow.
History, links, and past cycles
let history = client.identities.history.await?;
for entry in &history
// A past cycle's observations.
if let Some = history.last.and_then
for link in client.identities.links.await?
Disregarding an identity
Leave your own staff and test accounts out of scoring and escalations:
use IdentityUpdate;
client
.identities
.update
.await?;
IdentityUpdate::attributes merges attributes into the identity the way identity_data on an event
does. An update that sets nothing is refused before any request.
Asking for a review
When a score looks wrong, Dregs's AI reviewer will look over the analysis and say why. The review runs in
the background, so read it back later with reviews().
let review = client
.identities
.review
.await?;
review.status; // Some("PENDING"), then Some("FINISHED")
Listing and paging
Every namespace with a list() returns one Page at a time, numbered from 0, and a list_all() that
walks every page for you as a Stream.
Each list() takes a builder for its filters and paging:
use ;
use TryStreamExt; // or futures::TryStreamExt
let page = client
.identities
.list
.await?;
page.total_elements; // how many match in all
page.has_next; // whether another page follows
let mut identities = client.identities.list_all;
while let Some = identities.try_next.await?
Filters you leave out are not sent. A page holds at most 100 items. Page dereferences to a slice of its
items, and the stream owns a clone of the client, so it can be moved into a spawned task. A page that
fails to load ends the stream with that error.
Groups
track() records groups and memberships as events arrive. The groups() namespace reads them back, and
keeps Dregs in step when something changes outside an event, such as a user leaving a team:
use ;
client
.groups
.create
.await?;
let group = client.groups.get.await?;
group.identity_count; // Some(12)
client
.groups
.update
.await?;
client.groups.add_member.await?;
client.groups.remove_member.await?;
let mut teams = client
.groups
.list_all;
while let Some = teams.try_next.await?
create() takes the same Group builder as track(), and merges into the group when one with the same
type and id already exists, so it is safe to call on every sync. The type defaults to "organization".
The groups Dregs returns are TrackedGroups, to keep them apart from the builder.
Events, devices, and escalations
use ;
let mut events = client.events.list_all;
while let Some = events.try_next.await?
client.devices.update.await?; // disregard, e.g. a shared office machine
let mut escalations = client.escalations.list_all;
while let Some = escalations.try_next.await?
let summary = client.escalations.summary.await?; // open, acknowledged, and closed counts
The events Dregs returns are TrackedEvents, to keep them apart from the Event builder track() takes.
Errors
Every call returns dregs::Result<T>, whose error is dregs::Error. When Dregs answered with an error,
error.kind() says which:
use ApiErrorKind;
match client.track.await
| Error | When |
|---|---|
ApiErrorKind::BadRequest |
400, the event was malformed |
ApiErrorKind::Authentication |
401, the secret key was not recognized |
ApiErrorKind::QuotaExceeded |
402, the account is over its monthly event limit |
ApiErrorKind::PermissionDenied |
403, the credential may not do this |
ApiErrorKind::NotFound |
404, no such identity, group, event, device, or escalation, or no analysis yet |
ApiErrorKind::RateLimited |
429, too many requests |
ApiErrorKind::Server |
5xx |
Error::Timeout |
the request timed out |
Error::Connection |
the request never reached Dregs |
Error::InvalidArgument |
refused before sending, such as an empty identity or an update that sets nothing |
The API errors are Error::Api, carrying an ApiError with the status, message, parsed body, and
request_id. When the error body carries no message, the message is the HTTP reason phrase, such as
Not Found.
Retries
Connection failures, timeouts, 429s, and 5xx are retried automatically with exponential backoff and
jitter, honouring Retry-After when the server sends one. Two retries by default:
let client = builder.max_retries.build?; // or 0 to handle it yourself
Concurrency
Every call is an async fn that resolves when Dregs has answered, so awaiting track() in a request
handler makes that request wait on the round trip. Where the response does not depend on the outcome,
spawn it instead:
let client = client.clone;
spawn;
Retries happen inside the spawned task, and the event id is generated before the first attempt, so a retry can never double-count.
Webhooks
Dregs signs every webhook with the channel's signing secret. Verify it against the raw request body before acting on the payload — a re-serialized value will not match, because key order and whitespace change.
use ;
async
verify also rejects payloads older than five minutes as replays; use verify_with and
VerifyOptions::default().tolerance(None) to skip that if you are deduplicating on the event id
yourself. The signing secret is shown once, when you create the webhook channel, and is not your API
secret key.
Configuration
use Duration;
let client = builder
.secret_key // defaults to $DREGS_SECRET_KEY
.base_url // defaults to $DREGS_BASE_URL, then https://dregs.com/api
.timeout
.max_retries
.http_client // bring your own for proxies or custom TLS
.build?;
TLS
TLS goes through rustls by default, verifying certificates with the platform's verifier. To use the operating system's TLS library instead:
= { = "1", = false, = ["native-tls"] }
Types
Responses are plain structs with public fields. Each one also keeps the body it was built from in
raw, so a field Dregs adds after this release is reachable without waiting for an SDK upgrade. Parsing
is lenient: a field that is missing or not the expected type reads as None rather than failing the
call. The response structs are #[non_exhaustive], so new fields arrive in minor releases.
Contributing
See CONTRIBUTING.md. The short version:
Links
- Dregs manual and REST API reference
- Dregs MCP server, for connecting AI agents to your data
- Security policy
License
MIT. See LICENSE.