bzr 0.2.0

A CLI for Bugzilla, inspired by gh
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
use std::fmt;

#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum BzrError {
    #[error("HTTP request failed: {}", format_http_error(.0))]
    Http(#[from] reqwest::Error),

    #[error("Config error: {0}")]
    Config(String),

    #[error("Bugzilla API error: {message} (code {code})")]
    Api { code: i64, message: String },

    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    #[error("TOML parse error: {0}")]
    TomlParse(#[from] toml::de::Error),

    #[error("TOML serialize error: {0}")]
    TomlSerialize(#[from] toml::ser::Error),

    #[error("XML-RPC error: {0}")]
    XmlRpc(String),

    #[error("{resource} not found: {id}")]
    NotFound { resource: &'static str, id: String },

    #[error("HTTP {status}: {body}")]
    HttpStatus { status: u16, body: String },

    #[error("{0}")]
    InputValidation(String),

    #[error("Failed to parse response: {0}")]
    Deserialize(String),

    #[error("Authentication error: {0}")]
    Auth(String),

    #[error("Data integrity error: {0}")]
    DataIntegrity(String),

    #[error("batch update: {succeeded} succeeded, {failed} failed")]
    BatchPartialFailure { succeeded: usize, failed: usize },

    #[error("keyring error: {0}")]
    Keyring(String),

    #[error("TLS pin mismatch for {server}: expected {expected}, got {actual}")]
    PinMismatch {
        server: String,
        expected: String,
        actual: String,
    },

    #[error(
        "TLS certificate issuer changed for {server}: expected \"{expected_issuer}\", \
         got \"{actual_issuer}\" — possible MITM attack"
    )]
    IssuerChanged {
        server: String,
        expected_issuer: String,
        actual_issuer: String,
    },

    #[error("{0}")]
    Other(String),
}

pub type Result<T> = std::result::Result<T, BzrError>;

// Error type constants for type-safe error classification
const ERROR_TYPE_CONFIG: &str = "config";
const ERROR_TYPE_API: &str = "api";
const ERROR_TYPE_HTTP: &str = "http";
const ERROR_TYPE_IO: &str = "io";
const ERROR_TYPE_NOT_FOUND: &str = "not_found";
const ERROR_TYPE_INPUT: &str = "input";
const ERROR_TYPE_DESERIALIZE: &str = "deserialize";
const ERROR_TYPE_AUTH: &str = "auth";
const ERROR_TYPE_DATA_INTEGRITY: &str = "data_integrity";
const ERROR_TYPE_BATCH_PARTIAL_FAILURE: &str = "batch_partial_failure";
const ERROR_TYPE_KEYRING: &str = "keyring";
const ERROR_TYPE_TLS: &str = "tls";
const ERROR_TYPE_OTHER: &str = "other";

// Exit code constants
const EXIT_CODE_OTHER: i32 = 1;
const EXIT_CODE_NOT_FOUND: i32 = 2;
const EXIT_CODE_CONFIG: i32 = 3;
const EXIT_CODE_API: i32 = 4;
const EXIT_CODE_HTTP: i32 = 5;
const EXIT_CODE_IO: i32 = 6;
const EXIT_CODE_INPUT: i32 = 7;
const EXIT_CODE_DESERIALIZE: i32 = 8;
const EXIT_CODE_AUTH: i32 = 9;
const EXIT_CODE_DATA_INTEGRITY: i32 = 10;
const EXIT_CODE_BATCH_PARTIAL_FAILURE: i32 = 11;
const EXIT_CODE_KEYRING: i32 = 12;
const EXIT_CODE_TLS: i32 = 13;

/// Bugzilla internal server error code (HTTP 500 with code 100500).
/// Used for retry logic in hybrid mode when extensions crash.
pub const BUGZILLA_INTERNAL_ERROR: i64 = 100_500;

/// Walk a `std::error::Error` source chain into a single string.
///
/// reqwest's `Display` only shows the error kind and URL, omitting the
/// underlying cause. This helper concatenates the full chain so callers
/// get actionable messages like "error sending request …: invalid peer
/// certificate: `UnknownIssuer`".
pub(crate) fn format_error_chain(err: &dyn std::error::Error) -> String {
    let mut full = err.to_string();
    let mut source = err.source();
    while let Some(cause) = source {
        full.push_str(": ");
        full.push_str(&cause.to_string());
        source = cause.source();
    }
    full
}

/// Format a reqwest error for display: redact API keys and add TLS hints.
fn format_http_error(err: &reqwest::Error) -> String {
    let chain = format_error_chain(err);
    let mut msg = redact_api_key(&chain);
    if crate::http::is_connect_tls_error(err.is_connect(), &chain) {
        msg.push_str(crate::http::TLS_HINT);
    }
    msg
}

fn redact_api_key(msg: &str) -> String {
    const MARKER: &str = "Bugzilla_api_key=";
    if let Some(idx) = msg.find(MARKER) {
        let prefix = &msg[..idx + MARKER.len()];
        // Find the end of the key value (next & or ) or end of string)
        let rest = &msg[idx + MARKER.len()..];
        let end = rest.find(['&', ')', ' ']).unwrap_or(rest.len());
        format!("{prefix}[REDACTED]{}", &rest[end..])
    } else {
        msg.to_string()
    }
}

impl BzrError {
    pub fn config(msg: impl fmt::Display) -> Self {
        BzrError::Config(msg.to_string())
    }

    /// Returns `true` for transport-level failures that may succeed on retry
    /// via a different protocol (e.g. XML-RPC fallback in Hybrid mode).
    /// Domain errors like `Auth`, `NotFound`, and `Config` are not retriable.
    pub fn is_transport_failure(&self) -> bool {
        matches!(
            self,
            BzrError::Http(_) | BzrError::HttpStatus { .. } | BzrError::XmlRpc(_)
        )
    }

    pub fn exit_code(&self) -> i32 {
        match self {
            BzrError::Config(_) | BzrError::TomlParse(_) | BzrError::TomlSerialize(_) => {
                EXIT_CODE_CONFIG
            }
            BzrError::Api { .. } | BzrError::XmlRpc(_) => EXIT_CODE_API,
            BzrError::Http(_) | BzrError::HttpStatus { .. } => EXIT_CODE_HTTP,
            BzrError::Io(_) => EXIT_CODE_IO,
            BzrError::NotFound { .. } => EXIT_CODE_NOT_FOUND,
            BzrError::InputValidation(_) => EXIT_CODE_INPUT,
            BzrError::Deserialize(_) => EXIT_CODE_DESERIALIZE,
            BzrError::Auth(_) => EXIT_CODE_AUTH,
            BzrError::DataIntegrity(_) => EXIT_CODE_DATA_INTEGRITY,
            BzrError::BatchPartialFailure { .. } => EXIT_CODE_BATCH_PARTIAL_FAILURE,
            BzrError::Keyring(_) => EXIT_CODE_KEYRING,
            BzrError::PinMismatch { .. } | BzrError::IssuerChanged { .. } => EXIT_CODE_TLS,
            BzrError::Other(_) => EXIT_CODE_OTHER,
        }
    }

    pub fn error_type(&self) -> &'static str {
        match self {
            BzrError::Config(_) | BzrError::TomlParse(_) | BzrError::TomlSerialize(_) => {
                ERROR_TYPE_CONFIG
            }
            BzrError::Api { .. } | BzrError::XmlRpc(_) => ERROR_TYPE_API,
            BzrError::Http(_) | BzrError::HttpStatus { .. } => ERROR_TYPE_HTTP,
            BzrError::Io(_) => ERROR_TYPE_IO,
            BzrError::NotFound { .. } => ERROR_TYPE_NOT_FOUND,
            BzrError::InputValidation(_) => ERROR_TYPE_INPUT,
            BzrError::Deserialize(_) => ERROR_TYPE_DESERIALIZE,
            BzrError::Auth(_) => ERROR_TYPE_AUTH,
            BzrError::DataIntegrity(_) => ERROR_TYPE_DATA_INTEGRITY,
            BzrError::BatchPartialFailure { .. } => ERROR_TYPE_BATCH_PARTIAL_FAILURE,
            BzrError::Keyring(_) => ERROR_TYPE_KEYRING,
            BzrError::PinMismatch { .. } | BzrError::IssuerChanged { .. } => ERROR_TYPE_TLS,
            BzrError::Other(_) => ERROR_TYPE_OTHER,
        }
    }
}

#[cfg(test)]
#[expect(clippy::unwrap_used)]
mod tests {
    use super::*;

    #[test]
    fn exit_code_config() {
        let err = BzrError::Config("bad config".into());
        assert_eq!(err.exit_code(), 3);
    }

    #[test]
    fn exit_code_api() {
        let err = BzrError::Api {
            code: 101,
            message: "Invalid Bug ID".into(),
        };
        assert_eq!(err.exit_code(), 4);
    }

    #[test]
    fn exit_code_io() {
        let err = BzrError::Io(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "file not found",
        ));
        assert_eq!(err.exit_code(), 6);
    }

    #[test]
    fn exit_code_other() {
        let err = BzrError::Other("something went wrong".into());
        assert_eq!(err.exit_code(), 1);
    }

    #[test]
    fn exit_code_toml_parse() {
        let toml_err: std::result::Result<toml::Value, _> = toml::from_str("{{bad");
        let err = BzrError::TomlParse(toml_err.unwrap_err());
        assert_eq!(err.exit_code(), 3);
    }

    #[test]
    fn error_type_config() {
        let err = BzrError::Config("x".into());
        assert_eq!(err.error_type(), "config");
    }

    #[test]
    fn error_type_api() {
        let err = BzrError::Api {
            code: 1,
            message: "x".into(),
        };
        assert_eq!(err.error_type(), "api");
    }

    #[test]
    fn error_type_io() {
        let err = BzrError::Io(std::io::Error::other("x"));
        assert_eq!(err.error_type(), "io");
    }

    #[test]
    fn error_type_other() {
        let err = BzrError::Other("x".into());
        assert_eq!(err.error_type(), "other");
    }

    #[test]
    fn exit_code_not_found() {
        let err = BzrError::NotFound {
            resource: "bug",
            id: "42".into(),
        };
        assert_eq!(err.exit_code(), 2);
        assert_eq!(err.error_type(), "not_found");
        assert_eq!(err.to_string(), "bug not found: 42");
    }

    #[test]
    fn error_type_toml_parse() {
        let toml_err: std::result::Result<toml::Value, _> = toml::from_str("{{bad");
        let err = BzrError::TomlParse(toml_err.unwrap_err());
        assert_eq!(err.error_type(), "config");
    }

    #[test]
    fn exit_code_http_status() {
        let err = BzrError::HttpStatus {
            status: 500,
            body: "internal error".into(),
        };
        assert_eq!(err.exit_code(), 5);
        assert_eq!(err.error_type(), "http");
        assert_eq!(err.to_string(), "HTTP 500: internal error");
    }

    #[test]
    fn exit_code_input_validation() {
        let err = BzrError::InputValidation("bad flag".into());
        assert_eq!(err.exit_code(), 7);
        assert_eq!(err.error_type(), "input");
        assert_eq!(err.to_string(), "bad flag");
    }

    #[test]
    fn exit_code_deserialize() {
        let err = BzrError::Deserialize("invalid JSON".into());
        assert_eq!(err.exit_code(), 8);
        assert_eq!(err.error_type(), "deserialize");
        assert_eq!(err.to_string(), "Failed to parse response: invalid JSON");
    }

    #[test]
    fn exit_code_auth() {
        let err = BzrError::Auth("invalid API key".into());
        assert_eq!(err.exit_code(), 9);
        assert_eq!(err.error_type(), "auth");
        assert_eq!(err.to_string(), "Authentication error: invalid API key");
    }

    #[test]
    fn exit_code_data_integrity() {
        let err = BzrError::DataIntegrity("attachment has no data".into());
        assert_eq!(err.exit_code(), 10);
        assert_eq!(err.error_type(), "data_integrity");
    }

    #[test]
    fn sanitize_http_error_redacts_api_key() {
        let input = "error sending request for url (http://localhost:8090/rest/extensions?Bugzilla_api_key=SecretKey123)";
        let result = redact_api_key(input);
        assert!(
            !result.contains("SecretKey123"),
            "API key should be redacted: {result}"
        );
        assert!(
            result.contains("Bugzilla_api_key=[REDACTED]"),
            "should contain redacted placeholder: {result}"
        );
        assert!(
            result.contains("rest/extensions"),
            "path should be preserved: {result}"
        );
    }

    #[test]
    fn sanitize_http_error_preserves_message_without_key() {
        let input = "connection refused";
        let result = redact_api_key(input);
        assert_eq!(result, "connection refused");
    }

    #[test]
    fn sanitize_http_error_redacts_marker_at_string_start() {
        // The marker at index 0 is the boundary case for the post-marker
        // slicing arithmetic — must not underflow.
        let input = "Bugzilla_api_key=secret";
        let result = redact_api_key(input);
        assert_eq!(result, "Bugzilla_api_key=[REDACTED]");
    }

    #[test]
    fn sanitize_http_error_handles_key_with_other_params() {
        let input =
            "error for url (http://host/rest/bug?Bugzilla_api_key=secret&include_fields=id)";
        let result = redact_api_key(input);
        assert!(
            !result.contains("secret"),
            "API key should be redacted: {result}"
        );
        assert!(
            result.contains("&include_fields=id"),
            "other params should be preserved: {result}"
        );
    }

    #[test]
    fn exit_code_keyring() {
        let err = BzrError::Keyring("keychain locked".into());
        assert_eq!(err.exit_code(), 12);
        assert_eq!(err.error_type(), "keyring");
        assert_eq!(err.to_string(), "keyring error: keychain locked");
    }

    #[test]
    fn exit_code_pin_mismatch() {
        let err = BzrError::PinMismatch {
            server: "test".into(),
            expected: "sha256//old".into(),
            actual: "sha256//new".into(),
        };
        assert_eq!(err.exit_code(), 13);
        assert_eq!(err.error_type(), "tls");
        assert!(err.to_string().contains("pin mismatch"));
    }

    #[test]
    fn exit_code_issuer_changed() {
        let err = BzrError::IssuerChanged {
            server: "test".into(),
            expected_issuer: "CN=Good CA".into(),
            actual_issuer: "CN=Evil CA".into(),
        };
        assert_eq!(err.exit_code(), 13);
        assert_eq!(err.error_type(), "tls");
        assert!(err.to_string().contains("MITM"));
    }

    /// reqwest's `Display` omits the source chain (e.g. "connection refused").
    /// Verify that `format_http_error` walks the chain so the user sees the
    /// actual cause, not just "error sending request for url (URL)".
    #[tokio::test]
    async fn format_http_error_includes_source_chain() {
        let client = reqwest::Client::builder().build().unwrap();
        // Connect to a port that is almost certainly not listening.
        let err = client
            .get("http://127.0.0.1:1/unreachable")
            .send()
            .await
            .unwrap_err();

        // reqwest Display: only kind + URL, no cause
        let display_only = err.to_string();
        assert!(
            display_only.contains("error sending request"),
            "expected reqwest error kind: {display_only}"
        );

        let formatted = format_http_error(&err);
        // Our formatter must include the underlying OS-level cause
        assert!(
            formatted.len() > display_only.len(),
            "format_http_error should include source chain, got: {formatted}"
        );
        // The source chain should mention connection-level detail
        assert!(
            formatted.contains("connect")
                || formatted.contains("refused")
                || formatted.contains("tcp"),
            "expected connection-level detail in: {formatted}"
        );
    }
}