-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathregistry.rs
1836 lines (1685 loc) · 58 KB
/
registry.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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Interact with the [`TestRegistry`]
//!
//! # Example
//!
//! ```no_run
//! use cargo_test_support::registry::Package;
//! use cargo_test_support::project;
//! use cargo_test_support::str;
//!
//! // Publish package "a" depending on "b".
//! Package::new("a", "1.0.0")
//! .dep("b", "1.0.0")
//! .file("src/lib.rs", r#"
//! extern crate b;
//! pub fn f() -> i32 { b::f() * 2 }
//! "#)
//! .publish();
//!
//! // Publish package "b".
//! Package::new("b", "1.0.0")
//! .file("src/lib.rs", r#"
//! pub fn f() -> i32 { 12 }
//! "#)
//! .publish();
//!
//! // Create a project that uses package "a".
//! let p = project()
//! .file("Cargo.toml", r#"
//! [package]
//! name = "foo"
//! version = "0.0.1"
//!
//! [dependencies]
//! a = "1.0"
//! "#)
//! .file("src/main.rs", r#"
//! extern crate a;
//! fn main() { println!("{}", a::f()); }
//! "#)
//! .build();
//!
//! p.cargo("run").with_stdout_data(str!["24"]).run();
//! ```
use crate::git::repo;
use crate::paths;
use crate::publish::{create_index_line, write_to_index};
use cargo_util::paths::append;
use cargo_util::Sha256;
use flate2::write::GzEncoder;
use flate2::Compression;
use pasetors::keys::{AsymmetricPublicKey, AsymmetricSecretKey};
use pasetors::paserk::FormatAsPaserk;
use pasetors::token::UntrustedToken;
use std::collections::{BTreeMap, HashMap};
use std::fmt;
use std::fs::{self, File};
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::thread::{self, JoinHandle};
use tar::{Builder, Header};
use time::format_description::well_known::Rfc3339;
use time::{Duration, OffsetDateTime};
use url::Url;
/// Path to the local index for psuedo-crates.io.
///
/// This is a Git repo
/// initialized with a `config.json` file pointing to `dl_path` for downloads
/// and `api_path` for uploads.
///
/// ex: `$CARGO_TARGET_TMPDIR/cit/t0/registry`
pub fn registry_path() -> PathBuf {
generate_path("registry")
}
/// Path to the local web API uploads
///
/// Cargo will place the contents of a web API
/// request here. For example, `api/v1/crates/new` is the result of publishing a crate.
///
/// ex: `$CARGO_TARGET_TMPDIR/cit/t0/api`
pub fn api_path() -> PathBuf {
generate_path("api")
}
/// Path to download `.crate` files using the web API endpoint.
///
/// Crates
/// should be organized as `{name}/{version}/download` to match the web API
/// endpoint. This is rarely used and must be manually set up.
///
/// ex: `$CARGO_TARGET_TMPDIR/cit/t0/dl`
pub fn dl_path() -> PathBuf {
generate_path("dl")
}
/// Path to the alternative-registry version of [`registry_path`]
///
/// ex: `$CARGO_TARGET_TMPDIR/cit/t0/alternative-registry`
pub fn alt_registry_path() -> PathBuf {
generate_path("alternative-registry")
}
/// URL to the alternative-registry version of `registry_url`
fn alt_registry_url() -> Url {
generate_url("alternative-registry")
}
/// Path to the alternative-registry version of [`dl_path`]
///
/// ex: `$CARGO_TARGET_TMPDIR/cit/t0/alternative-dl`
pub fn alt_dl_path() -> PathBuf {
generate_path("alternative-dl")
}
/// Path to the alternative-registry version of [`api_path`]
///
/// ex: `$CARGO_TARGET_TMPDIR/cit/t0/alternative-api`
pub fn alt_api_path() -> PathBuf {
generate_path("alternative-api")
}
fn generate_path(name: &str) -> PathBuf {
paths::root().join(name)
}
fn generate_url(name: &str) -> Url {
Url::from_file_path(generate_path(name)).ok().unwrap()
}
/// Auth-token for publishing, see [`RegistryBuilder::token`]
#[derive(Clone)]
pub enum Token {
Plaintext(String),
Keys(String, Option<String>),
}
impl Token {
/// This is a valid PASETO secret key.
///
/// This one is already publicly available as part of the text of the RFC so is safe to use for tests.
pub fn rfc_key() -> Token {
Token::Keys(
"k3.secret.fNYVuMvBgOlljt9TDohnaYLblghqaHoQquVZwgR6X12cBFHZLFsaU3q7X3k1Zn36"
.to_string(),
Some("sub".to_string()),
)
}
}
type RequestCallback = Box<dyn Send + Fn(&Request, &HttpServer) -> Response>;
/// Prepare a local [`TestRegistry`] fixture
///
/// See also [`init`] and [`alt_init`]
pub struct RegistryBuilder {
/// If set, configures an alternate registry with the given name.
alternative: Option<String>,
/// The authorization token for the registry.
token: Option<Token>,
/// If set, the registry requires authorization for all operations.
auth_required: bool,
/// If set, serves the index over http.
http_index: bool,
/// If set, serves the API over http.
http_api: bool,
/// If set, config.json includes 'api'
api: bool,
/// Write the token in the configuration.
configure_token: bool,
/// Write the registry in configuration.
configure_registry: bool,
/// API responders.
custom_responders: HashMap<String, RequestCallback>,
/// Handler for 404 responses.
not_found_handler: RequestCallback,
/// If nonzero, the git index update to be delayed by the given number of seconds.
delayed_index_update: usize,
/// Credential provider in configuration
credential_provider: Option<String>,
}
/// A local registry fixture
///
/// Most tests won't need to call this directly but instead interact with [`Package`]
pub struct TestRegistry {
server: Option<HttpServerHandle>,
index_url: Url,
path: PathBuf,
api_url: Url,
dl_url: Url,
token: Token,
}
impl TestRegistry {
pub fn index_url(&self) -> &Url {
&self.index_url
}
pub fn api_url(&self) -> &Url {
&self.api_url
}
pub fn token(&self) -> &str {
match &self.token {
Token::Plaintext(s) => s,
Token::Keys(_, _) => panic!("registry was not configured with a plaintext token"),
}
}
pub fn key(&self) -> &str {
match &self.token {
Token::Plaintext(_) => panic!("registry was not configured with a secret key"),
Token::Keys(s, _) => s,
}
}
/// Shutdown the server thread and wait for it to stop.
/// `Drop` automatically stops the server, but this additionally
/// waits for the thread to stop.
pub fn join(self) {
if let Some(mut server) = self.server {
server.stop();
let handle = server.handle.take().unwrap();
handle.join().unwrap();
}
}
}
impl RegistryBuilder {
#[must_use]
pub fn new() -> RegistryBuilder {
let not_found = |_req: &Request, _server: &HttpServer| -> Response {
Response {
code: 404,
headers: vec![],
body: b"not found".to_vec(),
}
};
RegistryBuilder {
alternative: None,
token: None,
auth_required: false,
http_api: false,
http_index: false,
api: true,
configure_registry: true,
configure_token: true,
custom_responders: HashMap::new(),
not_found_handler: Box::new(not_found),
delayed_index_update: 0,
credential_provider: None,
}
}
/// Adds a custom HTTP response for a specific url
#[must_use]
pub fn add_responder<R: 'static + Send + Fn(&Request, &HttpServer) -> Response>(
mut self,
url: impl Into<String>,
responder: R,
) -> Self {
self.custom_responders
.insert(url.into(), Box::new(responder));
self
}
#[must_use]
pub fn not_found_handler<R: 'static + Send + Fn(&Request, &HttpServer) -> Response>(
mut self,
responder: R,
) -> Self {
self.not_found_handler = Box::new(responder);
self
}
/// Configures the git index update to be delayed by the given number of seconds.
#[must_use]
pub fn delayed_index_update(mut self, delay: usize) -> Self {
self.delayed_index_update = delay;
self
}
/// Sets whether or not to initialize as an alternative registry.
#[must_use]
pub fn alternative_named(mut self, alt: &str) -> Self {
self.alternative = Some(alt.to_string());
self
}
/// Sets whether or not to initialize as an alternative registry.
#[must_use]
pub fn alternative(self) -> Self {
self.alternative_named("alternative")
}
/// Prevents placing a token in the configuration
#[must_use]
pub fn no_configure_token(mut self) -> Self {
self.configure_token = false;
self
}
/// Prevents adding the registry to the configuration.
#[must_use]
pub fn no_configure_registry(mut self) -> Self {
self.configure_registry = false;
self
}
/// Sets the token value
#[must_use]
pub fn token(mut self, token: Token) -> Self {
self.token = Some(token);
self
}
/// Sets this registry to require the authentication token for
/// all operations.
#[must_use]
pub fn auth_required(mut self) -> Self {
self.auth_required = true;
self
}
/// Operate the index over http
#[must_use]
pub fn http_index(mut self) -> Self {
self.http_index = true;
self
}
/// Operate the api over http
#[must_use]
pub fn http_api(mut self) -> Self {
self.http_api = true;
self
}
/// The registry has no api.
#[must_use]
pub fn no_api(mut self) -> Self {
self.api = false;
self
}
/// The credential provider to configure for this registry.
#[must_use]
pub fn credential_provider(mut self, provider: &[&str]) -> Self {
self.credential_provider = Some(format!("['{}']", provider.join("','")));
self
}
/// Initializes the registry.
#[must_use]
pub fn build(self) -> TestRegistry {
let config_path = paths::cargo_home().join("config.toml");
t!(fs::create_dir_all(config_path.parent().unwrap()));
let prefix = if let Some(alternative) = &self.alternative {
format!("{alternative}-")
} else {
String::new()
};
let registry_path = generate_path(&format!("{prefix}registry"));
let index_url = generate_url(&format!("{prefix}registry"));
let api_url = generate_url(&format!("{prefix}api"));
let dl_url = generate_url(&format!("{prefix}dl"));
let dl_path = generate_path(&format!("{prefix}dl"));
let api_path = generate_path(&format!("{prefix}api"));
let token = self
.token
.unwrap_or_else(|| Token::Plaintext(format!("{prefix}sekrit")));
let (server, index_url, api_url, dl_url) = if !self.http_index && !self.http_api {
// No need to start the HTTP server.
(None, index_url, api_url, dl_url)
} else {
let server = HttpServer::new(
registry_path.clone(),
dl_path,
api_path.clone(),
token.clone(),
self.auth_required,
self.custom_responders,
self.not_found_handler,
self.delayed_index_update,
);
let index_url = if self.http_index {
server.index_url()
} else {
index_url
};
let api_url = if self.http_api {
server.api_url()
} else {
api_url
};
let dl_url = server.dl_url();
(Some(server), index_url, api_url, dl_url)
};
let registry = TestRegistry {
api_url,
index_url,
server,
dl_url,
path: registry_path,
token,
};
if self.configure_registry {
if let Some(alternative) = &self.alternative {
append(
&config_path,
format!(
"
[registries.{alternative}]
index = '{}'",
registry.index_url
)
.as_bytes(),
)
.unwrap();
if let Some(p) = &self.credential_provider {
append(
&config_path,
&format!(
"
credential-provider = {p}
"
)
.as_bytes(),
)
.unwrap()
}
} else {
append(
&config_path,
format!(
"
[source.crates-io]
replace-with = 'dummy-registry'
[registries.dummy-registry]
index = '{}'",
registry.index_url
)
.as_bytes(),
)
.unwrap();
if let Some(p) = &self.credential_provider {
append(
&config_path,
&format!(
"
[registry]
credential-provider = {p}
"
)
.as_bytes(),
)
.unwrap()
}
}
}
if self.configure_token {
let credentials = paths::cargo_home().join("credentials.toml");
match ®istry.token {
Token::Plaintext(token) => {
if let Some(alternative) = &self.alternative {
append(
&credentials,
format!(
r#"
[registries.{alternative}]
token = "{token}"
"#
)
.as_bytes(),
)
.unwrap();
} else {
append(
&credentials,
format!(
r#"
[registry]
token = "{token}"
"#
)
.as_bytes(),
)
.unwrap();
}
}
Token::Keys(key, subject) => {
let mut out = if let Some(alternative) = &self.alternative {
format!("\n[registries.{alternative}]\n")
} else {
format!("\n[registry]\n")
};
out += &format!("secret-key = \"{key}\"\n");
if let Some(subject) = subject {
out += &format!("secret-key-subject = \"{subject}\"\n");
}
append(&credentials, out.as_bytes()).unwrap();
}
}
}
let auth = if self.auth_required {
r#","auth-required":true"#
} else {
""
};
let api = if self.api {
format!(r#","api":"{}""#, registry.api_url)
} else {
String::new()
};
// Initialize a new registry.
repo(®istry.path)
.file(
"config.json",
&format!(r#"{{"dl":"{}"{api}{auth}}}"#, registry.dl_url),
)
.build();
fs::create_dir_all(api_path.join("api/v1/crates")).unwrap();
registry
}
}
/// Published package builder for [`TestRegistry`]
///
/// This uses "source replacement" using an automatically generated
/// `.cargo/config` file to ensure that dependencies will use these packages
/// instead of contacting crates.io. See `source-replacement.md` for more
/// details on how source replacement works.
///
/// Call [`Package::publish`] to finalize and create the package.
///
/// If no files are specified, an empty `lib.rs` file is automatically created.
///
/// The `Cargo.toml` file is automatically generated based on the methods
/// called on `Package` (for example, calling [`Package::dep()`] will add to the
/// `[dependencies]` automatically). You may also specify a `Cargo.toml` file
/// to override the generated one.
///
/// This supports different registry types:
/// - Regular source replacement that replaces `crates.io` (the default).
/// - A "local registry" which is a subset for vendoring (see
/// [`Package::local`]).
/// - An "alternative registry" which requires specifying the registry name
/// (see [`Package::alternative`]).
///
/// This does not support "directory sources". See `directory.rs` for
/// `VendorPackage` which implements directory sources.
#[must_use]
pub struct Package {
name: String,
vers: String,
deps: Vec<Dependency>,
files: Vec<PackageFile>,
yanked: bool,
features: FeatureMap,
local: bool,
alternative: bool,
invalid_index_line: bool,
index_line: Option<String>,
edition: Option<String>,
resolver: Option<String>,
proc_macro: bool,
links: Option<String>,
rust_version: Option<String>,
cargo_features: Vec<String>,
v: Option<u32>,
}
pub(crate) type FeatureMap = BTreeMap<String, Vec<String>>;
/// Published package dependency builder, see [`Package::add_dep`]
#[derive(Clone)]
pub struct Dependency {
name: String,
vers: String,
kind: String,
artifact: Option<String>,
bindep_target: Option<String>,
lib: bool,
target: Option<String>,
features: Vec<String>,
registry: Option<String>,
package: Option<String>,
optional: bool,
default_features: bool,
public: bool,
}
/// Entry with data that corresponds to [`tar::EntryType`].
#[non_exhaustive]
enum EntryData {
Regular(String),
Symlink(PathBuf),
}
/// A file to be created in a package.
struct PackageFile {
path: String,
contents: EntryData,
/// The Unix mode for the file. Note that when extracted on Windows, this
/// is mostly ignored since it doesn't have the same style of permissions.
mode: u32,
/// If `true`, the file is created in the root of the tarfile, used for
/// testing invalid packages.
extra: bool,
}
const DEFAULT_MODE: u32 = 0o644;
/// Setup a local psuedo-crates.io [`TestRegistry`]
///
/// This is implicitly called by [`Package::new`].
///
/// When calling `cargo publish`, see instead [`crate::publish`].
pub fn init() -> TestRegistry {
RegistryBuilder::new().build()
}
/// Setup a local "alternative" [`TestRegistry`]
///
/// When calling `cargo publish`, see instead [`crate::publish`].
pub fn alt_init() -> TestRegistry {
init();
RegistryBuilder::new().alternative().build()
}
pub struct HttpServerHandle {
addr: SocketAddr,
handle: Option<JoinHandle<()>>,
}
impl HttpServerHandle {
pub fn index_url(&self) -> Url {
Url::parse(&format!("sparse+http://{}/index/", self.addr.to_string())).unwrap()
}
pub fn api_url(&self) -> Url {
Url::parse(&format!("http://{}/", self.addr.to_string())).unwrap()
}
pub fn dl_url(&self) -> Url {
Url::parse(&format!("http://{}/dl", self.addr.to_string())).unwrap()
}
fn stop(&self) {
if let Ok(mut stream) = TcpStream::connect(self.addr) {
// shutdown the server
let _ = stream.write_all(b"stop");
let _ = stream.flush();
}
}
}
impl Drop for HttpServerHandle {
fn drop(&mut self) {
self.stop();
}
}
/// Request to the test http server
#[derive(Clone)]
pub struct Request {
pub url: Url,
pub method: String,
pub body: Option<Vec<u8>>,
pub authorization: Option<String>,
pub if_modified_since: Option<String>,
pub if_none_match: Option<String>,
}
impl fmt::Debug for Request {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// body is not included as it can produce long debug outputs
f.debug_struct("Request")
.field("url", &self.url)
.field("method", &self.method)
.field("authorization", &self.authorization)
.field("if_modified_since", &self.if_modified_since)
.field("if_none_match", &self.if_none_match)
.finish()
}
}
/// Response from the test http server
pub struct Response {
pub code: u32,
pub headers: Vec<String>,
pub body: Vec<u8>,
}
pub struct HttpServer {
listener: TcpListener,
registry_path: PathBuf,
dl_path: PathBuf,
api_path: PathBuf,
addr: SocketAddr,
token: Token,
auth_required: bool,
custom_responders: HashMap<String, RequestCallback>,
not_found_handler: RequestCallback,
delayed_index_update: usize,
}
/// A helper struct that collects the arguments for [`HttpServer::check_authorized`].
/// Based on looking at the request, these are the fields that the authentication header should attest to.
struct Mutation<'a> {
mutation: &'a str,
name: Option<&'a str>,
vers: Option<&'a str>,
cksum: Option<&'a str>,
}
impl HttpServer {
pub fn new(
registry_path: PathBuf,
dl_path: PathBuf,
api_path: PathBuf,
token: Token,
auth_required: bool,
custom_responders: HashMap<String, RequestCallback>,
not_found_handler: RequestCallback,
delayed_index_update: usize,
) -> HttpServerHandle {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let server = HttpServer {
listener,
registry_path,
dl_path,
api_path,
addr,
token,
auth_required,
custom_responders,
not_found_handler,
delayed_index_update,
};
let handle = Some(thread::spawn(move || server.start()));
HttpServerHandle { addr, handle }
}
fn start(&self) {
let mut line = String::new();
'server: loop {
let (socket, _) = self.listener.accept().unwrap();
let mut buf = BufReader::new(socket);
line.clear();
if buf.read_line(&mut line).unwrap() == 0 {
// Connection terminated.
continue;
}
// Read the "GET path HTTP/1.1" line.
let mut parts = line.split_ascii_whitespace();
let method = parts.next().unwrap().to_ascii_lowercase();
if method == "stop" {
// Shutdown the server.
return;
}
let addr = self.listener.local_addr().unwrap();
let url = format!(
"http://{}/{}",
addr,
parts.next().unwrap().trim_start_matches('/')
);
let url = Url::parse(&url).unwrap();
// Grab headers we care about.
let mut if_modified_since = None;
let mut if_none_match = None;
let mut authorization = None;
let mut content_len = None;
loop {
line.clear();
if buf.read_line(&mut line).unwrap() == 0 {
continue 'server;
}
if line == "\r\n" {
// End of headers.
line.clear();
break;
}
let (name, value) = line.split_once(':').unwrap();
let name = name.trim().to_ascii_lowercase();
let value = value.trim().to_string();
match name.as_str() {
"if-modified-since" => if_modified_since = Some(value),
"if-none-match" => if_none_match = Some(value),
"authorization" => authorization = Some(value),
"content-length" => content_len = Some(value),
_ => {}
}
}
let mut body = None;
if let Some(con_len) = content_len {
let len = con_len.parse::<u64>().unwrap();
let mut content = vec![0u8; len as usize];
buf.read_exact(&mut content).unwrap();
body = Some(content)
}
let req = Request {
authorization,
if_modified_since,
if_none_match,
method,
url,
body,
};
println!("req: {:#?}", req);
let response = self.route(&req);
let buf = buf.get_mut();
write!(buf, "HTTP/1.1 {}\r\n", response.code).unwrap();
write!(buf, "Content-Length: {}\r\n", response.body.len()).unwrap();
write!(buf, "Connection: close\r\n").unwrap();
for header in response.headers {
write!(buf, "{}\r\n", header).unwrap();
}
write!(buf, "\r\n").unwrap();
buf.write_all(&response.body).unwrap();
buf.flush().unwrap();
}
}
fn check_authorized(&self, req: &Request, mutation: Option<Mutation<'_>>) -> bool {
let (private_key, private_key_subject) = if mutation.is_some() || self.auth_required {
match &self.token {
Token::Plaintext(token) => return Some(token) == req.authorization.as_ref(),
Token::Keys(private_key, private_key_subject) => {
(private_key.as_str(), private_key_subject)
}
}
} else {
assert!(req.authorization.is_none(), "unexpected token");
return true;
};
macro_rules! t {
($e:expr) => {
match $e {
Some(e) => e,
None => return false,
}
};
}
let secret: AsymmetricSecretKey<pasetors::version3::V3> = private_key.try_into().unwrap();
let public: AsymmetricPublicKey<pasetors::version3::V3> = (&secret).try_into().unwrap();
let pub_key_id: pasetors::paserk::Id = (&public).into();
let mut paserk_pub_key_id = String::new();
FormatAsPaserk::fmt(&pub_key_id, &mut paserk_pub_key_id).unwrap();
// https://github.com/rust-lang/rfcs/blob/master/text/3231-cargo-asymmetric-tokens.md#how-the-registry-server-will-validate-an-asymmetric-token
// - The PASETO is in v3.public format.
let authorization = t!(&req.authorization);
let untrusted_token = t!(
UntrustedToken::<pasetors::Public, pasetors::version3::V3>::try_from(authorization)
.ok()
);
// - The PASETO validates using the public key it looked up based on the key ID.
#[derive(serde::Deserialize, Debug)]
struct Footer<'a> {
url: &'a str,
kip: &'a str,
}
let footer: Footer<'_> =
t!(serde_json::from_slice(untrusted_token.untrusted_footer()).ok());
if footer.kip != paserk_pub_key_id {
return false;
}
let trusted_token =
t!(
pasetors::version3::PublicToken::verify(&public, &untrusted_token, None, None,)
.ok()
);
// - The URL matches the registry base URL
if footer.url != "https://github.com/rust-lang/crates.io-index"
&& footer.url != &format!("sparse+http://{}/index/", self.addr.to_string())
{
return false;
}
// - The PASETO is still within its valid time period.
#[derive(serde::Deserialize)]
struct Message<'a> {
iat: &'a str,
sub: Option<&'a str>,
mutation: Option<&'a str>,
name: Option<&'a str>,
vers: Option<&'a str>,
cksum: Option<&'a str>,
_challenge: Option<&'a str>, // todo: PASETO with challenges
v: Option<u8>,
}
let message: Message<'_> = t!(serde_json::from_str(trusted_token.payload()).ok());
let token_time = t!(OffsetDateTime::parse(message.iat, &Rfc3339).ok());
let now = OffsetDateTime::now_utc();
if (now - token_time) > Duration::MINUTE {
return false;
}
if private_key_subject.as_deref() != message.sub {
return false;
}
// - If the claim v is set, that it has the value of 1.
if let Some(v) = message.v {
if v != 1 {
return false;
}
}
// - If the server issues challenges, that the challenge has not yet been answered.
// todo: PASETO with challenges
// - If the operation is a mutation:
if let Some(mutation) = mutation {
// - That the operation matches the mutation field and is one of publish, yank, or unyank.
if message.mutation != Some(mutation.mutation) {
return false;
}
// - That the package, and version match the request.
if message.name != mutation.name {
return false;
}
if message.vers != mutation.vers {
return false;
}
// - If the mutation is publish, that the version has not already been published, and that the hash matches the request.
if mutation.mutation == "publish" {
if message.cksum != mutation.cksum {
return false;
}
}
} else {
// - If the operation is a read, that the mutation field is not set.
if message.mutation.is_some()
|| message.name.is_some()
|| message.vers.is_some()
|| message.cksum.is_some()
{
return false;
}
}
true
}
/// Route the request
fn route(&self, req: &Request) -> Response {
// Check for custom responder
if let Some(responder) = self.custom_responders.get(req.url.path()) {
return responder(&req, self);
}
let path: Vec<_> = req.url.path()[1..].split('/').collect();
match (req.method.as_str(), path.as_slice()) {
("get", ["index", ..]) => {
if !self.check_authorized(req, None) {
self.unauthorized(req)
} else {
self.index(&req)
}
}
("get", ["dl", ..]) => {
if !self.check_authorized(req, None) {
self.unauthorized(req)
} else {
self.dl(&req)
}
}
// publish
("put", ["api", "v1", "crates", "new"]) => self.check_authorized_publish(req),
// The remainder of the operators in the test framework do nothing other than responding 'ok'.
//
// Note: We don't need to support anything real here because there are no tests that
// currently require anything other than publishing via the http api.
// yank / unyank
("delete" | "put", ["api", "v1", "crates", crate_name, version, mutation]) => {
if !self.check_authorized(
req,
Some(Mutation {
mutation,
name: Some(crate_name),
vers: Some(version),
cksum: None,
}),
) {