m/cup
1
0
mirror of https://github.com/sergi0g/cup.git synced 2025-11-18 01:43:41 -05:00

Add support for private registries/images

This commit is contained in:
Sergio
2024-08-31 18:43:30 +03:00
parent 90239f83e9
commit 2549ed7801
10 changed files with 143 additions and 88 deletions

View File

@@ -1,8 +1,10 @@
use std::{collections::{HashMap, HashSet}, sync::Mutex};
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
use json::JsonValue;
use crate::{docker::get_images_from_docker_daemon, image::Image, registry::{check_auth, get_token, get_latest_digests}, utils::unsplit_image};
#[cfg(feature = "cli")]
use crate::docker::get_image_from_docker_daemon;
#[cfg(feature = "cli")]
@@ -23,7 +25,7 @@ where
}
}
pub async fn get_all_updates(socket: Option<String>) -> Vec<(String, Option<bool>)> {
pub async fn get_all_updates(socket: Option<String>, config: &JsonValue) -> Vec<(String, Option<bool>)> {
let image_map_mutex: Mutex<HashMap<String, &Option<String>>> = Mutex::new(HashMap::new());
let local_images = get_images_from_docker_daemon(socket).await;
local_images.par_iter().for_each(|image| {
@@ -42,12 +44,13 @@ pub async fn get_all_updates(socket: Option<String>) -> Vec<(String, Option<bool
.par_iter()
.filter(|image| &image.registry == registry)
.collect();
let mut latest_images = match check_auth(registry) {
let credentials = config["authentication"][registry].clone().take_string().or(None);
let mut latest_images = match check_auth(registry, config) {
Some(auth_url) => {
let token = get_token(images.clone(), &auth_url);
get_latest_digests(images, Some(&token))
let token = get_token(images.clone(), &auth_url, &credentials);
get_latest_digests(images, Some(&token), config)
}
None => get_latest_digests(images, None),
None => get_latest_digests(images, None, config),
};
remote_images.append(&mut latest_images);
}
@@ -67,15 +70,16 @@ pub async fn get_all_updates(socket: Option<String>) -> Vec<(String, Option<bool
}
#[cfg(feature = "cli")]
pub async fn get_update(image: &str, socket: Option<String>) -> Option<bool> {
pub async fn get_update(image: &str, socket: Option<String>, config: &JsonValue) -> Option<bool> {
let local_image = get_image_from_docker_daemon(socket, image).await;
let token = match check_auth(&local_image.registry) {
Some(auth_url) => get_token(vec![&local_image], &auth_url),
let credentials = config["authentication"][&local_image.registry].clone().take_string().or(None);
let token = match check_auth(&local_image.registry, config) {
Some(auth_url) => get_token(vec![&local_image], &auth_url, &credentials),
None => String::new(),
};
let remote_image = match token.as_str() {
"" => get_latest_digest(&local_image, None),
_ => get_latest_digest(&local_image, Some(&token)),
"" => get_latest_digest(&local_image, None, config),
_ => get_latest_digest(&local_image, Some(&token), config),
};
match &remote_image.digest {
Some(d) => Some(d != &local_image.digest.unwrap()),

View File

@@ -69,7 +69,7 @@ async fn main() {
#[cfg(feature = "cli")]
Some(Commands::Check { image, icons, raw }) => match image {
Some(name) => {
let has_update = get_update(name, cli.socket).await;
let has_update = get_update(name, cli.socket, &config).await;
match raw {
true => print_raw_update(name, &has_update),
false => print_update(name, &has_update),
@@ -77,10 +77,10 @@ async fn main() {
}
None => {
match raw {
true => print_raw_updates(&get_all_updates(cli.socket).await),
true => print_raw_updates(&get_all_updates(cli.socket, &config).await),
false => {
let spinner = Spinner::new();
let updates = get_all_updates(cli.socket).await;
let updates = get_all_updates(cli.socket, &config).await;
spinner.succeed();
print_updates(&updates, icons);
}

View File

@@ -6,24 +6,26 @@ use ureq::Error;
use http_auth::parse_challenges;
use crate::{error, image::Image};
use crate::{error, image::Image, warn};
pub fn check_auth(registry: &str) -> Option<String> {
let response = ureq::get(&format!("https://{}/v2/", registry)).call();
pub fn check_auth(registry: &str, config: &JsonValue) -> Option<String> {
let protocol = if config["insecure_registries"].contains(registry) { "http" } else { "https" };
let response = ureq::get(&format!("{}://{}/v2/", protocol, registry)).call();
match response {
Ok(_) => None,
Err(Error::Status(401, response)) => match response.header("www-authenticate") {
Some(challenge) => Some(parse_www_authenticate(challenge)),
None => error!("Server returned invalid response!"),
None => error!("Unauthorized to access registry {} and no way to authenticate was provided", registry),
},
Err(e) => error!("{}", e),
}
}
pub fn get_latest_digest(image: &Image, token: Option<&String>) -> Image {
pub fn get_latest_digest(image: &Image, token: Option<&String>, config: &JsonValue) -> Image {
let protocol = if config["insecure_registries"].contains(json::JsonValue::from(image.registry.clone())) { "http" } else { "https" };
let mut request = ureq::head(&format!(
"https://{}/v2/{}/manifests/{}",
&image.registry, &image.repository, &image.tag
"{}://{}/v2/{}/manifests/{}",
protocol, &image.registry, &image.repository, &image.tag
));
if let Some(t) = token {
request = request.set("Authorization", &format!("Bearer {}", t));
@@ -35,14 +37,17 @@ pub fn get_latest_digest(image: &Image, token: Option<&String>) -> Image {
Ok(response) => response,
Err(Error::Status(401, response)) => {
if token.is_some() {
error!("Failed to authenticate to registry {} with given token!\n{}", &image.registry, token.unwrap())
warn!("Failed to authenticate to registry {} with given token!\n{}", &image.registry, token.unwrap());
return Image { digest: None, ..image.clone() }
} else {
return get_latest_digest(
image,
Some(&get_token(
vec![image],
&parse_www_authenticate(response.header("www-authenticate").unwrap()),
&None // I think?
)),
config
);
}
}
@@ -63,10 +68,10 @@ pub fn get_latest_digest(image: &Image, token: Option<&String>) -> Image {
}
}
pub fn get_latest_digests(images: Vec<&Image>, token: Option<&String>) -> Vec<Image> {
pub fn get_latest_digests(images: Vec<&Image>, token: Option<&String>, config: &JsonValue) -> Vec<Image> {
let result: Mutex<Vec<Image>> = Mutex::new(Vec::new());
images.par_iter().for_each(|&image| {
let digest = get_latest_digest(image, token).digest;
let digest = get_latest_digest(image, token, config).digest;
result.lock().unwrap().push(Image {
digest,
..image.clone()
@@ -76,14 +81,17 @@ pub fn get_latest_digests(images: Vec<&Image>, token: Option<&String>) -> Vec<Im
r
}
pub fn get_token(images: Vec<&Image>, auth_url: &str) -> String {
pub fn get_token(images: Vec<&Image>, auth_url: &str, credentials: &Option<String>) -> String {
let mut final_url = auth_url.to_owned();
for image in images {
final_url = format!("{}&scope=repository:{}:pull", final_url, image.repository);
}
let raw_response = match ureq::get(&final_url)
.set("Accept", "application/vnd.oci.image.index.v1+json") // Seems to be unnecesarry. Will probably remove in the future
.call()
let mut base_request = ureq::get(&final_url).set("Accept", "application/vnd.oci.image.index.v1+json"); // Seems to be unnecesarry. Will probably remove in the future
base_request = match credentials {
Some(creds) => base_request.set("Authorization", &format!("Basic {}", creds)),
None => base_request
};
let raw_response = match base_request.call()
{
Ok(response) => match response.into_string() {
Ok(res) => res,
@@ -118,6 +126,6 @@ fn parse_www_authenticate(www_auth: &str) -> String {
error!("Unsupported scheme {}", &challenge.scheme)
}
} else {
error!("No challenge provided");
error!("No challenge provided by the server");
}
}

View File

@@ -94,7 +94,7 @@ impl ServerData {
s
}
async fn refresh(&mut self) {
let updates = sort_update_vec(&get_all_updates(self.socket.clone()).await);
let updates = sort_update_vec(&get_all_updates(self.socket.clone(), &self.config["authentication"]).await);
self.raw_updates = updates;
let template = liquid::ParserBuilder::with_stdlib()
.build()

View File

@@ -13,6 +13,14 @@ macro_rules! error {
})
}
// A small macro to print in yellow as a warning
#[macro_export]
macro_rules! warn {
($($arg:tt)*) => ({
eprintln!("\x1b[93m{}\x1b[0m", format!($($arg)*));
})
}
/// Takes an image and splits it into registry, repository and tag. For example ghcr.io/sergi0g/cup:latest becomes ['ghcr.io', 'sergi0g/cup', 'latest'].
pub fn split_image(image: &str) -> (String, String, String) {
static RE: Lazy<Regex> = Lazy::new(|| {
@@ -23,15 +31,16 @@ pub fn split_image(image: &str) -> (String, String, String) {
});
match RE.captures(image) {
Some(c) => {
return (
match c.name("registry") {
let registry = match c.name("registry") {
Some(registry) => registry.as_str().to_owned(),
None => String::from("registry-1.docker.io"),
},
};
return (
registry.clone(),
match c.name("repository") {
Some(repository) => {
let repo = repository.as_str().to_owned();
if !repo.contains('/') {
if !repo.contains('/') && registry == "registry-1.docker.io" {
format!("library/{}", repo)
} else {
repo