1use krizaka_rust::files::FilesError;
8use krizaka_rust::menu::MenuError;
9use krizaka_rust::nav_guard::OriginError;
10use krizaka_rust::scope::ScopeError;
11use krizaka_rust::secrets::SecretError;
12use krizaka_rust::settings::SettingsError;
13use krizaka_rust::update::{FeedError, MissingPubkey};
14use serde::ser::SerializeStruct;
15use serde::{Serialize, Serializer};
16use std::fmt;
17use std::sync::{Mutex, MutexGuard};
18
19pub const CODES: &[(&str, &str)] = &[
21 (
22 "scope_forbidden",
23 "this folder is too broad or too sensitive to be granted",
24 ),
25 ("scope_not_found", "the path does not exist"),
26 ("scope_outside", "the path is outside the granted folders"),
27 ("scope_io", "the folder grants could not be read or saved"),
28 ("files_io", "the folder or file could not be read"),
29 ("files_not_a_file", "this is not a file"),
30 ("secret_bad_key", "not a secret key"),
31 ("secret_bad_value", "not a value the Keychain keeps"),
32 ("secret_store_failed", "the secret store failed"),
33 ("settings_no_folder", "the settings path has no folder"),
34 (
35 "settings_not_a_file_name",
36 "the settings path is not a file name",
37 ),
38 ("settings_io", "the settings file could not be written"),
39 ("settings_encode", "the settings could not be encoded"),
40 (
41 "menu_bad_standard_label",
42 "a standard menu label is not valid",
43 ),
44 ("menu_bad_menu_title", "a menu title is not valid"),
45 ("menu_bad_item_label", "a menu item label is not valid"),
46 ("menu_too_many_menus", "too many menus"),
47 ("menu_bad_item_count", "a menu has no item or too many"),
48 ("menu_bad_id", "a menu item id is not valid"),
49 ("menu_duplicate_id", "a menu item id is used twice"),
50 ("menu_empty_accelerator", "a shortcut is empty"),
51 (
52 "menu_bad_modifier",
53 "a shortcut has a modifier that is not known",
54 ),
55 ("menu_bad_key", "a shortcut has a key that is not known"),
56 (
57 "menu_reserved_accelerator",
58 "a shortcut belongs to a standard menu",
59 ),
60 ("menu_duplicate_accelerator", "a shortcut is used twice"),
61 (
62 "feed_missing_channel",
63 "the update feed must name {channel}",
64 ),
65 ("feed_not_a_url", "the update feed is not a valid URL"),
66 (
67 "feed_not_https",
68 "the update feed must be served over https",
69 ),
70 ("feed_credentials", "no credentials in the update feed"),
71 ("updater_missing_pubkey", "the updater needs a public key"),
72 ("origin_not_a_url", "the hosted app is not a valid URL"),
73 ("origin_credentials", "no credentials in the hosted app URL"),
74 ("origin_missing_host", "the hosted app URL has no host"),
75 (
76 "origin_not_https",
77 "the hosted app must be served over https",
78 ),
79 ("not_a_folder", "this is not a folder"),
80 ("watch_failed", "the folder could not be watched"),
81 ("platform_failed", "the system refused the operation"),
82 (
83 "kit_locked",
84 "the kit's state is locked by an earlier failure",
85 ),
86];
87
88#[derive(Debug)]
90pub enum CommandError {
91 Scope(ScopeError),
92 Files(FilesError),
93 Secret(SecretError),
94 Settings(SettingsError),
95 Menu(MenuError),
96 Feed(FeedError),
97 Pubkey(MissingPubkey),
98 Origin(OriginError),
99 NotAFolder,
101 Watch(notify::Error),
103 Platform(String),
105 Locked,
107}
108
109impl CommandError {
110 pub fn code(&self) -> &'static str {
112 match self {
113 CommandError::Scope(e) => e.code(),
114 CommandError::Files(e) => e.code(),
115 CommandError::Secret(e) => e.code(),
116 CommandError::Settings(e) => e.code(),
117 CommandError::Menu(e) => e.code(),
118 CommandError::Feed(e) => e.code(),
119 CommandError::Pubkey(e) => e.code(),
120 CommandError::Origin(e) => e.code(),
121 CommandError::NotAFolder => "not_a_folder",
122 CommandError::Watch(_) => "watch_failed",
123 CommandError::Platform(_) => "platform_failed",
124 CommandError::Locked => "kit_locked",
125 }
126 }
127
128 pub fn message(&self) -> &'static str {
130 let code = self.code();
131 CODES
132 .iter()
133 .find(|(known, _)| *known == code)
134 .map_or("the command failed", |(_, message)| message)
135 }
136}
137
138impl fmt::Display for CommandError {
139 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140 write!(f, "{}: {}", self.code(), self.message())
141 }
142}
143
144impl std::error::Error for CommandError {
145 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
146 match self {
147 CommandError::Scope(e) => Some(e),
148 CommandError::Files(e) => Some(e),
149 CommandError::Secret(e) => Some(e),
150 CommandError::Settings(e) => Some(e),
151 CommandError::Menu(e) => Some(e),
152 CommandError::Feed(e) => Some(e),
153 CommandError::Pubkey(e) => Some(e),
154 CommandError::Origin(e) => Some(e),
155 CommandError::Watch(e) => Some(e),
156 CommandError::NotAFolder | CommandError::Platform(_) | CommandError::Locked => None,
157 }
158 }
159}
160
161impl Serialize for CommandError {
162 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
163 let mut wire = serializer.serialize_struct("CommandError", 2)?;
164 wire.serialize_field("code", self.code())?;
165 wire.serialize_field("message", self.message())?;
166 wire.end()
167 }
168}
169
170macro_rules! from_error {
171 ($($source:ty => $variant:ident),+ $(,)?) => {
172 $(impl From<$source> for CommandError {
173 fn from(error: $source) -> Self {
174 CommandError::$variant(error)
175 }
176 })+
177 };
178}
179
180from_error! {
181 ScopeError => Scope,
182 FilesError => Files,
183 SecretError => Secret,
184 SettingsError => Settings,
185 MenuError => Menu,
186 FeedError => Feed,
187 MissingPubkey => Pubkey,
188 OriginError => Origin,
189 notify::Error => Watch,
190}
191
192pub(crate) fn lock<T>(mutex: &Mutex<T>) -> Result<MutexGuard<'_, T>, CommandError> {
194 mutex.lock().map_err(|_| CommandError::Locked)
195}
196
197#[cfg(test)]
198mod tests {
199 use super::*;
200 use serde_json::json;
201
202 type TestResult = Result<(), Box<dyn std::error::Error>>;
203
204 fn one_of_each() -> Vec<CommandError> {
205 let encode = <serde_json::Error as serde::ser::Error>::custom("x");
206 vec![
207 ScopeError::Forbidden("/".into()).into(),
208 ScopeError::NotFound("/x".into()).into(),
209 ScopeError::OutsideScope("/x".into()).into(),
210 ScopeError::Io("x".into()).into(),
211 FilesError::Io(std::io::Error::other("x")).into(),
212 FilesError::NotAFile.into(),
213 FilesError::Scope(ScopeError::Io("x".into())).into(),
214 SecretError::BadKey.into(),
215 SecretError::BadValue.into(),
216 SecretError::Poisoned.into(),
217 SecretError::Backend("x".into()).into(),
218 SettingsError::NoFolder.into(),
219 SettingsError::NotAFileName.into(),
220 SettingsError::Io(std::io::Error::other("x")).into(),
221 SettingsError::Encode(encode).into(),
222 MenuError::BadStandardLabel("copy").into(),
223 MenuError::BadMenuTitle.into(),
224 MenuError::BadItemLabel.into(),
225 MenuError::TooManyMenus.into(),
226 MenuError::BadItemCount.into(),
227 MenuError::BadId.into(),
228 MenuError::DuplicateId.into(),
229 MenuError::EmptyAccelerator.into(),
230 MenuError::BadModifier.into(),
231 MenuError::BadKey.into(),
232 MenuError::ReservedAccelerator.into(),
233 MenuError::DuplicateAccelerator.into(),
234 FeedError::MissingChannel.into(),
235 FeedError::NotAUrl.into(),
236 FeedError::NotHttps.into(),
237 FeedError::Credentials.into(),
238 MissingPubkey.into(),
239 OriginError::NotAUrl.into(),
240 OriginError::Credentials.into(),
241 OriginError::MissingHost.into(),
242 OriginError::NotHttps.into(),
243 CommandError::NotAFolder,
244 CommandError::Watch(notify::Error::generic("x")),
245 CommandError::Platform("x".into()),
246 CommandError::Locked,
247 ]
248 }
249
250 #[test]
251 fn a_command_error_is_a_code_and_a_message_on_the_wire() -> TestResult {
252 let error: CommandError = ScopeError::OutsideScope("/Users/a/secret.pdf".into()).into();
253 assert_eq!(
254 serde_json::to_value(&error)?,
255 json!({"code": "scope_outside", "message": "the path is outside the granted folders"})
256 );
257 let error: CommandError = SecretError::BadKey.into();
258 assert_eq!(
259 serde_json::to_value(&error)?,
260 json!({"code": "secret_bad_key", "message": "not a secret key"})
261 );
262 Ok(())
263 }
264
265 #[test]
266 fn every_code_is_listed_once_in_snake_case_and_has_a_message() {
267 let mut seen = std::collections::HashSet::new();
268 for (code, message) in CODES {
269 assert!(seen.insert(*code), "{code} is listed twice");
270 assert!(
271 !code.is_empty()
272 && code.starts_with(|c: char| c.is_ascii_lowercase())
273 && code
274 .chars()
275 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_'),
276 "{code} is not snake_case"
277 );
278 assert!(!message.is_empty());
279 }
280 for error in one_of_each() {
281 assert!(
282 seen.contains(error.code()),
283 "{} is not in CODES",
284 error.code()
285 );
286 }
287 }
288
289 #[test]
290 fn the_message_never_repeats_what_the_page_sent() -> TestResult {
291 for error in one_of_each() {
292 let wire = serde_json::to_string(&error)?;
293 for secret in ["/Users/a/secret.pdf", "/x", "yz_sess_token"] {
294 assert!(!wire.contains(secret), "{wire}");
295 }
296 }
297 let error: CommandError = ScopeError::Forbidden("/Users/a/.ssh".into()).into();
298 assert!(!serde_json::to_string(&error)?.contains(".ssh"));
299 Ok(())
300 }
301
302 #[test]
303 fn a_command_error_is_a_std_error_with_its_cause() {
304 fn is_error<E: std::error::Error + Send + Sync + 'static>() {}
305 is_error::<CommandError>();
306 let error: CommandError = FilesError::NotAFile.into();
307 assert!(std::error::Error::source(&error).is_some());
308 }
309
310 #[test]
311 fn a_poisoned_lock_is_an_error_not_a_panic() {
312 let mutex = Mutex::new(1);
313 let _ = std::thread::scope(|s| {
314 s.spawn(|| {
315 let _guard = mutex.lock().unwrap();
316 panic!("poison it");
317 })
318 .join()
319 });
320 assert!(matches!(lock(&mutex), Err(CommandError::Locked)));
321 }
322}