-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathtest_auth.rs
630 lines (551 loc) · 18.5 KB
/
test_auth.rs
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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// Copyright 2025 Oxide Computer Company
use std::{
fs::{read_to_string, write, File},
path::Path,
};
use assert_cmd::Command;
use expectorate::assert_contents;
use httpmock::{Method::POST, Mock, MockServer};
use oxide::types::CurrentUser;
use oxide_httpmock::MockServerExt;
use predicates::prelude::*;
use predicates::str;
use serde_json::json;
fn scrub_server(raw: String, server: String) -> String {
raw.replace(&server, "<TEST-SERVER>")
}
struct MockOAuth<'a> {
device_auth: Mock<'a>,
device_token: Mock<'a>,
me: Mock<'a>,
}
impl<'a> MockOAuth<'a> {
fn new(server: &'a MockServer) -> Self {
let device_auth = server.mock(|when, then| {
let body = json!({
"device_code": "DEV-CODE",
"user_code": "0X1-D3C",
"verification_uri": "http://go.here.to/verify",
"expires_in": 10,
});
when.method(POST).path("/device/auth");
then.status(200)
.json_body(body)
.header("content-type", "application/json");
});
// This is where we'd poll, but let's just wave them through.
let device_token = server.mock(|when, then| {
let body = json!({
"access_token": "123-456-789",
"token_type": "Bearer",
});
when.method(POST).path("/device/token");
then.delay(std::time::Duration::from_secs(1))
.status(200)
.json_body(body)
.header("content-type", "application/json");
});
// User and silo identity now that we're "authenticated".
let me = server.current_user_view(|when, then| {
when.into_inner().any_request();
then.ok(&CurrentUser {
display_name: "falken".to_string(),
id: "831dedf4-0a66-4b04-a232-b610f9f8924c".parse().unwrap(),
silo_id: "12e8c7a4-399f-41e2-985e-7b120ecbcc1a".parse().unwrap(),
silo_name: "crystal-palace".try_into().unwrap(),
});
});
Self {
device_auth,
device_token,
me,
}
}
fn assert(&self) {
self.device_auth.assert();
self.device_token.assert();
self.me.assert();
}
fn assert_hits(&self, hits: usize) {
self.device_auth.assert_hits(hits);
self.device_token.assert_hits(hits);
self.me.assert_hits(hits);
}
}
/// Assert the mode of a file on Unix. Does nothing on Windows.
#[track_caller]
fn assert_mode(path: &Path, expected_mode: u32) {
#[cfg(not(unix))]
{
// Avoid unused parameter warnings on Windows.
let _ = path;
let _ = expected_mode;
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let file = std::fs::File::open(path).unwrap();
let stat = file.metadata().unwrap();
let mode = stat.permissions().mode();
let umask = get_umask();
let derived_mode = expected_mode & !umask;
// Validate only the bottom nine permission bits.
if mode & 0o777 != derived_mode & 0o777 {
panic!("assertion failed: modes do not match for {}\n expected: 0o{:o}\n actual: 0o{:o}\n umask: 0o{umask:03o}", path.display(), derived_mode & 0o777, mode & 0o777);
}
}
}
#[cfg(unix)]
fn get_umask() -> u32 {
// Taken from https://github.com/rust-lang/cargo/blob/0473ee8b87dc7dbee53d13065c204ae63a0a2a9e/src/cargo/util/mod.rs#L143-L159
use std::sync::OnceLock;
static UMASK: OnceLock<u32> = OnceLock::new();
// We cannot retrieve umask without modifying it. Set it to zero, then
// immediately revert it to the original value. Store this so that we have a
// consistent value for the life of the program.
*UMASK.get_or_init(|| unsafe {
let umask = libc::umask(0);
libc::umask(umask);
umask as u32
})
}
// Test the first login where no config files exist yet.
#[test]
fn test_auth_login_first() {
let server = MockServer::start();
let mock = MockOAuth::new(&server);
let temp_dir = tempfile::tempdir().unwrap().into_path();
// Make sure we know how to make non-existent directories.
let config_dir = temp_dir.join(".config").join("oxide");
let cmd = Command::cargo_bin("oxide")
.unwrap()
.env("RUST_BACKTRACE", "1")
.arg("--config-dir")
.arg(config_dir.as_os_str())
.arg("auth")
.arg("login")
.arg("--no-browser")
.arg("--host")
.arg(server.url(""))
.assert()
.success();
let stdout = String::from_utf8_lossy(&cmd.get_output().stdout);
assert_contents(
"tests/data/test_auth_login_first.stdout",
&scrub_server(stdout.to_string(), server.url("")),
);
mock.assert();
assert_contents(
"tests/data/test_auth_login_first_credentials.toml",
&scrub_server(
read_to_string(config_dir.join("credentials.toml")).unwrap(),
server.url(""),
),
);
assert_mode(&config_dir.join("credentials.toml"), 0o600);
assert_contents(
"tests/data/test_auth_login_first_config.toml",
&read_to_string(config_dir.join("config.toml")).unwrap(),
);
assert_mode(&config_dir.join("config.toml"), 0o644);
}
fn write_first_creds(dir: &Path) {
let cred_path = dir.join("credentials.toml");
let creds = "\
[profile.first]\n\
host = \"https://oxide.internal\"\n\
token = \"***-***-***\"\n\
user = \"00000000-0000-0000-0000-000000000000\"\n\
";
write(&cred_path, creds).unwrap();
// On Unix set permissions to 0600 to avoid triggering permissions warning.
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let file = File::open(&cred_path).unwrap();
let mut perms = file.metadata().unwrap().permissions();
perms.set_mode(0o600);
file.set_permissions(perms).unwrap();
}
}
fn write_first_config(dir: &Path) {
let config_path = dir.join("config.toml");
let config = "\
default-profile = \"first\"
";
write(config_path, config).unwrap();
}
#[test]
fn test_auth_login_existing_default() {
let server = MockServer::start();
let mock = MockOAuth::new(&server);
let temp_dir = tempfile::tempdir().unwrap().into_path();
write_first_creds(&temp_dir);
let creds_path = temp_dir.join("credentials.toml");
assert_mode(&creds_path, 0o600);
write_first_config(&temp_dir);
assert_mode(&temp_dir.join("config.toml"), 0o644);
let cmd = Command::cargo_bin("oxide")
.unwrap()
.env("RUST_BACKTRACE", "1")
.arg("--profile")
.arg("crystal-palace")
.arg("--config-dir")
.arg(temp_dir.as_os_str())
.arg("auth")
.arg("login")
.arg("--no-browser")
.arg("--host")
.arg(server.url(""))
.assert()
.success();
let stdout = String::from_utf8_lossy(&cmd.get_output().stdout);
let creds_path = temp_dir.join("credentials.toml");
assert_contents(
"tests/data/test_auth_existing_default.stdout",
&scrub_server(stdout.to_string(), server.url("")),
);
mock.assert();
assert_contents(
"tests/data/test_auth_existing_default_credentials.toml",
&scrub_server(read_to_string(&creds_path).unwrap(), server.url("")),
);
assert_mode(&creds_path, 0o600);
assert_contents(
"tests/data/test_auth_existing_default_config.toml",
&read_to_string(temp_dir.join("config.toml")).unwrap(),
);
assert_mode(&temp_dir.join("config.toml"), 0o644);
}
#[test]
fn test_auth_login_existing_no_default() {
let server = MockServer::start();
let mock = MockOAuth::new(&server);
let temp_dir = tempfile::tempdir().unwrap().into_path();
write_first_creds(&temp_dir);
assert_mode(&temp_dir.join("credentials.toml"), 0o600);
let cmd = Command::cargo_bin("oxide")
.unwrap()
.env("RUST_BACKTRACE", "1")
.arg("--config-dir")
.arg(temp_dir.as_os_str())
.arg("auth")
.arg("login")
.arg("--no-browser")
.arg("--host")
.arg(server.url(""))
.assert()
.success();
let stdout = String::from_utf8_lossy(&cmd.get_output().stdout);
assert_contents(
"tests/data/test_auth_existing_no_default.stdout",
&scrub_server(stdout.to_string(), server.url("")),
);
mock.assert();
assert_contents(
"tests/data/test_auth_existing_no_default_credentials.toml",
&scrub_server(
read_to_string(temp_dir.join("credentials.toml")).unwrap(),
server.url(""),
),
);
assert_mode(&temp_dir.join("credentials.toml"), 0o600);
assert_contents(
"tests/data/test_auth_existing_no_default_config.toml",
&read_to_string(temp_dir.join("config.toml")).unwrap(),
);
assert_mode(&temp_dir.join("config.toml"), 0o644);
}
#[test]
#[cfg(unix)]
fn test_auth_credentials_permissions() {
let server = MockServer::start();
let temp_dir = tempfile::tempdir().unwrap().into_path();
let cred_path = temp_dir.join("credentials.toml");
let creds = format!(
"\
[profile.lightman]\n\
host = \"{}\"\n\
token = \"***-***-*ok\"\n\
user = \"00000000-0000-0000-0000-000000000000\"\n\
\n\
",
server.url(""),
);
write(&cred_path, creds).unwrap();
assert_mode(&cred_path, 0o644);
// Validate authenticated credentials
let cmd = Command::cargo_bin("oxide")
.unwrap()
.arg("--config-dir")
.arg(temp_dir.as_os_str())
.arg("auth")
.arg("status")
.assert()
.success();
let stderr = String::from_utf8_lossy(&cmd.get_output().stderr);
fn scrub_creds(raw: String, path: &Path) -> String {
let path = path.to_string_lossy().to_string();
raw.replace(&path, "<CREDENTIALS-PATH>")
}
assert_contents(
"tests/data/test_auth_credentials_permissions.stderr",
&scrub_creds(stderr.to_string(), &cred_path),
);
assert_mode(&cred_path, 0o644);
}
#[test]
fn test_auth_login_double() {
let server = MockServer::start();
let mock = MockOAuth::new(&server);
let temp_dir = tempfile::tempdir().unwrap().into_path();
Command::cargo_bin("oxide")
.unwrap()
.env("RUST_BACKTRACE", "1")
.arg("--config-dir")
.arg(temp_dir.as_os_str())
.arg("auth")
.arg("login")
.arg("--no-browser")
.arg("--host")
.arg(server.url(""))
.assert()
.success();
let cmd = Command::cargo_bin("oxide")
.unwrap()
.env("RUST_BACKTRACE", "1")
.arg("--config-dir")
.arg(temp_dir.as_os_str())
.arg("auth")
.arg("login")
.arg("--no-browser")
.arg("--host")
.arg(server.url(""))
.assert()
.success();
let stdout = String::from_utf8_lossy(&cmd.get_output().stdout);
assert_contents(
"tests/data/test_auth_double.stdout",
&scrub_server(stdout.to_string(), server.url("")),
);
mock.assert_hits(2);
assert_contents(
"tests/data/test_auth_double_credentials.toml",
&scrub_server(
read_to_string(temp_dir.join("credentials.toml")).unwrap(),
server.url(""),
),
);
assert_mode(&temp_dir.join("credentials.toml"), 0o600);
assert_contents(
"tests/data/test_auth_double_config.toml",
&read_to_string(temp_dir.join("config.toml")).unwrap(),
);
assert_mode(&temp_dir.join("config.toml"), 0o644);
}
#[test]
fn test_cmd_auth_status() {
let server = MockServer::start();
let temp_dir = tempfile::tempdir().unwrap().into_path();
let cred_path = temp_dir.join("credentials.toml");
let creds = format!(
"\
[profile.lightman]\n\
host = \"{}\"\n\
token = \"***-***-*ok\"\n\
user = \"00000000-0000-0000-0000-000000000000\"\n\
\n\
[profile.jennifer]\n\
host = \"{}\"\n\
token = \"***-***-*ok\"\n\
user = \"00000000-0000-0000-0000-000000000001\"\n\
\n\
[profile.malvin]\n\
host = \"{}\"\n\
token = \"***-***-bad\"\n\
user = \"00000000-0000-0000-0000-000000000002\"\n\
\n\
[profile.sting]\n\
host = \"https://unresolvabledomainnameihope\"\n\
token = \"***-***-***\"\n\
user = \"00000000-0000-0000-0000-000000000002\"\n\
\n\
",
server.url(""),
server.url(""),
server.url(""),
);
write(&cred_path, creds).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let file = File::open(&cred_path).unwrap();
let mut perms = file.metadata().unwrap().permissions();
perms.set_mode(0o600);
file.set_permissions(perms).unwrap()
}
let empty_creds_dir = tempfile::tempdir().unwrap().into_path();
File::create(empty_creds_dir.join("credentials.toml")).unwrap();
let ok = server.current_user_view(|when, then| {
when.into_inner()
.header("authorization", "Bearer ***-***-*ok");
then.ok(&oxide::types::CurrentUser {
display_name: "privileged".to_string(),
id: "001de000-05e4-4000-8000-000000004007".parse().unwrap(),
silo_id: "d1bb398f-872c-438c-a4c6-2211e2042526".parse().unwrap(),
silo_name: "funky-town".parse().unwrap(),
});
});
let bad = server.current_user_view(|when, then| {
when.into_inner()
.header("authorization", "Bearer ***-***-bad");
then.client_error(
401,
&oxide::types::Error {
error_code: None,
message: "** IMPROPER REQUEST **".to_string(),
request_id: "42".to_string(),
},
);
});
// Validate authenticated credentials
let cmd = Command::cargo_bin("oxide")
.unwrap()
.arg("--config-dir")
.arg(temp_dir.as_os_str())
.arg("auth")
.arg("status")
.assert()
.success();
let stdout = String::from_utf8_lossy(&cmd.get_output().stdout);
// DNS failure output can vary by platform
let stdout = match stdout.find("dns error:") {
Some(ii) => &stdout[..ii],
None => &stdout,
};
assert_contents(
"tests/data/test_auth_status.stdout",
&scrub_server(stdout.to_string(), server.url("")),
);
// Validate empty `credentials.toml` does not error.
Command::cargo_bin("oxide")
.unwrap()
.arg("--config-dir")
.arg(empty_creds_dir.as_os_str())
.arg("auth")
.arg("status")
.assert()
.success()
.stdout(str::is_empty());
ok.assert_hits(2);
bad.assert();
}
#[test]
fn test_cmd_auth_status_env() {
let server = MockServer::start();
let oxide_mock = server.current_user_view(|when, then| {
when.into_inner()
.header("authorization", "Bearer oxide-token-good");
then.ok(&oxide::types::CurrentUser {
display_name: "privileged".to_string(),
id: "001de000-05e4-4000-8000-000000004007".parse().unwrap(),
silo_id: "d1bb398f-872c-438c-a4c6-2211e2042526".parse().unwrap(),
silo_name: "funky-town".parse().unwrap(),
});
});
// Validate authenticated credentials
Command::cargo_bin("oxide")
.unwrap()
.arg("auth")
.arg("status")
.env("OXIDE_HOST", server.url(""))
.env("OXIDE_TOKEN", "oxide-token-good")
.assert()
.success()
.stdout(format!(
"Logged in to {} as 001de000-05e4-4000-8000-000000004007\n",
server.url("")
));
oxide_mock.assert();
let oxide_mock = server.current_user_view(|when, then| {
when.into_inner()
.header("authorization", "Bearer oxide-token-bad");
then.server_error(
500,
&oxide::types::Error {
error_code: None,
message: "oops".to_string(),
request_id: "42".to_string(),
},
);
});
// Try invalid credentials.
Command::cargo_bin("oxide")
.unwrap()
.arg("auth")
.arg("status")
.env("OXIDE_HOST", server.url(""))
.env("OXIDE_TOKEN", "oxide-token-bad")
.assert()
.success()
.stdout(format!(
"{}: Server responded with an error message: oops\n",
server.url("")
));
oxide_mock.assert();
}
#[test]
fn test_cmd_auth_debug_logging() {
let server = MockServer::start();
let oxide_mock = server.current_user_view(|when, then| {
when.into_inner()
.header("authorization", "Bearer oxide-token-good");
then.ok(&oxide::types::CurrentUser {
display_name: "privileged".to_string(),
id: "001de000-05e4-4000-8000-000000004007".parse().unwrap(),
silo_id: "d1bb398f-872c-438c-a4c6-2211e2042526".parse().unwrap(),
silo_name: "funky-town".parse().unwrap(),
});
});
let cmd = Command::cargo_bin("oxide")
.unwrap()
.arg("auth")
.arg("status")
.env("RUST_LOG", "oxide=debug")
.env("OXIDE_HOST", server.url(""))
.env("OXIDE_TOKEN", "oxide-token-good")
.assert()
.success();
let stderr_str = std::str::from_utf8(&cmd.get_output().stderr).unwrap();
assert!(str::is_match(r#""level":"DEBUG""#)
.unwrap()
.eval(stderr_str));
assert!(str::is_match(r#""message":"request succeeded""#)
.unwrap()
.eval(stderr_str));
assert!(str::is_match(r#""url":"http://127.0.0.1:\d+/v1/me""#)
.unwrap()
.eval(stderr_str));
assert!(str::is_match(r#""path":"/v1/me""#)
.unwrap()
.eval(stderr_str));
assert!(str::is_match(r#""remote_addr":"127.0.0.1:\d+""#)
.unwrap()
.eval(stderr_str));
assert!(str::is_match(r#""http.request.method":"GET""#)
.unwrap()
.eval(stderr_str));
assert!(str::is_match(r#""http.response.content_length":\d+"#)
.unwrap()
.eval(stderr_str));
assert!(str::is_match(r#""http.response.status_code":200"#)
.unwrap()
.eval(stderr_str));
assert!(str::is_match(r#""duration_ms":\d+"#)
.unwrap()
.eval(stderr_str));
oxide_mock.assert();
}