-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathimageproxy.rs
More file actions
1135 lines (1025 loc) · 40.7 KB
/
imageproxy.rs
File metadata and controls
1135 lines (1025 loc) · 40.7 KB
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
//! Run skopeo as a subprocess to fetch container images.
//!
//! This allows fetching a container image manifest and layers in a streaming fashion.
//!
//! More information: <https://github.com/containers/skopeo/pull/1476>
pub mod transport;
// Re-export oci_spec so consumers don't need to add it as a dependency.
// NOTE: Bumping oci_spec in a semver-incompatible way requires bumping this crate too.
// See Cargo.toml for details.
pub use ::oci_spec;
pub use transport::{
ContainersStorageRef, ImageReference, ImageReferenceError, Transport, TransportConversionError,
};
use ::oci_spec::image::{Descriptor, Digest};
use cap_std_ext::prelude::CapStdExtCommandExt;
use cap_std_ext::{cap_std, cap_tempfile};
use futures_util::{Future, FutureExt};
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::iter::FusedIterator;
use std::num::NonZeroU32;
use std::ops::Range;
use std::os::fd::OwnedFd;
use std::os::unix::prelude::CommandExt;
use std::path::PathBuf;
use std::pin::Pin;
use std::process::{Command, Stdio};
use std::sync::{Arc, Mutex, OnceLock};
use thiserror::Error;
use tokio::io::{AsyncBufRead, AsyncReadExt};
use tokio::sync::Mutex as AsyncMutex;
use tokio::task::JoinError;
use tracing::instrument;
/// Errors returned by this crate.
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum Error {
#[error("i/o error: {0}")]
/// An input/output error
Io(#[from] std::io::Error),
#[error("skopeo spawn error: {0}")]
/// An error spawning skopeo
SkopeoSpawnError(#[source] std::io::Error),
#[error("serialization error: {0}")]
/// Returned when serialization or deserialization fails
SerDe(#[from] serde_json::Error),
/// The proxy failed to initiate a request
#[error("failed to invoke method {method}: {error}")]
RequestInitiationFailure { method: Box<str>, error: Box<str> },
/// An error returned from the remote proxy
#[error("proxy request returned error: {0}")]
RequestReturned(Box<str>),
#[error("semantic version error: {0}")]
SemanticVersion(#[from] semver::Error),
#[error("proxy too old (requested={requested_version} found={found_version}) error")]
/// The proxy doesn't support the requested semantic version
ProxyTooOld {
requested_version: Box<str>,
found_version: Box<str>,
},
#[error("configuration error: {0}")]
/// Conflicting or missing configuration
Configuration(Box<str>),
#[error("other error: {0}")]
/// An unknown other error
Other(Box<str>),
}
impl Error {
pub(crate) fn new_other(e: impl Into<Box<str>>) -> Self {
Self::Other(e.into())
}
}
/// Errors returned by get_raw_blob
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum GetBlobError {
/// A client may reasonably retry on this type of error.
#[error("retryable error: {0}")]
Retryable(Box<str>),
#[error("other error: {0}")]
/// An unknown other error
Other(Box<str>),
}
impl From<rustix::io::Errno> for Error {
fn from(value: rustix::io::Errno) -> Self {
Self::Io(value.into())
}
}
/// The error type returned from this crate.
pub type Result<T> = std::result::Result<T, Error>;
/// File descriptor range which is reserved for passing data down into the proxy;
/// avoid configuring the command to use files in this range. (Also, stdin is
/// reserved)
pub const RESERVED_FD_RANGE: Range<i32> = 100..200;
// This is defined in skopeo; maximum size of JSON we will read/write.
// Note that payload data (non-metadata) should go over a pipe file descriptor.
const MAX_MSG_SIZE: usize = 32 * 1024;
fn base_proto_version() -> &'static semver::VersionReq {
// Introduced in https://github.com/containers/skopeo/pull/1523
static BASE_PROTO_VERSION: OnceLock<semver::VersionReq> = OnceLock::new();
BASE_PROTO_VERSION.get_or_init(|| semver::VersionReq::parse("0.2.3").unwrap())
}
fn layer_info_proto_version() -> &'static semver::VersionReq {
static LAYER_INFO_PROTO_VERSION: OnceLock<semver::VersionReq> = OnceLock::new();
LAYER_INFO_PROTO_VERSION.get_or_init(|| semver::VersionReq::parse("0.2.5").unwrap())
}
fn layer_info_piped_proto_version() -> &'static semver::VersionReq {
static LAYER_INFO_PROTO_VERSION: OnceLock<semver::VersionReq> = OnceLock::new();
LAYER_INFO_PROTO_VERSION.get_or_init(|| semver::VersionReq::parse("0.2.7").unwrap())
}
#[derive(Serialize)]
struct Request {
method: String,
args: Vec<serde_json::Value>,
}
impl Request {
fn new<T, I>(method: &str, args: T) -> Self
where
T: IntoIterator<Item = I>,
I: Into<serde_json::Value>,
{
let args: Vec<_> = args.into_iter().map(|v| v.into()).collect();
Self {
method: method.to_string(),
args,
}
}
fn new_bare(method: &str) -> Self {
Self {
method: method.to_string(),
args: vec![],
}
}
}
#[derive(Deserialize)]
struct Reply {
success: bool,
error: String,
pipeid: u32,
value: serde_json::Value,
}
type ChildFuture = Pin<
Box<
dyn Future<Output = std::result::Result<std::io::Result<std::process::Output>, JoinError>>
+ Send,
>,
>;
/// Manage a child process proxy to fetch container images.
pub struct ImageProxy {
sockfd: Arc<Mutex<OwnedFd>>,
childwait: Arc<AsyncMutex<ChildFuture>>,
protover: semver::Version,
}
impl std::fmt::Debug for ImageProxy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ImageProxy").finish()
}
}
/// Opaque identifier for an image
#[derive(Debug, PartialEq, Eq)]
pub struct OpenedImage(u32);
#[derive(Debug, PartialEq, Eq)]
struct PipeId(NonZeroU32);
impl PipeId {
fn try_new(pipeid: u32) -> Option<Self> {
Some(Self(NonZeroU32::new(pipeid)?))
}
}
/// Configuration for the proxy.
#[derive(Debug, Default)]
pub struct ImageProxyConfig {
/// Path to container auth file; equivalent to `skopeo --authfile`.
/// This conflicts with [`auth_data`].
pub authfile: Option<PathBuf>,
/// Data stream for container auth. This conflicts with [`authfile`].
pub auth_data: Option<File>,
/// Do not use default container authentication paths; equivalent to `skopeo --no-creds`.
///
/// Defaults to `false`; in other words, use the default file paths from `man containers-auth.json`.
pub auth_anonymous: bool,
// Directory with certificates (*.crt, *.cert, *.key) used to connect to registry
// Equivalent to `skopeo --cert-dir`
pub certificate_directory: Option<PathBuf>,
/// Decryption keys to decrypt an encrypted container image.
/// equivalent to `skopeo copy --decryption-key <path_to_decryption_key> `
pub decryption_keys: Option<Vec<String>>,
/// If set, disable TLS verification. Equivalent to `skopeo --tls-verify=false`.
pub insecure_skip_tls_verification: Option<bool>,
/// If set, disable signature verification. Equivalent to `skopeo --insecure-policy`.
pub insecure_policy: Option<bool>,
/// Prefix to add to the user agent string. Equivalent to `skopeo --user-agent-prefix`.
/// The resulting user agent will be in the format "prefix skopeo/version".
/// This option is only used if the installed skopeo version supports it.
pub user_agent_prefix: Option<String>,
/// If enabled, propagate debug-logging level from the proxy via stderr to the
/// current process' stderr. Note than when enabled, this also means that standard
/// error will no longer be captured.
pub debug: bool,
/// Provide a configured [`std::process::Command`] instance.
///
/// This allows configuring aspects of the resulting child `skopeo` process.
/// The intention of this hook is to allow the caller to use e.g.
/// `systemd-run` or equivalent containerization tools. For example you
/// can set up a command whose arguments are `systemd-run -Pq -p DynamicUser=yes -- skopeo`.
/// You can also set up arbitrary aspects of the child via e.g.
/// [`current_dir`] [`pre_exec`].
///
/// [`current_dir`]: https://doc.rust-lang.org/std/process/struct.Command.html#method.current_dir
/// [`pre_exec`]: https://doc.rust-lang.org/std/os/unix/process/trait.CommandExt.html#tymethod.pre_exec
///
/// The default is to wrap via util-linux `setpriv --pdeathsig SIGTERM -- skopeo`,
/// which on Linux binds the lifecycle of the child process to the parent.
///
/// Note that you *must* add `skopeo` as the primary argument or
/// indirectly. However, all other command line options including
/// `experimental-image-proxy` will be injected by this library.
/// You may use a different command name from `skopeo` if your
/// application has set up a compatible copy, e.g. `/usr/lib/myapp/my-private-skopeo`/
pub skopeo_cmd: Option<Command>,
}
/// Check if skopeo supports --user-agent-prefix by probing --help output
fn supports_user_agent_prefix() -> bool {
static SUPPORTS_USER_AGENT: OnceLock<bool> = OnceLock::new();
*SUPPORTS_USER_AGENT.get_or_init(|| {
Command::new("skopeo")
.arg("--help")
.stdout(Stdio::piped())
.stderr(Stdio::null())
.output()
.ok()
.and_then(|output| {
String::from_utf8(output.stdout)
.ok()
.map(|help| help.contains("--user-agent-prefix"))
})
.unwrap_or(false)
})
}
impl TryFrom<ImageProxyConfig> for Command {
type Error = Error;
fn try_from(config: ImageProxyConfig) -> Result<Self> {
let debug = config.debug || std::env::var_os("CONTAINERS_IMAGE_PROXY_DEBUG").is_some();
let mut allocated_fds = RESERVED_FD_RANGE.clone();
let mut alloc_fd = || {
allocated_fds.next().ok_or_else(|| {
Error::Other("Ran out of reserved file descriptors for child".into())
})
};
// By default, we set up pdeathsig to "lifecycle bind" the child process to us.
let mut c = config.skopeo_cmd.unwrap_or_else(|| {
let mut c = std::process::Command::new("skopeo");
// SAFETY: set_parent_process_death_signal is async-signal-safe
#[allow(unsafe_code)]
unsafe {
c.pre_exec(|| {
Ok(rustix::process::set_parent_process_death_signal(Some(
rustix::process::Signal::TERM,
))?)
});
}
c
});
c.arg("experimental-image-proxy");
if debug {
c.arg("--debug");
}
let auth_option_count = [
config.authfile.is_some(),
config.auth_data.is_some(),
config.auth_anonymous,
]
.into_iter()
.filter(|&x| x)
.count();
if auth_option_count > 1 {
// This is a programmer error really
return Err(Error::Configuration(
"Conflicting authentication options".into(),
));
}
if let Some(authfile) = config.authfile {
c.arg("--authfile");
c.arg(authfile);
} else if let Some(mut auth_data) = config.auth_data.map(std::io::BufReader::new) {
// If we get the authentication data as a file, we always copy it to a new temporary file under
// the assumption that the caller provided it this way to aid in privilege separation where
// the file is only readable to privileged code.
let target_fd = alloc_fd()?;
let tmpd = &cap_std::fs::Dir::open_ambient_dir("/tmp", cap_std::ambient_authority())?;
let mut tempfile =
cap_tempfile::TempFile::new_anonymous(tmpd).map(std::io::BufWriter::new)?;
std::io::copy(&mut auth_data, &mut tempfile)?;
let tempfile = tempfile
.into_inner()
.map_err(|e| e.into_error())?
.into_std();
let fd = std::sync::Arc::new(tempfile.into());
c.take_fd_n(fd, target_fd);
c.arg("--authfile");
c.arg(format!("/proc/self/fd/{target_fd}"));
} else if config.auth_anonymous {
c.arg("--no-creds");
}
if let Some(certificate_directory) = config.certificate_directory {
c.arg("--cert-dir");
c.arg(certificate_directory);
}
if let Some(decryption_keys) = config.decryption_keys {
for decryption_key in &decryption_keys {
c.arg("--decryption-key");
c.arg(decryption_key);
}
}
if config.insecure_skip_tls_verification.unwrap_or_default() {
c.arg("--tls-verify=false");
}
if config.insecure_policy.unwrap_or_default() {
c.arg("--insecure-policy");
}
// Add user agent prefix if provided and supported by skopeo
if let Some(user_agent_prefix) = config.user_agent_prefix {
if supports_user_agent_prefix() {
c.arg("--user-agent-prefix");
c.arg(user_agent_prefix);
}
}
c.stdout(Stdio::null());
if !debug {
c.stderr(Stdio::piped());
}
Ok(c)
}
}
/// BlobInfo collects known information about a blob
#[derive(Debug, serde::Deserialize)]
pub struct ConvertedLayerInfo {
/// Uncompressed digest of a layer; for more information, see
/// https://github.com/opencontainers/image-spec/blob/main/config.md#layer-diffid
pub digest: Digest,
/// Size of blob
pub size: u64,
/// Mediatype of blob
pub media_type: oci_spec::image::MediaType,
}
/// A single fd; requires invoking FinishPipe
#[derive(Debug)]
struct FinishPipe {
pipeid: PipeId,
datafd: OwnedFd,
}
/// There is a data FD and an error FD. The error FD will be JSON.
#[derive(Debug)]
struct DualFds {
datafd: OwnedFd,
errfd: OwnedFd,
}
/// Helper trait for parsing the pipeid and/or file descriptors of a reply
trait FromReplyFds: Send + 'static
where
Self: Sized,
{
fn from_reply(
iterable: impl IntoIterator<IntoIter: FusedIterator, Item = OwnedFd>,
pipeid: u32,
) -> Result<Self>;
}
/// No file descriptors or pipeid expected
impl FromReplyFds for () {
fn from_reply(fds: impl IntoIterator<Item = OwnedFd>, pipeid: u32) -> Result<Self> {
if fds.into_iter().next().is_some() {
return Err(Error::Other("expected no fds".into()));
}
if pipeid != 0 {
return Err(Error::Other("unexpected pipeid".into()));
}
Ok(())
}
}
/// A FinishPipe instance
impl FromReplyFds for FinishPipe {
fn from_reply(fds: impl IntoIterator<Item = OwnedFd>, pipeid: u32) -> Result<Self> {
let Some(pipeid) = PipeId::try_new(pipeid) else {
return Err(Error::Other("Expected pipeid for FinishPipe".into()));
};
let datafd = fds
.into_iter()
.exactly_one()
.map_err(|_| Error::Other("Expected exactly one fd for FinishPipe".into()))?;
Ok(Self { pipeid, datafd })
}
}
/// A DualFds instance
impl FromReplyFds for DualFds {
fn from_reply(fds: impl IntoIterator<Item = OwnedFd>, pipeid: u32) -> Result<Self> {
if pipeid != 0 {
return Err(Error::Other("Unexpected pipeid with DualFds".into()));
}
let [datafd, errfd] = fds
.into_iter()
.collect_array()
.ok_or_else(|| Error::Other("Expected two fds for DualFds".into()))?;
Ok(Self { datafd, errfd })
}
}
impl ImageProxy {
/// Create an image proxy that fetches the target image, using default configuration.
pub async fn new() -> Result<Self> {
Self::new_with_config(Default::default()).await
}
/// Create an image proxy that fetches the target image
#[instrument]
pub async fn new_with_config(config: ImageProxyConfig) -> Result<Self> {
let mut c = Command::try_from(config)?;
let (mysock, theirsock) = rustix::net::socketpair(
rustix::net::AddressFamily::UNIX,
rustix::net::SocketType::SEQPACKET,
rustix::net::SocketFlags::CLOEXEC,
None,
)?;
c.stdin(Stdio::from(theirsock));
let child = match c.spawn() {
Ok(c) => c,
Err(error) => return Err(Error::SkopeoSpawnError(error)),
};
tracing::debug!("Spawned skopeo pid={:?}", child.id());
// Here we use std sync API via thread because tokio installs
// a SIGCHLD handler which can conflict with e.g. the glib one
// which may also be in process.
// xref https://github.com/tokio-rs/tokio/issues/3520#issuecomment-968985861
let childwait = tokio::task::spawn_blocking(move || child.wait_with_output());
let sockfd = Arc::new(Mutex::new(mysock));
let mut r = Self {
sockfd,
childwait: Arc::new(AsyncMutex::new(Box::pin(childwait))),
protover: semver::Version::new(0, 0, 0),
};
// Verify semantic version
let protover: String = r.impl_request("Initialize", [(); 0]).await?;
tracing::debug!("Remote protocol version: {protover}");
let protover = semver::Version::parse(protover.as_str())?;
// Previously we had a feature to opt-in to requiring newer versions using `if cfg!()`.
let supported = base_proto_version();
if !supported.matches(&protover) {
return Err(Error::ProxyTooOld {
requested_version: protover.to_string().into(),
found_version: supported.to_string().into(),
});
}
r.protover = protover;
Ok(r)
}
/// Create and send a request. Should only be used by impl_request.
async fn impl_request_raw<T: serde::de::DeserializeOwned + Send + 'static, F: FromReplyFds>(
sockfd: Arc<Mutex<OwnedFd>>,
req: Request,
) -> Result<(T, F)> {
tracing::trace!("sending request {}", req.method.as_str());
// TODO: Investigate https://crates.io/crates/uds for SOCK_SEQPACKET tokio
let r = tokio::task::spawn_blocking(move || {
let sockfd = sockfd.lock().unwrap();
let sendbuf = serde_json::to_vec(&req)?;
let sockfd = &*sockfd;
rustix::net::send(sockfd, &sendbuf, rustix::net::SendFlags::empty())?;
drop(sendbuf);
let mut buf = [0u8; MAX_MSG_SIZE];
let mut cmsg_space: Vec<std::mem::MaybeUninit<u8>> =
vec![std::mem::MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(1))];
let mut cmsg_buffer = rustix::net::RecvAncillaryBuffer::new(cmsg_space.as_mut_slice());
let iov = std::io::IoSliceMut::new(buf.as_mut());
let mut iov = [iov];
let nread = rustix::net::recvmsg(
sockfd,
&mut iov,
&mut cmsg_buffer,
rustix::net::RecvFlags::CMSG_CLOEXEC,
)?
.bytes;
let fdret = cmsg_buffer
.drain()
.filter_map(|m| match m {
rustix::net::RecvAncillaryMessage::ScmRights(f) => Some(f),
_ => None,
})
.flatten();
let buf = &buf[..nread];
let reply: Reply = serde_json::from_slice(buf)?;
if !reply.success {
return Err(Error::RequestInitiationFailure {
method: req.method.clone().into(),
error: reply.error.into(),
});
}
let fds = FromReplyFds::from_reply(fdret, reply.pipeid)?;
Ok((serde_json::from_value(reply.value)?, fds))
})
.await
.map_err(|e| Error::Other(e.to_string().into()))??;
tracing::trace!("completed request");
Ok(r)
}
/// Create a request that may return file descriptors, and also check for an unexpected
/// termination of the child process.
#[instrument(skip(args))]
async fn impl_request_with_fds<
T: serde::de::DeserializeOwned + Send + 'static,
F: FromReplyFds,
>(
&self,
method: &str,
args: impl IntoIterator<Item = impl Into<serde_json::Value>>,
) -> Result<(T, F)> {
let req = Self::impl_request_raw(Arc::clone(&self.sockfd), Request::new(method, args));
let mut childwait = self.childwait.lock().await;
tokio::select! {
r = req => { r }
r = childwait.as_mut() => {
let r = r.map_err(|e| Error::Other(e.to_string().into()))??;
let stderr = String::from_utf8_lossy(&r.stderr);
Err(Error::Other(format!("skopeo proxy unexpectedly exited during request method {}: {}\n{}", method, r.status, stderr).into()))
}
}
}
/// A synchronous invocation which does not return any file descriptors.
async fn impl_request<T: serde::de::DeserializeOwned + Send + 'static>(
&self,
method: &str,
args: impl IntoIterator<Item = impl Into<serde_json::Value>>,
) -> Result<T> {
let (r, ()) = self.impl_request_with_fds(method, args).await?;
Ok(r)
}
#[instrument]
async fn finish_pipe(&self, pipeid: PipeId) -> Result<()> {
tracing::debug!("closing pipe");
let (r, ()) = self
.impl_request_with_fds("FinishPipe", [pipeid.0.get()])
.await?;
Ok(r)
}
/// Open an image for fetching, using a string reference.
#[instrument]
pub async fn open_image(&self, imgref: &str) -> Result<OpenedImage> {
tracing::debug!("opening image");
let imgid = self.impl_request("OpenImage", [imgref]).await?;
Ok(OpenedImage(imgid))
}
/// Open an image for fetching, using a structured [`ImageReference`].
#[instrument]
pub async fn open_image_ref(&self, imgref: &ImageReference) -> Result<OpenedImage> {
self.open_image(&imgref.to_string()).await
}
/// Open an image for fetching if it exists, using a string reference.
/// Returns `Ok(None)` if the image does not exist.
#[instrument]
pub async fn open_image_optional(&self, imgref: &str) -> Result<Option<OpenedImage>> {
tracing::debug!("opening image");
let imgid = self.impl_request("OpenImageOptional", [imgref]).await?;
if imgid == 0 {
Ok(None)
} else {
Ok(Some(OpenedImage(imgid)))
}
}
/// Open an image for fetching if it exists, using a structured [`ImageReference`].
/// Returns `Ok(None)` if the image does not exist.
#[instrument]
pub async fn open_image_optional_ref(
&self,
imgref: &ImageReference,
) -> Result<Option<OpenedImage>> {
self.open_image_optional(&imgref.to_string()).await
}
#[instrument]
pub async fn close_image(&self, img: &OpenedImage) -> Result<()> {
self.impl_request("CloseImage", [img.0]).await
}
async fn read_finish_pipe(&self, pipe: FinishPipe) -> Result<Vec<u8>> {
let fd = tokio::fs::File::from_std(std::fs::File::from(pipe.datafd));
let mut fd = tokio::io::BufReader::new(fd);
let mut r = Vec::new();
let reader = fd.read_to_end(&mut r);
let (nbytes, finish) = tokio::join!(reader, self.finish_pipe(pipe.pipeid));
finish?;
assert_eq!(nbytes?, r.len());
Ok(r)
}
/// Fetch the manifest as raw bytes, converted to OCI if necessary.
/// The original digest of the unconverted manifest is also returned.
/// For more information on OCI manifests, see <https://github.com/opencontainers/image-spec/blob/main/manifest.md>
pub async fn fetch_manifest_raw_oci(&self, img: &OpenedImage) -> Result<(String, Vec<u8>)> {
let (digest, pipefd) = self.impl_request_with_fds("GetManifest", [img.0]).await?;
Ok((digest, self.read_finish_pipe(pipefd).await?))
}
/// Fetch the manifest.
/// For more information on OCI manifests, see <https://github.com/opencontainers/image-spec/blob/main/manifest.md>
pub async fn fetch_manifest(
&self,
img: &OpenedImage,
) -> Result<(String, oci_spec::image::ImageManifest)> {
let (digest, raw) = self.fetch_manifest_raw_oci(img).await?;
let manifest = serde_json::from_slice(&raw)?;
Ok((digest, manifest))
}
/// Fetch the config.
/// For more information on OCI config, see <https://github.com/opencontainers/image-spec/blob/main/config.md>
pub async fn fetch_config_raw(&self, img: &OpenedImage) -> Result<Vec<u8>> {
let ((), pipe) = self.impl_request_with_fds("GetFullConfig", [img.0]).await?;
self.read_finish_pipe(pipe).await
}
/// Fetch the config.
/// For more information on OCI config, see <https://github.com/opencontainers/image-spec/blob/main/config.md>
pub async fn fetch_config(
&self,
img: &OpenedImage,
) -> Result<oci_spec::image::ImageConfiguration> {
let raw = self.fetch_config_raw(img).await?;
serde_json::from_slice(&raw).map_err(Into::into)
}
/// Fetch a blob identified by e.g. `sha256:<digest>`.
/// <https://github.com/opencontainers/image-spec/blob/main/descriptor.md>
///
/// The requested size and digest are verified (by the proxy process).
///
/// Note that because of the implementation details of this function, you should
/// [`futures::join!`] the returned futures instead of polling one after the other. The
/// secondary "driver" future will only return once everything has been read from
/// the reader future.
#[instrument]
pub async fn get_blob(
&self,
img: &OpenedImage,
digest: &Digest,
size: u64,
) -> Result<(
impl AsyncBufRead + Send + Unpin,
impl Future<Output = Result<()>> + Unpin + '_,
)> {
// For previous discussion on digest/size verification, see
// https://github.com/cgwalters/container-image-proxy/issues/1#issuecomment-926712009
tracing::debug!("fetching blob");
let args: Vec<serde_json::Value> =
vec![img.0.into(), digest.to_string().into(), size.into()];
// Note that size may be -1 here if e.g. the remote registry doesn't give a Content-Length
// for example.
// We have always validated the size later (in FinishPipe) so out of conservatism we
// just ignore the size here.
let (_bloblen, pipe): (serde_json::Number, FinishPipe) =
self.impl_request_with_fds("GetBlob", args).await?;
let fd = tokio::fs::File::from_std(std::fs::File::from(pipe.datafd));
let fd = tokio::io::BufReader::new(fd);
let finish = Box::pin(self.finish_pipe(pipe.pipeid));
Ok((fd, finish))
}
async fn read_blob_error(fd: OwnedFd) -> std::result::Result<(), GetBlobError> {
let fd = tokio::fs::File::from_std(std::fs::File::from(fd));
let mut errfd = tokio::io::BufReader::new(fd);
let mut buf = Vec::new();
errfd
.read_to_end(&mut buf)
.await
.map_err(|e| GetBlobError::Other(e.to_string().into_boxed_str()))?;
if buf.is_empty() {
return Ok(());
}
#[derive(Deserialize)]
struct RemoteError {
code: String,
message: String,
}
let e: RemoteError = serde_json::from_slice(&buf)
.map_err(|e| GetBlobError::Other(e.to_string().into_boxed_str()))?;
match e.code.as_str() {
// Actually this is OK
"EPIPE" => Ok(()),
"retryable" => Err(GetBlobError::Retryable(e.message.into_boxed_str())),
_ => Err(GetBlobError::Other(e.message.into_boxed_str())),
}
}
/// Fetch a blob identified by e.g. `sha256:<digest>`; does not perform
/// any verification that the blob matches the digest. The size of the
/// blob (if available) and a pipe file descriptor are returned.
#[instrument]
pub async fn get_raw_blob(
&self,
img: &OpenedImage,
digest: &Digest,
) -> Result<(
Option<u64>,
tokio::fs::File,
impl Future<Output = std::result::Result<(), GetBlobError>> + Unpin + '_,
)> {
tracing::debug!("fetching blob");
let args: Vec<serde_json::Value> = vec![img.0.into(), digest.to_string().into()];
let (bloblen, fds): (i64, DualFds) = self.impl_request_with_fds("GetRawBlob", args).await?;
// See the GetBlob case, we have a best-effort attempt to return the size, but it might not be known
let bloblen = u64::try_from(bloblen).ok();
let fd = tokio::fs::File::from_std(std::fs::File::from(fds.datafd));
let err = Self::read_blob_error(fds.errfd).boxed();
Ok((bloblen, fd, err))
}
/// Fetch a descriptor. The requested size and digest are verified (by the proxy process).
#[instrument]
pub async fn get_descriptor(
&self,
img: &OpenedImage,
descriptor: &Descriptor,
) -> Result<(
impl AsyncBufRead + Send + Unpin,
impl Future<Output = Result<()>> + Unpin + '_,
)> {
self.get_blob(img, descriptor.digest(), descriptor.size())
.await
}
///Returns data that can be used to find the "diffid" corresponding to a particular layer.
#[instrument]
pub async fn get_layer_info(
&self,
img: &OpenedImage,
) -> Result<Option<Vec<ConvertedLayerInfo>>> {
tracing::debug!("Getting layer info");
if layer_info_piped_proto_version().matches(&self.protover) {
let ((), pipe) = self
.impl_request_with_fds("GetLayerInfoPiped", [img.0])
.await?;
let buf = self.read_finish_pipe(pipe).await?;
return Ok(Some(serde_json::from_slice(&buf)?));
}
if !layer_info_proto_version().matches(&self.protover) {
return Ok(None);
}
let layers = self.impl_request("GetLayerInfo", [img.0]).await?;
Ok(Some(layers))
}
/// Close the connection and wait for the child process to exit successfully.
#[instrument]
pub async fn finalize(self) -> Result<()> {
let _ = &self;
let req = Request::new_bare("Shutdown");
let sendbuf = serde_json::to_vec(&req)?;
// SAFETY: Only panics if a worker thread already panic'd
let sockfd = Arc::try_unwrap(self.sockfd).unwrap().into_inner().unwrap();
rustix::net::send(sockfd, &sendbuf, rustix::net::SendFlags::empty())?;
drop(sendbuf);
tracing::debug!("sent shutdown request");
let mut childwait = self.childwait.lock().await;
let output = childwait
.as_mut()
.await
.map_err(|e| Error::new_other(e.to_string()))??;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(Error::RequestReturned(
format!("proxy failed: {}\n{}", output.status, stderr).into(),
));
}
tracing::debug!("proxy exited successfully");
Ok(())
}
}
#[cfg(test)]
mod tests {
use std::io::{BufWriter, Seek, Write};
use std::os::fd::{AsRawFd, OwnedFd};
use super::*;
use cap_std_ext::cap_std::fs::Dir;
use rustix::fs::{memfd_create, MemfdFlags};
/// Check if we have skopeo
fn check_skopeo() -> bool {
static HAVE_SKOPEO: OnceLock<bool> = OnceLock::new();
*HAVE_SKOPEO.get_or_init(|| {
Command::new("skopeo")
.arg("--help")
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.is_ok()
})
}
fn validate(c: Command, contains: &[&str], not_contains: &[&str]) {
// Format via debug, because
// https://doc.rust-lang.org/std/process/struct.Command.html#method.get_args
// is experimental
let d = format!("{:?}", c);
for c in contains {
assert!(d.contains(c), "{} missing {}", d, c);
}
for c in not_contains {
assert!(!d.contains(c), "{} should not contain {}", d, c);
}
}
#[test]
fn proxy_configs() {
let tmpd = &cap_tempfile::tempdir(cap_std::ambient_authority()).unwrap();
let c = Command::try_from(ImageProxyConfig::default()).unwrap();
validate(
c,
&["experimental-image-proxy"],
&["--no-creds", "--tls-verify", "--authfile"],
);
let c = Command::try_from(ImageProxyConfig {
authfile: Some(PathBuf::from("/path/to/authfile")),
..Default::default()
})
.unwrap();
validate(c, &[r"--authfile", "/path/to/authfile"], &[]);
let decryption_key_path = "/path/to/decryption_key";
let c = Command::try_from(ImageProxyConfig {
decryption_keys: Some(vec![decryption_key_path.to_string()]),
..Default::default()
})
.unwrap();
validate(c, &[r"--decryption-key", "/path/to/decryption_key"], &[]);
let c = Command::try_from(ImageProxyConfig {
certificate_directory: Some(PathBuf::from("/path/to/certs")),
..Default::default()
})
.unwrap();
validate(c, &[r"--cert-dir", "/path/to/certs"], &[]);
let c = Command::try_from(ImageProxyConfig {
insecure_skip_tls_verification: Some(true),
..Default::default()
})
.unwrap();
validate(c, &[r"--tls-verify=false"], &[]);
let c = Command::try_from(ImageProxyConfig {
insecure_policy: Some(true),
..Default::default()
})
.unwrap();
validate(c, &[r"--insecure-policy"], &[]);
let mut tmpf = cap_tempfile::TempFile::new_anonymous(tmpd).unwrap();
tmpf.write_all(r#"{ "auths": {} "#.as_bytes()).unwrap();
tmpf.seek(std::io::SeekFrom::Start(0)).unwrap();
let c = Command::try_from(ImageProxyConfig {
auth_data: Some(tmpf.into_std()),
..Default::default()
})
.unwrap();
validate(c, &["--authfile", "/proc/self/fd/100"], &[]);
// Test user-agent-prefix - only validate if supported
let c = Command::try_from(ImageProxyConfig {
user_agent_prefix: Some("bootc/1.0".to_string()),
..Default::default()
})
.unwrap();
if supports_user_agent_prefix() {
validate(c, &["--user-agent-prefix", "bootc/1.0"], &[]);
} else {
validate(c, &[], &["--user-agent-prefix"]);
}
}
#[tokio::test]
async fn skopeo_not_found() {
let mut config = ImageProxyConfig {
..ImageProxyConfig::default()
};
config.skopeo_cmd = Some(Command::new("no-skopeo"));
match ImageProxy::new_with_config(config).await {
Ok(_) => panic!("Expected an error"),
Err(ref e @ Error::SkopeoSpawnError(ref inner)) => {
assert_eq!(inner.kind(), std::io::ErrorKind::NotFound);
// Just to double check
assert!(e
.to_string()
.contains("skopeo spawn error: No such file or directory"));
}
Err(e) => panic!("Unexpected error {e}"),
}
}
#[tokio::test]
async fn test_proxy_send_sync() {
fn assert_send_sync(_x: impl Send + Sync) {}
let Ok(proxy) = ImageProxy::new().await else {
// doesn't matter: we only actually care to test if this compiles
return;
};
assert_send_sync(&proxy);
assert_send_sync(proxy);
let opened = OpenedImage(0);
assert_send_sync(&opened);
assert_send_sync(opened);
}
fn generate_err_fd(v: serde_json::Value) -> Result<OwnedFd> {
let tmp = Dir::open_ambient_dir("/tmp", cap_std::ambient_authority())?;
let mut tf = cap_tempfile::TempFile::new_anonymous(&tmp).map(BufWriter::new)?;
serde_json::to_writer(&mut tf, &v)?;
let mut tf = tf.into_inner().map_err(|e| e.into_error())?;
tf.seek(std::io::SeekFrom::Start(0))?;
let r = tf.into_std().into();
Ok(r)
}
#[tokio::test]
async fn test_read_blob_error_retryable() -> Result<()> {
let retryable = serde_json::json!({
"code": "retryable",
"message": "foo",
});
let retryable = generate_err_fd(retryable)?;
let err = ImageProxy::read_blob_error(retryable).boxed();
let e = err.await.unwrap_err();
match e {
GetBlobError::Retryable(s) => assert_eq!(s.as_ref(), "foo"),