bzr 0.4.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
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
520
521
522
523
524
525
526
527
528
529
530
531
#![expect(clippy::unwrap_used)]

use wiremock::matchers::{body_json, method, path, query_param};
use wiremock::{Mock, MockServer, ResponseTemplate};

use super::super::encode_path;
use super::super::USER_FIELDS_BASIC;
use crate::client::test_helpers::{test_client, test_client_hybrid};
use crate::error::BzrError;
use crate::types::{ApiMode, AuthMethod, CreateGroupParams, UpdateGroupParams};

#[tokio::test]
async fn get_group_members_returns_users() {
    let mock = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/rest/user"))
        .and(query_param("group", "admin"))
        .and(query_param("include_fields", USER_FIELDS_BASIC))
        .and(query_param("match", "*"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "users": [
                {
                    "id": 1,
                    "name": "alice@example.com",
                    "real_name": "Alice",
                    "email": "alice@example.com"
                },
                {
                    "id": 2,
                    "name": "bob@example.com",
                    "real_name": "Bob",
                    "email": "bob@example.com"
                }
            ]
        })))
        .mount(&mock)
        .await;

    let client = test_client(&mock.uri());
    let users = client.get_group_members("admin", false).await.unwrap();
    assert_eq!(users.len(), 2);
    assert_eq!(users[0].name, "alice@example.com");
}

#[tokio::test]
async fn get_group_members_details_sends_include_fields() {
    let mock = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/rest/user"))
        .and(query_param("group", "admin"))
        .and(query_param(
            "include_fields",
            super::super::USER_FIELDS_DETAILED,
        ))
        .and(query_param("match", "*"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "users": [
                {
                    "id": 1,
                    "name": "alice@example.com",
                    "real_name": "Alice",
                    "email": "alice@example.com",
                    "can_login": true,
                    "groups": [{"id": 10, "name": "admin", "description": "Admins"}]
                }
            ]
        })))
        .mount(&mock)
        .await;

    let client = test_client(&mock.uri());
    let users = client.get_group_members("admin", true).await.unwrap();
    assert_eq!(users.len(), 1);
    assert_eq!(users[0].name, "alice@example.com");
    assert_eq!(users[0].groups.len(), 1);
    assert_eq!(users[0].groups[0].name, "admin");
    assert_eq!(users[0].can_login, Some(true));
}

#[tokio::test]
async fn get_group_members_empty() {
    let mock = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/rest/user"))
        .and(query_param("group", "nobody"))
        .and(query_param("match", "*"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({"users": []})))
        .mount(&mock)
        .await;

    let client = test_client(&mock.uri());
    let users = client.get_group_members("nobody", false).await.unwrap();
    assert!(users.is_empty());
}

#[tokio::test]
async fn get_group_members_api_error() {
    let mock = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/rest/user"))
        .and(query_param("group", "nonexistent"))
        .and(query_param("match", "*"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "error": true,
            "code": 51,
            "message": "There is no group named 'nonexistent'."
        })))
        .mount(&mock)
        .await;

    let client = test_client(&mock.uri());
    let err = client
        .get_group_members("nonexistent", false)
        .await
        .unwrap_err();
    let msg = err.to_string();
    assert!(
        msg.contains("nonexistent"),
        "Expected error to mention group name, got: {msg}"
    );
}

#[tokio::test]
async fn add_user_to_group_sends_put() {
    let mock = MockServer::start().await;
    Mock::given(method("PUT"))
        .and(path(format!(
            "/rest/user/{}",
            encode_path("alice@example.com")
        )))
        .and(body_json(
            serde_json::json!({"groups": {"add": ["testers"]}}),
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "users": [{"id": 1, "changes": {}}]
        })))
        .expect(1)
        .mount(&mock)
        .await;

    let client = test_client(&mock.uri());
    client
        .add_user_to_group("alice@example.com", "testers")
        .await
        .unwrap();
}

#[tokio::test]
async fn remove_user_from_group_sends_put() {
    let mock = MockServer::start().await;
    Mock::given(method("PUT"))
        .and(path(format!(
            "/rest/user/{}",
            encode_path("bob@example.com")
        )))
        .and(body_json(
            serde_json::json!({"groups": {"remove": ["testers"]}}),
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "users": [{"id": 2, "changes": {}}]
        })))
        .expect(1)
        .mount(&mock)
        .await;

    let client = test_client(&mock.uri());
    client
        .remove_user_from_group("bob@example.com", "testers")
        .await
        .unwrap();
}

#[tokio::test]
async fn get_group_returns_info() {
    let mock = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/rest/group"))
        .and(query_param("names", "admin"))
        .and(query_param("membership", "1"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "groups": [{
                "id": 1,
                "name": "admin",
                "description": "Administrators",
                "is_active": true,
                "membership": []
            }]
        })))
        .mount(&mock)
        .await;

    let client = test_client(&mock.uri());
    let info = client.get_group("admin").await.unwrap();
    assert_eq!(info.name, "admin");
    assert!(info.is_active);
}

#[tokio::test]
async fn get_group_rest_empty_response_returns_not_found() {
    let mock = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/rest/group"))
        .and(query_param("names", "missing"))
        .and(query_param("membership", "1"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "groups": []
        })))
        .expect(1)
        .mount(&mock)
        .await;

    let client = test_client(&mock.uri());
    let err = client.get_group("missing").await.unwrap_err();
    assert!(matches!(
        err,
        BzrError::NotFound {
            resource: "group",
            ..
        }
    ));
}

#[tokio::test]
async fn get_group_forbidden() {
    let mock = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/rest/group"))
        .and(query_param("names", "secret"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "error": true,
            "code": 51,
            "message": "You are not authorized."
        })))
        .mount(&mock)
        .await;

    let client = test_client(&mock.uri());
    let err = client.get_group("secret").await.unwrap_err();
    assert!(err.to_string().contains("not authorized"));
}

#[tokio::test]
async fn hybrid_get_group_32610_falls_back_to_xmlrpc() {
    let mock = MockServer::start().await;

    // REST returns error 32610 (Bugzilla 5.3+ blocks GET for Group.get)
    Mock::given(method("GET"))
        .and(path("/rest/group"))
        .and(query_param("names", "admin"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "error": true,
            "code": 32610,
            "message": "For security reasons, you must use HTTP POST to call the 'get' method."
        })))
        .expect(1)
        .mount(&mock)
        .await;

    // XML-RPC fallback succeeds
    Mock::given(method("POST"))
        .and(path("/xmlrpc.cgi"))
        .respond_with(
            ResponseTemplate::new(200).set_body_string(xmlrpc_group_response(
                1,
                "admin",
                "Administrators",
            )),
        )
        .expect(1)
        .mount(&mock)
        .await;

    let client = test_client_hybrid(&mock.uri());
    let info = client.get_group("admin").await.unwrap();
    assert_eq!(info.name, "admin");
    assert_eq!(info.description, "Administrators");
}

#[tokio::test]
async fn hybrid_get_group_transport_failure_falls_back_to_xmlrpc() {
    // A 5xx response from REST is a transport failure under
    // `is_transport_failure()`. In Hybrid mode it must trigger the
    // XML-RPC retry, not propagate as the final error.
    let mock = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/rest/group"))
        .and(query_param("names", "admin"))
        .respond_with(ResponseTemplate::new(500))
        .expect(1)
        .mount(&mock)
        .await;

    Mock::given(method("POST"))
        .and(path("/xmlrpc.cgi"))
        .respond_with(
            ResponseTemplate::new(200).set_body_string(xmlrpc_group_response(
                1,
                "admin",
                "Administrators",
            )),
        )
        .expect(1)
        .mount(&mock)
        .await;

    let client = test_client_hybrid(&mock.uri());
    let info = client.get_group("admin").await.unwrap();
    assert_eq!(info.name, "admin");
}

#[tokio::test]
async fn rest_get_group_32610_falls_back_to_xmlrpc() {
    let mock = MockServer::start().await;

    // REST returns error 32610 (Bugzilla 5.3+ blocks GET for Group.get)
    Mock::given(method("GET"))
        .and(path("/rest/group"))
        .and(query_param("names", "admin"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "error": true,
            "code": 32610,
            "message": "For security reasons, you must use HTTP POST to call the 'get' method."
        })))
        .expect(1)
        .mount(&mock)
        .await;

    // XML-RPC fallback succeeds
    Mock::given(method("POST"))
        .and(path("/xmlrpc.cgi"))
        .respond_with(
            ResponseTemplate::new(200).set_body_string(xmlrpc_group_response(
                1,
                "admin",
                "Administrators",
            )),
        )
        .expect(1)
        .mount(&mock)
        .await;

    // Uses test_client (Rest mode), not hybrid
    let client = test_client(&mock.uri());
    let info = client.get_group("admin").await.unwrap();
    assert_eq!(info.name, "admin");
    assert_eq!(info.description, "Administrators");
}

#[tokio::test]
async fn xmlrpc_mode_get_group_bypasses_rest() {
    let mock = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/rest/group"))
        .respond_with(ResponseTemplate::new(500))
        .expect(0)
        .mount(&mock)
        .await;

    Mock::given(method("POST"))
        .and(path("/xmlrpc.cgi"))
        .respond_with(
            ResponseTemplate::new(200).set_body_string(xmlrpc_group_response(
                1,
                "admin",
                "Administrators",
            )),
        )
        .expect(1)
        .mount(&mock)
        .await;

    let client = super::BugzillaClient::new(crate::client::BugzillaClientConfig {
        base_url: &mock.uri(),
        credential: "test-key",
        auth_method: AuthMethod::Header,
        api_mode: ApiMode::XmlRpc,
        email_hint: None,
        tls_config: &crate::tls::TlsConfig::default(),
    })
    .unwrap();

    let info = client.get_group("admin").await.unwrap();
    assert_eq!(info.name, "admin");
}

#[tokio::test]
async fn hybrid_get_group_api_error_does_not_fall_back() {
    let mock = MockServer::start().await;

    // REST returns a non-retriable API error (not 32610, not transport)
    Mock::given(method("GET"))
        .and(path("/rest/group"))
        .and(query_param("names", "secret"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "error": true,
            "code": 51,
            "message": "You are not authorized."
        })))
        .expect(1)
        .mount(&mock)
        .await;

    // XML-RPC should not be called
    Mock::given(method("POST"))
        .and(path("/xmlrpc.cgi"))
        .respond_with(ResponseTemplate::new(200))
        .expect(0)
        .mount(&mock)
        .await;

    let client = test_client_hybrid(&mock.uri());
    let err = client.get_group("secret").await.unwrap_err();
    assert!(
        err.to_string().contains("not authorized"),
        "expected auth error, got: {err}"
    );
}

/// Build a mock XML-RPC Group.get response containing one group.
fn xmlrpc_group_response(id: i64, name: &str, description: &str) -> String {
    format!(
        r#"<?xml version="1.0" encoding="UTF-8"?>
        <methodResponse><params><param><value><struct>
          <member><name>groups</name><value><array><data>
            <value><struct>
              <member><name>id</name><value><int>{id}</int></value></member>
              <member><name>name</name><value><string>{name}</string></value></member>
              <member><name>description</name><value><string>{description}</string></value></member>
              <member><name>is_active</name><value><boolean>1</boolean></value></member>
              <member><name>membership</name><value><array><data></data></array></value></member>
            </struct></value>
          </data></array></value></member>
        </struct></value></param></params></methodResponse>"#
    )
}

#[tokio::test]
async fn create_group_returns_id() {
    let mock = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/rest/group"))
        .and(body_json(serde_json::json!({
            "name": "testers",
            "description": "Test team",
            "is_active": true,
        })))
        .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({"id": 5})))
        .expect(1)
        .mount(&mock)
        .await;

    let client = test_client(&mock.uri());
    let id = client
        .create_group(&CreateGroupParams {
            name: "testers".into(),
            description: "Test team".into(),
            is_active: true,
        })
        .await
        .unwrap();
    assert_eq!(id, 5);
}

#[tokio::test]
async fn create_group_forbidden() {
    let mock = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/rest/group"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "error": true,
            "code": 51,
            "message": "You are not authorized."
        })))
        .mount(&mock)
        .await;

    let client = test_client(&mock.uri());
    let err = client
        .create_group(&CreateGroupParams {
            name: "x".into(),
            description: "x".into(),
            is_active: true,
        })
        .await
        .unwrap_err();
    assert!(err.to_string().contains("not authorized"));
}

#[tokio::test]
async fn update_group_sends_put() {
    let mock = MockServer::start().await;
    Mock::given(method("PUT"))
        .and(path("/rest/group/testers"))
        .and(body_json(serde_json::json!({
            "description": "Updated testers",
        })))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "groups": [{"id": 5, "changes": {}}]
        })))
        .expect(1)
        .mount(&mock)
        .await;

    let client = test_client(&mock.uri());
    let params = UpdateGroupParams {
        description: Some("Updated testers".into()),
        ..Default::default()
    };
    client.update_group("testers", &params).await.unwrap();
}

#[tokio::test]
async fn update_group_forbidden() {
    let mock = MockServer::start().await;
    Mock::given(method("PUT"))
        .and(path("/rest/group/testers"))
        .respond_with(ResponseTemplate::new(403).set_body_json(serde_json::json!({
            "error": true,
            "code": 51,
            "message": "You are not authorized."
        })))
        .mount(&mock)
        .await;

    let client = test_client(&mock.uri());
    let params = UpdateGroupParams::default();
    let err = client.update_group("testers", &params).await.unwrap_err();
    assert!(err.to_string().contains("not authorized"));
}