Skip to main content

stealth_oxide/
error.rs

1use chromiumoxide::error::CdpError;
2
3use crate::config::Patch;
4
5/// Collection of consistency issues rejected by strict validation.
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub struct ValidationErrors(Vec<ValidationIssue>);
8
9impl ValidationErrors {
10    /// Borrows every reported issue.
11    pub fn issues(&self) -> &[ValidationIssue] {
12        &self.0
13    }
14
15    /// Consumes the collection and returns its issues.
16    pub fn into_issues(self) -> Vec<ValidationIssue> {
17        self.0
18    }
19}
20
21impl From<Vec<ValidationIssue>> for ValidationErrors {
22    fn from(issues: Vec<ValidationIssue>) -> Self {
23        Self(issues)
24    }
25}
26
27impl std::fmt::Display for ValidationErrors {
28    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29        for (index, issue) in self.0.iter().enumerate() {
30            if index > 0 {
31                formatter.write_str("; ")?;
32            }
33            std::fmt::Display::fmt(issue, formatter)?;
34        }
35        Ok(())
36    }
37}
38
39/// A known consistency or configuration problem.
40#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
41#[non_exhaustive]
42pub enum ValidationIssue {
43    /// A required text value is empty.
44    #[error("{field} must not be empty")]
45    EmptyValue {
46        /// Stable field name.
47        field: &'static str,
48    },
49    /// Screen dimensions are invalid.
50    #[error("screen dimensions must be greater than zero")]
51    InvalidScreenDimensions,
52    /// Available work-area dimensions exceed the screen.
53    #[error("available screen dimensions cannot exceed screen dimensions")]
54    WorkAreaExceedsScreen,
55    /// Device scale factor is invalid.
56    #[error("device scale factor must be finite and greater than zero")]
57    InvalidScaleFactor,
58    /// Locale and primary navigator language disagree.
59    #[error("the first navigator language must match the Intl locale")]
60    LocaleLanguageMismatch,
61    /// Touch state and point count disagree.
62    #[error("touch configuration is contradictory")]
63    TouchContradiction,
64    /// User agent, navigator platform, and Client Hints platform disagree.
65    #[error("user agent, navigator platform, and UA Client Hints platform disagree")]
66    PlatformMismatch,
67    /// User-agent and Client Hint Chrome versions disagree.
68    #[error("Chrome user-agent and UA Client Hints versions disagree")]
69    ChromeVersionMismatch,
70    /// A Client Hint brand occurs more than once.
71    #[error("duplicate UA Client Hint brand: {brand}")]
72    DuplicateBrand {
73        /// Duplicated brand name.
74        brand: String,
75    },
76    /// Reduced and full UA Client Hint brand sets disagree.
77    #[error("reduced and full UA Client Hint brand sets disagree")]
78    ClientHintBrandSetMismatch,
79    /// Required Chromium and Google Chrome brand entries are missing.
80    #[error("UA Client Hints must include Chromium and Google Chrome brands")]
81    MissingChromeBrands,
82    /// WoW64 is only valid for a 32-bit x86 Windows browser identity.
83    #[error("UA Client Hint WoW64 metadata is incompatible with the identity")]
84    InvalidWow64,
85    /// Architecture and bitness are not a supported Client Hint combination.
86    #[error("UA Client Hint architecture and bitness are incompatible")]
87    InvalidArchitectureBitness,
88    /// Model and form-factor metadata contradict the mobile state.
89    #[error("UA Client Hint model and form factors contradict the mobile state")]
90    MobileMetadataMismatch,
91    /// Platform version does not follow the platform's expected format.
92    #[error("UA Client Hint platform version has an invalid format")]
93    InvalidPlatformVersion,
94}
95
96/// Error returned while validating a profile or applying a CDP patch.
97#[derive(Debug, thiserror::Error)]
98#[non_exhaustive]
99pub enum Error {
100    /// A nested target command could not be encoded for CDP transport.
101    #[error("failed to encode a target-session CDP command: {0}")]
102    TargetCommandJson(serde_json::Error),
103
104    /// A network-interceptor header policy contains an unsafe or invalid value.
105    #[cfg(feature = "interceptor")]
106    #[error("invalid interceptor header policy: {message}")]
107    InvalidInterceptorHeader {
108        /// Description of the rejected header mutation.
109        message: String,
110    },
111
112    /// A profile seed document contains an invalid value.
113    #[cfg(feature = "seeding")]
114    #[error("invalid profile seed: {message}")]
115    InvalidSeed {
116        /// Description of the invalid seed value.
117        message: String,
118    },
119
120    /// A profile seed could not be decoded from JSON.
121    #[cfg(feature = "seeding")]
122    #[error("invalid profile seed JSON: {0}")]
123    SeedJson(#[from] serde_json::Error),
124
125    /// Strict validation rejected one or more known contradictions.
126    #[error("stealth configuration failed validation: {issues}")]
127    Validation {
128        /// All issues discovered before patch execution.
129        issues: ValidationErrors,
130    },
131
132    /// A typed CDP parameter builder rejected the supplied profile value.
133    #[error("failed to build the {patch} CDP parameters: {message}")]
134    InvalidPatchParameters {
135        /// Stable name of the patch that failed.
136        patch: &'static str,
137        /// Error returned by the generated CDP builder.
138        message: String,
139    },
140
141    /// Chromium rejected a CDP command while applying a patch.
142    #[error("failed to apply the {patch} CDP patch: {source}")]
143    Cdp {
144        /// Stable name of the patch that failed.
145        patch: &'static str,
146        /// Original Chromiumoxide error.
147        #[source]
148        source: CdpError,
149    },
150
151    /// A patch failed after earlier operations may already have succeeded.
152    #[error("failed to apply {patch:?} after applying {applied:?}: {source}")]
153    Apply {
154        /// Patch that failed.
155        patch: Patch,
156        /// Patches successfully applied before the failure.
157        applied: Vec<Patch>,
158        /// Original patch construction or Chromiumoxide error.
159        #[source]
160        source: Box<Error>,
161    },
162}
163
164impl Error {
165    #[cfg(feature = "interceptor")]
166    pub(crate) fn invalid_interceptor_header(message: impl Into<String>) -> Self {
167        Self::InvalidInterceptorHeader {
168            message: message.into(),
169        }
170    }
171
172    #[cfg(feature = "seeding")]
173    pub(crate) fn invalid_seed(message: impl Into<String>) -> Self {
174        Self::InvalidSeed {
175            message: message.into(),
176        }
177    }
178
179    pub(crate) fn invalid_parameters(patch: &'static str, message: impl Into<String>) -> Self {
180        Self::InvalidPatchParameters {
181            patch,
182            message: message.into(),
183        }
184    }
185
186    pub(crate) fn target_command_json(source: serde_json::Error) -> Self {
187        Self::TargetCommandJson(source)
188    }
189
190    pub(crate) fn cdp(patch: &'static str, source: CdpError) -> Self {
191        Self::Cdp { patch, source }
192    }
193}
194
195/// Result type returned by `stealth-oxide`.
196pub type Result<T> = std::result::Result<T, Error>;