dregs 0.1.0

The official Rust client for Dregs, which scores the users of your application for fraud and abuse.
Documentation
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
//! Typed views over the Dregs API's responses.
//!
//! Every model keeps the response it was built from in `raw`, so a field Dregs adds after this
//! release is still reachable without waiting for an SDK upgrade. Parsing is deliberately
//! lenient: a missing or unexpected field becomes `None` rather than an error, because an SDK
//! that refuses to parse a response it half-understands is worse than one that hands back what it
//! got.

use std::fmt;
use std::ops::Deref;

use chrono::{DateTime, NaiveDateTime, Utc};
use serde_json::{Map, Value};

/// The four categories Dregs scores an identity in.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Category {
    /// How likely it is that a person, rather than a script, is behind the account.
    Humanity,
    /// How genuine the details on the account look.
    Authenticity,
    /// How distinct the account is from others in the same tenant.
    Uniqueness,
    /// How ordinary the account's activity looks.
    Behavior,
}

impl Category {
    /// The name the API uses for the category, such as `"HUMANITY"`.
    pub fn as_str(self) -> &'static str {
        match self {
            Category::Humanity => "HUMANITY",
            Category::Authenticity => "AUTHENTICITY",
            Category::Uniqueness => "UNIQUENESS",
            Category::Behavior => "BEHAVIOR",
        }
    }

    /// Parses the API's name for a category, ignoring case. A category this release predates
    /// gives `None`, so it cannot break an otherwise good response.
    pub fn parse(value: &str) -> Option<Category> {
        [
            Category::Humanity,
            Category::Authenticity,
            Category::Uniqueness,
            Category::Behavior,
        ]
        .into_iter()
        .find(|category| category.as_str().eq_ignore_ascii_case(value))
    }
}

impl fmt::Display for Category {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// The outcome of a [`Client::track`](crate::Client::track) call.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct TrackResult {
    /// The status Dregs reported, normally `"success"`.
    pub status: Option<String>,
    /// The event's identifier, either the one you supplied or one Dregs generated. It is `None`
    /// when the event was not recorded.
    pub id: Option<String>,
    /// The device fingerprint Dregs resolved, for events that carried a device signature.
    /// Server-side events do not, so this is normally `None`.
    pub fingerprint: Option<String>,
    /// The response body as received.
    pub raw: Value,
}

impl TrackResult {
    /// Whether Dregs recorded the event.
    ///
    /// This is `false` in the uncommon case where Dregs accepts the request without recording an
    /// event. A server-side integration holding a valid secret key should not normally see it,
    /// so it is worth a log line if you do. Ingestion failures that are the caller's to act on (a
    /// bad request, an unknown key, an exhausted quota, a rate limit) are returned as errors
    /// instead of landing here.
    pub fn accepted(&self) -> bool {
        self.id.is_some()
    }

    pub(crate) fn from_value(raw: Value) -> Self {
        TrackResult {
            status: string(&raw, "status"),
            id: string(&raw, "id"),
            fingerprint: string(&raw, "fingerprint"),
            raw,
        }
    }
}

/// A label Dregs applied to an identity, from an analyzer or a badge rule.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Badge {
    /// The badge's identifier, such as `"behavior.account-takeover-signal"`.
    pub slug: Option<String>,
    /// A human-readable name for the badge.
    pub name: Option<String>,
    /// The kind of badge.
    pub badge_type: Option<String>,
    /// Why the badge was applied.
    pub explanation: Option<String>,
    /// The details behind the badge.
    pub metadata: Map<String, Value>,
    /// The badge as received.
    pub raw: Value,
}

impl Badge {
    fn from_value(raw: &Value) -> Self {
        Badge {
            slug: string(raw, "slug"),
            name: string(raw, "name"),
            badge_type: string(raw, "type"),
            explanation: string(raw, "explanation"),
            metadata: object(raw, "metadata"),
            raw: raw.clone(),
        }
    }
}

/// One analyzer's finding, and the reasoning behind a slice of a score.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Observation {
    /// The category the observation contributes to.
    pub category: Option<Category>,
    /// The analyzer's identifier, such as `"humanity.user-agent"`.
    pub id: Option<String>,
    /// A human-readable name for the analyzer.
    pub label: Option<String>,
    /// A sentence describing what the analyzer found.
    pub explanation: Option<String>,
    /// 0.0 for entirely suspicious, 1.0 for entirely legitimate.
    pub value: Option<f64>,
    /// How sure the analyzer is, from 0.0 to 1.0.
    pub confidence: Option<f64>,
    /// How heavily this observation counts toward the category score.
    pub weight: Option<f64>,
    /// The counts and details behind the finding.
    pub metadata: Map<String, Value>,
    /// The observation as received.
    pub raw: Value,
}

impl Observation {
    fn from_value(raw: &Value) -> Self {
        Observation {
            category: category(raw),
            id: string(raw, "id"),
            label: string(raw, "label"),
            explanation: string(raw, "explanation"),
            value: float(raw, "value"),
            confidence: float(raw, "confidence"),
            weight: float(raw, "weight"),
            metadata: object(raw, "metadata"),
            raw: raw.clone(),
        }
    }
}

/// One category's score.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Score {
    /// The category scored. `None` for a category this release of the SDK predates; the API's
    /// name for it is still in `raw`.
    pub category: Option<Category>,
    /// An integer from 0 (worst) to 100 (best).
    pub value: Option<i64>,
    /// The observations behind the score. This is empty on the result of
    /// [`Identities::scores`](crate::Identities::scores), which reports the scores alone; the
    /// observations come from [`Identities::analysis`](crate::Identities::analysis).
    pub observations: Vec<Observation>,
    /// The score as received.
    pub raw: Value,
}

impl Score {
    fn from_value(raw: &Value) -> Self {
        Score {
            category: category(raw),
            value: integer(raw, "value"),
            observations: objects(raw, "observations")
                .map(Observation::from_value)
                .collect(),
            raw: raw.clone(),
        }
    }

    fn bare(category: Category, value: i64) -> Self {
        Score {
            category: Some(category),
            value: Some(value),
            observations: Vec::new(),
            raw: Value::Null,
        }
    }
}

/// An identity's four category scores.
///
/// Dereferences to a slice of [`Score`], and also offers the four categories by name:
///
/// ```
/// # async fn run(client: dregs::Client) -> dregs::Result<()> {
/// let scores = client.identities().scores("user_12345").await?;
///
/// if scores.humanity().is_some_and(|humanity| humanity < 30) {
///     // hold for review
/// }
///
/// for score in &scores {
///     println!("{:?}: {:?}", score.category, score.value);
/// }
/// # Ok(())
/// # }
/// ```
///
/// A category Dregs has not scored yet is absent from the slice, and its named accessor returns
/// `None`.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Scores(Vec<Score>);

impl Scores {
    /// The score for `category`, or `None` when it has not been scored.
    pub fn get(&self, category: Category) -> Option<&Score> {
        self.0.iter().find(|score| score.category == Some(category))
    }

    fn value(&self, category: Category) -> Option<i64> {
        self.get(category).and_then(|score| score.value)
    }

    /// How likely it is that a person, rather than a script, is behind the account.
    pub fn humanity(&self) -> Option<i64> {
        self.value(Category::Humanity)
    }

    /// How genuine the details on the account look.
    pub fn authenticity(&self) -> Option<i64> {
        self.value(Category::Authenticity)
    }

    /// How distinct the account is from others in the same tenant.
    pub fn uniqueness(&self) -> Option<i64> {
        self.value(Category::Uniqueness)
    }

    /// How ordinary the account's activity looks.
    pub fn behavior(&self) -> Option<i64> {
        self.value(Category::Behavior)
    }

    /// The scores as a vector.
    pub fn into_vec(self) -> Vec<Score> {
        self.0
    }

    pub(crate) fn from_value(raw: &Value) -> Self {
        let items = match raw {
            Value::Array(items) => items
                .iter()
                .filter(|item| item.is_object())
                .map(Score::from_value)
                .collect(),
            _ => Vec::new(),
        };

        Scores(items)
    }
}

impl Deref for Scores {
    type Target = [Score];

    fn deref(&self) -> &[Score] {
        &self.0
    }
}

impl IntoIterator for Scores {
    type Item = Score;
    type IntoIter = std::vec::IntoIter<Score>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl<'a> IntoIterator for &'a Scores {
    type Item = &'a Score;
    type IntoIter = std::slice::Iter<'a, Score>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}

/// A user Dregs is tracking, and their current scores.
///
/// `id` is your own identifier for the user, the one you pass to
/// [`Event::new`](crate::Event::new) and to `dregs.identify()` in the browser tracker, not an
/// internal Dregs id.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Identity {
    /// Your own id for the user.
    pub id: Option<String>,
    /// The name Dregs displays for the user, from the attributes you have sent.
    pub display_name: Option<String>,
    /// The email Dregs displays for the user.
    pub display_email: Option<String>,
    /// The username Dregs displays for the user.
    pub display_username: Option<String>,
    /// The humanity score, from 0 to 100.
    pub humanity_score: Option<i64>,
    /// The authenticity score, from 0 to 100.
    pub authenticity_score: Option<i64>,
    /// The uniqueness score, from 0 to 100.
    pub uniqueness_score: Option<i64>,
    /// The behavior score, from 0 to 100.
    pub behavior_score: Option<i64>,
    /// When Dregs first saw the identity.
    pub created_at: Option<DateTime<Utc>>,
    /// When the identity last changed.
    pub updated_at: Option<DateTime<Utc>>,
    /// When an event was last tracked against the identity.
    pub last_tracked_at: Option<DateTime<Utc>>,
    /// When the identity was last scored.
    pub last_scored_at: Option<DateTime<Utc>>,
    /// Whether the identity has been disregarded, and so is left out of scoring and alerting.
    pub disregarded: bool,
    /// The badges applied to the identity.
    pub badges: Vec<Badge>,
    /// Every attribute you have sent for the identity.
    pub data: Map<String, Value>,
    /// The identity as received.
    pub raw: Value,
}

impl Identity {
    /// The identity's scores, as a [`Scores`] for parity with
    /// [`Identities::scores`](crate::Identities::scores).
    pub fn scores(&self) -> Scores {
        let pairs = [
            (Category::Humanity, self.humanity_score),
            (Category::Authenticity, self.authenticity_score),
            (Category::Uniqueness, self.uniqueness_score),
            (Category::Behavior, self.behavior_score),
        ];

        Scores(
            pairs
                .into_iter()
                .filter_map(|(category, value)| value.map(|value| Score::bare(category, value)))
                .collect(),
        )
    }

    pub(crate) fn from_value(raw: Value) -> Self {
        Identity {
            id: string(&raw, "id"),
            display_name: string(&raw, "displayName"),
            display_email: string(&raw, "displayEmail"),
            display_username: string(&raw, "displayUsername"),
            humanity_score: integer(&raw, "humanityScore"),
            authenticity_score: integer(&raw, "authenticityScore"),
            uniqueness_score: integer(&raw, "uniquenessScore"),
            behavior_score: integer(&raw, "behaviorScore"),
            created_at: datetime(&raw, "createdAt"),
            updated_at: datetime(&raw, "updatedAt"),
            last_tracked_at: datetime(&raw, "lastTrackedAt"),
            last_scored_at: datetime(&raw, "lastScoredAt"),
            disregarded: raw
                .get("disregarded")
                .and_then(Value::as_bool)
                .unwrap_or(false),
            badges: objects(&raw, "badges").map(Badge::from_value).collect(),
            data: object(&raw, "data"),
            raw,
        }
    }
}

/// One analysis cycle: the scores an identity was given, and why.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Analysis {
    /// The cycle's identifier.
    pub id: Option<i64>,
    /// The identity that was analyzed.
    pub identity_id: Option<String>,
    /// The four category scores, each carrying its observations.
    pub scores: Scores,
    /// How many events the cycle considered.
    pub event_count: Option<i64>,
    /// How many devices the cycle considered.
    pub device_count: Option<i64>,
    /// How long the cycle took.
    pub duration_millis: Option<i64>,
    /// When the cycle started.
    pub started_at: Option<DateTime<Utc>>,
    /// When the cycle finished.
    pub finished_at: Option<DateTime<Utc>>,
    /// The analysis as received.
    pub raw: Value,
}

impl Analysis {
    /// Every observation from the cycle, across all four categories.
    pub fn observations(&self) -> impl Iterator<Item = &Observation> {
        self.scores
            .iter()
            .flat_map(|score| score.observations.iter())
    }

    pub(crate) fn from_value(raw: Value) -> Self {
        Analysis {
            id: integer(&raw, "id"),
            identity_id: string(&raw, "identityId"),
            scores: raw
                .get("scores")
                .map(Scores::from_value)
                .unwrap_or_default(),
            event_count: integer(&raw, "eventCount"),
            device_count: integer(&raw, "deviceCount"),
            duration_millis: integer(&raw, "durationMillis"),
            started_at: datetime(&raw, "startedAt"),
            finished_at: datetime(&raw, "finishedAt"),
            raw,
        }
    }
}

fn string(raw: &Value, key: &str) -> Option<String> {
    raw.get(key).and_then(Value::as_str).map(str::to_owned)
}

fn float(raw: &Value, key: &str) -> Option<f64> {
    raw.get(key).and_then(Value::as_f64)
}

/// Reads an integer, accepting a float with no fractional part, since JSON does not distinguish
/// the two and a serializer that writes `85.0` should not cost the caller their score.
fn integer(raw: &Value, key: &str) -> Option<i64> {
    let value = raw.get(key)?;

    value.as_i64().or_else(|| {
        value
            .as_f64()
            .filter(|f| f.fract() == 0.0 && f.is_finite())
            .map(|f| f as i64)
    })
}

fn object(raw: &Value, key: &str) -> Map<String, Value> {
    raw.get(key)
        .and_then(Value::as_object)
        .cloned()
        .unwrap_or_default()
}

fn objects<'a>(raw: &'a Value, key: &str) -> impl Iterator<Item = &'a Value> {
    raw.get(key)
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
        .filter(|item| item.is_object())
}

fn category(raw: &Value) -> Option<Category> {
    raw.get("category")
        .and_then(Value::as_str)
        .and_then(Category::parse)
}

/// Parses an ISO-8601 timestamp, reading one with no offset as UTC and returning `None` for
/// anything unparseable.
pub(crate) fn parse_datetime(value: &str) -> Option<DateTime<Utc>> {
    if let Ok(parsed) = DateTime::parse_from_rfc3339(value) {
        return Some(parsed.with_timezone(&Utc));
    }

    NaiveDateTime::parse_from_str(value, "%Y-%m-%dT%H:%M:%S%.f")
        .ok()
        .map(|naive| naive.and_utc())
}

fn datetime(raw: &Value, key: &str) -> Option<DateTime<Utc>> {
    raw.get(key)
        .and_then(Value::as_str)
        .and_then(parse_datetime)
}