use super::oci::ImageConfig;
use bytes::Bytes;
use http_body_util::{BodyExt, Full};
use hyper::body::Incoming;
use hyper::{Request, Response, StatusCode};
use hyper_util::rt::TokioIo;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::io;
use std::path::Path;
use std::sync::{Arc, OnceLock};
use std::time::Duration;
use tokio::io::AsyncWriteExt;
pub const MAX_MANIFEST: u64 = 4 << 20;
pub const MAX_CONFIG: u64 = 8 << 20;
pub const MAX_LAYER: u64 = 2 << 30;
const MAX_TOKEN: u64 = 256 << 10;
const IO_TIMEOUT: Duration = Duration::from_secs(60);
pub const PULL_DEADLINE: Duration = Duration::from_secs(600);
const ACCEPT: &str = "application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json";
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Reference {
pub registry: String,
pub repo: String,
pub reference: String,
}
fn bad(msg: impl Into<String>) -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, msg.into())
}
pub fn digest_hex(d: &str) -> io::Result<&str> {
match d.strip_prefix("sha256:") {
Some(h) if h.len() == 64 && h.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) => {
Ok(h)
}
_ => Err(bad(format!("unsupported digest {d:?}"))),
}
}
pub fn sha256_hex(data: &[u8]) -> String {
hex(ring::digest::digest(&ring::digest::SHA256, data).as_ref())
}
fn hex(b: &[u8]) -> String {
b.iter().map(|x| format!("{x:02x}")).collect()
}
pub fn parse_reference(image: &str) -> io::Result<Reference> {
if image.is_empty() || image.len() > 512 || image.bytes().any(|b| !b.is_ascii_graphic()) {
return Err(bad(format!("invalid image reference {image:?}")));
}
let (name, reference) = crate::docker::split_image(image);
let (registry, repo) = match name.split_once('/') {
Some((h, rest)) if h.contains('.') || h.contains(':') || h == "localhost" => {
(h.to_string(), rest.to_string())
}
_ => ("docker.io".to_string(), name.to_string()),
};
let registry = match registry.as_str() {
"docker.io" | "index.docker.io" => "registry-1.docker.io".to_string(),
_ => registry,
};
let repo = if registry == "registry-1.docker.io" && !repo.contains('/') {
format!("library/{repo}")
} else {
repo
};
let repo_ok = !repo.is_empty()
&& repo.split('/').all(|c| {
!c.is_empty()
&& c.bytes().all(|b| {
b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'.' | b'_' | b'-')
})
&& c != "."
&& c != ".."
});
let host_ok = registry
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b':'));
let ref_ok = if reference.contains(':') {
digest_hex(reference).is_ok()
} else {
!reference.is_empty()
&& reference.len() <= 128
&& reference
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
};
if !repo_ok || !host_ok || !ref_ok {
return Err(bad(format!("invalid image reference {image:?}")));
}
Ok(Reference {
registry,
repo,
reference: reference.to_string(),
})
}
#[derive(Clone, Debug, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Descriptor {
#[serde(default)]
pub media_type: String,
pub digest: String,
#[serde(default)]
pub size: u64,
#[serde(default)]
pub platform: Option<Platform>,
}
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct Platform {
#[serde(default)]
pub architecture: String,
#[serde(default)]
pub os: String,
#[serde(default)]
pub variant: Option<String>,
}
#[derive(Debug, PartialEq)]
pub enum Manifest {
Index(Vec<Descriptor>),
Image {
config: Descriptor,
layers: Vec<Descriptor>,
},
}
pub fn parse_manifest(content_type: &str, body: &[u8]) -> io::Result<Manifest> {
let v: Value = serde_json::from_slice(body).map_err(|e| bad(format!("manifest: {e}")))?;
if v["schemaVersion"].as_i64() != Some(2) {
return Err(bad("only schemaVersion 2 manifests are supported"));
}
let mt = v["mediaType"]
.as_str()
.unwrap_or(content_type)
.split(';')
.next()
.unwrap_or_default()
.trim()
.to_string();
let index = mt.ends_with("manifest.list.v2+json")
|| mt.ends_with("image.index.v1+json")
|| (mt.is_empty() || mt == "application/json") && v["manifests"].is_array();
if index {
let m: Vec<Descriptor> = serde_json::from_value(v["manifests"].clone())
.map_err(|e| bad(format!("index: {e}")))?;
return Ok(Manifest::Index(m));
}
let image = mt.ends_with("distribution.manifest.v2+json")
|| mt.ends_with("image.manifest.v1+json")
|| (mt.is_empty() || mt == "application/json") && v["layers"].is_array();
if !image {
return Err(bad(format!("unsupported manifest type {mt:?}")));
}
let config: Descriptor =
serde_json::from_value(v["config"].clone()).map_err(|e| bad(format!("config: {e}")))?;
let layers: Vec<Descriptor> =
serde_json::from_value(v["layers"].clone()).map_err(|e| bad(format!("layers: {e}")))?;
digest_hex(&config.digest)?;
if layers.is_empty() || layers.len() > 127 {
return Err(bad("manifest has a bad number of layers"));
}
for l in &layers {
digest_hex(&l.digest)?;
if l.media_type.contains("zstd") || l.media_type.contains("foreign") {
return Err(bad(format!("unsupported layer type {}", l.media_type)));
}
if l.size > MAX_LAYER {
return Err(bad("layer too large"));
}
}
Ok(Manifest::Image { config, layers })
}
pub fn host_arch() -> &'static str {
match std::env::consts::ARCH {
"x86_64" => "amd64",
"aarch64" => "arm64",
"arm" => "arm",
other => other,
}
}
pub fn pick_platform<'a>(list: &'a [Descriptor], arch: &str) -> Option<&'a Descriptor> {
let matches = |d: &&Descriptor| {
d.platform
.as_ref()
.is_some_and(|p| p.os == "linux" && p.architecture == arch)
};
list.iter()
.filter(matches)
.find(|d| {
arch != "arm64"
|| d.platform
.as_ref()
.and_then(|p| p.variant.as_deref())
.is_none_or(|v| v == "v8")
})
.or_else(|| list.iter().find(matches))
}
pub fn parse_challenge(h: &str) -> Option<(String, Option<String>, Option<String>)> {
let rest = h
.trim()
.strip_prefix("Bearer ")
.or_else(|| h.trim().strip_prefix("bearer "))?;
let (mut realm, mut service, mut scope) = (None, None, None);
let mut s = rest.trim();
while !s.is_empty() {
let (k, after) = s.split_once('=')?;
let after = after.trim_start();
let (val, next) = if let Some(q) = after.strip_prefix('"') {
let end = q.find('"')?;
(&q[..end], &q[end + 1..])
} else {
let end = after.find(',').unwrap_or(after.len());
(&after[..end], &after[end..])
};
match k.trim().to_ascii_lowercase().as_str() {
"realm" => realm = Some(val.to_string()),
"service" => service = Some(val.to_string()),
"scope" => scope = Some(val.to_string()),
_ => {}
}
s = next.trim_start_matches([',', ' ']);
}
Some((realm?, service, scope))
}
fn enc(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for b in s.bytes() {
if b.is_ascii_alphanumeric() || b"-_.~".contains(&b) {
out.push(b as char);
} else {
out.push_str(&format!("%{b:02X}"));
}
}
out
}
#[derive(Clone, Debug, PartialEq)]
struct Url {
host: String,
port: u16,
path: String,
}
fn parse_url(s: &str) -> io::Result<Url> {
let rest = s
.strip_prefix("https://")
.ok_or_else(|| bad(format!("only https URLs are allowed: {s}")))?;
let (auth, path) = match rest.find('/') {
Some(i) => (&rest[..i], &rest[i..]),
None => (rest, "/"),
};
if auth.contains('@') || auth.is_empty() {
return Err(bad("bad URL authority"));
}
let (host, port) = match auth.rsplit_once(':') {
Some((h, p)) => (h, p.parse().map_err(|_| bad("bad URL port"))?),
None => (auth, 443),
};
if host.is_empty()
|| !host
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-'))
{
return Err(bad("bad URL host"));
}
if path.bytes().any(|b| !b.is_ascii_graphic()) {
return Err(bad("bad URL path"));
}
Ok(Url {
host: host.to_string(),
port,
path: path.to_string(),
})
}
fn tls_config() -> io::Result<Arc<rustls::ClientConfig>> {
static CFG: OnceLock<Arc<rustls::ClientConfig>> = OnceLock::new();
if let Some(c) = CFG.get() {
return Ok(c.clone());
}
use rustls_pki_types::CertificateDer;
use rustls_pki_types::pem::PemObject;
let mut roots = rustls::RootCertStore::empty();
let mut files: Vec<String> = std::env::var("SSL_CERT_FILE").into_iter().collect();
files.extend(
[
"/etc/ssl/certs/ca-certificates.crt",
"/etc/pki/tls/certs/ca-bundle.crt",
"/etc/ssl/cert.pem",
]
.map(String::from),
);
for f in files {
if let Ok(it) = CertificateDer::pem_file_iter(&f) {
for c in it.flatten() {
let _ = roots.add(c);
}
}
if !roots.is_empty() {
break;
}
}
if roots.is_empty() {
return Err(io::Error::other(
"no CA certificates found (set SSL_CERT_FILE)",
));
}
let mut cfg = rustls::ClientConfig::builder_with_provider(Arc::new(
rustls::crypto::ring::default_provider(),
))
.with_safe_default_protocol_versions()
.map_err(io::Error::other)?
.with_root_certificates(roots)
.with_no_client_auth();
cfg.alpn_protocols = vec![b"http/1.1".to_vec()];
let cfg = Arc::new(cfg);
let _ = CFG.set(cfg.clone());
Ok(cfg)
}
async fn send(url: &Url, headers: &[(&str, String)]) -> io::Result<Response<Incoming>> {
let cfg = tls_config()?;
let fut = async {
let tcp = tokio::net::TcpStream::connect((url.host.as_str(), url.port)).await?;
let name = rustls_pki_types::ServerName::try_from(url.host.clone())
.map_err(|_| bad("bad TLS server name"))?;
let tls = tokio_rustls::TlsConnector::from(cfg)
.connect(name, tcp)
.await?;
let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(tls))
.await
.map_err(io::Error::other)?;
tokio::spawn(async move {
let _ = conn.await;
});
let mut req = Request::get(url.path.as_str())
.header("Host", url.host.as_str())
.header("User-Agent", "krab/0.1");
for (k, v) in headers {
req = req.header(*k, v.as_str());
}
let req = req
.body(Full::new(Bytes::new()))
.map_err(io::Error::other)?;
sender.send_request(req).await.map_err(io::Error::other)
};
tokio::time::timeout(IO_TIMEOUT, fut)
.await
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "registry request timed out"))?
}
async fn get(
url: &str,
token: Option<&str>,
accept: Option<&str>,
) -> io::Result<Response<Incoming>> {
let mut cur = parse_url(url)?;
let origin = cur.host.clone();
for _ in 0..6 {
let mut h: Vec<(&str, String)> = Vec::new();
if let Some(a) = accept {
h.push(("Accept", a.to_string()));
}
if let Some(t) = token.filter(|_| cur.host == origin) {
h.push(("Authorization", format!("Bearer {t}")));
}
let resp = send(&cur, &h).await?;
if !resp.status().is_redirection() {
return Ok(resp);
}
let loc = resp
.headers()
.get("location")
.and_then(|v| v.to_str().ok())
.ok_or_else(|| bad("redirect without location"))?
.to_string();
cur = if loc.starts_with('/') {
Url { path: loc, ..cur }
} else {
parse_url(&loc)?
};
}
Err(bad("too many redirects"))
}
async fn read_limited(resp: Response<Incoming>, max: u64) -> io::Result<Vec<u8>> {
if let Some(n) = content_length(&resp)
&& n > max
{
return Err(bad("response too large"));
}
let mut body = resp.into_body();
let mut out = Vec::new();
loop {
let frame = tokio::time::timeout(IO_TIMEOUT, body.frame())
.await
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "registry read timed out"))?;
let Some(frame) = frame else { break };
if let Ok(d) = frame.map_err(io::Error::other)?.into_data() {
if out.len() as u64 + d.len() as u64 > max {
return Err(bad("response too large"));
}
out.extend_from_slice(&d);
}
}
Ok(out)
}
fn content_length(resp: &Response<Incoming>) -> Option<u64> {
resp.headers()
.get("content-length")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse().ok())
}
fn status_err(what: &str, s: StatusCode) -> io::Error {
let kind = match s {
StatusCode::NOT_FOUND => io::ErrorKind::NotFound,
StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN => io::ErrorKind::PermissionDenied,
_ => io::ErrorKind::Other,
};
io::Error::new(kind, format!("{what}: registry returned {s}"))
}
pub struct Session {
pub r: Reference,
token: Option<String>,
}
impl Session {
pub fn new(r: Reference) -> Self {
Self { r, token: None }
}
fn url(&self, kind: &str, reference: &str) -> String {
format!(
"https://{}/v2/{}/{kind}/{reference}",
self.r.registry, self.r.repo
)
}
async fn authorize(&mut self, challenge: &str) -> io::Result<()> {
let (realm, service, scope) =
parse_challenge(challenge).ok_or_else(|| bad("unsupported registry auth challenge"))?;
let scope = scope.unwrap_or_else(|| format!("repository:{}:pull", self.r.repo));
let mut url = realm.clone();
url.push(if realm.contains('?') { '&' } else { '?' });
if let Some(s) = service {
url.push_str(&format!("service={}&", enc(&s)));
}
url.push_str(&format!("scope={}", enc(&scope)));
let resp = get(&url, None, None).await?;
if !resp.status().is_success() {
return Err(status_err("token", resp.status()));
}
let body = read_limited(resp, MAX_TOKEN).await?;
let v: Value = serde_json::from_slice(&body).map_err(|_| bad("bad token response"))?;
let t = v["token"]
.as_str()
.or_else(|| v["access_token"].as_str())
.filter(|t| !t.is_empty())
.ok_or_else(|| bad("token response without token"))?;
self.token = Some(t.to_string());
Ok(())
}
async fn fetch(&mut self, url: &str, accept: Option<&str>) -> io::Result<Response<Incoming>> {
let mut retried = false;
loop {
let resp = get(url, self.token.as_deref(), accept).await?;
if resp.status() == StatusCode::UNAUTHORIZED && !retried {
let ch = resp
.headers()
.get("www-authenticate")
.and_then(|v| v.to_str().ok())
.unwrap_or_default()
.to_string();
self.authorize(&ch).await?;
retried = true;
continue;
}
if !resp.status().is_success() {
return Err(status_err(url, resp.status()));
}
return Ok(resp);
}
}
pub async fn manifest(&mut self, reference: &str) -> io::Result<(String, Manifest)> {
let url = self.url("manifests", reference);
let resp = self.fetch(&url, Some(ACCEPT)).await?;
let ct = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or_default()
.to_string();
let body = read_limited(resp, MAX_MANIFEST).await?;
let digest = format!("sha256:{}", sha256_hex(&body));
if reference.starts_with("sha256:") && digest != reference {
return Err(bad(format!("manifest digest mismatch for {reference}")));
}
Ok((digest, parse_manifest(&ct, &body)?))
}
pub async fn blob_bytes(&mut self, digest: &str, max: u64) -> io::Result<Vec<u8>> {
digest_hex(digest)?;
let resp = self.fetch(&self.url("blobs", digest), None).await?;
let body = read_limited(resp, max).await?;
if format!("sha256:{}", sha256_hex(&body)) != digest {
return Err(bad(format!("blob digest mismatch for {digest}")));
}
Ok(body)
}
pub async fn blob_to_file(&mut self, digest: &str, dst: &Path, max: u64) -> io::Result<()> {
let hex_want = digest_hex(digest)?.to_string();
if tokio::fs::metadata(dst).await.is_ok() {
return Ok(());
}
let resp = self.fetch(&self.url("blobs", digest), None).await?;
if content_length(&resp).is_some_and(|n| n > max) {
return Err(bad("layer too large"));
}
let tmp = dst.with_extension(format!("tmp{}", std::process::id()));
let mut f = tokio::fs::File::create(&tmp).await?;
let mut ctx = ring::digest::Context::new(&ring::digest::SHA256);
let mut total = 0u64;
let mut body = resp.into_body();
let res: io::Result<()> = async {
loop {
let frame = tokio::time::timeout(IO_TIMEOUT, body.frame())
.await
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "blob read timed out"))?;
let Some(frame) = frame else { break };
if let Ok(d) = frame.map_err(io::Error::other)?.into_data() {
total += d.len() as u64;
if total > max {
return Err(bad("layer too large"));
}
ctx.update(&d);
f.write_all(&d).await?;
}
}
f.flush().await?;
f.sync_all().await?;
if hex(ctx.finish().as_ref()) != hex_want {
return Err(bad(format!("blob digest mismatch for {digest}")));
}
Ok(())
}
.await;
if let Err(e) = res {
let _ = tokio::fs::remove_file(&tmp).await;
return Err(e);
}
tokio::fs::rename(&tmp, dst).await
}
}
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
pub struct ImageRecord {
pub image: String,
pub digest: String,
pub config_digest: String,
pub layers: Vec<String>,
pub config: ImageConfig,
}
pub fn image_config(blob: &[u8]) -> io::Result<ImageConfig> {
let v: Value = serde_json::from_slice(blob).map_err(|e| bad(format!("image config: {e}")))?;
let os = v["os"].as_str().unwrap_or("linux");
if os != "linux" {
return Err(bad(format!("image os {os} is not supported")));
}
if v["config"].is_null() {
return Ok(ImageConfig::default());
}
serde_json::from_value(v["config"].clone()).map_err(|e| bad(format!("image config: {e}")))
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn references() {
let r = parse_reference("nginx:alpine").unwrap();
assert_eq!(
r,
Reference {
registry: "registry-1.docker.io".into(),
repo: "library/nginx".into(),
reference: "alpine".into()
}
);
let r = parse_reference("ghcr.io/org/app@sha256:".to_string().as_str());
assert!(r.is_err());
let d = format!("sha256:{}", "a".repeat(64));
let r = parse_reference(&format!("ghcr.io/org/app@{d}")).unwrap();
assert_eq!(
(r.registry.as_str(), r.repo.as_str()),
("ghcr.io", "org/app")
);
assert_eq!(r.reference, d);
let r = parse_reference("localhost:5000/x").unwrap();
assert_eq!(
(r.registry.as_str(), r.reference.as_str()),
("localhost:5000", "latest")
);
assert_eq!(
parse_reference("bitnami/redis").unwrap().repo,
"bitnami/redis"
);
for bad in ["", "UPPER/x", "a/../b", "x:t@g", "a b", "quay.io/a//b"] {
assert!(parse_reference(bad).is_err(), "{bad}");
}
}
#[test]
fn manifest_list_picks_platform() {
let d = |c: char| format!("sha256:{}", c.to_string().repeat(64));
let body = json!({
"schemaVersion": 2,
"mediaType": "application/vnd.docker.distribution.manifest.list.v2+json",
"manifests": [
{"digest": d('a'), "mediaType": "x", "size": 1, "platform": {"architecture": "arm", "os": "linux", "variant": "v7"}},
{"digest": d('b'), "size": 1, "platform": {"architecture": "arm64", "os": "linux", "variant": "v8"}},
{"digest": d('c'), "size": 1, "platform": {"architecture": "amd64", "os": "linux"}},
{"digest": d('d'), "size": 1, "platform": {"architecture": "unknown", "os": "unknown"}}
]
});
let Manifest::Index(list) = parse_manifest("", body.to_string().as_bytes()).unwrap() else {
panic!()
};
assert_eq!(pick_platform(&list, "amd64").unwrap().digest, d('c'));
assert_eq!(pick_platform(&list, "arm64").unwrap().digest, d('b'));
assert!(pick_platform(&list, "s390x").is_none());
let oci = json!({"schemaVersion": 2, "manifests": [{"digest": d('e'), "platform": {"architecture": "amd64", "os": "linux"}}]});
assert!(matches!(
parse_manifest(
"application/vnd.oci.image.index.v1+json",
oci.to_string().as_bytes()
)
.unwrap(),
Manifest::Index(_)
));
}
#[test]
fn image_manifests() {
let d = |c: char| format!("sha256:{}", c.to_string().repeat(64));
let docker = json!({
"schemaVersion": 2,
"mediaType": "application/vnd.docker.distribution.manifest.v2+json",
"config": {"mediaType": "application/vnd.docker.container.image.v1+json", "digest": d('1'), "size": 10},
"layers": [{"mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip", "digest": d('2'), "size": 100}]
});
let Manifest::Image { config, layers } =
parse_manifest("", docker.to_string().as_bytes()).unwrap()
else {
panic!()
};
assert_eq!(config.digest, d('1'));
assert_eq!(layers[0].digest, d('2'));
let oci = json!({
"schemaVersion": 2,
"config": {"digest": d('3')},
"layers": [{"mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", "digest": d('4')}]
});
assert!(matches!(
parse_manifest(
"application/vnd.oci.image.manifest.v1+json",
oci.to_string().as_bytes()
)
.unwrap(),
Manifest::Image { .. }
));
let zstd = json!({"schemaVersion": 2, "mediaType": "application/vnd.oci.image.manifest.v1+json", "config": {"digest": d('3')}, "layers": [{"mediaType": "application/vnd.oci.image.layer.v1.tar+zstd", "digest": d('4')}]});
assert!(parse_manifest("", zstd.to_string().as_bytes()).is_err());
let evil = json!({"schemaVersion": 2, "mediaType": "application/vnd.oci.image.manifest.v1+json", "config": {"digest": "sha256:../../x"}, "layers": [{"digest": d('4')}]});
assert!(parse_manifest("", evil.to_string().as_bytes()).is_err());
assert!(parse_manifest("", br#"{"schemaVersion": 1}"#).is_err());
}
#[test]
fn challenges_and_urls() {
let (realm, service, scope) = parse_challenge(
r#"Bearer realm="https://auth.docker.io/token",service="registry.docker.io",scope="repository:library/nginx:pull""#,
)
.unwrap();
assert_eq!(realm, "https://auth.docker.io/token");
assert_eq!(service.as_deref(), Some("registry.docker.io"));
assert_eq!(scope.as_deref(), Some("repository:library/nginx:pull"));
let (realm, service, _) =
parse_challenge(r#"Bearer realm="https://ghcr.io/token",service="ghcr.io""#).unwrap();
assert_eq!(
(realm.as_str(), service.as_deref()),
("https://ghcr.io/token", Some("ghcr.io"))
);
assert!(parse_challenge("Basic realm=x").is_none());
let u = parse_url("https://r.io:5000/v2/x?y=1").unwrap();
assert_eq!(
(u.host.as_str(), u.port, u.path.as_str()),
("r.io", 5000, "/v2/x?y=1")
);
assert!(parse_url("http://r.io/").is_err());
assert!(parse_url("https://user@r.io/").is_err());
assert!(digest_hex("sha256:ABC").is_err());
}
#[test]
fn image_config_parse() {
let c = image_config(br#"{"os":"linux","config":{"Cmd":["sh"],"Env":["A=1"],"User":"1"}}"#)
.unwrap();
assert_eq!(c.cmd, Some(vec!["sh".to_string()]));
assert!(image_config(br#"{"os":"windows","config":{}}"#).is_err());
}
}