~ knotless Search/
↑↓ move↵ open⇧↵ all results

johnandersen777.bsky.social/vuln-notif

0
0
main
616 lines · 17.3 KB Raw History
//! 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")
}