summaryrefslogtreecommitdiffstats
path: root/src/tools/cargo/tests/testsuite/login.rs
blob: 85b299f282a2164ee70a103313300810ca5ce049 (plain)
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
//! Tests for the `cargo login` command.

use cargo_test_support::cargo_process;
use cargo_test_support::paths::{self, CargoPathExt};
use cargo_test_support::registry::{self, RegistryBuilder};
use cargo_test_support::t;
use std::fs;
use std::path::PathBuf;

const TOKEN: &str = "test-token";
const TOKEN2: &str = "test-token2";
const ORIGINAL_TOKEN: &str = "api-token";

fn credentials_toml() -> PathBuf {
    paths::home().join(".cargo/credentials.toml")
}

fn setup_new_credentials() {
    setup_new_credentials_at(credentials_toml());
}

fn setup_new_credentials_at(config: PathBuf) {
    t!(fs::create_dir_all(config.parent().unwrap()));
    t!(fs::write(
        &config,
        format!(r#"token = "{token}""#, token = ORIGINAL_TOKEN)
    ));
}

/// Asserts whether or not the token is set to the given value for the given registry.
pub fn check_token(expected_token: Option<&str>, registry: Option<&str>) {
    let credentials = credentials_toml();
    assert!(credentials.is_file());

    let contents = fs::read_to_string(&credentials).unwrap();
    let toml: toml::Table = contents.parse().unwrap();

    let actual_token = match registry {
        // A registry has been provided, so check that the token exists in a
        // table for the registry.
        Some(registry) => toml
            .get("registries")
            .and_then(|registries_table| registries_table.get(registry))
            .and_then(|registry_table| match registry_table.get("token") {
                Some(&toml::Value::String(ref token)) => Some(token.as_str().to_string()),
                _ => None,
            }),
        // There is no registry provided, so check the global token instead.
        None => toml
            .get("registry")
            .and_then(|registry_table| registry_table.get("token"))
            .and_then(|v| match v {
                toml::Value::String(ref token) => Some(token.as_str().to_string()),
                _ => None,
            }),
    };

    match (actual_token, expected_token) {
        (None, None) => {}
        (Some(actual), Some(expected)) => assert_eq!(actual, expected),
        (None, Some(expected)) => {
            panic!("expected `{registry:?}` to be `{expected}`, but was not set")
        }
        (Some(actual), None) => {
            panic!("expected `{registry:?}` to be unset, but was set to `{actual}`")
        }
    }
}

#[cargo_test]
fn registry_credentials() {
    let _alternative = RegistryBuilder::new().alternative().build();
    let _alternative2 = RegistryBuilder::new()
        .alternative_named("alternative2")
        .build();

    setup_new_credentials();

    let reg = "alternative";

    cargo_process("login --registry").arg(reg).arg(TOKEN).run();

    // Ensure that we have not updated the default token
    check_token(Some(ORIGINAL_TOKEN), None);

    // Also ensure that we get the new token for the registry
    check_token(Some(TOKEN), Some(reg));

    let reg2 = "alternative2";
    cargo_process("login --registry")
        .arg(reg2)
        .arg(TOKEN2)
        .run();

    // Ensure not overwriting 1st alternate registry token with
    // 2nd alternate registry token (see rust-lang/cargo#7701).
    check_token(Some(ORIGINAL_TOKEN), None);
    check_token(Some(TOKEN), Some(reg));
    check_token(Some(TOKEN2), Some(reg2));
}

#[cargo_test]
fn empty_login_token() {
    let registry = RegistryBuilder::new()
        .no_configure_registry()
        .no_configure_token()
        .build();
    setup_new_credentials();

    cargo_process("login")
        .replace_crates_io(registry.index_url())
        .with_stdout("please paste the token found on [..]/me below")
        .with_stdin("\t\n")
        .with_stderr(
            "\
[UPDATING] crates.io index
[ERROR] please provide a non-empty token
",
        )
        .with_status(101)
        .run();

    cargo_process("login")
        .replace_crates_io(registry.index_url())
        .arg("")
        .with_stderr(
            "\
[ERROR] please provide a non-empty token
",
        )
        .with_status(101)
        .run();
}

#[cargo_test]
fn invalid_login_token() {
    let registry = RegistryBuilder::new()
        .no_configure_registry()
        .no_configure_token()
        .build();
    setup_new_credentials();

    let check = |stdin: &str, stderr: &str, status: i32| {
        cargo_process("login")
            .replace_crates_io(registry.index_url())
            .with_stdout("please paste the token found on [..]/me below")
            .with_stdin(stdin)
            .with_stderr(stderr)
            .with_status(status)
            .run();
    };

    let invalid = |stdin: &str| {
        check(
            stdin,
            "[ERROR] token contains invalid characters.
Only printable ISO-8859-1 characters are allowed as it is sent in a HTTPS header.",
            101,
        )
    };
    let valid = |stdin: &str| check(stdin, "[LOGIN] token for `crates.io` saved", 0);

    // Update config.json so that the rest of the tests don't need to care
    // whether or not `Updating` is printed.
    check(
        "test",
        "\
[UPDATING] crates.io index
[LOGIN] token for `crates.io` saved
",
        0,
    );

    invalid("😄");
    invalid("\u{0016}");
    invalid("\u{0000}");
    invalid("你好");
    valid("foo\tbar");
    valid("foo bar");
    valid(
        r##"!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"##,
    );
}

#[cargo_test]
fn bad_asymmetric_token_args() {
    // These cases are kept brief as the implementation is covered by clap, so this is only smoke testing that we have clap configured correctly.
    cargo_process("login --key-subject=foo tok")
        .with_stderr_contains(
            "error: the argument '--key-subject <SUBJECT>' cannot be used with '[token]'",
        )
        .with_status(1)
        .run();

    cargo_process("login --generate-keypair tok")
        .with_stderr_contains(
            "error: the argument '--generate-keypair' cannot be used with '[token]'",
        )
        .with_status(1)
        .run();

    cargo_process("login --secret-key tok")
        .with_stderr_contains("error: the argument '--secret-key' cannot be used with '[token]'")
        .with_status(1)
        .run();

    cargo_process("login --generate-keypair --secret-key")
        .with_stderr_contains(
            "error: the argument '--generate-keypair' cannot be used with '--secret-key'",
        )
        .with_status(1)
        .run();
}

#[cargo_test]
fn asymmetric_requires_nightly() {
    let registry = registry::init();
    cargo_process("login --key-subject=foo")          
        .replace_crates_io(registry.index_url())
        .with_status(101)
        .with_stderr_contains("[ERROR] the `key-subject` flag is unstable, pass `-Z registry-auth` to enable it\n\
            See https://github.com/rust-lang/cargo/issues/10519 for more information about the `key-subject` flag.")
        .run();
    cargo_process("login --generate-keypair")
        .replace_crates_io(registry.index_url())
        .with_status(101)
        .with_stderr_contains("[ERROR] the `generate-keypair` flag is unstable, pass `-Z registry-auth` to enable it\n\
            See https://github.com/rust-lang/cargo/issues/10519 for more information about the `generate-keypair` flag.")
        .run();
    cargo_process("login --secret-key")
        .replace_crates_io(registry.index_url())
        .with_status(101)
        .with_stderr_contains("[ERROR] the `secret-key` flag is unstable, pass `-Z registry-auth` to enable it\n\
            See https://github.com/rust-lang/cargo/issues/10519 for more information about the `secret-key` flag.")
        .run();
}

#[cargo_test]
fn login_with_no_cargo_dir() {
    // Create a config in the root directory because `login` requires the
    // index to be updated, and we don't want to hit crates.io.
    let registry = registry::init();
    fs::rename(paths::home().join(".cargo"), paths::root().join(".cargo")).unwrap();
    paths::home().rm_rf();
    cargo_process("login foo -v")
        .replace_crates_io(registry.index_url())
        .run();
    let credentials = fs::read_to_string(credentials_toml()).unwrap();
    assert_eq!(credentials, "[registry]\ntoken = \"foo\"\n");
}

#[cargo_test]
fn login_with_differently_sized_token() {
    // Verify that the configuration file gets properly truncated.
    let registry = registry::init();
    let credentials = credentials_toml();
    fs::remove_file(&credentials).unwrap();
    cargo_process("login lmaolmaolmao -v")
        .replace_crates_io(registry.index_url())
        .run();
    cargo_process("login lmao -v")
        .replace_crates_io(registry.index_url())
        .run();
    cargo_process("login lmaolmaolmao -v")
        .replace_crates_io(registry.index_url())
        .run();
    let credentials = fs::read_to_string(&credentials).unwrap();
    assert_eq!(credentials, "[registry]\ntoken = \"lmaolmaolmao\"\n");
}

#[cargo_test]
fn login_with_token_on_stdin() {
    let registry = registry::init();
    let credentials = credentials_toml();
    fs::remove_file(&credentials).unwrap();
    cargo_process("login lmao -v")
        .replace_crates_io(registry.index_url())
        .run();
    cargo_process("login")
        .replace_crates_io(registry.index_url())
        .with_stdout("please paste the token found on [..]/me below")
        .with_stdin("some token")
        .run();
    let credentials = fs::read_to_string(&credentials).unwrap();
    assert_eq!(credentials, "[registry]\ntoken = \"some token\"\n");
}

#[cargo_test]
fn login_with_asymmetric_token_and_subject_on_stdin() {
    let registry = registry::init();
    let credentials = credentials_toml();
    fs::remove_file(&credentials).unwrap();
    cargo_process("login --key-subject=foo --secret-key -v -Z registry-auth")
        .masquerade_as_nightly_cargo(&["registry-auth"])
        .replace_crates_io(registry.index_url())
        .with_stdout(
            "\
        please paste the API secret key below
k3.public.AmDwjlyf8jAV3gm5Z7Kz9xAOcsKslt_Vwp5v-emjFzBHLCtcANzTaVEghTNEMj9PkQ",
        )
        .with_stdin("k3.secret.fNYVuMvBgOlljt9TDohnaYLblghqaHoQquVZwgR6X12cBFHZLFsaU3q7X3k1Zn36")
        .run();
    let credentials = fs::read_to_string(&credentials).unwrap();
    assert!(credentials.starts_with("[registry]\n"));
    assert!(credentials.contains("secret-key-subject = \"foo\"\n"));
    assert!(credentials.contains("secret-key = \"k3.secret.fNYVuMvBgOlljt9TDohnaYLblghqaHoQquVZwgR6X12cBFHZLFsaU3q7X3k1Zn36\"\n"));
}

#[cargo_test]
fn login_with_asymmetric_token_on_stdin() {
    let registry = registry::init();
    let credentials = credentials_toml();
    fs::remove_file(&credentials).unwrap();
    cargo_process("login --secret-key -v -Z registry-auth")
        .masquerade_as_nightly_cargo(&["registry-auth"])
        .replace_crates_io(registry.index_url())
        .with_stdout(
            "\
    please paste the API secret key below
k3.public.AmDwjlyf8jAV3gm5Z7Kz9xAOcsKslt_Vwp5v-emjFzBHLCtcANzTaVEghTNEMj9PkQ",
        )
        .with_stdin("k3.secret.fNYVuMvBgOlljt9TDohnaYLblghqaHoQquVZwgR6X12cBFHZLFsaU3q7X3k1Zn36")
        .run();
    let credentials = fs::read_to_string(&credentials).unwrap();
    assert_eq!(credentials, "[registry]\nsecret-key = \"k3.secret.fNYVuMvBgOlljt9TDohnaYLblghqaHoQquVZwgR6X12cBFHZLFsaU3q7X3k1Zn36\"\n");
}

#[cargo_test]
fn login_with_asymmetric_key_subject_without_key() {
    let registry = registry::init();
    let credentials = credentials_toml();
    fs::remove_file(&credentials).unwrap();
    cargo_process("login --key-subject=foo -Z registry-auth")
        .masquerade_as_nightly_cargo(&["registry-auth"])
        .replace_crates_io(registry.index_url())
        .with_stderr_contains("error: need a secret_key to set a key_subject")
        .with_status(101)
        .run();

    // ok so add a secret_key to the credentials
    cargo_process("login --secret-key -v -Z registry-auth")
        .masquerade_as_nightly_cargo(&["registry-auth"])
        .replace_crates_io(registry.index_url())
        .with_stdout(
            "please paste the API secret key below
k3.public.AmDwjlyf8jAV3gm5Z7Kz9xAOcsKslt_Vwp5v-emjFzBHLCtcANzTaVEghTNEMj9PkQ",
        )
        .with_stdin("k3.secret.fNYVuMvBgOlljt9TDohnaYLblghqaHoQquVZwgR6X12cBFHZLFsaU3q7X3k1Zn36")
        .run();

    // and then it should work
    cargo_process("login --key-subject=foo -Z registry-auth")
        .masquerade_as_nightly_cargo(&["registry-auth"])
        .replace_crates_io(registry.index_url())
        .run();

    let credentials = fs::read_to_string(&credentials).unwrap();
    assert!(credentials.starts_with("[registry]\n"));
    assert!(credentials.contains("secret-key-subject = \"foo\"\n"));
    assert!(credentials.contains("secret-key = \"k3.secret.fNYVuMvBgOlljt9TDohnaYLblghqaHoQquVZwgR6X12cBFHZLFsaU3q7X3k1Zn36\"\n"));
}

#[cargo_test]
fn login_with_generate_asymmetric_token() {
    let registry = registry::init();
    let credentials = credentials_toml();
    fs::remove_file(&credentials).unwrap();
    cargo_process("login --generate-keypair -Z registry-auth")
        .masquerade_as_nightly_cargo(&["registry-auth"])
        .replace_crates_io(registry.index_url())
        .with_stdout("k3.public.[..]")
        .run();
    let credentials = fs::read_to_string(&credentials).unwrap();
    assert!(credentials.contains("secret-key = \"k3.secret."));
}

#[cargo_test]
fn default_registry_configured() {
    // When registry.default is set, login should use that one when
    // --registry is not used.
    let _alternative = RegistryBuilder::new().alternative().build();
    let cargo_home = paths::home().join(".cargo");
    cargo_util::paths::append(
        &cargo_home.join("config"),
        br#"
            [registry]
            default = "alternative"
        "#,
    )
    .unwrap();

    cargo_process("login")
        .arg("a-new-token")
        .with_stderr(
            "\
[UPDATING] `alternative` index
[LOGIN] token for `alternative` saved
",
        )
        .run();

    check_token(None, None);
    check_token(Some("a-new-token"), Some("alternative"));
}