1use crate::crd::OAuth2ClientImageStatus;
2
3use kanidm_proto::internal::{ImageType, ImageValue};
4use kaniop_k8s_util::error::{Error, Result};
5use sha2::{Digest, Sha256};
6use std::time::Duration;
7
8const MAX_IMAGE_SIZE: u64 = 256 * 1024;
9const HTTP_TIMEOUT: Duration = Duration::from_secs(30);
10const HTTP_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
11
12pub struct ImageHeaders {
13 pub etag: Option<String>,
14 pub last_modified: Option<String>,
15 pub content_length: Option<u64>,
16 pub content_type: Option<String>,
17}
18
19pub struct DownloadedImage {
20 pub image_value: ImageValue,
21 pub headers: ImageHeaders,
22 pub content_hash: String,
23}
24
25pub async fn fetch_headers(url: &str) -> Result<ImageHeaders> {
26 let client = reqwest::Client::builder()
27 .timeout(HTTP_TIMEOUT)
28 .connect_timeout(HTTP_CONNECT_TIMEOUT)
29 .build()
30 .map_err(|e| Error::HttpError("failed to build HTTP client".to_string(), e))?;
31
32 let response = client
33 .head(url)
34 .send()
35 .await
36 .map_err(|e| Error::HttpError(format!("HEAD request failed for {url}"), e))?;
37
38 let etag = response
39 .headers()
40 .get(reqwest::header::ETAG)
41 .and_then(|v| v.to_str().ok())
42 .map(|s| s.to_string());
43
44 let last_modified = response
45 .headers()
46 .get(reqwest::header::LAST_MODIFIED)
47 .and_then(|v| v.to_str().ok())
48 .map(|s| s.to_string());
49
50 let content_length = response
51 .headers()
52 .get(reqwest::header::CONTENT_LENGTH)
53 .and_then(|v| v.to_str().ok())
54 .and_then(|s| s.parse::<u64>().ok());
55
56 let content_type = response
57 .headers()
58 .get(reqwest::header::CONTENT_TYPE)
59 .and_then(|v| v.to_str().ok())
60 .map(|s| s.to_string());
61
62 Ok(ImageHeaders {
63 etag,
64 last_modified,
65 content_length,
66 content_type,
67 })
68}
69
70pub async fn download_image(url: &str) -> Result<DownloadedImage> {
71 let client = reqwest::Client::builder()
72 .timeout(HTTP_TIMEOUT)
73 .connect_timeout(HTTP_CONNECT_TIMEOUT)
74 .build()
75 .map_err(|e| Error::HttpError("failed to build HTTP client".to_string(), e))?;
76
77 let response = client
78 .get(url)
79 .send()
80 .await
81 .map_err(|e| Error::HttpError(format!("GET request failed for {url}"), e))?;
82
83 let content_length = response
84 .headers()
85 .get(reqwest::header::CONTENT_LENGTH)
86 .and_then(|v| v.to_str().ok())
87 .and_then(|s| s.parse::<u64>().ok());
88
89 if let Some(len) = content_length {
90 if len > MAX_IMAGE_SIZE {
91 return Err(Error::ImageError(format!(
92 "image size {len} exceeds maximum allowed size {MAX_IMAGE_SIZE} bytes"
93 )));
94 }
95 }
96
97 let content_type = response
98 .headers()
99 .get(reqwest::header::CONTENT_TYPE)
100 .and_then(|v| v.to_str().ok())
101 .map(|s| s.to_string());
102
103 let image_type = match &content_type {
104 Some(ct) => ImageType::try_from_content_type(ct)
105 .map_err(|e| Error::ImageError(format!("unsupported content type: {e}")))?,
106 None => return Err(Error::ImageError("missing Content-Type header".to_string())),
107 };
108
109 let bytes = response
110 .bytes()
111 .await
112 .map_err(|e| Error::HttpError(format!("failed to read response body from {url}"), e))?;
113
114 if bytes.len() as u64 > MAX_IMAGE_SIZE {
115 return Err(Error::ImageError(format!(
116 "downloaded image size {} exceeds maximum allowed size {MAX_IMAGE_SIZE} bytes",
117 bytes.len()
118 )));
119 }
120
121 let mut hasher = Sha256::new();
122 hasher.update(&bytes);
123 let content_hash = format!("{:x}", hasher.finalize());
124
125 let etag = None;
126 let last_modified = None;
127
128 let filename = url
129 .rsplit('/')
130 .next()
131 .unwrap_or("image")
132 .split('?')
133 .next()
134 .unwrap_or("image")
135 .to_string();
136
137 let image_value = ImageValue::new(filename, image_type, bytes.to_vec());
138
139 Ok(DownloadedImage {
140 image_value,
141 headers: ImageHeaders {
142 etag,
143 last_modified,
144 content_length: Some(bytes.len() as u64),
145 content_type,
146 },
147 content_hash,
148 })
149}
150
151pub fn needs_update(spec_url: &str, status: &Option<OAuth2ClientImageStatus>) -> bool {
152 match status {
153 None => true,
154 Some(s) => s.url != spec_url,
155 }
156}
157
158pub fn headers_changed(current: &ImageHeaders, cached: &OAuth2ClientImageStatus) -> bool {
159 if current.etag.is_some() && cached.etag.is_some() {
160 return current.etag != cached.etag;
161 }
162
163 if current.last_modified.is_some() && cached.last_modified.is_some() {
164 return current.last_modified != cached.last_modified;
165 }
166
167 if current.content_length.is_some() && cached.content_length.is_some() {
168 return current.content_length != cached.content_length;
169 }
170
171 false
172}