viceroy-lib 0.17.0

Viceroy implementation details.
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
854
//! Error types.

use crate::{pushpin::PushpinRedirectInfo, wiggle_abi::types::FastlyStatus};
use std::error::Error as StdError;
use std::io;
use url::Url;
use wiggle::GuestError;

#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// Thrown by hostcalls when a buffer is larger than its `*_len` limit.
    #[error("Buffer length error: {buf} too long to fit in {len}")]
    BufferLengthError {
        buf: &'static str,
        len: &'static str,
    },

    /// Error when viceroy has encountered a fatal error and the underlying wasmtime
    /// instance must be terminated with a Trap.
    #[error("Fatal error: [{0}]")]
    FatalError(String),

    /// Error when viceroy has been given an invalid file.
    #[error("Expected a valid Wasm file")]
    FileFormat,

    #[error("Expected a valid wastime's profiling strategy")]
    ProfilingStrategy,

    #[error(transparent)]
    FastlyConfig(#[from] FastlyConfigError),

    #[error("Could not determine address from backend URL: {0}")]
    BackendUrl(Url),

    /// An error from guest-provided arguments to a hostcall. These errors may be created
    /// automatically by the Wiggle-generated glue code that converts parameters from their ABI
    /// representation into richer Rust types, or by fallible methods of `GuestPtr` in the
    /// wiggle_abi trait implementations.
    #[error("Guest error: [{0}]")]
    GuestError(#[from] wiggle::GuestError),

    #[error(transparent)]
    HandleError(#[from] HandleError),

    #[error(transparent)]
    HyperError(#[from] hyper::Error),

    #[error(transparent)]
    Infallible(#[from] std::convert::Infallible),

    /// Error when an invalid argument is supplied to a hostcall.
    #[error("Invalid argument given")]
    InvalidArgument,

    #[error(transparent)]
    InvalidHeaderName(#[from] http::header::InvalidHeaderName),

    #[error(transparent)]
    InvalidHeaderValue(#[from] http::header::InvalidHeaderValue),

    #[error(transparent)]
    InvalidMethod(#[from] http::method::InvalidMethod),

    #[error(transparent)]
    InvalidStatusCode(#[from] http::status::InvalidStatusCode),

    #[error(transparent)]
    InvalidUri(#[from] http::uri::InvalidUri),

    #[error(transparent)]
    IoError(#[from] std::io::Error),

    #[error("Limit exceeded: {msg}")]
    LimitExceeded { msg: &'static str },

    #[error("Missing downstream metadata for request")]
    MissingDownstreamMetadata,

    #[error(transparent)]
    Other(#[from] anyhow::Error),

    #[error("Unsupported operation: {msg}")]
    Unsupported { msg: &'static str },

    /// Downstream response is already sending.
    #[error("Downstream response already sending")]
    DownstreamRespSending,

    #[error("Unexpected error sending a chunk to a streaming body")]
    StreamingChunkSend,

    #[error("Unknown backend: {0}")]
    UnknownBackend(String),

    #[error(transparent)]
    DictionaryError(#[from] crate::wiggle_abi::DictionaryError),

    #[error(transparent)]
    DeviceDetectionError(#[from] crate::wiggle_abi::DeviceDetectionError),

    #[error(transparent)]
    ObjectStoreError(#[from] crate::object_store::ObjectStoreError),

    #[error(transparent)]
    KvStoreError(#[from] crate::object_store::KvStoreError),

    #[error(transparent)]
    SecretStoreError(#[from] crate::wiggle_abi::SecretStoreError),

    #[error{"Expected UTF-8"}]
    Utf8Expected(#[from] std::str::Utf8Error),

    #[error{"Unsupported ABI version"}]
    AbiVersionMismatch,

    #[error(transparent)]
    DownstreamRequestError(#[from] DownstreamRequestError),

    #[error("{0} is not currently supported for local testing")]
    NotAvailable(&'static str),

    #[error("Could not load native certificates: {0}")]
    BadCerts(std::io::Error),

    #[error("No CA certificates available")]
    TlsNoCAAvailable,

    #[error("No valid CA certificates found in provided certificate bundle")]
    TlsNoValidCACerts,

    #[error("Invalid or missing host for TLS connection")]
    TlsInvalidHost,

    #[error("TLS certificate validation failed")]
    TlsCertificateValidationFailed,

    #[error("Could not generate new backend name from '{0}'")]
    BackendNameRegistryError(String),

    #[error(transparent)]
    HttpError(#[from] http::Error),

    #[error("Object Store '{0}' does not exist")]
    UnknownObjectStore(String),

    #[error("Invalid Object Store `key` value used: {0}.")]
    ObjectStoreKeyValidationError(#[from] crate::object_store::KeyValidationError),

    #[error("Unfinished streaming body")]
    UnfinishedStreamingBody,

    #[error("Shared memory not supported yet")]
    SharedMemory,

    #[error("Value absent from structure")]
    ValueAbsent,

    #[error("String conversion error")]
    ToStr(#[from] http::header::ToStrError),

    #[error("invalid client certificate")]
    InvalidClientCert(#[from] crate::config::ClientCertError),

    #[error("Invalid response to ALPN request; wanted '{0}', got '{1}'")]
    InvalidAlpnResponse(&'static str, String),

    #[error("Resource temporarily unavailable")]
    Again,

    #[error("cache error: {0}")]
    CacheError(crate::cache::Error),
}

impl Error {
    /// Convert to an error code representation suitable for passing across the ABI boundary.
    ///
    /// For more information about specific error codes see [`fastly_shared::FastlyStatus`][status],
    /// as well as the `witx` interface definition located in `wasm_abi/typenames.witx`.
    ///
    /// [status]: fastly_shared/struct.FastlyStatus.html
    pub fn to_fastly_status(&self) -> FastlyStatus {
        match self {
            Error::BufferLengthError { .. } => FastlyStatus::Buflen,
            Error::InvalidArgument => FastlyStatus::Inval,
            Error::ValueAbsent => FastlyStatus::None,
            Error::Unsupported { .. } | Error::NotAvailable(_) => FastlyStatus::Unsupported,
            Error::HandleError { .. } => FastlyStatus::Badf,
            Error::InvalidStatusCode { .. } => FastlyStatus::Inval,
            Error::UnknownBackend(_) | Error::InvalidClientCert(_) => FastlyStatus::Inval,
            // Map specific kinds of `hyper::Error` into their respective error codes.
            Error::HyperError(e) if e.is_parse() => FastlyStatus::Httpinvalid,
            Error::HyperError(e) if e.is_user() => FastlyStatus::Httpuser,
            Error::HyperError(e) if e.is_incomplete_message() => FastlyStatus::Httpincomplete,
            Error::HyperError(e)
                if e.source()
                    .and_then(|e| e.downcast_ref::<io::Error>())
                    .map(|ioe| ioe.kind())
                    == Some(io::ErrorKind::UnexpectedEof) =>
            {
                FastlyStatus::Httpincomplete
            }
            Error::HyperError(_) => FastlyStatus::Error,
            // Destructuring a GuestError is recursive, so we use a helper function:
            Error::GuestError(e) => Self::guest_error_fastly_status(e),
            // We delegate to some error types' own implementation of `to_fastly_status`.
            Error::DictionaryError(e) => e.to_fastly_status(),
            Error::DeviceDetectionError(e) => e.to_fastly_status(),
            Error::ObjectStoreError(e) => e.into(),
            Error::KvStoreError(e) => e.into(),
            Error::SecretStoreError(e) => e.into(),
            Error::Again => FastlyStatus::Again,
            Error::LimitExceeded { .. } => FastlyStatus::Limitexceeded,
            Error::CacheError(e) => e.into(),
            // All other hostcall errors map to a generic `ERROR` value.
            Error::AbiVersionMismatch
            | Error::BackendUrl(_)
            | Error::BadCerts(_)
            | Error::TlsNoCAAvailable
            | Error::TlsNoValidCACerts
            | Error::TlsInvalidHost
            | Error::TlsCertificateValidationFailed
            | Error::DownstreamRequestError(_)
            | Error::DownstreamRespSending
            | Error::FastlyConfig(_)
            | Error::FatalError(_)
            | Error::FileFormat
            | Error::Infallible(_)
            | Error::InvalidHeaderName(_)
            | Error::InvalidHeaderValue(_)
            | Error::InvalidMethod(_)
            | Error::InvalidUri(_)
            | Error::IoError(_)
            | Error::MissingDownstreamMetadata
            | Error::Other(_)
            | Error::ProfilingStrategy
            | Error::StreamingChunkSend
            | Error::Utf8Expected(_)
            | Error::BackendNameRegistryError(_)
            | Error::HttpError(_)
            | Error::UnknownObjectStore(_)
            | Error::ObjectStoreKeyValidationError(_)
            | Error::UnfinishedStreamingBody
            | Error::SharedMemory
            | Error::ToStr(_)
            | Error::InvalidAlpnResponse(_, _) => FastlyStatus::Error,
        }
    }

    fn guest_error_fastly_status(e: &GuestError) -> FastlyStatus {
        use GuestError::*;
        match e {
            PtrNotAligned { .. } => FastlyStatus::Badalign,
            // We may want to expand the FastlyStatus enum to distinguish between more of these
            // values.
            InvalidFlagValue { .. }
            | InvalidEnumValue { .. }
            | PtrOutOfBounds { .. }
            | PtrOverflow
            | InvalidUtf8 { .. }
            | TryFromIntError { .. } => FastlyStatus::Inval,
            // These errors indicate either a pathological user input or an internal programming
            // error
            SliceLengthsDiffer => FastlyStatus::Error,
            // Recursive case: InFunc wraps a GuestError with some context which
            // doesn't determine what sort of FastlyStatus we return.
            InFunc { err, .. } => Self::guest_error_fastly_status(err),
        }
    }
}

/// Errors thrown due to an invalid resource handle of some kind.
#[derive(Debug, thiserror::Error)]
pub enum HandleError {
    /// A request handle was not valid.
    #[error("Invalid request handle: {0}")]
    InvalidRequestHandle(crate::wiggle_abi::types::RequestHandle),

    /// A response handle was not valid.
    #[error("Invalid response handle: {0}")]
    InvalidResponseHandle(crate::wiggle_abi::types::ResponseHandle),

    /// A body handle was not valid.
    #[error("Invalid body handle: {0}")]
    InvalidBodyHandle(crate::wiggle_abi::types::BodyHandle),

    /// A logging endpoint handle was not valid.
    #[error("Invalid endpoint handle: {0}")]
    InvalidEndpointHandle(crate::wiggle_abi::types::EndpointHandle),

    /// A request handle was not valid.
    #[error("Invalid pending request promise handle: {0}")]
    InvalidPendingRequestHandle(crate::wiggle_abi::types::PendingRequestHandle),

    /// A request handle was not valid.
    #[error("Invalid pending downstream request handle: {0}")]
    InvalidPendingDownstreamHandle(crate::wiggle_abi::types::AsyncItemHandle),

    /// A lookup handle was not valid.
    #[error("Invalid pending KV lookup handle: {0}")]
    InvalidPendingKvLookupHandle(crate::wiggle_abi::types::PendingKvLookupHandle),

    /// A insert handle was not valid.
    #[error("Invalid pending KV insert handle: {0}")]
    InvalidPendingKvInsertHandle(crate::wiggle_abi::types::PendingKvInsertHandle),

    /// A delete handle was not valid.
    #[error("Invalid pending KV delete handle: {0}")]
    InvalidPendingKvDeleteHandle(crate::wiggle_abi::types::PendingKvDeleteHandle),

    /// A list handle was not valid.
    #[error("Invalid pending KV list handle: {0}")]
    InvalidPendingKvListHandle(crate::wiggle_abi::types::PendingKvListHandle),

    /// A dictionary handle was not valid.
    #[error("Invalid dictionary handle: {0}")]
    InvalidDictionaryHandle(crate::wiggle_abi::types::DictionaryHandle),

    /// An object-store handle was not valid.
    #[error("Invalid object-store handle: {0}")]
    InvalidObjectStoreHandle(crate::wiggle_abi::types::ObjectStoreHandle),

    /// A secret store handle was not valid.
    #[error("Invalid secret store handle: {0}")]
    InvalidSecretStoreHandle(crate::wiggle_abi::types::SecretStoreHandle),

    /// A secret handle was not valid.
    #[error("Invalid secret handle: {0}")]
    InvalidSecretHandle(crate::wiggle_abi::types::SecretHandle),

    /// An async item handle was not valid.
    #[error("Invalid async item handle: {0}")]
    InvalidAsyncItemHandle(crate::wiggle_abi::types::AsyncItemHandle),

    /// An acl handle was not valid.
    #[error("Invalid acl handle: {0}")]
    InvalidAclHandle(crate::wiggle_abi::types::AclHandle),

    /// A cache handle was not valid.
    #[error("Invalid cache handle: {0}")]
    InvalidCacheHandle(crate::wiggle_abi::types::CacheHandle),
}

/// Errors that can occur in a worker thread running a guest module.
///
/// See [`ExecuteCtx::handle_request`][handle_request] and [`ExecuteCtx::run_guest`][run_guest] for
/// more information about guest execution.
///
/// [handle_request]: ../execute/struct.ExecuteCtx.html#method.handle_request
/// [run_guest]: ../execute/struct.ExecuteCtx.html#method.run_guest
#[derive(Debug, thiserror::Error)]
pub(crate) enum ExecutionError {
    /// Errors thrown by the guest's entrypoint.
    ///
    /// See [`wasmtime::Func::call`][call] for more information.
    ///
    /// [call]: https://docs.rs/wasmtime/latest/wasmtime/struct.Func.html#method.call
    #[error("WebAssembly execution trapped: {0}")]
    WasmTrap(anyhow::Error),

    /// Errors thrown when trying to instantiate a guest context.
    #[error("Error creating context: {0}")]
    Context(anyhow::Error),

    /// Errors thrown when type-checking WebAssembly before instantiation
    #[error("Error type-checking WebAssembly instantiation: {0}")]
    Typechecking(anyhow::Error),

    /// Errors thrown when trying to instantiate a guest module.
    #[error("Error instantiating WebAssembly: {0}")]
    Instantiation(anyhow::Error),
}

/// Errors that can occur while parsing a `fastly.toml` file.
#[derive(Debug, thiserror::Error)]
pub enum FastlyConfigError {
    /// An I/O error that occurred while reading the file.
    #[error("error reading '{path}': {err}")]
    IoError {
        path: String,
        #[source]
        err: std::io::Error,
    },

    #[error("invalid configuration for '{name}': {err}")]
    InvalidDeviceDetectionDefinition {
        name: String,
        #[source]
        err: DeviceDetectionConfigError,
    },

    #[error("invalid configuration for '{name}': {err}")]
    InvalidGeolocationDefinition {
        name: String,
        #[source]
        err: GeolocationConfigError,
    },

    #[error("invalid configuration for '{name}': {err}")]
    InvalidAclDefinition {
        name: String,
        #[source]
        err: AclConfigError,
    },

    #[error("invalid configuration for '{name}': {err}")]
    InvalidBackendDefinition {
        name: String,
        #[source]
        err: BackendConfigError,
    },

    #[error("invalid configuration for '{name}': {err}")]
    InvalidDictionaryDefinition {
        name: String,
        #[source]
        err: DictionaryConfigError,
    },

    #[error("invalid configuration for '{name}': {err}")]
    InvalidObjectStoreDefinition {
        name: String,
        #[source]
        err: ObjectStoreConfigError,
    },

    #[error("invalid configuration for '{name}': {err}")]
    InvalidSecretStoreDefinition {
        name: String,
        #[source]
        err: SecretStoreConfigError,
    },

    #[error("invalid configuration for '{name}': {err}")]
    InvalidShieldingSiteDefinition {
        name: String,
        #[source]
        err: ShieldingSiteConfigError,
    },

    /// An error that occurred while deserializing the file.
    ///
    /// This represents errors caused by syntactically invalid TOML data, missing fields, etc.
    #[error("error parsing `fastly.toml`: {0}")]
    InvalidFastlyToml(#[from] toml::de::Error),

    /// The `manifest_version` field contained a value greater than is
    /// currently supported.
    #[error("unsupported manifest version {0}; max supported version is {1}")]
    UnsupportedManifestVersion(u32, u32),
}

/// Errors that may occur while validating acl configurations.
#[derive(Debug, thiserror::Error)]
pub enum AclConfigError {
    /// An I/O error that occurred while processing a file.
    #[error(transparent)]
    IoError(std::io::Error),

    /// An error occurred parsing JSON.
    #[error(transparent)]
    JsonError(serde_json::error::Error),

    #[error("acl must be a TOML table or string")]
    InvalidType,

    #[error("missing 'file' field")]
    MissingFile,
}

/// Errors that may occur while validating backend configurations.
#[derive(Debug, thiserror::Error)]
pub enum BackendConfigError {
    #[error("definition was not provided as a TOML table")]
    InvalidEntryType,

    #[error("invalid override_host: {0}")]
    InvalidOverrideHost(#[from] http::header::InvalidHeaderValue),

    #[error("'override_host' field is empty")]
    EmptyOverrideHost,

    #[error("'override_host' field was not a string")]
    InvalidOverrideHostEntry,

    #[error("'cert_host' field is empty")]
    EmptyCertHost,

    #[error("'cert_host' field was not a string")]
    InvalidCertHostEntry,

    #[error("'ca_certificate' field is empty")]
    EmptyCACert,

    #[error("'ca_certificate' field was invalid: {0}")]
    InvalidCACertEntry(String),

    #[error("'use_sni' field was not a boolean")]
    InvalidUseSniEntry,

    #[error("'grpc' field was not a boolean")]
    InvalidGrpcEntry,

    #[error(
        "'health' field has invalid value '{0}' (expected 'unknown', 'healthy', or 'unhealthy')"
    )]
    InvalidHealthEntry(String),

    #[error("invalid url: {0}")]
    InvalidUrl(#[from] http::uri::InvalidUri),

    #[error("'url' field was not a string")]
    InvalidUrlEntry,

    #[error("no default definition provided")]
    MissingDefault,

    #[error("missing 'url' field")]
    MissingUrl,

    #[error("unrecognized key '{0}'")]
    UnrecognizedKey(String),

    #[error(transparent)]
    ClientCertError(#[from] crate::config::ClientCertError),
}

/// Errors that may occur while validating dictionary configurations.
#[derive(Debug, thiserror::Error)]
pub enum DictionaryConfigError {
    /// An I/O error that occurred while reading the file.
    #[error(transparent)]
    IoError(std::io::Error),

    #[error("'contents' was not provided as a TOML table")]
    InvalidContentsType,

    #[error("inline dictionary value was not a string")]
    InvalidInlineEntryType,

    #[error("definition was not provided as a TOML table")]
    InvalidEntryType,

    #[error("'name' field was not a string")]
    InvalidNameEntry,

    #[error(
        "'{0}' is not a valid format for the dictionary. Supported format(s) are: 'inline-toml', 'json'."
    )]
    InvalidDictionaryFormat(String),

    #[error("'file' field is empty")]
    EmptyFileEntry,

    #[error("'format' field is empty")]
    EmptyFormatEntry,

    #[error("'file' field was not a string")]
    InvalidFileEntry,

    #[error("'format' field was not a string")]
    InvalidFormatEntry,

    #[error("missing 'contents' field")]
    MissingContents,

    #[error("no default definition provided")]
    MissingDefault,

    #[error("missing 'name' field")]
    MissingName,

    #[error("missing 'file' field")]
    MissingFile,

    #[error("missing 'format' field")]
    MissingFormat,

    #[error("unrecognized key '{0}'")]
    UnrecognizedKey(String),

    #[error("Item key named '{key}' is too long, max size is {size}")]
    DictionaryItemKeyTooLong { key: String, size: i32 },

    #[error("too many items, max amount is {size}")]
    DictionaryCountTooLong { size: i32 },

    #[error(
        "Item value under key named '{key}' is of the wrong format. The value is expected to be a JSON String"
    )]
    DictionaryItemValueWrongFormat { key: String },

    #[error("Item value named '{key}' is too long, max size is {size}")]
    DictionaryItemValueTooLong { key: String, size: i32 },

    #[error(
        "The file is of the wrong format. The file is expected to contain a single JSON Object"
    )]
    DictionaryFileWrongFormat,
}

/// Errors that may occur while validating device detection configurations.
#[derive(Debug, thiserror::Error)]
pub enum DeviceDetectionConfigError {
    /// An I/O error that occurred while reading the file.
    #[error(transparent)]
    IoError(std::io::Error),

    #[error("definition was not provided as a TOML table")]
    InvalidEntryType,

    #[error("missing 'file' field")]
    MissingFile,

    #[error("'file' field is empty")]
    EmptyFileEntry,

    #[error("missing 'user_agents' field")]
    MissingUserAgents,

    #[error("inline device detection value was not a string")]
    InvalidInlineEntryType,

    #[error("'file' field was not a string")]
    InvalidFileEntry,

    #[error("'user_agents' was not provided as a TOML table")]
    InvalidUserAgentsType,

    #[error("unrecognized key '{0}'")]
    UnrecognizedKey(String),

    #[error("missing 'format' field")]
    MissingFormat,

    #[error("'format' field was not a string")]
    InvalidFormatEntry,

    #[error(
        "'{0}' is not a valid format for the device detection mapping. Supported format(s) are: 'inline-toml', 'json'."
    )]
    InvalidDeviceDetectionMappingFormat(String),

    #[error(
        "The file is of the wrong format. The file is expected to contain a single JSON Object"
    )]
    DeviceDetectionFileWrongFormat,

    #[error("'format' field is empty")]
    EmptyFormatEntry,

    #[error(
        "Item value under key named '{key}' is of the wrong format. The value is expected to be a JSON String"
    )]
    DeviceDetectionItemValueWrongFormat { key: String },
}

/// Errors that may occur while validating geolocation configurations.
#[derive(Debug, thiserror::Error)]
pub enum GeolocationConfigError {
    /// An I/O error that occurred while reading the file.
    #[error(transparent)]
    IoError(std::io::Error),

    #[error("definition was not provided as a TOML table")]
    InvalidEntryType,

    #[error("missing 'file' field")]
    MissingFile,

    #[error("'file' field is empty")]
    EmptyFileEntry,

    #[error("missing 'addresses' field")]
    MissingAddresses,

    #[error("inline geolocation value was not a string")]
    InvalidInlineEntryType,

    #[error("'file' field was not a string")]
    InvalidFileEntry,

    #[error("'addresses' was not provided as a TOML table")]
    InvalidAddressesType,

    #[error("unrecognized key '{0}'")]
    UnrecognizedKey(String),

    #[error("missing 'format' field")]
    MissingFormat,

    #[error("'format' field was not a string")]
    InvalidFormatEntry,

    #[error("IP address not valid: '{0}'")]
    InvalidAddressEntry(String),

    #[error(
        "'{0}' is not a valid format for the geolocation mapping. Supported format(s) are: 'inline-toml', 'json'."
    )]
    InvalidGeolocationMappingFormat(String),

    #[error(
        "The file is of the wrong format. The file is expected to contain a single JSON Object"
    )]
    GeolocationFileWrongFormat,

    #[error("'format' field is empty")]
    EmptyFormatEntry,

    #[error(
        "Item value under key named '{key}' is of the wrong format. The value is expected to be a JSON String"
    )]
    GeolocationItemValueWrongFormat { key: String },
}

/// Errors that may occur while validating object store configurations.
#[derive(Debug, thiserror::Error)]
pub enum ObjectStoreConfigError {
    /// An I/O error that occurred while reading the file.
    #[error(transparent)]
    IoError(std::io::Error),
    #[error("The `file` and `data` keys for the object `{0}` are set. Only one can be used.")]
    FileAndData(String),
    #[error("The `file` or `data` key for the object `{0}` is not set. One must be used.")]
    NoFileOrData(String),
    #[error("The `data` value for the object `{0}` is not a string.")]
    DataNotAString(String),
    #[error("The `metadata` value for the object `{0}` is not a string.")]
    MetadataNotAString(String),
    #[error("The `file` value for the object `{0}` is not a string.")]
    FileNotAString(String),
    #[error("The `key` key for an object is not set. It must be used.")]
    NoKey,
    #[error("The `key` value for an object is not a string.")]
    KeyNotAString,
    #[error("There is no array of objects for the given store.")]
    NotAnArray,
    #[error("There is an object in the given store that is not a table of keys.")]
    NotATable,
    #[error("There was an error when manipulating the ObjectStore: {0}.")]
    ObjectStoreError(#[from] crate::object_store::ObjectStoreError),
    #[error("There was an error when manipulating the KvStore: {0}.")]
    KvStoreError(#[from] crate::object_store::KvStoreError),
    #[error("Invalid `key` value used: {0}.")]
    KeyValidationError(#[from] crate::object_store::KeyValidationError),
    #[error("'{0}' is not a valid format for the config store. Supported format(s) are: 'json'.")]
    InvalidFileFormat(String),
    #[error("When using a top-level 'file' to load data, both 'file' and 'format' must be set.")]
    OnlyOneFormatOrFileSet,
    #[error(
        "The file is of the wrong format. The file is expected to contain a single JSON Object."
    )]
    FileWrongFormat,
    #[error(
        "Item value under key named '{key}' is of the wrong format. The value is expected to be a JSON String."
    )]
    FileValueWrongFormat { key: String },
    #[error(
        "Item value under key named '{key}' is of the wrong format. 'data' and 'file' are mutually exclusive."
    )]
    BothDataAndFilePresent { key: String },
    #[error(
        "Item value under key named '{key}' is of the wrong format. One of 'data' or 'file' must be present."
    )]
    MissingDataOrFile { key: String },
}

/// Errors that may occur while validating secret store configurations.
#[derive(Debug, thiserror::Error)]
pub enum SecretStoreConfigError {
    /// An I/O error that occurred while reading the file.
    #[error(transparent)]
    IoError(std::io::Error),

    #[error("'{0}' is not a valid format for the secret store. Supported format(s) are: 'json'.")]
    InvalidFileFormat(String),
    #[error("When using a top-level 'file' to load data, both 'file' and 'format' must be set.")]
    OnlyOneFormatOrFileSet,
    #[error(
        "The file is of the wrong format. The file is expected to contain a single JSON object."
    )]
    FileWrongFormat,
    #[error(
        "More than one of `file`, `data`, or `env` keys for the object `{0}` are set. Only one can be used."
    )]
    FileDataEnvExclusive(String),
    #[error("None of `file`, `data`, or `env` keys for the object `{0}` is set. One must be used.")]
    FileDataEnvNotSet(String),
    #[error("The `data` value for the object `{0}` is not a string.")]
    DataNotAString(String),
    #[error("The `file` value for the object `{0}` is not a string.")]
    FileNotAString(String),
    #[error("The `env` value for the object `{0}` is not a string.")]
    EnvNotAString(String),

    #[error("The `key` key for an object is not set. It must be used.")]
    NoKey,
    #[error("The `key` value for an object is not a string.")]
    KeyNotAString,

    #[error("There is no array of objects for the given store.")]
    NotAnArray,
    #[error("There is an object in the given store that is not a table of keys.")]
    NotATable,

    #[error("Invalid secret store name: {0}")]
    InvalidSecretStoreName(String),

    #[error("Invalid secret name: {0}")]
    InvalidSecretName(String),
}

/// Errors that may occur while validating shielding site configurations.
#[derive(Debug, thiserror::Error)]
pub enum ShieldingSiteConfigError {
    #[error(
        "Illegal TOML value for shielding site; must be either the string 'local' or a table containing an encrypted and unencrypted URL."
    )]
    IllegalSiteValue,

    #[error("Illegal TOML string for shielding site; must be 'local'")]
    IllegalSiteString,

    #[error(
        "Illegal table for shielding site; must have exactly one key named 'encrypted', and one named 'unencrypted'"
    )]
    IllegalSiteDefinition,

    #[error("Illegal URL ({url}): {error}")]
    IllegalUrl { url: String, error: url::ParseError },
}

/// Errors related to the downstream request.
#[derive(Debug, thiserror::Error)]
pub enum DownstreamRequestError {
    #[error("Request HOST header is missing or invalid")]
    InvalidHost,

    #[error("Request URL is invalid")]
    InvalidUrl,
}

/// An enum representing outcomes where the guest does not produce a standard
/// HTTP response, but instead signals for a different action.
#[derive(Debug, thiserror::Error)]
pub enum NonHttpResponse {
    #[error("graceful Pushpin redirect")]
    PushpinRedirect(PushpinRedirectInfo),
    // In the future, e.g.
    // #[error("websocket upgrade requested")]
    // WebSocketUpgrade(WebSocketUpgradeInfo),
}