summaryrefslogtreecommitdiffstats
path: root/sq/src/commands/mappings.rs
blob: 0846cb52d8b1c7c8e09066a1401c7de839b52e33 (plain)
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
use anyhow::Context;

use prettytable::{Table, Cell, Row, row, cell};

use sequoia_openpgp as openpgp;
use openpgp::{
    Result,
    cert::{
        Cert,
    },
    parse::Parse,
    serialize::Serialize,
};
use sequoia_store as store;
use store::{
    Mapping,
    LogIter,
};

use crate::{
    Config,
    help_warning,
    commands::dump::Convert,
    open_or_stdin,
    create_or_stdout,
};

pub fn dispatch_mapping(config: Config, m: &clap::ArgMatches) -> Result<()> {
    let mapping = Mapping::open(&config.context, config.network_policy,
                                &config.realm_name, &config.mapping_name)
        .context("Failed to open the mapping")?;

    match m.subcommand() {
        ("list",  Some(_)) => {
            list_bindings(&mapping, &config.realm_name, &config.mapping_name)?;
        },
        ("add",  Some(m)) => {
            let fp = m.value_of("fingerprint").unwrap().parse()
                .expect("Malformed fingerprint");
            mapping.add(m.value_of("label").unwrap(), &fp)?;
        },
        ("import",  Some(m)) => {
            let label = m.value_of("label").unwrap();
            help_warning(label);
            let mut input = open_or_stdin(m.value_of("input"))?;
            let cert = Cert::from_reader(&mut input)?;
            mapping.import(label, &cert)?;
        },
        ("export",  Some(m)) => {
            let cert = mapping.lookup(m.value_of("label").unwrap())?.cert()?;
            let mut output = create_or_stdout(m.value_of("output"),
                                              config.force)?;
            if m.is_present("binary") {
                cert.serialize(&mut output)?;
            } else {
                cert.armored().serialize(&mut output)?;
            }
        },
        ("delete",  Some(m)) => {
            if m.is_present("label") == m.is_present("the-mapping") {
                return Err(anyhow::anyhow!(
                    "Please specify either a label or --the-mapping."));
            }

            if m.is_present("the-mapping") {
                mapping.delete().context("Failed to delete the mapping")?;
            } else {
                let binding = mapping.lookup(m.value_of("label").unwrap())
                    .context("Failed to get key")?;
                binding.delete().context("Failed to delete the binding")?;
            }
        },
        ("stats",  Some(m)) => {
            mapping_print_stats(&mapping,
                                m.value_of("label").unwrap())?;
        },
        ("log",  Some(m)) => {
            if m.is_present("label") {
                let binding = mapping.lookup(m.value_of("label").unwrap())
                    .context("No such key")?;
                print_log(binding.log().context("Failed to get log")?, false);
            } else {
                print_log(mapping.log().context("Failed to get log")?, true);
            }
        },
        _ => unreachable!(),
    }

    Ok(())
}

pub fn dispatch_list(config: Config, m: &clap::ArgMatches) -> Result<()> {
    match m.subcommand() {
        ("mappings",  Some(m)) => {
            let mut table = Table::new();
            table.set_format(*prettytable::format::consts::FORMAT_NO_LINESEP_WITH_TITLE);
            table.set_titles(row!["realm", "name", "network policy"]);

            for (realm, name, network_policy, _)
                in Mapping::list(&config.context, m.value_of("prefix").unwrap_or(""))? {
                    table.add_row(Row::new(vec![
                        Cell::new(&realm),
                        Cell::new(&name),
                        Cell::new(&format!("{:?}", network_policy))
                    ]));
                }

            table.printstd();
        },
        ("bindings",  Some(m)) => {
            for (realm, name, _, mapping)
                in Mapping::list(&config.context, m.value_of("prefix").unwrap_or(""))? {
                    list_bindings(&mapping, &realm, &name)?;
                }
        },
        ("keys",  Some(_)) => {
            let mut table = Table::new();
            table.set_format(*prettytable::format::consts::FORMAT_NO_LINESEP_WITH_TITLE);
            table.set_titles(row!["fingerprint", "updated", "status"]);

            for (fingerprint, key) in store::Store::list_keys(&config.context)? {
                let stats = key.stats()
                    .context("Failed to get key stats")?;
                table.add_row(Row::new(vec![
                    Cell::new(&fingerprint.to_string()),
                    if let Some(t) = stats.updated {
                        Cell::new(&t.convert().to_string())
                    } else {
                        Cell::new("")
                    },
                    Cell::new("")
                ]));
            }

            table.printstd();
        },
        ("log",  Some(_)) => {
            print_log(store::Store::server_log(&config.context)?, true);
        },
        _ => unreachable!(),
    }

    Ok(())
}

fn list_bindings(mapping: &Mapping, realm: &str, name: &str)
                 -> Result<()> {
    if mapping.iter()?.count() == 0 {
        println!("No label-key bindings in the \"{}/{}\" mapping.",
                 realm, name);
        return Ok(());
    }

    println!("Realm: {:?}, mapping: {:?}:", realm, name);

    let mut table = Table::new();
    table.set_format(*prettytable::format::consts::FORMAT_NO_LINESEP_WITH_TITLE);
    table.set_titles(row!["label", "fingerprint"]);
    for (label, fingerprint, _) in mapping.iter()? {
        table.add_row(Row::new(vec![
            Cell::new(&label),
            Cell::new(&fingerprint.to_string())]));
    }
    table.printstd();
    Ok(())