grindvakt_core/error.rs
1//! The crate's error type.
2
3use crate::config::Provider;
4use std::time::Duration;
5
6/// Everything that can go wrong in `grindvakt-core`.
7///
8/// The variants are meant to be matched by a UI: [`Error::Auth`], [`Error::RateLimited`],
9/// [`Error::Ambiguous`], [`Error::NoGlobalAddress`], [`Error::Network`] and
10/// [`Error::Provider`] each call for a different message. Messages never contain secrets
11/// (tokens, passwords, recovery words or keys) or request URLs.
12#[derive(Debug, thiserror::Error)]
13#[non_exhaustive]
14pub enum Error {
15 /// The provider rejected the token (HTTP 401/403, or an account that is not in good
16 /// standing).
17 #[error("{provider}: authentication failed: {message}")]
18 Auth {
19 /// Provider name, such as `dnsimple`.
20 provider: String,
21 /// What the provider said.
22 message: String,
23 },
24 /// The provider is throttling requests (HTTP 429).
25 #[error("{provider}: rate limited{}", .retry_after.map(|d| format!(", retry after {}s", d.as_secs())).unwrap_or_default())]
26 RateLimited {
27 /// Provider name.
28 provider: String,
29 /// How long the provider asked us to wait, when it said.
30 retry_after: Option<Duration>,
31 },
32 /// The provider or address sources could not be reached (DNS, connect, TLS, timeout).
33 #[error("network: {0}")]
34 Network(String),
35 /// A provider API call failed or returned something unexpected.
36 #[error("{provider} API: {message}")]
37 Provider {
38 /// Provider name.
39 provider: String,
40 /// What went wrong (status code or error text; never the token).
41 message: String,
42 },
43 /// Planning found records it will not guess about (for example two `A` records where
44 /// one is wanted); nothing was changed.
45 #[error("refusing to modify records: {0}")]
46 Ambiguous(String),
47 /// There is no globally routable address to publish: the sources agree on a private,
48 /// CGNAT or otherwise non-global address, or (for IPv6) there is no IPv6 connectivity.
49 /// A peer-to-peer app should fall back to relays.
50 #[error("no global address: {0}")]
51 NoGlobalAddress(String),
52 /// Address sources answered but did not agree (no strict majority).
53 #[error("address lookup: {0}")]
54 AddressLookup(String),
55 /// A record you asked for is invalid (name, TTL or TXT value).
56 #[error("invalid record: {0}")]
57 InvalidRecord(String),
58 /// A configuration value is missing or out of range.
59 #[error("invalid configuration: {0}")]
60 Config(String),
61 /// Reading, writing or locking a file failed.
62 #[error("{context}: {source}")]
63 Io {
64 /// What was being done, including the path.
65 context: String,
66 /// The underlying error.
67 #[source]
68 source: std::io::Error,
69 },
70 /// A path was refused for safety (symlink, reparse point, wrong owner or insecure ACL).
71 #[error("insecure path: {0}")]
72 InsecurePath(String),
73 /// Another process holds the single-instance lock.
74 #[error("already running: {0}")]
75 Locked(String),
76 /// The password or recovery phrase is wrong, or the vault was tampered with.
77 #[error("wrong password or recovery phrase, or the vault was tampered with")]
78 WrongSecret,
79 /// The recovery phrase is not 24 valid BIP39 English words.
80 #[error("invalid recovery phrase: {0}")]
81 InvalidRecoveryPhrase(String),
82 /// The vault file has an unsupported version or out-of-bounds KDF parameters.
83 #[error("unsupported vault: {0}")]
84 UnsupportedVault(String),
85 /// The vault file could not be parsed or decoded.
86 #[error("corrupt vault: {0}")]
87 CorruptVault(String),
88 /// The vault has no token stored for this provider.
89 #[error("no {0} token is stored in the vault")]
90 TokenMissing(Provider),
91 /// A cryptographic primitive failed (for example, no system randomness).
92 #[error("crypto failure: {0}")]
93 Crypto(String),
94}
95
96/// `Result` with [`Error`].
97pub type Result<T, E = Error> = std::result::Result<T, E>;
98
99impl Error {
100 pub(crate) fn io(context: impl Into<String>, source: std::io::Error) -> Self {
101 Error::Io {
102 context: context.into(),
103 source,
104 }
105 }
106
107 /// A [`Error::Provider`] error, for your own [`crate::provider::DnsProvider`]s.
108 pub fn provider(provider: impl Into<String>, message: impl std::fmt::Display) -> Self {
109 Error::Provider {
110 provider: provider.into(),
111 message: message.to_string(),
112 }
113 }
114
115 /// Whether retrying later could help (network trouble, throttling, provider 5xx-type
116 /// failures). Auth, ambiguity, bad input and missing addresses are not retryable.
117 pub fn is_retryable(&self) -> bool {
118 matches!(
119 self,
120 Error::Network(_)
121 | Error::RateLimited { .. }
122 | Error::Provider { .. }
123 | Error::AddressLookup(_)
124 )
125 }
126}
127
128impl From<std::io::Error> for Error {
129 fn from(source: std::io::Error) -> Self {
130 Error::Io {
131 context: "I/O".into(),
132 source,
133 }
134 }
135}
136
137#[cfg(feature = "vault")]
138impl From<weirdnet_keys::KeysError> for Error {
139 fn from(e: weirdnet_keys::KeysError) -> Self {
140 match e {
141 weirdnet_keys::KeysError::Unlock(_) => Error::WrongSecret,
142 other => Error::Crypto(other.to_string()),
143 }
144 }
145}
146
147/// Attach context to `std::io::Result`.
148#[allow(dead_code)]
149pub(crate) trait IoContext<T> {
150 fn ctx(self, f: impl FnOnce() -> String) -> Result<T>;
151}
152
153impl<T> IoContext<T> for std::io::Result<T> {
154 fn ctx(self, f: impl FnOnce() -> String) -> Result<T> {
155 self.map_err(|e| Error::io(f(), e))
156 }
157}