lintian-brush 0.182.0

Automatic lintian issue fixer
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
use crate::declare_detector;
use crate::diagnostic::{Action, Diagnostic, FilesystemAction};
use crate::{FixerError, FixerPreferences, LintianIssue, Visibility};
use debian_workspace::Workspace;
use std::path::{Path, PathBuf};

const KEY_BLOCK_START: &[u8] = b"-----BEGIN PGP PUBLIC KEY BLOCK-----";
const KEY_BLOCK_END: &[u8] = b"-----END PGP PUBLIC KEY BLOCK-----";

/// Result of minimizing a key block
#[derive(Debug)]
enum MinimizeResult {
    /// No changes needed - key is already minimal
    NoChanges,
    /// Third-party signatures were removed (minimized key, keyid, count)
    SignaturesRemoved(Vec<u8>, String, usize),
    /// Only format was upgraded (no signatures removed)
    FormatUpgraded(Vec<u8>),
}

/// Minimize a PGP key block by removing extra signatures
/// This keeps only self-signatures and removes third-party certifications
///
/// If opinionated is true, may upgrade packet format from old to new
/// If opinionated is false, preserves original format
fn minimize_key_block(
    key: &[u8],
    opinionated: bool,
) -> Result<MinimizeResult, Box<dyn std::error::Error>> {
    use sequoia_openpgp::cert::CertParser;
    use sequoia_openpgp::packet::Packet;
    use sequoia_openpgp::parse::{PacketParser, PacketParserResult, Parse};
    use sequoia_openpgp::serialize::Serialize;
    use sequoia_openpgp::KeyHandle;

    // First, use CertParser to understand the certificate structure
    // This tells us which keys belong to the cert so we can identify self-signatures
    let certs: Vec<_> = CertParser::from_bytes(key)?.collect::<Result<Vec<_>, _>>()?;
    if certs.is_empty() {
        return Err("No certificates found in key block".into());
    }

    // Collect KeyHandles for ALL certs (primary keys and all subkeys)
    let mut key_handles: Vec<KeyHandle> = Vec::new();
    for cert in &certs {
        key_handles.push(cert.fingerprint().into());
        key_handles.push(cert.keyid().into());
        for key in cert.keys() {
            key_handles.push(key.key().fingerprint().into());
            key_handles.push(key.key().keyid().into());
        }
    }

    // Now parse the ORIGINAL key data with PacketParser to preserve packet format
    // We'll filter out third-party signatures but keep everything else as-is
    let mut filtered_packets: Vec<Packet> = Vec::new();
    let mut ppr = PacketParser::from_bytes(key)?;
    let mut third_party_count = 0;

    while let PacketParserResult::Some(pp) = ppr {
        let (packet, next_ppr) = pp.recurse()?;

        match &packet {
            Packet::Signature(sig) => {
                // Check if this signature is from one of our keys
                let issuers = sig.get_issuers();
                let is_self_sig = issuers.iter().any(|issuer| key_handles.contains(issuer));

                if is_self_sig {
                    // Keep self-signatures
                    filtered_packets.push(packet);
                } else {
                    // Count but don't keep third-party signatures
                    third_party_count += 1;
                }
            }
            _ => {
                // Keep all non-signature packets (keys, user IDs, etc.) as-is
                filtered_packets.push(packet);
            }
        }

        ppr = next_ppr;
    }

    // Serialize the filtered packets
    use sequoia_openpgp::armor::{Kind, Writer};
    let is_armored = key.windows(5).any(|w| w == b"-----");
    let mut output = Vec::new();

    if is_armored {
        let mut writer = Writer::new(&mut output, Kind::PublicKey)?;
        for packet in &filtered_packets {
            Serialize::serialize(packet, &mut writer)?;
        }
        writer.finalize()?;
    } else {
        for packet in &filtered_packets {
            Serialize::serialize(packet, &mut output)?;
        }
    }

    // Determine what actually changed
    if third_party_count == 0 {
        // No signatures were removed
        if output == key {
            // Serialization is identical - no changes at all
            return Ok(MinimizeResult::NoChanges);
        } else if opinionated {
            // Serialization differs (format change) and opinionated mode allows it
            return Ok(MinimizeResult::FormatUpgraded(output));
        } else {
            // Serialization differs but we're not opinionated - don't upgrade format
            return Ok(MinimizeResult::NoChanges);
        }
    }

    // Signatures were removed - get the primary key's keyid
    let keyid = certs[0].keyid().to_hex();

    Ok(MinimizeResult::SignaturesRemoved(
        output,
        keyid,
        third_party_count,
    ))
}

pub fn detect(
    ws: &dyn Workspace,
    preferences: &FixerPreferences,
) -> Result<Vec<Diagnostic>, FixerError> {
    let opinionated = preferences.opinionated.unwrap_or(false);
    let paths = [
        "debian/upstream/signing-key.asc",
        "debian/upstream/signing-key.pgp",
        "debian/upstream-signing-key.pgp",
    ];

    let mut diagnostics: Vec<Diagnostic> = Vec::new();

    for path_str in &paths {
        let contents = match ws.read_file(Path::new(path_str))? {
            Some(c) => c,
            None => continue,
        };
        let mut outlines: Vec<u8> = Vec::new();
        let mut key_block: Vec<u8> = Vec::new();
        let mut in_key_block = false;
        let mut signatures_removed_here = false;
        let mut format_upgraded_here = false;
        let mut issues_here: Vec<LintianIssue> = Vec::new();
        let mut i = 0;

        while i < contents.len() {
            let line_start = i;
            let line_end = contents[i..]
                .iter()
                .position(|&b| b == b'\n')
                .map(|pos| i + pos + 1)
                .unwrap_or(contents.len());
            let line = &contents[line_start..line_end];
            let trimmed: Vec<u8> = line
                .iter()
                .filter(|&&b| b != b'\r' && b != b'\n')
                .copied()
                .collect();

            if trimmed == KEY_BLOCK_START {
                in_key_block = true;
                key_block.clear();
                key_block.extend_from_slice(line);
            } else if trimmed == KEY_BLOCK_END && in_key_block {
                key_block.extend_from_slice(line);
                match minimize_key_block(&key_block, opinionated) {
                    Ok(MinimizeResult::NoChanges) => {
                        outlines.extend_from_slice(&key_block);
                    }
                    Ok(MinimizeResult::SignaturesRemoved(minimized, keyid, count)) => {
                        outlines.extend_from_slice(&minimized);
                        signatures_removed_here = true;
                        issues_here.push(LintianIssue::source_with_info(
                            "public-upstream-key-not-minimal",
                            Visibility::Info,
                            vec![format!(
                                "has {} extra signature(s) for keyid {} [{}]",
                                count, keyid, path_str
                            )],
                        ));
                    }
                    Ok(MinimizeResult::FormatUpgraded(upgraded)) => {
                        outlines.extend_from_slice(&upgraded);
                        format_upgraded_here = true;
                    }
                    Err(e) => {
                        tracing::debug!("Unable to minimize key block in {}: {}", path_str, e);
                        outlines.extend_from_slice(&key_block);
                    }
                }
                in_key_block = false;
                key_block.clear();
            } else if in_key_block {
                key_block.extend_from_slice(line);
            } else {
                outlines.extend_from_slice(line);
            }
            i = line_end;
        }
        if in_key_block {
            return Err(FixerError::Other("Key block without end".to_string()));
        }

        if contents == outlines {
            continue;
        }
        let rel = PathBuf::from(*path_str);
        let action = Action::Filesystem(FilesystemAction::Write {
            file: rel,
            content: outlines,
        });
        let (description, label) = if signatures_removed_here {
            (
                "Upstream signing key contains extra signatures.",
                "Re-export upstream signing key without extra signatures.",
            )
        } else if format_upgraded_here {
            (
                "Upstream signing key uses an old packet format.",
                "Upgrade upstream signing key to new packet format.",
            )
        } else {
            continue;
        };
        if issues_here.is_empty() {
            diagnostics.push(Diagnostic::untagged(description, label, vec![action]));
        } else {
            for (i, issue) in issues_here.into_iter().enumerate() {
                let actions = if i == 0 {
                    vec![action.clone()]
                } else {
                    Vec::new()
                };
                diagnostics.push(Diagnostic::with_actions(issue, description, label, actions));
            }
        }
    }

    Ok(diagnostics)
}

declare_detector! {
    name: "public-upstream-key-not-minimal",
    tags: ["public-upstream-key-not-minimal"],
    triggers: [
        debian_workspace::Trigger::File("debian/upstream/signing-key.asc"),
        debian_workspace::Trigger::File("debian/upstream/signing-key.pgp"),
        debian_workspace::Trigger::File("debian/upstream-signing-key.pgp"),
    ],
    detect: |ws, prefs| detect(ws, prefs),
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::detector::Detector;
    use crate::Version;
    use std::fs;
    use tempfile::TempDir;

    fn run_apply(base: &Path, opinionated: bool) -> Result<crate::FixerResult, FixerError> {
        let v: Version = "1.0".parse().unwrap();
        let prefs = FixerPreferences {
            opinionated: Some(opinionated),
            ..Default::default()
        };
        let adapter = DetectorImpl;
        {
            let ws = debian_workspace::fs_workspace::FsWorkspace::new(
                base,
                Some("test".into()),
                Some(v.clone()),
            );
            adapter.apply(&ws, &prefs)
        }
    }

    #[test]
    fn test_minimize_key() {
        let temp_dir = TempDir::new().unwrap();
        let debian_dir = temp_dir.path().join("debian");
        let upstream_dir = debian_dir.join("upstream");
        fs::create_dir_all(&upstream_dir).unwrap();

        // Use the actual test fixture key
        let test_fixture_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(
            "tests/public-upstream-key-not-minimal/simple/in/debian/upstream/signing-key.asc",
        );

        // Skip test if fixture doesn't exist
        if !test_fixture_path.exists() {
            eprintln!(
                "Skipping test: fixture not found at {:?}",
                test_fixture_path
            );
            return;
        }

        let input_key = fs::read(&test_fixture_path).unwrap();
        let key_path = upstream_dir.join("signing-key.asc");
        fs::write(&key_path, &input_key).unwrap();

        // Apply the fixer (not opinionated)
        let result = run_apply(temp_dir.path(), false);
        assert!(result.is_ok());

        // Check that the file was modified and is smaller
        let output_key = fs::read(&key_path).unwrap();
        assert!(output_key.len() < input_key.len());

        // Verify the key is still valid (may be a keyring with multiple certs)
        use sequoia_openpgp::cert::CertParser;
        use sequoia_openpgp::parse::Parse;
        let certs: Vec<_> = CertParser::from_bytes(&output_key)
            .unwrap()
            .collect::<Result<Vec<_>, _>>()
            .unwrap();
        assert!(
            !certs.is_empty(),
            "Output should contain at least one valid cert"
        );
    }

    #[test]
    fn test_already_minimal() {
        let temp_dir = TempDir::new().unwrap();
        let debian_dir = temp_dir.path().join("debian");
        let upstream_dir = debian_dir.join("upstream");
        fs::create_dir_all(&upstream_dir).unwrap();

        // Use the already-minimal test fixture
        let test_fixture_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/public-upstream-key-not-minimal/already-minimal/in/debian/upstream/signing-key.asc");

        if !test_fixture_path.exists() {
            eprintln!(
                "Skipping test: fixture not found at {:?}",
                test_fixture_path
            );
            return;
        }

        let input_key = fs::read(&test_fixture_path).unwrap();
        let key_path = upstream_dir.join("signing-key.asc");
        fs::write(&key_path, &input_key).unwrap();

        // Apply the fixer (not opinionated)
        let result = run_apply(temp_dir.path(), false);

        // Should return NoChanges if already minimal
        assert!(matches!(result, Err(FixerError::NoChanges)));

        // Verify file wasn't changed
        let output_key = fs::read(&key_path).unwrap();
        assert_eq!(
            input_key, output_key,
            "File should not be modified when already minimal"
        );
    }

    #[test]
    fn test_already_minimal_opinionated() {
        let temp_dir = TempDir::new().unwrap();
        let debian_dir = temp_dir.path().join("debian");
        let upstream_dir = debian_dir.join("upstream");
        fs::create_dir_all(&upstream_dir).unwrap();

        // Use the already-minimal test fixture (in old GPG format)
        let test_fixture_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/public-upstream-key-not-minimal/already-minimal/in/debian/upstream/signing-key.asc");

        if !test_fixture_path.exists() {
            eprintln!(
                "Skipping test: fixture not found at {:?}",
                test_fixture_path
            );
            return;
        }

        let input_key = fs::read(&test_fixture_path).unwrap();
        let key_path = upstream_dir.join("signing-key.asc");
        fs::write(&key_path, &input_key).unwrap();

        // Apply the fixer with opinionated=true
        let result = run_apply(temp_dir.path(), true);
        assert!(
            result.is_ok(),
            "Opinionated mode should upgrade format: {:?}",
            result
        );

        let result = result.unwrap();
        assert_eq!(
            result.description, "Upgrade upstream signing key to new packet format.",
            "Should report format upgrade, not tag fix"
        );
        assert!(
            result.fixed_lintian_tags().is_empty(),
            "Should not report any lintian tags as fixed when only upgrading format"
        );

        // Verify file was changed (format upgraded)
        let output_key = fs::read(&key_path).unwrap();
        assert_ne!(
            input_key, output_key,
            "File should be modified in opinionated mode"
        );
    }

    #[test]
    fn test_no_key_file() {
        let temp_dir = TempDir::new().unwrap();

        // Apply the fixer
        let result = run_apply(temp_dir.path(), false);
        assert!(matches!(result, Err(FixerError::NoChanges)));
    }
}