yandex-tracker-cli 1.0.0

Token-efficient Yandex Tracker CLI for humans and AI agents
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
//! `auth login`.
//!
//! The real command writes to the OS keychain, which a test must not do — a CI
//! runner has no unlocked keychain, and a developer's should not collect entries
//! from a test run. Everything up to the writes is exercised through `--dry-run`,
//! which login honours like every other write; the file-writing half is unit
//! tested in `config::store`.

#![allow(clippy::expect_used, clippy::unwrap_used)]

use predicates::prelude::*;
use wiremock::matchers::{header, method, path};
use wiremock::{Mock, ResponseTemplate};

mod harness;
use harness::Harness;

fn myself() -> serde_json::Value {
    serde_json::json!({
        "self": "https://api.tracker.yandex.net/v3/myself",
        "uid": 1_120_000_000_000_219_i64,
        "login": "ilubenets",
        "display": "Ilya Lubenets",
        "email": "someone@example.com"
    })
}

/// A mistyped token that reaches the keychain fails later, somewhere else,
/// looking like a permissions problem. Checking first is one request.
#[tokio::test]
async fn the_token_is_verified_before_anything_is_stored() {
    let harness = Harness::new().await;
    Mock::given(method("GET"))
        .and(path("/v3/myself"))
        .and(header("authorization", "OAuth test-token"))
        .and(header("x-cloud-org-id", "12345"))
        .respond_with(ResponseTemplate::new(200).set_body_json(myself()))
        .mount(&harness.server)
        .await;

    harness
        .run_raw(&[
            "auth",
            "login",
            "--account",
            "work",
            "--org-id",
            "12345",
            "--dry-run",
        ])
        .write_stdin("test-token\n")
        .assert()
        .success()
        .stderr(predicate::str::contains(
            "verified as ilubenets in org 12345",
        ))
        .stderr(predicate::str::contains("dry run: would store a token"))
        .stderr(predicate::str::contains(
            "dry run: would write profile `work`",
        ));
}

/// The two organisation headers are not interchangeable, and the wrong one
/// answers 403 — which reads as a permissions problem rather than a
/// configuration mistake. Trying both here costs one request, once.
#[tokio::test]
async fn the_organisation_header_form_is_detected() {
    let harness = Harness::new().await;
    Mock::given(method("GET"))
        .and(path("/v3/myself"))
        .and(header("x-cloud-org-id", "12345"))
        .respond_with(ResponseTemplate::new(403))
        .mount(&harness.server)
        .await;
    Mock::given(method("GET"))
        .and(path("/v3/myself"))
        .and(header("x-org-id", "12345"))
        .respond_with(ResponseTemplate::new(200).set_body_json(myself()))
        .mount(&harness.server)
        .await;

    harness
        .run_raw(&[
            "auth",
            "login",
            "--account",
            "work",
            "--org-id",
            "12345",
            "--dry-run",
        ])
        .write_stdin("test-token\n")
        .assert()
        .success()
        .stderr(predicate::str::contains("Yandex360"));
}

/// A rejected token is rejected under either header, so there is nothing to
/// retry and the message should say what is actually wrong.
#[tokio::test]
async fn a_rejected_token_fails_immediately_without_trying_the_other_header() {
    let harness = Harness::new().await;
    Mock::given(method("GET"))
        .and(path("/v3/myself"))
        .respond_with(ResponseTemplate::new(401))
        .expect(1)
        .mount(&harness.server)
        .await;

    harness
        .run_raw(&[
            "auth",
            "login",
            "--account",
            "work",
            "--org-id",
            "12345",
            "--dry-run",
        ])
        .write_stdin("wrong-token\n")
        .assert()
        .code(3)
        .stderr(predicate::str::contains("token was rejected"));
}

#[tokio::test]
async fn a_wrong_org_id_reports_that_both_forms_were_tried() {
    let harness = Harness::new().await;
    Mock::given(method("GET"))
        .and(path("/v3/myself"))
        .respond_with(ResponseTemplate::new(403))
        .mount(&harness.server)
        .await;

    harness
        .run_raw(&[
            "auth",
            "login",
            "--account",
            "work",
            "--org-id",
            "99999",
            "--dry-run",
        ])
        .write_stdin("test-token\n")
        .assert()
        .code(5)
        .stderr(predicate::str::contains(
            "checked both organisation header forms",
        ));
}

/// Without an organisation there is nothing to write a profile from, and saying
/// so beats leaving someone with a token and no way to use it.
#[tokio::test]
async fn login_without_an_org_id_says_the_setup_is_unfinished() {
    let harness = Harness::new().await;

    harness
        .run_raw(&["auth", "login", "--account", "work", "--dry-run"])
        .write_stdin("test-token\n")
        .assert()
        .success()
        .stderr(predicate::str::contains("no --org-id given"))
        .stderr(predicate::str::contains(
            "ytcli auth login --account work --org-id",
        ));
}

#[tokio::test]
async fn an_empty_token_is_refused_before_any_request() {
    let harness = Harness::new().await;

    harness
        .run_raw(&[
            "auth",
            "login",
            "--account",
            "work",
            "--org-id",
            "12345",
            "--dry-run",
        ])
        .write_stdin("   \n")
        .assert()
        .code(3)
        .stderr(predicate::str::contains("no token given"));

    assert!(
        harness
            .server
            .received_requests()
            .await
            .expect("recorded")
            .is_empty()
    );
}

/// The profile name defaults to the account name, and --queue lands in it.
#[tokio::test]
async fn the_profile_can_be_named_and_given_a_queue() {
    let harness = Harness::new().await;
    Mock::given(method("GET"))
        .and(path("/v3/myself"))
        .respond_with(ResponseTemplate::new(200).set_body_json(myself()))
        .mount(&harness.server)
        .await;

    harness
        .run_raw(&[
            "auth",
            "login",
            "--account",
            "admin",
            "--org-id",
            "12345",
            "--profile",
            "work",
            "--queue",
            "PROJ",
            "--dry-run",
        ])
        .write_stdin("test-token\n")
        .assert()
        .success()
        .stderr(predicate::str::contains(
            "would write profile `work` (account=admin, org=12345",
        ));
}

/// `auth status` is the command someone runs when something is wrong, so it
/// answers the questions that get asked: who am I, what can I reach.
#[tokio::test]
async fn status_reports_identity_and_what_the_profile_can_see() {
    let harness = Harness::new().await;
    Mock::given(method("GET"))
        .and(path("/v3/myself"))
        .respond_with(ResponseTemplate::new(200).set_body_json(myself()))
        .mount(&harness.server)
        .await;
    Mock::given(method("GET"))
        .and(path("/v3/queues"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
            {"id": 7, "key": "PROJ", "name": "Product"},
            {"id": 8, "key": "INFRA", "name": "Infrastructure"}
        ])))
        .mount(&harness.server)
        .await;
    Mock::given(method("POST"))
        .and(path("/v3/entities/project/_search"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "hits": 3,
            "pages": 1,
            "values": [
                {"id": "a1", "shortId": 12, "entityType": "project",
                 "fields": {"summary": "Storage rework"}},
                {"id": "a2", "shortId": 13, "entityType": "project",
                 "fields": {"summary": "Billing"}}
            ]
        })))
        .mount(&harness.server)
        .await;
    Mock::given(method("POST"))
        .and(path("/v3/entities/goal/_search"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "hits": 1, "pages": 1, "values": []
        })))
        .mount(&harness.server)
        .await;
    Mock::given(method("POST"))
        .and(path("/v3/issues/_count"))
        .respond_with(ResponseTemplate::new(200).set_body_json(7))
        .mount(&harness.server)
        .await;

    let output = harness.run_raw(&["auth", "status"]).assert().success();
    let stdout = String::from_utf8(output.get_output().stdout.clone()).expect("utf-8");

    assert!(stdout.contains("profile test"));
    assert!(stdout.contains("org: 12345 (Cloud)"));
    // The suffix is here because every test authenticates through
    // `YTCLI_TOKEN`; a keychain-backed profile prints `token: ok` alone.
    assert!(stdout.contains("token: ok (from YTCLI_TOKEN)   user: ilubenets (Ilya Lubenets)"));
    assert!(stdout.contains("queues: 2   projects: 3   goals: 1   my open issues: 7"));
    assert!(stdout.contains("Storage rework (12), Billing (13), +1 more"));
    assert!(stdout.contains("PROJ, INFRA"));
}

/// A profile that cannot see projects should still report its queues rather
/// than losing the whole line.
#[tokio::test]
async fn status_survives_a_partly_unavailable_organisation() {
    let harness = Harness::new().await;
    Mock::given(method("GET"))
        .and(path("/v3/myself"))
        .respond_with(ResponseTemplate::new(200).set_body_json(myself()))
        .mount(&harness.server)
        .await;
    Mock::given(method("GET"))
        .and(path("/v3/queues"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
            {"id": 7, "key": "PROJ", "name": "Product"}
        ])))
        .mount(&harness.server)
        .await;
    Mock::given(method("POST"))
        .and(path("/v3/entities/project/_search"))
        .respond_with(ResponseTemplate::new(403))
        .mount(&harness.server)
        .await;

    let output = harness.run_raw(&["auth", "status"]).assert().success();
    let stdout = String::from_utf8(output.get_output().stdout.clone()).expect("utf-8");

    assert!(stdout.contains("queues: 1   projects: -"));
    assert!(stdout.contains("PROJ"));
}

/// A rejected token should come with the instructions for getting a new one.
#[tokio::test]
async fn status_with_a_rejected_token_points_at_the_token_docs() {
    let harness = Harness::new().await;
    Mock::given(method("GET"))
        .and(path("/v3/myself"))
        .respond_with(ResponseTemplate::new(401))
        .mount(&harness.server)
        .await;

    harness
        .run_raw(&["auth", "status"])
        .assert()
        .code(3)
        .stdout(predicate::str::contains("token: rejected"))
        .stderr(predicate::str::contains("oauth.yandex.ru/client/new"));
}

#[tokio::test]
async fn brief_skips_the_counts_and_their_requests() {
    let harness = Harness::new().await;
    Mock::given(method("GET"))
        .and(path("/v3/myself"))
        .respond_with(ResponseTemplate::new(200).set_body_json(myself()))
        .mount(&harness.server)
        .await;

    let output = harness
        .run_raw(&["auth", "status", "--brief"])
        .assert()
        .success();
    let stdout = String::from_utf8(output.get_output().stdout.clone()).expect("utf-8");

    assert!(stdout.contains("token: ok"));
    assert!(!stdout.contains("my open issues"));

    let requests = harness.server.received_requests().await.expect("recorded");
    assert_eq!(requests.len(), 1);
}

/// The help must answer "where do I get these" without anyone having to fail
/// first — the same text the wizard shows.
#[test]
fn login_help_carries_the_credential_instructions() {
    let output = assert_cmd::Command::cargo_bin("ytcli")
        .expect("binary built")
        .args(["auth", "login", "--help"])
        .assert()
        .success();
    let stdout = String::from_utf8(output.get_output().stdout.clone()).expect("utf-8");

    assert!(stdout.contains("oauth.yandex.ru/client/new"));
    // The two domains are separate origins with separate cookies, and the whole
    // point of naming one is that both steps happen on it.
    assert!(stdout.contains("Stay on one domain"));
    assert!(stdout.contains("tracker:write"));
    assert!(stdout.contains("tracker.yandex.ru/admin/orgs"));
    assert!(stdout.contains("--org-kind yandex360"));
    assert!(stdout.contains("walks you through each step"));
}

/// Outside a terminal there is nobody to answer, so a missing account is an
/// error rather than a prompt that would hang a script.
#[tokio::test]
async fn without_a_terminal_a_missing_account_is_an_error_not_a_prompt() {
    let harness = Harness::new().await;

    harness
        .run_raw(&["auth", "login", "--dry-run"])
        .write_stdin("some-token\n")
        .assert()
        .code(2)
        .stderr(predicate::str::contains(
            "--account is required when not running in a terminal",
        ));
}

/// Switching the default profile is a local edit, and nothing more.
///
/// No token is read and no request is made: asking the keychain for a
/// credential in order to change a line in a config file would be theatre.
#[tokio::test]
async fn use_switches_the_default_profile_without_touching_the_network() {
    let harness = Harness::new().await;
    harness.add_profile("other", "99999");

    harness
        .run_raw(&["auth", "use", "other"])
        .assert()
        .success()
        .stderr(predicate::str::contains("default profile:"))
        .stderr(predicate::str::contains("other"));

    let config = std::fs::read_to_string(harness.config_path()).expect("read config");
    assert!(config.contains(r#"default_profile = "other""#), "{config}");

    let requests = harness.server.received_requests().await.unwrap_or_default();
    assert!(requests.is_empty(), "{requests:?}");
}

/// A default naming a profile that does not exist is a config every later
/// command fails on, with a worse message than this one.
#[tokio::test]
async fn use_refuses_a_profile_that_does_not_exist() {
    let harness = Harness::new().await;

    harness
        .run_raw(&["auth", "use", "nope"])
        .assert()
        .code(4)
        .stderr(predicate::str::contains("no profile called `nope`"))
        .stderr(predicate::str::contains("configured: test"));
}

/// `--dry-run` says what it would do and leaves the file alone, like every
/// other write here.
#[tokio::test]
async fn use_under_dry_run_changes_nothing() {
    let harness = Harness::new().await;
    harness.add_profile("other", "99999");
    let before = std::fs::read_to_string(harness.config_path()).expect("read config");

    harness
        .run_raw(&["auth", "use", "other", "--dry-run"])
        .assert()
        .success()
        .stderr(predicate::str::contains("dry run: would make `other`"));

    let after = std::fs::read_to_string(harness.config_path()).expect("read config");
    assert_eq!(before, after);
}

/// Two profiles on one organisation are not a collision. `FINANSY-1` names one
/// issue there, and either login fetches it — the tool routes rather than
/// refuses, so a warning saying it will be refused describes a rule that was
/// removed and sends the reader to qualify keys that never needed it.
#[tokio::test]
async fn two_profiles_on_one_organisation_are_not_warned_about() {
    let harness = Harness::new().await;
    harness.add_profile("second", "12345");
    status_answers(&harness).await;

    let output = harness.run_raw(&["auth", "status"]).assert().success();
    let stderr = String::from_utf8(output.get_output().stderr.clone()).expect("utf-8");

    assert!(!stderr.contains("PROJ"), "{stderr}");
}

/// One organisation apart, the same two queue keys *are* ambiguous, and that is
/// the case the warning exists for.
#[tokio::test]
async fn a_queue_key_shared_across_organisations_is_warned_about() {
    let harness = Harness::new().await;
    harness.add_profile("other", "99999");
    status_answers(&harness).await;

    let output = harness.run_raw(&["auth", "status"]).assert().success();
    let stderr = String::from_utf8(output.get_output().stderr.clone()).expect("utf-8");

    assert!(stderr.contains("queue PROJ is visible in"), "{stderr}");
    assert!(stderr.contains("different organisations"), "{stderr}");
}

/// Enough of an organisation for `auth status` to finish for every profile.
async fn status_answers(harness: &Harness) {
    Mock::given(method("GET"))
        .and(path("/v3/myself"))
        .respond_with(ResponseTemplate::new(200).set_body_json(myself()))
        .mount(&harness.server)
        .await;
    Mock::given(method("GET"))
        .and(path("/v3/queues"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
            {"id": 7, "key": "PROJ", "name": "Product"}
        ])))
        .mount(&harness.server)
        .await;
    Mock::given(method("POST"))
        .and(path("/v3/entities/project/_search"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "hits": 0, "pages": 1, "values": []
        })))
        .mount(&harness.server)
        .await;
    Mock::given(method("POST"))
        .and(path("/v3/entities/goal/_search"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "hits": 0, "pages": 1, "values": []
        })))
        .mount(&harness.server)
        .await;
    Mock::given(method("POST"))
        .and(path("/v3/issues/_count"))
        .respond_with(ResponseTemplate::new(200).set_body_json(0))
        .mount(&harness.server)
        .await;
}

/// `YTCLI_TOKEN` applies to every account at once, which is right in CI and
/// wrong on a laptop — a shell that exports it on entering a directory, as the
/// oh-my-zsh `dotenv` plugin does, makes every profile the same identity. The
/// rows then agree for a reason nothing in them explains, so the override says
/// so on each of them and once at the end.
#[tokio::test]
async fn an_environment_token_says_it_is_standing_in_for_the_keychain() {
    let harness = Harness::new().await;
    harness.add_profile("second", "12345");
    status_answers(&harness).await;

    let output = harness.run_raw(&["auth", "status"]).assert().success();
    let stdout = String::from_utf8(output.get_output().stdout.clone()).expect("utf-8");
    let stderr = String::from_utf8(output.get_output().stderr.clone()).expect("utf-8");

    assert_eq!(
        stdout.matches("(from YTCLI_TOKEN)").count(),
        2,
        "both profiles were read through the one token: {stdout}"
    );
    assert!(stderr.contains("YTCLI_TOKEN is set"), "{stderr}");
}

/// "Where did this come from" is the question this command exists to answer, so
/// it answers it about the configuration too, not only about the profiles.
#[tokio::test]
async fn status_names_the_config_file_and_the_overriding_environment() {
    let harness = Harness::new().await;
    status_answers(&harness).await;

    let output = harness.run_raw(&["auth", "status", "--brief"]).assert();
    let stdout = String::from_utf8(output.get_output().stdout.clone()).expect("utf-8");

    assert!(stdout.starts_with("config: "), "{stdout}");
    assert!(stdout.contains("config.toml"), "{stdout}");
    // Names, never values: one of these holds a token, and a diagnostic that
    // prints credentials cannot be pasted into a bug report.
    assert!(stdout.contains("environment: YTCLI_"), "{stdout}");
    assert!(!stdout.contains("test-token"), "{stdout}");
}