scanii 1.3.0

Minimal-dependency Rust SDK for the Scanii content security API
Documentation
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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufReader, Read};
use std::path::Path;
use std::time::Duration;

use ureq::{Agent, AgentBuilder, Request, Response};

use crate::error::ScaniiError;
use crate::models::{
    ScaniiAuthToken, ScaniiPendingResult, ScaniiProcessingResult, ScaniiTraceResult,
};
use crate::multipart;

const DEFAULT_ENDPOINT: &str = "https://api.scanii.com";
const API_VERSION_PATH: &str = "/v2.2";
const DEFAULT_TIMEOUT_SECS: u64 = 60;

/// Crate version, inlined at compile time from `Cargo.toml`.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

/// Synchronous client for the Scanii REST API v2.2.
///
/// Construct via [`ScaniiClient::builder`]. The client is `Send + Sync` and
/// can be safely shared across threads.
///
/// Per SDK Principle 3 the client is integration-only: it does not retry,
/// batch, or paginate. Each public method maps to exactly one HTTP request.
///
/// See <https://scanii.github.io/openapi/v22/>.
///
/// # Example
///
/// ```no_run
/// # use scanii::ScaniiClient;
/// # fn main() -> Result<(), scanii::ScaniiError> {
/// let client = ScaniiClient::builder()
///     .key("your-key")
///     .secret("your-secret")
///     .build()?;
/// client.ping()?;
/// # Ok(()) }
/// ```
#[derive(Debug, Clone)]
pub struct ScaniiClient {
    agent: Agent,
    base_url: String,
    auth_header: String,
    user_agent: String,
}

/// Builder for [`ScaniiClient`].
///
/// Set either `key` + `secret` (HTTP Basic Auth), or `token` (auth-token
/// authentication). Mixing the two is a configuration error.
#[derive(Debug, Default, Clone)]
pub struct ScaniiClientBuilder {
    key: Option<String>,
    secret: Option<String>,
    token: Option<String>,
    target: Option<crate::ScaniiTarget>,
    endpoint: Option<String>,
    user_agent: Option<String>,
    timeout: Option<Duration>,
}

struct ResponseHeaders {
    request_id: Option<String>,
    host_id: Option<String>,
    location: Option<String>,
}

impl ScaniiClient {
    /// Start building a client.
    pub fn builder() -> ScaniiClientBuilder {
        ScaniiClientBuilder::default()
    }

    /// Submit content from any [`Read`] source for synchronous scanning.
    ///
    /// The body is streamed — memory use is independent of content length.
    ///
    /// `filename` goes verbatim into the multipart `Content-Disposition`
    /// header; `content_type` defaults to `application/octet-stream` when
    /// `None`.
    ///
    /// For file-on-disk uploads, prefer the [`Self::process_file`] convenience.
    ///
    /// See <https://scanii.github.io/openapi/v22/> — `POST /files`.
    pub fn process<R: Read>(
        &self,
        reader: R,
        filename: &str,
        content_type: Option<&str>,
        metadata: Option<&HashMap<String, String>>,
        callback: Option<&str>,
    ) -> Result<ScaniiProcessingResult, ScaniiError> {
        let ct = content_type.unwrap_or("application/octet-stream");
        let response =
            self.post_multipart_streaming("/files", reader, filename, ct, metadata, callback)?;
        let response = require_status(response, 201)?;
        let headers = capture_headers(&response);
        let body = response_to_string(response)?;
        let mut result: ScaniiProcessingResult = parse_json(&body)?;
        attach_processing_headers(&mut result, headers);
        Ok(result)
    }

    /// Submit a file from disk for synchronous scanning.
    ///
    /// Opens the file with `BufReader`, derives the filename from the path,
    /// and infers the content type by extension. Delegates to [`Self::process`].
    ///
    /// See <https://scanii.github.io/openapi/v22/> — `POST /files`.
    pub fn process_file(
        &self,
        path: &Path,
        metadata: Option<&HashMap<String, String>>,
        callback: Option<&str>,
    ) -> Result<ScaniiProcessingResult, ScaniiError> {
        let filename = path_filename(path);
        let content_type = multipart::guess_content_type(path);
        let reader = BufReader::new(File::open(path)?);
        self.process(reader, &filename, Some(content_type), metadata, callback)
    }

    /// Submit content from any [`Read`] source for server-side asynchronous
    /// scanning. The body is streamed — memory use is independent of content
    /// length. Returns a pending id; the final result is delivered to
    /// `callback` (when supplied) or fetched via [`Self::retrieve`].
    ///
    /// For file-on-disk uploads, prefer the [`Self::process_async_file`] convenience.
    ///
    /// See <https://scanii.github.io/openapi/v22/> — `POST /files/async`.
    pub fn process_async<R: Read>(
        &self,
        reader: R,
        filename: &str,
        content_type: Option<&str>,
        metadata: Option<&HashMap<String, String>>,
        callback: Option<&str>,
    ) -> Result<ScaniiPendingResult, ScaniiError> {
        let ct = content_type.unwrap_or("application/octet-stream");
        let response = self.post_multipart_streaming(
            "/files/async",
            reader,
            filename,
            ct,
            metadata,
            callback,
        )?;
        let response = require_status(response, 202)?;
        let headers = capture_headers(&response);
        let body = response_to_string(response)?;
        let mut result: ScaniiPendingResult = parse_json(&body)?;
        attach_pending_headers(&mut result, headers);
        Ok(result)
    }

    /// Submit a file from disk for server-side asynchronous scanning.
    ///
    /// Opens the file with `BufReader` and delegates to [`Self::process_async`].
    ///
    /// See <https://scanii.github.io/openapi/v22/> — `POST /files/async`.
    pub fn process_async_file(
        &self,
        path: &Path,
        metadata: Option<&HashMap<String, String>>,
        callback: Option<&str>,
    ) -> Result<ScaniiPendingResult, ScaniiError> {
        let filename = path_filename(path);
        let content_type = multipart::guess_content_type(path);
        let reader = BufReader::new(File::open(path)?);
        self.process_async(reader, &filename, Some(content_type), metadata, callback)
    }

    /// Deprecated: use [`Self::process`] (stream-based) instead.
    #[deprecated(
        since = "1.1.0",
        note = "use `process` (stream-based); will be removed in a future major version"
    )]
    pub fn process_reader<R: Read>(
        &self,
        reader: R,
        filename: &str,
        content_type: Option<&str>,
        metadata: Option<&HashMap<String, String>>,
        callback: Option<&str>,
    ) -> Result<ScaniiProcessingResult, ScaniiError> {
        self.process(reader, filename, content_type, metadata, callback)
    }

    /// Deprecated: use [`Self::process_file`] (path-based convenience) instead.
    #[deprecated(
        since = "1.1.0",
        note = "use `process_file`; will be removed in a future major version"
    )]
    pub fn process_path(
        &self,
        path: &Path,
        metadata: Option<&HashMap<String, String>>,
        callback: Option<&str>,
    ) -> Result<ScaniiProcessingResult, ScaniiError> {
        self.process_file(path, metadata, callback)
    }

    /// Deprecated: use [`Self::process_async`] (stream-based) instead.
    #[deprecated(
        since = "1.1.0",
        note = "use `process_async` (stream-based); will be removed in a future major version"
    )]
    pub fn process_async_reader<R: Read>(
        &self,
        reader: R,
        filename: &str,
        content_type: Option<&str>,
        metadata: Option<&HashMap<String, String>>,
        callback: Option<&str>,
    ) -> Result<ScaniiPendingResult, ScaniiError> {
        self.process_async(reader, filename, content_type, metadata, callback)
    }

    /// Deprecated: use [`Self::process_async_file`] (path-based convenience) instead.
    #[deprecated(
        since = "1.1.0",
        note = "use `process_async_file`; will be removed in a future major version"
    )]
    pub fn process_async_path(
        &self,
        path: &Path,
        metadata: Option<&HashMap<String, String>>,
        callback: Option<&str>,
    ) -> Result<ScaniiPendingResult, ScaniiError> {
        self.process_async_file(path, metadata, callback)
    }

    /// Ask Scanii to download a remote URL and scan it asynchronously.
    ///
    /// See <https://scanii.github.io/openapi/v22/> — `POST /files/fetch`.
    pub fn fetch(
        &self,
        location: &str,
        metadata: Option<&HashMap<String, String>>,
        callback: Option<&str>,
    ) -> Result<ScaniiPendingResult, ScaniiError> {
        if location.is_empty() {
            return Err(ScaniiError::Config("location must not be empty".into()));
        }

        let mut owned: Vec<(String, String)> = vec![("location".into(), location.to_owned())];
        if let Some(cb) = callback {
            owned.push(("callback".into(), cb.to_owned()));
        }
        if let Some(m) = metadata {
            for (k, v) in m {
                owned.push((format!("metadata[{k}]"), v.clone()));
            }
        }
        let pairs: Vec<(&str, &str)> = owned
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_str()))
            .collect();

        let response = self.request("POST", "/files/fetch").send_form(&pairs)?;
        let response = require_status(response, 202)?;
        let headers = capture_headers(&response);
        let body = response_to_string(response)?;
        let mut result: ScaniiPendingResult = parse_json(&body)?;
        attach_pending_headers(&mut result, headers);
        Ok(result)
    }

    /// Retrieve a previously submitted scan result by id.
    ///
    /// See <https://scanii.github.io/openapi/v22/> — `GET /files/{id}`.
    pub fn retrieve(&self, id: &str) -> Result<ScaniiProcessingResult, ScaniiError> {
        if id.is_empty() {
            return Err(ScaniiError::Config("id must not be empty".into()));
        }
        let path = format!("/files/{}", url_encode(id));
        let response = self.request("GET", &path).call()?;
        let response = require_status(response, 200)?;
        let headers = capture_headers(&response);
        let body = response_to_string(response)?;
        let mut result: ScaniiProcessingResult = parse_json(&body)?;
        attach_processing_headers(&mut result, headers);
        Ok(result)
    }

    /// Retrieve the ordered processing events (trace) for a previously submitted scan.
    ///
    /// Returns `Ok(None)` when no trace exists for the given id (404).
    /// Returns `Ok(Some(..))` when the trace is found (200).
    ///
    /// This is preview API surface per the v2.2 spec — the shape may shift
    /// before it is marked stable.
    ///
    /// See <https://scanii.github.io/openapi/v22/> — `GET /files/{id}/trace`.
    pub fn retrieve_trace(&self, id: &str) -> Result<Option<ScaniiTraceResult>, ScaniiError> {
        if id.is_empty() {
            return Err(ScaniiError::Config("id must not be empty".into()));
        }
        let path = format!("/files/{}/trace", url_encode(id));
        let response = match self.request("GET", &path).call() {
            Ok(r) => r,
            Err(ureq::Error::Status(404, _)) => return Ok(None),
            Err(e) => return Err(ScaniiError::from(e)),
        };
        let response = require_status(response, 200)?;
        let headers = capture_headers(&response);
        let body = response_to_string(response)?;
        let mut result: ScaniiTraceResult = parse_json(&body)?;
        result.request_id = headers.request_id;
        result.host_id = headers.host_id;
        result.resource_location = headers.location;
        Ok(Some(result))
    }

    /// Submit a URL for synchronous scanning.
    ///
    /// Instructs the server to fetch the content from `location` and scan it,
    /// returning a full [`ScaniiProcessingResult`] synchronously. Distinct from
    /// [`Self::fetch`], which is asynchronous and posts to `/files/fetch`.
    ///
    /// This is preview API surface per the v2.2 spec — the shape may shift
    /// before it is marked stable.
    ///
    /// See <https://scanii.github.io/openapi/v22/> — `POST /files`.
    pub fn process_from_url(
        &self,
        location: &str,
        metadata: Option<&HashMap<String, String>>,
    ) -> Result<ScaniiProcessingResult, ScaniiError> {
        if location.is_empty() {
            return Err(ScaniiError::Config("location must not be empty".into()));
        }

        let mut fields: HashMap<String, String> = HashMap::new();
        fields.insert("location".into(), location.to_owned());
        if let Some(m) = metadata {
            for (k, v) in m {
                fields.insert(format!("metadata[{k}]"), v.clone());
            }
        }

        let boundary = multipart::make_boundary();
        let ct = multipart::make_content_type(&boundary);
        let body = multipart::build_text_only_body(&boundary, &fields);

        let response = self
            .request("POST", "/files")
            .set("Content-Type", &ct)
            .send_bytes(&body)?;
        let response = require_status(response, 201)?;
        let headers = capture_headers(&response);
        let body = response_to_string(response)?;
        let mut result: ScaniiProcessingResult = parse_json(&body)?;
        attach_processing_headers(&mut result, headers);
        Ok(result)
    }

    /// Verify that the configured credentials reach the API.
    ///
    /// See <https://scanii.github.io/openapi/v22/> — `GET /ping`.
    pub fn ping(&self) -> Result<(), ScaniiError> {
        let response = self.request("GET", "/ping").call()?;
        let _ = require_status(response, 200)?;
        Ok(())
    }

    /// Mint a short-lived auth token. `timeout_seconds` must be positive.
    ///
    /// See <https://scanii.github.io/openapi/v22/> — `POST /auth/tokens`.
    pub fn create_auth_token(&self, timeout_seconds: u64) -> Result<ScaniiAuthToken, ScaniiError> {
        if timeout_seconds == 0 {
            return Err(ScaniiError::Config(
                "timeout_seconds must be positive".into(),
            ));
        }
        let timeout_str = timeout_seconds.to_string();
        let response = self
            .request("POST", "/auth/tokens")
            .send_form(&[("timeout", timeout_str.as_str())])?;

        let status = response.status();
        if status != 200 && status != 201 {
            return Err(error_from_response(response));
        }
        let headers = capture_headers(&response);
        let body = response_to_string(response)?;
        let mut result: ScaniiAuthToken = parse_json(&body)?;
        attach_auth_token_headers(&mut result, headers);
        Ok(result)
    }

    /// Inspect a previously created auth token.
    ///
    /// See <https://scanii.github.io/openapi/v22/> — `GET /auth/tokens/{id}`.
    pub fn retrieve_auth_token(&self, id: &str) -> Result<ScaniiAuthToken, ScaniiError> {
        if id.is_empty() {
            return Err(ScaniiError::Config("id must not be empty".into()));
        }
        let path = format!("/auth/tokens/{}", url_encode(id));
        let response = self.request("GET", &path).call()?;
        let response = require_status(response, 200)?;
        let headers = capture_headers(&response);
        let body = response_to_string(response)?;
        let mut result: ScaniiAuthToken = parse_json(&body)?;
        attach_auth_token_headers(&mut result, headers);
        Ok(result)
    }

    /// Revoke an auth token.
    ///
    /// See <https://scanii.github.io/openapi/v22/> — `DELETE /auth/tokens/{id}`.
    pub fn delete_auth_token(&self, id: &str) -> Result<(), ScaniiError> {
        if id.is_empty() {
            return Err(ScaniiError::Config("id must not be empty".into()));
        }
        let path = format!("/auth/tokens/{}", url_encode(id));
        let response = self.request("DELETE", &path).call()?;
        let _ = require_status(response, 204)?;
        Ok(())
    }

    fn request(&self, method: &str, path: &str) -> Request {
        let url = format!("{}{}", self.base_url, path);
        self.agent
            .request(method, &url)
            .set("Authorization", &self.auth_header)
            .set("User-Agent", &self.user_agent)
            .set("Accept", "application/json")
    }

    fn post_multipart_streaming<R: Read>(
        &self,
        path: &str,
        reader: R,
        filename: &str,
        content_type: &str,
        metadata: Option<&HashMap<String, String>>,
        callback: Option<&str>,
    ) -> Result<Response, ScaniiError> {
        let boundary = multipart::make_boundary();
        let ct = multipart::make_content_type(&boundary);

        let mut fields: HashMap<String, String> = HashMap::new();
        if let Some(m) = metadata {
            for (k, v) in m {
                fields.insert(format!("metadata[{k}]"), v.clone());
            }
        }
        if let Some(cb) = callback {
            fields.insert("callback".into(), cb.to_owned());
        }

        let prologue = multipart::build_prologue(&boundary, filename, content_type, &fields);
        let epilogue = multipart::build_epilogue(&boundary);

        let body = std::io::Cursor::new(prologue)
            .chain(reader)
            .chain(std::io::Cursor::new(epilogue));

        Ok(self
            .request("POST", path)
            .set("Content-Type", &ct)
            .send(body)?)
    }
}

fn path_filename(path: &Path) -> String {
    path.file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| "upload".to_owned())
}

impl ScaniiClientBuilder {
    /// Set the API key. Cannot contain a colon.
    pub fn key(mut self, key: impl Into<String>) -> Self {
        self.key = Some(key.into());
        self
    }

    /// Set the API secret. Pair with [`Self::key`].
    pub fn secret(mut self, secret: impl Into<String>) -> Self {
        self.secret = Some(secret.into());
        self
    }

    /// Authenticate with a previously minted auth-token id instead of `key` + `secret`.
    pub fn token(mut self, token: impl Into<String>) -> Self {
        self.token = Some(token.into());
        self
    }

    /// Set the regional API endpoint via a [`ScaniiTarget`].
    ///
    /// Use a regional constructor for production:
    ///
    /// ```no_run
    /// use scanii::{ScaniiClient, ScaniiTarget};
    /// # fn main() -> Result<(), scanii::ScaniiError> {
    /// let client = ScaniiClient::builder()
    ///     .key("k").secret("s")
    ///     .target(ScaniiTarget::us1())
    ///     .build()?;
    /// # Ok(()) }
    /// ```
    ///
    /// Or [`ScaniiTarget::from_url`] for local scanii-cli testing.
    pub fn target(mut self, target: crate::ScaniiTarget) -> Self {
        self.target = Some(target);
        self
    }

    /// Override the API endpoint as a raw URL string.
    ///
    /// Prefer [`.target()`](ScaniiClientBuilder::target) with a
    /// [`ScaniiTarget`] regional constructor or [`ScaniiTarget::from_url`].
    #[deprecated(
        since = "1.3.0",
        note = "Use .target(ScaniiTarget::us1()) or ScaniiTarget::from_url(...) instead; \
                will be removed in a future major version"
    )]
    pub fn endpoint(mut self, endpoint: impl Into<String>) -> Self {
        self.endpoint = Some(endpoint.into());
        self
    }

    /// Optional user-agent fragment prepended to the SDK's default.
    pub fn user_agent(mut self, ua: impl Into<String>) -> Self {
        self.user_agent = Some(ua.into());
        self
    }

    /// Override the request timeout. Default is 60 seconds.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Validate and assemble the client.
    pub fn build(self) -> Result<ScaniiClient, ScaniiError> {
        let auth_header = if let Some(token) = self.token.as_deref() {
            if self.key.is_some() || self.secret.is_some() {
                return Err(ScaniiError::Config(
                    "supply either token or key+secret, not both".into(),
                ));
            }
            if token.is_empty() {
                return Err(ScaniiError::Config("token must not be empty".into()));
            }
            format!("Basic {}", base64_encode(&format!("{token}:")))
        } else {
            let key = self.key.as_deref().ok_or_else(|| {
                ScaniiError::Config("key must be set (or use token for auth-token mode)".into())
            })?;
            if key.is_empty() {
                return Err(ScaniiError::Config("key must not be empty".into()));
            }
            if key.contains(':') {
                return Err(ScaniiError::Config("key must not contain a colon".into()));
            }
            let secret = self.secret.as_deref().ok_or_else(|| {
                ScaniiError::Config("secret must be set when using key auth".into())
            })?;
            format!("Basic {}", base64_encode(&format!("{key}:{secret}")))
        };

        let endpoint = if let Some(t) = self.target {
            t.url
        } else if let Some(e) = self.endpoint {
            e
        } else {
            eprintln!(
                "[scanii] DEPRECATION: No target set; defaulting to https://api.scanii.com \
                 (AUTO). This does not guarantee regional data placement. Use \
                 .target(ScaniiTarget::us1()) or another regional constructor for explicit data \
                 residency control. The AUTO default will be removed in a future major version."
            );
            DEFAULT_ENDPOINT.to_owned()
        };
        let endpoint = endpoint.trim_end_matches('/').to_owned();
        let base_url = format!("{endpoint}{API_VERSION_PATH}");

        let default_ua = format!("scanii-rust/{VERSION}");
        let user_agent = match self.user_agent {
            Some(prefix) if !prefix.is_empty() => format!("{prefix} {default_ua}"),
            _ => default_ua,
        };

        let timeout = self
            .timeout
            .unwrap_or_else(|| Duration::from_secs(DEFAULT_TIMEOUT_SECS));
        let agent = AgentBuilder::new().timeout(timeout).build();

        Ok(ScaniiClient {
            agent,
            base_url,
            auth_header,
            user_agent,
        })
    }
}

fn require_status(response: Response, expected: u16) -> Result<Response, ScaniiError> {
    if response.status() == expected {
        Ok(response)
    } else {
        Err(error_from_response(response))
    }
}

fn error_from_response(response: Response) -> ScaniiError {
    let status = response.status();
    let request_id = response.header("x-scanii-request-id").map(|s| s.to_owned());
    let retry_after = response
        .header("retry-after")
        .and_then(|s| s.parse::<u64>().ok());
    let body = response.into_string().unwrap_or_default();
    let message = parse_error_message(&body).unwrap_or_else(|| format!("HTTP {status}"));

    match status {
        401 | 403 => ScaniiError::Auth {
            message,
            request_id,
        },
        429 => ScaniiError::RateLimit {
            retry_after,
            message,
            request_id,
        },
        _ => ScaniiError::Http {
            status,
            message,
            request_id,
        },
    }
}

fn parse_error_message(body: &str) -> Option<String> {
    if body.is_empty() {
        return None;
    }
    if let Ok(serde_json::Value::Object(map)) = serde_json::from_str::<serde_json::Value>(body) {
        if let Some(serde_json::Value::String(err)) = map.get("error") {
            return Some(err.clone());
        }
    }
    Some(body.to_owned())
}

fn capture_headers(response: &Response) -> ResponseHeaders {
    ResponseHeaders {
        request_id: response.header("x-scanii-request-id").map(|s| s.to_owned()),
        host_id: response.header("x-scanii-host-id").map(|s| s.to_owned()),
        location: response.header("location").map(|s| s.to_owned()),
    }
}

fn attach_processing_headers(result: &mut ScaniiProcessingResult, h: ResponseHeaders) {
    result.request_id = h.request_id;
    result.host_id = h.host_id;
    result.resource_location = h.location;
}

fn attach_pending_headers(result: &mut ScaniiPendingResult, h: ResponseHeaders) {
    result.request_id = h.request_id;
    result.host_id = h.host_id;
    result.resource_location = h.location;
}

fn attach_auth_token_headers(result: &mut ScaniiAuthToken, h: ResponseHeaders) {
    result.request_id = h.request_id;
    result.host_id = h.host_id;
    result.resource_location = h.location;
}

fn response_to_string(response: Response) -> Result<String, ScaniiError> {
    response
        .into_string()
        .map_err(|e| ScaniiError::Transport(e.to_string()))
}

fn parse_json<T: serde::de::DeserializeOwned>(body: &str) -> Result<T, ScaniiError> {
    serde_json::from_str(body).map_err(ScaniiError::from)
}

fn url_encode(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    for byte in input.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(byte as char);
            }
            _ => {
                out.push_str(&format!("%{byte:02X}"));
            }
        }
    }
    out
}

/// Minimal stdlib-only base64 encoder. Used once per client (auth header).
fn base64_encode(input: &str) -> String {
    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let bytes = input.as_bytes();
    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
    let mut i = 0;
    while i + 3 <= bytes.len() {
        let n =
            (u32::from(bytes[i]) << 16) | (u32::from(bytes[i + 1]) << 8) | u32::from(bytes[i + 2]);
        out.push(ALPHABET[((n >> 18) & 0x3F) as usize] as char);
        out.push(ALPHABET[((n >> 12) & 0x3F) as usize] as char);
        out.push(ALPHABET[((n >> 6) & 0x3F) as usize] as char);
        out.push(ALPHABET[(n & 0x3F) as usize] as char);
        i += 3;
    }
    let remaining = bytes.len() - i;
    if remaining == 1 {
        let n = u32::from(bytes[i]) << 16;
        out.push(ALPHABET[((n >> 18) & 0x3F) as usize] as char);
        out.push(ALPHABET[((n >> 12) & 0x3F) as usize] as char);
        out.push('=');
        out.push('=');
    } else if remaining == 2 {
        let n = (u32::from(bytes[i]) << 16) | (u32::from(bytes[i + 1]) << 8);
        out.push(ALPHABET[((n >> 18) & 0x3F) as usize] as char);
        out.push(ALPHABET[((n >> 12) & 0x3F) as usize] as char);
        out.push(ALPHABET[((n >> 6) & 0x3F) as usize] as char);
        out.push('=');
    }
    out
}

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

    #[test]
    fn builder_rejects_empty_key() {
        let err = ScaniiClient::builder()
            .key("")
            .secret("s")
            .build()
            .unwrap_err();
        assert!(matches!(err, ScaniiError::Config(_)), "got {err:?}");
    }

    #[test]
    fn builder_rejects_colon_in_key() {
        let err = ScaniiClient::builder()
            .key("a:b")
            .secret("s")
            .build()
            .unwrap_err();
        assert!(matches!(err, ScaniiError::Config(_)));
    }

    #[test]
    fn builder_rejects_missing_secret() {
        let err = ScaniiClient::builder().key("k").build().unwrap_err();
        assert!(matches!(err, ScaniiError::Config(_)));
    }

    #[test]
    fn builder_rejects_token_plus_key() {
        let err = ScaniiClient::builder()
            .token("t")
            .key("k")
            .secret("s")
            .build()
            .unwrap_err();
        assert!(matches!(err, ScaniiError::Config(_)));
    }

    #[test]
    fn builder_token_only_succeeds() {
        let _ = ScaniiClient::builder().token("tok").build().unwrap();
    }

    #[test]
    fn base64_known_vectors() {
        assert_eq!(base64_encode(""), "");
        assert_eq!(base64_encode("f"), "Zg==");
        assert_eq!(base64_encode("fo"), "Zm8=");
        assert_eq!(base64_encode("foo"), "Zm9v");
        assert_eq!(base64_encode("foob"), "Zm9vYg==");
        assert_eq!(base64_encode("fooba"), "Zm9vYmE=");
        assert_eq!(base64_encode("foobar"), "Zm9vYmFy");
        assert_eq!(base64_encode("key:secret"), "a2V5OnNlY3JldA==");
    }

    #[test]
    fn url_encode_basic() {
        assert_eq!(url_encode("abc"), "abc");
        assert_eq!(url_encode("a/b"), "a%2Fb");
        assert_eq!(url_encode("a b"), "a%20b");
    }

    #[test]
    fn version_constant_matches_cargo_pkg_version() {
        assert_eq!(VERSION, env!("CARGO_PKG_VERSION"));
    }

    // process_file and process must produce byte-identical multipart bodies
    // for the same content. They go through the same post_multipart_streaming
    // helper, so this asserts that the prologue + reader + epilogue assembly
    // matches whether the file is opened via File::open or supplied as a Cursor.
    #[test]
    fn path_and_reader_paths_produce_equivalent_bodies() {
        use std::io::Read as _;

        let content = b"hello world from a file";
        let dir = std::env::temp_dir();
        let path = dir.join(format!(
            "scanii-rust-equiv-{}-{}.txt",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_nanos())
                .unwrap_or(0)
        ));
        std::fs::write(&path, content).expect("write fixture");

        let boundary = "fixed-boundary-for-test";
        let mut fields = HashMap::new();
        fields.insert("metadata[k]".into(), "v".into());

        let prologue =
            crate::multipart::build_prologue(boundary, "fixture.txt", "text/plain", &fields);
        let epilogue = crate::multipart::build_epilogue(boundary);

        // Reader-source body: stream over Cursor<&[u8]>.
        let mut reader_body = prologue.clone();
        std::io::Cursor::new(content)
            .read_to_end(&mut reader_body)
            .expect("read cursor");
        reader_body.extend_from_slice(&epilogue);

        // Path-source body: stream over File.
        let mut path_body = prologue.clone();
        std::fs::File::open(&path)
            .expect("open fixture")
            .read_to_end(&mut path_body)
            .expect("read file");
        path_body.extend_from_slice(&epilogue);

        assert_eq!(reader_body, path_body);

        let _ = std::fs::remove_file(&path);
    }
}