wot-network 0.0.6

Data structures for OpenPGP Web of Trust calculations
Documentation
//! Helper for mapping cert identifiers (e.g. OpenPGP fingerprints) to short human-friendly strings.
//!
//! This can be nice to have to map test-data that uses fingerprints as certificate identifiers
//! to human-readable short-hands.
//!
//! E.g. Alice's certificate might have the fingerprint `468df36d08e878d73b90af1d33740db9e63b0245`,
//! but we might like to map the certificate identifier to `A` for easy human readability.
//!
//! Such a mapping can be useful to make test specifications as well as mermaid
//! representations of WoT network graphs easier to read.

use std::{
    collections::HashMap,
    fs::File,
    io::{BufRead, BufReader},
    path::Path,
};

use crate::{Binding, Network};

/// Very naive implementation of loading a certificate id mapping file.
///
/// Input files are expected to contain a series of lines of the form:
///
/// `468df36d08e878d73b90af1d33740db9e63b0245,A`
/// `7b64f0f207214f9894a2f4d08a95e57f3c773e72,B`
pub fn load_certid_map(path: &Path) -> HashMap<String, String> {
    let mut map = HashMap::new();

    let file = File::open(path).expect("FIXME");
    for line in BufReader::new(file).lines() {
        let line = line.expect("FIXME");
        let Some((a, b)) = line.split_once(',') else {
            panic!("FIXME")
        };

        map.insert(a.trim().to_string(), b.trim().to_string());
    }

    map
}

/// Transform a [Network] into a variant of itself by mapping certificate identifiers to (usually)
/// shortened versions of themselves.
///
/// This is typically used to map test data that uses fingerprint-based certificate identifiers to
/// human-readable shorthand names.
pub fn map_names(input: &Network, map: HashMap<String, String>) -> Network {
    let apply_map = |input: &str| map.get(input).map_or(input, |v| v).to_string();

    let mut output = Network::new();

    for certification in input.certifications.values().flatten() {
        output.add_binding(
            apply_map(&certification.issuer.0).into(),
            Binding {
                cert: apply_map(&certification.target.cert.0).into(),
                identity: certification.target.identity.clone(),
            },
        );
    }

    for delegation in input.delegations.values().flatten() {
        output.add_delegation(
            apply_map(&delegation.issuer.0).into(),
            apply_map(&delegation.target.0).into(),
            delegation.trust_amount,
            delegation.trust_depth,
            delegation.regexes.clone(),
        );
    }

    output
}