akas 2.4.18

AKAS: API Key Authorization Server
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
use crate::{
    models::{Headers, KeyFormat},
    state::AppState,
};
use actix_web::http::header::HeaderMap;
use sha2::{Digest, Sha256};
use std::{fs::metadata, io::ErrorKind, path::Path};
use url::Url;

/// Checks if the provided bearer token grants administrative privileges.
///
/// # Arguments
///
/// * `token`: The token from the `BearerAuth` extractor.
/// * `data` - A reference to the [`AppState`] struct, which holds the
///   application's configuration, including `no_admin_key` and `admin_key`.
///
/// # Returns
///
/// `true` if administrative privileges are granted (either `no_admin_key` is true,
/// or the token matches the `admin_key`), otherwise `false`.
///
pub fn check_admin(token: &str, data: &AppState) -> bool {
    data.no_admin_key || token == data.admin_key
}

/// Checks if a given key is valid based on specified length and prefix constraints.
///
/// This function is a helper to validate API keys or similar strings against two criteria:
/// a required exact length and an optional starting prefix.
///
/// # Arguments
///
/// * `key` - A string slice (`&str`) representing the key to be validated.
/// * `length` - An unsigned 16-bit integer (`u16`) specifying the required exact length of the key.
///   If `0`, this length check is skipped, and any length is considered valid.
/// * `prefix` - A string slice (`&str`) specifying the required starting prefix of the key.
///   If empty, this prefix check is skipped, and any prefix is considered valid.
///
/// # Returns
///
/// * `true` - If the key meets all specified length and prefix requirements.
/// * `false` - If the key fails any of the checks (incorrect length when `length > 0`,
///   or incorrect prefix when `prefix` is not empty).
///
pub fn is_key_valid(key: &str, length: u16, prefix: &str) -> bool {
    if length > 0 && key.chars().count() as u16 != length {
        return false;
    }
    if !prefix.is_empty() && !key.starts_with(prefix) {
        return false;
    }
    true
}

/// Parses common HTTP headers into a structured `Headers` object.
///
/// Extracts specific `x-` prefixed headers, providing a default "-" string
/// if a header is missing or invalid. The `x-akas-metadata` header is
/// truncated if its length exceeds `original_length` or `metadata_length`.
///
/// # Arguments
///
/// * `headers` - A reference to the `HeaderMap` containing the HTTP request headers.
/// * `original_length` - The maximum allowed length for the `x-forwarded-for`, `x-original-...` headers.
///   If 0, original_uri will be "-".
/// * `metadata_length` - The maximum allowed length for the `x-akas-metadata` header.
///   If 0, metadata will be "-".
///
/// # Returns
///
/// A `Headers` struct containing the parsed and sanitized header values.
///
pub fn parse_headers(headers: &HeaderMap, original_length: u16, metadata_length: u16) -> Headers {
    let forwarded_for = get_truncated_header(headers, "x-forwarded-for", original_length);
    let original_host = get_truncated_header(headers, "x-original-host", original_length);
    let original_uri = get_truncated_header(headers, "x-original-uri", original_length);
    let metadata = get_truncated_header(headers, "x-akas-metadata", metadata_length);

    Headers {
        forwarded_for,
        original_host,
        original_uri,
        metadata,
    }
}

/// Retrieves a header from the HeaderMap, converts it to a string,
/// and truncates it to a maximum length if specified.
///
/// Returns a default "-" string if the header is missing, invalid,
/// or if `max_len` is 0 (unless the header is present and `max_len` > 0).
///
/// # Arguments
/// * `headers` - The HeaderMap to search within.
/// * `header_name` - The name of the header to retrieve (e.g., "x-akas-metadata").
/// * `max_len` - The maximum length for the header's value. If 0, an empty string is returned
///   unless the header is explicitly present and can be truncated.
///
/// # Returns
/// A `String` containing the header's value, truncated if necessary, or "-".
///
fn get_truncated_header(headers: &HeaderMap, header_name: &str, max_len: u16) -> String {
    if max_len == 0 {
        return "-".to_string();
    }

    headers
        .get(header_name)
        .and_then(|v| v.to_str().ok())
        .map(|s| {
            if s.is_empty() {
                return "-".to_string();
            }
            let actual_max_len = max_len as usize;
            if s.len() > actual_max_len {
                s.chars().take(actual_max_len).collect::<String>()
            } else {
                s.to_string()
            }
        })
        .unwrap_or_else(|| "-".to_string())
}

/// Hashes the input string using SHA256 and returns the hexadecimal representation of the hash.
///
/// # Arguments
///
/// * `input` - A string slice (`&str`) to be hashed.
///
/// # Returns
///
/// A `String` containing the hexadecimal representation of the SHA256 hash.
///
pub fn sha256_hex(input: &str) -> String {
    let mut hasher = Sha256::new();
    hasher.update(input.as_bytes());
    hex::encode(hasher.finalize())
}

/// Validates the user inputs.
///
/// This function checks that:
/// - `host` is a valid URL.
/// - `filename` is a path to an existing and readable file.
/// - `format` is one of the valid formats: "plain" or "sha256".
///
/// # Arguments
///
/// * `host` - The URL of the server.
/// * `filename` - The path to the file.
/// * `format` - The format of the file ("plain" or "sha256").
///
/// # Errors
///
/// Returns a `std::io::Error` if any of the checks fail.
///
pub fn validate_inputs(host: &str, filename: &str, format: &str) -> Result<(), std::io::Error> {
    if Url::parse(host).is_err() {
        return Err(std::io::Error::new(
            ErrorKind::InvalidInput,
            format!("{} is not a valid URL.", host),
        ));
    }
    // Check if file exists and is readable
    let file_path = Path::new(filename);
    if !file_path.exists() {
        return Err(std::io::Error::new(
            ErrorKind::InvalidInput,
            format!("{} is not a path to an existing file.", filename),
        ));
    }
    if !file_path.is_file() || !metadata(file_path)?.is_file() {
        return Err(std::io::Error::new(
            ErrorKind::InvalidInput,
            format!("{} is not a valid file.", filename),
        ));
    }
    // Check the permission file
    if metadata(file_path)?.permissions().readonly() {
        return Err(std::io::Error::new(
            ErrorKind::PermissionDenied,
            format!("File {} is not readable.", filename),
        ));
    }
    // Check file format type
    if KeyFormat::from_str(format).is_none() {
        return Err(std::io::Error::new(
            ErrorKind::InvalidInput,
            format!(
                "{} is not a valid format. Choose from '{}' or '{}'.",
                format,
                KeyFormat::Plain.as_str(),
                KeyFormat::Sha256.as_str()
            ),
        ));
    }
    Ok(())
}

#[cfg(test)]
mod check_admin_tests {
    use super::*;
    use crate::init_state;
    use crate::AppConfig;
    use crate::AppState;
    use prometheus::{IntCounterVec, Opts};
    use std::sync::Arc;

    fn create_default_app_state(no_admin: bool, admin_key: &str) -> AppState {
        let auth_counter = Arc::new(
            IntCounterVec::new(Opts::new("test_auth", "Test auth counter"), &["status"]).unwrap(),
        );

        init_state(AppConfig {
            admin_key: admin_key.to_string(),
            no_admin_key: no_admin,
            local: false,
            enable_metrics: false,
            port: 5001,
            log_level: "info".to_string(),
            original_length: 0,
            metadata_length: 0,
            key_length: 0,
            key_prefix: "".to_string(),
            auth_counter: auth_counter,
        })
        .unwrap()
    }

    #[test]
    fn test_check_admin_no_admin_key_set() {
        let data = create_default_app_state(true, ""); // no_admin_key is true
        assert!(check_admin("any_token", &data));
        assert!(check_admin("", &data));
    }

    #[test]
    fn test_check_admin_with_correct_key() {
        let data = create_default_app_state(false, "secret_key");
        assert!(check_admin("secret_key", &data));
    }

    #[test]
    fn test_check_admin_with_incorrect_key() {
        let data = create_default_app_state(false, "secret_key");
        assert!(!check_admin("wrong_key", &data));
    }

    #[test]
    fn test_check_admin_with_empty_token_and_set_key() {
        let data = create_default_app_state(false, "secret_key");
        assert!(!check_admin("", &data));
    }

    #[test]
    fn test_check_admin_empty_token_non_empty_key() {
        let data = create_default_app_state(false, "some_key"); // no_admin_key is false
        assert!(!check_admin("", &data));
    }
}

#[cfg(test)]
mod is_key_valid_tests {
    use super::*;

    /// Test case: Key matches both length and prefix.
    #[test]
    fn test_valid_key_with_length_and_prefix() {
        assert!(is_key_valid("testkey123", 10, "test"));
    }

    /// Test case: Key matches only length (empty prefix).
    #[test]
    fn test_valid_key_with_length_no_prefix() {
        assert!(is_key_valid("exactlength", 11, ""));
    }

    /// Test case: Key matches only prefix (length 0).
    #[test]
    fn test_valid_key_with_prefix_no_length() {
        assert!(is_key_valid("mysecretkey", 0, "mysecret"));
    }

    /// Test case: Key is valid when both length and prefix checks are skipped.
    #[test]
    fn test_valid_key_no_constraints() {
        assert!(is_key_valid("anykeywilldo", 0, ""));
    }

    /// Test case: Key has incorrect length when length is specified.
    #[test]
    fn test_invalid_key_wrong_length() {
        assert!(!is_key_valid("short", 10, "short"));
        assert!(!is_key_valid("toolongkey", 5, "toolong"));
    }

    /// Test case: Key has incorrect prefix when prefix is specified.
    #[test]
    fn test_invalid_key_wrong_prefix() {
        assert!(!is_key_valid("wrongprefixkey", 14, "correct"));
    }

    /// Test case: Key fails both length and prefix constraints.
    #[test]
    fn test_invalid_key_wrong_length_and_prefix() {
        assert!(!is_key_valid("bad", 10, "wrong"));
    }

    /// Test case: Empty key with constraints.
    #[test]
    fn test_empty_key_with_constraints() {
        assert!(!is_key_valid("", 5, "prefix"));
        assert!(!is_key_valid("", 0, "prefix")); // Empty key doesn't start with non-empty prefix
        assert!(!is_key_valid("", 1, "")); // Empty key doesn't match length 1
    }

    /// Test case: Empty key with no constraints.
    #[test]
    fn test_empty_key_no_constraints() {
        assert!(is_key_valid("", 0, ""));
    }

    /// Test case: Key with exactly the minimum required length.
    #[test]
    fn test_key_min_length() {
        assert!(is_key_valid("abc", 3, "ab"));
    }

    /// Test case: Key with special characters.
    #[test]
    fn test_key_with_special_characters() {
        assert!(is_key_valid("k€y!@#$", 7, "k€y"));
    }

    /// Test case: Prefix is longer than the key.
    #[test]
    fn test_prefix_longer_than_key() {
        assert!(!is_key_valid("abc", 3, "abcd"));
    }
}

#[cfg(test)]
mod parse_headers_tests {
    use super::*;
    use actix_web::http::header::{HeaderMap, HeaderName, HeaderValue};

    #[test]
    fn test_parse_headers_all_present() {
        let mut headers = HeaderMap::new();
        headers.insert(
            HeaderName::from_static("x-forwarded-for"),
            HeaderValue::from_static("203.0.113.195"),
        );
        headers.insert(
            HeaderName::from_static("x-original-host"),
            HeaderValue::from_static("my-host.com"),
        );
        headers.insert(
            HeaderName::from_static("x-original-uri"),
            HeaderValue::from_static("/some/path"),
        );
        headers.insert(
            HeaderName::from_static("x-akas-metadata"),
            HeaderValue::from_static("metadata1"),
        );
        let original_length = 100;
        let metadata_length = 50;
        let result = parse_headers(&headers, original_length, metadata_length);

        assert_eq!(result.forwarded_for, "203.0.113.195");
        assert_eq!(result.original_host, "my-host.com");
        assert_eq!(result.original_uri, "/some/path");
        assert_eq!(result.metadata, "metadata1");
    }

    #[test]
    fn test_parse_headers_missing_headers() {
        let mut headers = HeaderMap::new();
        headers.insert(
            HeaderName::from_static("x-original-other"),
            HeaderValue::from_static("other-value"),
        );
        let original_length = 100;
        let metadata_length = 10;
        let result = parse_headers(&headers, original_length, metadata_length);

        assert_eq!(result.forwarded_for, "-");
        assert_eq!(result.original_host, "-");
        assert_eq!(result.original_uri, "-");
        assert_eq!(result.metadata, "-");
    }
    #[test]
    fn test_parse_headers_all_missing_except_metadata() {
        let mut headers = HeaderMap::new();
        headers.insert(
            HeaderName::from_static("x-akas-metadata"),
            HeaderValue::from_static("metadata1"),
        );
        let original_length = 100;
        let metadata_length = 10;
        let result = parse_headers(&headers, original_length, metadata_length);

        assert_eq!(result.forwarded_for, "-");
        assert_eq!(result.original_host, "-");
        assert_eq!(result.original_uri, "-");
        assert_eq!(result.metadata, "metadata1");
    }

    #[test]
    fn test_parse_headers_original_truncation() {
        let mut headers = HeaderMap::new();
        headers.insert(
            HeaderName::from_static("x-forwarded-for"),
            HeaderValue::from_static("203.0.113.195"),
        );
        headers.insert(
            HeaderName::from_static("x-original-host"),
            HeaderValue::from_static("my-host.com"),
        );
        headers.insert(
            HeaderName::from_static("x-original-uri"),
            HeaderValue::from_static("/some/path"),
        );
        headers.insert(
            HeaderName::from_static("x-akas-metadata"),
            HeaderValue::from_static("metadata1"),
        );
        let original_length = 5;
        let metadata_length = 50;
        let result = parse_headers(&headers, original_length, metadata_length);

        assert_eq!(result.forwarded_for, "203.0");
        assert_eq!(result.original_host, "my-ho");
        assert_eq!(result.original_uri, "/some");
        assert_eq!(result.metadata, "metadata1");
    }

    #[test]
    fn test_parse_headers_akas_metadata_truncation() {
        let mut headers = HeaderMap::new();
        headers.insert(
            HeaderName::from_static("x-akas-metadata"),
            HeaderValue::from_static("long_value_that_should_be_truncated"),
        );
        let original_length = 100;
        let metadata_length = 10;
        let result = parse_headers(&headers, original_length, metadata_length);

        assert_eq!(result.metadata, "long_value");
    }

    #[test]
    fn test_parse_headers_akas_metadata_exact_length() {
        let mut headers = HeaderMap::new();
        headers.insert(
            HeaderName::from_static("x-akas-metadata"),
            HeaderValue::from_static("12345"),
        );
        let original_length = 100;
        let metadata_length = 5;
        let result = parse_headers(&headers, original_length, metadata_length);

        assert_eq!(result.forwarded_for, "-");
        assert_eq!(result.original_host, "-");
        assert_eq!(result.original_uri, "-");
        assert_eq!(result.metadata, "12345");
    }

    #[test]
    fn test_parse_headers_original_length_zero() {
        let mut headers = HeaderMap::new();
        headers.insert(
            HeaderName::from_static("x-forwarded-for"),
            HeaderValue::from_static("203.0.113.195"),
        );
        headers.insert(
            HeaderName::from_static("x-original-host"),
            HeaderValue::from_static("my-host.com"),
        );
        headers.insert(
            HeaderName::from_static("x-original-uri"),
            HeaderValue::from_static("/some/path"),
        );
        headers.insert(
            HeaderName::from_static("x-akas-metadata"),
            HeaderValue::from_static("metadata1"),
        );
        let original_length = 0;
        let metadata_length = 20;
        let result = parse_headers(&headers, original_length, metadata_length);

        assert_eq!(result.forwarded_for, "-");
        assert_eq!(result.original_host, "-");
        assert_eq!(result.original_uri, "-");
        assert_eq!(result.metadata, "metadata1");
    }

    #[test]
    fn test_parse_headers_metadata_length_zero() {
        let mut headers = HeaderMap::new();
        headers.insert(
            HeaderName::from_static("x-original-host"),
            HeaderValue::from_static("my-host.com"),
        );
        headers.insert(
            HeaderName::from_static("x-akas-metadata"),
            HeaderValue::from_static("metadata1"),
        );
        let original_length = 100;
        let metadata_length = 0;
        let result = parse_headers(&headers, original_length, metadata_length);

        assert_eq!(result.forwarded_for, "-");
        assert_eq!(result.original_host, "my-host.com");
        assert_eq!(result.original_uri, "-");
        assert_eq!(result.metadata, "-");
    }

    #[test]
    fn test_parse_headers_empty_header_values() {
        let mut headers = HeaderMap::new();
        headers.insert(
            HeaderName::from_static("x-original-host"),
            HeaderValue::from_static(""),
        );
        headers.insert(
            HeaderName::from_static("x-original-uri"),
            HeaderValue::from_static(""),
        );
        headers.insert(
            HeaderName::from_static("x-akas-metadata"),
            HeaderValue::from_static(""),
        );
        let original_length = 100;
        let metadata_length = 10;
        let result = parse_headers(&headers, original_length, metadata_length);

        assert_eq!(result.forwarded_for, "-");
        assert_eq!(result.original_host, "-");
        assert_eq!(result.original_uri, "-");
        assert_eq!(result.metadata, "-");
    }
}

#[cfg(test)]
mod get_truncated_header_tests {
    use super::*;
    use actix_web::http::header::{HeaderMap, HeaderName, HeaderValue};

    #[test]
    fn test_header_exists_and_no_truncation_needed() {
        let mut headers = HeaderMap::new();
        headers.insert(
            HeaderName::from_static("x-test-header"),
            HeaderValue::from_static("Hello World"),
        );
        let result = get_truncated_header(&headers, "x-test-header", 20);
        assert_eq!(result, "Hello World".to_string());
    }

    #[test]
    fn test_header_exists_and_truncation_needed() {
        let mut headers = HeaderMap::new();
        headers.insert(
            HeaderName::from_static("x-test-header"),
            HeaderValue::from_static("This is a long string that needs to be truncated."),
        );
        let result = get_truncated_header(&headers, "x-test-header", 10);
        assert_eq!(result, "This is a ".to_string()); // Truncated to 10 characters
    }

    #[test]
    fn test_header_exists_and_exact_length() {
        let mut headers = HeaderMap::new();
        headers.insert(
            HeaderName::from_static("x-test-header"),
            HeaderValue::from_static("ExactLength"),
        );
        let result = get_truncated_header(&headers, "x-test-header", 11);
        assert_eq!(result, "ExactLength".to_string());
    }

    #[test]
    fn test_header_not_found() {
        let headers = HeaderMap::new(); // Empty HeaderMap
        let result = get_truncated_header(&headers, "non-existent-header", 10);
        assert_eq!(result, "-".to_string()); // Should default to "-"
    }

    #[test]
    fn test_max_len_is_zero() {
        let mut headers = HeaderMap::new();
        headers.insert(
            HeaderName::from_static("x-test-header"),
            HeaderValue::from_static("Some value"),
        );
        let result = get_truncated_header(&headers, "x-test-header", 0);
        assert_eq!(result, "-".to_string()); // Should return "-" if max_len is 0
    }

    #[test]
    fn test_empty_header_value() {
        let mut headers = HeaderMap::new();
        headers.insert(
            HeaderName::from_static("x-empty-header"),
            HeaderValue::from_static(""),
        );
        let result = get_truncated_header(&headers, "x-empty-header", 10);
        assert_eq!(result, "-".to_string());
    }
}

#[cfg(test)]
mod sha256_hex_tests {
    use super::*;
    use crate::state::EMPTY_STRING_SHA256;

    #[test]
    fn test_sha256_hex_hello_world() {
        let input = "hello world";
        let expected_hash = "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9";
        assert_eq!(sha256_hex(input), expected_hash);
    }

    #[test]
    fn test_sha256_hex_empty_string() {
        let input = "";
        assert_eq!(sha256_hex(input), EMPTY_STRING_SHA256);
    }

    #[test]
    fn test_sha256_hex_long_string() {
        let input = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
        let expected_hash = "1f38b148591b024f56cd04fa661758d758dd31d855a225c4645126e76be72f32";
        assert_eq!(sha256_hex(input), expected_hash);
    }

    #[test]
    fn test_sha256_hex_with_unicode() {
        let input = "你好世界"; // "Hello world" in Chinese
        let expected_hash = "beca6335b20ff57ccc47403ef4d9e0b8fccb4442b3151c2e7d50050673d43172";
        assert_eq!(sha256_hex(input), expected_hash);
    }
}

#[cfg(test)]
mod validate_inputs_tests {
    use super::*;

    #[test]
    fn test_validate_inputs_ok() {
        assert!(
            validate_inputs("https://example.com", "tests/files/plain_key.txt", "plain").is_ok()
        );
        assert!(
            validate_inputs("https://example.com", "tests/files/plain_key.txt", "sha256").is_ok()
        );
        assert!(validate_inputs(
            "http://localhost:5001",
            "tests/files/plain_key.txt",
            "sha256"
        )
        .is_ok());
    }

    #[test]
    fn test_validate_inputs_invalid_host() {
        let err = validate_inputs("invalid_url", "tests/files/plain_key.txt", "plain").unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
        assert_eq!(err.to_string(), "invalid_url is not a valid URL.");
    }

    #[test]
    fn test_validate_inputs_non_existent_file() {
        let err = validate_inputs(
            "https://example.com",
            "tests/files/non_existent_file.txt",
            "plain",
        )
        .unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
        assert_eq!(
            err.to_string(),
            "tests/files/non_existent_file.txt is not a path to an existing file."
        );
    }

    #[test]
    fn test_validate_inputs_dir_instead_file() {
        let err = validate_inputs("https://example.com", "tests/files", "plain").unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
        assert_eq!(err.to_string(), "tests/files is not a valid file.");
    }

    #[test]
    fn test_validate_inputs_invalid_format() {
        let err = validate_inputs(
            "https://example.com",
            "tests/files/plain_key.txt",
            "invalid_format",
        )
        .unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidInput);
        assert_eq!(
            err.to_string(),
            "invalid_format is not a valid format. Choose from 'plain' or 'sha256'."
        );
    }
}