summaryrefslogtreecommitdiffstats
path: root/openpgp/tests/for-each-artifact.rs
blob: cb729dc543b1d22a5d9adc3571a8ec6071bdf613 (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
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
use std::env;
use std::fmt::Write;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};

use anyhow::anyhow;

use sequoia_openpgp as openpgp;
use crate::openpgp::parse::*;
use crate::openpgp::PacketPile;
use crate::openpgp::Result;
use crate::openpgp::serialize::{Serialize, SerializeInto};

mod for_each_artifact {
    use super::*;

    // Pretty print buf as a hexadecimal string.
    fn hex(buf: &[u8]) -> Result<String> {
        let mut s = String::new();
        for (i, b) in buf.iter().enumerate() {
            if i % 32 == 0 {
                if i > 0 {
                    write!(s, "\n")?;
                }
                write!(s, "{:04}:", i)?;
            }
            if i % 2 == 0 {
                write!(s, " ")?;
            }
            if i % 8 == 0 {
                write!(s, " ")?;
            }
            write!(s, "{:02X}", b)?;
        }
        writeln!(s, "")?;
        Ok(s)
    }

    // Find the first difference between two serialized messages.
    fn diff_serialized(a: &[u8], b: &[u8]) -> Result<()> {
        if a == b {
            return Ok(())
        }

        // There's a difference.  Find it.
        let p = PacketPile::from_bytes(a)?.into_children();
        let p_len = p.len();

        let q = PacketPile::from_bytes(b)?.into_children();
        let q_len = q.len();

        let mut offset = 0;
        for (i, (p, q)) in p.zip(q).enumerate() {
            let a = &a[offset..offset+p.serialized_len()];
            let b = &b[offset..offset+q.serialized_len()];

            if a == b {
                offset += p.serialized_len();
                continue;
            }

            eprintln!("Difference detected at packet #{}, offset: {}",
                      i, offset);

            eprintln!(" left packet: {:?}", p);
            eprintln!("right packet: {:?}", q);
            eprintln!(" left hex ({} bytes):\n{}", a.len(), hex(a)?);
            eprintln!("right hex ({} bytes):\n{}", b.len(), hex(b)?);

            return Err(anyhow!("Packets #{} differ at offset {}",
                               i, offset));
        }

        assert!(p_len != q_len);
        eprintln!("Differing number of packets: {} bytes vs. {} bytes",
                  p_len, q_len);

        return Err(
            anyhow!("Differing number of packets: {} bytes vs. {} bytes",
                    p_len, q_len));
    }

    #[test]
    fn packet_roundtrip() {
        for_all_files(&test_data_dir(), |src| {
            for_all_packets(src, |p| {
                let mut v = Vec::new();
                p.serialize(&mut v)?;
                let q = openpgp::Packet::from_bytes(&v)?;
                if p != &q {
                    return Err(anyhow::anyhow!(
                        "assertion failed: p == q\np = {:?}\nq = {:?}", p, q));
                }
                let w = p.to_vec()?;
                if v != w {
                    return Err(anyhow::anyhow!(
                        "assertion failed: v == w\nv = {:?}\nw = {:?}", v, w));
                }
                Ok(())
            })
        }).unwrap();
    }

    #[test]
    fn cert_roundtrip() {
        for_all_files(&test_data_dir(), |src| {
            let p = if let Ok(cert) = openpgp::Cert::from_file(src) {
                cert
            } else {
                // Ignore non-Cert files.
                return Ok(());
            };

            let mut v = Vec::new();
            p.as_tsk().serialize(&mut v)?;
            let q = openpgp::Cert::from_bytes(&v)?;
            if p != q {
                eprintln!("roundtripping {:?} failed", src);

                let p_: Vec<_> = p.clone().as_tsk().into_packets().collect();
                let q_: Vec<_> = q.clone().as_tsk().into_packets().collect();
                eprintln!("original: {} packets; roundtripped: {} packets",
                          p_.len(), q_.len());

                for (i, (p, q)) in p_.iter().zip(q_.iter()).enumerate() {
                    if p != q {
                        eprintln!("First difference at packet {}:\nOriginal: {:?}\nNew: {:?}",
                                  i, p, q);
                        break;
                    }
                }

                eprintln!("This is the recovered cert:\n{}",
                          String::from_utf8_lossy(
                              &q.armored().to_vec().unwrap()));
            }
            assert_eq!(p, q, "roundtripping {:?} failed", src);

            let w = p.as_tsk().to_vec().unwrap();
            assert_eq!(v, w,
                       "Serialize and SerializeInto disagree on {:?}", p);

            // Check that Cert::into_packets2() and Cert::to_vec()
            // agree.  (Cert::into_packets2() returns no secret keys if
            // secret key material is present; Cert::to_vec only ever
            // returns public keys.)
            let v = p.to_vec()?;
            let mut buf = Vec::new();
            for p in p.clone().into_packets2() {
                p.serialize(&mut buf)?;
            }
            if let Err(_err) = diff_serialized(&buf, &v) {
                panic!("Checking that \
                        Cert::into_packets2() \
                        and Cert::to_vec() agree.");
            }

            // Check that Cert::as_tsk().into_packets() and
            // Cert::as_tsk().to_vec() agree.
            let v = p.as_tsk().to_vec()?;
            let mut buf = Vec::new();
            for p in p.as_tsk().into_packets() {
                p.serialize(&mut buf)?;
            }
            if let Err(_err) = diff_serialized(&buf, &v<