-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy patherror.rs
326 lines (309 loc) · 13.2 KB
/
error.rs
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
use std::error::Error;
use std::fmt::{Display, Formatter};
use actix_web::{HttpResponseBuilder, ResponseError, http::StatusCode};
use actix_web_lab::sse::Event;
use serde::Serialize;
use serde_json::json;
use tokio::sync::mpsc::error::SendError;
use tracing::debug;
use crate::types::{EdgeToken, Status, UnleashBadRequest};
pub const TRUST_PROXY_PARSE_ERROR: &str =
"needs to be a valid ip address (ipv4 or ipv6) or a valid cidr (ipv4 or ipv6)";
#[derive(Debug)]
pub enum FeatureError {
AccessDenied,
NotFound,
Retriable(reqwest::StatusCode),
}
#[derive(Debug, Serialize)]
pub struct FrontendHydrationMissing {
pub project: String,
pub environment: String,
}
impl From<&EdgeToken> for FrontendHydrationMissing {
fn from(value: &EdgeToken) -> Self {
Self {
project: value.projects.join(","),
environment: value
.environment
.clone()
.unwrap_or_else(|| "default".into()), // Should never hit or_else because we don't handle admin tokens
}
}
}
#[derive(Debug)]
pub enum CertificateError {
Pkcs12ArchiveNotFound(String),
Pkcs12IdentityGeneration(String),
Pkcs12X509Error(String),
Pkcs12ParseError(String),
Pem8ClientKeyNotFound(String),
Pem8ClientCertNotFound(String),
Pem8IdentityGeneration(String),
NoCertificateFiles,
RootCertificatesError(String),
}
impl Display for CertificateError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
CertificateError::Pkcs12ArchiveNotFound(e) => {
write!(f, "Failed to find pkcs12 archive. {e:?}")
}
CertificateError::Pkcs12IdentityGeneration(e) => {
write!(
f,
"Failed to generate pkcs12 identity from parameters. {e:?}"
)
}
CertificateError::Pem8ClientKeyNotFound(e) => {
write!(f, "Failed to get pem8 client key. {e:?}")
}
CertificateError::Pem8ClientCertNotFound(e) => {
write!(f, "Failed to get pem8 client cert. {e:?}")
}
CertificateError::Pem8IdentityGeneration(e) => {
write!(
f,
"Failed to generate pkcs8 identity from parameters. {e:?}"
)
}
CertificateError::NoCertificateFiles => {
write!(
f,
"Could find neither a pfx file nor a pkcs#8 certificate. Aborting"
)
}
CertificateError::RootCertificatesError(e) => {
write!(f, "Could not load root certificate {e:?}")
}
CertificateError::Pkcs12ParseError(e) => {
write!(f, "Failed to parse PKCS#12 archive {e:?}")
}
CertificateError::Pkcs12X509Error(e) => {
write!(
f,
"Failed to read X509 certificate from PKCS#12 archive. {e:?}"
)
}
}
}
}
#[derive(Debug)]
pub enum EdgeError {
AuthorizationDenied,
AuthorizationPending,
ClientBuildError(String),
ClientCacheError,
ClientCertificateError(CertificateError),
ClientFeaturesFetchError(FeatureError),
ClientFeaturesParseError(String),
ClientHydrationFailed(String),
ClientRegisterError,
ContextParseError,
EdgeMetricsError,
EdgeMetricsRequestError(reqwest::StatusCode, Option<UnleashBadRequest>),
EdgeTokenError,
EdgeTokenParseError,
FeatureNotFound(String),
Forbidden(String),
FrontendExpectedToBeHydrated(String),
FrontendNotYetHydrated(FrontendHydrationMissing),
HealthCheckError(String),
InvalidBackupFile(String, String),
InvalidServerUrl(String),
InvalidTokenWithStrictBehavior,
JsonParseError(String),
NoFeaturesFile,
NoTokenProvider,
NoTokens(String),
NotReady,
PersistenceError(String),
ReadyCheckError(String),
SseError(String),
TlsError(String),
TokenParseError(String),
TokenValidationError(reqwest::StatusCode),
}
impl Error for EdgeError {}
impl Display for EdgeError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
EdgeError::InvalidBackupFile(path, why_invalid) => {
write!(f, "file at path: {path} was invalid due to {why_invalid}")
}
EdgeError::TlsError(msg) => write!(f, "Could not configure TLS: {msg}"),
EdgeError::NoFeaturesFile => write!(f, "No features file located"),
EdgeError::AuthorizationDenied => write!(f, "Not allowed to access"),
EdgeError::NoTokenProvider => write!(f, "Could not get a TokenProvider"),
EdgeError::NoTokens(msg) => write!(f, "{msg}"),
EdgeError::TokenParseError(token) => write!(f, "Could not parse edge token: {token}"),
EdgeError::PersistenceError(msg) => write!(f, "{msg}"),
EdgeError::JsonParseError(msg) => write!(f, "{msg}"),
EdgeError::ClientFeaturesFetchError(fe) => match fe {
FeatureError::Retriable(status_code) => write!(
f,
"Could not fetch client features. Will retry {status_code}"
),
FeatureError::AccessDenied => write!(
f,
"Could not fetch client features because api key was not allowed"
),
FeatureError::NotFound => write!(
f,
"Could not fetch features because upstream url was not found"
),
},
EdgeError::FeatureNotFound(name) => {
write!(f, "Failed to find feature with name {name}")
}
EdgeError::ClientFeaturesParseError(error) => {
write!(f, "Failed to parse client features: [{error}]")
}
EdgeError::ClientRegisterError => {
write!(f, "Failed to register client")
}
EdgeError::ClientCertificateError(cert_error) => {
write!(f, "Failed to build cert {cert_error:?}")
}
EdgeError::ClientBuildError(e) => write!(f, "Failed to build client {e:?}"),
EdgeError::InvalidServerUrl(msg) => write!(f, "Failed to parse server url: [{msg}]"),
EdgeError::EdgeTokenError => write!(f, "Edge token error"),
EdgeError::EdgeTokenParseError => write!(f, "Failed to parse token response"),
EdgeError::EdgeMetricsRequestError(status_code, message) => {
write!(
f,
"Failed to post metrics with status code: {status_code} and response {message:?}"
)
}
EdgeError::AuthorizationPending => {
write!(f, "No validation for token has happened yet")
}
EdgeError::EdgeMetricsError => write!(f, "Edge metrics error"),
EdgeError::FrontendNotYetHydrated(hydration_info) => {
write!(f, "Edge not yet hydrated for {hydration_info:?}")
}
EdgeError::ContextParseError => {
write!(f, "Failed to parse query parameters to frontend api")
}
EdgeError::HealthCheckError(message) => {
write!(f, "{message}")
}
EdgeError::ReadyCheckError(message) => {
write!(f, "{message}")
}
EdgeError::TokenValidationError(status_code) => {
write!(
f,
"Received status code {} when trying to validate token against upstream server",
status_code
)
}
EdgeError::ClientHydrationFailed(message) => {
write!(
f,
"Client hydration failed. Somehow we said [{message}] when it did"
)
}
EdgeError::ClientCacheError => {
write!(f, "Fetching client features from cache failed")
}
EdgeError::FrontendExpectedToBeHydrated(message) => {
write!(f, "{}", message)
}
EdgeError::NotReady => {
write!(f, "Edge is not ready to serve requests")
}
EdgeError::InvalidTokenWithStrictBehavior => write!(
f,
"Edge is running with strict behavior and the token is not subsumed by any registered tokens"
),
EdgeError::SseError(message) => write!(f, "{}", message),
EdgeError::Forbidden(reason) => write!(f, "{}", reason),
}
}
}
impl ResponseError for EdgeError {
fn status_code(&self) -> actix_web::http::StatusCode {
match self {
EdgeError::InvalidBackupFile(_, _) => StatusCode::INTERNAL_SERVER_ERROR,
EdgeError::TlsError(_) => StatusCode::INTERNAL_SERVER_ERROR,
EdgeError::NoFeaturesFile => StatusCode::INTERNAL_SERVER_ERROR,
EdgeError::AuthorizationDenied => StatusCode::FORBIDDEN,
EdgeError::NoTokenProvider => StatusCode::INTERNAL_SERVER_ERROR,
EdgeError::NoTokens(_) => StatusCode::INTERNAL_SERVER_ERROR,
EdgeError::TokenParseError(_) => StatusCode::FORBIDDEN,
EdgeError::ClientBuildError(_) => StatusCode::INTERNAL_SERVER_ERROR,
EdgeError::ClientFeaturesParseError(_) => StatusCode::INTERNAL_SERVER_ERROR,
EdgeError::ClientFeaturesFetchError(_) => StatusCode::INTERNAL_SERVER_ERROR,
EdgeError::InvalidServerUrl(_) => StatusCode::INTERNAL_SERVER_ERROR,
EdgeError::PersistenceError(_) => StatusCode::INTERNAL_SERVER_ERROR,
EdgeError::JsonParseError(_) => StatusCode::INTERNAL_SERVER_ERROR,
EdgeError::EdgeTokenError => StatusCode::BAD_REQUEST,
EdgeError::EdgeTokenParseError => StatusCode::BAD_REQUEST,
EdgeError::TokenValidationError(_) => StatusCode::BAD_REQUEST,
EdgeError::AuthorizationPending => StatusCode::UNAUTHORIZED,
EdgeError::FeatureNotFound(_) => StatusCode::NOT_FOUND,
EdgeError::EdgeMetricsError => StatusCode::BAD_REQUEST,
EdgeError::ClientRegisterError => StatusCode::BAD_REQUEST,
EdgeError::ClientCertificateError(_) => StatusCode::INTERNAL_SERVER_ERROR,
EdgeError::FrontendNotYetHydrated(_) => StatusCode::NETWORK_AUTHENTICATION_REQUIRED,
EdgeError::ContextParseError => StatusCode::BAD_REQUEST,
EdgeError::EdgeMetricsRequestError(status_code, _) => {
StatusCode::from_u16(status_code.as_u16()).unwrap()
}
EdgeError::HealthCheckError(_) => StatusCode::INTERNAL_SERVER_ERROR,
EdgeError::ReadyCheckError(_) => StatusCode::INTERNAL_SERVER_ERROR,
EdgeError::ClientHydrationFailed(_) => StatusCode::INTERNAL_SERVER_ERROR,
EdgeError::ClientCacheError => StatusCode::INTERNAL_SERVER_ERROR,
EdgeError::FrontendExpectedToBeHydrated(_) => StatusCode::INTERNAL_SERVER_ERROR,
EdgeError::NotReady => StatusCode::SERVICE_UNAVAILABLE,
EdgeError::InvalidTokenWithStrictBehavior => StatusCode::FORBIDDEN,
EdgeError::SseError(_) => StatusCode::INTERNAL_SERVER_ERROR,
EdgeError::Forbidden(_) => StatusCode::FORBIDDEN,
}
}
fn error_response(&self) -> actix_web::HttpResponse<actix_web::body::BoxBody> {
match self {
EdgeError::FrontendNotYetHydrated(hydration_info) => {
HttpResponseBuilder::new(self.status_code()).json(json!({
"explanation": "Edge does not yet have data for this token. Please make a call against /api/client/features with a client token that has the same access as your token",
"access": hydration_info
}))
},
EdgeError::TokenParseError(token) => {
debug!("Failed to parse token: {}", token);
HttpResponseBuilder::new(self.status_code()).json(json!({
"explanation": format!("Edge could not parse token: {}", token),
}))
},
EdgeError::TokenValidationError(status_code) => {
debug!("Failed to validate token upstream");
HttpResponseBuilder::new(self.status_code()).json(json!({
"explanation": format!("Received a non 200 status code when trying to validate token upstream"),
"status_code": status_code.as_str()
}))
}
EdgeError::NotReady => {
HttpResponseBuilder::new(self.status_code()).json(json!({
"error": "Edge is not ready to serve requests",
"status": Status::NotReady
}))
}
_ => HttpResponseBuilder::new(self.status_code()).json(json!({
"error": self.to_string()
}))
}
}
}
impl From<serde_json::Error> for EdgeError {
fn from(value: serde_json::Error) -> Self {
EdgeError::JsonParseError(value.to_string())
}
}
impl From<SendError<Event>> for EdgeError {
fn from(value: SendError<Event>) -> Self {
EdgeError::SseError(value.to_string())
}
}
#[cfg(test)]
mod tests {}