hackerone-api 0.2.0

Unofficial, dependency-light Rust client for the HackerOne API (v1): submit reports, read your reports, hacktivity, balance, and earnings.
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
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
695
696
//! Wire types.
//!
//! The HackerOne API speaks a JSON:API-ish dialect: every payload is wrapped
//! in `data` / `attributes` / `relationships`, with `links` and `meta` beside
//! it. These types model that envelope generically ([`Resource`],
//! [`SingleDoc`], [`CollectionDoc`], [`Page`]) and then the domain objects
//! (reports, programs, scopes, weaknesses, …).
//!
//! Domain structs keep the fields the API documents and stash everything else
//! in a flattened `extra` map, so a server-side field addition never breaks a
//! decode.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

/// Deserialize a JSON:API `id` that may arrive as a string *or* a number.
///
/// HackerOne is inconsistent: hacker report ids are strings (`"1337"`), while
/// hacktivity item ids are integers (`689314`). Both decode to `Option<String>`.
fn de_id<'de, D>(deserializer: D) -> std::result::Result<Option<String>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let value = Option::<serde_json::Value>::deserialize(deserializer)?;
    Ok(value.and_then(|v| match v {
        serde_json::Value::String(s) => Some(s),
        serde_json::Value::Number(n) => Some(n.to_string()),
        _ => None,
    }))
}

/// JSON:API `links` object (pagination URLs).
#[derive(Debug, Clone, Deserialize, Default)]
pub struct Links {
    /// Next page URL, when there is one.
    #[serde(default)]
    pub next: Option<String>,
    /// Last page URL.
    #[serde(default)]
    pub last: Option<String>,
    /// Self URL.
    #[serde(default, rename = "self")]
    pub this: Option<String>,
}

/// JSON:API `meta` object, kept loose.
#[derive(Debug, Clone, Deserialize, Default)]
pub struct Meta {
    /// Any keys the API includes.
    #[serde(flatten)]
    pub extra: BTreeMap<String, serde_json::Value>,
}

/// A single JSON:API resource: id + type + attributes.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(bound(deserialize = "A: serde::Deserialize<'de> + Default"))]
pub struct Resource<A> {
    /// Resource id (string or number on the wire — see [`de_id`]).
    #[serde(default, deserialize_with = "de_id")]
    pub id: Option<String>,
    /// Resource type (`"report"`, `"program"`, …).
    #[serde(default, rename = "type")]
    pub kind: Option<String>,
    /// The resource's attributes.
    #[serde(default)]
    pub attributes: A,
    /// Relationships, kept as raw JSON.
    #[serde(default)]
    pub relationships: serde_json::Value,
}

/// A bare `{ "data": … }` envelope whose `data` is not a JSON:API resource.
///
/// A few endpoints return a plain object under `data` instead of the usual
/// `id`/`type`/`attributes` resource — notably
/// `GET /v1/hackers/payments/balance` (`{"data":{"balance":105}}`).
#[derive(Debug, Clone, Deserialize)]
pub struct DataDoc<A> {
    /// The unwrapped object.
    pub data: A,
}

/// A single-object response (`GET /v1/me`, `GET /v1/reports/{id}`, …).
#[derive(Debug, Clone, Deserialize)]
#[serde(bound(deserialize = "A: serde::Deserialize<'de> + Default"))]
pub struct SingleDoc<A> {
    /// The resource.
    pub data: Resource<A>,
    /// Pagination/navigation links.
    #[serde(default)]
    pub links: Links,
    /// Response metadata.
    #[serde(default)]
    pub meta: Meta,
}

/// A collection response (`GET /v1/reports`, `GET /v1/me/programs`, …).
#[derive(Debug, Clone, Deserialize)]
#[serde(bound(deserialize = "A: serde::Deserialize<'de> + Default"))]
pub struct CollectionDoc<A> {
    /// The resources.
    #[serde(default)]
    pub data: Vec<Resource<A>>,
    /// Pagination links.
    #[serde(default)]
    pub links: Links,
    /// Response metadata.
    #[serde(default)]
    pub meta: Meta,
}

/// A decoded page: the items plus the links needed to fetch more.
#[derive(Debug, Clone)]
pub struct Page<A> {
    /// The page's resources.
    pub resources: Vec<Resource<A>>,
    /// URL of the next page, if any.
    pub next: Option<String>,
    /// URL of the last page, if any.
    pub last: Option<String>,
}

impl<A> Page<A> {
    /// Build a page from a decoded collection document.
    pub fn from_doc(doc: CollectionDoc<A>) -> Self {
        Self {
            resources: doc.data,
            next: doc.links.next,
            last: doc.links.last,
        }
    }

    /// Number of items on this page.
    pub fn len(&self) -> usize {
        self.resources.len()
    }

    /// Whether the page is empty.
    pub fn is_empty(&self) -> bool {
        self.resources.is_empty()
    }

    /// The item attributes, in order.
    pub fn items(&self) -> impl Iterator<Item = &A> {
        self.resources.iter().map(|r| &r.attributes)
    }

    /// The item ids, in order.
    pub fn ids(&self) -> impl Iterator<Item = Option<&str>> {
        self.resources.iter().map(|r| r.id.as_deref())
    }

    /// Consume the page into the bare item list.
    pub fn into_items(self) -> Vec<A> {
        self.resources.into_iter().map(|r| r.attributes).collect()
    }
}

macro_rules! flexible {
    ($name:ident { $( $field:ident : $ty:ty ),* $(,)? }) => {
        #[derive(Debug, Clone, Deserialize, Default)]
        #[doc = concat!("See the HackerOne API reference for `", stringify!($name), "`.")]
        pub struct $name {
            $(
                #[serde(default)]
                #[doc = concat!("`", stringify!($field), "`")]
                pub $field: Option<$ty>,
            )*
            /// Fields the API returned that this version does not name.
            #[serde(flatten)]
            pub extra: BTreeMap<String, serde_json::Value>,
        }
    };
}

flexible!(User {
    username: String,
    name: String,
    email: String,
    created_at: String,
    disabled: bool,
    location: String,
});

flexible!(Program {
    handle: String,
    name: String,
    state: String,
    submission_state: String,
    offers_bounties: bool,
    policy: String,
    started_accepting_at: String,
});

flexible!(StructuredScope {
    asset_identifier: String,
    asset_type: String,
    eligible_for_bounty: bool,
    eligible_for_submission: bool,
    max_severity: String,
    instruction: String,
    created_at: String,
});

flexible!(Report {
    title: String,
    state: String,
    created_at: String,
    updated_at: String,
    vulnerability_information: String,
    disclosed_at: String,
    bounty_awarded_at: String,
    has_bounty: bool,
});

flexible!(Weakness {
    name: String,
    description: String,
    external_id: String,
    created_at: String,
});

flexible!(Severity {
    rating: String,
    score: f64,
    cvss_vector: String,
    author_type: String,
    created_at: String,
});

flexible!(Hacktivity {
    title: String,
    substate: String,
    url: String,
    disclosed_at: String,
    submitted_at: String,
    disclosed: bool,
    cve_ids: Vec<String>,
    cwe: String,
    severity_rating: String,
    votes: i64,
    total_awarded_amount: i64,
    latest_disclosable_action: String,
    latest_disclosable_activity_at: String,
});

flexible!(Earning {
    amount: f64,
    created_at: String,
});

/// The authenticated hacker's payment balance
/// (`GET /v1/hackers/payments/balance`).
///
/// The endpoint returns a bare `{"data":{"balance":105}}` (no `attributes`
/// wrapper), so this type accepts both that shape and a JSON:API
/// `{"data":{"attributes":{"balance":…}}}` shape. Amounts are read from a
/// JSON number *or* a numeric string.
#[derive(Debug, Clone, Default)]
pub struct Balance {
    /// The balance amount, if the server reported one.
    pub balance: Option<f64>,
    /// The currency, if the server reported one.
    pub currency: Option<String>,
    /// Fields the API returned that this version does not name.
    pub extra: BTreeMap<String, serde_json::Value>,
}

/// Parse a JSON number or numeric string into `f64`.
fn parse_amount(value: &serde_json::Value) -> Option<f64> {
    match value {
        serde_json::Value::Number(n) => n.as_f64(),
        serde_json::Value::String(s) => s.parse::<f64>().ok(),
        _ => None,
    }
}

impl<'de> Deserialize<'de> for Balance {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use serde::de::Error as _;
        let value = serde_json::Value::deserialize(deserializer)?;
        let object = match value {
            serde_json::Value::Object(map) => map,
            other => {
                return Err(D::Error::custom(format!(
                    "balance: expected an object, got {other}"
                )))
            }
        };

        // Accept `{balance:…}` or a resource `{attributes:{balance:…}}`.
        let source = match object.get("attributes") {
            Some(serde_json::Value::Object(attrs)) => attrs.clone(),
            _ => object,
        };

        let balance = source.get("balance").and_then(parse_amount);
        let currency = source
            .get("currency")
            .and_then(|v| v.as_str())
            .map(str::to_string);

        let extra = source
            .into_iter()
            .filter(|(k, _)| k != "balance" && k != "currency")
            .collect();

        Ok(Balance {
            balance,
            currency,
            extra,
        })
    }
}

/// Severity rating supplied when creating a report.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum SeverityRating {
    /// `none`
    None,
    /// `low`
    Low,
    /// `medium`
    Medium,
    /// `high`
    High,
    /// `critical`
    Critical,
}

impl SeverityRating {
    /// The wire value.
    pub fn as_str(self) -> &'static str {
        match self {
            SeverityRating::None => "none",
            SeverityRating::Low => "low",
            SeverityRating::Medium => "medium",
            SeverityRating::High => "high",
            SeverityRating::Critical => "critical",
        }
    }
}

/// Report states accepted by a state change.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ReportState {
    /// `new`
    New,
    /// `triaged`
    Triaged,
    /// `needs_more_info`
    NeedsMoreInfo,
    /// `resolved`
    Resolved,
    /// `informative`
    Informative,
    /// `not_applicable`
    NotApplicable,
    /// `duplicate`
    Duplicate,
    /// `spam`
    Spam,
}

impl ReportState {
    /// The wire value.
    pub fn as_str(self) -> &'static str {
        match self {
            ReportState::New => "new",
            ReportState::Triaged => "triaged",
            ReportState::NeedsMoreInfo => "needs_more_info",
            ReportState::Resolved => "resolved",
            ReportState::Informative => "informative",
            ReportState::NotApplicable => "not_applicable",
            ReportState::Duplicate => "duplicate",
            ReportState::Spam => "spam",
        }
    }
}

/// A hacker report to create (`POST /v1/hackers/reports`).
///
/// Build it with the chainable methods, then submit it with
/// [`Client::create_report`](crate::Client::create_report).
///
/// The JSON:API body this renders is exactly:
///
/// ```json
/// {
///   "data": {
///     "type": "report",
///     "attributes": {
///       "team_handle": "chia_network",
///       "title": "…",
///       "vulnerability_information": "…",
///       "impact": "…",
///       "severity_rating": "high",
///       "weakness_id": 1337,
///       "structured_scope_id": 57
///     }
///   }
/// }
/// ```
#[derive(Debug, Clone, Default, PartialEq)]
pub struct CreateHackerReport {
    /// Program handle the report is submitted to (required), e.g. `chia_network`.
    pub team_handle: String,
    /// Report title (required).
    pub title: String,
    /// Detailed write-up: steps to reproduce + supporting material (required).
    pub vulnerability_information: String,
    /// The security impact an attacker could achieve (required).
    pub impact: String,
    /// Qualitative severity, one of the five documented ratings.
    pub severity_rating: Option<SeverityRating>,
    /// Weakness (CWE) object id.
    pub weakness_id: Option<u64>,
    /// Structured scope object id this report targets.
    pub structured_scope_id: Option<u64>,
}

impl CreateHackerReport {
    /// A report for `team_handle` with `title`.
    pub fn new(team_handle: impl Into<String>, title: impl Into<String>) -> Self {
        Self {
            team_handle: team_handle.into(),
            title: title.into(),
            ..Default::default()
        }
    }

    /// Set the vulnerability write-up (required by the API).
    pub fn vulnerability_information(mut self, text: impl Into<String>) -> Self {
        self.vulnerability_information = text.into();
        self
    }

    /// Set the impact statement (required by the API).
    pub fn impact(mut self, text: impl Into<String>) -> Self {
        self.impact = text.into();
        self
    }

    /// Set the severity rating.
    pub fn severity(mut self, rating: SeverityRating) -> Self {
        self.severity_rating = Some(rating);
        self
    }

    /// Attach a weakness (CWE) id.
    pub fn weakness_id(mut self, id: u64) -> Self {
        self.weakness_id = Some(id);
        self
    }

    /// Pin the structured scope id.
    pub fn structured_scope_id(mut self, id: u64) -> Self {
        self.structured_scope_id = Some(id);
        self
    }

    /// Render the JSON:API request body, validating the required fields.
    pub fn to_json(&self) -> Result<serde_json::Value, crate::Error> {
        for (field, value) in [
            ("team_handle", &self.team_handle),
            ("title", &self.title),
            ("vulnerability_information", &self.vulnerability_information),
            ("impact", &self.impact),
        ] {
            if value.trim().is_empty() {
                return Err(crate::Error::Invalid(format!("report.{field} is required")));
            }
        }

        let mut attributes = serde_json::Map::new();
        attributes.insert("team_handle".into(), serde_json::json!(self.team_handle));
        attributes.insert("title".into(), serde_json::json!(self.title));
        attributes.insert(
            "vulnerability_information".into(),
            serde_json::json!(self.vulnerability_information),
        );
        attributes.insert("impact".into(), serde_json::json!(self.impact));
        if let Some(rating) = self.severity_rating {
            attributes.insert("severity_rating".into(), serde_json::json!(rating.as_str()));
        }
        if let Some(id) = self.weakness_id {
            attributes.insert("weakness_id".into(), serde_json::json!(id));
        }
        if let Some(id) = self.structured_scope_id {
            attributes.insert("structured_scope_id".into(), serde_json::json!(id));
        }

        Ok(serde_json::json!({
            "data": {
                "type": "report",
                "attributes": serde_json::Value::Object(attributes),
            }
        }))
    }
}

/// Pagination for the hacker list endpoints (`page[number]`, `page[size]`).
#[derive(Debug, Clone, Default)]
pub struct PageQuery {
    /// 1-based page number.
    pub page_number: Option<u32>,
    /// Page size (1–100 per the API).
    pub page_size: Option<u32>,
    /// Any extra `key=value` pairs, passed through verbatim.
    pub extra: Vec<(String, String)>,
}

impl PageQuery {
    /// An empty query (server defaults: page 1, size 25).
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the page.
    pub fn page(mut self, number: u32, size: u32) -> Self {
        self.page_number = Some(number);
        self.page_size = Some(size);
        self
    }

    /// Add a raw query pair.
    pub fn filter(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.extra.push((key.into(), value.into()));
        self
    }

    /// Render to query pairs, in the HackerOne `page[…]` shape.
    pub fn to_pairs(&self) -> Vec<(String, String)> {
        let mut pairs = Vec::new();
        if let Some(n) = self.page_number {
            pairs.push(("page[number]".to_string(), n.to_string()));
        }
        if let Some(s) = self.page_size {
            pairs.push(("page[size]".to_string(), s.to_string()));
        }
        pairs.extend(self.extra.iter().cloned());
        pairs
    }
}

/// Query for [`Client::hacktivity`](crate::Client::hacktivity).
///
/// `query_string` uses HackerOne's Apache-Lucene filter syntax, e.g.
/// `severity_rating:critical AND disclosed:true`.
#[derive(Debug, Clone, Default)]
pub struct HacktivityQuery {
    /// Lucene query string (`queryString`).
    pub query_string: Option<String>,
    /// Sort attribute; prefix with `-` for descending.
    pub sort: Option<String>,
    /// 1-based page number.
    pub page_number: Option<u32>,
    /// Page size (1–100 per the API).
    pub page_size: Option<u32>,
    /// Any extra `key=value` pairs, passed through verbatim.
    pub extra: Vec<(String, String)>,
}

impl HacktivityQuery {
    /// An empty query (server returns all, newest activity first).
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the Lucene query string.
    pub fn query(mut self, query: impl Into<String>) -> Self {
        self.query_string = Some(query.into());
        self
    }

    /// Set the sort attribute (prefix `-` for descending).
    pub fn sort(mut self, sort: impl Into<String>) -> Self {
        self.sort = Some(sort.into());
        self
    }

    /// Set the page.
    pub fn page(mut self, number: u32, size: u32) -> Self {
        self.page_number = Some(number);
        self.page_size = Some(size);
        self
    }

    /// Add a raw query pair.
    pub fn filter(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.extra.push((key.into(), value.into()));
        self
    }

    /// Render to query pairs.
    pub fn to_pairs(&self) -> Vec<(String, String)> {
        let mut pairs = Vec::new();
        if let Some(q) = &self.query_string {
            pairs.push(("queryString".to_string(), q.clone()));
        }
        if let Some(sort) = &self.sort {
            pairs.push(("sort".to_string(), sort.clone()));
        }
        if let Some(n) = self.page_number {
            pairs.push(("page[number]".to_string(), n.to_string()));
        }
        if let Some(s) = self.page_size {
            pairs.push(("page[size]".to_string(), s.to_string()));
        }
        pairs.extend(self.extra.iter().cloned());
        pairs
    }
}

/// Filters for [`Client::reports`](crate::Client::reports).
#[derive(Debug, Clone, Default)]
pub struct ReportQuery {
    /// Restrict to these states, e.g. `["new", "triaged"]`.
    pub states: Vec<String>,
    /// Restrict to a program handle.
    pub program: Option<String>,
    /// Sort expression, e.g. `-created_at`.
    pub sort: Option<String>,
    /// 1-based page number.
    pub page_number: Option<u32>,
    /// Page size.
    pub page_size: Option<u32>,
    /// Any extra `key=value` pairs, passed through verbatim.
    pub extra: Vec<(String, String)>,
}

impl ReportQuery {
    /// An empty query.
    pub fn new() -> Self {
        Self::default()
    }

    /// Restrict to a state.
    pub fn state(mut self, state: impl Into<String>) -> Self {
        self.states.push(state.into());
        self
    }

    /// Restrict to a program handle.
    pub fn program(mut self, handle: impl Into<String>) -> Self {
        self.program = Some(handle.into());
        self
    }

    /// Sort expression (prefix `-` for descending).
    pub fn sort(mut self, sort: impl Into<String>) -> Self {
        self.sort = Some(sort.into());
        self
    }

    /// Set the page.
    pub fn page(mut self, number: u32, size: u32) -> Self {
        self.page_number = Some(number);
        self.page_size = Some(size);
        self
    }

    /// Add a raw filter.
    pub fn filter(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.extra.push((key.into(), value.into()));
        self
    }

    /// Render to query pairs, in the HackerOne `filter[…]` / `page[…]` shape.
    pub fn to_pairs(&self) -> Vec<(String, String)> {
        let mut pairs = Vec::new();
        for state in &self.states {
            pairs.push(("filter[state][]".to_string(), state.clone()));
        }
        if let Some(program) = &self.program {
            pairs.push(("filter[program][]".to_string(), program.clone()));
        }
        if let Some(sort) = &self.sort {
            pairs.push(("sort".to_string(), sort.clone()));
        }
        if let Some(n) = self.page_number {
            pairs.push(("page[number]".to_string(), n.to_string()));
        }
        if let Some(s) = self.page_size {
            pairs.push(("page[size]".to_string(), s.to_string()));
        }
        pairs.extend(self.extra.iter().cloned());
        pairs
    }
}