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
//! Shared PDS fakes and builders for the integration tests.
//!
//! [`FakePds`] is both a scripted transport (queued replies drive retry and
//! error-path tests) and a small record store keyed by `(collection, rkey)`
//! (list/delete/software graph tests). A call with no queued reply succeeds
//! against the store, except `getRecord` on a missing key (404).
#![allow(dead_code)]
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde_json::{Value, json};
use vuln_notif::db::DbHandle;
use vuln_notif::log::{CaptureSink, Level, Logger};
use vuln_notif::pds::{PdsApi, Publisher, PublisherConfig, RateGovernor, XrpcResponse};
use vuln_notif::records::PreparedRow;
use vuln_notif::time::{RealTime, Time};
/// NVD collection used by the publisher tests.
pub const COLLECTION: &str = "com.nahdig.cve.nvdV2";
/// The DID every fake session resolves to.
pub const REPO: &str = "did:plc:test";
/// CID reported by fake writes.
pub const PUT_CID: &str = "bafyput";
/// CID reported by fake deletes.
pub const DELETE_CID: &str = "bafycommit";
pub struct FakeTime {
now: Mutex<f64>,
sleeps: Mutex<Vec<f64>>,
}
impl FakeTime {
pub fn new(now: f64) -> Arc<Self> {
Arc::new(Self {
now: Mutex::new(now),
sleeps: Mutex::new(Vec::new()),
})
}
pub fn sleeps(&self) -> Vec<f64> {
self.sleeps.lock().unwrap().clone()
}
}
#[async_trait]
impl Time for FakeTime {
fn now_unix(&self) -> f64 {
*self.now.lock().unwrap()
}
fn now_utc(&self) -> DateTime<Utc> {
DateTime::from_timestamp(self.now_unix() as i64, 0).expect("fake timestamp")
}
async fn sleep(&self, duration: Duration) {
self.sleeps.lock().unwrap().push(duration.as_secs_f64());
}
fn jitter(&self, _scale: f64) -> f64 {
0.0
}
}
#[derive(Clone)]
pub enum Reply {
Response(XrpcResponse),
Transport(String),
}
#[derive(Clone, Debug, Default)]
pub struct ApiCall {
pub method: &'static str,
pub repo: String,
pub collection: String,
pub rkey: String,
pub access: String,
pub record: Option<Value>,
pub writes: Option<Vec<Value>>,
pub bytes: Option<Vec<u8>>,
pub mime: Option<String>,
pub cursor: Option<String>,
pub limit: Option<usize>,
}
#[derive(Default)]
struct FakeState {
create: VecDeque<Reply>,
refresh: VecDeque<Reply>,
get: VecDeque<Reply>,
create_record: VecDeque<Reply>,
put: VecDeque<Reply>,
apply: VecDeque<Reply>,
list: VecDeque<Reply>,
delete: VecDeque<Reply>,
upload: VecDeque<Reply>,
calls: Vec<ApiCall>,
records: BTreeMap<(String, String), Value>,
}
pub struct FakePds {
state: Mutex<FakeState>,
}
impl FakePds {
pub fn new() -> Arc<Self> {
Arc::new(Self {
state: Mutex::new(FakeState::default()),
})
}
fn state(&self) -> std::sync::MutexGuard<'_, FakeState> {
self.state.lock().unwrap()
}
}
macro_rules! push_reply {
($name:ident, $field:ident) => {
impl FakePds {
pub fn $name(&self, reply: Reply) {
self.state.lock().unwrap().$field.push_back(reply);
}
}
};
}
push_reply!(push_create, create);
push_reply!(push_refresh, refresh);
push_reply!(push_get, get);
push_reply!(push_create_record, create_record);
push_reply!(push_put, put);
push_reply!(push_apply, apply);
push_reply!(push_list, list);
push_reply!(push_delete, delete);
push_reply!(push_upload, upload);
impl FakePds {
pub fn calls(&self) -> Vec<ApiCall> {
self.state().calls.clone()
}
pub fn count(&self, method: &str) -> usize {
self.calls()
.iter()
.filter(|call| call.method == method)
.count()
}
/// Every `putRecord` call, in order.
pub fn puts(&self) -> Vec<ApiCall> {
self.calls()
.into_iter()
.filter(|call| call.method == "putRecord")
.collect()
}
pub fn record(&self, collection: &str, rkey: &str) -> Option<Value> {
self.state()
.records
.get(&(collection.to_owned(), rkey.to_owned()))
.cloned()
}
pub fn store(&self) -> BTreeMap<(String, String), Value> {
self.state().records.clone()
}
pub fn seed_record(&self, collection: &str, rkey: &str, value: Value) {
self.state()
.records
.insert((collection.to_owned(), rkey.to_owned()), value);
}
}
fn scripted(reply: Option<Reply>) -> anyhow::Result<Option<XrpcResponse>> {
match reply {
None => Ok(None),
Some(Reply::Response(response)) => Ok(Some(response)),
Some(Reply::Transport(message)) => Err(anyhow::anyhow!("{message}")),
}
}
fn ok(body: Value) -> XrpcResponse {
XrpcResponse {
status: 200,
body,
..XrpcResponse::default()
}
}
fn write_response(repo: &str, collection: &str, rkey: &str) -> XrpcResponse {
ok(json!({
"uri": record_uri(repo, collection, rkey),
"cid": PUT_CID,
}))
}
fn missing_record() -> XrpcResponse {
XrpcResponse {
status: 404,
body: json!({"error": "RecordNotFound", "message": "Could not locate record"}),
..XrpcResponse::default()
}
}
fn apply_to_store(records: &mut BTreeMap<(String, String), Value>, writes: &[Value]) {
for write in writes {
let collection = write
.get("collection")
.and_then(Value::as_str)
.unwrap_or_default();
let rkey = write
.get("rkey")
.and_then(Value::as_str)
.unwrap_or_default();
let kind = write
.get("$type")
.and_then(Value::as_str)
.unwrap_or_default();
let key = (collection.to_owned(), rkey.to_owned());
if kind.ends_with("#delete") || (kind.is_empty() && write.get("value").is_none()) {
records.remove(&key);
} else if let Some(value) = write.get("value") {
records.insert(key, value.clone());
}
}
}
fn list_page(
records: &BTreeMap<(String, String), Value>,
repo: &str,
collection: &str,
cursor: Option<&str>,
limit: Option<usize>,
) -> XrpcResponse {
let limit = limit.unwrap_or(50).max(1);
let entries: Vec<(&String, &Value)> = records
.iter()
.filter(|((entry_collection, rkey), _)| {
entry_collection.as_str() == collection
&& cursor.is_none_or(|cursor| rkey.as_str() > cursor)
})
.map(|((_, rkey), value)| (rkey, value))
.collect();
let has_more = entries.len() > limit;
let items: Vec<Value> = entries
.iter()
.take(limit)
.map(|(rkey, value)| {
json!({
"uri": record_uri(repo, collection, rkey),
"cid": PUT_CID,
"value": value,
})
})
.collect();
let mut body = json!({ "records": items });
if has_more {
body["cursor"] = Value::String(entries[limit - 1].0.to_string());
}
ok(body)
}
#[async_trait]
impl PdsApi for FakePds {
async fn create_session(&self, handle: &str, password: &str) -> anyhow::Result<XrpcResponse> {
let mut state = self.state();
state.calls.push(ApiCall {
method: "createSession",
access: format!("{handle}:{password}"),
..ApiCall::default()
});
match scripted(state.create.pop_front())? {
Some(response) => Ok(response),
None => Ok(ok(session_body("access", "refresh"))),
}
}
async fn refresh_session(&self, refresh_jwt: &str) -> anyhow::Result<XrpcResponse> {
let mut state = self.state();
state.calls.push(ApiCall {
method: "refreshSession",
access: refresh_jwt.to_owned(),
..ApiCall::default()
});
match scripted(state.refresh.pop_front())? {
Some(response) => Ok(response),
None => Ok(ok(session_body("access", "refresh"))),
}
}
async fn get_record(
&self,
repo: &str,
collection: &str,
rkey: &str,
access_jwt: &str,
) -> anyhow::Result<XrpcResponse> {
let mut state = self.state();
state.calls.push(ApiCall {
method: "getRecord",
repo: repo.to_owned(),
collection: collection.to_owned(),
rkey: rkey.to_owned(),
access: access_jwt.to_owned(),
..ApiCall::default()
});
if let Some(response) = scripted(state.get.pop_front())? {
return Ok(response);
}
match state.records.get(&(collection.to_owned(), rkey.to_owned())) {
Some(value) => Ok(ok(json!({
"uri": record_uri(repo, collection, rkey),
"cid": PUT_CID,
"value": value,
}))),
None => Ok(missing_record()),
}
}
async fn create_record(
&self,
repo: &str,
collection: &str,
rkey: &str,
record: &Value,
access_jwt: &str,
) -> anyhow::Result<XrpcResponse> {
let mut state = self.state();
state.calls.push(ApiCall {
method: "createRecord",
repo: repo.to_owned(),
collection: collection.to_owned(),
rkey: rkey.to_owned(),
access: access_jwt.to_owned(),
record: Some(record.clone()),
..ApiCall::default()
});
let key = (collection.to_owned(), rkey.to_owned());
match scripted(state.create_record.pop_front())? {
Some(response) => {
if response.status == 200 {
state.records.insert(key, record.clone());
}
Ok(response)
}
None => {
state.records.insert(key, record.clone());
Ok(write_response(repo, collection, rkey))
}
}
}
async fn put_record(
&self,
repo: &str,
collection: &str,
rkey: &str,
record: &Value,
access_jwt: &str,
) -> anyhow::Result<XrpcResponse> {
let mut state = self.state();
state.calls.push(ApiCall {
method: "putRecord",
repo: repo.to_owned(),
collection: collection.to_owned(),
rkey: rkey.to_owned(),
access: access_jwt.to_owned(),
record: Some(record.clone()),
..ApiCall::default()
});
let key = (collection.to_owned(), rkey.to_owned());
match scripted(state.put.pop_front())? {
Some(response) => {
if response.status == 200 {
state.records.insert(key, record.clone());
}
Ok(response)
}
None => {
state.records.insert(key, record.clone());
Ok(write_response(repo, collection, rkey))
}
}
}
async fn apply_writes(
&self,
repo: &str,
writes: &[Value],
access_jwt: &str,
) -> anyhow::Result<XrpcResponse> {
let mut state = self.state();
state.calls.push(ApiCall {
method: "applyWrites",
repo: repo.to_owned(),
access: access_jwt.to_owned(),
writes: Some(writes.to_vec()),
..ApiCall::default()
});
match scripted(state.apply.pop_front())? {
Some(response) => {
if response.status == 200 {
apply_to_store(&mut state.records, writes);
}
Ok(response)
}
None => {
apply_to_store(&mut state.records, writes);
Ok(ok(json!({ "results": [] })))
}
}
}
async fn list_records(
&self,
repo: &str,
collection: &str,
cursor: Option<&str>,
limit: Option<usize>,
access_jwt: &str,
) -> anyhow::Result<XrpcResponse> {
let mut state = self.state();
state.calls.push(ApiCall {
method: "listRecords",
repo: repo.to_owned(),
collection: collection.to_owned(),
access: access_jwt.to_owned(),
cursor: cursor.map(str::to_owned),
limit,
..ApiCall::default()
});
match scripted(state.list.pop_front())? {
Some(response) => Ok(response),
None => Ok(list_page(&state.records, repo, collection, cursor, limit)),
}
}
async fn delete_record(
&self,
repo: &str,
collection: &str,
rkey: &str,
access_jwt: &str,
) -> anyhow::Result<XrpcResponse> {
let mut state = self.state();
state.calls.push(ApiCall {
method: "deleteRecord",
repo: repo.to_owned(),
collection: collection.to_owned(),
rkey: rkey.to_owned(),
access: access_jwt.to_owned(),
..ApiCall::default()
});
let key = (collection.to_owned(), rkey.to_owned());
match scripted(state.delete.pop_front())? {
Some(response) => {
if response.status == 200 {
state.records.remove(&key);
}
Ok(response)
}
None => {
if state.records.remove(&key).is_some() {
Ok(ok(json!({"commit": {"cid": DELETE_CID}})))
} else {
Ok(missing_record())
}
}
}
}
async fn upload_blob(
&self,
bytes: &[u8],
mime_type: &str,
access_jwt: &str,
) -> anyhow::Result<XrpcResponse> {
let mut state = self.state();
state.calls.push(ApiCall {
method: "uploadBlob",
access: access_jwt.to_owned(),
bytes: Some(bytes.to_vec()),
mime: Some(mime_type.to_owned()),
..ApiCall::default()
});
match scripted(state.upload.pop_front())? {
Some(response) => Ok(response),
None => Ok(ok(json!({}))),
}
}
}
// ---------------------------------------------------------------------------
// Builders
// ---------------------------------------------------------------------------
pub fn response(status: u16, body: Value) -> Reply {
Reply::Response(XrpcResponse {
status,
headers: HashMap::new(),
body,
bytes: Vec::new(),
})
}
pub fn response_with_headers(status: u16, body: Value, headers: &[(&str, &str)]) -> Reply {
Reply::Response(XrpcResponse {
status,
headers: headers
.iter()
.map(|(key, value)| ((*key).to_owned(), (*value).to_owned()))
.collect(),
body,
bytes: Vec::new(),
})
}
pub fn session_body(access: &str, refresh: &str) -> Value {
json!({
"did": REPO,
"handle": "alice.test",
"accessJwt": access,
"refreshJwt": refresh,
})
}
pub fn ok_session(access: &str, refresh: &str) -> Reply {
response(200, session_body(access, refresh))
}
pub fn record_uri(repo: &str, collection: &str, rkey: &str) -> String {
format!("at://{repo}/{collection}/{rkey}")
}
pub fn strong_ref(uri: &str, cid: &str) -> Value {
json!({"uri": uri, "cid": cid})
}
pub async fn governor(db: &DbHandle, time: Arc<FakeTime>) -> Arc<RateGovernor> {
Arc::new(RateGovernor::new(
db.clone(),
5_000.0,
35_000.0,
3_000.0,
time,
))
}
pub async fn publisher_with(
api: Arc<dyn PdsApi>,
time: Arc<FakeTime>,
collection: &str,
logger: Logger,
) -> (Publisher, Arc<RateGovernor>, DbHandle) {
let db = DbHandle::open_in_memory().await.expect("in-memory db");
let governor = governor(&db, time.clone()).await;
let publisher = Publisher::with_api(
PublisherConfig {
pds_url: "http://127.0.0.1:2583".to_owned(),
handle: "alice.test".to_owned(),
app_password: "app-pw".to_owned(),
collection: collection.to_owned(),
timeout_secs: 5.0,
governor: governor.clone(),
},
api,
logger,
time,
)
.expect("publisher");
(publisher, governor, db)
}
pub fn logger() -> (Logger, Arc<CaptureSink>) {
let sink = Arc::new(CaptureSink::default());
(Logger::new(sink.clone(), Level::Debug), sink)
}
pub fn prepared(cve_id: &str) -> PreparedRow {
PreparedRow {
cve_id: cve_id.to_owned(),
record: json!({"$type": COLLECTION, "id": cve_id}),
mode: "normal".to_owned(),
blob: None,
sha256: None,
blob_bytes: 0,
record_bytes: 123,
reason: None,
}
}
/// Publisher backed by a real clock (software graph tests).
pub fn make_publisher(api: Arc<dyn PdsApi>, db: &DbHandle) -> Publisher {
let config = PublisherConfig {
pds_url: "http://127.0.0.1:2583".to_owned(),
handle: "alice.test".to_owned(),
app_password: "app-pw".to_owned(),
collection: COLLECTION.to_owned(),
timeout_secs: 60.0,
governor: Arc::new(RateGovernor::new(
db.clone(),
5_000.0,
35_000.0,
3_000.0,
Arc::new(RealTime),
)),
};
Publisher::with_api(config, api, Logger::stderr(Level::Info), Arc::new(RealTime))
.expect("fake publisher")
}