1use crate::crd::OAuth2ClientImageStatus;
2
3use kanidm_proto::internal::{ImageType, ImageValue};
4use kaniop_k8s_util::error::{Error, Result};
5use sha2::{Digest, Sha256};
6use std::sync::LazyLock;
7use std::time::Duration;
8use tracing::warn;
9
10pub const DEFAULT_MAX_IMAGE_SIZE: u64 = 256 * 1024;
11pub const DEFAULT_HTTP_TIMEOUT: Duration = Duration::from_secs(30);
12pub const DEFAULT_HTTP_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
13const MAX_RETRIES: u32 = 3;
14const RETRY_BASE_DELAY: Duration = Duration::from_millis(100);
15
16static HTTP_CLIENT: LazyLock<reqwest::Client> = LazyLock::new(|| {
17 reqwest::Client::builder()
18 .timeout(DEFAULT_HTTP_TIMEOUT)
19 .connect_timeout(DEFAULT_HTTP_CONNECT_TIMEOUT)
20 .pool_max_idle_per_host(5)
21 .pool_idle_timeout(Duration::from_secs(60))
22 .build()
23 .expect("Failed to create HTTP client")
24});
25
26#[derive(Clone, Debug)]
27pub struct ImageConfig {
28 pub max_image_size: u64,
29 pub http_timeout: Duration,
30 pub http_connect_timeout: Duration,
31}
32
33impl Default for ImageConfig {
34 fn default() -> Self {
35 Self {
36 max_image_size: DEFAULT_MAX_IMAGE_SIZE,
37 http_timeout: DEFAULT_HTTP_TIMEOUT,
38 http_connect_timeout: DEFAULT_HTTP_CONNECT_TIMEOUT,
39 }
40 }
41}
42
43pub struct ImageHeaders {
44 pub etag: Option<String>,
45 pub last_modified: Option<String>,
46 pub content_length: Option<u64>,
47 pub content_type: Option<String>,
48}
49
50pub struct DownloadedImage {
51 pub image_value: ImageValue,
52 pub headers: ImageHeaders,
53 pub content_hash: String,
54}
55
56fn extract_headers(response: &reqwest::Response) -> ImageHeaders {
57 let etag = response
58 .headers()
59 .get(reqwest::header::ETAG)
60 .and_then(|v| v.to_str().ok())
61 .map(|s| s.to_string());
62
63 let last_modified = response
64 .headers()
65 .get(reqwest::header::LAST_MODIFIED)
66 .and_then(|v| v.to_str().ok())
67 .map(|s| s.to_string());
68
69 let content_length = response
70 .headers()
71 .get(reqwest::header::CONTENT_LENGTH)
72 .and_then(|v| v.to_str().ok())
73 .and_then(|s| s.parse::<u64>().ok());
74
75 let content_type = response
76 .headers()
77 .get(reqwest::header::CONTENT_TYPE)
78 .and_then(|v| v.to_str().ok())
79 .map(|s| s.to_string());
80
81 ImageHeaders {
82 etag,
83 last_modified,
84 content_length,
85 content_type,
86 }
87}
88
89fn is_transient_error(error: &reqwest::Error) -> bool {
90 if error.is_timeout() || error.is_connect() {
91 return true;
92 }
93
94 if let Some(status) = error.status() {
95 return status.is_server_error();
96 }
97
98 false
99}
100
101async fn with_retry<F, T, Fut>(operation: &str, url: &str, f: F) -> Result<T>
102where
103 F: Fn() -> Fut,
104 Fut: std::future::Future<Output = Result<T>>,
105{
106 let mut last_error = None;
107
108 for attempt in 0..MAX_RETRIES {
109 match f().await {
110 Ok(result) => return Ok(result),
111 Err(e) => {
112 let is_transient =
113 matches!(&e, Error::HttpError(_, inner) if is_transient_error(inner));
114
115 if !is_transient || attempt == MAX_RETRIES - 1 {
116 return Err(e);
117 }
118
119 let delay = RETRY_BASE_DELAY * 2u32.pow(attempt);
120 warn!(
121 operation = operation,
122 url = url,
123 attempt = attempt + 1,
124 max_retries = MAX_RETRIES,
125 delay_ms = delay.as_millis(),
126 error = ?e,
127 "Retrying after transient error"
128 );
129 tokio::time::sleep(delay).await;
130 last_error = Some(e);
131 }
132 }
133 }
134
135 Err(last_error.expect("At least one error occurred"))
136}
137
138pub async fn fetch_headers(url: &str) -> Result<ImageHeaders> {
139 fetch_headers_with_config(url, &ImageConfig::default()).await
140}
141
142pub async fn fetch_headers_with_config(url: &str, config: &ImageConfig) -> Result<ImageHeaders> {
143 let client = reqwest::Client::builder()
144 .timeout(config.http_timeout)
145 .connect_timeout(config.http_connect_timeout)
146 .build()
147 .map_err(|e| Error::HttpError("failed to build HTTP client".to_string(), e))?;
148
149 with_retry("fetch_headers", url, || async {
150 let response = client
151 .head(url)
152 .send()
153 .await
154 .map_err(|e| Error::HttpError(format!("HEAD request failed for {url}"), e))?;
155
156 Ok(extract_headers(&response))
157 })
158 .await
159}
160
161pub async fn download_image(url: &str) -> Result<DownloadedImage> {
162 download_image_with_config(url, &ImageConfig::default()).await
163}
164
165pub async fn download_image_with_config(
166 url: &str,
167 config: &ImageConfig,
168) -> Result<DownloadedImage> {
169 with_retry("download_image", url, || async {
170 let response = HTTP_CLIENT
171 .get(url)
172 .send()
173 .await
174 .map_err(|e| Error::HttpError(format!("GET request failed for {url}"), e))?;
175
176 let headers = extract_headers(&response);
177
178 if let Some(len) = headers.content_length {
179 if len > config.max_image_size {
180 return Err(Error::ImageError(format!(
181 "image size {len} exceeds maximum allowed size {} bytes",
182 config.max_image_size
183 )));
184 }
185 }
186
187 let image_type = match &headers.content_type {
188 Some(ct) => ImageType::try_from_content_type(ct)
189 .map_err(|e| Error::ImageError(format!("unsupported content type: {e}")))?,
190 None => return Err(Error::ImageError("missing Content-Type header".to_string())),
191 };
192
193 let bytes = response
194 .bytes()
195 .await
196 .map_err(|e| Error::HttpError(format!("failed to read response body from {url}"), e))?;
197
198 if bytes.len() as u64 > config.max_image_size {
199 return Err(Error::ImageError(format!(
200 "downloaded image size {} exceeds maximum allowed size {} bytes",
201 bytes.len(),
202 config.max_image_size
203 )));
204 }
205
206 let mut hasher = Sha256::new();
207 hasher.update(&bytes);
208 let content_hash = format!("{:x}", hasher.finalize());
209
210 let filename = extract_filename(url);
211
212 let image_value = ImageValue::new(filename, image_type, bytes.to_vec());
213
214 Ok(DownloadedImage {
215 image_value,
216 headers: ImageHeaders {
217 etag: headers.etag,
218 last_modified: headers.last_modified,
219 content_length: Some(bytes.len() as u64),
220 content_type: headers.content_type,
221 },
222 content_hash,
223 })
224 })
225 .await
226}
227
228fn extract_filename(url: &str) -> String {
229 url::Url::parse(url)
230 .ok()
231 .and_then(|parsed| {
232 parsed
233 .path_segments()
234 .and_then(|mut segments| segments.next_back().map(|s| s.to_string()))
235 })
236 .filter(|name| !name.is_empty())
237 .unwrap_or_else(|| {
238 let mut hasher = Sha256::new();
239 hasher.update(url.as_bytes());
240 format!("image_{:x}", hasher.finalize())
241 })
242}
243
244pub fn needs_update(spec_url: &str, status: &Option<OAuth2ClientImageStatus>) -> bool {
245 match status {
246 None => true,
247 Some(s) => s.url != spec_url,
248 }
249}
250
251pub fn headers_changed(current: &ImageHeaders, cached: &OAuth2ClientImageStatus) -> bool {
252 if current.etag.is_some() && cached.etag.is_some() {
253 return current.etag != cached.etag;
254 }
255
256 if current.last_modified.is_some() && cached.last_modified.is_some() {
257 return current.last_modified != cached.last_modified;
258 }
259
260 if current.content_length.is_some() && cached.content_length.is_some() {
261 return current.content_length != cached.content_length;
262 }
263
264 false
265}
266
267#[cfg(test)]
268mod tests {
269 use super::*;
270
271 #[test]
272 fn test_extract_filename_from_url() {
273 assert_eq!(
274 extract_filename("https://example.com/path/to/image.png"),
275 "image.png"
276 );
277 assert_eq!(
278 extract_filename("https://example.com/image.svg?query=1"),
279 "image.svg"
280 );
281 }
282
283 #[test]
284 fn test_extract_filename_from_invalid_url() {
285 let result = extract_filename("not-a-url");
286 assert!(result.starts_with("image_"));
287 }
288
289 #[test]
290 fn test_extract_filename_from_url_without_path() {
291 let result = extract_filename("https://example.com");
292 assert!(result.starts_with("image_"));
293 }
294
295 #[test]
296 fn test_headers_changed_with_etag() {
297 let current = ImageHeaders {
298 etag: Some("etag1".to_string()),
299 last_modified: None,
300 content_length: Some(100),
301 content_type: Some("image/png".to_string()),
302 };
303 let cached = OAuth2ClientImageStatus {
304 url: "https://example.com/image.png".to_string(),
305 etag: Some("etag2".to_string()),
306 last_modified: None,
307 content_length: Some(100),
308 content_hash: Some("hash".to_string()),
309 };
310 assert!(headers_changed(¤t, &cached));
311
312 let cached_same = OAuth2ClientImageStatus {
313 url: "https://example.com/image.png".to_string(),
314 etag: Some("etag1".to_string()),
315 last_modified: None,
316 content_length: Some(100),
317 content_hash: Some("hash".to_string()),
318 };
319 assert!(!headers_changed(¤t, &cached_same));
320 }
321
322 #[test]
323 fn test_headers_changed_with_last_modified() {
324 let current = ImageHeaders {
325 etag: None,
326 last_modified: Some("Mon, 01 Jan 2024 00:00:00 GMT".to_string()),
327 content_length: Some(100),
328 content_type: Some("image/png".to_string()),
329 };
330 let cached = OAuth2ClientImageStatus {
331 url: "https://example.com/image.png".to_string(),
332 etag: None,
333 last_modified: Some("Tue, 02 Jan 2024 00:00:00 GMT".to_string()),
334 content_length: Some(100),
335 content_hash: Some("hash".to_string()),
336 };
337 assert!(headers_changed(¤t, &cached));
338 }
339
340 #[test]
341 fn test_headers_changed_with_content_length() {
342 let current = ImageHeaders {
343 etag: None,
344 last_modified: None,
345 content_length: Some(100),
346 content_type: Some("image/png".to_string()),
347 };
348 let cached = OAuth2ClientImageStatus {
349 url: "https://example.com/image.png".to_string(),
350 etag: None,
351 last_modified: None,
352 content_length: Some(200),
353 content_hash: Some("hash".to_string()),
354 };
355 assert!(headers_changed(¤t, &cached));
356 }
357
358 #[test]
359 fn test_headers_changed_no_change() {
360 let current = ImageHeaders {
361 etag: None,
362 last_modified: None,
363 content_length: Some(100),
364 content_type: Some("image/png".to_string()),
365 };
366 let cached = OAuth2ClientImageStatus {
367 url: "https://example.com/image.png".to_string(),
368 etag: None,
369 last_modified: None,
370 content_length: Some(100),
371 content_hash: Some("hash".to_string()),
372 };
373 assert!(!headers_changed(¤t, &cached));
374 }
375
376 #[test]
377 fn test_needs_update() {
378 assert!(needs_update("https://example.com/image.png", &None));
379
380 let status = Some(OAuth2ClientImageStatus {
381 url: "https://example.com/old.png".to_string(),
382 etag: None,
383 last_modified: None,
384 content_length: None,
385 content_hash: None,
386 });
387 assert!(needs_update("https://example.com/new.png", &status));
388
389 let status_same = Some(OAuth2ClientImageStatus {
390 url: "https://example.com/image.png".to_string(),
391 etag: None,
392 last_modified: None,
393 content_length: None,
394 content_hash: None,
395 });
396 assert!(!needs_update("https://example.com/image.png", &status_same));
397 }
398
399 #[test]
400 fn test_image_config_default() {
401 let config = ImageConfig::default();
402 assert_eq!(config.max_image_size, DEFAULT_MAX_IMAGE_SIZE);
403 assert_eq!(config.http_timeout, DEFAULT_HTTP_TIMEOUT);
404 assert_eq!(config.http_connect_timeout, DEFAULT_HTTP_CONNECT_TIMEOUT);
405 }
406}