Skip to main content

kaniop_oauth2/
image.rs

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