sequoia-git 0.6.0

A tool for managing and enforcing a commit signing policy.
Documentation
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
use std::borrow::Cow;
use std::io;
use std::sync::Mutex;

use git2::{Oid, Repository};
use serde::Serialize;
use openpgp::{
    Cert,
    Fingerprint,
    Packet,
    packet::Signature,
};
use super::*;

/// What output format to prefer, when there's an option?
#[derive(Clone)]
pub enum Format {
    /// Output that is meant to be read by humans, instead of programs.
    ///
    /// This type of output has no version, and is not meant to be
    /// parsed by programs.
    HumanReadable,

    /// Output as JSON.
    Json,
}

impl std::str::FromStr for Format {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "human-readable" => Ok(Self::HumanReadable),
            "json" => Ok(Self::Json),
            _ => Err(anyhow!("unknown output format {:?}", s)),
        }
    }
}

/// Emits a human-readable description of the policy to stdout.
pub fn describe_policy(p: &Policy) -> Result<()> {
    println!("# OpenPGP policy file for git, version {}",
             p.version());
    println!();

    println!("## Commit Goodlist");
    println!();

    for commit in p.commit_goodlist() {
        println!("  - {}", commit);
    }
    println!();

    println!("## Authorizations");
    println!();

    for (i, (name, auth)) in p.authorization().iter().enumerate()
    {
        println!("{}. {}", i, name);
        let ident = vec![' '; i.to_string().len() + 2]
            .into_iter().collect::<String>();

        if auth.sign_commit {
            println!("{}- may sign commits", ident);
        }
        if auth.sign_tag {
            println!("{}- may sign tags", ident);
        }
        if auth.sign_archive {
            println!("{}- may sign archives", ident);
        }
        if auth.add_user {
            println!("{}- may add users", ident);
        }
        if auth.retire_user {
            println!("{}- may retire users", ident);
        }
        if auth.audit {
            println!("{}- may goodlist commits", ident);
        }
        for cert in auth.certs()? {
            println!("{}- has OpenPGP cert: {}", ident,
                     cert?.fingerprint());
        }
    }
    Ok(())
}

/// Emits a human-readable description of a difference between two
/// policies to stdout.
pub fn describe_diff(p: &Diff) -> Result<()> {
    fn quote<'a>(s: &'a str) -> Cow<'a, str> {
        if s.chars().any(|c| {
            ! (c.is_alphanumeric()
               || ['-', '_', '.', '+'].contains(&c))
        })
        {
            format!("{:?}", s).into()
        } else {
            s.into()
        }
    }

    let quote_component = |c: &Packet| -> String {
        match c {
            Packet::PublicSubkey(k) => {
                format!("subkey {}", k.fingerprint())
            }
            Packet::SecretSubkey(k) => {
                format!("subkey (with secret key material) {}", k.fingerprint())
            }
            Packet::UserID(u) => {
                format!("user ID {}", quote(&String::from_utf8_lossy(u.value())))
            }
            c => {
                format!("{} ({:?})", c.tag(), c)
            }
        }
    };

    let is_self_signed = |cert: &Fingerprint, sig: &Signature| -> bool {
        let cert = KeyHandle::from(cert);
        sig.get_issuers().into_iter().any(|kh| kh.aliases(&cert))
    };

    for change in &p.changes {
        use Change::*;
        match change {
            VersionChange { from, to } =>
                println!("  - Version changed from {} to {}.", from, to),

            GoodlistCommit(oid) =>
                println!("  - Commit {} was added to the goodlist.", oid),
            UngoodlistCommit(oid) =>
                println!("  - Commit {} was removed from the goodlist.", oid),

            AddUser(name) =>
                println!("  - User {} was added.", quote(name)),

            RetireUser(name) =>
                println!("  - User {} was retired.", quote(name)),

            AddRight(name, right) =>
                println!("  - User {} was granted the right {}.",
                         quote(name), right),
            RemoveRight(name, right) =>
                println!("  - User {}'s {} right was revoked.",
                         quote(name), right),

            AddCert(name, fpr) =>
                println!("  - User {}: new certificate {}.", quote(name), fpr),
            RemoveCert(name, fpr) =>
                println!("  - User {}: removed certificate {}.", quote(name), fpr),

            AddPacket(name, fpr, component, sig) =>
                println!("  - User {}'s certificate {} has a new {} signature {:02x}{:02x} on {}.",
                         quote(name), fpr,
                         if is_self_signed(fpr, sig) {
                             "self-signed"
                         } else {
                             "third-party"
                         },
                         sig.digest_prefix()[0],
                         sig.digest_prefix()[1],
                         quote_component(component)),
            RemovePacket(name, fpr, component, sig) =>
                println!("  - User {}'s certificate {} lost the {} signature {:02x}{:02x} on {}.",
                         quote(name), fpr,
                         if is_self_signed(fpr, sig) {
                             "self-signed"
                         } else {
                             "third-party"
                         },
                         sig.digest_prefix()[0],
                         sig.digest_prefix()[1],
                         quote_component(component)),
        }
    }

    Ok(())
}

// The version of the commit output.  This follows semantic
// versioning.
static COMMIT_JSON_VERSION: &'static str = "1.0.0";

#[derive(Serialize)]
pub struct Commit<'a> {
    version: &'static str,
    #[serde(serialize_with = "crate::utils::serialize_oid")]
    id: &'a Oid,
    // The commit's summary (if any).
    summary: Option<String>,
    #[serde(serialize_with = "crate::utils::serialize_optional_oid")]
    parent_id: Option<&'a Oid>,
    results: Vec<std::result::Result<String, (String, Option<String>)>>,
}

static MISSING_SIGNATURE_HINT: Mutex<bool> = Mutex::new(false);
static MISSING_KEY_HINT: Mutex<bool> = Mutex::new(false);
static MALFORMED_MESSAGE_HINT: Mutex<bool> = Mutex::new(false);

impl<'a> Commit<'a> {
    pub fn new(git: &Repository,
               id: &'a Oid,
               parent_id: Option<&'a Oid>,
               shadow_policy: &Option<PathBuf>,
               result: &'a sequoia_git::Result<Vec<sequoia_git::Result<(String, Signature, Cert, Fingerprint)>>>)
               -> Result<Self>
    {
        let hint = |e: &Error| -> Option<String> {
            match (shadow_policy, e) {
                (None, _) => None,
                (Some(p), Error::MissingSignature(commit)) => {
                    let mut shown = MISSING_SIGNATURE_HINT.lock().unwrap();
                    if ! *shown {
                        *shown = true;
                        Some(format!("when using an external policy, do\n\n\
                                      git show {1} \n\
                                      \n  and verify that the commit is good.  \
                                      If satisfied, do\n\n\
                                      sq-git policy goodlist --policy-file {0} {1}",
                                     p.display(), commit))
                    } else {
                        None
                    }
                }
                (Some(p), Error::MissingKey(handle)) => {
                    let mut shown = MISSING_KEY_HINT.lock().unwrap();
                    if ! *shown {
                        *shown = true;
                        Some(format!("when using an external policy, do\n\n\
                                      sq keyserver get {1} \n\
                                      \n  and verify that the cert belongs to the \
                                      committer.  If satisfied, do\n\n\
                                      sq-git policy authorize --policy-file {} \
                                      <ROLE-NAME> {} --sign-commit",
                                     p.display(), handle))
                    } else {
                        None
                    }
                }
                (_, Error::Other(e)) => {
                    if let Some(e) = e.downcast_ref::<openpgp::Error>() {
                        if let openpgp::Error::MalformedMessage(_) = e {
                            let mut shown
                                = MALFORMED_MESSAGE_HINT.lock().unwrap();
                            if ! *shown {
                                *shown = true;
                                Some(format!("\
a signature is malformed.  It was probably created by GitHub, which\n\
is known to created invalid signatures.  See the following discussion for\n\
more information:\n\
\n\
https://github.com/orgs/community/discussions/27607"))
                            } else {
                                None
                            }
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                }
                _ => None,
            }
        };

        let mut r = Vec::new();
        match result {
            Ok(results) => {
                for e in results.iter()
                    .filter_map(|r| r.as_ref().err())
                {
                    r.push(Err((e.to_string(), hint(e))));
                }
                for (name, _s, c, _signer_fpr) in results.iter()
                    .filter_map(|r| r.as_ref().ok())
                {
                    r.push(Ok(format!("{} [{}]", name, c.fingerprint())));
                }
            },
            Err(e) => {
                r.push(Err((e.to_string(), hint(e))));
            },
        }

        let mut summary = None;
        match git.find_commit(id.clone()) {
            Ok(commit) => {
                summary = commit.summary().map(String::from);
            }
            Err(err) => {
                eprintln!("Error looking up commit: {}", err);
            }
        }

        Ok(Commit {
            version: COMMIT_JSON_VERSION,
            id,
            summary,
            parent_id,
            results: r,
        })
    }

    pub fn describe(&self, sink: &mut dyn io::Write, verbosity: &Verbosity) -> Result<()> {
        for r in &self.results {
            let id = if let Some(parent_id) = self.parent_id {
                format!("Authenticating {} with {}",
                        self.id, parent_id)
            } else {
                self.id.to_string()
            };

            match r {
                Err((e, hint)) => {
                    if ! verbosity.quiet() {
                        writeln!(sink, "{}:\n  Error: {}", id, e)?;
                        if let Some(summary) = self.summary.as_ref() {
                            writeln!(sink, "  {}", summary)?;
                        }
                        if let Some(h) = hint {
                            writeln!(sink, "\n  Hint: {}", h)?;
                        }
                    }
                },
                Ok(fp) => {
                    if verbosity.verbose() {
                        writeln!(sink, "{}:\n  Signer: {}", id, fp)?;
                        if let Some(summary) = self.summary.as_ref() {
                            writeln!(sink, "  {}", summary)?;
                        }
                    }
                },
            }
        }

        Ok(())
    }
}

#[derive(Serialize)]
pub struct Tag<'a> {
    version: &'static str,
    #[serde(serialize_with = "crate::utils::serialize_tag")]
    tag: &'a git2::Tag<'a>,
    // The tag's summary (if any).
    summary: Option<String>,
    results: Vec<std::result::Result<String, (String, Option<String>)>>,
}

impl<'a> Tag<'a> {
    pub fn new(_git: &Repository,
               tag: &'a git2::Tag<'a>,
               shadow_policy: &Option<PathBuf>,
               result: &'a sequoia_git::Result<Vec<sequoia_git::Result<(String, Signature, Cert, Fingerprint)>>>)
               -> Result<Self>
    {
        let hint = |e: &Error| -> Option<String> {
            match (shadow_policy, e) {
                (None, _) => None,
                (Some(p), Error::MissingKey(handle)) => {
                    let mut shown = MISSING_KEY_HINT.lock().unwrap();
                    if ! *shown {
                        *shown = true;
                        Some(format!("when using an external policy, do\n\n\
                                      sq keyserver get {1} \n\
                                      \n  and verify that the cert belongs to the \
                                      committer.  If satisfied, do\n\n\
                                      sq-git policy authorize --policy-file {} \
                                      <ROLE-NAME> {} --sign-tag",
                                     p.display(), handle))
                    } else {
                        None
                    }
                }
                (_, Error::Other(e)) => {
                    if let Some(e) = e.downcast_ref::<openpgp::Error>() {
                        if let openpgp::Error::MalformedMessage(_) = e {
                            let mut shown
                                = MALFORMED_MESSAGE_HINT.lock().unwrap();
                            if ! *shown {
                                *shown = true;
                                Some(format!("\
a signature is malformed.  It was probably created by GitHub, which\n\
is known to created invalid signatures.  See the following discussion for\n\
more information:\n\
\n\
https://github.com/orgs/community/discussions/27607"))
                            } else {
                                None
                            }
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                }
                _ => None,
            }
        };

        let mut r = Vec::new();
        match result {
            Ok(results) => {
                for e in results.iter()
                    .filter_map(|r| r.as_ref().err())
                {
                    r.push(Err((e.to_string(), hint(e))));
                }
                for (name, _s, c, _signer_fpr) in results.iter()
                    .filter_map(|r| r.as_ref().ok())
                {
                    r.push(Ok(format!("{} [{}]", name, c.fingerprint())));
                }
            },
            Err(e) => {
                r.push(Err((e.to_string(), hint(e))));
            },
        }

        Ok(Tag {
            version: COMMIT_JSON_VERSION,
            tag,
            summary: tag.message().map(|s| s.to_string()),
            results: r,
        })
    }

    pub fn describe(&self, sink: &mut dyn io::Write, verbosity: &Verbosity) -> Result<()> {
        for r in &self.results {
            let id = format!("Authenticating tag {} with {}",
                             self.tag.name().unwrap_or("<missing-tag-name>"),
                             self.tag.target_id());

            match r {
                Err((e, hint)) => {
                    if ! verbosity.quiet() {
                        writeln!(sink, "{}:\n  Error: {}", id, e)?;
                        if let Some(summary) = self.summary.as_ref() {
                            writeln!(sink, "  {}", summary)?;
                        }
                        if let Some(h) = hint {
                            writeln!(sink, "\n  Hint: {}", h)?;
                        }
                    }
                },
                Ok(fp) => {
                    if verbosity.verbose() {
                        writeln!(sink, "{}:\n  Signer: {}", id, fp)?;
                        if let Some(summary) = self.summary.as_ref() {
                            writeln!(sink, "  {}", summary)?;
                        }
                    }
                },
            }
        }

        Ok(())
    }
}

// The version of the commit output.  This follows semantic
// versioning.
static ARCHIVE_JSON_VERSION: &'static str = "1.0.0";

#[derive(Serialize)]
pub struct Archive {
    version: &'static str,
    results: Vec<std::result::Result<String, String>>,
}

impl Archive {
    pub fn new(result: sequoia_git::Result<Vec<sequoia_git::Result<(String, Signature, Cert, Fingerprint)>>>)
               -> Result<Self>
    {
        let mut r = Vec::new();
        match result {
            Ok(results) => {
                for e in results.iter()
                    .filter_map(|r| r.as_ref().err())
                {
                    r.push(Err(e.to_string()));
                }
                for (name, _s, c, _signer_fpr) in results.iter()
                    .filter_map(|r| r.as_ref().ok())
                {
                    r.push(Ok(format!("{} [{}]", name, c.fingerprint())));
                }
            },
            Err(e) => {
                r.push(Err(e.to_string()));
            },
        }

        Ok(Self {
            version: ARCHIVE_JSON_VERSION,
            results: r,
        })
    }

    pub fn describe(&self, sink: &mut dyn io::Write) -> Result<()> {
        for r in &self.results {
            match r {
                Err(e) => {
                    writeln!(sink, "{}", e)?;
                },
                Ok(fp) => {
                    writeln!(sink, "{}", fp)?;
                },
            }
        }

        Ok(())
    }
}